attention.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # All rights reserved.
  3. #
  4. # This source code is licensed under the license found in the
  5. # LICENSE file in the root directory of this source tree.
  6. # References:
  7. # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
  8. # https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
  9. import logging
  10. from torch import Tensor
  11. from torch import nn
  12. logger = logging.getLogger("dinov2")
  13. try:
  14. from xformers.ops import memory_efficient_attention, unbind, fmha
  15. XFORMERS_AVAILABLE = True
  16. except ImportError:
  17. logger.warning("xFormers not available")
  18. XFORMERS_AVAILABLE = False
  19. class Attention(nn.Module):
  20. def __init__(
  21. self,
  22. dim: int,
  23. num_heads: int = 8,
  24. qkv_bias: bool = False,
  25. proj_bias: bool = True,
  26. attn_drop: float = 0.0,
  27. proj_drop: float = 0.0,
  28. ) -> None:
  29. super().__init__()
  30. self.num_heads = num_heads
  31. head_dim = dim // num_heads
  32. self.scale = head_dim**-0.5
  33. self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
  34. self.attn_drop = nn.Dropout(attn_drop)
  35. self.proj = nn.Linear(dim, dim, bias=proj_bias)
  36. self.proj_drop = nn.Dropout(proj_drop)
  37. def forward(self, x: Tensor) -> Tensor:
  38. B, N, C = x.shape
  39. qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
  40. q, k, v = qkv[0] * self.scale, qkv[1], qkv[2]
  41. attn = q @ k.transpose(-2, -1)
  42. attn = attn.softmax(dim=-1)
  43. attn = self.attn_drop(attn)
  44. x = (attn @ v).transpose(1, 2).reshape(B, N, C)
  45. x = self.proj(x)
  46. x = self.proj_drop(x)
  47. return x
  48. class MemEffAttention(Attention):
  49. def forward(self, x: Tensor, attn_bias=None) -> Tensor:
  50. if not XFORMERS_AVAILABLE:
  51. assert attn_bias is None, "xFormers is required for nested tensors usage"
  52. return super().forward(x)
  53. B, N, C = x.shape
  54. qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
  55. q, k, v = unbind(qkv, 2)
  56. x = memory_efficient_attention(q, k, v, attn_bias=attn_bias)
  57. x = x.reshape([B, N, C])
  58. x = self.proj(x)
  59. x = self.proj_drop(x)
  60. return x