robinzixuan commited on
Commit
edd6a9b
1 Parent(s): 3f8c456

Upload 2 files

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