robinzixuan commited on
Commit
9f0e988
1 Parent(s): 7612bed

Upload 2 files

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