robinzixuan
commited on
Commit
•
921b6e1
1
Parent(s):
a59be4f
Upload 2 files
Browse files- configuration_vit.py +138 -0
- modeling_vit.py +1085 -0
configuration_vit.py
ADDED
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# coding=utf-8
|
2 |
+
# Copyright 2021 Google AI and The HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
"""ViT model configuration"""
|
16 |
+
|
17 |
+
from collections import OrderedDict
|
18 |
+
from typing import Mapping
|
19 |
+
|
20 |
+
from packaging import version
|
21 |
+
|
22 |
+
from transformers.configuration_utils import PretrainedConfig
|
23 |
+
from transformers.onnx import OnnxConfig
|
24 |
+
from transformers.utils import logging
|
25 |
+
|
26 |
+
|
27 |
+
logger = logging.get_logger(__name__)
|
28 |
+
|
29 |
+
|
30 |
+
class ViTConfig(PretrainedConfig):
|
31 |
+
r"""
|
32 |
+
This is the configuration class to store the configuration of a [`ViTModel`]. It is used to instantiate an ViT
|
33 |
+
model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
|
34 |
+
defaults will yield a similar configuration to that of the ViT
|
35 |
+
[google/vit-base-patch16-224](https://huggingface.co/google/vit-base-patch16-224) architecture.
|
36 |
+
|
37 |
+
Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
|
38 |
+
documentation from [`PretrainedConfig`] for more information.
|
39 |
+
|
40 |
+
|
41 |
+
Args:
|
42 |
+
hidden_size (`int`, *optional*, defaults to 768):
|
43 |
+
Dimensionality of the encoder layers and the pooler layer.
|
44 |
+
num_hidden_layers (`int`, *optional*, defaults to 12):
|
45 |
+
Number of hidden layers in the Transformer encoder.
|
46 |
+
num_attention_heads (`int`, *optional*, defaults to 12):
|
47 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
48 |
+
intermediate_size (`int`, *optional*, defaults to 3072):
|
49 |
+
Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
|
50 |
+
hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
|
51 |
+
The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
|
52 |
+
`"relu"`, `"selu"` and `"gelu_new"` are supported.
|
53 |
+
hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
|
54 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
55 |
+
attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
|
56 |
+
The dropout ratio for the attention probabilities.
|
57 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
58 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
59 |
+
layer_norm_eps (`float`, *optional*, defaults to 1e-12):
|
60 |
+
The epsilon used by the layer normalization layers.
|
61 |
+
image_size (`int`, *optional*, defaults to 224):
|
62 |
+
The size (resolution) of each image.
|
63 |
+
patch_size (`int`, *optional*, defaults to 16):
|
64 |
+
The size (resolution) of each patch.
|
65 |
+
num_channels (`int`, *optional*, defaults to 3):
|
66 |
+
The number of input channels.
|
67 |
+
qkv_bias (`bool`, *optional*, defaults to `True`):
|
68 |
+
Whether to add a bias to the queries, keys and values.
|
69 |
+
encoder_stride (`int`, *optional*, defaults to 16):
|
70 |
+
Factor to increase the spatial resolution by in the decoder head for masked image modeling.
|
71 |
+
|
72 |
+
Example:
|
73 |
+
|
74 |
+
```python
|
75 |
+
>>> from transformers import ViTConfig, ViTModel
|
76 |
+
|
77 |
+
>>> # Initializing a ViT vit-base-patch16-224 style configuration
|
78 |
+
>>> configuration = ViTConfig()
|
79 |
+
|
80 |
+
>>> # Initializing a model (with random weights) from the vit-base-patch16-224 style configuration
|
81 |
+
>>> model = ViTModel(configuration)
|
82 |
+
|
83 |
+
>>> # Accessing the model configuration
|
84 |
+
>>> configuration = model.config
|
85 |
+
```"""
|
86 |
+
|
87 |
+
model_type = "vit"
|
88 |
+
|
89 |
+
def __init__(
|
90 |
+
self,
|
91 |
+
hidden_size=768,
|
92 |
+
num_hidden_layers=12,
|
93 |
+
num_attention_heads=12,
|
94 |
+
intermediate_size=3072,
|
95 |
+
hidden_act="gelu",
|
96 |
+
hidden_dropout_prob=0.0,
|
97 |
+
attention_probs_dropout_prob=0.0,
|
98 |
+
initializer_range=0.02,
|
99 |
+
layer_norm_eps=1e-12,
|
100 |
+
image_size=224,
|
101 |
+
patch_size=16,
|
102 |
+
num_channels=3,
|
103 |
+
qkv_bias=True,
|
104 |
+
encoder_stride=16,
|
105 |
+
**kwargs,
|
106 |
+
):
|
107 |
+
super().__init__(**kwargs)
|
108 |
+
|
109 |
+
self.hidden_size = hidden_size
|
110 |
+
self.num_hidden_layers = num_hidden_layers
|
111 |
+
self.num_attention_heads = num_attention_heads
|
112 |
+
self.intermediate_size = intermediate_size
|
113 |
+
self.hidden_act = hidden_act
|
114 |
+
self.hidden_dropout_prob = hidden_dropout_prob
|
115 |
+
self.attention_probs_dropout_prob = attention_probs_dropout_prob
|
116 |
+
self.initializer_range = initializer_range
|
117 |
+
self.layer_norm_eps = layer_norm_eps
|
118 |
+
self.image_size = image_size
|
119 |
+
self.patch_size = patch_size
|
120 |
+
self.num_channels = num_channels
|
121 |
+
self.qkv_bias = qkv_bias
|
122 |
+
self.encoder_stride = encoder_stride
|
123 |
+
|
124 |
+
|
125 |
+
class ViTOnnxConfig(OnnxConfig):
|
126 |
+
torch_onnx_minimum_version = version.parse("1.11")
|
127 |
+
|
128 |
+
@property
|
129 |
+
def inputs(self) -> Mapping[str, Mapping[int, str]]:
|
130 |
+
return OrderedDict(
|
131 |
+
[
|
132 |
+
("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
|
133 |
+
]
|
134 |
+
)
|
135 |
+
|
136 |
+
@property
|
137 |
+
def atol_for_validation(self) -> float:
|
138 |
+
return 1e-4
|
modeling_vit.py
ADDED
@@ -0,0 +1,1085 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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The HuggingFace Inc. team. All rights reserved.
|
3 |
+
#
|
4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
5 |
+
# you may not use this file except in compliance with the License.
|
6 |
+
# You may obtain a copy of the License at
|
7 |
+
#
|
8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
9 |
+
#
|
10 |
+
# Unless required by applicable law or agreed to in writing, software
|
11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13 |
+
# See the License for the specific language governing permissions and
|
14 |
+
# limitations under the License.
|
15 |
+
"""PyTorch ViT model."""
|
16 |
+
|
17 |
+
import collections.abc
|
18 |
+
import math
|
19 |
+
from typing import Dict, List, Optional, Set, Tuple, Union
|
20 |
+
from functools import partial
|
21 |
+
from enum import Flag, auto
|
22 |
+
import torch
|
23 |
+
import torch.utils.checkpoint
|
24 |
+
from torch import nn
|
25 |
+
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
|
26 |
+
import numpy as np
|
27 |
+
from transformers.activations import ACT2FN
|
28 |
+
from transformers.modeling_outputs import (
|
29 |
+
BaseModelOutput,
|
30 |
+
BaseModelOutputWithPooling,
|
31 |
+
ImageClassifierOutput,
|
32 |
+
MaskedImageModelingOutput,
|
33 |
+
)
|
34 |
+
from transformers.modeling_utils import PreTrainedModel
|
35 |
+
from transformers.pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
|
36 |
+
from transformers.utils import (
|
37 |
+
add_code_sample_docstrings,
|
38 |
+
add_start_docstrings,
|
39 |
+
add_start_docstrings_to_model_forward,
|
40 |
+
logging,
|
41 |
+
replace_return_docstrings,
|
42 |
+
)
|
43 |
+
from .configuration_vit import ViTConfig
|
44 |
+
|
45 |
+
|
46 |
+
logger = logging.get_logger(__name__)
|
47 |
+
|
48 |
+
# General docstring
|
49 |
+
_CONFIG_FOR_DOC = "ViTConfig"
|
50 |
+
|
51 |
+
# Base docstring
|
52 |
+
_CHECKPOINT_FOR_DOC = "google/vit-base-patch16-224-in21k"
|
53 |
+
_EXPECTED_OUTPUT_SHAPE = [1, 197, 768]
|
54 |
+
|
55 |
+
# Image classification docstring
|
56 |
+
_IMAGE_CLASS_CHECKPOINT = "google/vit-base-patch16-224"
|
57 |
+
_IMAGE_CLASS_EXPECTED_OUTPUT = "Egyptian cat"
|
58 |
+
|
59 |
+
|
60 |
+
|
61 |
+
|
62 |
+
class BaseEnumOptions(Flag):
|
63 |
+
def __str__(self):
|
64 |
+
return self.name
|
65 |
+
|
66 |
+
@classmethod
|
67 |
+
def list_names(cls):
|
68 |
+
return [m.name for m in cls]
|
69 |
+
class AttentionGateType(BaseEnumOptions):
|
70 |
+
none = 0
|
71 |
+
unconditional_per_head = 1
|
72 |
+
conditional_per_head = 2
|
73 |
+
conditional_per_token = 3
|
74 |
+
|
75 |
+
def softmax_n_shifted_zeros(input: torch.Tensor, n: int, dim=-1) -> torch.Tensor:
|
76 |
+
"""
|
77 |
+
$\text(softmax)_n(x_i) = exp(x_i) / (n + \sum_j exp(x_j))$
|
78 |
+
|
79 |
+
Note: softmax_n, with fixed input, is _not_ shift-symmetric when n != 0
|
80 |
+
"""
|
81 |
+
# compute the maxes along the last dimension
|
82 |
+
input_maxes = input.max(dim=dim, keepdim=True).values
|
83 |
+
# shift the input to prevent overflow (and underflow in the denominator)
|
84 |
+
shifted_inputs = torch.subtract(input, input_maxes)
|
85 |
+
# compute the numerator and softmax_0 denominator using the shifted input
|
86 |
+
numerator = torch.exp(shifted_inputs)
|
87 |
+
original_denominator = numerator.sum(dim=dim, keepdim=True)
|
88 |
+
# we need to shift the zeros in the same way we shifted the inputs
|
89 |
+
shifted_zeros = torch.multiply(input_maxes, -1)
|
90 |
+
# and then add this contribution to the denominator
|
91 |
+
denominator = torch.add(original_denominator,
|
92 |
+
torch.multiply(torch.exp(shifted_zeros), n))
|
93 |
+
return torch.divide(numerator, denominator)
|
94 |
+
def logit(p, eps=1e-16):
|
95 |
+
p = np.clip(p, eps, 1 - eps)
|
96 |
+
return -np.log(1 / p - 1)
|
97 |
+
|
98 |
+
def softmax_1(input: torch.Tensor, dim=-1) -> torch.Tensor:
|
99 |
+
"""
|
100 |
+
$\text(softmax)_n(x_i) = exp(x_i) / (1 + \sum_j exp(x_j))$
|
101 |
+
"""
|
102 |
+
return softmax_n_shifted_zeros(input, 1, dim=dim)
|
103 |
+
|
104 |
+
|
105 |
+
def clipped_softmax(data, dim=1, eta=1.1, gamma=-0.1, **kw):
|
106 |
+
sm_out = torch.nn.functional.softmax(data, dim=dim, **kw)
|
107 |
+
stretched_out = sm_out * (eta - gamma) + gamma
|
108 |
+
return torch.clip(stretched_out, 0, 1)
|
109 |
+
def clipped_softmax1(data, dim=1, eta=1.1, gamma=-0.1, **kw):
|
110 |
+
sm_out = softmax_1(data, dim=dim, **kw)
|
111 |
+
stretched_out = sm_out * (eta - gamma) + gamma
|
112 |
+
return torch.clip(stretched_out, 0, 1)
|
113 |
+
|
114 |
+
class ViTEmbeddings(nn.Module):
|
115 |
+
"""
|
116 |
+
Construct the CLS token, position and patch embeddings. Optionally, also the mask token.
|
117 |
+
"""
|
118 |
+
|
119 |
+
def __init__(self, config: ViTConfig, use_mask_token: bool = False) -> None:
|
120 |
+
super().__init__()
|
121 |
+
|
122 |
+
self.cls_token = nn.Parameter(torch.randn(1, 1, config.hidden_size))
|
123 |
+
self.mask_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size)) if use_mask_token else None
|
124 |
+
self.patch_embeddings = ViTPatchEmbeddings(config)
|
125 |
+
num_patches = self.patch_embeddings.num_patches
|
126 |
+
self.position_embeddings = nn.Parameter(torch.randn(1, num_patches + 1, config.hidden_size))
|
127 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
128 |
+
self.config = config
|
129 |
+
|
130 |
+
def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
|
131 |
+
"""
|
132 |
+
This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher
|
133 |
+
resolution images.
|
134 |
+
|
135 |
+
Source:
|
136 |
+
https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174
|
137 |
+
"""
|
138 |
+
|
139 |
+
num_patches = embeddings.shape[1] - 1
|
140 |
+
num_positions = self.position_embeddings.shape[1] - 1
|
141 |
+
if num_patches == num_positions and height == width:
|
142 |
+
return self.position_embeddings
|
143 |
+
class_pos_embed = self.position_embeddings[:, 0]
|
144 |
+
patch_pos_embed = self.position_embeddings[:, 1:]
|
145 |
+
dim = embeddings.shape[-1]
|
146 |
+
h0 = height // self.config.patch_size
|
147 |
+
w0 = width // self.config.patch_size
|
148 |
+
# we add a small number to avoid floating point error in the interpolation
|
149 |
+
# see discussion at https://github.com/facebookresearch/dino/issues/8
|
150 |
+
h0, w0 = h0 + 0.1, w0 + 0.1
|
151 |
+
patch_pos_embed = patch_pos_embed.reshape(1, int(math.sqrt(num_positions)), int(math.sqrt(num_positions)), dim)
|
152 |
+
patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
|
153 |
+
patch_pos_embed = nn.functional.interpolate(
|
154 |
+
patch_pos_embed,
|
155 |
+
scale_factor=(h0 / math.sqrt(num_positions), w0 / math.sqrt(num_positions)),
|
156 |
+
mode="bicubic",
|
157 |
+
align_corners=False,
|
158 |
+
)
|
159 |
+
assert int(h0) == patch_pos_embed.shape[-2] and int(w0) == patch_pos_embed.shape[-1]
|
160 |
+
patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
|
161 |
+
return torch.cat((class_pos_embed.unsqueeze(0), patch_pos_embed), dim=1)
|
162 |
+
|
163 |
+
def forward(
|
164 |
+
self,
|
165 |
+
pixel_values: torch.Tensor,
|
166 |
+
bool_masked_pos: Optional[torch.BoolTensor] = None,
|
167 |
+
interpolate_pos_encoding: bool = False,
|
168 |
+
) -> torch.Tensor:
|
169 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
170 |
+
embeddings = self.patch_embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
|
171 |
+
|
172 |
+
if bool_masked_pos is not None:
|
173 |
+
seq_length = embeddings.shape[1]
|
174 |
+
mask_tokens = self.mask_token.expand(batch_size, seq_length, -1)
|
175 |
+
# replace the masked visual tokens by mask_tokens
|
176 |
+
mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
|
177 |
+
embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
|
178 |
+
|
179 |
+
# add the [CLS] token to the embedded patch tokens
|
180 |
+
cls_tokens = self.cls_token.expand(batch_size, -1, -1)
|
181 |
+
embeddings = torch.cat((cls_tokens, embeddings), dim=1)
|
182 |
+
|
183 |
+
# add positional encoding to each token
|
184 |
+
if interpolate_pos_encoding:
|
185 |
+
embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
|
186 |
+
else:
|
187 |
+
embeddings = embeddings + self.position_embeddings
|
188 |
+
|
189 |
+
embeddings = self.dropout(embeddings)
|
190 |
+
|
191 |
+
return embeddings
|
192 |
+
|
193 |
+
|
194 |
+
class ViTPatchEmbeddings(nn.Module):
|
195 |
+
"""
|
196 |
+
This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
|
197 |
+
`hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
|
198 |
+
Transformer.
|
199 |
+
"""
|
200 |
+
|
201 |
+
def __init__(self, config):
|
202 |
+
super().__init__()
|
203 |
+
image_size, patch_size = config.image_size, config.patch_size
|
204 |
+
num_channels, hidden_size = config.num_channels, config.hidden_size
|
205 |
+
|
206 |
+
image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
|
207 |
+
patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
|
208 |
+
num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
|
209 |
+
self.image_size = image_size
|
210 |
+
self.patch_size = patch_size
|
211 |
+
self.num_channels = num_channels
|
212 |
+
self.num_patches = num_patches
|
213 |
+
|
214 |
+
self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
|
215 |
+
|
216 |
+
def forward(self, pixel_values: torch.Tensor, interpolate_pos_encoding: bool = False) -> torch.Tensor:
|
217 |
+
batch_size, num_channels, height, width = pixel_values.shape
|
218 |
+
if num_channels != self.num_channels:
|
219 |
+
raise ValueError(
|
220 |
+
"Make sure that the channel dimension of the pixel values match with the one set in the configuration."
|
221 |
+
f" Expected {self.num_channels} but got {num_channels}."
|
222 |
+
)
|
223 |
+
if not interpolate_pos_encoding:
|
224 |
+
if height != self.image_size[0] or width != self.image_size[1]:
|
225 |
+
raise ValueError(
|
226 |
+
f"Input image size ({height}*{width}) doesn't match model"
|
227 |
+
f" ({self.image_size[0]}*{self.image_size[1]})."
|
228 |
+
)
|
229 |
+
embeddings = self.projection(pixel_values).flatten(2).transpose(1, 2)
|
230 |
+
return embeddings
|
231 |
+
|
232 |
+
|
233 |
+
class ViTSelfAttention(nn.Module):
|
234 |
+
def __init__(self, config: ViTConfig,
|
235 |
+
gamma=None,
|
236 |
+
ssm_eps=None,
|
237 |
+
tau=None,
|
238 |
+
skip_attn=False,
|
239 |
+
attn_gate_type=AttentionGateType.conditional_per_token,
|
240 |
+
attn_gate_init=0.25,
|
241 |
+
attn_gate_mlp=False,
|
242 |
+
attn_gate_mlp2=False,
|
243 |
+
max_seq_length=None,
|
244 |
+
fine_tuning=False,
|
245 |
+
attn_gate_linear_all_features=False) -> None:
|
246 |
+
super().__init__()
|
247 |
+
if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
|
248 |
+
raise ValueError(
|
249 |
+
f"The hidden size {config.hidden_size,} is not a multiple of the number of attention "
|
250 |
+
f"heads {config.num_attention_heads}."
|
251 |
+
)
|
252 |
+
|
253 |
+
self.num_attention_heads = config.num_attention_heads
|
254 |
+
self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
|
255 |
+
self.all_head_size = self.num_attention_heads * self.attention_head_size
|
256 |
+
self.softmax_fn = softmax_1
|
257 |
+
self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
258 |
+
self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
259 |
+
self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
|
260 |
+
|
261 |
+
self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
|
262 |
+
self.gamma = gamma
|
263 |
+
self.ssm_eps = ssm_eps
|
264 |
+
self.tau = tau
|
265 |
+
self.max_seq_length = max_seq_length
|
266 |
+
|
267 |
+
# define softmax function
|
268 |
+
|
269 |
+
self.skip_attn = skip_attn
|
270 |
+
|
271 |
+
# attention gating
|
272 |
+
self.last_gate_avg_prob = None
|
273 |
+
self.last_gate_all_probs = None
|
274 |
+
|
275 |
+
self.attn_gate_type = attn_gate_type
|
276 |
+
self.attn_gate_init = attn_gate_init
|
277 |
+
self.attn_gate_mlp = attn_gate_mlp
|
278 |
+
self.attn_gate_mlp2 = attn_gate_mlp2
|
279 |
+
self.attn_gate_linear_all_features = attn_gate_linear_all_features
|
280 |
+
|
281 |
+
self.alpha = None
|
282 |
+
self.gate_fn = torch.sigmoid
|
283 |
+
self.pooling_fn = partial(torch.mean, dim=1, keepdims=True)
|
284 |
+
|
285 |
+
self.fine_tuning = fine_tuning
|
286 |
+
|
287 |
+
# gate scaling factor
|
288 |
+
self.gate_scaling_factor = 1.0
|
289 |
+
if self.fine_tuning and self.attn_gate_init is not None:
|
290 |
+
self.gate_scaling_factor = 1.0 / self.attn_gate_init
|
291 |
+
|
292 |
+
# define gate
|
293 |
+
if self.attn_gate_type == AttentionGateType.unconditional_per_head:
|
294 |
+
init_alpha = torch.zeros(size=(self.num_attention_heads,))
|
295 |
+
self.alpha = nn.Parameter(init_alpha, requires_grad=True)
|
296 |
+
|
297 |
+
elif self.attn_gate_type in (
|
298 |
+
AttentionGateType.conditional_per_head,
|
299 |
+
AttentionGateType.conditional_per_token,
|
300 |
+
):
|
301 |
+
if self.attn_gate_linear_all_features:
|
302 |
+
self.alpha = nn.Linear(self.all_head_size, self.num_attention_heads, bias=True)
|
303 |
+
|
304 |
+
else: # separate predictors for each head
|
305 |
+
module_list = []
|
306 |
+
for _ in range(self.num_attention_heads):
|
307 |
+
if self.attn_gate_mlp:
|
308 |
+
fc = nn.Sequential(
|
309 |
+
nn.Linear(
|
310 |
+
self.attention_head_size, self.attention_head_size // 4, bias=True
|
311 |
+
),
|
312 |
+
nn.ReLU(),
|
313 |
+
nn.Linear(self.attention_head_size // 4, 1, bias=True),
|
314 |
+
)
|
315 |
+
elif self.attn_gate_mlp2:
|
316 |
+
fc = nn.Sequential(
|
317 |
+
nn.Linear(
|
318 |
+
self.attention_head_size, self.attention_head_size, bias=True
|
319 |
+
),
|
320 |
+
nn.ReLU(),
|
321 |
+
nn.Linear(self.attention_head_size, 1, bias=True),
|
322 |
+
)
|
323 |
+
else:
|
324 |
+
fc = nn.Linear(self.attention_head_size, 1, bias=True)
|
325 |
+
|
326 |
+
if self.attn_gate_init is not None:
|
327 |
+
init_bias = logit(self.attn_gate_init)
|
328 |
+
torch.nn.init.constant_(fc.bias, init_bias)
|
329 |
+
|
330 |
+
if self.fine_tuning:
|
331 |
+
# init to a very small values
|
332 |
+
torch.nn.init.normal_(fc.weight, mean=0.0, std=0.01)
|
333 |
+
|
334 |
+
module_list.append(fc)
|
335 |
+
self.alpha = nn.ModuleList(module_list)
|
336 |
+
|
337 |
+
|
338 |
+
def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
|
339 |
+
new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
|
340 |
+
x = x.view(new_x_shape)
|
341 |
+
return x.permute(0, 2, 1, 3)
|
342 |
+
|
343 |
+
def forward(
|
344 |
+
self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False
|
345 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
346 |
+
mixed_query_layer = self.query(hidden_states)
|
347 |
+
|
348 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
349 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
350 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
351 |
+
|
352 |
+
# Take the dot product between "query" and "key" to get the raw attention scores.
|
353 |
+
attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
|
354 |
+
|
355 |
+
attention_scores = attention_scores / math.sqrt(self.attention_head_size)
|
356 |
+
|
357 |
+
# Normalize the attention scores to probabilities.
|
358 |
+
attention_probs = self.softmax_fn(attention_scores, dim=-1)
|
359 |
+
|
360 |
+
# This is actually dropping out entire tokens to attend to, which might
|
361 |
+
# seem a bit unusual, but is taken from the original Transformer paper.
|
362 |
+
attention_probs = self.dropout(attention_probs)
|
363 |
+
|
364 |
+
# Mask heads if we want to
|
365 |
+
if head_mask is not None:
|
366 |
+
attention_probs = attention_probs * head_mask
|
367 |
+
|
368 |
+
context_layer = torch.matmul(attention_probs, value_layer)
|
369 |
+
|
370 |
+
|
371 |
+
# *** Gating ***
|
372 |
+
if self.attn_gate_type == AttentionGateType.unconditional_per_head:
|
373 |
+
gate = self.gate_fn(self.alpha) # (H,)
|
374 |
+
context_layer *= gate.view(-1, 1, 1) # (B, H, T, d_head)
|
375 |
+
|
376 |
+
self.last_gate_avg_prob = gate.view(-1)
|
377 |
+
|
378 |
+
elif self.attn_gate_type in (
|
379 |
+
AttentionGateType.conditional_per_head,
|
380 |
+
AttentionGateType.conditional_per_token,
|
381 |
+
):
|
382 |
+
|
383 |
+
x = hidden_states
|
384 |
+
|
385 |
+
if self.attn_gate_linear_all_features: # assume per_token
|
386 |
+
alpha = self.alpha(x) # (B, T, H)
|
387 |
+
gate = self.gate_fn(alpha)
|
388 |
+
gate = gate.permute(0, 2, 1).contiguous() # (B, H, T)
|
389 |
+
gate = gate.unsqueeze(3) # (B, H, T, 1)
|
390 |
+
|
391 |
+
else:
|
392 |
+
x = self.transpose_for_scores(x) # (B, H, T, d_head)
|
393 |
+
|
394 |
+
alpha = []
|
395 |
+
for head_idx in range(self.num_attention_heads):
|
396 |
+
x_head = x[:, head_idx, ...] # (B, T, d_head)
|
397 |
+
fc_head = self.alpha[head_idx]
|
398 |
+
alpha_head = fc_head(x_head) # (B, T, 1)
|
399 |
+
if self.attn_gate_type == AttentionGateType.conditional_per_head:
|
400 |
+
alpha_head = self.pooling_fn(alpha_head) # (B, 1, 1)
|
401 |
+
alpha.append(alpha_head)
|
402 |
+
alpha = torch.stack(alpha, dim=1) # (B, H, *, 1)
|
403 |
+
gate = self.gate_fn(alpha)
|
404 |
+
|
405 |
+
context_layer *= gate * self.gate_scaling_factor
|
406 |
+
|
407 |
+
self.last_gate_all_probs = gate # all gates to see the distributions
|
408 |
+
avg_gate = gate.mean(dim=0)
|
409 |
+
self.last_gate_avg_prob = avg_gate.view(self.num_attention_heads, -1).mean(dim=1)
|
410 |
+
|
411 |
+
|
412 |
+
|
413 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
414 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
415 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
416 |
+
|
417 |
+
outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
|
418 |
+
|
419 |
+
return outputs
|
420 |
+
|
421 |
+
def scaled_dot_product_attention(query, key, value, softmax_fn, attn_mask=None, dropout_p=0.0, is_causal=False, scale=None) -> torch.Tensor:
|
422 |
+
# Efficient implementation equivalent to the following:
|
423 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
424 |
+
L, S = query.size(-2), key.size(-2)
|
425 |
+
scale_factor = 1 / math.sqrt(query.size(-1)) if scale is None else scale
|
426 |
+
attn_bias = torch.zeros(L, S, dtype=query.dtype, device=query.device)
|
427 |
+
if is_causal:
|
428 |
+
assert attn_mask is None
|
429 |
+
temp_mask = torch.ones(L, S, dtype=torch.bool).tril(diagonal=0)
|
430 |
+
attn_bias.masked_fill_(temp_mask.logical_not(), float("-inf"))
|
431 |
+
attn_bias.to(query.dtype)
|
432 |
+
|
433 |
+
if attn_mask is not None:
|
434 |
+
if attn_mask.dtype == torch.bool:
|
435 |
+
attn_mask.masked_fill_(attn_mask.logical_not(), float("-inf"))
|
436 |
+
else:
|
437 |
+
attn_bias += attn_mask
|
438 |
+
attn_weight = query @ key.transpose(-2, -1) * scale_factor
|
439 |
+
attn_weight += attn_bias
|
440 |
+
attn_weight = softmax_fn(attn_weight, dim=-1)
|
441 |
+
attn_weight = torch.dropout(attn_weight, dropout_p, train=True)
|
442 |
+
return attn_weight @ value
|
443 |
+
|
444 |
+
class ViTSdpaSelfAttention(ViTSelfAttention):
|
445 |
+
def __init__(self, config: ViTConfig) -> None:
|
446 |
+
super().__init__(config)
|
447 |
+
self.attention_probs_dropout_prob = config.attention_probs_dropout_prob
|
448 |
+
|
449 |
+
def forward(
|
450 |
+
self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False
|
451 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
452 |
+
mixed_query_layer = self.query(hidden_states)
|
453 |
+
|
454 |
+
key_layer = self.transpose_for_scores(self.key(hidden_states))
|
455 |
+
value_layer = self.transpose_for_scores(self.value(hidden_states))
|
456 |
+
query_layer = self.transpose_for_scores(mixed_query_layer)
|
457 |
+
|
458 |
+
context_layer = scaled_dot_product_attention(
|
459 |
+
query_layer,
|
460 |
+
key_layer,
|
461 |
+
value_layer,
|
462 |
+
dropout_p=self.attention_probs_dropout_prob if self.training else 0.0,
|
463 |
+
attn_mask=head_mask,
|
464 |
+
softmax_fn = self.softmax_fn,
|
465 |
+
is_causal=False,
|
466 |
+
scale=None,
|
467 |
+
)
|
468 |
+
|
469 |
+
context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
|
470 |
+
new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
|
471 |
+
context_layer = context_layer.view(new_context_layer_shape)
|
472 |
+
|
473 |
+
return context_layer, None
|
474 |
+
|
475 |
+
|
476 |
+
class ViTSelfOutput(nn.Module):
|
477 |
+
"""
|
478 |
+
The residual connection is defined in ViTLayer instead of here (as is the case with other models), due to the
|
479 |
+
layernorm applied before each block.
|
480 |
+
"""
|
481 |
+
|
482 |
+
def __init__(self, config: ViTConfig) -> None:
|
483 |
+
super().__init__()
|
484 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
485 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
486 |
+
|
487 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
488 |
+
hidden_states = self.dense(hidden_states)
|
489 |
+
hidden_states = self.dropout(hidden_states)
|
490 |
+
|
491 |
+
return hidden_states
|
492 |
+
|
493 |
+
|
494 |
+
class ViTAttention(nn.Module):
|
495 |
+
def __init__(self, config: ViTConfig) -> None:
|
496 |
+
super().__init__()
|
497 |
+
self.attention = ViTSelfAttention(config)
|
498 |
+
self.output = ViTSelfOutput(config)
|
499 |
+
self.pruned_heads = set()
|
500 |
+
|
501 |
+
def prune_heads(self, heads: Set[int]) -> None:
|
502 |
+
if len(heads) == 0:
|
503 |
+
return
|
504 |
+
heads, index = find_pruneable_heads_and_indices(
|
505 |
+
heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
|
506 |
+
)
|
507 |
+
|
508 |
+
# Prune linear layers
|
509 |
+
self.attention.query = prune_linear_layer(self.attention.query, index)
|
510 |
+
self.attention.key = prune_linear_layer(self.attention.key, index)
|
511 |
+
self.attention.value = prune_linear_layer(self.attention.value, index)
|
512 |
+
self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
|
513 |
+
|
514 |
+
# Update hyper params and store pruned heads
|
515 |
+
self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
|
516 |
+
self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
|
517 |
+
self.pruned_heads = self.pruned_heads.union(heads)
|
518 |
+
|
519 |
+
def forward(
|
520 |
+
self,
|
521 |
+
hidden_states: torch.Tensor,
|
522 |
+
head_mask: Optional[torch.Tensor] = None,
|
523 |
+
output_attentions: bool = False,
|
524 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
525 |
+
self_outputs = self.attention(hidden_states, head_mask, output_attentions)
|
526 |
+
|
527 |
+
attention_output = self.output(self_outputs[0], hidden_states)
|
528 |
+
|
529 |
+
outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
|
530 |
+
return outputs
|
531 |
+
|
532 |
+
|
533 |
+
class ViTSdpaAttention(ViTAttention):
|
534 |
+
def __init__(self, config: ViTConfig) -> None:
|
535 |
+
super().__init__(config)
|
536 |
+
self.attention = ViTSdpaSelfAttention(config)
|
537 |
+
|
538 |
+
|
539 |
+
class ViTIntermediate(nn.Module):
|
540 |
+
def __init__(self, config: ViTConfig) -> None:
|
541 |
+
super().__init__()
|
542 |
+
self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
|
543 |
+
if isinstance(config.hidden_act, str):
|
544 |
+
self.intermediate_act_fn = ACT2FN[config.hidden_act]
|
545 |
+
else:
|
546 |
+
self.intermediate_act_fn = config.hidden_act
|
547 |
+
|
548 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
549 |
+
hidden_states = self.dense(hidden_states)
|
550 |
+
hidden_states = self.intermediate_act_fn(hidden_states)
|
551 |
+
|
552 |
+
return hidden_states
|
553 |
+
|
554 |
+
|
555 |
+
class ViTOutput(nn.Module):
|
556 |
+
def __init__(self, config: ViTConfig) -> None:
|
557 |
+
super().__init__()
|
558 |
+
self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
|
559 |
+
self.dropout = nn.Dropout(config.hidden_dropout_prob)
|
560 |
+
|
561 |
+
def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
|
562 |
+
hidden_states = self.dense(hidden_states)
|
563 |
+
hidden_states = self.dropout(hidden_states)
|
564 |
+
|
565 |
+
hidden_states = hidden_states + input_tensor
|
566 |
+
|
567 |
+
return hidden_states
|
568 |
+
|
569 |
+
|
570 |
+
VIT_ATTENTION_CLASSES = {
|
571 |
+
"eager": ViTAttention,
|
572 |
+
"sdpa": ViTSdpaAttention,
|
573 |
+
}
|
574 |
+
|
575 |
+
|
576 |
+
class ViTLayer(nn.Module):
|
577 |
+
"""This corresponds to the Block class in the timm implementation."""
|
578 |
+
|
579 |
+
def __init__(self, config: ViTConfig) -> None:
|
580 |
+
super().__init__()
|
581 |
+
self.chunk_size_feed_forward = config.chunk_size_feed_forward
|
582 |
+
self.seq_len_dim = 1
|
583 |
+
self.attention = VIT_ATTENTION_CLASSES[config._attn_implementation](config)
|
584 |
+
self.intermediate = ViTIntermediate(config)
|
585 |
+
self.output = ViTOutput(config)
|
586 |
+
self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
587 |
+
self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
588 |
+
|
589 |
+
def forward(
|
590 |
+
self,
|
591 |
+
hidden_states: torch.Tensor,
|
592 |
+
head_mask: Optional[torch.Tensor] = None,
|
593 |
+
output_attentions: bool = False,
|
594 |
+
) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
|
595 |
+
self_attention_outputs = self.attention(
|
596 |
+
self.layernorm_before(hidden_states), # in ViT, layernorm is applied before self-attention
|
597 |
+
head_mask,
|
598 |
+
output_attentions=output_attentions,
|
599 |
+
)
|
600 |
+
attention_output = self_attention_outputs[0]
|
601 |
+
outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
|
602 |
+
|
603 |
+
# first residual connection
|
604 |
+
hidden_states = attention_output + hidden_states
|
605 |
+
|
606 |
+
# in ViT, layernorm is also applied after self-attention
|
607 |
+
layer_output = self.layernorm_after(hidden_states)
|
608 |
+
layer_output = self.intermediate(layer_output)
|
609 |
+
|
610 |
+
# second residual connection is done here
|
611 |
+
layer_output = self.output(layer_output, hidden_states)
|
612 |
+
|
613 |
+
outputs = (layer_output,) + outputs
|
614 |
+
|
615 |
+
return outputs
|
616 |
+
|
617 |
+
|
618 |
+
class ViTEncoder(nn.Module):
|
619 |
+
def __init__(self, config: ViTConfig) -> None:
|
620 |
+
super().__init__()
|
621 |
+
self.config = config
|
622 |
+
self.layer = nn.ModuleList([ViTLayer(config) for _ in range(config.num_hidden_layers)])
|
623 |
+
self.gradient_checkpointing = False
|
624 |
+
|
625 |
+
def forward(
|
626 |
+
self,
|
627 |
+
hidden_states: torch.Tensor,
|
628 |
+
head_mask: Optional[torch.Tensor] = None,
|
629 |
+
output_attentions: bool = False,
|
630 |
+
output_hidden_states: bool = False,
|
631 |
+
return_dict: bool = True,
|
632 |
+
) -> Union[tuple, BaseModelOutput]:
|
633 |
+
all_hidden_states = () if output_hidden_states else None
|
634 |
+
all_self_attentions = () if output_attentions else None
|
635 |
+
|
636 |
+
for i, layer_module in enumerate(self.layer):
|
637 |
+
if output_hidden_states:
|
638 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
639 |
+
|
640 |
+
layer_head_mask = head_mask[i] if head_mask is not None else None
|
641 |
+
|
642 |
+
if self.gradient_checkpointing and self.training:
|
643 |
+
layer_outputs = self._gradient_checkpointing_func(
|
644 |
+
layer_module.__call__,
|
645 |
+
hidden_states,
|
646 |
+
layer_head_mask,
|
647 |
+
output_attentions,
|
648 |
+
)
|
649 |
+
else:
|
650 |
+
layer_outputs = layer_module(hidden_states, layer_head_mask, output_attentions)
|
651 |
+
|
652 |
+
hidden_states = layer_outputs[0]
|
653 |
+
|
654 |
+
if output_attentions:
|
655 |
+
all_self_attentions = all_self_attentions + (layer_outputs[1],)
|
656 |
+
|
657 |
+
if output_hidden_states:
|
658 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
659 |
+
|
660 |
+
if not return_dict:
|
661 |
+
return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
|
662 |
+
return BaseModelOutput(
|
663 |
+
last_hidden_state=hidden_states,
|
664 |
+
hidden_states=all_hidden_states,
|
665 |
+
attentions=all_self_attentions,
|
666 |
+
)
|
667 |
+
|
668 |
+
|
669 |
+
class ViTPreTrainedModel(PreTrainedModel):
|
670 |
+
"""
|
671 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
672 |
+
models.
|
673 |
+
"""
|
674 |
+
|
675 |
+
config_class = ViTConfig
|
676 |
+
base_model_prefix = "vit"
|
677 |
+
main_input_name = "pixel_values"
|
678 |
+
supports_gradient_checkpointing = True
|
679 |
+
_no_split_modules = ["ViTEmbeddings", "ViTLayer"]
|
680 |
+
_supports_sdpa = True
|
681 |
+
|
682 |
+
def _init_weights(self, module: Union[nn.Linear, nn.Conv2d, nn.LayerNorm]) -> None:
|
683 |
+
"""Initialize the weights"""
|
684 |
+
if isinstance(module, (nn.Linear, nn.Conv2d)):
|
685 |
+
# Upcast the input in `fp32` and cast it back to desired `dtype` to avoid
|
686 |
+
# `trunc_normal_cpu` not implemented in `half` issues
|
687 |
+
module.weight.data = nn.init.trunc_normal_(
|
688 |
+
module.weight.data.to(torch.float32), mean=0.0, std=self.config.initializer_range
|
689 |
+
).to(module.weight.dtype)
|
690 |
+
if module.bias is not None:
|
691 |
+
module.bias.data.zero_()
|
692 |
+
elif isinstance(module, nn.LayerNorm):
|
693 |
+
module.bias.data.zero_()
|
694 |
+
module.weight.data.fill_(1.0)
|
695 |
+
elif isinstance(module, ViTEmbeddings):
|
696 |
+
module.position_embeddings.data = nn.init.trunc_normal_(
|
697 |
+
module.position_embeddings.data.to(torch.float32),
|
698 |
+
mean=0.0,
|
699 |
+
std=self.config.initializer_range,
|
700 |
+
).to(module.position_embeddings.dtype)
|
701 |
+
|
702 |
+
module.cls_token.data = nn.init.trunc_normal_(
|
703 |
+
module.cls_token.data.to(torch.float32),
|
704 |
+
mean=0.0,
|
705 |
+
std=self.config.initializer_range,
|
706 |
+
).to(module.cls_token.dtype)
|
707 |
+
|
708 |
+
|
709 |
+
VIT_START_DOCSTRING = r"""
|
710 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
|
711 |
+
as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
712 |
+
behavior.
|
713 |
+
|
714 |
+
Parameters:
|
715 |
+
config ([`ViTConfig`]): Model configuration class with all the parameters of the model.
|
716 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
717 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
718 |
+
"""
|
719 |
+
|
720 |
+
VIT_INPUTS_DOCSTRING = r"""
|
721 |
+
Args:
|
722 |
+
pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
|
723 |
+
Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`ViTImageProcessor.__call__`]
|
724 |
+
for details.
|
725 |
+
|
726 |
+
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
|
727 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
728 |
+
|
729 |
+
- 1 indicates the head is **not masked**,
|
730 |
+
- 0 indicates the head is **masked**.
|
731 |
+
|
732 |
+
output_attentions (`bool`, *optional*):
|
733 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
734 |
+
tensors for more detail.
|
735 |
+
output_hidden_states (`bool`, *optional*):
|
736 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
737 |
+
more detail.
|
738 |
+
interpolate_pos_encoding (`bool`, *optional*):
|
739 |
+
Whether to interpolate the pre-trained position encodings.
|
740 |
+
return_dict (`bool`, *optional*):
|
741 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
742 |
+
"""
|
743 |
+
|
744 |
+
|
745 |
+
@add_start_docstrings(
|
746 |
+
"The bare ViT Model transformer outputting raw hidden-states without any specific head on top.",
|
747 |
+
VIT_START_DOCSTRING,
|
748 |
+
)
|
749 |
+
class ViTModel(ViTPreTrainedModel):
|
750 |
+
def __init__(self, config: ViTConfig, add_pooling_layer: bool = True, use_mask_token: bool = False):
|
751 |
+
super().__init__(config)
|
752 |
+
self.config = config
|
753 |
+
|
754 |
+
self.embeddings = ViTEmbeddings(config, use_mask_token=use_mask_token)
|
755 |
+
self.encoder = ViTEncoder(config)
|
756 |
+
|
757 |
+
self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
|
758 |
+
self.pooler = ViTPooler(config) if add_pooling_layer else None
|
759 |
+
|
760 |
+
# Initialize weights and apply final processing
|
761 |
+
self.post_init()
|
762 |
+
|
763 |
+
def get_input_embeddings(self) -> ViTPatchEmbeddings:
|
764 |
+
return self.embeddings.patch_embeddings
|
765 |
+
|
766 |
+
def _prune_heads(self, heads_to_prune: Dict[int, List[int]]) -> None:
|
767 |
+
"""
|
768 |
+
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
|
769 |
+
class PreTrainedModel
|
770 |
+
"""
|
771 |
+
for layer, heads in heads_to_prune.items():
|
772 |
+
self.encoder.layer[layer].attention.prune_heads(heads)
|
773 |
+
|
774 |
+
@add_start_docstrings_to_model_forward(VIT_INPUTS_DOCSTRING)
|
775 |
+
@add_code_sample_docstrings(
|
776 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
777 |
+
output_type=BaseModelOutputWithPooling,
|
778 |
+
config_class=_CONFIG_FOR_DOC,
|
779 |
+
modality="vision",
|
780 |
+
expected_output=_EXPECTED_OUTPUT_SHAPE,
|
781 |
+
)
|
782 |
+
def forward(
|
783 |
+
self,
|
784 |
+
pixel_values: Optional[torch.Tensor] = None,
|
785 |
+
bool_masked_pos: Optional[torch.BoolTensor] = None,
|
786 |
+
head_mask: Optional[torch.Tensor] = None,
|
787 |
+
output_attentions: Optional[bool] = None,
|
788 |
+
output_hidden_states: Optional[bool] = None,
|
789 |
+
interpolate_pos_encoding: Optional[bool] = None,
|
790 |
+
return_dict: Optional[bool] = None,
|
791 |
+
) -> Union[Tuple, BaseModelOutputWithPooling]:
|
792 |
+
r"""
|
793 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`, *optional*):
|
794 |
+
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
|
795 |
+
"""
|
796 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
797 |
+
output_hidden_states = (
|
798 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
799 |
+
)
|
800 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
801 |
+
|
802 |
+
if pixel_values is None:
|
803 |
+
raise ValueError("You have to specify pixel_values")
|
804 |
+
|
805 |
+
# Prepare head mask if needed
|
806 |
+
# 1.0 in head_mask indicate we keep the head
|
807 |
+
# attention_probs has shape bsz x n_heads x N x N
|
808 |
+
# input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
|
809 |
+
# and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
|
810 |
+
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
|
811 |
+
|
812 |
+
# TODO: maybe have a cleaner way to cast the input (from `ImageProcessor` side?)
|
813 |
+
expected_dtype = self.embeddings.patch_embeddings.projection.weight.dtype
|
814 |
+
if pixel_values.dtype != expected_dtype:
|
815 |
+
pixel_values = pixel_values.to(expected_dtype)
|
816 |
+
|
817 |
+
embedding_output = self.embeddings(
|
818 |
+
pixel_values, bool_masked_pos=bool_masked_pos, interpolate_pos_encoding=interpolate_pos_encoding
|
819 |
+
)
|
820 |
+
|
821 |
+
encoder_outputs = self.encoder(
|
822 |
+
embedding_output,
|
823 |
+
head_mask=head_mask,
|
824 |
+
output_attentions=output_attentions,
|
825 |
+
output_hidden_states=output_hidden_states,
|
826 |
+
return_dict=return_dict,
|
827 |
+
)
|
828 |
+
sequence_output = encoder_outputs[0]
|
829 |
+
sequence_output = self.layernorm(sequence_output)
|
830 |
+
pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
|
831 |
+
|
832 |
+
if not return_dict:
|
833 |
+
head_outputs = (sequence_output, pooled_output) if pooled_output is not None else (sequence_output,)
|
834 |
+
return head_outputs + encoder_outputs[1:]
|
835 |
+
|
836 |
+
return BaseModelOutputWithPooling(
|
837 |
+
last_hidden_state=sequence_output,
|
838 |
+
pooler_output=pooled_output,
|
839 |
+
hidden_states=encoder_outputs.hidden_states,
|
840 |
+
attentions=encoder_outputs.attentions,
|
841 |
+
)
|
842 |
+
|
843 |
+
|
844 |
+
class ViTPooler(nn.Module):
|
845 |
+
def __init__(self, config: ViTConfig):
|
846 |
+
super().__init__()
|
847 |
+
self.dense = nn.Linear(config.hidden_size, config.hidden_size)
|
848 |
+
self.activation = nn.Tanh()
|
849 |
+
|
850 |
+
def forward(self, hidden_states):
|
851 |
+
# We "pool" the model by simply taking the hidden state corresponding
|
852 |
+
# to the first token.
|
853 |
+
first_token_tensor = hidden_states[:, 0]
|
854 |
+
pooled_output = self.dense(first_token_tensor)
|
855 |
+
pooled_output = self.activation(pooled_output)
|
856 |
+
return pooled_output
|
857 |
+
|
858 |
+
|
859 |
+
@add_start_docstrings(
|
860 |
+
"""ViT Model with a decoder on top for masked image modeling, as proposed in [SimMIM](https://arxiv.org/abs/2111.09886).
|
861 |
+
|
862 |
+
<Tip>
|
863 |
+
|
864 |
+
Note that we provide a script to pre-train this model on custom data in our [examples
|
865 |
+
directory](https://github.com/huggingface/transformers/tree/main/examples/pytorch/image-pretraining).
|
866 |
+
|
867 |
+
</Tip>
|
868 |
+
""",
|
869 |
+
VIT_START_DOCSTRING,
|
870 |
+
)
|
871 |
+
class ViTForMaskedImageModeling(ViTPreTrainedModel):
|
872 |
+
def __init__(self, config: ViTConfig) -> None:
|
873 |
+
super().__init__(config)
|
874 |
+
|
875 |
+
self.vit = ViTModel(config, add_pooling_layer=False, use_mask_token=True)
|
876 |
+
|
877 |
+
self.decoder = nn.Sequential(
|
878 |
+
nn.Conv2d(
|
879 |
+
in_channels=config.hidden_size,
|
880 |
+
out_channels=config.encoder_stride**2 * config.num_channels,
|
881 |
+
kernel_size=1,
|
882 |
+
),
|
883 |
+
nn.PixelShuffle(config.encoder_stride),
|
884 |
+
)
|
885 |
+
|
886 |
+
# Initialize weights and apply final processing
|
887 |
+
self.post_init()
|
888 |
+
|
889 |
+
@add_start_docstrings_to_model_forward(VIT_INPUTS_DOCSTRING)
|
890 |
+
@replace_return_docstrings(output_type=MaskedImageModelingOutput, config_class=_CONFIG_FOR_DOC)
|
891 |
+
def forward(
|
892 |
+
self,
|
893 |
+
pixel_values: Optional[torch.Tensor] = None,
|
894 |
+
bool_masked_pos: Optional[torch.BoolTensor] = None,
|
895 |
+
head_mask: Optional[torch.Tensor] = None,
|
896 |
+
output_attentions: Optional[bool] = None,
|
897 |
+
output_hidden_states: Optional[bool] = None,
|
898 |
+
interpolate_pos_encoding: Optional[bool] = None,
|
899 |
+
return_dict: Optional[bool] = None,
|
900 |
+
) -> Union[tuple, MaskedImageModelingOutput]:
|
901 |
+
r"""
|
902 |
+
bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
|
903 |
+
Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
|
904 |
+
|
905 |
+
Returns:
|
906 |
+
|
907 |
+
Examples:
|
908 |
+
```python
|
909 |
+
>>> from transformers import AutoImageProcessor, ViTForMaskedImageModeling
|
910 |
+
>>> import torch
|
911 |
+
>>> from PIL import Image
|
912 |
+
>>> import requests
|
913 |
+
|
914 |
+
>>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
915 |
+
>>> image = Image.open(requests.get(url, stream=True).raw)
|
916 |
+
|
917 |
+
>>> image_processor = AutoImageProcessor.from_pretrained("google/vit-base-patch16-224-in21k")
|
918 |
+
>>> model = ViTForMaskedImageModeling.from_pretrained("google/vit-base-patch16-224-in21k")
|
919 |
+
|
920 |
+
>>> num_patches = (model.config.image_size // model.config.patch_size) ** 2
|
921 |
+
>>> pixel_values = image_processor(images=image, return_tensors="pt").pixel_values
|
922 |
+
>>> # create random boolean mask of shape (batch_size, num_patches)
|
923 |
+
>>> bool_masked_pos = torch.randint(low=0, high=2, size=(1, num_patches)).bool()
|
924 |
+
|
925 |
+
>>> outputs = model(pixel_values, bool_masked_pos=bool_masked_pos)
|
926 |
+
>>> loss, reconstructed_pixel_values = outputs.loss, outputs.reconstruction
|
927 |
+
>>> list(reconstructed_pixel_values.shape)
|
928 |
+
[1, 3, 224, 224]
|
929 |
+
```"""
|
930 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
931 |
+
|
932 |
+
if bool_masked_pos is not None and (self.config.patch_size != self.config.encoder_stride):
|
933 |
+
raise ValueError(
|
934 |
+
"When `bool_masked_pos` is provided, `patch_size` must be equal to `encoder_stride` to ensure that "
|
935 |
+
"the reconstructed image has the same dimensions as the input. "
|
936 |
+
f"Got `patch_size` = {self.config.patch_size} and `encoder_stride` = {self.config.encoder_stride}."
|
937 |
+
)
|
938 |
+
|
939 |
+
outputs = self.vit(
|
940 |
+
pixel_values,
|
941 |
+
bool_masked_pos=bool_masked_pos,
|
942 |
+
head_mask=head_mask,
|
943 |
+
output_attentions=output_attentions,
|
944 |
+
output_hidden_states=output_hidden_states,
|
945 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
946 |
+
return_dict=return_dict,
|
947 |
+
)
|
948 |
+
|
949 |
+
sequence_output = outputs[0]
|
950 |
+
|
951 |
+
# Reshape to (batch_size, num_channels, height, width)
|
952 |
+
sequence_output = sequence_output[:, 1:]
|
953 |
+
batch_size, sequence_length, num_channels = sequence_output.shape
|
954 |
+
height = width = math.floor(sequence_length**0.5)
|
955 |
+
sequence_output = sequence_output.permute(0, 2, 1).reshape(batch_size, num_channels, height, width)
|
956 |
+
|
957 |
+
# Reconstruct pixel values
|
958 |
+
reconstructed_pixel_values = self.decoder(sequence_output)
|
959 |
+
|
960 |
+
masked_im_loss = None
|
961 |
+
if bool_masked_pos is not None:
|
962 |
+
size = self.config.image_size // self.config.patch_size
|
963 |
+
bool_masked_pos = bool_masked_pos.reshape(-1, size, size)
|
964 |
+
mask = (
|
965 |
+
bool_masked_pos.repeat_interleave(self.config.patch_size, 1)
|
966 |
+
.repeat_interleave(self.config.patch_size, 2)
|
967 |
+
.unsqueeze(1)
|
968 |
+
.contiguous()
|
969 |
+
)
|
970 |
+
reconstruction_loss = nn.functional.l1_loss(pixel_values, reconstructed_pixel_values, reduction="none")
|
971 |
+
masked_im_loss = (reconstruction_loss * mask).sum() / (mask.sum() + 1e-5) / self.config.num_channels
|
972 |
+
|
973 |
+
if not return_dict:
|
974 |
+
output = (reconstructed_pixel_values,) + outputs[1:]
|
975 |
+
return ((masked_im_loss,) + output) if masked_im_loss is not None else output
|
976 |
+
|
977 |
+
return MaskedImageModelingOutput(
|
978 |
+
loss=masked_im_loss,
|
979 |
+
reconstruction=reconstructed_pixel_values,
|
980 |
+
hidden_states=outputs.hidden_states,
|
981 |
+
attentions=outputs.attentions,
|
982 |
+
)
|
983 |
+
|
984 |
+
|
985 |
+
@add_start_docstrings(
|
986 |
+
"""
|
987 |
+
ViT Model transformer with an image classification head on top (a linear layer on top of the final hidden state of
|
988 |
+
the [CLS] token) e.g. for ImageNet.
|
989 |
+
|
990 |
+
<Tip>
|
991 |
+
|
992 |
+
Note that it's possible to fine-tune ViT on higher resolution images than the ones it has been trained on, by
|
993 |
+
setting `interpolate_pos_encoding` to `True` in the forward of the model. This will interpolate the pre-trained
|
994 |
+
position embeddings to the higher resolution.
|
995 |
+
|
996 |
+
</Tip>
|
997 |
+
""",
|
998 |
+
VIT_START_DOCSTRING,
|
999 |
+
)
|
1000 |
+
class ViTForImageClassification(ViTPreTrainedModel):
|
1001 |
+
def __init__(self, config: ViTConfig) -> None:
|
1002 |
+
super().__init__(config)
|
1003 |
+
|
1004 |
+
self.num_labels = config.num_labels
|
1005 |
+
self.vit = ViTModel(config, add_pooling_layer=False)
|
1006 |
+
|
1007 |
+
# Classifier head
|
1008 |
+
self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
|
1009 |
+
|
1010 |
+
# Initialize weights and apply final processing
|
1011 |
+
self.post_init()
|
1012 |
+
|
1013 |
+
@add_start_docstrings_to_model_forward(VIT_INPUTS_DOCSTRING)
|
1014 |
+
@add_code_sample_docstrings(
|
1015 |
+
checkpoint=_IMAGE_CLASS_CHECKPOINT,
|
1016 |
+
output_type=ImageClassifierOutput,
|
1017 |
+
config_class=_CONFIG_FOR_DOC,
|
1018 |
+
expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
|
1019 |
+
)
|
1020 |
+
def forward(
|
1021 |
+
self,
|
1022 |
+
pixel_values: Optional[torch.Tensor] = None,
|
1023 |
+
head_mask: Optional[torch.Tensor] = None,
|
1024 |
+
labels: Optional[torch.Tensor] = None,
|
1025 |
+
output_attentions: Optional[bool] = None,
|
1026 |
+
output_hidden_states: Optional[bool] = None,
|
1027 |
+
interpolate_pos_encoding: Optional[bool] = None,
|
1028 |
+
return_dict: Optional[bool] = None,
|
1029 |
+
) -> Union[tuple, ImageClassifierOutput]:
|
1030 |
+
r"""
|
1031 |
+
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
|
1032 |
+
Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
|
1033 |
+
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
|
1034 |
+
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
|
1035 |
+
"""
|
1036 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
1037 |
+
|
1038 |
+
outputs = self.vit(
|
1039 |
+
pixel_values,
|
1040 |
+
head_mask=head_mask,
|
1041 |
+
output_attentions=output_attentions,
|
1042 |
+
output_hidden_states=output_hidden_states,
|
1043 |
+
interpolate_pos_encoding=interpolate_pos_encoding,
|
1044 |
+
return_dict=return_dict,
|
1045 |
+
)
|
1046 |
+
|
1047 |
+
sequence_output = outputs[0]
|
1048 |
+
|
1049 |
+
logits = self.classifier(sequence_output[:, 0, :])
|
1050 |
+
|
1051 |
+
loss = None
|
1052 |
+
if labels is not None:
|
1053 |
+
# move labels to correct device to enable model parallelism
|
1054 |
+
labels = labels.to(logits.device)
|
1055 |
+
if self.config.problem_type is None:
|
1056 |
+
if self.num_labels == 1:
|
1057 |
+
self.config.problem_type = "regression"
|
1058 |
+
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
|
1059 |
+
self.config.problem_type = "single_label_classification"
|
1060 |
+
else:
|
1061 |
+
self.config.problem_type = "multi_label_classification"
|
1062 |
+
|
1063 |
+
if self.config.problem_type == "regression":
|
1064 |
+
loss_fct = MSELoss()
|
1065 |
+
if self.num_labels == 1:
|
1066 |
+
loss = loss_fct(logits.squeeze(), labels.squeeze())
|
1067 |
+
else:
|
1068 |
+
loss = loss_fct(logits, labels)
|
1069 |
+
elif self.config.problem_type == "single_label_classification":
|
1070 |
+
loss_fct = CrossEntropyLoss()
|
1071 |
+
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
|
1072 |
+
elif self.config.problem_type == "multi_label_classification":
|
1073 |
+
loss_fct = BCEWithLogitsLoss()
|
1074 |
+
loss = loss_fct(logits, labels)
|
1075 |
+
|
1076 |
+
if not return_dict:
|
1077 |
+
output = (logits,) + outputs[1:]
|
1078 |
+
return ((loss,) + output) if loss is not None else output
|
1079 |
+
|
1080 |
+
return ImageClassifierOutput(
|
1081 |
+
loss=loss,
|
1082 |
+
logits=logits,
|
1083 |
+
hidden_states=outputs.hidden_states,
|
1084 |
+
attentions=outputs.attentions,
|
1085 |
+
)
|