robinzixuan commited on
Commit
9a50c7a
1 Parent(s): 7e9264f

Upload 2 files

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