π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): drop the dead `xformers` paths from DeDoDe's vendored DINOv2 (#4288)
Dmytro Mishkine095e88fa5c4
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6a65c3e14..608fcc630 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -292,6 +292,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* DeDoDe's vendored DINOv2 no longer probes for `xformers`; the pure-PyTorch path it always ran is the+ only one. (#4288)* `kornia.feature.LightGlue` no longer probes for `flash_attn`; the SDPA path it always used is nowthe only one. `kornia.feature.lightglue.Attention.enable_flash`, the attribute that combined theconstructor argument with the probe result (and so always equalled the argument, because SDPA isdiff --git a/kornia/feature/dedode/transformer/layers/attention.py b/kornia/feature/dedode/transformer/layers/attention.pyindex d5ca0cfe1..7d50aaf3e 100644--- a/kornia/feature/dedode/transformer/layers/attention.py+++ b/kornia/feature/dedode/transformer/layers/attention.py@@ -25,20 +25,8 @@# 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):"""Implement the standard Multi-Head Self-Attention mechanism.@@ -97,31 +85,23 @@ class Attention(nn.Module):class MemEffAttention(Attention):- """Implement a memory-efficient version of Multi-Head Self-Attention using xFormers."""+ """Implement Multi-Head Self-Attention under the class name the vendored DINOv2 builders select.++ The computation is the one of :class:`Attention`. The class name is kept because the DINOv2 model+ builders reference it; the extra ``attn_bias`` argument is kept so :meth:`forward` matches the upstream+ DINOv2 signature. Nothing in kornia passes it, and it must be ``None``.+ """def forward(self, x: Tensor, attn_bias=None) -> Tensor: # type: ignore[no-untyped-def]"""Run this DeDoDe module forward.Args:x: Input token sequence with shape :math:`(B, N, C)`.- attn_bias: Optional attention bias from xFormers for nested tensor support.+ attn_bias: Unsupported; must be ``None``.Returns:Attention output with shape :math:`(B, N, C)`."""- 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 x+ if attn_bias is not None:+ raise NotImplementedError("attn_bias is not supported")+ return super().forward(x)diff --git a/kornia/feature/dedode/transformer/layers/block.py b/kornia/feature/dedode/transformer/layers/block.pyindex 063b873d8..14f0b5b3f 100644--- a/kornia/feature/dedode/transformer/layers/block.py+++ b/kornia/feature/dedode/transformer/layers/block.py@@ -25,30 +25,16 @@# 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+from typing import Callableimport torchfrom torch import Tensor, nn-from kornia.core.check import KORNIA_CHECK--from .attention import Attention, MemEffAttention+from .attention import Attentionfrom .drop_path import DropPathfrom .layer_scale import LayerScalefrom .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):"""Implement a transformer block with attention and feed-forward sublayers.@@ -181,132 +167,29 @@ def drop_add_residual_stochastic_depth(return x_plus_residual.view_as(x)-def get_branges_scales(x, sample_drop_ratio=0.0):- """Add bernoulli sampled range and scale."""- 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):- """Add residual connections."""- 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):- """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:- """Add residual connections to a list of tensors."""- # 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):- """Implement a Transformer block capable of processing :class:`torch.NestedTensor` inputs."""-- 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:+ """Implement a transformer block over a single token tensor.- 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)+ The name is kept because the vendored DINOv2 model builders reference it. The nested-tensor+ list path this class used to offer needed an optional third-party dependency kornia never+ declared, so it was never reachable and has been removed.+ """def forward(self, x_or_x_list):"""Run this DeDoDe module forward.Args:- x_or_x_list: Either a single token tensor with shape :math:`(B, N, C)`, or a list of such tensors- for nested-tensor mode (requires xFormers).+ x_or_x_list: A single token tensor with shape :math:`(B, N, C)`.Returns:- Output token tensor(s) with the same shape(s) as the input.+ Output token tensor with the same shape as the input.++ Raises:+ TypeError: If the input is not a :class:`torch.Tensor`."""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 AssertionError+ raise TypeError(+ "NestedTensorBlock only accepts a Tensor; the nested-tensor list path was removed, "+ f"got {type(x_or_x_list).__name__}."+ )diff --git a/kornia/feature/dedode/transformer/layers/swiglu_ffn.py b/kornia/feature/dedode/transformer/layers/swiglu_ffn.pyindex 8b04dc337..1916d964f 100644--- a/kornia/feature/dedode/transformer/layers/swiglu_ffn.py+++ b/kornia/feature/dedode/transformer/layers/swiglu_ffn.py@@ -72,19 +72,11 @@ class SwiGLUFFN(nn.Module):return self.w3(hidden)-try:- from xformers.ops import SwiGLU+class SwiGLUFFNFused(SwiGLUFFN):+ """Implement :class:`SwiGLUFFN` with the DINOv2 hidden-dimension rounding.- XFORMERS_AVAILABLE = True-except ImportError:- SwiGLU = SwiGLUFFN- XFORMERS_AVAILABLE = False---class SwiGLUFFNFused(SwiGLU):- """Implement the fused SwiGLU activation and Feed-Forward Network.-- This implementation is optimized for training speed and memory usage.+ The hidden dimension is scaled by ``2 / 3`` and rounded up to a multiple of 8, which is the+ shape the pretrained DINOv2 checkpoints were saved with."""def __init__(diff --git a/tests/feature/test_dedode.py b/tests/feature/test_dedode.pyindex 35121091c..af3e37f80 100644--- a/tests/feature/test_dedode.py+++ b/tests/feature/test_dedode.py@@ -22,6 +22,7 @@ import torchfrom kornia.feature.dedode import DeDoDefrom kornia.feature.dedode.decoder import ConvRefiner+from kornia.feature.dedode.transformer.layers import MemEffAttention, NestedTensorBlockfrom testing.base import BaseTester@@ -45,6 +46,35 @@ class TestConvRefiner(BaseTester):assert not any("device_type of 'cuda'" in str(w.message) for w in caught)+class TestMemEffAttention(BaseTester):+ def test_attn_bias_raises(self, device, dtype):+ attention = MemEffAttention(dim=8, num_heads=2).to(device, dtype).eval()+ x = torch.rand(1, 5, 8, device=device, dtype=dtype)++ with pytest.raises(NotImplementedError, match="attn_bias is not supported"):+ attention(x, attn_bias=torch.zeros(1, 2, 5, 5, device=device, dtype=dtype))+++class TestNestedTensorBlock(BaseTester):+ def test_tensor_input(self, device, dtype):+ block = NestedTensorBlock(dim=8, num_heads=2).to(device, dtype).eval()+ x = torch.rand(1, 5, 8, device=device, dtype=dtype)++ out = block(x)++ assert out.shape == (1, 5, 8)+ # the block is a residual one, so the output has to differ from the input by the+ # attention and feed-forward branches actually having run.+ assert not torch.allclose(out, x)++ def test_list_input_raises(self, device, dtype):+ block = NestedTensorBlock(dim=8, num_heads=2).to(device, dtype).eval()+ x = torch.rand(1, 5, 8, device=device, dtype=dtype)++ with pytest.raises(TypeError, match="nested-tensor list path was removed"):+ block([x])++@pytest.mark.skip(reason="DeDoDe is ummaintained")class TestDeDoDe:@pytest.mark.slow