Addax-Data-Science commited on
Commit
e588fd8
·
verified ·
1 Parent(s): 9f71d6f

Upload 15 files

Browse files
dinov2/__init__.py ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
6
+ __version__ = "0.0.1"
dinov2/hub/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
dinov2/hub/backbones.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
6
+ from enum import Enum
7
+ from pathlib import Path
8
+ from typing import Optional, Union
9
+ from urllib.parse import urlparse
10
+
11
+ import torch
12
+
13
+ from .utils import _DINOV2_BASE_URL, _make_dinov2_model_name
14
+
15
+
16
+ class Weights(Enum):
17
+ LVD142M = "LVD142M"
18
+ XRAY_DINO = "XRay-DINO"
19
+
20
+
21
+ def is_url(path: str) -> bool:
22
+ parsed = urlparse(path)
23
+ return parsed.scheme in ("https", "file")
24
+
25
+
26
+ def convert_path_or_url_to_url(path: str) -> str:
27
+ if is_url(path):
28
+ return path
29
+ return Path(path).expanduser().resolve().as_uri()
30
+
31
+
32
+ def _make_dinov2_model(
33
+ *,
34
+ arch_name: str = "vit_large",
35
+ img_size: int = 518,
36
+ patch_size: int = 14,
37
+ init_values: float = 1.0,
38
+ ffn_layer: str = "mlp",
39
+ block_chunks: int = 0,
40
+ num_register_tokens: int = 0,
41
+ interpolate_antialias: bool = False,
42
+ interpolate_offset: float = 0.1,
43
+ pretrained: bool = True,
44
+ weights: Union[Weights, str] = Weights.LVD142M,
45
+ hash: Optional[str] = None,
46
+ check_hash: bool = False,
47
+ **kwargs,
48
+ ):
49
+ from ..models import vision_transformer as vits
50
+
51
+ model_base_name = _make_dinov2_model_name(arch_name, patch_size)
52
+ vit_kwargs = dict(
53
+ img_size=img_size,
54
+ patch_size=patch_size,
55
+ init_values=init_values,
56
+ ffn_layer=ffn_layer,
57
+ block_chunks=block_chunks,
58
+ num_register_tokens=num_register_tokens,
59
+ interpolate_antialias=interpolate_antialias,
60
+ interpolate_offset=interpolate_offset,
61
+ )
62
+ vit_kwargs.update(**kwargs)
63
+ model = vits.__dict__[arch_name](**vit_kwargs)
64
+
65
+ if pretrained:
66
+ if type(weights) is Weights and weights not in {
67
+ Weights.LVD142M,
68
+ Weights.XRAY_DINO,
69
+ }:
70
+ raise ValueError(f"Unsupported weights for the backbone: {weights}")
71
+ elif type(weights) is Weights:
72
+ model_full_name = _make_dinov2_model_name(arch_name, patch_size, num_register_tokens)
73
+ url = _DINOV2_BASE_URL + f"/{model_base_name}/{model_full_name}_pretrain.pth"
74
+ else:
75
+ url = convert_path_or_url_to_url(weights)
76
+ state_dict = torch.hub.load_state_dict_from_url(url, map_location="cpu", check_hash=check_hash)
77
+ model.load_state_dict(state_dict, strict=True)
78
+
79
+ return model
80
+
81
+
82
+ def dinov2_vits14(*, pretrained: bool = True, weights: Union[Weights, str] = Weights.LVD142M, **kwargs):
83
+ """
84
+ DINOv2 ViT-S/14 model (optionally) pretrained on the LVD-142M dataset.
85
+ """
86
+ return _make_dinov2_model(arch_name="vit_small", pretrained=pretrained, weights=weights, **kwargs)
87
+
88
+
89
+ def dinov2_vitb14(*, pretrained: bool = True, weights: Union[Weights, str] = Weights.LVD142M, **kwargs):
90
+ """
91
+ DINOv2 ViT-B/14 model (optionally) pretrained on the LVD-142M dataset.
92
+ """
93
+ return _make_dinov2_model(arch_name="vit_base", pretrained=pretrained, weights=weights, **kwargs)
94
+
95
+
96
+ def dinov2_vitl14(*, pretrained: bool = True, weights: Union[Weights, str] = Weights.LVD142M, **kwargs):
97
+ """
98
+ DINOv2 ViT-L/14 model (optionally) pretrained on the LVD-142M dataset.
99
+ """
100
+ return _make_dinov2_model(arch_name="vit_large", pretrained=pretrained, weights=weights, **kwargs)
101
+
102
+
103
+ def dinov2_vitg14(*, pretrained: bool = True, weights: Union[Weights, str] = Weights.LVD142M, **kwargs):
104
+ """
105
+ DINOv2 ViT-g/14 model (optionally) pretrained on the LVD-142M dataset.
106
+ """
107
+ return _make_dinov2_model(
108
+ arch_name="vit_giant2",
109
+ ffn_layer="swiglufused",
110
+ weights=weights,
111
+ pretrained=pretrained,
112
+ **kwargs,
113
+ )
114
+
115
+
116
+ def dinov2_vits14_reg(*, pretrained: bool = True, weights: Union[Weights, str] = Weights.LVD142M, **kwargs):
117
+ """
118
+ DINOv2 ViT-S/14 model with registers (optionally) pretrained on the LVD-142M dataset.
119
+ """
120
+ return _make_dinov2_model(
121
+ arch_name="vit_small",
122
+ pretrained=pretrained,
123
+ weights=weights,
124
+ num_register_tokens=4,
125
+ interpolate_antialias=True,
126
+ interpolate_offset=0.0,
127
+ **kwargs,
128
+ )
129
+
130
+
131
+ def dinov2_vitb14_reg(*, pretrained: bool = True, weights: Union[Weights, str] = Weights.LVD142M, **kwargs):
132
+ """
133
+ DINOv2 ViT-B/14 model with registers (optionally) pretrained on the LVD-142M dataset.
134
+ """
135
+ return _make_dinov2_model(
136
+ arch_name="vit_base",
137
+ pretrained=pretrained,
138
+ weights=weights,
139
+ num_register_tokens=4,
140
+ interpolate_antialias=True,
141
+ interpolate_offset=0.0,
142
+ **kwargs,
143
+ )
144
+
145
+
146
+ def dinov2_vitl14_reg(*, pretrained: bool = True, weights: Union[Weights, str] = Weights.LVD142M, **kwargs):
147
+ """
148
+ DINOv2 ViT-L/14 model with registers (optionally) pretrained on the LVD-142M dataset.
149
+ """
150
+ return _make_dinov2_model(
151
+ arch_name="vit_large",
152
+ pretrained=pretrained,
153
+ weights=weights,
154
+ num_register_tokens=4,
155
+ interpolate_antialias=True,
156
+ interpolate_offset=0.0,
157
+ **kwargs,
158
+ )
159
+
160
+
161
+ def dinov2_vitg14_reg(*, pretrained: bool = True, weights: Union[Weights, str] = Weights.LVD142M, **kwargs):
162
+ """
163
+ DINOv2 ViT-g/14 model with registers (optionally) pretrained on the LVD-142M dataset.
164
+ """
165
+ return _make_dinov2_model(
166
+ arch_name="vit_giant2",
167
+ ffn_layer="swiglufused",
168
+ weights=weights,
169
+ pretrained=pretrained,
170
+ num_register_tokens=4,
171
+ interpolate_antialias=True,
172
+ interpolate_offset=0.0,
173
+ **kwargs,
174
+ )
dinov2/hub/utils.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
6
+ import itertools
7
+ import math
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.nn.functional as F
12
+
13
+
14
+ _DINOV2_BASE_URL = "https://dl.fbaipublicfiles.com/dinov2"
15
+
16
+
17
+ def _make_dinov2_model_name(arch_name: str, patch_size: int, num_register_tokens: int = 0) -> str:
18
+ compact_arch_name = arch_name.replace("_", "")[:4]
19
+ registers_suffix = f"_reg{num_register_tokens}" if num_register_tokens else ""
20
+ return f"dinov2_{compact_arch_name}{patch_size}{registers_suffix}"
21
+
22
+
23
+ class CenterPadding(nn.Module):
24
+ def __init__(self, multiple):
25
+ super().__init__()
26
+ self.multiple = multiple
27
+
28
+ def _get_pad(self, size):
29
+ new_size = math.ceil(size / self.multiple) * self.multiple
30
+ pad_size = new_size - size
31
+ pad_size_left = pad_size // 2
32
+ pad_size_right = pad_size - pad_size_left
33
+ return pad_size_left, pad_size_right
34
+
35
+ @torch.inference_mode()
36
+ def forward(self, x):
37
+ pads = list(itertools.chain.from_iterable(self._get_pad(m) for m in x.shape[:1:-1]))
38
+ output = F.pad(x, pads)
39
+ return output
dinov2/layers/__init__.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
6
+ from .dino_head import DINOHead
7
+ from .layer_scale import LayerScale
8
+ from .mlp import Mlp
9
+ from .patch_embed import PatchEmbed
10
+ from .swiglu_ffn import SwiGLUFFN, SwiGLUFFNFused, SwiGLUFFNAligned
11
+ from .block import NestedTensorBlock, CausalAttentionBlock
12
+ from .attention import Attention, MemEffAttention
dinov2/layers/attention.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
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
+
10
+ import logging
11
+ import os
12
+ import warnings
13
+
14
+ import torch
15
+ from torch import nn, Tensor
16
+
17
+
18
+ logger = logging.getLogger("dinov2")
19
+
20
+
21
+ XFORMERS_ENABLED = os.environ.get("XFORMERS_DISABLED") is None
22
+ try:
23
+ if XFORMERS_ENABLED:
24
+ from xformers.ops import memory_efficient_attention, unbind
25
+
26
+ XFORMERS_AVAILABLE = True
27
+ warnings.warn("xFormers is available (Attention)")
28
+ else:
29
+ warnings.warn("xFormers is disabled (Attention)")
30
+ raise ImportError
31
+ except ImportError:
32
+ XFORMERS_AVAILABLE = False
33
+ warnings.warn("xFormers is not available (Attention)")
34
+
35
+
36
+ class Attention(nn.Module):
37
+ def __init__(
38
+ self,
39
+ dim: int,
40
+ num_heads: int = 8,
41
+ qkv_bias: bool = False,
42
+ proj_bias: bool = True,
43
+ attn_drop: float = 0.0,
44
+ proj_drop: float = 0.0,
45
+ ) -> None:
46
+ super().__init__()
47
+ self.dim = dim
48
+ self.num_heads = num_heads
49
+ head_dim = dim // num_heads
50
+ self.scale = head_dim**-0.5
51
+
52
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
53
+ self.attn_drop = attn_drop
54
+ self.proj = nn.Linear(dim, dim, bias=proj_bias)
55
+ self.proj_drop = nn.Dropout(proj_drop)
56
+
57
+ def init_weights(
58
+ self, init_attn_std: float | None = None, init_proj_std: float | None = None, factor: float = 1.0
59
+ ) -> None:
60
+ init_attn_std = init_attn_std or (self.dim**-0.5)
61
+ init_proj_std = init_proj_std or init_attn_std * factor
62
+ nn.init.normal_(self.qkv.weight, std=init_attn_std)
63
+ nn.init.normal_(self.proj.weight, std=init_proj_std)
64
+ if self.qkv.bias is not None:
65
+ nn.init.zeros_(self.qkv.bias)
66
+ if self.proj.bias is not None:
67
+ nn.init.zeros_(self.proj.bias)
68
+
69
+ def forward(self, x: Tensor, is_causal: bool = False) -> Tensor:
70
+ B, N, C = x.shape
71
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
72
+ q, k, v = torch.unbind(qkv, 2)
73
+ q, k, v = [t.transpose(1, 2) for t in [q, k, v]]
74
+ x = nn.functional.scaled_dot_product_attention(
75
+ q, k, v, attn_mask=None, dropout_p=self.attn_drop if self.training else 0, is_causal=is_causal
76
+ )
77
+ x = x.transpose(1, 2).contiguous().view(B, N, C)
78
+ x = self.proj_drop(self.proj(x))
79
+ return x
80
+
81
+
82
+ class MemEffAttention(Attention):
83
+ def forward(self, x: Tensor, attn_bias=None) -> Tensor:
84
+ if not XFORMERS_AVAILABLE:
85
+ if attn_bias is not None:
86
+ raise AssertionError("xFormers is required for using nested tensors")
87
+ return super().forward(x)
88
+
89
+ B, N, C = x.shape
90
+ qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
91
+
92
+ q, k, v = unbind(qkv, 2)
93
+
94
+ x = memory_efficient_attention(q, k, v, attn_bias=attn_bias)
95
+ x = x.reshape([B, N, C])
96
+
97
+ x = self.proj(x)
98
+ x = self.proj_drop(x)
99
+ return x
dinov2/layers/block.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
6
+ # References:
7
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
8
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
9
+
10
+ import logging
11
+ import os
12
+ from typing import Callable, List, Any, Tuple, Dict, Optional
13
+ import warnings
14
+
15
+ import torch
16
+ from torch import nn, Tensor
17
+
18
+ from .attention import Attention, MemEffAttention
19
+ from .drop_path import DropPath
20
+ from .layer_scale import LayerScale
21
+ from .mlp import Mlp
22
+
23
+
24
+ logger = logging.getLogger("dinov2")
25
+
26
+
27
+ XFORMERS_ENABLED = os.environ.get("XFORMERS_DISABLED") is None
28
+ try:
29
+ if XFORMERS_ENABLED:
30
+ from xformers.ops import fmha, scaled_index_add, index_select_cat
31
+
32
+ XFORMERS_AVAILABLE = True
33
+ warnings.warn("xFormers is available (Block)")
34
+ else:
35
+ warnings.warn("xFormers is disabled (Block)")
36
+ raise ImportError
37
+ except ImportError:
38
+ XFORMERS_AVAILABLE = False
39
+
40
+ warnings.warn("xFormers is not available (Block)")
41
+
42
+
43
+ class Block(nn.Module):
44
+ def __init__(
45
+ self,
46
+ dim: int,
47
+ num_heads: int,
48
+ mlp_ratio: float = 4.0,
49
+ qkv_bias: bool = False,
50
+ proj_bias: bool = True,
51
+ ffn_bias: bool = True,
52
+ drop: float = 0.0,
53
+ attn_drop: float = 0.0,
54
+ init_values=None,
55
+ drop_path: float = 0.0,
56
+ act_layer: Callable[..., nn.Module] = nn.GELU,
57
+ norm_layer: Callable[..., nn.Module] = nn.LayerNorm,
58
+ attn_class: Callable[..., nn.Module] = Attention,
59
+ ffn_layer: Callable[..., nn.Module] = Mlp,
60
+ ) -> None:
61
+ super().__init__()
62
+ # print(f"biases: qkv: {qkv_bias}, proj: {proj_bias}, ffn: {ffn_bias}")
63
+ self.norm1 = norm_layer(dim)
64
+ self.attn = attn_class(
65
+ dim,
66
+ num_heads=num_heads,
67
+ qkv_bias=qkv_bias,
68
+ proj_bias=proj_bias,
69
+ attn_drop=attn_drop,
70
+ proj_drop=drop,
71
+ )
72
+ self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
73
+ self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
74
+
75
+ self.norm2 = norm_layer(dim)
76
+ mlp_hidden_dim = int(dim * mlp_ratio)
77
+ self.mlp = ffn_layer(
78
+ in_features=dim,
79
+ hidden_features=mlp_hidden_dim,
80
+ act_layer=act_layer,
81
+ drop=drop,
82
+ bias=ffn_bias,
83
+ )
84
+ self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
85
+ self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
86
+
87
+ self.sample_drop_ratio = drop_path
88
+
89
+ def forward(self, x: Tensor) -> Tensor:
90
+ def attn_residual_func(x: Tensor) -> Tensor:
91
+ return self.ls1(self.attn(self.norm1(x)))
92
+
93
+ def ffn_residual_func(x: Tensor) -> Tensor:
94
+ return self.ls2(self.mlp(self.norm2(x)))
95
+
96
+ if self.training and self.sample_drop_ratio > 0.1:
97
+ # the overhead is compensated only for a drop path rate larger than 0.1
98
+ x = drop_add_residual_stochastic_depth(
99
+ x,
100
+ residual_func=attn_residual_func,
101
+ sample_drop_ratio=self.sample_drop_ratio,
102
+ )
103
+ x = drop_add_residual_stochastic_depth(
104
+ x,
105
+ residual_func=ffn_residual_func,
106
+ sample_drop_ratio=self.sample_drop_ratio,
107
+ )
108
+ elif self.training and self.sample_drop_ratio > 0.0:
109
+ x = x + self.drop_path1(attn_residual_func(x))
110
+ x = x + self.drop_path1(ffn_residual_func(x)) # FIXME: drop_path2
111
+ else:
112
+ x = x + attn_residual_func(x)
113
+ x = x + ffn_residual_func(x)
114
+ return x
115
+
116
+
117
+ class CausalAttentionBlock(nn.Module):
118
+ def __init__(
119
+ self,
120
+ dim: int,
121
+ num_heads: int,
122
+ ffn_ratio: float = 4.0,
123
+ ls_init_value: Optional[float] = None,
124
+ is_causal: bool = True,
125
+ act_layer: Callable = nn.GELU,
126
+ norm_layer: Callable = nn.LayerNorm,
127
+ dropout_prob: float = 0.0,
128
+ ):
129
+ super().__init__()
130
+
131
+ self.dim = dim
132
+ self.is_causal = is_causal
133
+ self.ls1 = LayerScale(dim, init_values=ls_init_value) if ls_init_value else nn.Identity()
134
+ self.attention_norm = norm_layer(dim)
135
+ self.attention = Attention(dim, num_heads, attn_drop=dropout_prob, proj_drop=dropout_prob)
136
+
137
+ self.ffn_norm = norm_layer(dim)
138
+ ffn_hidden_dim = int(dim * ffn_ratio)
139
+ self.feed_forward = Mlp(
140
+ in_features=dim,
141
+ hidden_features=ffn_hidden_dim,
142
+ drop=dropout_prob,
143
+ act_layer=act_layer,
144
+ )
145
+
146
+ self.ls2 = LayerScale(dim, init_values=ls_init_value) if ls_init_value else nn.Identity()
147
+
148
+ def init_weights(
149
+ self,
150
+ init_attn_std: float | None = None,
151
+ init_proj_std: float | None = None,
152
+ init_fc_std: float | None = None,
153
+ factor: float = 1.0,
154
+ ) -> None:
155
+ init_attn_std = init_attn_std or (self.dim**-0.5)
156
+ init_proj_std = init_proj_std or init_attn_std * factor
157
+ init_fc_std = init_fc_std or (2 * self.dim) ** -0.5
158
+ self.attention.init_weights(init_attn_std, init_proj_std)
159
+ self.attention_norm.reset_parameters()
160
+ nn.init.normal_(self.feed_forward.fc1.weight, std=init_fc_std)
161
+ nn.init.normal_(self.feed_forward.fc2.weight, std=init_proj_std)
162
+ self.ffn_norm.reset_parameters()
163
+
164
+ def forward(
165
+ self,
166
+ x: torch.Tensor,
167
+ ):
168
+ x_attn = x + self.ls1(self.attention(self.attention_norm(x), self.is_causal))
169
+ x_ffn = x_attn + self.ls2(self.feed_forward(self.ffn_norm(x_attn)))
170
+ return x_ffn
171
+
172
+
173
+ def drop_add_residual_stochastic_depth(
174
+ x: Tensor,
175
+ residual_func: Callable[[Tensor], Tensor],
176
+ sample_drop_ratio: float = 0.0,
177
+ ) -> Tensor:
178
+ # 1) extract subset using permutation
179
+ b, n, d = x.shape
180
+ sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1)
181
+ brange = (torch.randperm(b, device=x.device))[:sample_subset_size]
182
+ x_subset = x[brange]
183
+
184
+ # 2) apply residual_func to get residual
185
+ residual = residual_func(x_subset)
186
+
187
+ x_flat = x.flatten(1)
188
+ residual = residual.flatten(1)
189
+
190
+ residual_scale_factor = b / sample_subset_size
191
+
192
+ # 3) add the residual
193
+ x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor)
194
+ return x_plus_residual.view_as(x)
195
+
196
+
197
+ def get_branges_scales(x, sample_drop_ratio=0.0):
198
+ b, n, d = x.shape
199
+ sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1)
200
+ brange = (torch.randperm(b, device=x.device))[:sample_subset_size]
201
+ residual_scale_factor = b / sample_subset_size
202
+ return brange, residual_scale_factor
203
+
204
+
205
+ def add_residual(x, brange, residual, residual_scale_factor, scaling_vector=None):
206
+ if scaling_vector is None:
207
+ x_flat = x.flatten(1)
208
+ residual = residual.flatten(1)
209
+ x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor)
210
+ else:
211
+ x_plus_residual = scaled_index_add(
212
+ x, brange, residual.to(dtype=x.dtype), scaling=scaling_vector, alpha=residual_scale_factor
213
+ )
214
+ return x_plus_residual
215
+
216
+
217
+ attn_bias_cache: Dict[Tuple, Any] = {}
218
+
219
+
220
+ def get_attn_bias_and_cat(x_list, branges=None):
221
+ """
222
+ this will perform the index select, cat the tensors, and provide the attn_bias from cache
223
+ """
224
+ batch_sizes = [b.shape[0] for b in branges] if branges is not None else [x.shape[0] for x in x_list]
225
+ all_shapes = tuple((b, x.shape[1]) for b, x in zip(batch_sizes, x_list))
226
+ if all_shapes not in attn_bias_cache.keys():
227
+ seqlens = []
228
+ for b, x in zip(batch_sizes, x_list):
229
+ for _ in range(b):
230
+ seqlens.append(x.shape[1])
231
+ attn_bias = fmha.BlockDiagonalMask.from_seqlens(seqlens)
232
+ attn_bias._batch_sizes = batch_sizes
233
+ attn_bias_cache[all_shapes] = attn_bias
234
+
235
+ if branges is not None:
236
+ cat_tensors = index_select_cat([x.flatten(1) for x in x_list], branges).view(1, -1, x_list[0].shape[-1])
237
+ else:
238
+ tensors_bs1 = tuple(x.reshape([1, -1, *x.shape[2:]]) for x in x_list)
239
+ cat_tensors = torch.cat(tensors_bs1, dim=1)
240
+
241
+ return attn_bias_cache[all_shapes], cat_tensors
242
+
243
+
244
+ def drop_add_residual_stochastic_depth_list(
245
+ x_list: List[Tensor],
246
+ residual_func: Callable[[Tensor, Any], Tensor],
247
+ sample_drop_ratio: float = 0.0,
248
+ scaling_vector=None,
249
+ ) -> Tensor:
250
+ # 1) generate random set of indices for dropping samples in the batch
251
+ branges_scales = [get_branges_scales(x, sample_drop_ratio=sample_drop_ratio) for x in x_list]
252
+ branges = [s[0] for s in branges_scales]
253
+ residual_scale_factors = [s[1] for s in branges_scales]
254
+
255
+ # 2) get attention bias and index+concat the tensors
256
+ attn_bias, x_cat = get_attn_bias_and_cat(x_list, branges)
257
+
258
+ # 3) apply residual_func to get residual, and split the result
259
+ residual_list = attn_bias.split(residual_func(x_cat, attn_bias=attn_bias)) # type: ignore
260
+
261
+ outputs = []
262
+ for x, brange, residual, residual_scale_factor in zip(x_list, branges, residual_list, residual_scale_factors):
263
+ outputs.append(add_residual(x, brange, residual, residual_scale_factor, scaling_vector).view_as(x))
264
+ return outputs
265
+
266
+
267
+ class NestedTensorBlock(Block):
268
+ def forward_nested(self, x_list: List[Tensor]) -> List[Tensor]:
269
+ """
270
+ x_list contains a list of tensors to nest together and run
271
+ """
272
+ assert isinstance(self.attn, MemEffAttention)
273
+
274
+ if self.training and self.sample_drop_ratio > 0.0:
275
+
276
+ def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
277
+ return self.attn(self.norm1(x), attn_bias=attn_bias)
278
+
279
+ def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
280
+ return self.mlp(self.norm2(x))
281
+
282
+ x_list = drop_add_residual_stochastic_depth_list(
283
+ x_list,
284
+ residual_func=attn_residual_func,
285
+ sample_drop_ratio=self.sample_drop_ratio,
286
+ scaling_vector=self.ls1.gamma if isinstance(self.ls1, LayerScale) else None,
287
+ )
288
+ x_list = drop_add_residual_stochastic_depth_list(
289
+ x_list,
290
+ residual_func=ffn_residual_func,
291
+ sample_drop_ratio=self.sample_drop_ratio,
292
+ scaling_vector=self.ls2.gamma if isinstance(self.ls1, LayerScale) else None,
293
+ )
294
+ return x_list
295
+ else:
296
+
297
+ def attn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
298
+ return self.ls1(self.attn(self.norm1(x), attn_bias=attn_bias))
299
+
300
+ def ffn_residual_func(x: Tensor, attn_bias=None) -> Tensor:
301
+ return self.ls2(self.mlp(self.norm2(x)))
302
+
303
+ attn_bias, x = get_attn_bias_and_cat(x_list)
304
+ x = x + attn_residual_func(x, attn_bias=attn_bias)
305
+ x = x + ffn_residual_func(x)
306
+ return attn_bias.split(x)
307
+
308
+ def forward(self, x_or_x_list):
309
+ if isinstance(x_or_x_list, Tensor):
310
+ return super().forward(x_or_x_list)
311
+ elif isinstance(x_or_x_list, list):
312
+ if not XFORMERS_AVAILABLE:
313
+ raise AssertionError("xFormers is required for using nested tensors")
314
+ return self.forward_nested(x_or_x_list)
315
+ else:
316
+ raise AssertionError
dinov2/layers/dino_head.py ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ from torch.nn.init import trunc_normal_
9
+ from torch.nn.utils import weight_norm
10
+
11
+
12
+ class DINOHead(nn.Module):
13
+ def __init__(
14
+ self,
15
+ in_dim,
16
+ out_dim,
17
+ use_bn=False,
18
+ nlayers=3,
19
+ hidden_dim=2048,
20
+ bottleneck_dim=256,
21
+ mlp_bias=True,
22
+ ):
23
+ super().__init__()
24
+ nlayers = max(nlayers, 1)
25
+ self.mlp = _build_mlp(nlayers, in_dim, bottleneck_dim, hidden_dim=hidden_dim, use_bn=use_bn, bias=mlp_bias)
26
+ self.apply(self._init_weights)
27
+ self.last_layer = weight_norm(nn.Linear(bottleneck_dim, out_dim, bias=False))
28
+ self.last_layer.weight_g.data.fill_(1)
29
+
30
+ def _init_weights(self, m):
31
+ if isinstance(m, nn.Linear):
32
+ trunc_normal_(m.weight, std=0.02)
33
+ if isinstance(m, nn.Linear) and m.bias is not None:
34
+ nn.init.constant_(m.bias, 0)
35
+
36
+ def forward(self, x):
37
+ x = self.mlp(x)
38
+ eps = 1e-6 if x.dtype == torch.float16 else 1e-12
39
+ x = nn.functional.normalize(x, dim=-1, p=2, eps=eps)
40
+ x = self.last_layer(x)
41
+ return x
42
+
43
+
44
+ def _build_mlp(nlayers, in_dim, bottleneck_dim, hidden_dim=None, use_bn=False, bias=True):
45
+ if nlayers == 1:
46
+ return nn.Linear(in_dim, bottleneck_dim, bias=bias)
47
+ else:
48
+ layers = [nn.Linear(in_dim, hidden_dim, bias=bias)]
49
+ if use_bn:
50
+ layers.append(nn.BatchNorm1d(hidden_dim))
51
+ layers.append(nn.GELU())
52
+ for _ in range(nlayers - 2):
53
+ layers.append(nn.Linear(hidden_dim, hidden_dim, bias=bias))
54
+ if use_bn:
55
+ layers.append(nn.BatchNorm1d(hidden_dim))
56
+ layers.append(nn.GELU())
57
+ layers.append(nn.Linear(hidden_dim, bottleneck_dim, bias=bias))
58
+ return nn.Sequential(*layers)
dinov2/layers/drop_path.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
6
+ # References:
7
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
8
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/drop.py
9
+
10
+
11
+ from torch import nn
12
+
13
+
14
+ def drop_path(x, drop_prob: float = 0.0, training: bool = False):
15
+ if drop_prob == 0.0 or not training:
16
+ return x
17
+ keep_prob = 1 - drop_prob
18
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
19
+ random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
20
+ if keep_prob > 0.0:
21
+ random_tensor.div_(keep_prob)
22
+ output = x * random_tensor
23
+ return output
24
+
25
+
26
+ class DropPath(nn.Module):
27
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
28
+
29
+ def __init__(self, drop_prob=None):
30
+ super(DropPath, self).__init__()
31
+ self.drop_prob = drop_prob
32
+
33
+ def forward(self, x):
34
+ return drop_path(x, self.drop_prob, self.training)
dinov2/layers/layer_scale.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
6
+ # Modified from: https://github.com/huggingface/pytorch-image-models/blob/main/timm/models/vision_transformer.py#L103-L110
7
+
8
+ from typing import Optional, Union
9
+
10
+ import torch
11
+ from torch import Tensor
12
+ from torch import nn
13
+
14
+
15
+ class LayerScale(nn.Module):
16
+ def __init__(
17
+ self,
18
+ dim: int,
19
+ init_values: Union[float, Tensor] = 1e-5,
20
+ inplace: bool = False,
21
+ device: Optional[torch.device] = None,
22
+ dtype: Optional[torch.dtype] = None,
23
+ ) -> None:
24
+ super().__init__()
25
+ self.inplace = inplace
26
+ self.init_values = init_values
27
+ self.gamma = nn.Parameter(torch.empty(dim, device=device, dtype=dtype))
28
+ self.reset_parameters()
29
+
30
+ def reset_parameters(self):
31
+ nn.init.constant_(self.gamma, self.init_values)
32
+
33
+ def forward(self, x: Tensor) -> Tensor:
34
+ return x.mul_(self.gamma) if self.inplace else x * self.gamma
dinov2/layers/mlp.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
6
+ # References:
7
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
8
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/mlp.py
9
+
10
+
11
+ from typing import Callable, Optional
12
+
13
+ from torch import Tensor, nn
14
+
15
+
16
+ class Mlp(nn.Module):
17
+ def __init__(
18
+ self,
19
+ in_features: int,
20
+ hidden_features: Optional[int] = None,
21
+ out_features: Optional[int] = None,
22
+ act_layer: Callable[..., nn.Module] = nn.GELU,
23
+ drop: float = 0.0,
24
+ bias: bool = True,
25
+ ) -> None:
26
+ super().__init__()
27
+ out_features = out_features or in_features
28
+ hidden_features = hidden_features or in_features
29
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias)
30
+ self.act = act_layer()
31
+ self.fc2 = nn.Linear(hidden_features, out_features, bias=bias)
32
+ self.drop = nn.Dropout(drop)
33
+
34
+ def forward(self, x: Tensor) -> Tensor:
35
+ x = self.fc1(x)
36
+ x = self.act(x)
37
+ x = self.drop(x)
38
+ x = self.fc2(x)
39
+ x = self.drop(x)
40
+ return x
dinov2/layers/patch_embed.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
6
+ # References:
7
+ # https://github.com/facebookresearch/dino/blob/master/vision_transformer.py
8
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/layers/patch_embed.py
9
+
10
+ from typing import Callable, Optional, Tuple, Union
11
+
12
+ from torch import Tensor
13
+ import torch.nn as nn
14
+
15
+
16
+ def make_2tuple(x):
17
+ if isinstance(x, tuple):
18
+ assert len(x) == 2
19
+ return x
20
+
21
+ assert isinstance(x, int)
22
+ return (x, x)
23
+
24
+
25
+ class PatchEmbed(nn.Module):
26
+ """
27
+ 2D image to patch embedding: (B,C,H,W) -> (B,N,D)
28
+
29
+ Args:
30
+ img_size: Image size.
31
+ patch_size: Patch token size.
32
+ in_chans: Number of input image channels.
33
+ embed_dim: Number of linear projection output channels.
34
+ norm_layer: Normalization layer.
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ img_size: Union[int, Tuple[int, int]] = 224,
40
+ patch_size: Union[int, Tuple[int, int]] = 16,
41
+ in_chans: int = 3,
42
+ embed_dim: int = 768,
43
+ norm_layer: Optional[Callable] = None,
44
+ flatten_embedding: bool = True,
45
+ ) -> None:
46
+ super().__init__()
47
+
48
+ image_HW = make_2tuple(img_size)
49
+ patch_HW = make_2tuple(patch_size)
50
+ patch_grid_size = (
51
+ image_HW[0] // patch_HW[0],
52
+ image_HW[1] // patch_HW[1],
53
+ )
54
+
55
+ self.img_size = image_HW
56
+ self.patch_size = patch_HW
57
+ self.patches_resolution = patch_grid_size
58
+ self.num_patches = patch_grid_size[0] * patch_grid_size[1]
59
+
60
+ self.in_chans = in_chans
61
+ self.embed_dim = embed_dim
62
+
63
+ self.flatten_embedding = flatten_embedding
64
+
65
+ self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW)
66
+ self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
67
+
68
+ def forward(self, x: Tensor) -> Tensor:
69
+ _, _, H, W = x.shape
70
+ patch_H, patch_W = self.patch_size
71
+
72
+ assert H % patch_H == 0, f"Input image height {H} is not a multiple of patch height {patch_H}"
73
+ assert W % patch_W == 0, f"Input image width {W} is not a multiple of patch width: {patch_W}"
74
+
75
+ x = self.proj(x) # B C H W
76
+ H, W = x.size(2), x.size(3)
77
+ x = x.flatten(2).transpose(1, 2) # B HW C
78
+ x = self.norm(x)
79
+ if not self.flatten_embedding:
80
+ x = x.reshape(-1, H, W, self.embed_dim) # B H W C
81
+ return x
82
+
83
+ def flops(self) -> float:
84
+ Ho, Wo = self.patches_resolution
85
+ flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1])
86
+ if self.norm is not None:
87
+ flops += Ho * Wo * self.embed_dim
88
+ return flops
dinov2/layers/swiglu_ffn.py ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
6
+ import os
7
+ from typing import Callable, Optional
8
+ import warnings
9
+
10
+ from torch import Tensor, nn
11
+ import torch.nn.functional as F
12
+
13
+
14
+ class SwiGLUFFN(nn.Module):
15
+ def __init__(
16
+ self,
17
+ in_features: int,
18
+ hidden_features: Optional[int] = None,
19
+ out_features: Optional[int] = None,
20
+ act_layer: Callable[..., nn.Module] = None,
21
+ drop: float = 0.0,
22
+ bias: bool = True,
23
+ ) -> None:
24
+ super().__init__()
25
+ out_features = out_features or in_features
26
+ hidden_features = hidden_features or in_features
27
+ self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias)
28
+ self.w3 = nn.Linear(hidden_features, out_features, bias=bias)
29
+
30
+ def forward(self, x: Tensor) -> Tensor:
31
+ x12 = self.w12(x)
32
+ x1, x2 = x12.chunk(2, dim=-1)
33
+ hidden = F.silu(x1) * x2
34
+ return self.w3(hidden)
35
+
36
+
37
+ XFORMERS_ENABLED = os.environ.get("XFORMERS_DISABLED") is None
38
+ try:
39
+ if XFORMERS_ENABLED:
40
+ from xformers.ops import SwiGLU
41
+
42
+ XFORMERS_AVAILABLE = True
43
+ warnings.warn("xFormers is available (SwiGLU)")
44
+ else:
45
+ warnings.warn("xFormers is disabled (SwiGLU)")
46
+ raise ImportError
47
+ except ImportError:
48
+ SwiGLU = SwiGLUFFN
49
+ XFORMERS_AVAILABLE = False
50
+
51
+ warnings.warn("xFormers is not available (SwiGLU)")
52
+
53
+
54
+ class SwiGLUFFNFused(SwiGLU):
55
+ def __init__(
56
+ self,
57
+ in_features: int,
58
+ hidden_features: Optional[int] = None,
59
+ out_features: Optional[int] = None,
60
+ act_layer: Callable[..., nn.Module] = None,
61
+ drop: float = 0.0,
62
+ bias: bool = True,
63
+ ) -> None:
64
+ out_features = out_features or in_features
65
+ hidden_features = hidden_features or in_features
66
+ hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8
67
+ super().__init__(
68
+ in_features=in_features,
69
+ hidden_features=hidden_features,
70
+ out_features=out_features,
71
+ bias=bias,
72
+ )
73
+
74
+
75
+ class SwiGLUFFNAligned(nn.Module):
76
+ def __init__(
77
+ self,
78
+ in_features: int,
79
+ hidden_features: Optional[int] = None,
80
+ out_features: Optional[int] = None,
81
+ act_layer: Callable[..., nn.Module] = nn.GELU,
82
+ drop: float = 0.0,
83
+ bias: bool = True,
84
+ align_to: int = 8,
85
+ device=None,
86
+ ) -> None:
87
+ super().__init__()
88
+ out_features = out_features or in_features
89
+ hidden_features = hidden_features or in_features
90
+ d = int(hidden_features * 2 / 3)
91
+ swiglu_hidden_features = d + (-d % align_to)
92
+ self.w1 = nn.Linear(in_features, swiglu_hidden_features, bias=bias, device=device)
93
+ self.w2 = nn.Linear(in_features, swiglu_hidden_features, bias=bias, device=device)
94
+ self.w3 = nn.Linear(swiglu_hidden_features, out_features, bias=bias, device=device)
95
+
96
+ def forward(self, x: Tensor) -> Tensor:
97
+ x1 = self.w1(x)
98
+ x2 = self.w2(x)
99
+ hidden = F.silu(x1) * x2
100
+ return self.w3(hidden)
dinov2/models/__init__.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
6
+ import logging
7
+
8
+ from . import vision_transformer as vits
9
+
10
+
11
+ logger = logging.getLogger("dinov2")
12
+
13
+
14
+ def build_model(args, only_teacher=False, img_size=224):
15
+ args.arch = args.arch.removesuffix("_memeff")
16
+ if "vit" in args.arch:
17
+ vit_kwargs = dict(
18
+ img_size=img_size,
19
+ patch_size=args.patch_size,
20
+ init_values=args.layerscale,
21
+ ffn_layer=args.ffn_layer,
22
+ block_chunks=args.block_chunks,
23
+ qkv_bias=args.qkv_bias,
24
+ proj_bias=args.proj_bias,
25
+ ffn_bias=args.ffn_bias,
26
+ num_register_tokens=args.num_register_tokens,
27
+ interpolate_offset=args.interpolate_offset,
28
+ interpolate_antialias=args.interpolate_antialias,
29
+ in_chans=args.in_chans,
30
+ channel_adaptive=args.channel_adaptive,
31
+ )
32
+ teacher = vits.__dict__[args.arch](**vit_kwargs)
33
+ if only_teacher:
34
+ return teacher, teacher.embed_dim
35
+ student = vits.__dict__[args.arch](
36
+ **vit_kwargs,
37
+ drop_path_rate=args.drop_path_rate,
38
+ drop_path_uniform=args.drop_path_uniform,
39
+ )
40
+ embed_dim = student.embed_dim
41
+ return student, teacher, embed_dim
42
+
43
+
44
+ def build_model_from_cfg(cfg, only_teacher=False):
45
+ return build_model(cfg.student, only_teacher=only_teacher, img_size=cfg.crops.global_crops_size)
dinov2/models/vision_transformer.py ADDED
@@ -0,0 +1,428 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
2
+ #
3
+ # This source code is licensed under the Apache License, Version 2.0
4
+ # found in the LICENSE file in the root directory of this source tree.
5
+
6
+ # References:
7
+ # https://github.com/facebookresearch/dino/blob/main/vision_transformer.py
8
+ # https://github.com/rwightman/pytorch-image-models/tree/master/timm/models/vision_transformer.py
9
+
10
+ from functools import partial
11
+ import math
12
+ import logging
13
+ from typing import Sequence, Tuple, Union, Callable
14
+
15
+ import numpy as np
16
+ import torch
17
+ import torch.nn as nn
18
+ import torch.utils.checkpoint
19
+ from torch.nn.init import trunc_normal_
20
+
21
+ from dinov2.layers import Mlp, PatchEmbed, SwiGLUFFNFused, MemEffAttention, NestedTensorBlock as Block
22
+
23
+
24
+ logger = logging.getLogger("dinov2")
25
+
26
+
27
+ def named_apply(fn: Callable, module: nn.Module, name="", depth_first=True, include_root=False) -> nn.Module:
28
+ if not depth_first and include_root:
29
+ fn(module=module, name=name)
30
+ for child_name, child_module in module.named_children():
31
+ child_name = ".".join((name, child_name)) if name else child_name
32
+ named_apply(fn=fn, module=child_module, name=child_name, depth_first=depth_first, include_root=True)
33
+ if depth_first and include_root:
34
+ fn(module=module, name=name)
35
+ return module
36
+
37
+
38
+ class BlockChunk(nn.ModuleList):
39
+ def forward(self, x):
40
+ for b in self:
41
+ x = b(x)
42
+ return x
43
+
44
+
45
+ class DinoVisionTransformer(nn.Module):
46
+ def __init__(
47
+ self,
48
+ img_size=224,
49
+ patch_size=16,
50
+ in_chans=3,
51
+ embed_dim=768,
52
+ depth=12,
53
+ num_heads=12,
54
+ mlp_ratio=4.0,
55
+ qkv_bias=True,
56
+ ffn_bias=True,
57
+ proj_bias=True,
58
+ drop_path_rate=0.0,
59
+ drop_path_uniform=False,
60
+ init_values=None, # for layerscale: None or 0 => no layerscale
61
+ embed_layer=PatchEmbed,
62
+ act_layer=nn.GELU,
63
+ block_fn=Block,
64
+ ffn_layer="mlp",
65
+ block_chunks=1,
66
+ num_register_tokens=0,
67
+ interpolate_antialias=False,
68
+ interpolate_offset=0.1,
69
+ channel_adaptive=False,
70
+ ):
71
+ """
72
+ Args:
73
+ img_size (int, tuple): input image size
74
+ patch_size (int, tuple): patch size
75
+ in_chans (int): number of input channels
76
+ embed_dim (int): embedding dimension
77
+ depth (int): depth of transformer
78
+ num_heads (int): number of attention heads
79
+ mlp_ratio (int): ratio of mlp hidden dim to embedding dim
80
+ qkv_bias (bool): enable bias for qkv if True
81
+ proj_bias (bool): enable bias for proj in attn if True
82
+ ffn_bias (bool): enable bias for ffn if True
83
+ drop_path_rate (float): stochastic depth rate
84
+ drop_path_uniform (bool): apply uniform drop rate across blocks
85
+ weight_init (str): weight init scheme
86
+ init_values (float): layer-scale init values
87
+ embed_layer (nn.Module): patch embedding layer
88
+ act_layer (nn.Module): MLP activation layer
89
+ block_fn (nn.Module): transformer block class
90
+ ffn_layer (str): "mlp", "swiglu", "swiglufused" or "identity"
91
+ block_chunks: (int) split block sequence into block_chunks units for FSDP wrap
92
+ num_register_tokens: (int) number of extra cls tokens (so-called "registers")
93
+ interpolate_antialias: (str) flag to apply anti-aliasing when interpolating positional embeddings
94
+ interpolate_offset: (float) work-around offset to apply when interpolating positional embeddings
95
+ """
96
+ super().__init__()
97
+ norm_layer = partial(nn.LayerNorm, eps=1e-6)
98
+
99
+ self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
100
+ self.num_tokens = 1
101
+ self.n_blocks = depth
102
+ self.num_heads = num_heads
103
+ self.patch_size = patch_size
104
+ self.num_register_tokens = num_register_tokens
105
+ self.interpolate_antialias = interpolate_antialias
106
+ self.interpolate_offset = interpolate_offset
107
+ self.bag_of_channels = channel_adaptive
108
+
109
+ self.patch_embed = embed_layer(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
110
+ num_patches = self.patch_embed.num_patches
111
+
112
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
113
+ self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim))
114
+ assert num_register_tokens >= 0
115
+ self.register_tokens = (
116
+ nn.Parameter(torch.zeros(1, num_register_tokens, embed_dim)) if num_register_tokens else None
117
+ )
118
+
119
+ if drop_path_uniform is True:
120
+ dpr = [drop_path_rate] * depth
121
+ else:
122
+ dpr = np.linspace(0, drop_path_rate, depth).tolist() # stochastic depth decay rule
123
+
124
+ if ffn_layer == "mlp":
125
+ logger.info("using MLP layer as FFN")
126
+ ffn_layer = Mlp
127
+ elif ffn_layer == "swiglufused" or ffn_layer == "swiglu":
128
+ logger.info("using SwiGLU layer as FFN")
129
+ ffn_layer = SwiGLUFFNFused
130
+ elif ffn_layer == "identity":
131
+ logger.info("using Identity layer as FFN")
132
+
133
+ def f(*args, **kwargs):
134
+ return nn.Identity()
135
+
136
+ ffn_layer = f
137
+ else:
138
+ raise NotImplementedError
139
+
140
+ blocks_list = [
141
+ block_fn(
142
+ dim=embed_dim,
143
+ num_heads=num_heads,
144
+ mlp_ratio=mlp_ratio,
145
+ qkv_bias=qkv_bias,
146
+ proj_bias=proj_bias,
147
+ ffn_bias=ffn_bias,
148
+ drop_path=dpr[i],
149
+ norm_layer=norm_layer,
150
+ act_layer=act_layer,
151
+ ffn_layer=ffn_layer,
152
+ init_values=init_values,
153
+ )
154
+ for i in range(depth)
155
+ ]
156
+ if block_chunks > 0:
157
+ self.chunked_blocks = True
158
+ chunked_blocks = []
159
+ chunksize = depth // block_chunks
160
+ for i in range(0, depth, chunksize):
161
+ # this is to keep the block index consistent if we chunk the block list
162
+ chunked_blocks.append([nn.Identity()] * i + blocks_list[i : i + chunksize])
163
+ self.blocks = nn.ModuleList([BlockChunk(p) for p in chunked_blocks])
164
+ else:
165
+ self.chunked_blocks = False
166
+ self.blocks = nn.ModuleList(blocks_list)
167
+
168
+ self.norm = norm_layer(embed_dim)
169
+ self.head = nn.Identity()
170
+
171
+ self.mask_token = nn.Parameter(torch.zeros(1, embed_dim))
172
+
173
+ self.init_weights()
174
+
175
+ def init_weights(self):
176
+ trunc_normal_(self.pos_embed, std=0.02)
177
+ nn.init.normal_(self.cls_token, std=1e-6)
178
+ if self.register_tokens is not None:
179
+ nn.init.normal_(self.register_tokens, std=1e-6)
180
+ named_apply(init_weights_vit_timm, self)
181
+
182
+ def interpolate_pos_encoding(self, x, w, h):
183
+ previous_dtype = x.dtype
184
+ npatch = x.shape[1] - 1
185
+ N = self.pos_embed.shape[1] - 1
186
+ if npatch == N and w == h:
187
+ return self.pos_embed
188
+ pos_embed = self.pos_embed.float()
189
+ class_pos_embed = pos_embed[:, 0]
190
+ patch_pos_embed = pos_embed[:, 1:]
191
+ dim = x.shape[-1]
192
+ w0 = w // self.patch_size
193
+ h0 = h // self.patch_size
194
+ M = int(math.sqrt(N)) # Recover the number of patches in each dimension
195
+ assert N == M * M
196
+ kwargs = {}
197
+ if self.interpolate_offset:
198
+ # Historical kludge: add a small number to avoid floating point error in the interpolation, see https://github.com/facebookresearch/dino/issues/8
199
+ # Note: still needed for backward-compatibility, the underlying operators are using both output size and scale factors
200
+ sx = float(w0 + self.interpolate_offset) / M
201
+ sy = float(h0 + self.interpolate_offset) / M
202
+ kwargs["scale_factor"] = (sx, sy)
203
+ else:
204
+ # Simply specify an output size instead of a scale factor
205
+ kwargs["size"] = (w0, h0)
206
+ patch_pos_embed = nn.functional.interpolate(
207
+ patch_pos_embed.reshape(1, M, M, dim).permute(0, 3, 1, 2),
208
+ mode="bicubic",
209
+ antialias=self.interpolate_antialias,
210
+ **kwargs,
211
+ )
212
+ assert (w0, h0) == patch_pos_embed.shape[-2:]
213
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
214
+ return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to(previous_dtype)
215
+
216
+ def prepare_tokens_with_masks(self, x, masks=None):
217
+ B, nc, w, h = x.shape
218
+ x = self.patch_embed(x)
219
+ if masks is not None:
220
+ x = torch.where(masks.unsqueeze(-1), self.mask_token.to(x.dtype).unsqueeze(0), x)
221
+
222
+ x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1)
223
+ x = x + self.interpolate_pos_encoding(x, w, h)
224
+
225
+ if self.register_tokens is not None:
226
+ x = torch.cat(
227
+ (
228
+ x[:, :1],
229
+ self.register_tokens.expand(x.shape[0], -1, -1),
230
+ x[:, 1:],
231
+ ),
232
+ dim=1,
233
+ )
234
+
235
+ return x
236
+
237
+ def forward_features_list(self, x_list, masks_list):
238
+ x = [self.prepare_tokens_with_masks(x, masks) for x, masks in zip(x_list, masks_list)]
239
+ for blk in self.blocks:
240
+ x = blk(x)
241
+
242
+ all_x = x
243
+ output = []
244
+ for x, masks in zip(all_x, masks_list):
245
+ x_norm = self.norm(x)
246
+ output.append(
247
+ {
248
+ "x_norm_clstoken": x_norm[:, 0],
249
+ "x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1],
250
+ "x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :],
251
+ "x_prenorm": x,
252
+ "masks": masks,
253
+ }
254
+ )
255
+ return output
256
+
257
+ def forward_features(self, x, masks=None):
258
+ if isinstance(x, list):
259
+ return self.forward_features_list(x, masks)
260
+
261
+ x = self.prepare_tokens_with_masks(x, masks)
262
+
263
+ for blk in self.blocks:
264
+ x = blk(x)
265
+
266
+ x_norm = self.norm(x)
267
+ return {
268
+ "x_norm_clstoken": x_norm[:, 0],
269
+ "x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1],
270
+ "x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :],
271
+ "x_prenorm": x,
272
+ "masks": masks,
273
+ }
274
+
275
+ def _get_intermediate_layers_not_chunked(self, x, n=1):
276
+ x = self.prepare_tokens_with_masks(x)
277
+ # If n is an int, take the n last blocks. If it's a list, take them
278
+ output, total_block_len = [], len(self.blocks)
279
+ blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n
280
+ for i, blk in enumerate(self.blocks):
281
+ x = blk(x)
282
+ if i in blocks_to_take:
283
+ output.append(x)
284
+ assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found"
285
+ return output
286
+
287
+ def _get_intermediate_layers_chunked(self, x, n=1):
288
+ x = self.prepare_tokens_with_masks(x)
289
+ output, i, total_block_len = [], 0, len(self.blocks[-1])
290
+ # If n is an int, take the n last blocks. If it's a list, take them
291
+ blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n
292
+ for block_chunk in self.blocks:
293
+ for blk in block_chunk[i:]: # Passing the nn.Identity()
294
+ x = blk(x)
295
+ if i in blocks_to_take:
296
+ output.append(x)
297
+ i += 1
298
+ assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found"
299
+ return output
300
+
301
+ def get_intermediate_layers(
302
+ self,
303
+ x: torch.Tensor,
304
+ n: Union[int, Sequence] = 1, # Layers or n last layers to take
305
+ reshape: bool = False,
306
+ return_class_token: bool = False,
307
+ norm=True,
308
+ ) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]]]:
309
+
310
+ if self.bag_of_channels:
311
+ B, C, H, W = x.shape
312
+ x = x.reshape(B * C, 1, H, W) # passing channels to batch dimension to get encodings for each channel
313
+
314
+ if self.chunked_blocks:
315
+ outputs = self._get_intermediate_layers_chunked(x, n)
316
+ else:
317
+ outputs = self._get_intermediate_layers_not_chunked(x, n)
318
+ if norm:
319
+ outputs = [self.norm(out) for out in outputs]
320
+ class_tokens = [out[:, 0] for out in outputs]
321
+ outputs = [out[:, 1 + self.num_register_tokens :] for out in outputs]
322
+ if reshape:
323
+ B, _, w, h = x.shape
324
+ outputs = [
325
+ out.reshape(B, w // self.patch_size, h // self.patch_size, -1).permute(0, 3, 1, 2).contiguous()
326
+ for out in outputs
327
+ ]
328
+
329
+ if self.bag_of_channels:
330
+ output = tuple(zip(outputs, class_tokens))
331
+ output = list(
332
+ zip(*output)
333
+ ) # unzip the tuple: (list of patch_tokens per block, list of class tokens per block)
334
+ patch_tokens_per_block = output[0] # [BLOCK1, BLOCK2, ...] where BLOCK1.shape: B*C, N, D
335
+ cls_tokens_per_block = output[1] # [BLOCK1, BLOCK2, ...] where BLOCK1.shape: B*C, D
336
+ patch_tokens_per_block = [
337
+ patch_tokens.reshape(B, C, patch_tokens.shape[-2], patch_tokens.shape[-1])
338
+ for patch_tokens in patch_tokens_per_block
339
+ ] # [BLOCK1, BLOCK2, ...] where BLOCK1.shape: B, C, N, D
340
+ cls_tokens_per_block = [cls_tokens.reshape(B, -1) for cls_tokens in cls_tokens_per_block]
341
+ output = tuple(zip(patch_tokens_per_block, cls_tokens_per_block))
342
+ return output
343
+
344
+ if return_class_token:
345
+ return tuple(zip(outputs, class_tokens))
346
+ return tuple(outputs)
347
+
348
+ def forward(self, *args, is_training=False, **kwargs):
349
+ ret = self.forward_features(*args, **kwargs)
350
+ if is_training:
351
+ return ret
352
+ else:
353
+ return self.head(ret["x_norm_clstoken"])
354
+
355
+
356
+ def init_weights_vit_timm(module: nn.Module, name: str = ""):
357
+ """ViT weight initialization, original timm impl (for reproducibility)"""
358
+ if isinstance(module, nn.Linear):
359
+ trunc_normal_(module.weight, std=0.02)
360
+ if module.bias is not None:
361
+ nn.init.zeros_(module.bias)
362
+
363
+
364
+ def vit_small(patch_size=16, num_register_tokens=0, in_chans=3, channel_adaptive=False, **kwargs):
365
+ model = DinoVisionTransformer(
366
+ patch_size=patch_size,
367
+ embed_dim=384,
368
+ depth=12,
369
+ num_heads=6,
370
+ mlp_ratio=4,
371
+ block_fn=partial(Block, attn_class=MemEffAttention),
372
+ num_register_tokens=num_register_tokens,
373
+ in_chans=in_chans,
374
+ channel_adaptive=channel_adaptive,
375
+ **kwargs,
376
+ )
377
+ return model
378
+
379
+
380
+ def vit_base(patch_size=16, num_register_tokens=0, in_chans=3, channel_adaptive=False, **kwargs):
381
+ model = DinoVisionTransformer(
382
+ patch_size=patch_size,
383
+ embed_dim=768,
384
+ depth=12,
385
+ num_heads=12,
386
+ mlp_ratio=4,
387
+ block_fn=partial(Block, attn_class=MemEffAttention),
388
+ num_register_tokens=num_register_tokens,
389
+ in_chans=in_chans,
390
+ channel_adaptive=channel_adaptive,
391
+ **kwargs,
392
+ )
393
+ return model
394
+
395
+
396
+ def vit_large(patch_size=16, num_register_tokens=0, in_chans=3, channel_adaptive=False, **kwargs):
397
+ model = DinoVisionTransformer(
398
+ patch_size=patch_size,
399
+ embed_dim=1024,
400
+ depth=24,
401
+ num_heads=16,
402
+ mlp_ratio=4,
403
+ block_fn=partial(Block, attn_class=MemEffAttention),
404
+ num_register_tokens=num_register_tokens,
405
+ in_chans=in_chans,
406
+ channel_adaptive=channel_adaptive,
407
+ **kwargs,
408
+ )
409
+ return model
410
+
411
+
412
+ def vit_giant2(patch_size=16, num_register_tokens=0, in_chans=3, channel_adaptive=False, **kwargs):
413
+ """
414
+ Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64
415
+ """
416
+ model = DinoVisionTransformer(
417
+ patch_size=patch_size,
418
+ embed_dim=1536,
419
+ depth=40,
420
+ num_heads=24,
421
+ mlp_ratio=4,
422
+ block_fn=partial(Block, attn_class=MemEffAttention),
423
+ num_register_tokens=num_register_tokens,
424
+ in_chans=in_chans,
425
+ channel_adaptive=channel_adaptive,
426
+ **kwargs,
427
+ )
428
+ return model