Upload model (#3)
Browse files- Upload model (f6a2cd542599543dbbce026175dd0c72521a7ced)
- adaptor_base.py +3 -1
- adaptor_generic.py +9 -2
- config.json +3 -10
- dinov2_arch.py +1016 -0
- enable_spectral_reparam.py +33 -19
- extra_models.py +52 -5
- hf_model.py +4 -1
- model.safetensors +2 -2
- radio_model.py +23 -11
adaptor_base.py
CHANGED
@@ -6,7 +6,7 @@
|
|
6 |
# distribution of this software and related documentation without an express
|
7 |
# license agreement from NVIDIA CORPORATION is strictly prohibited.
|
8 |
from argparse import Namespace
|
9 |
-
from typing import NamedTuple
|
10 |
|
11 |
import torch
|
12 |
from torch import nn
|
@@ -17,6 +17,8 @@ class AdaptorInput(NamedTuple):
|
|
17 |
images: torch.Tensor
|
18 |
summary: torch.Tensor
|
19 |
features: torch.Tensor
|
|
|
|
|
20 |
|
21 |
|
22 |
class RadioOutput(NamedTuple):
|
|
|
6 |
# distribution of this software and related documentation without an express
|
7 |
# license agreement from NVIDIA CORPORATION is strictly prohibited.
|
8 |
from argparse import Namespace
|
9 |
+
from typing import NamedTuple, Optional
|
10 |
|
11 |
import torch
|
12 |
from torch import nn
|
|
|
17 |
images: torch.Tensor
|
18 |
summary: torch.Tensor
|
19 |
features: torch.Tensor
|
20 |
+
feature_fmt: str
|
21 |
+
patch_size: int
|
22 |
|
23 |
|
24 |
class RadioOutput(NamedTuple):
|
adaptor_generic.py
CHANGED
@@ -41,7 +41,14 @@ class GenericAdaptor(AdaptorBase):
|
|
41 |
)
|
42 |
|
43 |
def forward(self, input: AdaptorInput) -> RadioOutput:
|
44 |
-
|
45 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
46 |
|
47 |
return RadioOutput(summary, feat)
|
|
|
41 |
)
|
42 |
|
43 |
def forward(self, input: AdaptorInput) -> RadioOutput:
|
44 |
+
# Convert input'd type to the type of the first parameter of the adaptor.
|
45 |
+
first_param = next(self.parameters())
|
46 |
+
summary = self.head_mlp(input.summary.to(dtype=first_param.dtype)).to(dtype=input.summary.dtype)
|
47 |
+
feat = self.feat_mlp(input.features.to(dtype=first_param.dtype)).to(dtype=input.features.dtype)
|
48 |
+
|
49 |
+
if input.feature_fmt == 'NCHW':
|
50 |
+
feat = (feat.reshape(feat.shape[0], input.images.shape[-2] // input.patch_size, input.images.shape[-1] // input.patch_size, feat.shape[2])
|
51 |
+
.permute(0, 3, 1, 2)
|
52 |
+
)
|
53 |
|
54 |
return RadioOutput(summary, feat)
|
config.json
CHANGED
@@ -41,7 +41,6 @@
|
|
41 |
],
|
42 |
"decay_rate": 0.1,
|
43 |
"depchain": true,
|
44 |
-
"device": "cuda:0",
|
45 |
"dist_bn": "reduce",
|
46 |
"dist_norm_weight": 0.0,
|
47 |
"distributed": true,
|
@@ -221,14 +220,8 @@
|
|
221 |
"AutoConfig": "hf_model.RADIOConfig",
|
222 |
"AutoModel": "hf_model.RADIOModel"
|
223 |
},
|
224 |
-
"feature_normalizer_config":
|
225 |
-
|
226 |
-
},
|
227 |
-
"inter_feature_normalizer_config": {
|
228 |
-
"embed_dim": 1280,
|
229 |
-
"num_intermediates": 32,
|
230 |
-
"rot_per_layer": true
|
231 |
-
},
|
232 |
"max_resolution": 2048,
|
233 |
"patch_size": 16,
|
234 |
"preferred_resolution": [
|
@@ -237,7 +230,7 @@
|
|
237 |
],
|
238 |
"rename_gamma_to_weight": true,
|
239 |
"torch_dtype": "float32",
|
240 |
-
"transformers_version": "4.
|
241 |
"version": "radio_v2.5-h",
|
242 |
"vitdet_window_size": null
|
243 |
}
|
|
|
41 |
],
|
42 |
"decay_rate": 0.1,
|
43 |
"depchain": true,
|
|
|
44 |
"dist_bn": "reduce",
|
45 |
"dist_norm_weight": 0.0,
|
46 |
"distributed": true,
|
|
|
220 |
"AutoConfig": "hf_model.RADIOConfig",
|
221 |
"AutoModel": "hf_model.RADIOModel"
|
222 |
},
|
223 |
+
"feature_normalizer_config": null,
|
224 |
+
"inter_feature_normalizer_config": null,
|
|
|
|
|
|
|
|
|
|
|
|
|
225 |
"max_resolution": 2048,
|
226 |
"patch_size": 16,
|
227 |
"preferred_resolution": [
|
|
|
230 |
],
|
231 |
"rename_gamma_to_weight": true,
|
232 |
"torch_dtype": "float32",
|
233 |
+
"transformers_version": "4.47.0.dev0",
|
234 |
"version": "radio_v2.5-h",
|
235 |
"vitdet_window_size": null
|
236 |
}
|
dinov2_arch.py
ADDED
@@ -0,0 +1,1016 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
# Nvidia
|
11 |
+
# NOTE: We re-define this model architecture primarily so that we don't have to worry about version compatibility breaking,
|
12 |
+
# but also because Huggingface does a string replace of `gamma` to something else when loading the model state,
|
13 |
+
# and this breaks loading of this model.
|
14 |
+
|
15 |
+
from enum import Enum
|
16 |
+
from functools import partial
|
17 |
+
import logging
|
18 |
+
import math
|
19 |
+
import os
|
20 |
+
import sys
|
21 |
+
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
|
22 |
+
import warnings
|
23 |
+
|
24 |
+
import torch
|
25 |
+
from torch import nn
|
26 |
+
from torch.nn import functional as F
|
27 |
+
from torch.nn.init import trunc_normal_
|
28 |
+
|
29 |
+
_torch_has_sdpa = hasattr(F, 'scaled_dot_product_attention')
|
30 |
+
|
31 |
+
|
32 |
+
XFORMERS_ENABLED = os.environ.get("XFORMERS_DISABLED") is None
|
33 |
+
try:
|
34 |
+
if XFORMERS_ENABLED:
|
35 |
+
from xformers.ops import fmha, scaled_index_add, index_select_cat, SwiGLU, memory_efficient_attention, unbind
|
36 |
+
|
37 |
+
XFORMERS_AVAILABLE = True
|
38 |
+
else:
|
39 |
+
raise ImportError
|
40 |
+
except ImportError:
|
41 |
+
XFORMERS_AVAILABLE = False
|
42 |
+
|
43 |
+
|
44 |
+
def make_2tuple(x):
|
45 |
+
if isinstance(x, tuple):
|
46 |
+
assert len(x) == 2
|
47 |
+
return x
|
48 |
+
|
49 |
+
assert isinstance(x, int)
|
50 |
+
return (x, x)
|
51 |
+
|
52 |
+
|
53 |
+
class PatchEmbed(nn.Module):
|
54 |
+
"""
|
55 |
+
2D image to patch embedding: (B,C,H,W) -> (B,N,D)
|
56 |
+
|
57 |
+
Args:
|
58 |
+
img_size: Image size.
|
59 |
+
patch_size: Patch token size.
|
60 |
+
in_chans: Number of input image channels.
|
61 |
+
embed_dim: Number of linear projection output channels.
|
62 |
+
norm_layer: Normalization layer.
|
63 |
+
"""
|
64 |
+
|
65 |
+
def __init__(
|
66 |
+
self,
|
67 |
+
img_size: Union[int, Tuple[int, int]] = 224,
|
68 |
+
patch_size: Union[int, Tuple[int, int]] = 16,
|
69 |
+
in_chans: int = 3,
|
70 |
+
embed_dim: int = 768,
|
71 |
+
norm_layer: Optional[Callable] = None,
|
72 |
+
flatten_embedding: bool = True,
|
73 |
+
) -> None:
|
74 |
+
super().__init__()
|
75 |
+
|
76 |
+
image_HW = make_2tuple(img_size)
|
77 |
+
patch_HW = make_2tuple(patch_size)
|
78 |
+
patch_grid_size = (
|
79 |
+
image_HW[0] // patch_HW[0],
|
80 |
+
image_HW[1] // patch_HW[1],
|
81 |
+
)
|
82 |
+
|
83 |
+
self.img_size = image_HW
|
84 |
+
self.patch_size = patch_HW
|
85 |
+
self.patches_resolution = patch_grid_size
|
86 |
+
self.num_patches = patch_grid_size[0] * patch_grid_size[1]
|
87 |
+
|
88 |
+
self.in_chans = in_chans
|
89 |
+
self.embed_dim = embed_dim
|
90 |
+
|
91 |
+
self.flatten_embedding = flatten_embedding
|
92 |
+
|
93 |
+
self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_HW, stride=patch_HW)
|
94 |
+
self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
|
95 |
+
|
96 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
97 |
+
_, _, H, W = x.shape
|
98 |
+
patch_H, patch_W = self.patch_size
|
99 |
+
|
100 |
+
assert H % patch_H == 0, f"Input image height {H} is not a multiple of patch height {patch_H}"
|
101 |
+
assert W % patch_W == 0, f"Input image width {W} is not a multiple of patch width: {patch_W}"
|
102 |
+
|
103 |
+
x = self.proj(x) # B C H W
|
104 |
+
H, W = x.size(2), x.size(3)
|
105 |
+
x = x.flatten(2).transpose(1, 2) # B HW C
|
106 |
+
x = self.norm(x)
|
107 |
+
if not self.flatten_embedding:
|
108 |
+
x = x.reshape(-1, H, W, self.embed_dim) # B H W C
|
109 |
+
return x
|
110 |
+
|
111 |
+
def flops(self) -> float:
|
112 |
+
Ho, Wo = self.patches_resolution
|
113 |
+
flops = Ho * Wo * self.embed_dim * self.in_chans * (self.patch_size[0] * self.patch_size[1])
|
114 |
+
if self.norm is not None:
|
115 |
+
flops += Ho * Wo * self.embed_dim
|
116 |
+
return flops
|
117 |
+
|
118 |
+
|
119 |
+
class Attention(nn.Module):
|
120 |
+
def __init__(
|
121 |
+
self,
|
122 |
+
dim: int,
|
123 |
+
num_heads: int = 8,
|
124 |
+
qkv_bias: bool = False,
|
125 |
+
proj_bias: bool = True,
|
126 |
+
attn_drop: float = 0.0,
|
127 |
+
proj_drop: float = 0.0,
|
128 |
+
) -> None:
|
129 |
+
super().__init__()
|
130 |
+
self.num_heads = num_heads
|
131 |
+
head_dim = dim // num_heads
|
132 |
+
self.scale = head_dim**-0.5
|
133 |
+
|
134 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
|
135 |
+
self.attn_drop = nn.Dropout(attn_drop)
|
136 |
+
self.proj = nn.Linear(dim, dim, bias=proj_bias)
|
137 |
+
self.proj_drop = nn.Dropout(proj_drop)
|
138 |
+
|
139 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
140 |
+
B, N, C = x.shape
|
141 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
142 |
+
|
143 |
+
q, k, v = qkv[0], qkv[1], qkv[2]
|
144 |
+
if _torch_has_sdpa:
|
145 |
+
x = F.scaled_dot_product_attention(
|
146 |
+
q, k, v,
|
147 |
+
is_causal=False,
|
148 |
+
dropout_p=self.attn_drop.p if self.training else 0.,
|
149 |
+
scale=self.scale,
|
150 |
+
)
|
151 |
+
else:
|
152 |
+
q = q * self.scale
|
153 |
+
attn = q @ k.transpose(-2, -1)
|
154 |
+
|
155 |
+
attn = attn.softmax(dim=-1)
|
156 |
+
attn = self.attn_drop(attn)
|
157 |
+
x = attn @ v
|
158 |
+
|
159 |
+
x = x.transpose(1, 2).reshape(B, N, C)
|
160 |
+
x = self.proj(x)
|
161 |
+
x = self.proj_drop(x)
|
162 |
+
return x
|
163 |
+
|
164 |
+
|
165 |
+
class MemEffAttention(Attention):
|
166 |
+
def forward(self, x: torch.Tensor, attn_bias=None) -> torch.Tensor:
|
167 |
+
if not XFORMERS_AVAILABLE:
|
168 |
+
if attn_bias is not None:
|
169 |
+
raise AssertionError("xFormers is required for using nested tensors")
|
170 |
+
return super().forward(x)
|
171 |
+
|
172 |
+
B, N, C = x.shape
|
173 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads)
|
174 |
+
|
175 |
+
q, k, v = unbind(qkv, 2)
|
176 |
+
|
177 |
+
x = memory_efficient_attention(q, k, v, attn_bias=attn_bias)
|
178 |
+
x = x.reshape([B, N, C])
|
179 |
+
|
180 |
+
x = self.proj(x)
|
181 |
+
x = self.proj_drop(x)
|
182 |
+
return x
|
183 |
+
|
184 |
+
|
185 |
+
class Mlp(nn.Module):
|
186 |
+
def __init__(
|
187 |
+
self,
|
188 |
+
in_features: int,
|
189 |
+
hidden_features: Optional[int] = None,
|
190 |
+
out_features: Optional[int] = None,
|
191 |
+
act_layer: Callable[..., nn.Module] = nn.GELU,
|
192 |
+
drop: float = 0.0,
|
193 |
+
bias: bool = True,
|
194 |
+
) -> None:
|
195 |
+
super().__init__()
|
196 |
+
out_features = out_features or in_features
|
197 |
+
hidden_features = hidden_features or in_features
|
198 |
+
self.fc1 = nn.Linear(in_features, hidden_features, bias=bias)
|
199 |
+
self.act = act_layer()
|
200 |
+
self.fc2 = nn.Linear(hidden_features, out_features, bias=bias)
|
201 |
+
self.drop = nn.Dropout(drop)
|
202 |
+
|
203 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
204 |
+
x = self.fc1(x)
|
205 |
+
x = self.act(x)
|
206 |
+
x = self.drop(x)
|
207 |
+
x = self.fc2(x)
|
208 |
+
x = self.drop(x)
|
209 |
+
return x
|
210 |
+
|
211 |
+
|
212 |
+
class SwiGLUFFN(nn.Module):
|
213 |
+
def __init__(
|
214 |
+
self,
|
215 |
+
in_features: int,
|
216 |
+
hidden_features: Optional[int] = None,
|
217 |
+
out_features: Optional[int] = None,
|
218 |
+
act_layer: Callable[..., nn.Module] = None,
|
219 |
+
drop: float = 0.0,
|
220 |
+
bias: bool = True,
|
221 |
+
) -> None:
|
222 |
+
super().__init__()
|
223 |
+
out_features = out_features or in_features
|
224 |
+
hidden_features = hidden_features or in_features
|
225 |
+
self.w12 = nn.Linear(in_features, 2 * hidden_features, bias=bias)
|
226 |
+
self.w3 = nn.Linear(hidden_features, out_features, bias=bias)
|
227 |
+
|
228 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
229 |
+
x12 = self.w12(x)
|
230 |
+
x1, x2 = x12.chunk(2, dim=-1)
|
231 |
+
hidden = F.silu(x1) * x2
|
232 |
+
return self.w3(hidden)
|
233 |
+
|
234 |
+
|
235 |
+
if not XFORMERS_AVAILABLE:
|
236 |
+
SwiGLU = SwiGLUFFN
|
237 |
+
|
238 |
+
|
239 |
+
class SwiGLUFFNFused(SwiGLU):
|
240 |
+
def __init__(
|
241 |
+
self,
|
242 |
+
in_features: int,
|
243 |
+
hidden_features: Optional[int] = None,
|
244 |
+
out_features: Optional[int] = None,
|
245 |
+
act_layer: Callable[..., nn.Module] = None,
|
246 |
+
drop: float = 0.0,
|
247 |
+
bias: bool = True,
|
248 |
+
) -> None:
|
249 |
+
out_features = out_features or in_features
|
250 |
+
hidden_features = hidden_features or in_features
|
251 |
+
hidden_features = (int(hidden_features * 2 / 3) + 7) // 8 * 8
|
252 |
+
super().__init__(
|
253 |
+
in_features=in_features,
|
254 |
+
hidden_features=hidden_features,
|
255 |
+
out_features=out_features,
|
256 |
+
bias=bias,
|
257 |
+
)
|
258 |
+
|
259 |
+
|
260 |
+
def drop_path(x, drop_prob: float = 0.0, training: bool = False):
|
261 |
+
if drop_prob == 0.0 or not training:
|
262 |
+
return x
|
263 |
+
keep_prob = 1 - drop_prob
|
264 |
+
shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
|
265 |
+
random_tensor = x.new_empty(shape).bernoulli_(keep_prob)
|
266 |
+
if keep_prob > 0.0:
|
267 |
+
random_tensor.div_(keep_prob)
|
268 |
+
output = x * random_tensor
|
269 |
+
return output
|
270 |
+
|
271 |
+
|
272 |
+
class DropPath(nn.Module):
|
273 |
+
"""Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
|
274 |
+
|
275 |
+
def __init__(self, drop_prob=None):
|
276 |
+
super(DropPath, self).__init__()
|
277 |
+
self.drop_prob = drop_prob
|
278 |
+
|
279 |
+
def forward(self, x):
|
280 |
+
return drop_path(x, self.drop_prob, self.training)
|
281 |
+
|
282 |
+
|
283 |
+
class LayerScale(nn.Module):
|
284 |
+
def __init__(
|
285 |
+
self,
|
286 |
+
dim: int,
|
287 |
+
init_values: Union[float, torch.Tensor] = 1e-5,
|
288 |
+
inplace: bool = False,
|
289 |
+
) -> None:
|
290 |
+
super().__init__()
|
291 |
+
self.inplace = inplace
|
292 |
+
self.grandma = nn.Parameter(init_values * torch.ones(dim))
|
293 |
+
|
294 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
295 |
+
return x.mul_(self.grandma) if self.inplace else x * self.grandma
|
296 |
+
|
297 |
+
def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs):
|
298 |
+
# Huggingface is absurd and it will rename strings that contain `gamma`, which means that the normal DINO implementation
|
299 |
+
# of LayerScale won't work with HFHub. So we rename the variable to 'grandma', and support loading checkpoints in either
|
300 |
+
# format
|
301 |
+
key_a = f'{prefix}gamma'
|
302 |
+
key_b = f'{prefix}grandma'
|
303 |
+
if key_a in state_dict:
|
304 |
+
gamma = state_dict[key_a]
|
305 |
+
elif key_b in state_dict:
|
306 |
+
gamma = state_dict[key_b]
|
307 |
+
else:
|
308 |
+
if strict:
|
309 |
+
raise KeyError(f"Couldn't find the key {key_a} nor {key_b} in the state dict!")
|
310 |
+
else:
|
311 |
+
missing_keys.append(key_a)
|
312 |
+
missing_keys.append(key_b)
|
313 |
+
unexpected_keys.extend(state_dict.keys())
|
314 |
+
gamma = None
|
315 |
+
|
316 |
+
if gamma is not None:
|
317 |
+
self.grandma.data.copy_(gamma)
|
318 |
+
|
319 |
+
# return super()._load_from_state_dict(state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs)
|
320 |
+
|
321 |
+
|
322 |
+
class Block(nn.Module):
|
323 |
+
def __init__(
|
324 |
+
self,
|
325 |
+
dim: int,
|
326 |
+
num_heads: int,
|
327 |
+
mlp_ratio: float = 4.0,
|
328 |
+
qkv_bias: bool = False,
|
329 |
+
proj_bias: bool = True,
|
330 |
+
ffn_bias: bool = True,
|
331 |
+
drop: float = 0.0,
|
332 |
+
attn_drop: float = 0.0,
|
333 |
+
init_values=None,
|
334 |
+
drop_path: float = 0.0,
|
335 |
+
act_layer: Callable[..., nn.Module] = nn.GELU,
|
336 |
+
norm_layer: Callable[..., nn.Module] = nn.LayerNorm,
|
337 |
+
attn_class: Callable[..., nn.Module] = Attention,
|
338 |
+
ffn_layer: Callable[..., nn.Module] = Mlp,
|
339 |
+
) -> None:
|
340 |
+
super().__init__()
|
341 |
+
# print(f"biases: qkv: {qkv_bias}, proj: {proj_bias}, ffn: {ffn_bias}")
|
342 |
+
self.norm1 = norm_layer(dim)
|
343 |
+
self.attn = attn_class(
|
344 |
+
dim,
|
345 |
+
num_heads=num_heads,
|
346 |
+
qkv_bias=qkv_bias,
|
347 |
+
proj_bias=proj_bias,
|
348 |
+
attn_drop=attn_drop,
|
349 |
+
proj_drop=drop,
|
350 |
+
)
|
351 |
+
self.ls1 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
|
352 |
+
self.drop_path1 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
353 |
+
|
354 |
+
self.norm2 = norm_layer(dim)
|
355 |
+
mlp_hidden_dim = int(dim * mlp_ratio)
|
356 |
+
self.mlp = ffn_layer(
|
357 |
+
in_features=dim,
|
358 |
+
hidden_features=mlp_hidden_dim,
|
359 |
+
act_layer=act_layer,
|
360 |
+
drop=drop,
|
361 |
+
bias=ffn_bias,
|
362 |
+
)
|
363 |
+
self.ls2 = LayerScale(dim, init_values=init_values) if init_values else nn.Identity()
|
364 |
+
self.drop_path2 = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
|
365 |
+
|
366 |
+
self.sample_drop_ratio = drop_path
|
367 |
+
|
368 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
369 |
+
def attn_residual_func(x: torch.Tensor) -> torch.Tensor:
|
370 |
+
return self.ls1(self.attn(self.norm1(x)))
|
371 |
+
|
372 |
+
def ffn_residual_func(x: torch.Tensor) -> torch.Tensor:
|
373 |
+
return self.ls2(self.mlp(self.norm2(x)))
|
374 |
+
|
375 |
+
if self.training and self.sample_drop_ratio > 0.1:
|
376 |
+
# the overhead is compensated only for a drop path rate larger than 0.1
|
377 |
+
x = drop_add_residual_stochastic_depth(
|
378 |
+
x,
|
379 |
+
residual_func=attn_residual_func,
|
380 |
+
sample_drop_ratio=self.sample_drop_ratio,
|
381 |
+
)
|
382 |
+
x = drop_add_residual_stochastic_depth(
|
383 |
+
x,
|
384 |
+
residual_func=ffn_residual_func,
|
385 |
+
sample_drop_ratio=self.sample_drop_ratio,
|
386 |
+
)
|
387 |
+
elif self.training and self.sample_drop_ratio > 0.0:
|
388 |
+
x = x + self.drop_path1(attn_residual_func(x))
|
389 |
+
x = x + self.drop_path1(ffn_residual_func(x)) # FIXME: drop_path2
|
390 |
+
else:
|
391 |
+
x = x + attn_residual_func(x)
|
392 |
+
x = x + ffn_residual_func(x)
|
393 |
+
return x
|
394 |
+
|
395 |
+
|
396 |
+
class NestedTensorBlock(Block):
|
397 |
+
def forward_nested(self, x_list: List[torch.Tensor]) -> List[torch.Tensor]:
|
398 |
+
"""
|
399 |
+
x_list contains a list of tensors to nest together and run
|
400 |
+
"""
|
401 |
+
assert isinstance(self.attn, MemEffAttention)
|
402 |
+
|
403 |
+
if self.training and self.sample_drop_ratio > 0.0:
|
404 |
+
|
405 |
+
def attn_residual_func(x: torch.Tensor, attn_bias=None) -> torch.Tensor:
|
406 |
+
return self.attn(self.norm1(x), attn_bias=attn_bias)
|
407 |
+
|
408 |
+
def ffn_residual_func(x: torch.Tensor, attn_bias=None) -> torch.Tensor:
|
409 |
+
return self.mlp(self.norm2(x))
|
410 |
+
|
411 |
+
x_list = drop_add_residual_stochastic_depth_list(
|
412 |
+
x_list,
|
413 |
+
residual_func=attn_residual_func,
|
414 |
+
sample_drop_ratio=self.sample_drop_ratio,
|
415 |
+
scaling_vector=self.ls1.grandma if isinstance(self.ls1, LayerScale) else None,
|
416 |
+
)
|
417 |
+
x_list = drop_add_residual_stochastic_depth_list(
|
418 |
+
x_list,
|
419 |
+
residual_func=ffn_residual_func,
|
420 |
+
sample_drop_ratio=self.sample_drop_ratio,
|
421 |
+
scaling_vector=self.ls2.grandma if isinstance(self.ls1, LayerScale) else None,
|
422 |
+
)
|
423 |
+
return x_list
|
424 |
+
else:
|
425 |
+
|
426 |
+
def attn_residual_func(x: torch.Tensor, attn_bias=None) -> torch.Tensor:
|
427 |
+
return self.ls1(self.attn(self.norm1(x), attn_bias=attn_bias))
|
428 |
+
|
429 |
+
def ffn_residual_func(x: torch.Tensor, attn_bias=None) -> torch.Tensor:
|
430 |
+
return self.ls2(self.mlp(self.norm2(x)))
|
431 |
+
|
432 |
+
attn_bias, x = get_attn_bias_and_cat(x_list)
|
433 |
+
x = x + attn_residual_func(x, attn_bias=attn_bias)
|
434 |
+
x = x + ffn_residual_func(x)
|
435 |
+
return attn_bias.split(x)
|
436 |
+
|
437 |
+
def forward(self, x_or_x_list):
|
438 |
+
if isinstance(x_or_x_list, torch.Tensor):
|
439 |
+
return super().forward(x_or_x_list)
|
440 |
+
elif isinstance(x_or_x_list, list):
|
441 |
+
if not XFORMERS_AVAILABLE:
|
442 |
+
raise AssertionError("xFormers is required for using nested tensors")
|
443 |
+
return self.forward_nested(x_or_x_list)
|
444 |
+
else:
|
445 |
+
raise AssertionError
|
446 |
+
|
447 |
+
|
448 |
+
def drop_add_residual_stochastic_depth(
|
449 |
+
x: torch.Tensor,
|
450 |
+
residual_func: Callable[[torch.Tensor], torch.Tensor],
|
451 |
+
sample_drop_ratio: float = 0.0,
|
452 |
+
) -> torch.Tensor:
|
453 |
+
# 1) extract subset using permutation
|
454 |
+
b, n, d = x.shape
|
455 |
+
sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1)
|
456 |
+
brange = (torch.randperm(b, device=x.device))[:sample_subset_size]
|
457 |
+
x_subset = x[brange]
|
458 |
+
|
459 |
+
# 2) apply residual_func to get residual
|
460 |
+
residual = residual_func(x_subset)
|
461 |
+
|
462 |
+
x_flat = x.flatten(1)
|
463 |
+
residual = residual.flatten(1)
|
464 |
+
|
465 |
+
residual_scale_factor = b / sample_subset_size
|
466 |
+
|
467 |
+
# 3) add the residual
|
468 |
+
x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor)
|
469 |
+
return x_plus_residual.view_as(x)
|
470 |
+
|
471 |
+
|
472 |
+
def get_branges_scales(x, sample_drop_ratio=0.0):
|
473 |
+
b, n, d = x.shape
|
474 |
+
sample_subset_size = max(int(b * (1 - sample_drop_ratio)), 1)
|
475 |
+
brange = (torch.randperm(b, device=x.device))[:sample_subset_size]
|
476 |
+
residual_scale_factor = b / sample_subset_size
|
477 |
+
return brange, residual_scale_factor
|
478 |
+
|
479 |
+
|
480 |
+
def add_residual(x, brange, residual, residual_scale_factor, scaling_vector=None):
|
481 |
+
if scaling_vector is None:
|
482 |
+
x_flat = x.flatten(1)
|
483 |
+
residual = residual.flatten(1)
|
484 |
+
x_plus_residual = torch.index_add(x_flat, 0, brange, residual.to(dtype=x.dtype), alpha=residual_scale_factor)
|
485 |
+
else:
|
486 |
+
x_plus_residual = scaled_index_add(
|
487 |
+
x, brange, residual.to(dtype=x.dtype), scaling=scaling_vector, alpha=residual_scale_factor
|
488 |
+
)
|
489 |
+
return x_plus_residual
|
490 |
+
|
491 |
+
|
492 |
+
attn_bias_cache: Dict[Tuple, Any] = {}
|
493 |
+
|
494 |
+
|
495 |
+
def get_attn_bias_and_cat(x_list, branges=None):
|
496 |
+
"""
|
497 |
+
this will perform the index select, cat the tensors, and provide the attn_bias from cache
|
498 |
+
"""
|
499 |
+
batch_sizes = [b.shape[0] for b in branges] if branges is not None else [x.shape[0] for x in x_list]
|
500 |
+
all_shapes = tuple((b, x.shape[1]) for b, x in zip(batch_sizes, x_list))
|
501 |
+
if all_shapes not in attn_bias_cache.keys():
|
502 |
+
seqlens = []
|
503 |
+
for b, x in zip(batch_sizes, x_list):
|
504 |
+
for _ in range(b):
|
505 |
+
seqlens.append(x.shape[1])
|
506 |
+
attn_bias = fmha.BlockDiagonalMask.from_seqlens(seqlens)
|
507 |
+
attn_bias._batch_sizes = batch_sizes
|
508 |
+
attn_bias_cache[all_shapes] = attn_bias
|
509 |
+
|
510 |
+
if branges is not None:
|
511 |
+
cat_tensors = index_select_cat([x.flatten(1) for x in x_list], branges).view(1, -1, x_list[0].shape[-1])
|
512 |
+
else:
|
513 |
+
tensors_bs1 = tuple(x.reshape([1, -1, *x.shape[2:]]) for x in x_list)
|
514 |
+
cat_tensors = torch.cat(tensors_bs1, dim=1)
|
515 |
+
|
516 |
+
return attn_bias_cache[all_shapes], cat_tensors
|
517 |
+
|
518 |
+
|
519 |
+
def drop_add_residual_stochastic_depth_list(
|
520 |
+
x_list: List[torch.Tensor],
|
521 |
+
residual_func: Callable[[torch.Tensor, Any], torch.Tensor],
|
522 |
+
sample_drop_ratio: float = 0.0,
|
523 |
+
scaling_vector=None,
|
524 |
+
) -> torch.Tensor:
|
525 |
+
# 1) generate random set of indices for dropping samples in the batch
|
526 |
+
branges_scales = [get_branges_scales(x, sample_drop_ratio=sample_drop_ratio) for x in x_list]
|
527 |
+
branges = [s[0] for s in branges_scales]
|
528 |
+
residual_scale_factors = [s[1] for s in branges_scales]
|
529 |
+
|
530 |
+
# 2) get attention bias and index+concat the tensors
|
531 |
+
attn_bias, x_cat = get_attn_bias_and_cat(x_list, branges)
|
532 |
+
|
533 |
+
# 3) apply residual_func to get residual, and split the result
|
534 |
+
residual_list = attn_bias.split(residual_func(x_cat, attn_bias=attn_bias)) # type: ignore
|
535 |
+
|
536 |
+
outputs = []
|
537 |
+
for x, brange, residual, residual_scale_factor in zip(x_list, branges, residual_list, residual_scale_factors):
|
538 |
+
outputs.append(add_residual(x, brange, residual, residual_scale_factor, scaling_vector).view_as(x))
|
539 |
+
return outputs
|
540 |
+
|
541 |
+
|
542 |
+
def named_apply(fn: Callable, module: nn.Module, name="", depth_first=True, include_root=False) -> nn.Module:
|
543 |
+
if not depth_first and include_root:
|
544 |
+
fn(module=module, name=name)
|
545 |
+
for child_name, child_module in module.named_children():
|
546 |
+
child_name = ".".join((name, child_name)) if name else child_name
|
547 |
+
named_apply(fn=fn, module=child_module, name=child_name, depth_first=depth_first, include_root=True)
|
548 |
+
if depth_first and include_root:
|
549 |
+
fn(module=module, name=name)
|
550 |
+
return module
|
551 |
+
|
552 |
+
|
553 |
+
class BlockChunk(nn.ModuleList):
|
554 |
+
def forward(self, x):
|
555 |
+
for b in self:
|
556 |
+
x = b(x)
|
557 |
+
return x
|
558 |
+
|
559 |
+
|
560 |
+
class DinoVisionTransformer(nn.Module):
|
561 |
+
def __init__(
|
562 |
+
self,
|
563 |
+
img_size=224,
|
564 |
+
patch_size=16,
|
565 |
+
in_chans=3,
|
566 |
+
embed_dim=768,
|
567 |
+
depth=12,
|
568 |
+
num_heads=12,
|
569 |
+
mlp_ratio=4.0,
|
570 |
+
qkv_bias=True,
|
571 |
+
ffn_bias=True,
|
572 |
+
proj_bias=True,
|
573 |
+
drop_path_rate=0.0,
|
574 |
+
drop_path_uniform=False,
|
575 |
+
init_values=None, # for layerscale: None or 0 => no layerscale
|
576 |
+
embed_layer=PatchEmbed,
|
577 |
+
act_layer=nn.GELU,
|
578 |
+
block_fn=Block,
|
579 |
+
ffn_layer="mlp",
|
580 |
+
block_chunks=1,
|
581 |
+
num_register_tokens=0,
|
582 |
+
interpolate_antialias=False,
|
583 |
+
interpolate_offset=0.1,
|
584 |
+
):
|
585 |
+
"""
|
586 |
+
Args:
|
587 |
+
img_size (int, tuple): input image size
|
588 |
+
patch_size (int, tuple): patch size
|
589 |
+
in_chans (int): number of input channels
|
590 |
+
embed_dim (int): embedding dimension
|
591 |
+
depth (int): depth of transformer
|
592 |
+
num_heads (int): number of attention heads
|
593 |
+
mlp_ratio (int): ratio of mlp hidden dim to embedding dim
|
594 |
+
qkv_bias (bool): enable bias for qkv if True
|
595 |
+
proj_bias (bool): enable bias for proj in attn if True
|
596 |
+
ffn_bias (bool): enable bias for ffn if True
|
597 |
+
drop_path_rate (float): stochastic depth rate
|
598 |
+
drop_path_uniform (bool): apply uniform drop rate across blocks
|
599 |
+
weight_init (str): weight init scheme
|
600 |
+
init_values (float): layer-scale init values
|
601 |
+
embed_layer (nn.Module): patch embedding layer
|
602 |
+
act_layer (nn.Module): MLP activation layer
|
603 |
+
block_fn (nn.Module): transformer block class
|
604 |
+
ffn_layer (str): "mlp", "swiglu", "swiglufused" or "identity"
|
605 |
+
block_chunks: (int) split block sequence into block_chunks units for FSDP wrap
|
606 |
+
num_register_tokens: (int) number of extra cls tokens (so-called "registers")
|
607 |
+
interpolate_antialias: (str) flag to apply anti-aliasing when interpolating positional embeddings
|
608 |
+
interpolate_offset: (float) work-around offset to apply when interpolating positional embeddings
|
609 |
+
"""
|
610 |
+
super().__init__()
|
611 |
+
norm_layer = partial(nn.LayerNorm, eps=1e-6)
|
612 |
+
|
613 |
+
self.num_features = self.embed_dim = embed_dim # num_features for consistency with other models
|
614 |
+
self.num_tokens = 1
|
615 |
+
self.n_blocks = depth
|
616 |
+
self.num_heads = num_heads
|
617 |
+
self.patch_size = patch_size
|
618 |
+
self.num_register_tokens = num_register_tokens
|
619 |
+
self.interpolate_antialias = interpolate_antialias
|
620 |
+
self.interpolate_offset = interpolate_offset
|
621 |
+
|
622 |
+
self.patch_embed = embed_layer(img_size=img_size, patch_size=patch_size, in_chans=in_chans, embed_dim=embed_dim)
|
623 |
+
num_patches = self.patch_embed.num_patches
|
624 |
+
|
625 |
+
self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim))
|
626 |
+
self.pos_embed = nn.Parameter(torch.zeros(1, num_patches + self.num_tokens, embed_dim))
|
627 |
+
assert num_register_tokens >= 0
|
628 |
+
self.register_tokens = (
|
629 |
+
nn.Parameter(torch.zeros(1, num_register_tokens, embed_dim)) if num_register_tokens else None
|
630 |
+
)
|
631 |
+
|
632 |
+
if drop_path_uniform is True:
|
633 |
+
dpr = [drop_path_rate] * depth
|
634 |
+
else:
|
635 |
+
dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
|
636 |
+
|
637 |
+
if ffn_layer == "mlp":
|
638 |
+
ffn_layer = Mlp
|
639 |
+
elif ffn_layer == "swiglufused" or ffn_layer == "swiglu":
|
640 |
+
ffn_layer = SwiGLUFFNFused
|
641 |
+
elif ffn_layer == "identity":
|
642 |
+
def f(*args, **kwargs):
|
643 |
+
return nn.Identity()
|
644 |
+
|
645 |
+
ffn_layer = f
|
646 |
+
else:
|
647 |
+
raise NotImplementedError
|
648 |
+
|
649 |
+
blocks_list = [
|
650 |
+
block_fn(
|
651 |
+
dim=embed_dim,
|
652 |
+
num_heads=num_heads,
|
653 |
+
mlp_ratio=mlp_ratio,
|
654 |
+
qkv_bias=qkv_bias,
|
655 |
+
proj_bias=proj_bias,
|
656 |
+
ffn_bias=ffn_bias,
|
657 |
+
drop_path=dpr[i],
|
658 |
+
norm_layer=norm_layer,
|
659 |
+
act_layer=act_layer,
|
660 |
+
ffn_layer=ffn_layer,
|
661 |
+
init_values=init_values,
|
662 |
+
)
|
663 |
+
for i in range(depth)
|
664 |
+
]
|
665 |
+
if block_chunks > 0:
|
666 |
+
self.chunked_blocks = True
|
667 |
+
chunked_blocks = []
|
668 |
+
chunksize = depth // block_chunks
|
669 |
+
for i in range(0, depth, chunksize):
|
670 |
+
# this is to keep the block index consistent if we chunk the block list
|
671 |
+
chunked_blocks.append([nn.Identity()] * i + blocks_list[i : i + chunksize])
|
672 |
+
self.blocks = nn.ModuleList([BlockChunk(p) for p in chunked_blocks])
|
673 |
+
else:
|
674 |
+
self.chunked_blocks = False
|
675 |
+
self.blocks = nn.ModuleList(blocks_list)
|
676 |
+
|
677 |
+
self.norm = norm_layer(embed_dim)
|
678 |
+
self.head = nn.Identity()
|
679 |
+
|
680 |
+
self.mask_token = nn.Parameter(torch.zeros(1, embed_dim))
|
681 |
+
|
682 |
+
def interpolate_pos_encoding(self, x, w, h):
|
683 |
+
previous_dtype = x.dtype
|
684 |
+
npatch = x.shape[1] - 1
|
685 |
+
N = self.pos_embed.shape[1] - 1
|
686 |
+
if npatch == N and w == h:
|
687 |
+
return self.pos_embed
|
688 |
+
pos_embed = self.pos_embed.float()
|
689 |
+
class_pos_embed = pos_embed[:, 0]
|
690 |
+
patch_pos_embed = pos_embed[:, 1:]
|
691 |
+
dim = x.shape[-1]
|
692 |
+
w0 = w // self.patch_size
|
693 |
+
h0 = h // self.patch_size
|
694 |
+
M = int(math.sqrt(N)) # Recover the number of patches in each dimension
|
695 |
+
assert N == M * M
|
696 |
+
kwargs = {}
|
697 |
+
if self.interpolate_offset:
|
698 |
+
# Historical kludge: add a small number to avoid floating point error in the interpolation, see https://github.com/facebookresearch/dino/issues/8
|
699 |
+
# Note: still needed for backward-compatibility, the underlying operators are using both output size and scale factors
|
700 |
+
sx = float(w0 + self.interpolate_offset) / M
|
701 |
+
sy = float(h0 + self.interpolate_offset) / M
|
702 |
+
kwargs["scale_factor"] = (sx, sy)
|
703 |
+
else:
|
704 |
+
# Simply specify an output size instead of a scale factor
|
705 |
+
kwargs["size"] = (w0, h0)
|
706 |
+
patch_pos_embed = nn.functional.interpolate(
|
707 |
+
patch_pos_embed.reshape(1, M, M, dim).permute(0, 3, 1, 2),
|
708 |
+
mode="bicubic",
|
709 |
+
antialias=self.interpolate_antialias,
|
710 |
+
**kwargs,
|
711 |
+
)
|
712 |
+
assert (w0, h0) == patch_pos_embed.shape[-2:]
|
713 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
714 |
+
return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1).to(previous_dtype)
|
715 |
+
|
716 |
+
def prepare_tokens_with_masks(self, x, masks=None):
|
717 |
+
B, nc, w, h = x.shape
|
718 |
+
x = self.patch_embed(x)
|
719 |
+
if masks is not None:
|
720 |
+
x = torch.where(masks.unsqueeze(-1), self.mask_token.to(x.dtype).unsqueeze(0), x)
|
721 |
+
|
722 |
+
x = torch.cat((self.cls_token.expand(x.shape[0], -1, -1), x), dim=1)
|
723 |
+
x = x + self.interpolate_pos_encoding(x, w, h)
|
724 |
+
|
725 |
+
if self.register_tokens is not None:
|
726 |
+
x = torch.cat(
|
727 |
+
(
|
728 |
+
x[:, :1],
|
729 |
+
self.register_tokens.expand(x.shape[0], -1, -1),
|
730 |
+
x[:, 1:],
|
731 |
+
),
|
732 |
+
dim=1,
|
733 |
+
)
|
734 |
+
|
735 |
+
return x
|
736 |
+
|
737 |
+
def forward_features_list(self, x_list, masks_list):
|
738 |
+
x = [self.prepare_tokens_with_masks(x, masks) for x, masks in zip(x_list, masks_list)]
|
739 |
+
for blk in self.blocks:
|
740 |
+
x = blk(x)
|
741 |
+
|
742 |
+
all_x = x
|
743 |
+
output = []
|
744 |
+
for x, masks in zip(all_x, masks_list):
|
745 |
+
x_norm = self.norm(x)
|
746 |
+
output.append(
|
747 |
+
{
|
748 |
+
"x_norm_clstoken": x_norm[:, 0],
|
749 |
+
"x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1],
|
750 |
+
"x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :],
|
751 |
+
"x_prenorm": x,
|
752 |
+
"masks": masks,
|
753 |
+
}
|
754 |
+
)
|
755 |
+
return output
|
756 |
+
|
757 |
+
def forward_features(self, x, masks=None):
|
758 |
+
if isinstance(x, list):
|
759 |
+
return self.forward_features_list(x, masks)
|
760 |
+
|
761 |
+
x = self.prepare_tokens_with_masks(x, masks)
|
762 |
+
|
763 |
+
for blk in self.blocks:
|
764 |
+
x = blk(x)
|
765 |
+
|
766 |
+
x_norm = self.norm(x)
|
767 |
+
return {
|
768 |
+
"x_norm_clstoken": x_norm[:, 0],
|
769 |
+
"x_norm_regtokens": x_norm[:, 1 : self.num_register_tokens + 1],
|
770 |
+
"x_norm_patchtokens": x_norm[:, self.num_register_tokens + 1 :],
|
771 |
+
"x_prenorm": x,
|
772 |
+
"masks": masks,
|
773 |
+
}
|
774 |
+
|
775 |
+
def _get_intermediate_layers_not_chunked(self, x, n=1):
|
776 |
+
x = self.prepare_tokens_with_masks(x)
|
777 |
+
# If n is an int, take the n last blocks. If it's a list, take them
|
778 |
+
output, total_block_len = [], len(self.blocks)
|
779 |
+
blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n
|
780 |
+
for i, blk in enumerate(self.blocks):
|
781 |
+
x = blk(x)
|
782 |
+
if i in blocks_to_take:
|
783 |
+
output.append(x)
|
784 |
+
assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found"
|
785 |
+
return output
|
786 |
+
|
787 |
+
def _get_intermediate_layers_chunked(self, x, n=1):
|
788 |
+
x = self.prepare_tokens_with_masks(x)
|
789 |
+
output, i, total_block_len = [], 0, len(self.blocks[-1])
|
790 |
+
# If n is an int, take the n last blocks. If it's a list, take them
|
791 |
+
blocks_to_take = range(total_block_len - n, total_block_len) if isinstance(n, int) else n
|
792 |
+
for block_chunk in self.blocks:
|
793 |
+
for blk in block_chunk[i:]: # Passing the nn.Identity()
|
794 |
+
x = blk(x)
|
795 |
+
if i in blocks_to_take:
|
796 |
+
output.append(x)
|
797 |
+
i += 1
|
798 |
+
assert len(output) == len(blocks_to_take), f"only {len(output)} / {len(blocks_to_take)} blocks found"
|
799 |
+
return output
|
800 |
+
|
801 |
+
def get_intermediate_layers(
|
802 |
+
self,
|
803 |
+
x: torch.Tensor,
|
804 |
+
n: Union[int, Sequence] = 1, # Layers or n last layers to take
|
805 |
+
reshape: bool = False,
|
806 |
+
return_class_token: bool = False,
|
807 |
+
norm=True,
|
808 |
+
) -> Tuple[Union[torch.Tensor, Tuple[torch.Tensor]]]:
|
809 |
+
if self.chunked_blocks:
|
810 |
+
outputs = self._get_intermediate_layers_chunked(x, n)
|
811 |
+
else:
|
812 |
+
outputs = self._get_intermediate_layers_not_chunked(x, n)
|
813 |
+
if norm:
|
814 |
+
outputs = [self.norm(out) for out in outputs]
|
815 |
+
class_tokens = [out[:, 0] for out in outputs]
|
816 |
+
outputs = [out[:, 1 + self.num_register_tokens :] for out in outputs]
|
817 |
+
if reshape:
|
818 |
+
B, _, w, h = x.shape
|
819 |
+
outputs = [
|
820 |
+
out.reshape(B, w // self.patch_size, h // self.patch_size, -1).permute(0, 3, 1, 2).contiguous()
|
821 |
+
for out in outputs
|
822 |
+
]
|
823 |
+
if return_class_token:
|
824 |
+
return tuple(zip(outputs, class_tokens))
|
825 |
+
return tuple(outputs)
|
826 |
+
|
827 |
+
def forward(self, *args, is_training=False, **kwargs):
|
828 |
+
ret = self.forward_features(*args, **kwargs)
|
829 |
+
if is_training:
|
830 |
+
return ret
|
831 |
+
else:
|
832 |
+
return self.head(ret["x_norm_clstoken"])
|
833 |
+
|
834 |
+
|
835 |
+
def vit_small(patch_size=16, num_register_tokens=0, **kwargs):
|
836 |
+
model = DinoVisionTransformer(
|
837 |
+
patch_size=patch_size,
|
838 |
+
embed_dim=384,
|
839 |
+
depth=12,
|
840 |
+
num_heads=6,
|
841 |
+
mlp_ratio=4,
|
842 |
+
block_fn=partial(Block, attn_class=MemEffAttention),
|
843 |
+
num_register_tokens=num_register_tokens,
|
844 |
+
**kwargs,
|
845 |
+
)
|
846 |
+
return model
|
847 |
+
|
848 |
+
|
849 |
+
def vit_base(patch_size=16, num_register_tokens=0, **kwargs):
|
850 |
+
model = DinoVisionTransformer(
|
851 |
+
patch_size=patch_size,
|
852 |
+
embed_dim=768,
|
853 |
+
depth=12,
|
854 |
+
num_heads=12,
|
855 |
+
mlp_ratio=4,
|
856 |
+
block_fn=partial(Block, attn_class=MemEffAttention),
|
857 |
+
num_register_tokens=num_register_tokens,
|
858 |
+
**kwargs,
|
859 |
+
)
|
860 |
+
return model
|
861 |
+
|
862 |
+
|
863 |
+
def vit_large(patch_size=16, num_register_tokens=0, **kwargs):
|
864 |
+
model = DinoVisionTransformer(
|
865 |
+
patch_size=patch_size,
|
866 |
+
embed_dim=1024,
|
867 |
+
depth=24,
|
868 |
+
num_heads=16,
|
869 |
+
mlp_ratio=4,
|
870 |
+
block_fn=partial(Block, attn_class=MemEffAttention),
|
871 |
+
num_register_tokens=num_register_tokens,
|
872 |
+
**kwargs,
|
873 |
+
)
|
874 |
+
return model
|
875 |
+
|
876 |
+
|
877 |
+
def vit_giant2(patch_size=16, num_register_tokens=0, **kwargs):
|
878 |
+
"""
|
879 |
+
Close to ViT-giant, with embed-dim 1536 and 24 heads => embed-dim per head 64
|
880 |
+
"""
|
881 |
+
model = DinoVisionTransformer(
|
882 |
+
patch_size=patch_size,
|
883 |
+
embed_dim=1536,
|
884 |
+
depth=40,
|
885 |
+
num_heads=24,
|
886 |
+
mlp_ratio=4,
|
887 |
+
block_fn=partial(Block, attn_class=MemEffAttention),
|
888 |
+
num_register_tokens=num_register_tokens,
|
889 |
+
**kwargs,
|
890 |
+
)
|
891 |
+
return model
|
892 |
+
|
893 |
+
|
894 |
+
class Weights(Enum):
|
895 |
+
LVD142M = "LVD142M"
|
896 |
+
|
897 |
+
|
898 |
+
def _make_dinov2_model(
|
899 |
+
*,
|
900 |
+
arch_name: str = "vit_large",
|
901 |
+
img_size: int = 518,
|
902 |
+
patch_size: int = 14,
|
903 |
+
init_values: float = 1.0,
|
904 |
+
ffn_layer: str = "mlp",
|
905 |
+
block_chunks: int = 0,
|
906 |
+
num_register_tokens: int = 0,
|
907 |
+
interpolate_antialias: bool = False,
|
908 |
+
interpolate_offset: float = 0.1,
|
909 |
+
weights: Union[Weights, str] = Weights.LVD142M,
|
910 |
+
**kwargs,
|
911 |
+
):
|
912 |
+
if isinstance(weights, str):
|
913 |
+
try:
|
914 |
+
weights = Weights[weights]
|
915 |
+
except KeyError:
|
916 |
+
raise AssertionError(f"Unsupported weights: {weights}")
|
917 |
+
|
918 |
+
vit_kwargs = dict(
|
919 |
+
img_size=img_size,
|
920 |
+
patch_size=patch_size,
|
921 |
+
init_values=init_values,
|
922 |
+
ffn_layer=ffn_layer,
|
923 |
+
block_chunks=block_chunks,
|
924 |
+
num_register_tokens=num_register_tokens,
|
925 |
+
interpolate_antialias=interpolate_antialias,
|
926 |
+
interpolate_offset=interpolate_offset,
|
927 |
+
)
|
928 |
+
vit_kwargs.update(**kwargs)
|
929 |
+
model = sys.modules[__name__].__dict__[arch_name](**vit_kwargs)
|
930 |
+
|
931 |
+
return model
|
932 |
+
|
933 |
+
|
934 |
+
def dinov2_vits14(**kwargs):
|
935 |
+
"""
|
936 |
+
DINOv2 ViT-S/14 model (optionally) pretrained on the LVD-142M dataset.
|
937 |
+
"""
|
938 |
+
return _make_dinov2_model(arch_name="vit_small", **kwargs)
|
939 |
+
|
940 |
+
|
941 |
+
def dinov2_vitb14(**kwargs):
|
942 |
+
"""
|
943 |
+
DINOv2 ViT-B/14 model (optionally) pretrained on the LVD-142M dataset.
|
944 |
+
"""
|
945 |
+
return _make_dinov2_model(arch_name="vit_base", **kwargs)
|
946 |
+
|
947 |
+
|
948 |
+
def dinov2_vitl14(**kwargs):
|
949 |
+
"""
|
950 |
+
DINOv2 ViT-L/14 model (optionally) pretrained on the LVD-142M dataset.
|
951 |
+
"""
|
952 |
+
return _make_dinov2_model(arch_name="vit_large", **kwargs)
|
953 |
+
|
954 |
+
|
955 |
+
def dinov2_vitg14(**kwargs):
|
956 |
+
"""
|
957 |
+
DINOv2 ViT-g/14 model (optionally) pretrained on the LVD-142M dataset.
|
958 |
+
"""
|
959 |
+
return _make_dinov2_model(
|
960 |
+
arch_name="vit_giant2",
|
961 |
+
ffn_layer="swiglufused",
|
962 |
+
**kwargs,
|
963 |
+
)
|
964 |
+
|
965 |
+
|
966 |
+
def dinov2_vits14_reg(**kwargs):
|
967 |
+
"""
|
968 |
+
DINOv2 ViT-S/14 model with registers (optionally) pretrained on the LVD-142M dataset.
|
969 |
+
"""
|
970 |
+
return _make_dinov2_model(
|
971 |
+
arch_name="vit_small",
|
972 |
+
num_register_tokens=4,
|
973 |
+
interpolate_antialias=True,
|
974 |
+
interpolate_offset=0.0,
|
975 |
+
**kwargs,
|
976 |
+
)
|
977 |
+
|
978 |
+
|
979 |
+
def dinov2_vitb14_reg(**kwargs):
|
980 |
+
"""
|
981 |
+
DINOv2 ViT-B/14 model with registers (optionally) pretrained on the LVD-142M dataset.
|
982 |
+
"""
|
983 |
+
return _make_dinov2_model(
|
984 |
+
arch_name="vit_base",
|
985 |
+
num_register_tokens=4,
|
986 |
+
interpolate_antialias=True,
|
987 |
+
interpolate_offset=0.0,
|
988 |
+
**kwargs,
|
989 |
+
)
|
990 |
+
|
991 |
+
|
992 |
+
def dinov2_vitl14_reg(**kwargs):
|
993 |
+
"""
|
994 |
+
DINOv2 ViT-L/14 model with registers (optionally) pretrained on the LVD-142M dataset.
|
995 |
+
"""
|
996 |
+
return _make_dinov2_model(
|
997 |
+
arch_name="vit_large",
|
998 |
+
num_register_tokens=4,
|
999 |
+
interpolate_antialias=True,
|
1000 |
+
interpolate_offset=0.0,
|
1001 |
+
**kwargs,
|
1002 |
+
)
|
1003 |
+
|
1004 |
+
|
1005 |
+
def dinov2_vitg14_reg(**kwargs):
|
1006 |
+
"""
|
1007 |
+
DINOv2 ViT-g/14 model with registers (optionally) pretrained on the LVD-142M dataset.
|
1008 |
+
"""
|
1009 |
+
return _make_dinov2_model(
|
1010 |
+
arch_name="vit_giant2",
|
1011 |
+
ffn_layer="swiglufused",
|
1012 |
+
num_register_tokens=4,
|
1013 |
+
interpolate_antialias=True,
|
1014 |
+
interpolate_offset=0.0,
|
1015 |
+
**kwargs,
|
1016 |
+
)
|
enable_spectral_reparam.py
CHANGED
@@ -9,7 +9,7 @@
|
|
9 |
from logging import getLogger
|
10 |
import math
|
11 |
import os
|
12 |
-
from typing import List, Union, Tuple
|
13 |
from types import MethodType
|
14 |
|
15 |
import torch
|
@@ -136,18 +136,28 @@ def enable_spectral_reparam(model: Union[nn.Module, List[nn.Module]],
|
|
136 |
eps: float = 1e-6,
|
137 |
init_norm_to_current: bool = False,
|
138 |
renorm_values: bool = True,
|
139 |
-
renorm_mlp: bool = True
|
|
|
140 |
if isinstance(model, (list, tuple)):
|
141 |
-
for sub in model:
|
|
|
142 |
enable_spectral_reparam(sub, n_power_iterations=n_power_iterations, eps=eps,
|
143 |
init_norm_to_current=init_norm_to_current, renorm_values=renorm_values,
|
144 |
-
renorm_mlp=renorm_mlp)
|
145 |
return
|
146 |
|
147 |
print('Enabling spectral reparametrization')
|
148 |
args = dict(n_power_iterations=n_power_iterations, dim=0, eps=eps, init_norm_to_current=init_norm_to_current)
|
149 |
visited_prefixes = set()
|
150 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
151 |
def parametrize_linear(linear: nn.Linear):
|
152 |
parametrize.register_parametrization(
|
153 |
linear,
|
@@ -161,36 +171,40 @@ def enable_spectral_reparam(model: Union[nn.Module, List[nn.Module]],
|
|
161 |
continue
|
162 |
|
163 |
if isinstance(mod, Attention) or name.endswith('.attn'):
|
164 |
-
|
165 |
-
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
|
|
170 |
parametrize_linear(mod.proj)
|
171 |
visited_prefixes.add(name)
|
172 |
elif name.endswith('mlp') and renorm_mlp and hasattr(mod, 'w12'):
|
173 |
-
|
174 |
-
|
175 |
-
|
176 |
-
|
177 |
-
|
178 |
-
|
|
|
|
|
179 |
visited_prefixes.add(name)
|
180 |
-
elif isinstance(mod, nn.Linear) and 'patch_generator' not in name:
|
181 |
parametrize_linear(mod)
|
182 |
|
183 |
|
184 |
-
def configure_spectral_reparam_from_args(model: nn.Module, args):
|
185 |
spectral_reparam = getattr(args, 'spectral_reparam', False)
|
186 |
if isinstance(spectral_reparam, bool) and spectral_reparam:
|
187 |
-
enable_spectral_reparam(model, init_norm_to_current=True)
|
188 |
elif isinstance(spectral_reparam, dict):
|
189 |
enable_spectral_reparam(
|
190 |
model,
|
191 |
n_power_iterations=spectral_reparam.get('n_power_iterations', 1),
|
192 |
eps=spectral_reparam.get('eps', 1e-12),
|
193 |
init_norm_to_current=True,
|
|
|
194 |
)
|
195 |
|
196 |
|
|
|
9 |
from logging import getLogger
|
10 |
import math
|
11 |
import os
|
12 |
+
from typing import Dict, List, Optional, Union, Tuple
|
13 |
from types import MethodType
|
14 |
|
15 |
import torch
|
|
|
136 |
eps: float = 1e-6,
|
137 |
init_norm_to_current: bool = False,
|
138 |
renorm_values: bool = True,
|
139 |
+
renorm_mlp: bool = True,
|
140 |
+
state_dict_guidance: Optional[Dict[str, torch.Tensor]] = None):
|
141 |
if isinstance(model, (list, tuple)):
|
142 |
+
for i, sub in enumerate(model):
|
143 |
+
sub_sd = state_dict_guidance[i] if isinstance(state_dict_guidance, (list, tuple)) else state_dict_guidance
|
144 |
enable_spectral_reparam(sub, n_power_iterations=n_power_iterations, eps=eps,
|
145 |
init_norm_to_current=init_norm_to_current, renorm_values=renorm_values,
|
146 |
+
renorm_mlp=renorm_mlp, state_dict_guidance=sub_sd)
|
147 |
return
|
148 |
|
149 |
print('Enabling spectral reparametrization')
|
150 |
args = dict(n_power_iterations=n_power_iterations, dim=0, eps=eps, init_norm_to_current=init_norm_to_current)
|
151 |
visited_prefixes = set()
|
152 |
|
153 |
+
def is_guidance_parametrized(name: str):
|
154 |
+
if state_dict_guidance is None:
|
155 |
+
return True
|
156 |
+
|
157 |
+
p_name = f'{name}.parametrizations'
|
158 |
+
is_prm = any(k for k in state_dict_guidance if k.startswith(p_name))
|
159 |
+
return is_prm
|
160 |
+
|
161 |
def parametrize_linear(linear: nn.Linear):
|
162 |
parametrize.register_parametrization(
|
163 |
linear,
|
|
|
171 |
continue
|
172 |
|
173 |
if isinstance(mod, Attention) or name.endswith('.attn'):
|
174 |
+
if is_guidance_parametrized(f'{name}.qkv'):
|
175 |
+
parametrize.register_parametrization(
|
176 |
+
mod.qkv,
|
177 |
+
'weight',
|
178 |
+
_AttnSNReweight(mod.qkv.weight, renorm_values=renorm_values, **args),
|
179 |
+
)
|
180 |
+
if hasattr(mod, 'proj') and is_guidance_parametrized(f'{name}.proj'):
|
181 |
parametrize_linear(mod.proj)
|
182 |
visited_prefixes.add(name)
|
183 |
elif name.endswith('mlp') and renorm_mlp and hasattr(mod, 'w12'):
|
184 |
+
if is_guidance_parametrized(f'{name}.w12'):
|
185 |
+
parametrize.register_parametrization(
|
186 |
+
mod.w12,
|
187 |
+
'weight',
|
188 |
+
_ChunkedSNReweight(mod.w12.weight, num_chunks=2, **args),
|
189 |
+
)
|
190 |
+
if is_guidance_parametrized(f'{name}.w3'):
|
191 |
+
parametrize_linear(mod.w3)
|
192 |
visited_prefixes.add(name)
|
193 |
+
elif isinstance(mod, nn.Linear) and 'patch_generator' not in name and is_guidance_parametrized(name):
|
194 |
parametrize_linear(mod)
|
195 |
|
196 |
|
197 |
+
def configure_spectral_reparam_from_args(model: nn.Module, args, state_dict_guidance: Optional[Dict[str, torch.Tensor]] = None):
|
198 |
spectral_reparam = getattr(args, 'spectral_reparam', False)
|
199 |
if isinstance(spectral_reparam, bool) and spectral_reparam:
|
200 |
+
enable_spectral_reparam(model, init_norm_to_current=True, state_dict_guidance=state_dict_guidance)
|
201 |
elif isinstance(spectral_reparam, dict):
|
202 |
enable_spectral_reparam(
|
203 |
model,
|
204 |
n_power_iterations=spectral_reparam.get('n_power_iterations', 1),
|
205 |
eps=spectral_reparam.get('eps', 1e-12),
|
206 |
init_norm_to_current=True,
|
207 |
+
state_dict_guidance=state_dict_guidance,
|
208 |
)
|
209 |
|
210 |
|
extra_models.py
CHANGED
@@ -1,13 +1,19 @@
|
|
1 |
from distutils.version import LooseVersion
|
|
|
2 |
from typing import List, Optional, Tuple, Union
|
3 |
import warnings
|
4 |
|
5 |
import torch
|
6 |
from torch import nn
|
|
|
7 |
|
8 |
from timm.models.registry import register_model
|
|
|
9 |
|
10 |
from .forward_intermediates import forward_intermediates
|
|
|
|
|
|
|
11 |
|
12 |
|
13 |
class PaliGemmaWrapper(nn.Module):
|
@@ -74,17 +80,38 @@ def paligemma_896_student(**kwargs):
|
|
74 |
return model
|
75 |
|
76 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
77 |
def _load_dino_v2(dino_v2_model, cache_dir: Optional[str] = None, pretrained=True, **kwargs):
|
78 |
if cache_dir:
|
79 |
torch.hub.set_dir(cache_dir)
|
80 |
-
model = torch.hub.load(
|
81 |
'facebookresearch/dinov2',
|
82 |
dino_v2_model,
|
83 |
pretrained=pretrained,
|
84 |
# **kwargs,
|
85 |
)
|
86 |
-
return model
|
87 |
|
|
|
|
|
|
|
|
|
|
|
|
|
88 |
|
89 |
class DinoWrapper(nn.Module):
|
90 |
def __init__(self, dino_model: nn.Module):
|
@@ -151,9 +178,29 @@ class DinoWrapper(nn.Module):
|
|
151 |
)
|
152 |
|
153 |
|
154 |
-
|
155 |
-
|
156 |
-
|
|
|
|
|
|
|
157 |
model = DinoWrapper(model)
|
158 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
159 |
return model
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
from distutils.version import LooseVersion
|
2 |
+
from types import MethodType
|
3 |
from typing import List, Optional, Tuple, Union
|
4 |
import warnings
|
5 |
|
6 |
import torch
|
7 |
from torch import nn
|
8 |
+
import torch.nn.functional as F
|
9 |
|
10 |
from timm.models.registry import register_model
|
11 |
+
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
|
12 |
|
13 |
from .forward_intermediates import forward_intermediates
|
14 |
+
from .input_conditioner import InputConditioner
|
15 |
+
|
16 |
+
_has_torch_sdpa = hasattr(F, 'scaled_dot_product_attention')
|
17 |
|
18 |
|
19 |
class PaliGemmaWrapper(nn.Module):
|
|
|
80 |
return model
|
81 |
|
82 |
|
83 |
+
def dv2_sdpa(self, x: torch.Tensor) -> torch.Tensor:
|
84 |
+
B, N, C = x.shape
|
85 |
+
qkv = self.qkv(x).reshape(B, N, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4)
|
86 |
+
|
87 |
+
q, k, v = qkv[0], qkv[1], qkv[2]
|
88 |
+
x = F.scaled_dot_product_attention(
|
89 |
+
q, k, v,
|
90 |
+
is_causal=False,
|
91 |
+
dropout_p=self.attn_drop.p if self.training else 0.,
|
92 |
+
scale=self.scale,
|
93 |
+
)
|
94 |
+
x = x.transpose(1, 2).reshape(B, N, C)
|
95 |
+
x = self.proj(x)
|
96 |
+
x = self.proj_drop(x)
|
97 |
+
return x
|
98 |
+
|
99 |
def _load_dino_v2(dino_v2_model, cache_dir: Optional[str] = None, pretrained=True, **kwargs):
|
100 |
if cache_dir:
|
101 |
torch.hub.set_dir(cache_dir)
|
102 |
+
model: nn.Module = torch.hub.load(
|
103 |
'facebookresearch/dinov2',
|
104 |
dino_v2_model,
|
105 |
pretrained=pretrained,
|
106 |
# **kwargs,
|
107 |
)
|
|
|
108 |
|
109 |
+
if _has_torch_sdpa:
|
110 |
+
for n, m in model.named_modules():
|
111 |
+
if n.endswith('.attn'):
|
112 |
+
m.forward = MethodType(dv2_sdpa, m)
|
113 |
+
|
114 |
+
return model
|
115 |
|
116 |
class DinoWrapper(nn.Module):
|
117 |
def __init__(self, dino_model: nn.Module):
|
|
|
178 |
)
|
179 |
|
180 |
|
181 |
+
def _dino_student(arch: str, **kwargs):
|
182 |
+
from . import dinov2_arch
|
183 |
+
|
184 |
+
factory = getattr(dinov2_arch, arch)
|
185 |
+
model = factory()
|
186 |
+
|
187 |
model = DinoWrapper(model)
|
188 |
|
189 |
+
conditioner = InputConditioner(
|
190 |
+
input_scale=1.0,
|
191 |
+
norm_mean=IMAGENET_DEFAULT_MEAN,
|
192 |
+
norm_std=IMAGENET_DEFAULT_STD,
|
193 |
+
)
|
194 |
+
|
195 |
+
model.input_conditioner = conditioner
|
196 |
+
|
197 |
return model
|
198 |
+
|
199 |
+
|
200 |
+
@register_model
|
201 |
+
def dino_v2_l_student(**kwargs):
|
202 |
+
return _dino_student('dinov2_vitl14_reg', **kwargs)
|
203 |
+
|
204 |
+
@register_model
|
205 |
+
def dino_v2_g_student(**kwargs):
|
206 |
+
return _dino_student('dinov2_vitg14_reg', **kwargs)
|
hf_model.py
CHANGED
@@ -28,6 +28,7 @@ from .adaptor_generic import GenericAdaptor, AdaptorBase
|
|
28 |
from .adaptor_mlp import create_mlp_from_config
|
29 |
from .adaptor_registry import adaptor_registry
|
30 |
from .cls_token import ClsToken
|
|
|
31 |
from .enable_cpe_support import enable_cpe
|
32 |
from .enable_spectral_reparam import configure_spectral_reparam_from_args
|
33 |
from .eradio_model import eradio
|
@@ -41,8 +42,8 @@ from .vit_patch_generator import ViTPatchGenerator
|
|
41 |
from .vitdet import apply_vitdet_arch, VitDetArgs
|
42 |
|
43 |
# Register extra models
|
44 |
-
from .extra_models import *
|
45 |
from .extra_timm_models import *
|
|
|
46 |
|
47 |
|
48 |
|
@@ -59,6 +60,8 @@ def rename_all_gamma_to_weight_with_proxy(module):
|
|
59 |
# Generate the new name by replacing 'gamma' with 'weight'
|
60 |
new_name = param_name.replace('gamma', 'weight')
|
61 |
|
|
|
|
|
62 |
# Remove the old parameter and assign it with the new name
|
63 |
delattr(submodule, param_name)
|
64 |
setattr(submodule, new_name, nn.Parameter(param.data))
|
|
|
28 |
from .adaptor_mlp import create_mlp_from_config
|
29 |
from .adaptor_registry import adaptor_registry
|
30 |
from .cls_token import ClsToken
|
31 |
+
from .dinov2_arch import dinov2_vitg14_reg
|
32 |
from .enable_cpe_support import enable_cpe
|
33 |
from .enable_spectral_reparam import configure_spectral_reparam_from_args
|
34 |
from .eradio_model import eradio
|
|
|
42 |
from .vitdet import apply_vitdet_arch, VitDetArgs
|
43 |
|
44 |
# Register extra models
|
|
|
45 |
from .extra_timm_models import *
|
46 |
+
from .extra_models import *
|
47 |
|
48 |
|
49 |
|
|
|
60 |
# Generate the new name by replacing 'gamma' with 'weight'
|
61 |
new_name = param_name.replace('gamma', 'weight')
|
62 |
|
63 |
+
print("In submodule {}: Renaming '{}' to '{}'".format(submodule_name, param_name, new_name))
|
64 |
+
|
65 |
# Remove the old parameter and assign it with the new name
|
66 |
delattr(submodule, param_name)
|
67 |
setattr(submodule, new_name, nn.Parameter(param.data))
|
model.safetensors
CHANGED
@@ -1,3 +1,3 @@
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
-
oid sha256:
|
3 |
-
size
|
|
|
1 |
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:7929c4c70895835ec06dd15d69f36f4f1d77973964ecac445eb96db1d0add7f3
|
3 |
+
size 2606616136
|
radio_model.py
CHANGED
@@ -145,7 +145,14 @@ class RADIOModel(nn.Module):
|
|
145 |
if fn is not None:
|
146 |
fn()
|
147 |
|
148 |
-
def forward(self, x: torch.Tensor) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
149 |
res_step = self.min_resolution_step
|
150 |
if res_step is not None and (x.shape[-2] % res_step != 0 or x.shape[-1] % res_step != 0):
|
151 |
raise ValueError('The input resolution must be a multiple of `self.min_resolution_step`. '
|
@@ -154,10 +161,10 @@ class RADIOModel(nn.Module):
|
|
154 |
|
155 |
x = self.input_conditioner(x)
|
156 |
y = self.model.forward_features(x)
|
157 |
-
ret = self._extract_final(x, y)
|
158 |
return ret
|
159 |
|
160 |
-
def _extract_final(self, x: torch.Tensor, y: torch.Tensor):
|
161 |
if isinstance(self.model, VisionTransformer):
|
162 |
patch_gen = getattr(self.model, "patch_generator", None)
|
163 |
if patch_gen is not None:
|
@@ -194,11 +201,19 @@ class RADIOModel(nn.Module):
|
|
194 |
bb_summary = all_summary
|
195 |
all_feat = y[:, self.num_summary_tokens:]
|
196 |
|
197 |
-
all_feat = all_feat.float()
|
198 |
-
|
199 |
all_feat = self.feature_normalizer(all_feat)
|
200 |
|
201 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
202 |
if self.adaptors:
|
203 |
ret = dict(backbone=ret)
|
204 |
for name, adaptor in self.adaptors.items():
|
@@ -206,7 +221,7 @@ class RADIOModel(nn.Module):
|
|
206 |
summary = all_summary[:, adaptor.head_idx]
|
207 |
else:
|
208 |
summary = all_summary
|
209 |
-
ada_input = AdaptorInput(images=x, summary=summary.float(), features=all_feat)
|
210 |
v = adaptor(ada_input).to(torch.float32)
|
211 |
ret[name] = v
|
212 |
|
@@ -275,7 +290,7 @@ class RADIOModel(nn.Module):
|
|
275 |
if intermediates_only:
|
276 |
return radio_outputs
|
277 |
else:
|
278 |
-
final = self._extract_final(x, final)
|
279 |
return final, radio_outputs
|
280 |
|
281 |
|
@@ -325,7 +340,4 @@ def create_model_from_args(args) -> nn.Module:
|
|
325 |
num_registers=getattr(args, 'cpe_num_registers', None),
|
326 |
)
|
327 |
|
328 |
-
if args.spectral_reparam:
|
329 |
-
configure_spectral_reparam_from_args(model, args)
|
330 |
-
|
331 |
return model
|
|
|
145 |
if fn is not None:
|
146 |
fn()
|
147 |
|
148 |
+
def forward(self, x: torch.Tensor, feature_fmt: str = 'NLC') -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
|
149 |
+
'''
|
150 |
+
Forward process for model.
|
151 |
+
Args:
|
152 |
+
x: Input tensor. Unless `make_preprocessor_external` has been called, then the dynamic range of `x` is expected to be `[0, 1]`,
|
153 |
+
otherwise `x` is expected to be mean centered with unit standard deviation.
|
154 |
+
feature_format: ['NLC', 'NCHW'] - The output format for the features.
|
155 |
+
'''
|
156 |
res_step = self.min_resolution_step
|
157 |
if res_step is not None and (x.shape[-2] % res_step != 0 or x.shape[-1] % res_step != 0):
|
158 |
raise ValueError('The input resolution must be a multiple of `self.min_resolution_step`. '
|
|
|
161 |
|
162 |
x = self.input_conditioner(x)
|
163 |
y = self.model.forward_features(x)
|
164 |
+
ret = self._extract_final(x, y, feature_fmt=feature_fmt)
|
165 |
return ret
|
166 |
|
167 |
+
def _extract_final(self, x: torch.Tensor, y: torch.Tensor, feature_fmt: str = 'NLC'):
|
168 |
if isinstance(self.model, VisionTransformer):
|
169 |
patch_gen = getattr(self.model, "patch_generator", None)
|
170 |
if patch_gen is not None:
|
|
|
201 |
bb_summary = all_summary
|
202 |
all_feat = y[:, self.num_summary_tokens:]
|
203 |
|
|
|
|
|
204 |
all_feat = self.feature_normalizer(all_feat)
|
205 |
|
206 |
+
if feature_fmt == 'NCHW':
|
207 |
+
fmt_feat = (all_feat.reshape(all_feat.shape[0], x.shape[-2] // self.patch_size, x.shape[-1] // self.patch_size, all_feat.shape[2])
|
208 |
+
.permute(0, 3, 1, 2)
|
209 |
+
)
|
210 |
+
elif feature_fmt == 'NLC':
|
211 |
+
fmt_feat = all_feat
|
212 |
+
else:
|
213 |
+
raise ValueError(f'Unsupported feature_fmt: {feature_fmt}. Must be one of ["NLC", "NCHW"]')
|
214 |
+
|
215 |
+
ret = RadioOutput(bb_summary.flatten(1), fmt_feat)
|
216 |
+
|
217 |
if self.adaptors:
|
218 |
ret = dict(backbone=ret)
|
219 |
for name, adaptor in self.adaptors.items():
|
|
|
221 |
summary = all_summary[:, adaptor.head_idx]
|
222 |
else:
|
223 |
summary = all_summary
|
224 |
+
ada_input = AdaptorInput(images=x, summary=summary.float(), features=all_feat, feature_fmt=feature_fmt, patch_size=self.patch_size)
|
225 |
v = adaptor(ada_input).to(torch.float32)
|
226 |
ret[name] = v
|
227 |
|
|
|
290 |
if intermediates_only:
|
291 |
return radio_outputs
|
292 |
else:
|
293 |
+
final = self._extract_final(x, final, feature_fmt=output_fmt)
|
294 |
return final, radio_outputs
|
295 |
|
296 |
|
|
|
340 |
num_registers=getattr(args, 'cpe_num_registers', None),
|
341 |
)
|
342 |
|
|
|
|
|
|
|
343 |
return model
|