🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Add DeDoDe (clean version) (#2835)
Dmytro Mishkinb6ca41c2482a
diff --git a/docs/source/feature.rst b/docs/source/feature.rstindex e112fa36f..f81f03cd6 100644--- a/docs/source/feature.rst+++ b/docs/source/feature.rst@@ -58,6 +58,9 @@ Local Features (Detector and Descriptors together).. autoclass:: SOLD2_detector:members: forward+.. autoclass:: DeDoDe+ :members: forward, from_pretrained, describe, detect+.. autoclass:: DISK:members: forward, from_pretrained, heatmap_and_dense_descriptorsdiff --git a/docs/source/references.bib b/docs/source/references.bibindex 55b988b0d..fd8c4acf6 100644--- a/docs/source/references.bib+++ b/docs/source/references.bib@@ -325,6 +325,13 @@ month = {mar}year={2020}}+@inproceedings{edstedt2024dedode,+ title={{DeDoDe: Detect, Don't Describe --- Describe, Don't Detect for Local Feature Matching}},+ author = {Johan Edstedt and Georg Bökman and Mårten Wadenbäck and Michael Felsberg},+ booktitle={2024 International Conference on 3D Vision (3DV)},+ year={2024}+}+@inproceedings{he2010guided,title = {Guided Image Filtering},booktitle = {Proceedings of the 11th European Conference on Computer Vision: Part I},@@ -368,12 +375,6 @@ month = {mar}year={2020}}-@inproceedings{wei2023generalized,- author = {Wei, Tong and Patel, Yash and Shekhovtsov, Alexander and Matas, Jiri and Barath, Daniel},- title = {Generalized Differentiable RANSAC},- booktitle = {ICCV},- year = {2023}-}@inproceedings{shin2017,title={JPEG-resistant Adversarial Images},@@ -390,3 +391,10 @@ month = {mar}booktitle={IEEE/CVF Winter Conference on Applications of Computer Vision (WACV)},year={2024}}++@inproceedings{wei2023generalized,+ author = {Wei, Tong and Patel, Yash and Shekhovtsov, Alexander and Matas, Jiri and Barath, Daniel},+ title = {Generalized Differentiable RANSAC},+ booktitle = {ICCV},+ year = {2023}+}diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.pyindex 1748da400..80c605a8a 100644--- a/kornia/feature/__init__.py+++ b/kornia/feature/__init__.py@@ -1,4 +1,5 @@from .affine_shape import LAFAffineShapeEstimator, LAFAffNetShapeEstimator, PatchAffineShapeEstimator+from .dedode import DeDoDefrom .defmo import DeFMOfrom .disk import DISK, DISKFeaturesfrom .hardnet import HardNet, HardNet8@@ -156,6 +157,7 @@ __all__ = ["perspective_transform_lafs","SOLD2_detector","SOLD2",+ "DeDoDe","DISK","DISKFeatures","LightGlue",diff --git a/kornia/feature/dedode/__init__.py b/kornia/feature/dedode/__init__.pynew file mode 100644index 000000000..551438f68--- /dev/null+++ b/kornia/feature/dedode/__init__.py@@ -0,0 +1,3 @@+from .dedode import DeDoDe++__all__ = ["DeDoDe"]diff --git a/kornia/feature/dedode/decoder.py b/kornia/feature/dedode/decoder.pynew file mode 100644index 000000000..081f4f7f4--- /dev/null+++ b/kornia/feature/dedode/decoder.py@@ -0,0 +1,99 @@+from typing import Any, Optional, Tuple++import torch+from torch import nn++from kornia.core import Tensor+++class Decoder(nn.Module):+ def __init__(self, layers: Any, *args, super_resolution: bool = False, num_prototypes: int = 1, **kwargs) -> None: # type: ignore[no-untyped-def]+ super().__init__(*args, **kwargs)+ self.layers = layers+ self.scales = self.layers.keys()+ self.super_resolution = super_resolution+ self.num_prototypes = num_prototypes++ def forward(+ self, features: Tensor, context: Optional[Tensor] = None, scale: Optional[int] = None+ ) -> Tuple[Tensor, Optional[Tensor]]:+ if context is not None:+ features = torch.cat((features, context), dim=1)+ stuff = self.layers[scale](features)+ logits, context = stuff[:, : self.num_prototypes], stuff[:, self.num_prototypes :]+ return logits, context+++class ConvRefiner(nn.Module):+ def __init__( # type: ignore[no-untyped-def]+ self,+ in_dim=6,+ hidden_dim=16,+ out_dim=2,+ dw=True,+ kernel_size=5,+ hidden_blocks=5,+ amp=True,+ residual=False,+ amp_dtype=torch.float16,+ ):+ super().__init__()+ self.block1 = self.create_block(+ in_dim,+ hidden_dim,+ dw=False,+ kernel_size=1,+ )+ self.hidden_blocks = nn.Sequential(+ *[+ self.create_block(+ hidden_dim,+ hidden_dim,+ dw=dw,+ kernel_size=kernel_size,+ )+ for hb in range(hidden_blocks)+ ]+ )+ self.hidden_blocks = self.hidden_blocks+ self.out_conv = nn.Conv2d(hidden_dim, out_dim, 1, 1, 0)+ self.amp = amp+ self.amp_dtype = amp_dtype+ self.residual = residual++ def create_block( # type: ignore[no-untyped-def]+ self,+ in_dim,+ out_dim,+ dw=True,+ kernel_size=5,+ bias=True,+ norm_type=nn.BatchNorm2d,+ ):+ num_groups = 1 if not dw else in_dim+ if dw:+ if out_dim % in_dim != 0:+ raise Exception("outdim must be divisible by indim for depthwise")+ conv1 = nn.Conv2d(+ in_dim,+ out_dim,+ kernel_size=kernel_size,+ stride=1,+ padding=kernel_size // 2,+ groups=num_groups,+ bias=bias,+ )+ norm = norm_type(out_dim) if norm_type is nn.BatchNorm2d else norm_type(num_channels=out_dim)+ relu = nn.ReLU(inplace=True)+ conv2 = nn.Conv2d(out_dim, out_dim, 1, 1, 0)+ return nn.Sequential(conv1, norm, relu, conv2)++ def forward(self, feats: Tensor) -> Tensor:+ b, c, hs, ws = feats.shape+ with torch.autocast("cuda", enabled=self.amp, dtype=self.amp_dtype):+ x0 = self.block1(feats)+ x = self.hidden_blocks(x0)+ if self.residual:+ x = (x + x0) / 1.4+ x = self.out_conv(x)+ return xdiff --git a/kornia/feature/dedode/dedode.py b/kornia/feature/dedode/dedode.pynew file mode 100644index 000000000..be6e76831--- /dev/null+++ b/kornia/feature/dedode/dedode.py@@ -0,0 +1,194 @@+from typing import Dict, Optional, Tuple++import torch+import torch.nn.functional as F++from kornia.core import Module, Tensor+from kornia.core.check import KORNIA_CHECK_SHAPE+from kornia.enhance.normalize import Normalize+from kornia.geometry.conversions import denormalize_pixel_coordinates+from kornia.utils.helpers import map_location_to_cpu++from .dedode_models import DeDoDeDescriptor, DeDoDeDetector, get_descriptor, get_detector+from .utils import sample_keypoints++urls: Dict[str, Dict[str, str]] = {+ "detector": {+ "L-upright": "https://github.com/Parskatt/DeDoDe/releases/download/dedode_pretrained_models/dedode_detector_L.pth",+ "L-C4": "https://github.com/georg-bn/rotation-steerers/releases/download/release-2/dedode_detector_C4.pth",+ "L-SO2": "https://github.com/georg-bn/rotation-steerers/releases/download/release-2/dedode_detector_SO2.pth",+ },+ "descriptor": {+ "B-upright": "https://github.com/Parskatt/DeDoDe/releases/download/dedode_pretrained_models/dedode_descriptor_B.pth",+ "B-C4": "https://github.com/georg-bn/rotation-steerers/releases/download/release-2/B_C4_Perm_descriptor_setting_C.pth",+ "B-SO2": "https://github.com/georg-bn/rotation-steerers/releases/download/release-2/B_SO2_Spread_descriptor_setting_C.pth",+ "G-upright": "https://github.com/Parskatt/DeDoDe/releases/download/dedode_pretrained_models/dedode_descriptor_G.pth",+ "G-C4": "https://github.com/georg-bn/rotation-steerers/releases/download/release-2/G_C4_Perm_descriptor_setting_C.pth",+ },+}+++class DeDoDe(Module):+ r"""Module which detects and/or describes local features in an image using the DeDode method.++ See :cite:`edstedt2024dedode` for details.++ .. note:: DeDode takes ImageNet normalized images as input (not in range [0, 1]).+ Example:+ >>> dedode = DeDoDe.from_pretrained(detector_weights="L-upright", descriptor_weights="B-upright")+ >>> images = torch.randn(1, 3, 256, 256)+ >>> keypoints, scores = dedode.detect(images)+ >>> descriptions = dedode.describe(images, keypoints = keypoints)+ >>> keypoints, scores, features = dedode(images) # alternatively do both+ """++ # TODO: implement steerers and mnn matchers+ def __init__(+ self, detector_model: str = "L", descriptor_model: str = "G", amp_dtype: torch.dtype = torch.float16+ ) -> None:+ super().__init__()+ self.detector: DeDoDeDetector = get_detector(detector_model, amp_dtype)+ self.descriptor: DeDoDeDescriptor = get_descriptor(descriptor_model, amp_dtype)+ self.normalizer = Normalize(torch.tensor([0.485, 0.456, 0.406]), std=torch.tensor([0.229, 0.224, 0.225]))++ def forward(+ self,+ images: Tensor,+ n: Optional[int] = 10_000,+ apply_imagenet_normalization: bool = True,+ pad_if_not_divisible: bool = True,+ ) -> Tuple[Tensor, Tensor, Tensor]:+ """Detects and describes keypoints in the input images.++ Args:+ images: A tensor of shape :math:`(B, 3, H, W)` containing the ImageNet-Normalized input images.+ n: The number of keypoints to detect.+ apply_imagenet_normalization: Whether to apply ImageNet normalization to the input images.++ Returns:+ keypoints: A tensor of shape :math:`(B, N, 2)` containing the detected keypoints in the image range,+ unlike `.detect()` function+ scores: A tensor of shape :math:`(B, N)` containing the scores of the detected keypoints.+ descriptions: A tensor of shape :math:`(B, N, DIM)` containing the descriptions of the detected keypoints.+ DIM is 256 for B and 512 for G.+ """+ if apply_imagenet_normalization:+ images = self.normalizer(images)+ B, C, H, W = images.shape+ if pad_if_not_divisible:+ h, w = images.shape[2:]+ pd_h = 14 - h % 14 if h % 14 > 0 else 0+ pd_w = 14 - w % 14 if w % 14 > 0 else 0+ images = torch.nn.functional.pad(images, (0, pd_w, 0, pd_h), value=0.0)+ keypoints, scores = self.detect(images, n=n, apply_imagenet_normalization=False, crop_h=h, crop_w=w)+ descriptions = self.describe(images, keypoints, apply_imagenet_normalization=False)+ return denormalize_pixel_coordinates(keypoints, H, W), scores, descriptions++ @torch.inference_mode()+ def detect(+ self,+ images: Tensor,+ n: Optional[int] = 10_000,+ apply_imagenet_normalization: bool = True,+ pad_if_not_divisible: bool = True,+ crop_h: Optional[int] = None,+ crop_w: Optional[int] = None,+ ) -> Tuple[Tensor, Tensor]:+ """Detects keypoints in the input images.++ Args:+ images: A tensor of shape :math:`(B, 3, H, W)` containing the input images.+ n: The number of keypoints to detect.+ apply_imagenet_normalization: Whether to apply ImageNet normalization to the input images.+ crop_h: The height of the crop to be used for detection. If None, the full image is used.+ crop_w: The width of the crop to be used for detection. If None, the full image is used.++ Returns:+ keypoints: A tensor of shape :math:`(B, N, 2)` containing the detected keypoints,+ normalized to the range :math:`[-1, 1]`.+ scores: A tensor of shape :math:`(B, N)` containing the scores of the detected keypoints.+ """+ KORNIA_CHECK_SHAPE(images, ["B", "3", "H", "W"])+ self.train(False)+ if pad_if_not_divisible:+ h, w = images.shape[2:]+ pd_h = 14 - h % 14 if h % 14 > 0 else 0+ pd_w = 14 - w % 14 if w % 14 > 0 else 0+ images = torch.nn.functional.pad(images, (0, pd_w, 0, pd_h), value=0.0)+ if apply_imagenet_normalization:+ images = self.normalizer(images)+ B, C, H, W = images.shape+ logits = self.detector.forward(images)+ if crop_h is not None and crop_w is not None:+ logits = logits[..., :crop_h, :crop_w]+ H, W = crop_h, crop_w+ scoremap = logits.reshape(B, H * W).softmax(dim=-1).reshape(B, H, W)+ keypoints, confidence = sample_keypoints(scoremap, num_samples=n)+ return keypoints, confidence++ @torch.inference_mode()+ def describe(+ self, images: Tensor, keypoints: Optional[Tensor] = None, apply_imagenet_normalization: bool = True+ ) -> Tensor:+ """Describes keypoints in the input images. If keypoints are not provided, returns the dense descriptors.++ Args:+ images: A tensor of shape :math:`(B, 3, H, W)` containing the input images.+ keypoints: An optional tensor of shape :math:`(B, N, 2)` containing the detected keypoints.+ apply_imagenet_normalization: Whether to apply ImageNet normalization to the input images.++ Returns:+ descriptions: A tensor of shape :math:`(B, N, DIM)` containing the descriptions of the detected keypoints.+ If the dense descriptors are requested, the shape is :math:`(B, DIM, H, W)`.+ """+ KORNIA_CHECK_SHAPE(images, ["B", "3", "H", "W"])+ B, C, H, W = images.shape+ if keypoints is not None:+ KORNIA_CHECK_SHAPE(keypoints, ["B", "N", "2"])+ if apply_imagenet_normalization:+ images = self.normalizer(images)+ self.train(False)+ descriptions = self.descriptor.forward(images)+ if keypoints is not None:+ described_keypoints = F.grid_sample(+ descriptions.float(), keypoints[:, None], mode="bilinear", align_corners=False+ )[:, :, 0].mT+ return described_keypoints+ return descriptions++ @classmethod+ def from_pretrained(+ cls,+ detector_weights: str = "L-upright",+ descriptor_weights: str = "G-upright",+ amp_dtype: torch.dtype = torch.float16,+ ) -> Module:+ r"""Loads a pretrained model.++ Depth model was trained using depth map supervision and is slightly more precise but biased to detect keypoints+ only where SfM depth is available. Epipolar model was trained using epipolar geometry supervision and+ is less precise but detects keypoints everywhere where they are matchable. The difference is especially+ pronounced on thin structures and on edges of objects.++ Args:+ detector_weights: The weights to load for the detector. One of 'L-upright', 'L-C4', 'L-SO2'.+ descriptor_weights: The weights to load for the descriptor.+ One of 'B-upright', 'B-C4', 'B-SO2', 'G-upright', 'G-C4'.+ checkpoint: The checkpoint to load. One of 'depth' or 'epipolar'.+ amp_dtype: the dtype to use for the model. One of torch.float16 or torch.float32.+ Default is torch.float16, suitable for CUDA. Use torch.float32 for CPU or MPS++ Returns:+ The pretrained model.+ """+ model: DeDoDe = cls(+ detector_model=detector_weights[0], descriptor_model=descriptor_weights[0], amp_dtype=amp_dtype+ )+ model.detector.load_state_dict(+ torch.hub.load_state_dict_from_url(urls["detector"][detector_weights], map_location=map_location_to_cpu)+ )+ model.descriptor.load_state_dict(+ torch.hub.load_state_dict_from_url(urls["descriptor"][descriptor_weights], map_location=map_location_to_cpu)+ )+ model.eval()+ return modeldiff --git a/kornia/feature/dedode/dedode_models.py b/kornia/feature/dedode/dedode_models.pynew file mode 100644index 000000000..dd70f5b88--- /dev/null+++ b/kornia/feature/dedode/dedode_models.py@@ -0,0 +1,185 @@+import torch+from torch import nn++from .decoder import ConvRefiner, Decoder+from .descriptor import DeDoDeDescriptor+from .detector import DeDoDeDetector+from .encoder import VGG19, VGG_DINOv2+++def dedode_detector_L(amp_dtype: torch.dtype = torch.float16) -> DeDoDeDetector:+ NUM_PROTOTYPES = 1+ residual = True+ hidden_blocks = 8+ amp = True+ conv_refiner = nn.ModuleDict(+ {+ "8": ConvRefiner(+ 512,+ 512,+ 256 + NUM_PROTOTYPES,+ hidden_blocks=hidden_blocks,+ residual=residual,+ amp=amp,+ amp_dtype=amp_dtype,+ ),+ "4": ConvRefiner(+ 256 + 256,+ 256,+ 128 + NUM_PROTOTYPES,+ hidden_blocks=hidden_blocks,+ residual=residual,+ amp=amp,+ amp_dtype=amp_dtype,+ ),+ "2": ConvRefiner(+ 128 + 128,+ 128,+ 64 + NUM_PROTOTYPES,+ hidden_blocks=hidden_blocks,+ residual=residual,+ amp=amp,+ amp_dtype=amp_dtype,+ ),+ "1": ConvRefiner(+ 64 + 64,+ 64,+ 1 + NUM_PROTOTYPES,+ hidden_blocks=hidden_blocks,+ residual=residual,+ amp=amp,+ amp_dtype=amp_dtype,+ ),+ }+ )+ encoder = VGG19(amp=amp, amp_dtype=amp_dtype)+ decoder = Decoder(conv_refiner)+ model = DeDoDeDetector(encoder=encoder, decoder=decoder)+ return model+++def dedode_descriptor_B(amp_dtype: torch.dtype = torch.float16) -> DeDoDeDescriptor:+ NUM_PROTOTYPES = 256 # == descriptor size+ residual = True+ hidden_blocks = 5+ amp = True+ conv_refiner = nn.ModuleDict(+ {+ "8": ConvRefiner(+ 512,+ 512,+ 256 + NUM_PROTOTYPES,+ hidden_blocks=hidden_blocks,+ residual=residual,+ amp=amp,+ amp_dtype=amp_dtype,+ ),+ "4": ConvRefiner(+ 256 + 256,+ 256,+ 128 + NUM_PROTOTYPES,+ hidden_blocks=hidden_blocks,+ residual=residual,+ amp=amp,+ amp_dtype=amp_dtype,+ ),+ "2": ConvRefiner(+ 128 + 128,+ 64,+ 32 + NUM_PROTOTYPES,+ hidden_blocks=hidden_blocks,+ residual=residual,+ amp=amp,+ amp_dtype=amp_dtype,+ ),+ "1": ConvRefiner(+ 64 + 32,+ 32,+ 1 + NUM_PROTOTYPES,+ hidden_blocks=hidden_blocks,+ residual=residual,+ amp=amp,+ amp_dtype=amp_dtype,+ ),+ }+ )+ encoder = VGG19(amp=amp, amp_dtype=amp_dtype)+ decoder = Decoder(conv_refiner, num_prototypes=NUM_PROTOTYPES)+ model = DeDoDeDescriptor(encoder=encoder, decoder=decoder)+ return model+++def dedode_descriptor_G(amp_dtype: torch.dtype = torch.float16) -> DeDoDeDescriptor:+ NUM_PROTOTYPES = 256 # == descriptor size+ residual = True+ hidden_blocks = 5+ amp = True+ conv_refiner = nn.ModuleDict(+ {+ "14": ConvRefiner(+ 1024,+ 768,+ 512 + NUM_PROTOTYPES,+ hidden_blocks=hidden_blocks,+ residual=residual,+ amp=amp,+ amp_dtype=amp_dtype,+ ),+ "8": ConvRefiner(+ 512 + 512,+ 512,+ 256 + NUM_PROTOTYPES,+ hidden_blocks=hidden_blocks,+ residual=residual,+ amp=amp,+ amp_dtype=amp_dtype,+ ),+ "4": ConvRefiner(+ 256 + 256,+ 256,+ 128 + NUM_PROTOTYPES,+ hidden_blocks=hidden_blocks,+ residual=residual,+ amp=amp,+ amp_dtype=amp_dtype,+ ),+ "2": ConvRefiner(+ 128 + 128,+ 64,+ 32 + NUM_PROTOTYPES,+ hidden_blocks=hidden_blocks,+ residual=residual,+ amp=amp,+ amp_dtype=amp_dtype,+ ),+ "1": ConvRefiner(+ 64 + 32,+ 32,+ 1 + NUM_PROTOTYPES,+ hidden_blocks=hidden_blocks,+ residual=residual,+ amp=amp,+ amp_dtype=amp_dtype,+ ),+ }+ )+ vgg_kwargs = {"amp": amp, "amp_dtype": amp_dtype}+ dinov2_kwargs = {"amp": amp, "amp_dtype": amp_dtype, "dinov2_weights": None}+ encoder = VGG_DINOv2(vgg_kwargs=vgg_kwargs, dinov2_kwargs=dinov2_kwargs)+ decoder = Decoder(conv_refiner, num_prototypes=NUM_PROTOTYPES)+ model = DeDoDeDescriptor(encoder=encoder, decoder=decoder)+ return model+++def get_detector(kind: str = "L", amp_dtype: torch.dtype = torch.float16) -> DeDoDeDetector:+ if kind == "L":+ return dedode_detector_L(amp_dtype)+ raise ValueError(f"Unknown detector kind: {kind}")+++def get_descriptor(kind: str = "B", amp_dtype: torch.dtype = torch.float16) -> DeDoDeDescriptor:+ if kind == "B":+ return dedode_descriptor_B(amp_dtype)+ if kind == "G":+ return dedode_descriptor_G(amp_dtype)+ raise ValueError(f"Unknown descriptor kind: {kind}")diff --git a/kornia/feature/dedode/descriptor.py b/kornia/feature/dedode/descriptor.pynew file mode 100644index 000000000..08108a469--- /dev/null+++ b/kornia/feature/dedode/descriptor.py@@ -0,0 +1,29 @@+import torch.nn.functional as F++from kornia.core import Module, Tensor+++class DeDoDeDescriptor(Module):+ def __init__(self, encoder: Module, decoder: Module, *args, **kwargs) -> None: # type: ignore[no-untyped-def]+ super().__init__(*args, **kwargs)+ self.encoder = encoder+ self.decoder = decoder++ def forward(+ self,+ images: Tensor,+ ) -> Tensor:+ features, sizes = self.encoder(images)+ context = None+ scales = self.decoder.scales+ for idx, (feature_map, scale) in enumerate(zip(reversed(features), scales)):+ if idx == 0:+ descriptions, context = self.decoder(feature_map, scale=scale, context=context)+ else:+ delta_descriptions, context = self.decoder(feature_map, scale=scale, context=context)+ descriptions = descriptions + delta_descriptions+ if idx < len(scales) - 1:+ size = sizes[-(idx + 2)]+ descriptions = F.interpolate(descriptions, size=size, mode="bilinear", align_corners=False)+ context = F.interpolate(context, size=size, mode="bilinear", align_corners=False)+ return descriptionsdiff --git a/kornia/feature/dedode/detector.py b/kornia/feature/dedode/detector.pynew file mode 100644index 000000000..59e1f7182--- /dev/null+++ b/kornia/feature/dedode/detector.py@@ -0,0 +1,32 @@+import torch.nn.functional as F+from torch import nn++from kornia.core import Module, Tensor+++class DeDoDeDetector(nn.Module):+ def __init__(self, encoder: Module, decoder: Module, *args, **kwargs) -> None: # type: ignore[no-untyped-def]+ super().__init__(*args, **kwargs)+ self.encoder = encoder+ self.decoder = decoder++ def forward(+ self,+ images: Tensor,+ ) -> Tensor:+ dtype = images.dtype+ features, sizes = self.encoder(images)+ context = None+ logits = None+ scales = ["8", "4", "2", "1"]+ for idx, (feature_map, scale) in enumerate(zip(reversed(features), scales)):+ delta_logits, context = self.decoder(feature_map, context=context, scale=scale)+ if logits is None:+ logits = delta_logits+ else:+ logits = logits + delta_logits.float() # ensure float (need bf16 doesn't have f.interpolate)+ if idx < len(scales) - 1:+ size = sizes[-(idx + 2)]+ logits = F.interpolate(logits, size=size, mode="bicubic", align_corners=False)+ context = F.interpolate(context.float(), size=size, mode="bilinear", align_corners=False)+ return logits.to(dtype) # type: ignorediff --git a/kornia/feature/dedode/encoder.py b/kornia/feature/dedode/encoder.pynew file mode 100644index 000000000..21223475f--- /dev/null+++ b/kornia/feature/dedode/encoder.py@@ -0,0 +1,76 @@+from typing import Any, Optional, Tuple++import torch+from torch import nn++from kornia.core import Module, Tensor++from .vgg import vgg19_bn+++class VGG19(Module):+ def __init__(self, amp: bool = False, amp_dtype: torch.dtype = torch.float16) -> None:+ super().__init__()+ self.layers = nn.ModuleList(vgg19_bn().features[:40]) # type: ignore+ # Maxpool layers: 6, 13, 26, 39+ self.amp = amp+ self.amp_dtype = amp_dtype++ def forward(self, x: Tensor, **kwargs): # type: ignore[no-untyped-def]+ with torch.autocast("cuda", enabled=self.amp, dtype=self.amp_dtype):+ feats = []+ sizes = []+ for layer in self.layers:+ if isinstance(layer, nn.MaxPool2d):+ feats.append(x)+ sizes.append(x.shape[-2:])+ x = layer(x)+ return feats, sizes+++class FrozenDINOv2(Module):+ def __init__(self, amp: bool = True, amp_dtype: torch.dtype = torch.float16, dinov2_weights: Optional[Any] = None):+ super().__init__()+ if dinov2_weights is None:+ dinov2_weights = torch.hub.load_state_dict_from_url(+ "https://dl.fbaipublicfiles.com/dinov2/dinov2_vitl14/dinov2_vitl14_pretrain.pth", map_location="cpu"+ )+ from .transformer import vit_large++ vit_kwargs = dict(+ img_size=518,+ patch_size=14,+ init_values=1.0,+ ffn_layer="mlp",+ block_chunks=0,+ )+ dinov2_vitl14 = vit_large(**vit_kwargs).eval()+ dinov2_vitl14.load_state_dict(dinov2_weights)+ self.amp = amp+ self.amp_dtype = amp_dtype+ if self.amp:+ dinov2_vitl14 = dinov2_vitl14.to(self.amp_dtype)+ self.dinov2_vitl14 = [dinov2_vitl14] # ugly hack to not show parameters to DDP++ def forward(self, x: Tensor): # type: ignore[no-untyped-def]+ B, C, H, W = x.shape+ if self.dinov2_vitl14[0].device != x.device:+ self.dinov2_vitl14[0] = self.dinov2_vitl14[0].to(x.device).to(self.amp_dtype)+ with torch.inference_mode():+ dinov2_features_16 = self.dinov2_vitl14[0].forward_features(x.to(self.amp_dtype))+ features_16 = dinov2_features_16["x_norm_patchtokens"].permute(0, 2, 1).reshape(B, 1024, H // 14, W // 14)+ return [features_16.clone()], [(H // 14, W // 14)] # clone from inference mode to use in autograd+++class VGG_DINOv2(Module):+ def __init__(self, vgg_kwargs=None, dinov2_kwargs=None): # type: ignore[no-untyped-def]+ if (vgg_kwargs is None) or (dinov2_kwargs is None):+ raise ValueError("Input kwargs please")+ super().__init__()+ self.vgg = VGG19(**vgg_kwargs)+ self.frozen_dinov2 = FrozenDINOv2(**dinov2_kwargs)++ def forward(self, x: Tensor) -> Tuple[Tensor, Tuple[int, int]]:+ feats_vgg, sizes_vgg = self.vgg(x)+ feat_dinov2, size_dinov2 = self.frozen_dinov2(x)+ return feats_vgg + feat_dinov2, sizes_vgg + size_dinov2diff --git a/kornia/feature/dedode/transformer/__init__.py b/kornia/feature/dedode/transformer/__init__.pynew file mode 100644index 000000000..c49e70568--- /dev/null+++ b/kornia/feature/dedode/transformer/__init__.py@@ -0,0 +1,5 @@+from .dinov2 import vit_large++__all__ = [+ "vit_large",+]diff --git a/kornia/feature/dedode/transformer/dinov2.py b/kornia/feature/dedode/transformer/dinov2.pynew file mode 100644index 000000000..f3782c1c3--- /dev/null+++ b/kornia/feature/dedode/transformer/dinov2.py@@ -0,0 +1,358 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+# All rights reserved.+#+# This source code is licensed under the license found in the+# LICENSE file in the root directory of this source tree.++# References:+# https://github.com/facebookresearch/dino/blob/main/vision_transformer.py+# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py++import math+from functools import partial+from typing import Callable, Sequence, Tuple, Union++import torch+import torch.utils.checkpoint+from torch import nn+from torch.nn.init import trunc_normal_++from kornia.core.check import KORNIA_CHECK++from .layers import MemEffAttention, Mlp, PatchEmbed, SwiGLUFFNFused+from .layers import NestedTensorBlock as Block+++def named_apply(fn: Callable, module: nn.Module, name="", depth_first=True, include_root=False) -> nn.Module:+ if not depth_first and include_root:+ fn(module=module, name=name)+ for child_name, child_module in module.named_children():+ child_name = ".".join((name, child_name)) if name else child_name+ named_apply(fn=fn, module=child_module, name=child_name, depth_first=depth_first, include_root=True)+ if depth_first and include_root:+ fn(module=module, name=name)+ return module+++class BlockChunk(nn.ModuleList):+ def forward(self, x):+ for b in self:+ x = b(x)+ return x+++class DinoVisionTransformer(nn.Module):+ def __init__(+ self,+ img_size=224,+ patch_size=16,+ in_chans=3,+ embed_dim=768,+ depth=12,+ num_heads=12,+ mlp_ratio=4.0,+ qkv_bias=True,+ ffn_bias=True,+ proj_bias=True,+ drop_path_rate=0.0,+ drop_path_uniform=False,+ init_values=None, # for layerscale: None or 0 => no layerscale+ embed_layer=PatchEmbed,+ act_layer=nn.GELU,+ block_fn=Block,+ ffn_layer="mlp",+ block_chunks=1,+ ):+ """+ Args:+ img_size (int, tuple): input image size+ patch_size (int, tuple): patch size+ in_chans (int): number of input channels+ embed_dim (int): embedding dimension+ depth (int): depth of transformer+ num_heads (int): number of attention heads+ mlp_ratio (int): ratio of mlp hidden dim to embedding dim+ qkv_bias (bool): enable bias for qkv if True+ proj_bias (bool): enable bias for proj in attn if True+ ffn_bias (bool): enable bias for ffn if True+ drop_path_rate (float): stochastic depth rate+ drop_path_uniform (bool): apply uniform drop rate across blocks+ weight_init (str): weight init scheme+ init_values (float): layer-scale init values+ embed_layer (nn.Module): patch embedding layer+ act_layer (nn.Module): MLP activation layer+ block_fn (nn.Module): transformer block class+ ffn_layer (str): "mlp", "swiglu", "swiglufused" or "identity"+ block_chunks: (int) split block sequence into block_chunks units for FSDP wrap+ """+ super().__init__()+ norm_layer = partial(nn.LayerNorm, eps=1e-6)++ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models+ self.num_tokens = 1+ self.n_blocks = depth+ self.num_heads = num_heads+ self.patch_size = patch_size++ self.patch_embed = embed_layer(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)+ num_patches = self.patch_embed.num_patches++ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim))++ if drop_path_uniform is True:+ dpr = [drop_path_rate] * depth+ else:+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule++ if ffn_layer == "mlp":+ ffn_layer = Mlp+ elif ffn_layer == "swiglufused" or ffn_layer == "swiglu":+ ffn_layer = SwiGLUFFNFused+ elif ffn_layer == "identity":++ def f(*args, **kwargs):+ return nn.Identity()++ ffn_layer = f+ else:+ raise NotImplementedError++ blocks_list = [+ block_fn(+ dim=embed_dim,+ num_heads=num_heads,+ mlp_ratio=mlp_ratio,+ qkv_bias=qkv_bias,+ proj_bias=proj_bias,+ ffn_bias=ffn_bias,+ drop_path=dpr[i],+ norm_layer=norm_layer,+ act_layer=act_layer,+ ffn_layer=ffn_layer,+ init_values=init_values,+ )+ for i in range(depth)+ ]+ if block_chunks > 0:+ self.chunked_blocks = True+ chunked_blocks = []+ chunksize = depth // block_chunks+ for i in range(0, depth, chunksize):+ # this is to keep the block index consistent if we chunk the block list+ chunked_blocks.append([nn.Identity()] * i + blocks_list[i : i + chunksize])+ self.blocks = nn.ModuleList([BlockChunk(p) for p in chunked_blocks])+ else:+ self.chunked_blocks = False+ self.blocks = nn.ModuleList(blocks_list)++ self.norm = norm_layer(embed_dim)+ self.head = nn.Identity()++ self.mask_token = nn.Parameter(torch.zeros(1, embed_dim))++ self.init_weights()+ for param in self.parameters():+ param.requires_grad = False++ @property+ def device(self):+ return self.cls_token.device++ def init_weights(self):+ trunc_normal_(self.pos_embed, std=0.02)+ nn.init.normal_(self.cls_token, std=1e-6)+ named_apply(init_weights_vit_timm, self)++ def interpolate_pos_encoding(self, x, w, h):+ previous_dtype = x.dtype+ npatch = x.shape[1] - 1+ N = self.pos_embed.shape[1] - 1+ if npatch == N and w == h:+ return self.pos_embed+ pos_embed = self.pos_embed.float()+ class_pos_embed = pos_embed[:, 0]+ patch_pos_embed = pos_embed[:, 1:]+ dim = x.shape[-1]+ w0 = w // self.patch_size+ h0 = h // self.patch_size+ # we add a small number to avoid floating point error in the interpolation+ # see discussion at https://github.com/facebookresearch/dino/issues/8+ w0, h0 = w0 + 0.1, h0 + 0.1++ patch_pos_embed = nn.functional.interpolate(+ patch_pos_embed.reshape(1, int(math.sqrt(N)), int(math.sqrt(N)), dim).permute(0, 3, 1, 2),+ scale_factor=(w0 / math.sqrt(N), h0 / math.sqrt(N)),+ mode="bicubic",+ )+ KORNIA_CHECK(int(w0) == patch_pos_embed.shape[-2])+ KORNIA_CHECK(int(h0) == patch_pos_embed.shape[-1])+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)+ return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to(previous_dtype)++ def prepare_tokens_with_masks(self, x, masks=None):+ B, nc, w, h = x.shape+ x = self.patch_embed(x)+ if masks is not None:+ x = torch.where(masks.unsqueeze(-1), self.mask_token.to(x.dtype).unsqueeze(0), x)++ x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1)+ x = x + self.interpolate_pos_encoding(x, w, h)++ return x++ def forward_features_list(self, x_list, masks_list):+ x = [self.prepare_tokens_with_masks(x, masks) for x, masks in zip(x_list, masks_list)]+ for blk in self.blocks:+ x = blk(x)++ all_x = x+ output = []+ for x, masks in zip(all_x, masks_list):+ x_norm = self.norm(x)+ output.append(+ {+ "x_norm_clstoken": x_norm[:, 0],+ "x_norm_patchtokens": x_norm[:, 1:],+ "x_prenorm": x,+ "masks": masks,+ }+ )+ return output++ def forward_features(self, x, masks=None):+ if isinstance(x, list):+ return self.forward_features_list(x, masks)++ x = self.prepare_tokens_with_masks(x, masks)++ for blk in self.blocks:+ x = blk(x)++ x_norm = self.norm(x)+ return {+ "x_norm_clstoken": x_norm[:, 0],+ "x_norm_patchtokens": x_norm[:, 1:],+ "x_prenorm": x,+ "masks": masks,+ }++ def _get_intermediate_layers_not_chunked(self, x, n=1):+ x = self.prepare_tokens_with_masks(x)+ # If n is an int, take the n last blocks. If it's a list, take them+ output, total_block_len = [], len(self.blocks)+ blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n+ for i, blk in enumerate(self.blocks):+ x = blk(x)+ if i in blocks_to_take:+ output.append(x)+ KORNIA_CHECK(len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found")+ return output++ def _get_intermediate_layers_chunked(self, x, n=1):+ x = self.prepare_tokens_with_masks(x)+ output, i, total_block_len = [], 0, len(self.blocks[-1])+ # If n is an int, take the n last blocks. If it's a list, take them+ blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n+ for block_chunk in self.blocks:+ for blk in block_chunk[i:]: # Passing the nn.Identity()+ x = blk(x)+ if i in blocks_to_take:+ output.append(x)+ i += 1+ KORNIA_CHECK(len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found")+ return output++ def get_intermediate_layers(+ self,+ x: torch.Tensor,+ n: Union[int, Sequence] = 1, # Layers or n last layers to take+ reshape: bool = False,+ return_class_token: bool = False,+ norm=True,+ ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]]]:+ if self.chunked_blocks:+ outputs = self._get_intermediate_layers_chunked(x, n)+ else:+ outputs = self._get_intermediate_layers_not_chunked(x, n)+ if norm:+ outputs = [self.norm(out) for out in outputs]+ class_tokens = [out[:, 0] for out in outputs]+ outputs = [out[:, 1:] for out in outputs]+ if reshape:+ B, _, w, h = x.shape+ outputs = [+ out.reshape(B, w // self.patch_size, h // self.patch_size, -1).permute(0, 3, 1, 2).contiguous()+ for out in outputs+ ]+ if return_class_token:+ return tuple(zip(outputs, class_tokens))+ return tuple(outputs)++ def forward(self, *args, is_training=False, **kwargs):+ ret = self.forward_features(*args, **kwargs)+ if is_training:+ return ret+ else:+ return self.head(ret["x_norm_clstoken"])+++def init_weights_vit_timm(module: nn.Module, name: str = ""):+ """ViT weight initialization, original timm impl (for reproducibility)"""+ if isinstance(module, nn.Linear):+ trunc_normal_(module.weight, std=0.02)+ if module.bias is not None:+ nn.init.zeros_(module.bias)+++def vit_small(patch_size=16, **kwargs):+ model = DinoVisionTransformer(+ patch_size=patch_size,+ embed_dim=384,+ depth=12,+ num_heads=6,+ mlp_ratio=4,+ block_fn=partial(Block, attn_class=MemEffAttention),+ **kwargs,+ )+ return model+++def vit_base(patch_size=16, **kwargs):+ model = DinoVisionTransformer(+ patch_size=patch_size,+ embed_dim=768,+ depth=12,+ num_heads=12,+ mlp_ratio=4,+ block_fn=partial(Block, attn_class=MemEffAttention),+ **kwargs,+ )+ return model+++def vit_large(patch_size=16, **kwargs):+ model = DinoVisionTransformer(+ patch_size=patch_size,+ embed_dim=1024,+ depth=24,+ num_heads=16,+ mlp_ratio=4,+ block_fn=partial(Block, attn_class=MemEffAttention),+ **kwargs,+ )+ return model+++def vit_giant2(patch_size=16, **kwargs):+ """Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64."""+ model = DinoVisionTransformer(+ patch_size=patch_size,+ embed_dim=1536,+ depth=40,+ num_heads=24,+ mlp_ratio=4,+ block_fn=partial(Block, attn_class=MemEffAttention),+ **kwargs,+ )+ return modeldiff --git a/kornia/feature/dedode/transformer/layers/__init__.py b/kornia/feature/dedode/transformer/layers/__init__.pynew file mode 100644index 000000000..daadf5eb3--- /dev/null+++ b/kornia/feature/dedode/transformer/layers/__init__.py@@ -0,0 +1,12 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+# All rights reserved.+#+# This source code is licensed under the license found in the+# LICENSE file in the root directory of this source tree.++from .attention import MemEffAttention+from .block import NestedTensorBlock+from .dino_head import DINOHead+from .mlp import Mlp+from .patch_embed import PatchEmbed+from .swiglu_ffn import SwiGLUFFN, SwiGLUFFNFuseddiff --git a/kornia/feature/dedode/transformer/layers/attention.py b/kornia/feature/dedode/transformer/layers/attention.pynew file mode 100644index 000000000..a3431e8d6--- /dev/null+++ b/kornia/feature/dedode/transformer/layers/attention.py@@ -0,0 +1,79 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+# All rights reserved.+#+# This source code is licensed under the license found in the+# LICENSE file in the root directory of this source tree.++# References:+# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py+# https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py++import logging++from torch import Tensor, nn++logger = logging.getLogger("dinov2")+++try:+ from xformers.ops import fmha, memory_efficient_attention, unbind++ XFORMERS_AVAILABLE = True+except ImportError:+ XFORMERS_AVAILABLE = False+++class Attention(nn.Module):+ def __init__(+ self,+ dim: int,+ num_heads: int = 8,+ qkv_bias: bool = False,+ proj_bias: bool = True,+ attn_drop: float = 0.0,+ proj_drop: float = 0.0,+ ) -> None:+ super().__init__()+ self.num_heads = num_heads+ head_dim = dim // num_heads+ self.scale = head_dim**-0.5++ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)+ self.attn_drop = nn.Dropout(attn_drop)+ self.proj = nn.Linear(dim, dim, bias=proj_bias)+ self.proj_drop = nn.Dropout(proj_drop)++ def forward(self, x: Tensor) -> Tensor:+ B, N, C = x.shape+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)++ q, k, v = qkv[0] * self.scale, qkv[1], qkv[2]+ attn = q @ k.transpose(-2, -1)++ attn = attn.softmax(dim=-1)+ attn = self.attn_drop(attn)++ x = (attn @ v).transpose(1, 2).reshape(B, N, C)+ x = self.proj(x)+ x = self.proj_drop(x)+ return x+++class MemEffAttention(Attention):+ def forward(self, x: Tensor, attn_bias=None) -> Tensor: # type: ignore[no-untyped-def]+ if not XFORMERS_AVAILABLE:+ if attn_bias is not None:+ raise ValueError("xFormers is required for nested tensors usage")+ return super().forward(x)++ B, N, C = x.shape+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)++ q, k, v = unbind(qkv, 2)++ x = memory_efficient_attention(q, k, v, attn_bias=attn_bias)+ x = x.reshape([B, N, C])++ x = self.proj(x)+ x = self.proj_drop(x)+ return xdiff --git a/kornia/feature/dedode/transformer/layers/block.py b/kornia/feature/dedode/transformer/layers/block.pynew file mode 100644index 000000000..a1d1770ba--- /dev/null+++ b/kornia/feature/dedode/transformer/layers/block.py@@ -0,0 +1,248 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+# All rights reserved.+#+# This source code is licensed under the license found in the+# LICENSE file in the root directory of this source tree.++# References:+# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py+# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py++import logging+from typing import Any, Callable, Dict, List, Tuple++import torch+from torch import Tensor, nn++from kornia.core.check import KORNIA_CHECK++from .attention import Attention, MemEffAttention+from .drop_path import DropPath+from .layer_scale import LayerScale+from .mlp import Mlp++logger = logging.getLogger("dinov2")+++try:+ from xformers.ops import fmha, index_select_cat, scaled_index_add++ XFORMERS_AVAILABLE = True+except ImportError:+ logger.warning("xFormers not available")+ XFORMERS_AVAILABLE = False+++class Block(nn.Module):+ def __init__(+ self,+ dim: int,+ num_heads: int,+ mlp_ratio: float = 4.0,+ qkv_bias: bool = False,+ proj_bias: bool = True,+ ffn_bias: bool = True,+ drop: float = 0.0,+ attn_drop: float = 0.0,+ init_values=None,+ drop_path: float = 0.0,+ act_layer: Callable[..., nn.Module] = nn.GELU,+ norm_layer: Callable[..., nn.Module] = nn.LayerNorm,+ attn_class: Callable[..., nn.Module] = Attention,+ ffn_layer: Callable[..., nn.Module] = Mlp,+ ) -> None:+ super().__init__()+ # print(f"biases: qkv: {qkv_bias}, proj: {proj_bias}, ffn: {ffn_bias}")+ self.norm1 = norm_layer(dim)+ self.attn = attn_class(+ dim,+ num_heads=num_heads,+ qkv_bias=qkv_bias,+ proj_bias=proj_bias,+ attn_drop=attn_drop,+ proj_drop=drop,+ )+ self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()+ self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()++ self.norm2 = norm_layer(dim)+ mlp_hidden_dim = int(dim * mlp_ratio)+ self.mlp = ffn_layer(+ in_features=dim,+ hidden_features=mlp_hidden_dim,+ act_layer=act_layer,+ drop=drop,+ bias=ffn_bias,+ )+ self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()+ self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()++ self.sample_drop_ratio = drop_path++ def forward(self, x: Tensor) -> Tensor:+ def attn_residual_func(x: Tensor) -> Tensor:+ return self.ls1(self.attn(self.norm1(x)))++ def ffn_residual_func(x: Tensor) -> Tensor:+ return self.ls2(self.mlp(self.norm2(x)))++ if self.training and self.sample_drop_ratio > 0.1:+ # the overhead is compensated only for a drop path rate larger than 0.1+ x = drop_add_residual_stochastic_depth(+ x,+ residual_func=attn_residual_func,+ sample_drop_ratio=self.sample_drop_ratio,+ )+ x = drop_add_residual_stochastic_depth(+ x,+ residual_func=ffn_residual_func,+ sample_drop_ratio=self.sample_drop_ratio,+ )+ elif self.training and self.sample_drop_ratio > 0.0:+ x = x + self.drop_path1(attn_residual_func(x))+ x = x + self.drop_path1(ffn_residual_func(x)) # FIXME: drop_path2+ else:+ x = x + attn_residual_func(x)+ x = x + ffn_residual_func(x)+ return x+++def drop_add_residual_stochastic_depth(+ x: Tensor,+ residual_func: Callable[[Tensor], Tensor],+ sample_drop_ratio: float = 0.0,+) -> Tensor:+ # 1) extract subset using permutation+ b, n, d = x.shape+ sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1)+ brange = (torch.randperm(b, device=x.device))[:sample_subset_size]+ x_subset = x[brange]++ # 2) apply residual_func to get residual+ residual = residual_func(x_subset)++ x_flat = x.flatten(1)+ residual = residual.flatten(1)++ residual_scale_factor = b / sample_subset_size++ # 3) add the residual+ x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor)+ return x_plus_residual.view_as(x)+++def get_branges_scales(x, sample_drop_ratio=0.0):+ b, n, d = x.shape+ sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1)+ brange = (torch.randperm(b, device=x.device))[:sample_subset_size]+ residual_scale_factor = b / sample_subset_size+ return brange, residual_scale_factor+++def add_residual(x, brange, residual, residual_scale_factor, scaling_vector=None):+ if scaling_vector is None:+ x_flat = x.flatten(1)+ residual = residual.flatten(1)+ x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor)+ else:+ x_plus_residual = scaled_index_add(+ x, brange, residual.to(dtype=x.dtype), scaling=scaling_vector, alpha=residual_scale_factor+ )+ return x_plus_residual+++attn_bias_cache: Dict[Tuple, Any] = {}+++def get_attn_bias_and_cat(x_list, branges=None):+ """This will perform the index select, cat the tensors, and provide the attn_bias from cache."""+ batch_sizes = [b.shape[0] for b in branges] if branges is not None else [x.shape[0] for x in x_list]+ all_shapes = tuple((b, x.shape[1]) for b, x in zip(batch_sizes, x_list))+ if all_shapes not in attn_bias_cache.keys():+ seqlens = []+ for b, x in zip(batch_sizes, x_list):+ for _ in range(b):+ seqlens.append(x.shape[1])+ attn_bias = fmha.BlockDiagonalMask.from_seqlens(seqlens)+ attn_bias._batch_sizes = batch_sizes+ attn_bias_cache[all_shapes] = attn_bias++ if branges is not None:+ cat_tensors = index_select_cat([x.flatten(1) for x in x_list], branges).view(1, -1, x_list[0].shape[-1])+ else:+ tensors_bs1 = tuple(x.reshape([1, -1, *x.shape[2:]]) for x in x_list)+ cat_tensors = torch.cat(tensors_bs1, dim=1)++ return attn_bias_cache[all_shapes], cat_tensors+++def drop_add_residual_stochastic_depth_list(+ x_list: List[Tensor],+ residual_func: Callable[[Tensor, Any], Tensor],+ sample_drop_ratio: float = 0.0,+ scaling_vector=None,+) -> Tensor:+ # 1) generate random set of indices for dropping samples in the batch+ branges_scales = [get_branges_scales(x, sample_drop_ratio=sample_drop_ratio) for x in x_list]+ branges = [s[0] for s in branges_scales]+ residual_scale_factors = [s[1] for s in branges_scales]++ # 2) get attention bias and index+concat the tensors+ attn_bias, x_cat = get_attn_bias_and_cat(x_list, branges)++ # 3) apply residual_func to get residual, and split the result+ residual_list = attn_bias.split(residual_func(x_cat, attn_bias=attn_bias)) # type: ignore++ outputs = []+ for x, brange, residual, residual_scale_factor in zip(x_list, branges, residual_list, residual_scale_factors):+ outputs.append(add_residual(x, brange, residual, residual_scale_factor, scaling_vector).view_as(x))+ return outputs+++class NestedTensorBlock(Block):+ def forward_nested(self, x_list: List[Tensor]) -> List[Tensor]:+ """x_list contains a list of tensors to nest together and run."""+ KORNIA_CHECK(isinstance(self.attn, MemEffAttention))++ if self.training and self.sample_drop_ratio > 0.0:++ def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor:+ return self.attn(self.norm1(x), attn_bias=attn_bias)++ def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor:+ return self.mlp(self.norm2(x))++ x_list = drop_add_residual_stochastic_depth_list(+ x_list,+ residual_func=attn_residual_func,+ sample_drop_ratio=self.sample_drop_ratio,+ scaling_vector=self.ls1.gamma if isinstance(self.ls1, LayerScale) else None,+ )+ x_list = drop_add_residual_stochastic_depth_list(+ x_list,+ residual_func=ffn_residual_func,+ sample_drop_ratio=self.sample_drop_ratio,+ scaling_vector=self.ls2.gamma if isinstance(self.ls1, LayerScale) else None,+ )+ return x_list+ else:++ def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor:+ return self.ls1(self.attn(self.norm1(x), attn_bias=attn_bias))++ def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor:+ return self.ls2(self.mlp(self.norm2(x)))++ attn_bias, x = get_attn_bias_and_cat(x_list)+ x = x + attn_residual_func(x, attn_bias=attn_bias)+ x = x + ffn_residual_func(x)+ return attn_bias.split(x)++ def forward(self, x_or_x_list):+ if isinstance(x_or_x_list, Tensor):+ return super().forward(x_or_x_list)+ elif isinstance(x_or_x_list, list):+ KORNIA_CHECK(XFORMERS_AVAILABLE, "Please install xFormers for nested tensors usage")+ return self.forward_nested(x_or_x_list)+ else:+ raise AssertionErrordiff --git a/kornia/feature/dedode/transformer/layers/dino_head.py b/kornia/feature/dedode/transformer/layers/dino_head.pynew file mode 100644index 000000000..26e8d6b84--- /dev/null+++ b/kornia/feature/dedode/transformer/layers/dino_head.py@@ -0,0 +1,59 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+# All rights reserved.+#+# This source code is licensed under the license found in the+# LICENSE file in the root directory of this source tree.++import torch+from torch import nn+from torch.nn.init import trunc_normal_+from torch.nn.utils import weight_norm+++class DINOHead(nn.Module):+ def __init__(+ self,+ in_dim,+ out_dim,+ use_bn=False,+ nlayers=3,+ hidden_dim=2048,+ bottleneck_dim=256,+ mlp_bias=True,+ ):+ super().__init__()+ nlayers = max(nlayers, 1)+ self.mlp = _build_mlp(nlayers, in_dim, bottleneck_dim, hidden_dim=hidden_dim, use_bn=use_bn, bias=mlp_bias)+ self.apply(self._init_weights)+ self.last_layer = weight_norm(nn.Linear(bottleneck_dim, out_dim, bias=False))+ self.last_layer.weight_g.data.fill_(1)++ def _init_weights(self, m):+ if isinstance(m, nn.Linear):+ trunc_normal_(m.weight, std=0.02)+ if isinstance(m, nn.Linear) and m.bias is not None:+ nn.init.constant_(m.bias, 0)++ def forward(self, x):+ x = self.mlp(x)+ eps = 1e-6 if x.dtype == torch.float16 else 1e-12+ x = nn.functional.normalize(x, dim=-1, p=2, eps=eps)+ x = self.last_layer(x)+ return x+++def _build_mlp(nlayers, in_dim, bottleneck_dim, hidden_dim=None, use_bn=False, bias=True):+ if nlayers == 1:+ return nn.Linear(in_dim, bottleneck_dim, bias=bias)+ else:+ layers = [nn.Linear(in_dim, hidden_dim, bias=bias)]+ if use_bn:+ layers.append(nn.BatchNorm1d(hidden_dim))+ layers.append(nn.GELU())+ for _ in range(nlayers - 2):+ layers.append(nn.Linear(hidden_dim, hidden_dim, bias=bias))+ if use_bn:+ layers.append(nn.BatchNorm1d(hidden_dim))+ layers.append(nn.GELU())+ layers.append(nn.Linear(hidden_dim, bottleneck_dim, bias=bias))+ return nn.Sequential(*layers)diff --git a/kornia/feature/dedode/transformer/layers/drop_path.py b/kornia/feature/dedode/transformer/layers/drop_path.pynew file mode 100644index 000000000..795124576--- /dev/null+++ b/kornia/feature/dedode/transformer/layers/drop_path.py@@ -0,0 +1,37 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+# All rights reserved.+#+# This source code is licensed under the license found in the+# LICENSE file in the root directory of this source tree.++# References:+# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py+# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/drop.py+from typing import Optional++from kornia.core import Module, Tensor+++def drop_path(x: Tensor, drop_prob: Optional[float] = 0.0, training: bool = False) -> Tensor:+ if drop_prob is None:+ drop_path = 0.0+ if drop_prob == 0.0 or not training:+ return x+ keep_prob = 1.0 - drop_prob # type: ignore+ shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets+ random_tensor = x.new_empty(shape).bernoulli_(keep_prob)+ if keep_prob > 0.0:+ random_tensor.div_(keep_prob)+ output = x * random_tensor+ return output+++class DropPath(Module):+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""++ def __init__(self, drop_prob: Optional[float] = None) -> None:+ super().__init__()+ self.drop_prob = drop_prob++ def forward(self, x: Tensor) -> Tensor:+ return drop_path(x, self.drop_prob, self.training)diff --git a/kornia/feature/dedode/transformer/layers/layer_scale.py b/kornia/feature/dedode/transformer/layers/layer_scale.pynew file mode 100644index 000000000..7035d1e9c--- /dev/null+++ b/kornia/feature/dedode/transformer/layers/layer_scale.py@@ -0,0 +1,27 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+# All rights reserved.+#+# This source code is licensed under the license found in the+# LICENSE file in the root directory of this source tree.++# Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L110++from typing import Union++import torch+from torch import Tensor, nn+++class LayerScale(nn.Module):+ def __init__(+ self,+ dim: int,+ init_values: Union[float, Tensor] = 1e-5,+ inplace: bool = False,+ ) -> None:+ super().__init__()+ self.inplace = inplace+ self.gamma = nn.Parameter(init_values * torch.ones(dim))++ def forward(self, x: Tensor) -> Tensor:+ return x.mul_(self.gamma) if self.inplace else x * self.gammadiff --git a/kornia/feature/dedode/transformer/layers/mlp.py b/kornia/feature/dedode/transformer/layers/mlp.pynew file mode 100644index 000000000..5e4b315f9--- /dev/null+++ b/kornia/feature/dedode/transformer/layers/mlp.py@@ -0,0 +1,41 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+# All rights reserved.+#+# This source code is licensed under the license found in the+# LICENSE file in the root directory of this source tree.++# References:+# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py+# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/mlp.py+++from typing import Callable, Optional++from torch import Tensor, nn+++class Mlp(nn.Module):+ def __init__(+ self,+ in_features: int,+ hidden_features: Optional[int] = None,+ out_features: Optional[int] = None,+ act_layer: Callable[..., nn.Module] = nn.GELU,+ drop: float = 0.0,+ bias: bool = True,+ ) -> None:+ super().__init__()+ out_features = out_features or in_features+ hidden_features = hidden_features or in_features+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias)+ self.act = act_layer()+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias)+ self.drop = nn.Dropout(drop)++ def forward(self, x: Tensor) -> Tensor:+ x = self.fc1(x)+ x = self.act(x)+ x = self.drop(x)+ x = self.fc2(x)+ x = self.drop(x)+ return xdiff --git a/kornia/feature/dedode/transformer/layers/patch_embed.py b/kornia/feature/dedode/transformer/layers/patch_embed.pynew file mode 100644index 000000000..1a1402a7a--- /dev/null+++ b/kornia/feature/dedode/transformer/layers/patch_embed.py@@ -0,0 +1,88 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+# All rights reserved.+#+# This source code is licensed under the license found in the+# LICENSE file in the root directory of this source tree.++# References:+# https://github.com/facebookresearch/dino/blob/master/vision_transformer.py+# https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py++from typing import Callable, Optional, Tuple, Union++from torch import Tensor, nn++from kornia.core.check import KORNIA_CHECK+++def make_2tuple(x):+ if isinstance(x, tuple):+ KORNIA_CHECK(len(x) == 2)+ return x+ KORNIA_CHECK(isinstance(x, int))+ return (x, x)+++class PatchEmbed(nn.Module):+ """+ 2D image to patch embedding: (B,C,H,W) -> (B,N,D)++ Args:+ img_size: Image size.+ patch_size: Patch token size.+ in_chans: Number of input image channels.+ embed_dim: Number of linear projection output channels.+ norm_layer: Normalization layer.+ """++ def __init__(+ self,+ img_size: Union[int, Tuple[int, int]] = 224,+ patch_size: Union[int, Tuple[int, int]] = 16,+ in_chans: int = 3,+ embed_dim: int = 768,+ norm_layer: Optional[Callable] = None,+ flatten_embedding: bool = True,+ ) -> None:+ super().__init__()++ image_HW = make_2tuple(img_size)+ patch_HW = make_2tuple(patch_size)+ patch_grid_size = (+ image_HW[0] // patch_HW[0],+ image_HW[1] // patch_HW[1],+ )++ self.img_size = image_HW+ self.patch_size = patch_HW+ self.patches_resolution = patch_grid_size+ self.num_patches = patch_grid_size[0] * patch_grid_size[1]++ self.in_chans = in_chans+ self.embed_dim = embed_dim++ self.flatten_embedding = flatten_embedding++ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW)+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()++ def forward(self, x: Tensor) -> Tensor:+ _, _, H, W = x.shape+ patch_H, patch_W = self.patch_size+ KORNIA_CHECK(H % patch_H == 0, f"Input image height {H} is not a multiple of patch height {patch_H}")+ KORNIA_CHECK(W % patch_W == 0, f"Input image width {W} is not a multiple of patch width: {patch_W}")++ x = self.proj(x) # B C H W+ H, W = x.size(2), x.size(3)+ x = x.flatten(2).transpose(1, 2) # B HW C+ x = self.norm(x)+ if not self.flatten_embedding:+ x = x.reshape(-1, H, W, self.embed_dim) # B H W C+ return x++ def flops(self) -> float:+ Ho, Wo = self.patches_resolution+ flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1])+ if self.norm is not None:+ flops += Ho * Wo * self.embed_dim+ return flopsdiff --git a/kornia/feature/dedode/transformer/layers/swiglu_ffn.py b/kornia/feature/dedode/transformer/layers/swiglu_ffn.pynew file mode 100644index 000000000..604405f1f--- /dev/null+++ b/kornia/feature/dedode/transformer/layers/swiglu_ffn.py@@ -0,0 +1,63 @@+# Copyright (c) Meta Platforms, Inc. and affiliates.+# All rights reserved.+#+# This source code is licensed under the license found in the+# LICENSE file in the root directory of this source tree.++from typing import Callable, Optional++import torch.nn.functional as F+from torch import Tensor, nn+++class SwiGLUFFN(nn.Module):+ def __init__(+ self,+ in_features: int,+ hidden_features: Optional[int] = None,+ out_features: Optional[int] = None,+ act_layer: Optional[Callable[..., nn.Module]] = None,+ drop: float = 0.0,+ bias: bool = True,+ ) -> None:+ super().__init__()+ out_features = out_features or in_features+ hidden_features = hidden_features or in_features+ self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias)+ self.w3 = nn.Linear(hidden_features, out_features, bias=bias)++ def forward(self, x: Tensor) -> Tensor:+ x12 = self.w12(x)+ x1, x2 = x12.chunk(2, dim=-1)+ hidden = F.silu(x1) * x2+ return self.w3(hidden)+++try:+ from xformers.ops import SwiGLU++ XFORMERS_AVAILABLE = True+except ImportError:+ SwiGLU = SwiGLUFFN+ XFORMERS_AVAILABLE = False+++class SwiGLUFFNFused(SwiGLU):+ def __init__(+ self,+ in_features: int,+ hidden_features: Optional[int] = None,+ out_features: Optional[int] = None,+ act_layer: Optional[Callable[..., nn.Module]] = None,+ drop: float = 0.0,+ bias: bool = True,+ ) -> None:+ out_features = out_features or in_features+ hidden_features = hidden_features or in_features+ hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8+ super().__init__(+ in_features=in_features,+ hidden_features=hidden_features,+ out_features=out_features,+ bias=bias,+ )diff --git a/kornia/feature/dedode/utils.py b/kornia/feature/dedode/utils.pynew file mode 100644index 000000000..1c4da398a--- /dev/null+++ b/kornia/feature/dedode/utils.py@@ -0,0 +1,36 @@+from typing import Optional, Tuple, Union++import torch+import torch.nn.functional as F++from kornia.core import Tensor++[email protected]_grad()+def sample_keypoints(+ scoremap: Tensor, num_samples: Optional[int] = 10_000, return_scoremap: bool = True, increase_coverage: bool = True+) -> Union[Tensor, Tuple[Tensor, Tensor]]:+ device = scoremap.device+ dtype = scoremap.dtype+ B, H, W = scoremap.shape+ if increase_coverage:+ weights = (-(torch.linspace(-2, 2, steps=51, device=device, dtype=dtype) ** 2)).exp()[None, None]+ # 10000 is just some number for maybe numerical stability, who knows. :), result is invariant anyway+ local_density_x = F.conv2d((scoremap[:, None] + 1e-6) * 10000, weights[..., None, :], padding=(0, 51 // 2))+ local_density = F.conv2d(local_density_x, weights[..., None], padding=(51 // 2, 0))[:, 0]+ scoremap = scoremap * (local_density + 1e-8) ** (-1 / 2)+ grid = get_grid(B, H, W, device=device).reshape(B, H * W, 2)+ inds = torch.topk(scoremap.reshape(B, H * W), k=num_samples).indices # type: ignore+ kps = torch.gather(grid, dim=1, index=inds[..., None].expand(B, num_samples, 2)) # type: ignore+ if return_scoremap:+ return kps, torch.gather(scoremap.reshape(B, H * W), dim=1, index=inds)+ return kps+++def get_grid(B: int, H: int, W: int, device: torch.device) -> torch.Tensor:+ x1_n_ = torch.meshgrid(+ *[torch.linspace(-1 + 1 / n, 1 - 1 / n, n, device=device) for n in (B, H, W)],+ indexing="ij",+ )+ x1_n = torch.stack((x1_n_[2], x1_n_[1]), dim=-1).reshape(B, H * W, 2)+ return x1_ndiff --git a/kornia/feature/dedode/vgg.py b/kornia/feature/dedode/vgg.pynew file mode 100644index 000000000..25c49a315--- /dev/null+++ b/kornia/feature/dedode/vgg.py@@ -0,0 +1,257 @@+from typing import Any, Dict, List, Optional, Union, cast++import torch+from torch import nn++from kornia.core import Module+++class VGG(nn.Module):+ def __init__(+ self, features: Module, num_classes: int = 1000, init_weights: bool = True, dropout: float = 0.5+ ) -> None:+ super().__init__()+ self.features = features+ self.avgpool = nn.AdaptiveAvgPool2d((7, 7))+ self.classifier = nn.Sequential(+ nn.Linear(512 * 7 * 7, 4096),+ nn.ReLU(True),+ nn.Dropout(p=dropout),+ nn.Linear(4096, 4096),+ nn.ReLU(True),+ nn.Dropout(p=dropout),+ nn.Linear(4096, num_classes),+ )+ if init_weights:+ for m in self.modules():+ if isinstance(m, nn.Conv2d):+ nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")+ if m.bias is not None:+ nn.init.constant_(m.bias, 0)+ elif isinstance(m, nn.BatchNorm2d):+ nn.init.constant_(m.weight, 1)+ nn.init.constant_(m.bias, 0)+ elif isinstance(m, nn.Linear):+ nn.init.normal_(m.weight, 0, 0.01)+ nn.init.constant_(m.bias, 0)++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ x = self.features(x)+ x = self.avgpool(x)+ x = torch.flatten(x, 1)+ x = self.classifier(x)+ return x+++def make_layers(cfg: List[Union[str, int]], batch_norm: bool = False) -> nn.Sequential:+ layers: List[nn.Module] = []+ in_channels = 3+ for v in cfg:+ if v == "M":+ layers += [nn.MaxPool2d(kernel_size=2, stride=2)]+ else:+ v = cast(int, v)+ conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)+ if batch_norm:+ layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)]+ else:+ layers += [conv2d, nn.ReLU(inplace=True)]+ in_channels = v+ return nn.Sequential(*layers)+++cfgs: Dict[str, List[Union[str, int]]] = {+ "A": [64, "M", 128, "M", 256, 256, "M", 512, 512, "M", 512, 512, "M"],+ "B": [64, 64, "M", 128, 128, "M", 256, 256, "M", 512, 512, "M", 512, 512, "M"],+ "D": [64, 64, "M", 128, 128, "M", 256, 256, 256, "M", 512, 512, 512, "M", 512, 512, 512, "M"],+ "E": [64, 64, "M", 128, 128, "M", 256, 256, 256, 256, "M", 512, 512, 512, 512, "M", 512, 512, 512, 512, "M"],+}+++def _vgg(cfg: str, batch_norm: bool, weights: Optional[Any] = None, **kwargs: Any) -> VGG:+ model = VGG(make_layers(cfgs[cfg], batch_norm=batch_norm), **kwargs)+ return model+++def vgg11(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:+ """VGG-11 from `Very Deep Convolutional Networks for Large-Scale Image Recognition <https://arxiv.org/abs/1409.1556>`__.++ Args:+ weights (:class:`~torchvision.models.VGG11_Weights`, optional): The+ pretrained weights to use. See+ :class:`~torchvision.models.VGG11_Weights` below for+ more details, and possible values. By default, no pre-trained+ weights are used.+ progress (bool, optional): If True, displays a progress bar of the+ download to stderr. Default is True.+ **kwargs: parameters passed to the ``torchvision.models.vgg.VGG``+ base class. Please refer to the `source code+ <https://github.com/pytorch/vision/blob/main/torchvision/models/vgg.py>`_+ for more details about this class.++ .. autoclass:: torchvision.models.VGG11_Weights+ :members:+ """++ return _vgg("A", False, weights, **kwargs)+++def vgg11_bn(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:+ """VGG-11-BN from `Very Deep Convolutional Networks for Large-Scale Image Recognition <https://arxiv.org/abs/1409.1556>`__.++ Args:+ weights (:class:`~torchvision.models.VGG11_BN_Weights`, optional): The+ pretrained weights to use. See+ :class:`~torchvision.models.VGG11_BN_Weights` below for+ more details, and possible values. By default, no pre-trained+ weights are used.+ progress (bool, optional): If True, displays a progress bar of the+ download to stderr. Default is True.+ **kwargs: parameters passed to the ``torchvision.models.vgg.VGG``+ base class. Please refer to the `source code+ <https://github.com/pytorch/vision/blob/main/torchvision/models/vgg.py>`_+ for more details about this class.++ .. autoclass:: torchvision.models.VGG11_BN_Weights+ :members:+ """++ return _vgg("A", True, weights, **kwargs)+++def vgg13(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:+ """VGG-13 from `Very Deep Convolutional Networks for Large-Scale Image Recognition <https://arxiv.org/abs/1409.1556>`__.++ Args:+ weights (:class:`~torchvision.models.VGG13_Weights`, optional): The+ pretrained weights to use. See+ :class:`~torchvision.models.VGG13_Weights` below for+ more details, and possible values. By default, no pre-trained+ weights are used.+ progress (bool, optional): If True, displays a progress bar of the+ download to stderr. Default is True.+ **kwargs: parameters passed to the ``torchvision.models.vgg.VGG``+ base class. Please refer to the `source code+ <https://github.com/pytorch/vision/blob/main/torchvision/models/vgg.py>`_+ for more details about this class.++ .. autoclass:: torchvision.models.VGG13_Weights+ :members:+ """++ return _vgg("B", False, weights, **kwargs)+++def vgg13_bn(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:+ """VGG-13-BN from `Very Deep Convolutional Networks for Large-Scale Image Recognition <https://arxiv.org/abs/1409.1556>`__.++ Args:+ weights (:class:`~torchvision.models.VGG13_BN_Weights`, optional): The+ pretrained weights to use. See+ :class:`~torchvision.models.VGG13_BN_Weights` below for+ more details, and possible values. By default, no pre-trained+ weights are used.+ progress (bool, optional): If True, displays a progress bar of the+ download to stderr. Default is True.+ **kwargs: parameters passed to the ``torchvision.models.vgg.VGG``+ base class. Please refer to the `source code+ <https://github.com/pytorch/vision/blob/main/torchvision/models/vgg.py>`_+ for more details about this class.++ .. autoclass:: torchvision.models.VGG13_BN_Weights+ :members:+ """++ return _vgg("B", True, weights, **kwargs)+++def vgg16(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:+ """VGG-16 from `Very Deep Convolutional Networks for Large-Scale Image Recognition <https://arxiv.org/abs/1409.1556>`__.++ Args:+ weights (:class:`~torchvision.models.VGG16_Weights`, optional): The+ pretrained weights to use. See+ :class:`~torchvision.models.VGG16_Weights` below for+ more details, and possible values. By default, no pre-trained+ weights are used.+ progress (bool, optional): If True, displays a progress bar of the+ download to stderr. Default is True.+ **kwargs: parameters passed to the ``torchvision.models.vgg.VGG``+ base class. Please refer to the `source code+ <https://github.com/pytorch/vision/blob/main/torchvision/models/vgg.py>`_+ for more details about this class.++ .. autoclass:: torchvision.models.VGG16_Weights+ :members:+ """++ return _vgg("D", False, weights, **kwargs)+++def vgg16_bn(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:+ """VGG-16-BN from `Very Deep Convolutional Networks for Large-Scale Image Recognition <https://arxiv.org/abs/1409.1556>`__.++ Args:+ weights (:class:`~torchvision.models.VGG16_BN_Weights`, optional): The+ pretrained weights to use. See+ :class:`~torchvision.models.VGG16_BN_Weights` below for+ more details, and possible values. By default, no pre-trained+ weights are used.+ progress (bool, optional): If True, displays a progress bar of the+ download to stderr. Default is True.+ **kwargs: parameters passed to the ``torchvision.models.vgg.VGG``+ base class. Please refer to the `source code+ <https://github.com/pytorch/vision/blob/main/torchvision/models/vgg.py>`_+ for more details about this class.++ .. autoclass:: torchvision.models.VGG16_BN_Weights+ :members:+ """++ return _vgg("D", True, weights, **kwargs)+++def vgg19(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:+ """VGG-19 from `Very Deep Convolutional Networks for Large-Scale Image Recognition <https://arxiv.org/abs/1409.1556>`__.++ Args:+ weights (:class:`~torchvision.models.VGG19_Weights`, optional): The+ pretrained weights to use. See+ :class:`~torchvision.models.VGG19_Weights` below for+ more details, and possible values. By default, no pre-trained+ weights are used.+ progress (bool, optional): If True, displays a progress bar of the+ download to stderr. Default is True.+ **kwargs: parameters passed to the ``torchvision.models.vgg.VGG``+ base class. Please refer to the `source code+ <https://github.com/pytorch/vision/blob/main/torchvision/models/vgg.py>`_+ for more details about this class.++ .. autoclass:: torchvision.models.VGG19_Weights+ :members:+ """++ return _vgg("E", False, weights, **kwargs)+++def vgg19_bn(*, weights: Optional[Any] = None, **kwargs: Any) -> VGG:+ """VGG-19_BN from `Very Deep Convolutional Networks for Large-Scale Image Recognition <https://arxiv.org/abs/1409.1556>`__.++ Args:+ weights (:class:`~torchvision.models.VGG19_BN_Weights`, optional): The+ pretrained weights to use. See+ :class:`~torchvision.models.VGG19_BN_Weights` below for+ more details, and possible values. By default, no pre-trained+ weights are used.+ progress (bool, optional): If True, displays a progress bar of the+ download to stderr. Default is True.+ **kwargs: parameters passed to the ``torchvision.models.vgg.VGG``+ base class. Please refer to the `source code+ <https://github.com/pytorch/vision/blob/main/torchvision/models/vgg.py>`_+ for more details about this class.++ .. autoclass:: torchvision.models.VGG19_BN_Weights+ :members:+ """++ return _vgg("E", True, weights, **kwargs)diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.pyindex 3a8480339..4e7e1d3f0 100644--- a/kornia/feature/integrated.py+++ b/kornia/feature/integrated.py@@ -410,14 +410,15 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):"""known_modes: ClassVar[List[str]] = [- "superpoint",- "disk",- "dedodeb","aliked",- "keynet_affnet_hardnet",+ "dedodeb",+ "dedodeg",+ "disk","dog_affnet_hardnet","doghardnet",+ "keynet_affnet_hardnet","sift",+ "superpoint",]def __init__(self, feature_name: str = "disk", params: Dict = {}) -> None: # type: ignorediff --git a/kornia/feature/lightglue.py b/kornia/feature/lightglue.pyindex 893e7143b..67ef03331 100644--- a/kornia/feature/lightglue.py+++ b/kornia/feature/lightglue.py@@ -353,6 +353,10 @@ class LightGlue(Module):"weights": "dedodeb_lightglue","input_dim": 256,},+ "dedodeg": {+ "weights": "dedodeg_lightglue",+ "input_dim": 256,+ },"disk": {"weights": "disk_lightglue","input_dim": 128,@@ -431,6 +435,9 @@ class LightGlue(Module):elif features in ["dedodeb"]:fname = "dedodeb_lightglue.pth"url = "http://cmp.felk.cvut.cz/~mishkdmy/models/dedodeb_lightglue.pth"+ elif features in ["dedodeg"]:+ fname = "dedodeg_lightglue.pth"+ url = "http://cmp.felk.cvut.cz/~mishkdmy/models/dedodeg_lightglue.pth"else:url = self.url.format(self.version, features)state_dict = torch.hub.load_state_dict_from_url(url, file_name=fname)@@ -512,7 +519,6 @@ class LightGlue(Module):kpts1 = concatenate([kpts1] + [data1[k].unsqueeze(-1) for k in ("scales", "oris")], -1)if self.conf.scale_coef != 1.0:kpts1[..., -2] = kpts1[..., -2] * self.conf.scale_coef-elif self.conf.add_laf:laf0 = scale_laf(data0["lafs"], self.conf.scale_coef)laf1 = scale_laf(data1["lafs"], self.conf.scale_coef)diff --git a/pyproject.toml b/pyproject.tomlindex c61eaa7db..52329a892 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -153,7 +153,7 @@ requires = [[tool.ruff.lint.pylint]allow-magic-value-types = ["bytes", "float", "int", "str"]- max-args = 17 # Recommended: 5+ max-args = 30 # Recommended: 5max-branches = 21 # Recommended: 12max-returns = 13 # Recommended: 6max-statements = 64 # Recommended: 50@@ -166,6 +166,7 @@ requires = ["tests/*" = ["S101", "S311", "BLE", "RUF012", "RUF005"] # allow assert, random, ignore BLE, mutable class attr"benchmarks/*" = ["S101", "S311", "BLE", "RUF012", "RUF005"] # allow assert, random, ignore BLE, mutable class attr"testing/*" = ["S101",] # allow assert+ "kornia/feature/dedode/*" = ["C408", "FLY002", "PLR1714", "F401", "F841"] # allow DINOv2 things[tool.ruff.format]skip-magic-trailing-comma = false@@ -233,6 +234,7 @@ partial_branches = [show_error_codes = truewarn_redundant_casts = truewarn_unused_ignores = true+ exclude = ["kornia/feature/dedode/transformer"][tool.pydocstyle]ignore = ['D105','D107','D203','D204','D213','D406','D407']diff --git a/tests/feature/test_dedode.py b/tests/feature/test_dedode.pynew file mode 100644index 000000000..7befb8d10--- /dev/null+++ b/tests/feature/test_dedode.py@@ -0,0 +1,29 @@+import sys++import pytest+import torch++from kornia.feature.dedode import DeDoDe+from kornia.utils._compat import torch_version_le+++class TestDeDoDe:+ @pytest.mark.skipif(torch_version_le(2, 0, 0), reason="Autocast not supported")+ def test_smoke(self, dtype, device):+ # only testing "B" as dinov2 is quite heavy+ dedode = DeDoDe(descriptor_model="B").to(device, dtype)+ shape = (2, 3, 128, 128)+ n = 1000+ inp = torch.randn(*shape, device=device, dtype=dtype)+ keypoints, scores, descriptions = dedode(inp, n=n)+ assert keypoints.shape == (shape[0], n, 2)+ assert scores.shape == (shape[0], n)+ assert descriptions.shape == (shape[0], n, 256)++ @pytest.mark.slow+ @pytest.mark.skipif(sys.platform == "win32", reason="this test takes so much memory in the CI with Windows")+ def load_weights(self, dtype, device):+ # only testing "B" as dinov2 is quite heavy+ dedode = DeDoDe(descriptor_model="B").to(device, dtype)+ dedode = DeDoDe(descriptor_model="G").to(device, dtype)+ print(dedode)