chen459664 commited on
Commit
a1f71da
·
verified ·
1 Parent(s): 4691440

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. SupplementaryMaterial_Code/transformers-4.37.2/models/distilbert/__pycache__/tokenization_distilbert_fast.cpython-310.pyc +0 -0
  2. SupplementaryMaterial_Code/transformers-4.37.2/models/dit/convert_dit_unilm_to_pytorch.py +231 -0
  3. SupplementaryMaterial_Code/transformers-4.37.2/models/donut/__pycache__/__init__.cpython-310.pyc +0 -0
  4. SupplementaryMaterial_Code/transformers-4.37.2/models/donut/__pycache__/processing_donut.cpython-310.pyc +0 -0
  5. SupplementaryMaterial_Code/transformers-4.37.2/models/donut/feature_extraction_donut.py +33 -0
  6. SupplementaryMaterial_Code/transformers-4.37.2/models/donut/modeling_donut_swin.py +952 -0
  7. SupplementaryMaterial_Code/transformers-4.37.2/models/dpr/__init__.py +148 -0
  8. SupplementaryMaterial_Code/transformers-4.37.2/models/dpr/__pycache__/__init__.cpython-310.pyc +0 -0
  9. SupplementaryMaterial_Code/transformers-4.37.2/models/dpr/__pycache__/convert_dpr_original_checkpoint_to_pytorch.cpython-310.pyc +0 -0
  10. SupplementaryMaterial_Code/transformers-4.37.2/models/dpr/__pycache__/modeling_dpr.cpython-310.pyc +0 -0
  11. SupplementaryMaterial_Code/transformers-4.37.2/models/dpr/__pycache__/modeling_tf_dpr.cpython-310.pyc +0 -0
  12. SupplementaryMaterial_Code/transformers-4.37.2/models/dpr/__pycache__/tokenization_dpr.cpython-310.pyc +0 -0
  13. SupplementaryMaterial_Code/transformers-4.37.2/models/dpr/__pycache__/tokenization_dpr_fast.cpython-310.pyc +0 -0
  14. SupplementaryMaterial_Code/transformers-4.37.2/models/dpr/configuration_dpr.py +149 -0
  15. SupplementaryMaterial_Code/transformers-4.37.2/models/dpr/modeling_dpr.py +669 -0
  16. SupplementaryMaterial_Code/transformers-4.37.2/models/dpr/modeling_tf_dpr.py +803 -0
  17. SupplementaryMaterial_Code/transformers-4.37.2/models/dpr/tokenization_dpr_fast.py +410 -0
  18. SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/__init__.py +76 -0
  19. SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/__pycache__/__init__.cpython-310.pyc +0 -0
  20. SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/__pycache__/configuration_dpt.cpython-310.pyc +0 -0
  21. SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/__pycache__/convert_dinov2_depth_to_hf.cpython-310.pyc +0 -0
  22. SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/__pycache__/convert_dpt_beit_to_hf.cpython-310.pyc +0 -0
  23. SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/__pycache__/convert_dpt_hybrid_to_pytorch.cpython-310.pyc +0 -0
  24. SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/__pycache__/convert_dpt_swinv2_to_hf.cpython-310.pyc +0 -0
  25. SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/__pycache__/convert_dpt_to_pytorch.cpython-310.pyc +0 -0
  26. SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/__pycache__/feature_extraction_dpt.cpython-310.pyc +0 -0
  27. SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/__pycache__/image_processing_dpt.cpython-310.pyc +0 -0
  28. SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/__pycache__/modeling_dpt.cpython-310.pyc +0 -0
  29. SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/configuration_dpt.py +258 -0
  30. SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/convert_dinov2_depth_to_hf.py +384 -0
  31. SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/convert_dpt_beit_to_hf.py +306 -0
  32. SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/convert_dpt_hybrid_to_pytorch.py +316 -0
  33. SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/convert_dpt_swinv2_to_hf.py +322 -0
  34. SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/convert_dpt_to_pytorch.py +286 -0
  35. SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/feature_extraction_dpt.py +33 -0
  36. SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/image_processing_dpt.py +463 -0
  37. SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/modeling_dpt.py +1384 -0
  38. SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/__init__.py +109 -0
  39. SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/__pycache__/__init__.cpython-310.pyc +0 -0
  40. SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/__pycache__/configuration_efficientformer.cpython-310.pyc +0 -0
  41. SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/__pycache__/convert_efficientformer_original_pytorch_checkpoint_to_pytorch.cpython-310.pyc +0 -0
  42. SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/__pycache__/image_processing_efficientformer.cpython-310.pyc +0 -0
  43. SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/__pycache__/modeling_efficientformer.cpython-310.pyc +0 -0
  44. SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/__pycache__/modeling_tf_efficientformer.cpython-310.pyc +0 -0
  45. SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/configuration_efficientformer.py +173 -0
  46. SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/convert_efficientformer_original_pytorch_checkpoint_to_pytorch.py +252 -0
  47. SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/image_processing_efficientformer.py +299 -0
  48. SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/modeling_efficientformer.py +806 -0
  49. SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/modeling_tf_efficientformer.py +1195 -0
  50. SupplementaryMaterial_Code/transformers-4.37.2/models/efficientnet/__init__.py +84 -0
SupplementaryMaterial_Code/transformers-4.37.2/models/distilbert/__pycache__/tokenization_distilbert_fast.cpython-310.pyc ADDED
Binary file (8.45 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/dit/convert_dit_unilm_to_pytorch.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
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
+ """Convert DiT checkpoints from the unilm repository."""
16
+
17
+
18
+ import argparse
19
+ import json
20
+ from pathlib import Path
21
+
22
+ import requests
23
+ import torch
24
+ from huggingface_hub import hf_hub_download
25
+ from PIL import Image
26
+
27
+ from transformers import BeitConfig, BeitForImageClassification, BeitForMaskedImageModeling, BeitImageProcessor
28
+ from transformers.image_utils import PILImageResampling
29
+ from transformers.utils import logging
30
+
31
+
32
+ logging.set_verbosity_info()
33
+ logger = logging.get_logger(__name__)
34
+
35
+
36
+ # here we list all keys to be renamed (original name on the left, our name on the right)
37
+ def create_rename_keys(config, has_lm_head=False, is_semantic=False):
38
+ prefix = "backbone." if is_semantic else ""
39
+
40
+ rename_keys = []
41
+ for i in range(config.num_hidden_layers):
42
+ # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
43
+ rename_keys.append((f"{prefix}blocks.{i}.norm1.weight", f"beit.encoder.layer.{i}.layernorm_before.weight"))
44
+ rename_keys.append((f"{prefix}blocks.{i}.norm1.bias", f"beit.encoder.layer.{i}.layernorm_before.bias"))
45
+ rename_keys.append(
46
+ (f"{prefix}blocks.{i}.attn.proj.weight", f"beit.encoder.layer.{i}.attention.output.dense.weight")
47
+ )
48
+ rename_keys.append(
49
+ (f"{prefix}blocks.{i}.attn.proj.bias", f"beit.encoder.layer.{i}.attention.output.dense.bias")
50
+ )
51
+ rename_keys.append((f"{prefix}blocks.{i}.norm2.weight", f"beit.encoder.layer.{i}.layernorm_after.weight"))
52
+ rename_keys.append((f"{prefix}blocks.{i}.norm2.bias", f"beit.encoder.layer.{i}.layernorm_after.bias"))
53
+ rename_keys.append((f"{prefix}blocks.{i}.mlp.fc1.weight", f"beit.encoder.layer.{i}.intermediate.dense.weight"))
54
+ rename_keys.append((f"{prefix}blocks.{i}.mlp.fc1.bias", f"beit.encoder.layer.{i}.intermediate.dense.bias"))
55
+ rename_keys.append((f"{prefix}blocks.{i}.mlp.fc2.weight", f"beit.encoder.layer.{i}.output.dense.weight"))
56
+ rename_keys.append((f"{prefix}blocks.{i}.mlp.fc2.bias", f"beit.encoder.layer.{i}.output.dense.bias"))
57
+
58
+ # projection layer + position embeddings
59
+ rename_keys.extend(
60
+ [
61
+ (f"{prefix}cls_token", "beit.embeddings.cls_token"),
62
+ (f"{prefix}patch_embed.proj.weight", "beit.embeddings.patch_embeddings.projection.weight"),
63
+ (f"{prefix}patch_embed.proj.bias", "beit.embeddings.patch_embeddings.projection.bias"),
64
+ (f"{prefix}pos_embed", "beit.embeddings.position_embeddings"),
65
+ ]
66
+ )
67
+
68
+ if has_lm_head:
69
+ # mask token + layernorm
70
+ rename_keys.extend(
71
+ [
72
+ ("mask_token", "beit.embeddings.mask_token"),
73
+ ("norm.weight", "layernorm.weight"),
74
+ ("norm.bias", "layernorm.bias"),
75
+ ]
76
+ )
77
+ else:
78
+ # layernorm + classification head
79
+ rename_keys.extend(
80
+ [
81
+ ("fc_norm.weight", "beit.pooler.layernorm.weight"),
82
+ ("fc_norm.bias", "beit.pooler.layernorm.bias"),
83
+ ("head.weight", "classifier.weight"),
84
+ ("head.bias", "classifier.bias"),
85
+ ]
86
+ )
87
+
88
+ return rename_keys
89
+
90
+
91
+ # we split up the matrix of each encoder layer into queries, keys and values
92
+ def read_in_q_k_v(state_dict, config, has_lm_head=False, is_semantic=False):
93
+ for i in range(config.num_hidden_layers):
94
+ prefix = "backbone." if is_semantic else ""
95
+ # queries, keys and values
96
+ in_proj_weight = state_dict.pop(f"{prefix}blocks.{i}.attn.qkv.weight")
97
+ q_bias = state_dict.pop(f"{prefix}blocks.{i}.attn.q_bias")
98
+ v_bias = state_dict.pop(f"{prefix}blocks.{i}.attn.v_bias")
99
+
100
+ state_dict[f"beit.encoder.layer.{i}.attention.attention.query.weight"] = in_proj_weight[
101
+ : config.hidden_size, :
102
+ ]
103
+ state_dict[f"beit.encoder.layer.{i}.attention.attention.query.bias"] = q_bias
104
+ state_dict[f"beit.encoder.layer.{i}.attention.attention.key.weight"] = in_proj_weight[
105
+ config.hidden_size : config.hidden_size * 2, :
106
+ ]
107
+ state_dict[f"beit.encoder.layer.{i}.attention.attention.value.weight"] = in_proj_weight[
108
+ -config.hidden_size :, :
109
+ ]
110
+ state_dict[f"beit.encoder.layer.{i}.attention.attention.value.bias"] = v_bias
111
+
112
+ # gamma_1 and gamma_2
113
+ # we call them lambda because otherwise they are renamed when using .from_pretrained
114
+ gamma_1 = state_dict.pop(f"{prefix}blocks.{i}.gamma_1")
115
+ gamma_2 = state_dict.pop(f"{prefix}blocks.{i}.gamma_2")
116
+
117
+ state_dict[f"beit.encoder.layer.{i}.lambda_1"] = gamma_1
118
+ state_dict[f"beit.encoder.layer.{i}.lambda_2"] = gamma_2
119
+
120
+
121
+ def rename_key(dct, old, new):
122
+ val = dct.pop(old)
123
+ dct[new] = val
124
+
125
+
126
+ # We will verify our results on an image of cute cats
127
+ def prepare_img():
128
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
129
+ im = Image.open(requests.get(url, stream=True).raw)
130
+ return im
131
+
132
+
133
+ @torch.no_grad()
134
+ def convert_dit_checkpoint(checkpoint_url, pytorch_dump_folder_path, push_to_hub=False):
135
+ """
136
+ Copy/paste/tweak model's weights to our BEiT structure.
137
+ """
138
+
139
+ # define default BEiT configuration
140
+ has_lm_head = False if "rvlcdip" in checkpoint_url else True
141
+ config = BeitConfig(use_absolute_position_embeddings=True, use_mask_token=has_lm_head)
142
+
143
+ # size of the architecture
144
+ if "large" in checkpoint_url or "dit-l" in checkpoint_url:
145
+ config.hidden_size = 1024
146
+ config.intermediate_size = 4096
147
+ config.num_hidden_layers = 24
148
+ config.num_attention_heads = 16
149
+
150
+ # labels
151
+ if "rvlcdip" in checkpoint_url:
152
+ config.num_labels = 16
153
+ repo_id = "huggingface/label-files"
154
+ filename = "rvlcdip-id2label.json"
155
+ id2label = json.load(open(hf_hub_download(repo_id, filename, repo_type="dataset"), "r"))
156
+ id2label = {int(k): v for k, v in id2label.items()}
157
+ config.id2label = id2label
158
+ config.label2id = {v: k for k, v in id2label.items()}
159
+
160
+ # load state_dict of original model, remove and rename some keys
161
+ state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu")["model"]
162
+
163
+ rename_keys = create_rename_keys(config, has_lm_head=has_lm_head)
164
+ for src, dest in rename_keys:
165
+ rename_key(state_dict, src, dest)
166
+ read_in_q_k_v(state_dict, config, has_lm_head=has_lm_head)
167
+
168
+ # load HuggingFace model
169
+ model = BeitForMaskedImageModeling(config) if has_lm_head else BeitForImageClassification(config)
170
+ model.eval()
171
+ model.load_state_dict(state_dict)
172
+
173
+ # Check outputs on an image
174
+ image_processor = BeitImageProcessor(
175
+ size=config.image_size, resample=PILImageResampling.BILINEAR, do_center_crop=False
176
+ )
177
+ image = prepare_img()
178
+
179
+ encoding = image_processor(images=image, return_tensors="pt")
180
+ pixel_values = encoding["pixel_values"]
181
+
182
+ outputs = model(pixel_values)
183
+ logits = outputs.logits
184
+
185
+ # verify logits
186
+ expected_shape = [1, 16] if "rvlcdip" in checkpoint_url else [1, 196, 8192]
187
+ assert logits.shape == torch.Size(expected_shape), "Shape of logits not as expected"
188
+
189
+ Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
190
+ print(f"Saving model to {pytorch_dump_folder_path}")
191
+ model.save_pretrained(pytorch_dump_folder_path)
192
+ print(f"Saving image processor to {pytorch_dump_folder_path}")
193
+ image_processor.save_pretrained(pytorch_dump_folder_path)
194
+
195
+ if push_to_hub:
196
+ if has_lm_head:
197
+ model_name = "dit-base" if "base" in checkpoint_url else "dit-large"
198
+ else:
199
+ model_name = "dit-base-finetuned-rvlcdip" if "dit-b" in checkpoint_url else "dit-large-finetuned-rvlcdip"
200
+ image_processor.push_to_hub(
201
+ repo_path_or_name=Path(pytorch_dump_folder_path, model_name),
202
+ organization="nielsr",
203
+ commit_message="Add image processor",
204
+ use_temp_dir=True,
205
+ )
206
+ model.push_to_hub(
207
+ repo_path_or_name=Path(pytorch_dump_folder_path, model_name),
208
+ organization="nielsr",
209
+ commit_message="Add model",
210
+ use_temp_dir=True,
211
+ )
212
+
213
+
214
+ if __name__ == "__main__":
215
+ parser = argparse.ArgumentParser()
216
+
217
+ parser.add_argument(
218
+ "--checkpoint_url",
219
+ default="https://layoutlm.blob.core.windows.net/dit/dit-pts/dit-base-224-p16-500k-62d53a.pth",
220
+ type=str,
221
+ help="URL to the original PyTorch checkpoint (.pth file).",
222
+ )
223
+ parser.add_argument(
224
+ "--pytorch_dump_folder_path", default=None, type=str, help="Path to the folder to output PyTorch model."
225
+ )
226
+ parser.add_argument(
227
+ "--push_to_hub",
228
+ action="store_true",
229
+ )
230
+ args = parser.parse_args()
231
+ convert_dit_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
SupplementaryMaterial_Code/transformers-4.37.2/models/donut/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.31 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/donut/__pycache__/processing_donut.cpython-310.pyc ADDED
Binary file (6.05 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/donut/feature_extraction_donut.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 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
+ """Feature extractor class for Donut."""
16
+
17
+ import warnings
18
+
19
+ from ...utils import logging
20
+ from .image_processing_donut import DonutImageProcessor
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class DonutFeatureExtractor(DonutImageProcessor):
27
+ def __init__(self, *args, **kwargs) -> None:
28
+ warnings.warn(
29
+ "The class DonutFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"
30
+ " use DonutImageProcessor instead.",
31
+ FutureWarning,
32
+ )
33
+ super().__init__(*args, **kwargs)
SupplementaryMaterial_Code/transformers-4.37.2/models/donut/modeling_donut_swin.py ADDED
@@ -0,0 +1,952 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 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 Donut Swin Transformer model.
16
+
17
+ This implementation is identical to a regular Swin Transformer, without final layer norm on top of the final hidden
18
+ states."""
19
+
20
+ import collections.abc
21
+ import math
22
+ from dataclasses import dataclass
23
+ from typing import Optional, Tuple, Union
24
+
25
+ import torch
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+
29
+ from ...activations import ACT2FN
30
+ from ...modeling_utils import PreTrainedModel
31
+ from ...pytorch_utils import find_pruneable_heads_and_indices, meshgrid, prune_linear_layer
32
+ from ...utils import (
33
+ ModelOutput,
34
+ add_code_sample_docstrings,
35
+ add_start_docstrings,
36
+ add_start_docstrings_to_model_forward,
37
+ logging,
38
+ )
39
+ from .configuration_donut_swin import DonutSwinConfig
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+ # General docstring
45
+ _CONFIG_FOR_DOC = "DonutSwinConfig"
46
+
47
+ # Base docstring
48
+ _CHECKPOINT_FOR_DOC = "https://huggingface.co/naver-clova-ix/donut-base"
49
+ _EXPECTED_OUTPUT_SHAPE = [1, 49, 768]
50
+
51
+ DONUT_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST = [
52
+ "naver-clova-ix/donut-base",
53
+ # See all Donut Swin models at https://huggingface.co/models?filter=donut
54
+ ]
55
+
56
+
57
+ @dataclass
58
+ # Copied from transformers.models.swin.modeling_swin.SwinEncoderOutput with Swin->DonutSwin
59
+ class DonutSwinEncoderOutput(ModelOutput):
60
+ """
61
+ DonutSwin encoder's outputs, with potential hidden states and attentions.
62
+
63
+ Args:
64
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
65
+ Sequence of hidden-states at the output of the last layer of the model.
66
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
67
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
68
+ shape `(batch_size, sequence_length, hidden_size)`.
69
+
70
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
71
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
72
+ Tuple of `torch.FloatTensor` (one for each stage) of shape `(batch_size, num_heads, sequence_length,
73
+ sequence_length)`.
74
+
75
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
76
+ heads.
77
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
78
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
79
+ shape `(batch_size, hidden_size, height, width)`.
80
+
81
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
82
+ include the spatial dimensions.
83
+ """
84
+
85
+ last_hidden_state: torch.FloatTensor = None
86
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
87
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
88
+ reshaped_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
89
+
90
+
91
+ @dataclass
92
+ # Copied from transformers.models.swin.modeling_swin.SwinModelOutput with Swin->DonutSwin
93
+ class DonutSwinModelOutput(ModelOutput):
94
+ """
95
+ DonutSwin model's outputs that also contains a pooling of the last hidden states.
96
+
97
+ Args:
98
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
99
+ Sequence of hidden-states at the output of the last layer of the model.
100
+ pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`, *optional*, returned when `add_pooling_layer=True` is passed):
101
+ Average pooling of the last layer hidden-state.
102
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
103
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
104
+ shape `(batch_size, sequence_length, hidden_size)`.
105
+
106
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
107
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
108
+ Tuple of `torch.FloatTensor` (one for each stage) of shape `(batch_size, num_heads, sequence_length,
109
+ sequence_length)`.
110
+
111
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
112
+ heads.
113
+ reshaped_hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
114
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each stage) of
115
+ shape `(batch_size, hidden_size, height, width)`.
116
+
117
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs reshaped to
118
+ include the spatial dimensions.
119
+ """
120
+
121
+ last_hidden_state: torch.FloatTensor = None
122
+ pooler_output: Optional[torch.FloatTensor] = None
123
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
124
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
125
+ reshaped_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
126
+
127
+
128
+ # Copied from transformers.models.swin.modeling_swin.window_partition
129
+ def window_partition(input_feature, window_size):
130
+ """
131
+ Partitions the given input into windows.
132
+ """
133
+ batch_size, height, width, num_channels = input_feature.shape
134
+ input_feature = input_feature.view(
135
+ batch_size, height // window_size, window_size, width // window_size, window_size, num_channels
136
+ )
137
+ windows = input_feature.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, num_channels)
138
+ return windows
139
+
140
+
141
+ # Copied from transformers.models.swin.modeling_swin.window_reverse
142
+ def window_reverse(windows, window_size, height, width):
143
+ """
144
+ Merges windows to produce higher resolution features.
145
+ """
146
+ num_channels = windows.shape[-1]
147
+ windows = windows.view(-1, height // window_size, width // window_size, window_size, window_size, num_channels)
148
+ windows = windows.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, height, width, num_channels)
149
+ return windows
150
+
151
+
152
+ # Copied from transformers.models.swin.modeling_swin.SwinEmbeddings with Swin->DonutSwin
153
+ class DonutSwinEmbeddings(nn.Module):
154
+ """
155
+ Construct the patch and position embeddings. Optionally, also the mask token.
156
+ """
157
+
158
+ def __init__(self, config, use_mask_token=False):
159
+ super().__init__()
160
+
161
+ self.patch_embeddings = DonutSwinPatchEmbeddings(config)
162
+ num_patches = self.patch_embeddings.num_patches
163
+ self.patch_grid = self.patch_embeddings.grid_size
164
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, config.embed_dim)) if use_mask_token else None
165
+
166
+ if config.use_absolute_embeddings:
167
+ self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.embed_dim))
168
+ else:
169
+ self.position_embeddings = None
170
+
171
+ self.norm = nn.LayerNorm(config.embed_dim)
172
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
173
+
174
+ def forward(
175
+ self, pixel_values: Optional[torch.FloatTensor], bool_masked_pos: Optional[torch.BoolTensor] = None
176
+ ) -> Tuple[torch.Tensor]:
177
+ embeddings, output_dimensions = self.patch_embeddings(pixel_values)
178
+ embeddings = self.norm(embeddings)
179
+ batch_size, seq_len, _ = embeddings.size()
180
+
181
+ if bool_masked_pos is not None:
182
+ mask_tokens = self.mask_token.expand(batch_size, seq_len, -1)
183
+ # replace the masked visual tokens by mask_tokens
184
+ mask = bool_masked_pos.unsqueeze(-1).type_as(mask_tokens)
185
+ embeddings = embeddings * (1.0 - mask) + mask_tokens * mask
186
+
187
+ if self.position_embeddings is not None:
188
+ embeddings = embeddings + self.position_embeddings
189
+
190
+ embeddings = self.dropout(embeddings)
191
+
192
+ return embeddings, output_dimensions
193
+
194
+
195
+ # Copied from transformers.models.swin.modeling_swin.SwinPatchEmbeddings
196
+ class DonutSwinPatchEmbeddings(nn.Module):
197
+ """
198
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
199
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
200
+ Transformer.
201
+ """
202
+
203
+ def __init__(self, config):
204
+ super().__init__()
205
+ image_size, patch_size = config.image_size, config.patch_size
206
+ num_channels, hidden_size = config.num_channels, config.embed_dim
207
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
208
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
209
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
210
+ self.image_size = image_size
211
+ self.patch_size = patch_size
212
+ self.num_channels = num_channels
213
+ self.num_patches = num_patches
214
+ self.grid_size = (image_size[0] // patch_size[0], image_size[1] // patch_size[1])
215
+
216
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
217
+
218
+ def maybe_pad(self, pixel_values, height, width):
219
+ if width % self.patch_size[1] != 0:
220
+ pad_values = (0, self.patch_size[1] - width % self.patch_size[1])
221
+ pixel_values = nn.functional.pad(pixel_values, pad_values)
222
+ if height % self.patch_size[0] != 0:
223
+ pad_values = (0, 0, 0, self.patch_size[0] - height % self.patch_size[0])
224
+ pixel_values = nn.functional.pad(pixel_values, pad_values)
225
+ return pixel_values
226
+
227
+ def forward(self, pixel_values: Optional[torch.FloatTensor]) -> Tuple[torch.Tensor, Tuple[int]]:
228
+ _, num_channels, height, width = pixel_values.shape
229
+ if num_channels != self.num_channels:
230
+ raise ValueError(
231
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
232
+ )
233
+ # pad the input to be divisible by self.patch_size, if needed
234
+ pixel_values = self.maybe_pad(pixel_values, height, width)
235
+ embeddings = self.projection(pixel_values)
236
+ _, _, height, width = embeddings.shape
237
+ output_dimensions = (height, width)
238
+ embeddings = embeddings.flatten(2).transpose(1, 2)
239
+
240
+ return embeddings, output_dimensions
241
+
242
+
243
+ # Copied from transformers.models.swin.modeling_swin.SwinPatchMerging
244
+ class DonutSwinPatchMerging(nn.Module):
245
+ """
246
+ Patch Merging Layer.
247
+
248
+ Args:
249
+ input_resolution (`Tuple[int]`):
250
+ Resolution of input feature.
251
+ dim (`int`):
252
+ Number of input channels.
253
+ norm_layer (`nn.Module`, *optional*, defaults to `nn.LayerNorm`):
254
+ Normalization layer class.
255
+ """
256
+
257
+ def __init__(self, input_resolution: Tuple[int], dim: int, norm_layer: nn.Module = nn.LayerNorm) -> None:
258
+ super().__init__()
259
+ self.input_resolution = input_resolution
260
+ self.dim = dim
261
+ self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
262
+ self.norm = norm_layer(4 * dim)
263
+
264
+ def maybe_pad(self, input_feature, height, width):
265
+ should_pad = (height % 2 == 1) or (width % 2 == 1)
266
+ if should_pad:
267
+ pad_values = (0, 0, 0, width % 2, 0, height % 2)
268
+ input_feature = nn.functional.pad(input_feature, pad_values)
269
+
270
+ return input_feature
271
+
272
+ def forward(self, input_feature: torch.Tensor, input_dimensions: Tuple[int, int]) -> torch.Tensor:
273
+ height, width = input_dimensions
274
+ # `dim` is height * width
275
+ batch_size, dim, num_channels = input_feature.shape
276
+
277
+ input_feature = input_feature.view(batch_size, height, width, num_channels)
278
+ # pad input to be disible by width and height, if needed
279
+ input_feature = self.maybe_pad(input_feature, height, width)
280
+ # [batch_size, height/2, width/2, num_channels]
281
+ input_feature_0 = input_feature[:, 0::2, 0::2, :]
282
+ # [batch_size, height/2, width/2, num_channels]
283
+ input_feature_1 = input_feature[:, 1::2, 0::2, :]
284
+ # [batch_size, height/2, width/2, num_channels]
285
+ input_feature_2 = input_feature[:, 0::2, 1::2, :]
286
+ # [batch_size, height/2, width/2, num_channels]
287
+ input_feature_3 = input_feature[:, 1::2, 1::2, :]
288
+ # batch_size height/2 width/2 4*num_channels
289
+ input_feature = torch.cat([input_feature_0, input_feature_1, input_feature_2, input_feature_3], -1)
290
+ input_feature = input_feature.view(batch_size, -1, 4 * num_channels) # batch_size height/2*width/2 4*C
291
+
292
+ input_feature = self.norm(input_feature)
293
+ input_feature = self.reduction(input_feature)
294
+
295
+ return input_feature
296
+
297
+
298
+ # Copied from transformers.models.beit.modeling_beit.drop_path
299
+ def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
300
+ """
301
+ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
302
+
303
+ Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
304
+ however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
305
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
306
+ layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
307
+ argument.
308
+ """
309
+ if drop_prob == 0.0 or not training:
310
+ return input
311
+ keep_prob = 1 - drop_prob
312
+ shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
313
+ random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
314
+ random_tensor.floor_() # binarize
315
+ output = input.div(keep_prob) * random_tensor
316
+ return output
317
+
318
+
319
+ # Copied from transformers.models.swin.modeling_swin.SwinDropPath
320
+ class DonutSwinDropPath(nn.Module):
321
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
322
+
323
+ def __init__(self, drop_prob: Optional[float] = None) -> None:
324
+ super().__init__()
325
+ self.drop_prob = drop_prob
326
+
327
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
328
+ return drop_path(hidden_states, self.drop_prob, self.training)
329
+
330
+ def extra_repr(self) -> str:
331
+ return "p={}".format(self.drop_prob)
332
+
333
+
334
+ # Copied from transformers.models.swin.modeling_swin.SwinSelfAttention with Swin->DonutSwin
335
+ class DonutSwinSelfAttention(nn.Module):
336
+ def __init__(self, config, dim, num_heads, window_size):
337
+ super().__init__()
338
+ if dim % num_heads != 0:
339
+ raise ValueError(
340
+ f"The hidden size ({dim}) is not a multiple of the number of attention heads ({num_heads})"
341
+ )
342
+
343
+ self.num_attention_heads = num_heads
344
+ self.attention_head_size = int(dim / num_heads)
345
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
346
+ self.window_size = (
347
+ window_size if isinstance(window_size, collections.abc.Iterable) else (window_size, window_size)
348
+ )
349
+
350
+ self.relative_position_bias_table = nn.Parameter(
351
+ torch.zeros((2 * self.window_size[0] - 1) * (2 * self.window_size[1] - 1), num_heads)
352
+ )
353
+
354
+ # get pair-wise relative position index for each token inside the window
355
+ coords_h = torch.arange(self.window_size[0])
356
+ coords_w = torch.arange(self.window_size[1])
357
+ coords = torch.stack(meshgrid([coords_h, coords_w], indexing="ij"))
358
+ coords_flatten = torch.flatten(coords, 1)
359
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]
360
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous()
361
+ relative_coords[:, :, 0] += self.window_size[0] - 1
362
+ relative_coords[:, :, 1] += self.window_size[1] - 1
363
+ relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1
364
+ relative_position_index = relative_coords.sum(-1)
365
+ self.register_buffer("relative_position_index", relative_position_index)
366
+
367
+ self.query = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
368
+ self.key = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
369
+ self.value = nn.Linear(self.all_head_size, self.all_head_size, bias=config.qkv_bias)
370
+
371
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
372
+
373
+ def transpose_for_scores(self, x):
374
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
375
+ x = x.view(new_x_shape)
376
+ return x.permute(0, 2, 1, 3)
377
+
378
+ def forward(
379
+ self,
380
+ hidden_states: torch.Tensor,
381
+ attention_mask: Optional[torch.FloatTensor] = None,
382
+ head_mask: Optional[torch.FloatTensor] = None,
383
+ output_attentions: Optional[bool] = False,
384
+ ) -> Tuple[torch.Tensor]:
385
+ batch_size, dim, num_channels = hidden_states.shape
386
+ mixed_query_layer = self.query(hidden_states)
387
+
388
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
389
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
390
+ query_layer = self.transpose_for_scores(mixed_query_layer)
391
+
392
+ # Take the dot product between "query" and "key" to get the raw attention scores.
393
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
394
+
395
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
396
+
397
+ relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)]
398
+ relative_position_bias = relative_position_bias.view(
399
+ self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1], -1
400
+ )
401
+
402
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous()
403
+ attention_scores = attention_scores + relative_position_bias.unsqueeze(0)
404
+
405
+ if attention_mask is not None:
406
+ # Apply the attention mask is (precomputed for all layers in DonutSwinModel forward() function)
407
+ mask_shape = attention_mask.shape[0]
408
+ attention_scores = attention_scores.view(
409
+ batch_size // mask_shape, mask_shape, self.num_attention_heads, dim, dim
410
+ )
411
+ attention_scores = attention_scores + attention_mask.unsqueeze(1).unsqueeze(0)
412
+ attention_scores = attention_scores.view(-1, self.num_attention_heads, dim, dim)
413
+
414
+ # Normalize the attention scores to probabilities.
415
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
416
+
417
+ # This is actually dropping out entire tokens to attend to, which might
418
+ # seem a bit unusual, but is taken from the original Transformer paper.
419
+ attention_probs = self.dropout(attention_probs)
420
+
421
+ # Mask heads if we want to
422
+ if head_mask is not None:
423
+ attention_probs = attention_probs * head_mask
424
+
425
+ context_layer = torch.matmul(attention_probs, value_layer)
426
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
427
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
428
+ context_layer = context_layer.view(new_context_layer_shape)
429
+
430
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
431
+
432
+ return outputs
433
+
434
+
435
+ # Copied from transformers.models.swin.modeling_swin.SwinSelfOutput
436
+ class DonutSwinSelfOutput(nn.Module):
437
+ def __init__(self, config, dim):
438
+ super().__init__()
439
+ self.dense = nn.Linear(dim, dim)
440
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
441
+
442
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
443
+ hidden_states = self.dense(hidden_states)
444
+ hidden_states = self.dropout(hidden_states)
445
+
446
+ return hidden_states
447
+
448
+
449
+ # Copied from transformers.models.swin.modeling_swin.SwinAttention with Swin->DonutSwin
450
+ class DonutSwinAttention(nn.Module):
451
+ def __init__(self, config, dim, num_heads, window_size):
452
+ super().__init__()
453
+ self.self = DonutSwinSelfAttention(config, dim, num_heads, window_size)
454
+ self.output = DonutSwinSelfOutput(config, dim)
455
+ self.pruned_heads = set()
456
+
457
+ def prune_heads(self, heads):
458
+ if len(heads) == 0:
459
+ return
460
+ heads, index = find_pruneable_heads_and_indices(
461
+ heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads
462
+ )
463
+
464
+ # Prune linear layers
465
+ self.self.query = prune_linear_layer(self.self.query, index)
466
+ self.self.key = prune_linear_layer(self.self.key, index)
467
+ self.self.value = prune_linear_layer(self.self.value, index)
468
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
469
+
470
+ # Update hyper params and store pruned heads
471
+ self.self.num_attention_heads = self.self.num_attention_heads - len(heads)
472
+ self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads
473
+ self.pruned_heads = self.pruned_heads.union(heads)
474
+
475
+ def forward(
476
+ self,
477
+ hidden_states: torch.Tensor,
478
+ attention_mask: Optional[torch.FloatTensor] = None,
479
+ head_mask: Optional[torch.FloatTensor] = None,
480
+ output_attentions: Optional[bool] = False,
481
+ ) -> Tuple[torch.Tensor]:
482
+ self_outputs = self.self(hidden_states, attention_mask, head_mask, output_attentions)
483
+ attention_output = self.output(self_outputs[0], hidden_states)
484
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
485
+ return outputs
486
+
487
+
488
+ # Copied from transformers.models.swin.modeling_swin.SwinIntermediate
489
+ class DonutSwinIntermediate(nn.Module):
490
+ def __init__(self, config, dim):
491
+ super().__init__()
492
+ self.dense = nn.Linear(dim, int(config.mlp_ratio * dim))
493
+ if isinstance(config.hidden_act, str):
494
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
495
+ else:
496
+ self.intermediate_act_fn = config.hidden_act
497
+
498
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
499
+ hidden_states = self.dense(hidden_states)
500
+ hidden_states = self.intermediate_act_fn(hidden_states)
501
+ return hidden_states
502
+
503
+
504
+ # Copied from transformers.models.swin.modeling_swin.SwinOutput
505
+ class DonutSwinOutput(nn.Module):
506
+ def __init__(self, config, dim):
507
+ super().__init__()
508
+ self.dense = nn.Linear(int(config.mlp_ratio * dim), dim)
509
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
510
+
511
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
512
+ hidden_states = self.dense(hidden_states)
513
+ hidden_states = self.dropout(hidden_states)
514
+ return hidden_states
515
+
516
+
517
+ # Copied from transformers.models.swin.modeling_swin.SwinLayer with Swin->DonutSwin
518
+ class DonutSwinLayer(nn.Module):
519
+ def __init__(self, config, dim, input_resolution, num_heads, shift_size=0):
520
+ super().__init__()
521
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
522
+ self.shift_size = shift_size
523
+ self.window_size = config.window_size
524
+ self.input_resolution = input_resolution
525
+ self.layernorm_before = nn.LayerNorm(dim, eps=config.layer_norm_eps)
526
+ self.attention = DonutSwinAttention(config, dim, num_heads, window_size=self.window_size)
527
+ self.drop_path = DonutSwinDropPath(config.drop_path_rate) if config.drop_path_rate > 0.0 else nn.Identity()
528
+ self.layernorm_after = nn.LayerNorm(dim, eps=config.layer_norm_eps)
529
+ self.intermediate = DonutSwinIntermediate(config, dim)
530
+ self.output = DonutSwinOutput(config, dim)
531
+
532
+ def set_shift_and_window_size(self, input_resolution):
533
+ if min(input_resolution) <= self.window_size:
534
+ # if window size is larger than input resolution, we don't partition windows
535
+ self.shift_size = 0
536
+ self.window_size = min(input_resolution)
537
+
538
+ def get_attn_mask(self, height, width, dtype):
539
+ if self.shift_size > 0:
540
+ # calculate attention mask for SW-MSA
541
+ img_mask = torch.zeros((1, height, width, 1), dtype=dtype)
542
+ height_slices = (
543
+ slice(0, -self.window_size),
544
+ slice(-self.window_size, -self.shift_size),
545
+ slice(-self.shift_size, None),
546
+ )
547
+ width_slices = (
548
+ slice(0, -self.window_size),
549
+ slice(-self.window_size, -self.shift_size),
550
+ slice(-self.shift_size, None),
551
+ )
552
+ count = 0
553
+ for height_slice in height_slices:
554
+ for width_slice in width_slices:
555
+ img_mask[:, height_slice, width_slice, :] = count
556
+ count += 1
557
+
558
+ mask_windows = window_partition(img_mask, self.window_size)
559
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
560
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
561
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0))
562
+ else:
563
+ attn_mask = None
564
+ return attn_mask
565
+
566
+ def maybe_pad(self, hidden_states, height, width):
567
+ pad_right = (self.window_size - width % self.window_size) % self.window_size
568
+ pad_bottom = (self.window_size - height % self.window_size) % self.window_size
569
+ pad_values = (0, 0, 0, pad_right, 0, pad_bottom)
570
+ hidden_states = nn.functional.pad(hidden_states, pad_values)
571
+ return hidden_states, pad_values
572
+
573
+ def forward(
574
+ self,
575
+ hidden_states: torch.Tensor,
576
+ input_dimensions: Tuple[int, int],
577
+ head_mask: Optional[torch.FloatTensor] = None,
578
+ output_attentions: Optional[bool] = False,
579
+ always_partition: Optional[bool] = False,
580
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
581
+ if not always_partition:
582
+ self.set_shift_and_window_size(input_dimensions)
583
+ else:
584
+ pass
585
+ height, width = input_dimensions
586
+ batch_size, _, channels = hidden_states.size()
587
+ shortcut = hidden_states
588
+
589
+ hidden_states = self.layernorm_before(hidden_states)
590
+
591
+ hidden_states = hidden_states.view(batch_size, height, width, channels)
592
+
593
+ # pad hidden_states to multiples of window size
594
+ hidden_states, pad_values = self.maybe_pad(hidden_states, height, width)
595
+
596
+ _, height_pad, width_pad, _ = hidden_states.shape
597
+ # cyclic shift
598
+ if self.shift_size > 0:
599
+ shifted_hidden_states = torch.roll(hidden_states, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2))
600
+ else:
601
+ shifted_hidden_states = hidden_states
602
+
603
+ # partition windows
604
+ hidden_states_windows = window_partition(shifted_hidden_states, self.window_size)
605
+ hidden_states_windows = hidden_states_windows.view(-1, self.window_size * self.window_size, channels)
606
+ attn_mask = self.get_attn_mask(height_pad, width_pad, dtype=hidden_states.dtype)
607
+ if attn_mask is not None:
608
+ attn_mask = attn_mask.to(hidden_states_windows.device)
609
+
610
+ attention_outputs = self.attention(
611
+ hidden_states_windows, attn_mask, head_mask, output_attentions=output_attentions
612
+ )
613
+
614
+ attention_output = attention_outputs[0]
615
+
616
+ attention_windows = attention_output.view(-1, self.window_size, self.window_size, channels)
617
+ shifted_windows = window_reverse(attention_windows, self.window_size, height_pad, width_pad)
618
+
619
+ # reverse cyclic shift
620
+ if self.shift_size > 0:
621
+ attention_windows = torch.roll(shifted_windows, shifts=(self.shift_size, self.shift_size), dims=(1, 2))
622
+ else:
623
+ attention_windows = shifted_windows
624
+
625
+ was_padded = pad_values[3] > 0 or pad_values[5] > 0
626
+ if was_padded:
627
+ attention_windows = attention_windows[:, :height, :width, :].contiguous()
628
+
629
+ attention_windows = attention_windows.view(batch_size, height * width, channels)
630
+
631
+ hidden_states = shortcut + self.drop_path(attention_windows)
632
+
633
+ layer_output = self.layernorm_after(hidden_states)
634
+ layer_output = self.intermediate(layer_output)
635
+ layer_output = hidden_states + self.output(layer_output)
636
+
637
+ layer_outputs = (layer_output, attention_outputs[1]) if output_attentions else (layer_output,)
638
+ return layer_outputs
639
+
640
+
641
+ # Copied from transformers.models.swin.modeling_swin.SwinStage with Swin->DonutSwin
642
+ class DonutSwinStage(nn.Module):
643
+ def __init__(self, config, dim, input_resolution, depth, num_heads, drop_path, downsample):
644
+ super().__init__()
645
+ self.config = config
646
+ self.dim = dim
647
+ self.blocks = nn.ModuleList(
648
+ [
649
+ DonutSwinLayer(
650
+ config=config,
651
+ dim=dim,
652
+ input_resolution=input_resolution,
653
+ num_heads=num_heads,
654
+ shift_size=0 if (i % 2 == 0) else config.window_size // 2,
655
+ )
656
+ for i in range(depth)
657
+ ]
658
+ )
659
+
660
+ # patch merging layer
661
+ if downsample is not None:
662
+ self.downsample = downsample(input_resolution, dim=dim, norm_layer=nn.LayerNorm)
663
+ else:
664
+ self.downsample = None
665
+
666
+ self.pointing = False
667
+
668
+ def forward(
669
+ self,
670
+ hidden_states: torch.Tensor,
671
+ input_dimensions: Tuple[int, int],
672
+ head_mask: Optional[torch.FloatTensor] = None,
673
+ output_attentions: Optional[bool] = False,
674
+ always_partition: Optional[bool] = False,
675
+ ) -> Tuple[torch.Tensor]:
676
+ height, width = input_dimensions
677
+ for i, layer_module in enumerate(self.blocks):
678
+ layer_head_mask = head_mask[i] if head_mask is not None else None
679
+
680
+ layer_outputs = layer_module(
681
+ hidden_states, input_dimensions, layer_head_mask, output_attentions, always_partition
682
+ )
683
+
684
+ hidden_states = layer_outputs[0]
685
+
686
+ hidden_states_before_downsampling = hidden_states
687
+ if self.downsample is not None:
688
+ height_downsampled, width_downsampled = (height + 1) // 2, (width + 1) // 2
689
+ output_dimensions = (height, width, height_downsampled, width_downsampled)
690
+ hidden_states = self.downsample(hidden_states_before_downsampling, input_dimensions)
691
+ else:
692
+ output_dimensions = (height, width, height, width)
693
+
694
+ stage_outputs = (hidden_states, hidden_states_before_downsampling, output_dimensions)
695
+
696
+ if output_attentions:
697
+ stage_outputs += layer_outputs[1:]
698
+ return stage_outputs
699
+
700
+
701
+ # Copied from transformers.models.swin.modeling_swin.SwinEncoder with Swin->DonutSwin
702
+ class DonutSwinEncoder(nn.Module):
703
+ def __init__(self, config, grid_size):
704
+ super().__init__()
705
+ self.num_layers = len(config.depths)
706
+ self.config = config
707
+ dpr = [x.item() for x in torch.linspace(0, config.drop_path_rate, sum(config.depths))]
708
+ self.layers = nn.ModuleList(
709
+ [
710
+ DonutSwinStage(
711
+ config=config,
712
+ dim=int(config.embed_dim * 2**i_layer),
713
+ input_resolution=(grid_size[0] // (2**i_layer), grid_size[1] // (2**i_layer)),
714
+ depth=config.depths[i_layer],
715
+ num_heads=config.num_heads[i_layer],
716
+ drop_path=dpr[sum(config.depths[:i_layer]) : sum(config.depths[: i_layer + 1])],
717
+ downsample=DonutSwinPatchMerging if (i_layer < self.num_layers - 1) else None,
718
+ )
719
+ for i_layer in range(self.num_layers)
720
+ ]
721
+ )
722
+
723
+ self.gradient_checkpointing = False
724
+
725
+ def forward(
726
+ self,
727
+ hidden_states: torch.Tensor,
728
+ input_dimensions: Tuple[int, int],
729
+ head_mask: Optional[torch.FloatTensor] = None,
730
+ output_attentions: Optional[bool] = False,
731
+ output_hidden_states: Optional[bool] = False,
732
+ output_hidden_states_before_downsampling: Optional[bool] = False,
733
+ always_partition: Optional[bool] = False,
734
+ return_dict: Optional[bool] = True,
735
+ ) -> Union[Tuple, DonutSwinEncoderOutput]:
736
+ all_hidden_states = () if output_hidden_states else None
737
+ all_reshaped_hidden_states = () if output_hidden_states else None
738
+ all_self_attentions = () if output_attentions else None
739
+
740
+ if output_hidden_states:
741
+ batch_size, _, hidden_size = hidden_states.shape
742
+ # rearrange b (h w) c -> b c h w
743
+ reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size)
744
+ reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
745
+ all_hidden_states += (hidden_states,)
746
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
747
+
748
+ for i, layer_module in enumerate(self.layers):
749
+ layer_head_mask = head_mask[i] if head_mask is not None else None
750
+
751
+ if self.gradient_checkpointing and self.training:
752
+ layer_outputs = self._gradient_checkpointing_func(
753
+ layer_module.__call__, hidden_states, input_dimensions, layer_head_mask, output_attentions
754
+ )
755
+ else:
756
+ layer_outputs = layer_module(
757
+ hidden_states, input_dimensions, layer_head_mask, output_attentions, always_partition
758
+ )
759
+
760
+ hidden_states = layer_outputs[0]
761
+ hidden_states_before_downsampling = layer_outputs[1]
762
+ output_dimensions = layer_outputs[2]
763
+
764
+ input_dimensions = (output_dimensions[-2], output_dimensions[-1])
765
+
766
+ if output_hidden_states and output_hidden_states_before_downsampling:
767
+ batch_size, _, hidden_size = hidden_states_before_downsampling.shape
768
+ # rearrange b (h w) c -> b c h w
769
+ # here we use the original (not downsampled) height and width
770
+ reshaped_hidden_state = hidden_states_before_downsampling.view(
771
+ batch_size, *(output_dimensions[0], output_dimensions[1]), hidden_size
772
+ )
773
+ reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
774
+ all_hidden_states += (hidden_states_before_downsampling,)
775
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
776
+ elif output_hidden_states and not output_hidden_states_before_downsampling:
777
+ batch_size, _, hidden_size = hidden_states.shape
778
+ # rearrange b (h w) c -> b c h w
779
+ reshaped_hidden_state = hidden_states.view(batch_size, *input_dimensions, hidden_size)
780
+ reshaped_hidden_state = reshaped_hidden_state.permute(0, 3, 1, 2)
781
+ all_hidden_states += (hidden_states,)
782
+ all_reshaped_hidden_states += (reshaped_hidden_state,)
783
+
784
+ if output_attentions:
785
+ all_self_attentions += layer_outputs[3:]
786
+
787
+ if not return_dict:
788
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
789
+
790
+ return DonutSwinEncoderOutput(
791
+ last_hidden_state=hidden_states,
792
+ hidden_states=all_hidden_states,
793
+ attentions=all_self_attentions,
794
+ reshaped_hidden_states=all_reshaped_hidden_states,
795
+ )
796
+
797
+
798
+ # Copied from transformers.models.swin.modeling_swin.SwinPreTrainedModel with Swin->DonutSwin
799
+ class DonutSwinPreTrainedModel(PreTrainedModel):
800
+ """
801
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
802
+ models.
803
+ """
804
+
805
+ config_class = DonutSwinConfig
806
+ base_model_prefix = "swin"
807
+ main_input_name = "pixel_values"
808
+ supports_gradient_checkpointing = True
809
+
810
+ def _init_weights(self, module):
811
+ """Initialize the weights"""
812
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
813
+ # Slightly different from the TF version which uses truncated_normal for initialization
814
+ # cf https://github.com/pytorch/pytorch/pull/5617
815
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
816
+ if module.bias is not None:
817
+ module.bias.data.zero_()
818
+ elif isinstance(module, nn.LayerNorm):
819
+ module.bias.data.zero_()
820
+ module.weight.data.fill_(1.0)
821
+
822
+
823
+ SWIN_START_DOCSTRING = r"""
824
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
825
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
826
+ behavior.
827
+
828
+ Parameters:
829
+ config ([`DonutSwinConfig`]): Model configuration class with all the parameters of the model.
830
+ Initializing with a config file does not load the weights associated with the model, only the
831
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
832
+ """
833
+
834
+ SWIN_INPUTS_DOCSTRING = r"""
835
+ Args:
836
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
837
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
838
+ [`DonutImageProcessor.__call__`] for details.
839
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
840
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
841
+
842
+ - 1 indicates the head is **not masked**,
843
+ - 0 indicates the head is **masked**.
844
+
845
+ output_attentions (`bool`, *optional*):
846
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
847
+ tensors for more detail.
848
+ output_hidden_states (`bool`, *optional*):
849
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
850
+ more detail.
851
+ return_dict (`bool`, *optional*):
852
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
853
+ """
854
+
855
+
856
+ @add_start_docstrings(
857
+ "The bare Donut Swin Model transformer outputting raw hidden-states without any specific head on top.",
858
+ SWIN_START_DOCSTRING,
859
+ )
860
+ class DonutSwinModel(DonutSwinPreTrainedModel):
861
+ def __init__(self, config, add_pooling_layer=True, use_mask_token=False):
862
+ super().__init__(config)
863
+ self.config = config
864
+ self.num_layers = len(config.depths)
865
+ self.num_features = int(config.embed_dim * 2 ** (self.num_layers - 1))
866
+
867
+ self.embeddings = DonutSwinEmbeddings(config, use_mask_token=use_mask_token)
868
+ self.encoder = DonutSwinEncoder(config, self.embeddings.patch_grid)
869
+
870
+ self.pooler = nn.AdaptiveAvgPool1d(1) if add_pooling_layer else None
871
+
872
+ # Initialize weights and apply final processing
873
+ self.post_init()
874
+
875
+ def get_input_embeddings(self):
876
+ return self.embeddings.patch_embeddings
877
+
878
+ def _prune_heads(self, heads_to_prune):
879
+ """
880
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
881
+ class PreTrainedModel
882
+ """
883
+ for layer, heads in heads_to_prune.items():
884
+ self.encoder.layer[layer].attention.prune_heads(heads)
885
+
886
+ @add_start_docstrings_to_model_forward(SWIN_INPUTS_DOCSTRING)
887
+ @add_code_sample_docstrings(
888
+ checkpoint=_CHECKPOINT_FOR_DOC,
889
+ output_type=DonutSwinModelOutput,
890
+ config_class=_CONFIG_FOR_DOC,
891
+ modality="vision",
892
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
893
+ )
894
+ def forward(
895
+ self,
896
+ pixel_values: Optional[torch.FloatTensor] = None,
897
+ bool_masked_pos: Optional[torch.BoolTensor] = None,
898
+ head_mask: Optional[torch.FloatTensor] = None,
899
+ output_attentions: Optional[bool] = None,
900
+ output_hidden_states: Optional[bool] = None,
901
+ return_dict: Optional[bool] = None,
902
+ ) -> Union[Tuple, DonutSwinModelOutput]:
903
+ r"""
904
+ bool_masked_pos (`torch.BoolTensor` of shape `(batch_size, num_patches)`):
905
+ Boolean masked positions. Indicates which patches are masked (1) and which aren't (0).
906
+ """
907
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
908
+ output_hidden_states = (
909
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
910
+ )
911
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
912
+
913
+ if pixel_values is None:
914
+ raise ValueError("You have to specify pixel_values")
915
+
916
+ # Prepare head mask if needed
917
+ # 1.0 in head_mask indicate we keep the head
918
+ # attention_probs has shape bsz x n_heads x N x N
919
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
920
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
921
+ head_mask = self.get_head_mask(head_mask, len(self.config.depths))
922
+
923
+ embedding_output, input_dimensions = self.embeddings(pixel_values, bool_masked_pos=bool_masked_pos)
924
+
925
+ encoder_outputs = self.encoder(
926
+ embedding_output,
927
+ input_dimensions,
928
+ head_mask=head_mask,
929
+ output_attentions=output_attentions,
930
+ output_hidden_states=output_hidden_states,
931
+ return_dict=return_dict,
932
+ )
933
+
934
+ sequence_output = encoder_outputs[0]
935
+
936
+ pooled_output = None
937
+ if self.pooler is not None:
938
+ pooled_output = self.pooler(sequence_output.transpose(1, 2))
939
+ pooled_output = torch.flatten(pooled_output, 1)
940
+
941
+ if not return_dict:
942
+ output = (sequence_output, pooled_output) + encoder_outputs[1:]
943
+
944
+ return output
945
+
946
+ return DonutSwinModelOutput(
947
+ last_hidden_state=sequence_output,
948
+ pooler_output=pooled_output,
949
+ hidden_states=encoder_outputs.hidden_states,
950
+ attentions=encoder_outputs.attentions,
951
+ reshaped_hidden_states=encoder_outputs.reshaped_hidden_states,
952
+ )
SupplementaryMaterial_Code/transformers-4.37.2/models/dpr/__init__.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import TYPE_CHECKING
16
+
17
+ from ...utils import (
18
+ OptionalDependencyNotAvailable,
19
+ _LazyModule,
20
+ is_tf_available,
21
+ is_tokenizers_available,
22
+ is_torch_available,
23
+ )
24
+
25
+
26
+ _import_structure = {
27
+ "configuration_dpr": ["DPR_PRETRAINED_CONFIG_ARCHIVE_MAP", "DPRConfig"],
28
+ "tokenization_dpr": [
29
+ "DPRContextEncoderTokenizer",
30
+ "DPRQuestionEncoderTokenizer",
31
+ "DPRReaderOutput",
32
+ "DPRReaderTokenizer",
33
+ ],
34
+ }
35
+
36
+
37
+ try:
38
+ if not is_tokenizers_available():
39
+ raise OptionalDependencyNotAvailable()
40
+ except OptionalDependencyNotAvailable:
41
+ pass
42
+ else:
43
+ _import_structure["tokenization_dpr_fast"] = [
44
+ "DPRContextEncoderTokenizerFast",
45
+ "DPRQuestionEncoderTokenizerFast",
46
+ "DPRReaderTokenizerFast",
47
+ ]
48
+
49
+ try:
50
+ if not is_torch_available():
51
+ raise OptionalDependencyNotAvailable()
52
+ except OptionalDependencyNotAvailable:
53
+ pass
54
+ else:
55
+ _import_structure["modeling_dpr"] = [
56
+ "DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST",
57
+ "DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST",
58
+ "DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST",
59
+ "DPRContextEncoder",
60
+ "DPRPretrainedContextEncoder",
61
+ "DPRPreTrainedModel",
62
+ "DPRPretrainedQuestionEncoder",
63
+ "DPRPretrainedReader",
64
+ "DPRQuestionEncoder",
65
+ "DPRReader",
66
+ ]
67
+
68
+ try:
69
+ if not is_tf_available():
70
+ raise OptionalDependencyNotAvailable()
71
+ except OptionalDependencyNotAvailable:
72
+ pass
73
+ else:
74
+ _import_structure["modeling_tf_dpr"] = [
75
+ "TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST",
76
+ "TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST",
77
+ "TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST",
78
+ "TFDPRContextEncoder",
79
+ "TFDPRPretrainedContextEncoder",
80
+ "TFDPRPretrainedQuestionEncoder",
81
+ "TFDPRPretrainedReader",
82
+ "TFDPRQuestionEncoder",
83
+ "TFDPRReader",
84
+ ]
85
+
86
+
87
+ if TYPE_CHECKING:
88
+ from .configuration_dpr import DPR_PRETRAINED_CONFIG_ARCHIVE_MAP, DPRConfig
89
+ from .tokenization_dpr import (
90
+ DPRContextEncoderTokenizer,
91
+ DPRQuestionEncoderTokenizer,
92
+ DPRReaderOutput,
93
+ DPRReaderTokenizer,
94
+ )
95
+
96
+ try:
97
+ if not is_tokenizers_available():
98
+ raise OptionalDependencyNotAvailable()
99
+ except OptionalDependencyNotAvailable:
100
+ pass
101
+ else:
102
+ from .tokenization_dpr_fast import (
103
+ DPRContextEncoderTokenizerFast,
104
+ DPRQuestionEncoderTokenizerFast,
105
+ DPRReaderTokenizerFast,
106
+ )
107
+
108
+ try:
109
+ if not is_torch_available():
110
+ raise OptionalDependencyNotAvailable()
111
+ except OptionalDependencyNotAvailable:
112
+ pass
113
+ else:
114
+ from .modeling_dpr import (
115
+ DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
116
+ DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
117
+ DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
118
+ DPRContextEncoder,
119
+ DPRPretrainedContextEncoder,
120
+ DPRPreTrainedModel,
121
+ DPRPretrainedQuestionEncoder,
122
+ DPRPretrainedReader,
123
+ DPRQuestionEncoder,
124
+ DPRReader,
125
+ )
126
+
127
+ try:
128
+ if not is_tf_available():
129
+ raise OptionalDependencyNotAvailable()
130
+ except OptionalDependencyNotAvailable:
131
+ pass
132
+ else:
133
+ from .modeling_tf_dpr import (
134
+ TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
135
+ TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
136
+ TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
137
+ TFDPRContextEncoder,
138
+ TFDPRPretrainedContextEncoder,
139
+ TFDPRPretrainedQuestionEncoder,
140
+ TFDPRPretrainedReader,
141
+ TFDPRQuestionEncoder,
142
+ TFDPRReader,
143
+ )
144
+
145
+ else:
146
+ import sys
147
+
148
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
SupplementaryMaterial_Code/transformers-4.37.2/models/dpr/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (2.21 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/dpr/__pycache__/convert_dpr_original_checkpoint_to_pytorch.cpython-310.pyc ADDED
Binary file (4.96 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/dpr/__pycache__/modeling_dpr.cpython-310.pyc ADDED
Binary file (22.3 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/dpr/__pycache__/modeling_tf_dpr.cpython-310.pyc ADDED
Binary file (27.5 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/dpr/__pycache__/tokenization_dpr.cpython-310.pyc ADDED
Binary file (15.4 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/dpr/__pycache__/tokenization_dpr_fast.cpython-310.pyc ADDED
Binary file (15.8 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/dpr/configuration_dpr.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2010, DPR authors, The Hugging Face Team.
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
+ """ DPR model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ DPR_PRETRAINED_CONFIG_ARCHIVE_MAP = {
24
+ "facebook/dpr-ctx_encoder-single-nq-base": (
25
+ "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/config.json"
26
+ ),
27
+ "facebook/dpr-question_encoder-single-nq-base": (
28
+ "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/config.json"
29
+ ),
30
+ "facebook/dpr-reader-single-nq-base": (
31
+ "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/config.json"
32
+ ),
33
+ "facebook/dpr-ctx_encoder-multiset-base": (
34
+ "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/config.json"
35
+ ),
36
+ "facebook/dpr-question_encoder-multiset-base": (
37
+ "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/config.json"
38
+ ),
39
+ "facebook/dpr-reader-multiset-base": (
40
+ "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/config.json"
41
+ ),
42
+ }
43
+
44
+
45
+ class DPRConfig(PretrainedConfig):
46
+ r"""
47
+ [`DPRConfig`] is the configuration class to store the configuration of a *DPRModel*.
48
+
49
+ This is the configuration class to store the configuration of a [`DPRContextEncoder`], [`DPRQuestionEncoder`], or a
50
+ [`DPRReader`]. It is used to instantiate the components of the DPR model according to the specified arguments,
51
+ defining the model component architectures. Instantiating a configuration with the defaults will yield a similar
52
+ configuration to that of the DPRContextEncoder
53
+ [facebook/dpr-ctx_encoder-single-nq-base](https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base)
54
+ architecture.
55
+
56
+ This class is a subclass of [`BertConfig`]. Please check the superclass for the documentation of all kwargs.
57
+
58
+ Args:
59
+ vocab_size (`int`, *optional*, defaults to 30522):
60
+ Vocabulary size of the DPR model. Defines the different tokens that can be represented by the *inputs_ids*
61
+ passed to the forward method of [`BertModel`].
62
+ hidden_size (`int`, *optional*, defaults to 768):
63
+ Dimensionality of the encoder layers and the pooler layer.
64
+ num_hidden_layers (`int`, *optional*, defaults to 12):
65
+ Number of hidden layers in the Transformer encoder.
66
+ num_attention_heads (`int`, *optional*, defaults to 12):
67
+ Number of attention heads for each attention layer in the Transformer encoder.
68
+ intermediate_size (`int`, *optional*, defaults to 3072):
69
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
70
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
71
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
72
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
73
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
74
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
75
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.1):
76
+ The dropout ratio for the attention probabilities.
77
+ max_position_embeddings (`int`, *optional*, defaults to 512):
78
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
79
+ just in case (e.g., 512 or 1024 or 2048).
80
+ type_vocab_size (`int`, *optional*, defaults to 2):
81
+ The vocabulary size of the *token_type_ids* passed into [`BertModel`].
82
+ initializer_range (`float`, *optional*, defaults to 0.02):
83
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
84
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
85
+ The epsilon used by the layer normalization layers.
86
+ pad_token_id (`int`, *optional*, defaults to 0):
87
+ Padding token id.
88
+ position_embedding_type (`str`, *optional*, defaults to `"absolute"`):
89
+ Type of position embedding. Choose one of `"absolute"`, `"relative_key"`, `"relative_key_query"`. For
90
+ positional embeddings use `"absolute"`. For more information on `"relative_key"`, please refer to
91
+ [Self-Attention with Relative Position Representations (Shaw et al.)](https://arxiv.org/abs/1803.02155).
92
+ For more information on `"relative_key_query"`, please refer to *Method 4* in [Improve Transformer Models
93
+ with Better Relative Position Embeddings (Huang et al.)](https://arxiv.org/abs/2009.13658).
94
+ projection_dim (`int`, *optional*, defaults to 0):
95
+ Dimension of the projection for the context and question encoders. If it is set to zero (default), then no
96
+ projection is done.
97
+
98
+ Example:
99
+
100
+ ```python
101
+ >>> from transformers import DPRConfig, DPRContextEncoder
102
+
103
+ >>> # Initializing a DPR facebook/dpr-ctx_encoder-single-nq-base style configuration
104
+ >>> configuration = DPRConfig()
105
+
106
+ >>> # Initializing a model (with random weights) from the facebook/dpr-ctx_encoder-single-nq-base style configuration
107
+ >>> model = DPRContextEncoder(configuration)
108
+
109
+ >>> # Accessing the model configuration
110
+ >>> configuration = model.config
111
+ ```"""
112
+
113
+ model_type = "dpr"
114
+
115
+ def __init__(
116
+ self,
117
+ vocab_size=30522,
118
+ hidden_size=768,
119
+ num_hidden_layers=12,
120
+ num_attention_heads=12,
121
+ intermediate_size=3072,
122
+ hidden_act="gelu",
123
+ hidden_dropout_prob=0.1,
124
+ attention_probs_dropout_prob=0.1,
125
+ max_position_embeddings=512,
126
+ type_vocab_size=2,
127
+ initializer_range=0.02,
128
+ layer_norm_eps=1e-12,
129
+ pad_token_id=0,
130
+ position_embedding_type="absolute",
131
+ projection_dim: int = 0,
132
+ **kwargs,
133
+ ):
134
+ super().__init__(pad_token_id=pad_token_id, **kwargs)
135
+
136
+ self.vocab_size = vocab_size
137
+ self.hidden_size = hidden_size
138
+ self.num_hidden_layers = num_hidden_layers
139
+ self.num_attention_heads = num_attention_heads
140
+ self.hidden_act = hidden_act
141
+ self.intermediate_size = intermediate_size
142
+ self.hidden_dropout_prob = hidden_dropout_prob
143
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
144
+ self.max_position_embeddings = max_position_embeddings
145
+ self.type_vocab_size = type_vocab_size
146
+ self.initializer_range = initializer_range
147
+ self.layer_norm_eps = layer_norm_eps
148
+ self.projection_dim = projection_dim
149
+ self.position_embedding_type = position_embedding_type
SupplementaryMaterial_Code/transformers-4.37.2/models/dpr/modeling_dpr.py ADDED
@@ -0,0 +1,669 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 DPR Authors, The Hugging Face Team.
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 DPR model for Open Domain Question Answering."""
16
+
17
+
18
+ from dataclasses import dataclass
19
+ from typing import Optional, Tuple, Union
20
+
21
+ import torch
22
+ from torch import Tensor, nn
23
+
24
+ from ...modeling_outputs import BaseModelOutputWithPooling
25
+ from ...modeling_utils import PreTrainedModel
26
+ from ...utils import (
27
+ ModelOutput,
28
+ add_start_docstrings,
29
+ add_start_docstrings_to_model_forward,
30
+ logging,
31
+ replace_return_docstrings,
32
+ )
33
+ from ..bert.modeling_bert import BertModel
34
+ from .configuration_dpr import DPRConfig
35
+
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+ _CONFIG_FOR_DOC = "DPRConfig"
40
+ _CHECKPOINT_FOR_DOC = "facebook/dpr-ctx_encoder-single-nq-base"
41
+
42
+ DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST = [
43
+ "facebook/dpr-ctx_encoder-single-nq-base",
44
+ "facebook/dpr-ctx_encoder-multiset-base",
45
+ ]
46
+ DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST = [
47
+ "facebook/dpr-question_encoder-single-nq-base",
48
+ "facebook/dpr-question_encoder-multiset-base",
49
+ ]
50
+ DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST = [
51
+ "facebook/dpr-reader-single-nq-base",
52
+ "facebook/dpr-reader-multiset-base",
53
+ ]
54
+
55
+
56
+ ##########
57
+ # Outputs
58
+ ##########
59
+
60
+
61
+ @dataclass
62
+ class DPRContextEncoderOutput(ModelOutput):
63
+ """
64
+ Class for outputs of [`DPRQuestionEncoder`].
65
+
66
+ Args:
67
+ pooler_output (`torch.FloatTensor` of shape `(batch_size, embeddings_size)`):
68
+ The DPR encoder outputs the *pooler_output* that corresponds to the context representation. Last layer
69
+ hidden-state of the first token of the sequence (classification token) further processed by a Linear layer.
70
+ This output is to be used to embed contexts for nearest neighbors queries with questions embeddings.
71
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
72
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
73
+ shape `(batch_size, sequence_length, hidden_size)`.
74
+
75
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
76
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
77
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
78
+ sequence_length)`.
79
+
80
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
81
+ heads.
82
+ """
83
+
84
+ pooler_output: torch.FloatTensor
85
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
86
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
87
+
88
+
89
+ @dataclass
90
+ class DPRQuestionEncoderOutput(ModelOutput):
91
+ """
92
+ Class for outputs of [`DPRQuestionEncoder`].
93
+
94
+ Args:
95
+ pooler_output (`torch.FloatTensor` of shape `(batch_size, embeddings_size)`):
96
+ The DPR encoder outputs the *pooler_output* that corresponds to the question representation. Last layer
97
+ hidden-state of the first token of the sequence (classification token) further processed by a Linear layer.
98
+ This output is to be used to embed questions for nearest neighbors queries with context embeddings.
99
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
100
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
101
+ shape `(batch_size, sequence_length, hidden_size)`.
102
+
103
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
104
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
105
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
106
+ sequence_length)`.
107
+
108
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
109
+ heads.
110
+ """
111
+
112
+ pooler_output: torch.FloatTensor
113
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
114
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
115
+
116
+
117
+ @dataclass
118
+ class DPRReaderOutput(ModelOutput):
119
+ """
120
+ Class for outputs of [`DPRQuestionEncoder`].
121
+
122
+ Args:
123
+ start_logits (`torch.FloatTensor` of shape `(n_passages, sequence_length)`):
124
+ Logits of the start index of the span for each passage.
125
+ end_logits (`torch.FloatTensor` of shape `(n_passages, sequence_length)`):
126
+ Logits of the end index of the span for each passage.
127
+ relevance_logits (`torch.FloatTensor` of shape `(n_passages, )`):
128
+ Outputs of the QA classifier of the DPRReader that corresponds to the scores of each passage to answer the
129
+ question, compared to all the other passages.
130
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
131
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
132
+ shape `(batch_size, sequence_length, hidden_size)`.
133
+
134
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
135
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
136
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
137
+ sequence_length)`.
138
+
139
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
140
+ heads.
141
+ """
142
+
143
+ start_logits: torch.FloatTensor
144
+ end_logits: torch.FloatTensor = None
145
+ relevance_logits: torch.FloatTensor = None
146
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
147
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
148
+
149
+
150
+ class DPRPreTrainedModel(PreTrainedModel):
151
+ def _init_weights(self, module):
152
+ """Initialize the weights"""
153
+ if isinstance(module, nn.Linear):
154
+ # Slightly different from the TF version which uses truncated_normal for initialization
155
+ # cf https://github.com/pytorch/pytorch/pull/5617
156
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
157
+ if module.bias is not None:
158
+ module.bias.data.zero_()
159
+ elif isinstance(module, nn.Embedding):
160
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
161
+ if module.padding_idx is not None:
162
+ module.weight.data[module.padding_idx].zero_()
163
+ elif isinstance(module, nn.LayerNorm):
164
+ module.bias.data.zero_()
165
+ module.weight.data.fill_(1.0)
166
+
167
+
168
+ class DPREncoder(DPRPreTrainedModel):
169
+ base_model_prefix = "bert_model"
170
+
171
+ def __init__(self, config: DPRConfig):
172
+ super().__init__(config)
173
+ self.bert_model = BertModel(config, add_pooling_layer=False)
174
+ if self.bert_model.config.hidden_size <= 0:
175
+ raise ValueError("Encoder hidden_size can't be zero")
176
+ self.projection_dim = config.projection_dim
177
+ if self.projection_dim > 0:
178
+ self.encode_proj = nn.Linear(self.bert_model.config.hidden_size, config.projection_dim)
179
+ # Initialize weights and apply final processing
180
+ self.post_init()
181
+
182
+ def forward(
183
+ self,
184
+ input_ids: Tensor,
185
+ attention_mask: Optional[Tensor] = None,
186
+ token_type_ids: Optional[Tensor] = None,
187
+ inputs_embeds: Optional[Tensor] = None,
188
+ output_attentions: bool = False,
189
+ output_hidden_states: bool = False,
190
+ return_dict: bool = False,
191
+ ) -> Union[BaseModelOutputWithPooling, Tuple[Tensor, ...]]:
192
+ outputs = self.bert_model(
193
+ input_ids=input_ids,
194
+ attention_mask=attention_mask,
195
+ token_type_ids=token_type_ids,
196
+ inputs_embeds=inputs_embeds,
197
+ output_attentions=output_attentions,
198
+ output_hidden_states=output_hidden_states,
199
+ return_dict=return_dict,
200
+ )
201
+ sequence_output = outputs[0]
202
+ pooled_output = sequence_output[:, 0, :]
203
+
204
+ if self.projection_dim > 0:
205
+ pooled_output = self.encode_proj(pooled_output)
206
+
207
+ if not return_dict:
208
+ return (sequence_output, pooled_output) + outputs[2:]
209
+
210
+ return BaseModelOutputWithPooling(
211
+ last_hidden_state=sequence_output,
212
+ pooler_output=pooled_output,
213
+ hidden_states=outputs.hidden_states,
214
+ attentions=outputs.attentions,
215
+ )
216
+
217
+ @property
218
+ def embeddings_size(self) -> int:
219
+ if self.projection_dim > 0:
220
+ return self.encode_proj.out_features
221
+ return self.bert_model.config.hidden_size
222
+
223
+
224
+ class DPRSpanPredictor(DPRPreTrainedModel):
225
+ base_model_prefix = "encoder"
226
+
227
+ def __init__(self, config: DPRConfig):
228
+ super().__init__(config)
229
+ self.encoder = DPREncoder(config)
230
+ self.qa_outputs = nn.Linear(self.encoder.embeddings_size, 2)
231
+ self.qa_classifier = nn.Linear(self.encoder.embeddings_size, 1)
232
+ # Initialize weights and apply final processing
233
+ self.post_init()
234
+
235
+ def forward(
236
+ self,
237
+ input_ids: Tensor,
238
+ attention_mask: Tensor,
239
+ inputs_embeds: Optional[Tensor] = None,
240
+ output_attentions: bool = False,
241
+ output_hidden_states: bool = False,
242
+ return_dict: bool = False,
243
+ ) -> Union[DPRReaderOutput, Tuple[Tensor, ...]]:
244
+ # notations: N - number of questions in a batch, M - number of passages per questions, L - sequence length
245
+ n_passages, sequence_length = input_ids.size() if input_ids is not None else inputs_embeds.size()[:2]
246
+ # feed encoder
247
+ outputs = self.encoder(
248
+ input_ids,
249
+ attention_mask=attention_mask,
250
+ inputs_embeds=inputs_embeds,
251
+ output_attentions=output_attentions,
252
+ output_hidden_states=output_hidden_states,
253
+ return_dict=return_dict,
254
+ )
255
+ sequence_output = outputs[0]
256
+
257
+ # compute logits
258
+ logits = self.qa_outputs(sequence_output)
259
+ start_logits, end_logits = logits.split(1, dim=-1)
260
+ start_logits = start_logits.squeeze(-1).contiguous()
261
+ end_logits = end_logits.squeeze(-1).contiguous()
262
+ relevance_logits = self.qa_classifier(sequence_output[:, 0, :])
263
+
264
+ # resize
265
+ start_logits = start_logits.view(n_passages, sequence_length)
266
+ end_logits = end_logits.view(n_passages, sequence_length)
267
+ relevance_logits = relevance_logits.view(n_passages)
268
+
269
+ if not return_dict:
270
+ return (start_logits, end_logits, relevance_logits) + outputs[2:]
271
+
272
+ return DPRReaderOutput(
273
+ start_logits=start_logits,
274
+ end_logits=end_logits,
275
+ relevance_logits=relevance_logits,
276
+ hidden_states=outputs.hidden_states,
277
+ attentions=outputs.attentions,
278
+ )
279
+
280
+
281
+ ##################
282
+ # PreTrainedModel
283
+ ##################
284
+
285
+
286
+ class DPRPretrainedContextEncoder(DPRPreTrainedModel):
287
+ """
288
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
289
+ models.
290
+ """
291
+
292
+ config_class = DPRConfig
293
+ load_tf_weights = None
294
+ base_model_prefix = "ctx_encoder"
295
+
296
+
297
+ class DPRPretrainedQuestionEncoder(DPRPreTrainedModel):
298
+ """
299
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
300
+ models.
301
+ """
302
+
303
+ config_class = DPRConfig
304
+ load_tf_weights = None
305
+ base_model_prefix = "question_encoder"
306
+
307
+
308
+ class DPRPretrainedReader(DPRPreTrainedModel):
309
+ """
310
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
311
+ models.
312
+ """
313
+
314
+ config_class = DPRConfig
315
+ load_tf_weights = None
316
+ base_model_prefix = "span_predictor"
317
+
318
+
319
+ ###############
320
+ # Actual Models
321
+ ###############
322
+
323
+
324
+ DPR_START_DOCSTRING = r"""
325
+
326
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
327
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
328
+ etc.)
329
+
330
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
331
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
332
+ and behavior.
333
+
334
+ Parameters:
335
+ config ([`DPRConfig`]): Model configuration class with all the parameters of the model.
336
+ Initializing with a config file does not load the weights associated with the model, only the
337
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
338
+ """
339
+
340
+ DPR_ENCODERS_INPUTS_DOCSTRING = r"""
341
+ Args:
342
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
343
+ Indices of input sequence tokens in the vocabulary. To match pretraining, DPR input sequence should be
344
+ formatted with [CLS] and [SEP] tokens as follows:
345
+
346
+ (a) For sequence pairs (for a pair title+text for example):
347
+
348
+ ```
349
+ tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
350
+ token_type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
351
+ ```
352
+
353
+ (b) For single sequences (for a question for example):
354
+
355
+ ```
356
+ tokens: [CLS] the dog is hairy . [SEP]
357
+ token_type_ids: 0 0 0 0 0 0 0
358
+ ```
359
+
360
+ DPR is a model with absolute position embeddings so it's usually advised to pad the inputs on the right
361
+ rather than the left.
362
+
363
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
364
+ [`PreTrainedTokenizer.__call__`] for details.
365
+
366
+ [What are input IDs?](../glossary#input-ids)
367
+ attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
368
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
369
+
370
+ - 1 for tokens that are **not masked**,
371
+ - 0 for tokens that are **masked**.
372
+
373
+ [What are attention masks?](../glossary#attention-mask)
374
+ token_type_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
375
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
376
+ 1]`:
377
+
378
+ - 0 corresponds to a *sentence A* token,
379
+ - 1 corresponds to a *sentence B* token.
380
+
381
+ [What are token type IDs?](../glossary#token-type-ids)
382
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
383
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
384
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
385
+ model's internal embedding lookup matrix.
386
+ output_attentions (`bool`, *optional*):
387
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
388
+ tensors for more detail.
389
+ output_hidden_states (`bool`, *optional*):
390
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
391
+ more detail.
392
+ return_dict (`bool`, *optional*):
393
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
394
+ """
395
+
396
+ DPR_READER_INPUTS_DOCSTRING = r"""
397
+ Args:
398
+ input_ids (`Tuple[torch.LongTensor]` of shapes `(n_passages, sequence_length)`):
399
+ Indices of input sequence tokens in the vocabulary. It has to be a sequence triplet with 1) the question
400
+ and 2) the passages titles and 3) the passages texts To match pretraining, DPR `input_ids` sequence should
401
+ be formatted with [CLS] and [SEP] with the format:
402
+
403
+ `[CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>`
404
+
405
+ DPR is a model with absolute position embeddings so it's usually advised to pad the inputs on the right
406
+ rather than the left.
407
+
408
+ Indices can be obtained using [`DPRReaderTokenizer`]. See this class documentation for more details.
409
+
410
+ [What are input IDs?](../glossary#input-ids)
411
+ attention_mask (`torch.FloatTensor` of shape `(n_passages, sequence_length)`, *optional*):
412
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
413
+
414
+ - 1 for tokens that are **not masked**,
415
+ - 0 for tokens that are **masked**.
416
+
417
+ [What are attention masks?](../glossary#attention-mask)
418
+ inputs_embeds (`torch.FloatTensor` of shape `(n_passages, sequence_length, hidden_size)`, *optional*):
419
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
420
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
421
+ model's internal embedding lookup matrix.
422
+ output_attentions (`bool`, *optional*):
423
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
424
+ tensors for more detail.
425
+ output_hidden_states (`bool`, *optional*):
426
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
427
+ more detail.
428
+ return_dict (`bool`, *optional*):
429
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
430
+ """
431
+
432
+
433
+ @add_start_docstrings(
434
+ "The bare DPRContextEncoder transformer outputting pooler outputs as context representations.",
435
+ DPR_START_DOCSTRING,
436
+ )
437
+ class DPRContextEncoder(DPRPretrainedContextEncoder):
438
+ def __init__(self, config: DPRConfig):
439
+ super().__init__(config)
440
+ self.config = config
441
+ self.ctx_encoder = DPREncoder(config)
442
+ # Initialize weights and apply final processing
443
+ self.post_init()
444
+
445
+ @add_start_docstrings_to_model_forward(DPR_ENCODERS_INPUTS_DOCSTRING)
446
+ @replace_return_docstrings(output_type=DPRContextEncoderOutput, config_class=_CONFIG_FOR_DOC)
447
+ def forward(
448
+ self,
449
+ input_ids: Optional[Tensor] = None,
450
+ attention_mask: Optional[Tensor] = None,
451
+ token_type_ids: Optional[Tensor] = None,
452
+ inputs_embeds: Optional[Tensor] = None,
453
+ output_attentions: Optional[bool] = None,
454
+ output_hidden_states: Optional[bool] = None,
455
+ return_dict: Optional[bool] = None,
456
+ ) -> Union[DPRContextEncoderOutput, Tuple[Tensor, ...]]:
457
+ r"""
458
+ Return:
459
+
460
+ Examples:
461
+
462
+ ```python
463
+ >>> from transformers import DPRContextEncoder, DPRContextEncoderTokenizer
464
+
465
+ >>> tokenizer = DPRContextEncoderTokenizer.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base")
466
+ >>> model = DPRContextEncoder.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base")
467
+ >>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors="pt")["input_ids"]
468
+ >>> embeddings = model(input_ids).pooler_output
469
+ ```"""
470
+
471
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
472
+ output_hidden_states = (
473
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
474
+ )
475
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
476
+
477
+ if input_ids is not None and inputs_embeds is not None:
478
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
479
+ elif input_ids is not None:
480
+ input_shape = input_ids.size()
481
+ elif inputs_embeds is not None:
482
+ input_shape = inputs_embeds.size()[:-1]
483
+ else:
484
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
485
+
486
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
487
+
488
+ if attention_mask is None:
489
+ attention_mask = (
490
+ torch.ones(input_shape, device=device)
491
+ if input_ids is None
492
+ else (input_ids != self.config.pad_token_id)
493
+ )
494
+ if token_type_ids is None:
495
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
496
+
497
+ outputs = self.ctx_encoder(
498
+ input_ids=input_ids,
499
+ attention_mask=attention_mask,
500
+ token_type_ids=token_type_ids,
501
+ inputs_embeds=inputs_embeds,
502
+ output_attentions=output_attentions,
503
+ output_hidden_states=output_hidden_states,
504
+ return_dict=return_dict,
505
+ )
506
+
507
+ if not return_dict:
508
+ return outputs[1:]
509
+ return DPRContextEncoderOutput(
510
+ pooler_output=outputs.pooler_output, hidden_states=outputs.hidden_states, attentions=outputs.attentions
511
+ )
512
+
513
+
514
+ @add_start_docstrings(
515
+ "The bare DPRQuestionEncoder transformer outputting pooler outputs as question representations.",
516
+ DPR_START_DOCSTRING,
517
+ )
518
+ class DPRQuestionEncoder(DPRPretrainedQuestionEncoder):
519
+ def __init__(self, config: DPRConfig):
520
+ super().__init__(config)
521
+ self.config = config
522
+ self.question_encoder = DPREncoder(config)
523
+ # Initialize weights and apply final processing
524
+ self.post_init()
525
+
526
+ @add_start_docstrings_to_model_forward(DPR_ENCODERS_INPUTS_DOCSTRING)
527
+ @replace_return_docstrings(output_type=DPRQuestionEncoderOutput, config_class=_CONFIG_FOR_DOC)
528
+ def forward(
529
+ self,
530
+ input_ids: Optional[Tensor] = None,
531
+ attention_mask: Optional[Tensor] = None,
532
+ token_type_ids: Optional[Tensor] = None,
533
+ inputs_embeds: Optional[Tensor] = None,
534
+ output_attentions: Optional[bool] = None,
535
+ output_hidden_states: Optional[bool] = None,
536
+ return_dict: Optional[bool] = None,
537
+ ) -> Union[DPRQuestionEncoderOutput, Tuple[Tensor, ...]]:
538
+ r"""
539
+ Return:
540
+
541
+ Examples:
542
+
543
+ ```python
544
+ >>> from transformers import DPRQuestionEncoder, DPRQuestionEncoderTokenizer
545
+
546
+ >>> tokenizer = DPRQuestionEncoderTokenizer.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
547
+ >>> model = DPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
548
+ >>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors="pt")["input_ids"]
549
+ >>> embeddings = model(input_ids).pooler_output
550
+ ```
551
+ """
552
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
553
+ output_hidden_states = (
554
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
555
+ )
556
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
557
+
558
+ if input_ids is not None and inputs_embeds is not None:
559
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
560
+ elif input_ids is not None:
561
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
562
+ input_shape = input_ids.size()
563
+ elif inputs_embeds is not None:
564
+ input_shape = inputs_embeds.size()[:-1]
565
+ else:
566
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
567
+
568
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
569
+
570
+ if attention_mask is None:
571
+ attention_mask = (
572
+ torch.ones(input_shape, device=device)
573
+ if input_ids is None
574
+ else (input_ids != self.config.pad_token_id)
575
+ )
576
+ if token_type_ids is None:
577
+ token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device)
578
+
579
+ outputs = self.question_encoder(
580
+ input_ids=input_ids,
581
+ attention_mask=attention_mask,
582
+ token_type_ids=token_type_ids,
583
+ inputs_embeds=inputs_embeds,
584
+ output_attentions=output_attentions,
585
+ output_hidden_states=output_hidden_states,
586
+ return_dict=return_dict,
587
+ )
588
+
589
+ if not return_dict:
590
+ return outputs[1:]
591
+ return DPRQuestionEncoderOutput(
592
+ pooler_output=outputs.pooler_output, hidden_states=outputs.hidden_states, attentions=outputs.attentions
593
+ )
594
+
595
+
596
+ @add_start_docstrings(
597
+ "The bare DPRReader transformer outputting span predictions.",
598
+ DPR_START_DOCSTRING,
599
+ )
600
+ class DPRReader(DPRPretrainedReader):
601
+ def __init__(self, config: DPRConfig):
602
+ super().__init__(config)
603
+ self.config = config
604
+ self.span_predictor = DPRSpanPredictor(config)
605
+ # Initialize weights and apply final processing
606
+ self.post_init()
607
+
608
+ @add_start_docstrings_to_model_forward(DPR_READER_INPUTS_DOCSTRING)
609
+ @replace_return_docstrings(output_type=DPRReaderOutput, config_class=_CONFIG_FOR_DOC)
610
+ def forward(
611
+ self,
612
+ input_ids: Optional[Tensor] = None,
613
+ attention_mask: Optional[Tensor] = None,
614
+ inputs_embeds: Optional[Tensor] = None,
615
+ output_attentions: Optional[bool] = None,
616
+ output_hidden_states: Optional[bool] = None,
617
+ return_dict: Optional[bool] = None,
618
+ ) -> Union[DPRReaderOutput, Tuple[Tensor, ...]]:
619
+ r"""
620
+ Return:
621
+
622
+ Examples:
623
+
624
+ ```python
625
+ >>> from transformers import DPRReader, DPRReaderTokenizer
626
+
627
+ >>> tokenizer = DPRReaderTokenizer.from_pretrained("facebook/dpr-reader-single-nq-base")
628
+ >>> model = DPRReader.from_pretrained("facebook/dpr-reader-single-nq-base")
629
+ >>> encoded_inputs = tokenizer(
630
+ ... questions=["What is love ?"],
631
+ ... titles=["Haddaway"],
632
+ ... texts=["'What Is Love' is a song recorded by the artist Haddaway"],
633
+ ... return_tensors="pt",
634
+ ... )
635
+ >>> outputs = model(**encoded_inputs)
636
+ >>> start_logits = outputs.start_logits
637
+ >>> end_logits = outputs.end_logits
638
+ >>> relevance_logits = outputs.relevance_logits
639
+ ```
640
+ """
641
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
642
+ output_hidden_states = (
643
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
644
+ )
645
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
646
+
647
+ if input_ids is not None and inputs_embeds is not None:
648
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
649
+ elif input_ids is not None:
650
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
651
+ input_shape = input_ids.size()
652
+ elif inputs_embeds is not None:
653
+ input_shape = inputs_embeds.size()[:-1]
654
+ else:
655
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
656
+
657
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
658
+
659
+ if attention_mask is None:
660
+ attention_mask = torch.ones(input_shape, device=device)
661
+
662
+ return self.span_predictor(
663
+ input_ids,
664
+ attention_mask,
665
+ inputs_embeds=inputs_embeds,
666
+ output_attentions=output_attentions,
667
+ output_hidden_states=output_hidden_states,
668
+ return_dict=return_dict,
669
+ )
SupplementaryMaterial_Code/transformers-4.37.2/models/dpr/modeling_tf_dpr.py ADDED
@@ -0,0 +1,803 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 DPR Authors, The Hugging Face Team.
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
+
16
+ """ TensorFlow DPR model for Open Domain Question Answering."""
17
+
18
+ from __future__ import annotations
19
+
20
+ from dataclasses import dataclass
21
+ from typing import Tuple, Union
22
+
23
+ import tensorflow as tf
24
+
25
+ from ...modeling_tf_outputs import TFBaseModelOutputWithPooling
26
+ from ...modeling_tf_utils import TFModelInputType, TFPreTrainedModel, get_initializer, shape_list, unpack_inputs
27
+ from ...utils import (
28
+ ModelOutput,
29
+ add_start_docstrings,
30
+ add_start_docstrings_to_model_forward,
31
+ logging,
32
+ replace_return_docstrings,
33
+ )
34
+ from ..bert.modeling_tf_bert import TFBertMainLayer
35
+ from .configuration_dpr import DPRConfig
36
+
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+ _CONFIG_FOR_DOC = "DPRConfig"
41
+
42
+ TF_DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST = [
43
+ "facebook/dpr-ctx_encoder-single-nq-base",
44
+ "facebook/dpr-ctx_encoder-multiset-base",
45
+ ]
46
+ TF_DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST = [
47
+ "facebook/dpr-question_encoder-single-nq-base",
48
+ "facebook/dpr-question_encoder-multiset-base",
49
+ ]
50
+ TF_DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST = [
51
+ "facebook/dpr-reader-single-nq-base",
52
+ "facebook/dpr-reader-multiset-base",
53
+ ]
54
+
55
+
56
+ ##########
57
+ # Outputs
58
+ ##########
59
+
60
+
61
+ @dataclass
62
+ class TFDPRContextEncoderOutput(ModelOutput):
63
+ r"""
64
+ Class for outputs of [`TFDPRContextEncoder`].
65
+
66
+ Args:
67
+ pooler_output (`tf.Tensor` of shape `(batch_size, embeddings_size)`):
68
+ The DPR encoder outputs the *pooler_output* that corresponds to the context representation. Last layer
69
+ hidden-state of the first token of the sequence (classification token) further processed by a Linear layer.
70
+ This output is to be used to embed contexts for nearest neighbors queries with questions embeddings.
71
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
72
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
73
+ `(batch_size, sequence_length, hidden_size)`.
74
+
75
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
76
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
77
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
78
+ sequence_length)`.
79
+
80
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
81
+ heads.
82
+ """
83
+
84
+ pooler_output: tf.Tensor = None
85
+ hidden_states: Tuple[tf.Tensor] | None = None
86
+ attentions: Tuple[tf.Tensor] | None = None
87
+
88
+
89
+ @dataclass
90
+ class TFDPRQuestionEncoderOutput(ModelOutput):
91
+ """
92
+ Class for outputs of [`TFDPRQuestionEncoder`].
93
+
94
+ Args:
95
+ pooler_output (`tf.Tensor` of shape `(batch_size, embeddings_size)`):
96
+ The DPR encoder outputs the *pooler_output* that corresponds to the question representation. Last layer
97
+ hidden-state of the first token of the sequence (classification token) further processed by a Linear layer.
98
+ This output is to be used to embed questions for nearest neighbors queries with context embeddings.
99
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
100
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
101
+ `(batch_size, sequence_length, hidden_size)`.
102
+
103
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
104
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
105
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
106
+ sequence_length)`.
107
+
108
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
109
+ heads.
110
+ """
111
+
112
+ pooler_output: tf.Tensor = None
113
+ hidden_states: Tuple[tf.Tensor] | None = None
114
+ attentions: Tuple[tf.Tensor] | None = None
115
+
116
+
117
+ @dataclass
118
+ class TFDPRReaderOutput(ModelOutput):
119
+ """
120
+ Class for outputs of [`TFDPRReaderEncoder`].
121
+
122
+ Args:
123
+ start_logits (`tf.Tensor` of shape `(n_passages, sequence_length)`):
124
+ Logits of the start index of the span for each passage.
125
+ end_logits (`tf.Tensor` of shape `(n_passages, sequence_length)`):
126
+ Logits of the end index of the span for each passage.
127
+ relevance_logits (`tf.Tensor` of shape `(n_passages, )`):
128
+ Outputs of the QA classifier of the DPRReader that corresponds to the scores of each passage to answer the
129
+ question, compared to all the other passages.
130
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
131
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
132
+ `(batch_size, sequence_length, hidden_size)`.
133
+
134
+ Hidden-states of the model at the output of each layer plus the initial embedding outputs.
135
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
136
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
137
+ sequence_length)`.
138
+
139
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
140
+ heads.
141
+ """
142
+
143
+ start_logits: tf.Tensor = None
144
+ end_logits: tf.Tensor = None
145
+ relevance_logits: tf.Tensor = None
146
+ hidden_states: Tuple[tf.Tensor] | None = None
147
+ attentions: Tuple[tf.Tensor] | None = None
148
+
149
+
150
+ class TFDPREncoderLayer(tf.keras.layers.Layer):
151
+ base_model_prefix = "bert_model"
152
+
153
+ def __init__(self, config: DPRConfig, **kwargs):
154
+ super().__init__(**kwargs)
155
+
156
+ # resolve name conflict with TFBertMainLayer instead of TFBertModel
157
+ self.bert_model = TFBertMainLayer(config, add_pooling_layer=False, name="bert_model")
158
+ self.config = config
159
+
160
+ if self.config.hidden_size <= 0:
161
+ raise ValueError("Encoder hidden_size can't be zero")
162
+ self.projection_dim = config.projection_dim
163
+ if self.projection_dim > 0:
164
+ self.encode_proj = tf.keras.layers.Dense(
165
+ config.projection_dim, kernel_initializer=get_initializer(config.initializer_range), name="encode_proj"
166
+ )
167
+
168
+ @unpack_inputs
169
+ def call(
170
+ self,
171
+ input_ids: tf.Tensor = None,
172
+ attention_mask: tf.Tensor | None = None,
173
+ token_type_ids: tf.Tensor | None = None,
174
+ inputs_embeds: tf.Tensor | None = None,
175
+ output_attentions: bool = None,
176
+ output_hidden_states: bool = None,
177
+ return_dict: bool = None,
178
+ training: bool = False,
179
+ ) -> Union[TFBaseModelOutputWithPooling, Tuple[tf.Tensor, ...]]:
180
+ outputs = self.bert_model(
181
+ input_ids=input_ids,
182
+ attention_mask=attention_mask,
183
+ token_type_ids=token_type_ids,
184
+ inputs_embeds=inputs_embeds,
185
+ output_attentions=output_attentions,
186
+ output_hidden_states=output_hidden_states,
187
+ return_dict=return_dict,
188
+ training=training,
189
+ )
190
+
191
+ sequence_output = outputs[0]
192
+ pooled_output = sequence_output[:, 0, :]
193
+ if self.projection_dim > 0:
194
+ pooled_output = self.encode_proj(pooled_output)
195
+
196
+ if not return_dict:
197
+ return (sequence_output, pooled_output) + outputs[1:]
198
+
199
+ return TFBaseModelOutputWithPooling(
200
+ last_hidden_state=sequence_output,
201
+ pooler_output=pooled_output,
202
+ hidden_states=outputs.hidden_states,
203
+ attentions=outputs.attentions,
204
+ )
205
+
206
+ @property
207
+ def embeddings_size(self) -> int:
208
+ if self.projection_dim > 0:
209
+ return self.projection_dim
210
+ return self.bert_model.config.hidden_size
211
+
212
+ def build(self, input_shape=None):
213
+ if self.built:
214
+ return
215
+ self.built = True
216
+ if getattr(self, "bert_model", None) is not None:
217
+ with tf.name_scope(self.bert_model.name):
218
+ self.bert_model.build(None)
219
+ if getattr(self, "encode_proj", None) is not None:
220
+ with tf.name_scope(self.encode_proj.name):
221
+ self.encode_proj.build(None)
222
+
223
+
224
+ class TFDPRSpanPredictorLayer(tf.keras.layers.Layer):
225
+ base_model_prefix = "encoder"
226
+
227
+ def __init__(self, config: DPRConfig, **kwargs):
228
+ super().__init__(**kwargs)
229
+ self.config = config
230
+ self.encoder = TFDPREncoderLayer(config, name="encoder")
231
+
232
+ self.qa_outputs = tf.keras.layers.Dense(
233
+ 2, kernel_initializer=get_initializer(config.initializer_range), name="qa_outputs"
234
+ )
235
+ self.qa_classifier = tf.keras.layers.Dense(
236
+ 1, kernel_initializer=get_initializer(config.initializer_range), name="qa_classifier"
237
+ )
238
+
239
+ @unpack_inputs
240
+ def call(
241
+ self,
242
+ input_ids: tf.Tensor = None,
243
+ attention_mask: tf.Tensor | None = None,
244
+ inputs_embeds: tf.Tensor | None = None,
245
+ output_attentions: bool = False,
246
+ output_hidden_states: bool = False,
247
+ return_dict: bool = False,
248
+ training: bool = False,
249
+ ) -> Union[TFDPRReaderOutput, Tuple[tf.Tensor, ...]]:
250
+ # notations: N - number of questions in a batch, M - number of passages per questions, L - sequence length
251
+ n_passages, sequence_length = shape_list(input_ids) if input_ids is not None else shape_list(inputs_embeds)[:2]
252
+ # feed encoder
253
+ outputs = self.encoder(
254
+ input_ids=input_ids,
255
+ attention_mask=attention_mask,
256
+ inputs_embeds=inputs_embeds,
257
+ output_attentions=output_attentions,
258
+ output_hidden_states=output_hidden_states,
259
+ return_dict=return_dict,
260
+ training=training,
261
+ )
262
+ sequence_output = outputs[0]
263
+
264
+ # compute logits
265
+ logits = self.qa_outputs(sequence_output)
266
+ start_logits, end_logits = tf.split(logits, 2, axis=-1)
267
+ start_logits = tf.squeeze(start_logits, axis=-1)
268
+ end_logits = tf.squeeze(end_logits, axis=-1)
269
+ relevance_logits = self.qa_classifier(sequence_output[:, 0, :])
270
+
271
+ # resize
272
+ start_logits = tf.reshape(start_logits, [n_passages, sequence_length])
273
+ end_logits = tf.reshape(end_logits, [n_passages, sequence_length])
274
+ relevance_logits = tf.reshape(relevance_logits, [n_passages])
275
+
276
+ if not return_dict:
277
+ return (start_logits, end_logits, relevance_logits) + outputs[2:]
278
+
279
+ return TFDPRReaderOutput(
280
+ start_logits=start_logits,
281
+ end_logits=end_logits,
282
+ relevance_logits=relevance_logits,
283
+ hidden_states=outputs.hidden_states,
284
+ attentions=outputs.attentions,
285
+ )
286
+
287
+ def build(self, input_shape=None):
288
+ if self.built:
289
+ return
290
+ self.built = True
291
+ if getattr(self, "encoder", None) is not None:
292
+ with tf.name_scope(self.encoder.name):
293
+ self.encoder.build(None)
294
+ if getattr(self, "qa_outputs", None) is not None:
295
+ with tf.name_scope(self.qa_outputs.name):
296
+ self.qa_outputs.build([None, None, self.encoder.embeddings_size])
297
+ if getattr(self, "qa_classifier", None) is not None:
298
+ with tf.name_scope(self.qa_classifier.name):
299
+ self.qa_classifier.build([None, None, self.encoder.embeddings_size])
300
+
301
+
302
+ class TFDPRSpanPredictor(TFPreTrainedModel):
303
+ base_model_prefix = "encoder"
304
+
305
+ def __init__(self, config: DPRConfig, **kwargs):
306
+ super().__init__(config, **kwargs)
307
+ self.encoder = TFDPRSpanPredictorLayer(config)
308
+
309
+ @unpack_inputs
310
+ def call(
311
+ self,
312
+ input_ids: tf.Tensor = None,
313
+ attention_mask: tf.Tensor | None = None,
314
+ token_type_ids: tf.Tensor | None = None,
315
+ inputs_embeds: tf.Tensor | None = None,
316
+ output_attentions: bool = False,
317
+ output_hidden_states: bool = False,
318
+ return_dict: bool = False,
319
+ training: bool = False,
320
+ ) -> Union[TFDPRReaderOutput, Tuple[tf.Tensor, ...]]:
321
+ outputs = self.encoder(
322
+ input_ids=input_ids,
323
+ attention_mask=attention_mask,
324
+ inputs_embeds=inputs_embeds,
325
+ output_attentions=output_attentions,
326
+ output_hidden_states=output_hidden_states,
327
+ return_dict=return_dict,
328
+ training=training,
329
+ )
330
+
331
+ return outputs
332
+
333
+
334
+ class TFDPREncoder(TFPreTrainedModel):
335
+ base_model_prefix = "encoder"
336
+
337
+ def __init__(self, config: DPRConfig, **kwargs):
338
+ super().__init__(config, **kwargs)
339
+
340
+ self.encoder = TFDPREncoderLayer(config)
341
+
342
+ @unpack_inputs
343
+ def call(
344
+ self,
345
+ input_ids: tf.Tensor = None,
346
+ attention_mask: tf.Tensor | None = None,
347
+ token_type_ids: tf.Tensor | None = None,
348
+ inputs_embeds: tf.Tensor | None = None,
349
+ output_attentions: bool = False,
350
+ output_hidden_states: bool = False,
351
+ return_dict: bool = False,
352
+ training: bool = False,
353
+ ) -> Union[TFDPRReaderOutput, Tuple[tf.Tensor, ...]]:
354
+ outputs = self.encoder(
355
+ input_ids=input_ids,
356
+ attention_mask=attention_mask,
357
+ inputs_embeds=inputs_embeds,
358
+ output_attentions=output_attentions,
359
+ output_hidden_states=output_hidden_states,
360
+ return_dict=return_dict,
361
+ training=training,
362
+ )
363
+ return outputs
364
+
365
+
366
+ ##################
367
+ # PreTrainedModel
368
+ ##################
369
+
370
+
371
+ class TFDPRPretrainedContextEncoder(TFPreTrainedModel):
372
+ """
373
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
374
+ models.
375
+ """
376
+
377
+ config_class = DPRConfig
378
+ base_model_prefix = "ctx_encoder"
379
+
380
+
381
+ class TFDPRPretrainedQuestionEncoder(TFPreTrainedModel):
382
+ """
383
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
384
+ models.
385
+ """
386
+
387
+ config_class = DPRConfig
388
+ base_model_prefix = "question_encoder"
389
+
390
+
391
+ class TFDPRPretrainedReader(TFPreTrainedModel):
392
+ """
393
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
394
+ models.
395
+ """
396
+
397
+ config_class = DPRConfig
398
+ base_model_prefix = "reader"
399
+
400
+
401
+ ###############
402
+ # Actual Models
403
+ ###############
404
+
405
+
406
+ TF_DPR_START_DOCSTRING = r"""
407
+
408
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
409
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
410
+ etc.)
411
+
412
+ This model is also a Tensorflow [tf.keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model)
413
+ subclass. Use it as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to
414
+ general usage and behavior.
415
+
416
+ <Tip>
417
+
418
+ TensorFlow models and layers in `transformers` accept two formats as input:
419
+
420
+ - having all inputs as keyword arguments (like PyTorch models), or
421
+ - having all inputs as a list, tuple or dict in the first positional argument.
422
+
423
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
424
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
425
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
426
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
427
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
428
+ positional argument:
429
+
430
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
431
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
432
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
433
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
434
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
435
+
436
+ Note that when creating models and layers with
437
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
438
+ about any of this, as you can just pass inputs like you would to any other Python function!
439
+
440
+ </Tip>
441
+
442
+ Parameters:
443
+ config ([`DPRConfig`]): Model configuration class with all the parameters of the model.
444
+ Initializing with a config file does not load the weights associated with the model, only the
445
+ configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
446
+ """
447
+
448
+ TF_DPR_ENCODERS_INPUTS_DOCSTRING = r"""
449
+ Args:
450
+ input_ids (`Numpy array` or `tf.Tensor` of shape `(batch_size, sequence_length)`):
451
+ Indices of input sequence tokens in the vocabulary. To match pretraining, DPR input sequence should be
452
+ formatted with [CLS] and [SEP] tokens as follows:
453
+
454
+ (a) For sequence pairs (for a pair title+text for example):
455
+
456
+ ```
457
+ tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]
458
+ token_type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1
459
+ ```
460
+
461
+ (b) For single sequences (for a question for example):
462
+
463
+ ```
464
+ tokens: [CLS] the dog is hairy . [SEP]
465
+ token_type_ids: 0 0 0 0 0 0 0
466
+ ```
467
+
468
+ DPR is a model with absolute position embeddings so it's usually advised to pad the inputs on the right
469
+ rather than the left.
470
+
471
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
472
+ [`PreTrainedTokenizer.__call__`] for details.
473
+
474
+ [What are input IDs?](../glossary#input-ids)
475
+ attention_mask (`Numpy array` or `tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
476
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
477
+
478
+ - 1 for tokens that are **not masked**,
479
+ - 0 for tokens that are **masked**.
480
+
481
+ [What are attention masks?](../glossary#attention-mask)
482
+ token_type_ids (`Numpy array` or `tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
483
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
484
+ 1]`:
485
+
486
+ - 0 corresponds to a *sentence A* token,
487
+ - 1 corresponds to a *sentence B* token.
488
+
489
+ [What are token type IDs?](../glossary#token-type-ids)
490
+ inputs_embeds (`Numpy array` or `tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
491
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
492
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
493
+ model's internal embedding lookup matrix.
494
+ output_attentions (`bool`, *optional*):
495
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
496
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
497
+ config will be used instead.
498
+ output_hidden_states (`bool`, *optional*):
499
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
500
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
501
+ used instead.
502
+ return_dict (`bool`, *optional*):
503
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
504
+ eager mode, in graph mode the value will always be set to True.
505
+ training (`bool`, *optional*, defaults to `False`):
506
+ Whether or not to use the model in training mode (some modules like dropout modules have different
507
+ behaviors between training and evaluation).
508
+ """
509
+
510
+ TF_DPR_READER_INPUTS_DOCSTRING = r"""
511
+ Args:
512
+ input_ids (`Numpy array` or `tf.Tensor` of shapes `(n_passages, sequence_length)`):
513
+ Indices of input sequence tokens in the vocabulary. It has to be a sequence triplet with 1) the question
514
+ and 2) the passages titles and 3) the passages texts To match pretraining, DPR `input_ids` sequence should
515
+ be formatted with [CLS] and [SEP] with the format:
516
+
517
+ `[CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>`
518
+
519
+ DPR is a model with absolute position embeddings so it's usually advised to pad the inputs on the right
520
+ rather than the left.
521
+
522
+ Indices can be obtained using [`DPRReaderTokenizer`]. See this class documentation for more details.
523
+ attention_mask (`Numpy array` or `tf.Tensor` of shape `(n_passages, sequence_length)`, *optional*):
524
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
525
+
526
+ - 1 for tokens that are **not masked**,
527
+ - 0 for tokens that are **masked**.
528
+
529
+ [What are attention masks?](../glossary#attention-mask)
530
+ inputs_embeds (`Numpy array` or `tf.Tensor` of shape `(n_passages, sequence_length, hidden_size)`, *optional*):
531
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
532
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
533
+ model's internal embedding lookup matrix.
534
+ output_hidden_states (`bool`, *optional*):
535
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
536
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
537
+ used instead.
538
+ return_dict (`bool`, *optional*):
539
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
540
+ eager mode, in graph mode the value will always be set to True.
541
+ training (`bool`, *optional*, defaults to `False`):
542
+ Whether or not to use the model in training mode (some modules like dropout modules have different
543
+ behaviors between training and evaluation).
544
+ """
545
+
546
+
547
+ @add_start_docstrings(
548
+ "The bare DPRContextEncoder transformer outputting pooler outputs as context representations.",
549
+ TF_DPR_START_DOCSTRING,
550
+ )
551
+ class TFDPRContextEncoder(TFDPRPretrainedContextEncoder):
552
+ def __init__(self, config: DPRConfig, *args, **kwargs):
553
+ super().__init__(config, *args, **kwargs)
554
+ self.ctx_encoder = TFDPREncoderLayer(config, name="ctx_encoder")
555
+
556
+ def get_input_embeddings(self):
557
+ try:
558
+ return self.ctx_encoder.bert_model.get_input_embeddings()
559
+ except AttributeError:
560
+ self.build()
561
+ return self.ctx_encoder.bert_model.get_input_embeddings()
562
+
563
+ @unpack_inputs
564
+ @add_start_docstrings_to_model_forward(TF_DPR_ENCODERS_INPUTS_DOCSTRING)
565
+ @replace_return_docstrings(output_type=TFDPRContextEncoderOutput, config_class=_CONFIG_FOR_DOC)
566
+ def call(
567
+ self,
568
+ input_ids: TFModelInputType | None = None,
569
+ attention_mask: tf.Tensor | None = None,
570
+ token_type_ids: tf.Tensor | None = None,
571
+ inputs_embeds: tf.Tensor | None = None,
572
+ output_attentions: bool | None = None,
573
+ output_hidden_states: bool | None = None,
574
+ return_dict: bool | None = None,
575
+ training: bool = False,
576
+ ) -> TFDPRContextEncoderOutput | Tuple[tf.Tensor, ...]:
577
+ r"""
578
+ Return:
579
+
580
+ Examples:
581
+
582
+ ```python
583
+ >>> from transformers import TFDPRContextEncoder, DPRContextEncoderTokenizer
584
+
585
+ >>> tokenizer = DPRContextEncoderTokenizer.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base")
586
+ >>> model = TFDPRContextEncoder.from_pretrained("facebook/dpr-ctx_encoder-single-nq-base", from_pt=True)
587
+ >>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors="tf")["input_ids"]
588
+ >>> embeddings = model(input_ids).pooler_output
589
+ ```
590
+ """
591
+ if input_ids is not None and inputs_embeds is not None:
592
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
593
+ elif input_ids is not None:
594
+ input_shape = shape_list(input_ids)
595
+ elif inputs_embeds is not None:
596
+ input_shape = shape_list(inputs_embeds)[:-1]
597
+ else:
598
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
599
+
600
+ if attention_mask is None:
601
+ attention_mask = (
602
+ tf.ones(input_shape, dtype=tf.dtypes.int32)
603
+ if input_ids is None
604
+ else (input_ids != self.config.pad_token_id)
605
+ )
606
+ if token_type_ids is None:
607
+ token_type_ids = tf.zeros(input_shape, dtype=tf.dtypes.int32)
608
+
609
+ outputs = self.ctx_encoder(
610
+ input_ids=input_ids,
611
+ attention_mask=attention_mask,
612
+ token_type_ids=token_type_ids,
613
+ inputs_embeds=inputs_embeds,
614
+ output_attentions=output_attentions,
615
+ output_hidden_states=output_hidden_states,
616
+ return_dict=return_dict,
617
+ training=training,
618
+ )
619
+
620
+ if not return_dict:
621
+ return outputs[1:]
622
+
623
+ return TFDPRContextEncoderOutput(
624
+ pooler_output=outputs.pooler_output, hidden_states=outputs.hidden_states, attentions=outputs.attentions
625
+ )
626
+
627
+ def build(self, input_shape=None):
628
+ if self.built:
629
+ return
630
+ self.built = True
631
+ if getattr(self, "ctx_encoder", None) is not None:
632
+ with tf.name_scope(self.ctx_encoder.name):
633
+ self.ctx_encoder.build(None)
634
+
635
+
636
+ @add_start_docstrings(
637
+ "The bare DPRQuestionEncoder transformer outputting pooler outputs as question representations.",
638
+ TF_DPR_START_DOCSTRING,
639
+ )
640
+ class TFDPRQuestionEncoder(TFDPRPretrainedQuestionEncoder):
641
+ def __init__(self, config: DPRConfig, *args, **kwargs):
642
+ super().__init__(config, *args, **kwargs)
643
+ self.question_encoder = TFDPREncoderLayer(config, name="question_encoder")
644
+
645
+ def get_input_embeddings(self):
646
+ try:
647
+ return self.question_encoder.bert_model.get_input_embeddings()
648
+ except AttributeError:
649
+ self.build()
650
+ return self.question_encoder.bert_model.get_input_embeddings()
651
+
652
+ @unpack_inputs
653
+ @add_start_docstrings_to_model_forward(TF_DPR_ENCODERS_INPUTS_DOCSTRING)
654
+ @replace_return_docstrings(output_type=TFDPRQuestionEncoderOutput, config_class=_CONFIG_FOR_DOC)
655
+ def call(
656
+ self,
657
+ input_ids: TFModelInputType | None = None,
658
+ attention_mask: tf.Tensor | None = None,
659
+ token_type_ids: tf.Tensor | None = None,
660
+ inputs_embeds: tf.Tensor | None = None,
661
+ output_attentions: bool | None = None,
662
+ output_hidden_states: bool | None = None,
663
+ return_dict: bool | None = None,
664
+ training: bool = False,
665
+ ) -> TFDPRQuestionEncoderOutput | Tuple[tf.Tensor, ...]:
666
+ r"""
667
+ Return:
668
+
669
+ Examples:
670
+
671
+ ```python
672
+ >>> from transformers import TFDPRQuestionEncoder, DPRQuestionEncoderTokenizer
673
+
674
+ >>> tokenizer = DPRQuestionEncoderTokenizer.from_pretrained("facebook/dpr-question_encoder-single-nq-base")
675
+ >>> model = TFDPRQuestionEncoder.from_pretrained("facebook/dpr-question_encoder-single-nq-base", from_pt=True)
676
+ >>> input_ids = tokenizer("Hello, is my dog cute ?", return_tensors="tf")["input_ids"]
677
+ >>> embeddings = model(input_ids).pooler_output
678
+ ```
679
+ """
680
+ if input_ids is not None and inputs_embeds is not None:
681
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
682
+ elif input_ids is not None:
683
+ input_shape = shape_list(input_ids)
684
+ elif inputs_embeds is not None:
685
+ input_shape = shape_list(inputs_embeds)[:-1]
686
+ else:
687
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
688
+
689
+ if attention_mask is None:
690
+ attention_mask = (
691
+ tf.ones(input_shape, dtype=tf.dtypes.int32)
692
+ if input_ids is None
693
+ else (input_ids != self.config.pad_token_id)
694
+ )
695
+ if token_type_ids is None:
696
+ token_type_ids = tf.zeros(input_shape, dtype=tf.dtypes.int32)
697
+
698
+ outputs = self.question_encoder(
699
+ input_ids=input_ids,
700
+ attention_mask=attention_mask,
701
+ token_type_ids=token_type_ids,
702
+ inputs_embeds=inputs_embeds,
703
+ output_attentions=output_attentions,
704
+ output_hidden_states=output_hidden_states,
705
+ return_dict=return_dict,
706
+ training=training,
707
+ )
708
+
709
+ if not return_dict:
710
+ return outputs[1:]
711
+ return TFDPRQuestionEncoderOutput(
712
+ pooler_output=outputs.pooler_output, hidden_states=outputs.hidden_states, attentions=outputs.attentions
713
+ )
714
+
715
+ def build(self, input_shape=None):
716
+ if self.built:
717
+ return
718
+ self.built = True
719
+ if getattr(self, "question_encoder", None) is not None:
720
+ with tf.name_scope(self.question_encoder.name):
721
+ self.question_encoder.build(None)
722
+
723
+
724
+ @add_start_docstrings(
725
+ "The bare DPRReader transformer outputting span predictions.",
726
+ TF_DPR_START_DOCSTRING,
727
+ )
728
+ class TFDPRReader(TFDPRPretrainedReader):
729
+ def __init__(self, config: DPRConfig, *args, **kwargs):
730
+ super().__init__(config, *args, **kwargs)
731
+ self.span_predictor = TFDPRSpanPredictorLayer(config, name="span_predictor")
732
+
733
+ def get_input_embeddings(self):
734
+ try:
735
+ return self.span_predictor.encoder.bert_model.get_input_embeddings()
736
+ except AttributeError:
737
+ self.build()
738
+ return self.span_predictor.encoder.bert_model.get_input_embeddings()
739
+
740
+ @unpack_inputs
741
+ @add_start_docstrings_to_model_forward(TF_DPR_READER_INPUTS_DOCSTRING)
742
+ @replace_return_docstrings(output_type=TFDPRReaderOutput, config_class=_CONFIG_FOR_DOC)
743
+ def call(
744
+ self,
745
+ input_ids: TFModelInputType | None = None,
746
+ attention_mask: tf.Tensor | None = None,
747
+ inputs_embeds: tf.Tensor | None = None,
748
+ output_attentions: bool | None = None,
749
+ output_hidden_states: bool | None = None,
750
+ return_dict: bool | None = None,
751
+ training: bool = False,
752
+ ) -> TFDPRReaderOutput | Tuple[tf.Tensor, ...]:
753
+ r"""
754
+ Return:
755
+
756
+ Examples:
757
+
758
+ ```python
759
+ >>> from transformers import TFDPRReader, DPRReaderTokenizer
760
+
761
+ >>> tokenizer = DPRReaderTokenizer.from_pretrained("facebook/dpr-reader-single-nq-base")
762
+ >>> model = TFDPRReader.from_pretrained("facebook/dpr-reader-single-nq-base", from_pt=True)
763
+ >>> encoded_inputs = tokenizer(
764
+ ... questions=["What is love ?"],
765
+ ... titles=["Haddaway"],
766
+ ... texts=["'What Is Love' is a song recorded by the artist Haddaway"],
767
+ ... return_tensors="tf",
768
+ ... )
769
+ >>> outputs = model(encoded_inputs)
770
+ >>> start_logits = outputs.start_logits
771
+ >>> end_logits = outputs.end_logits
772
+ >>> relevance_logits = outputs.relevance_logits
773
+ ```
774
+ """
775
+ if input_ids is not None and inputs_embeds is not None:
776
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
777
+ elif input_ids is not None:
778
+ input_shape = shape_list(input_ids)
779
+ elif inputs_embeds is not None:
780
+ input_shape = shape_list(inputs_embeds)[:-1]
781
+ else:
782
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
783
+
784
+ if attention_mask is None:
785
+ attention_mask = tf.ones(input_shape, dtype=tf.dtypes.int32)
786
+
787
+ return self.span_predictor(
788
+ input_ids=input_ids,
789
+ attention_mask=attention_mask,
790
+ inputs_embeds=inputs_embeds,
791
+ output_attentions=output_attentions,
792
+ output_hidden_states=output_hidden_states,
793
+ return_dict=return_dict,
794
+ training=training,
795
+ )
796
+
797
+ def build(self, input_shape=None):
798
+ if self.built:
799
+ return
800
+ self.built = True
801
+ if getattr(self, "span_predictor", None) is not None:
802
+ with tf.name_scope(self.span_predictor.name):
803
+ self.span_predictor.build(None)
SupplementaryMaterial_Code/transformers-4.37.2/models/dpr/tokenization_dpr_fast.py ADDED
@@ -0,0 +1,410 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The HuggingFace Inc. team, The Hugging Face Team.
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
+ """Tokenization classes for DPR."""
16
+
17
+
18
+ import collections
19
+ from typing import List, Optional, Union
20
+
21
+ from ...tokenization_utils_base import BatchEncoding
22
+ from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging
23
+ from ..bert.tokenization_bert_fast import BertTokenizerFast
24
+ from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.txt", "tokenizer_file": "tokenizer.json"}
30
+
31
+ CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP = {
32
+ "vocab_file": {
33
+ "facebook/dpr-ctx_encoder-single-nq-base": (
34
+ "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt"
35
+ ),
36
+ "facebook/dpr-ctx_encoder-multiset-base": (
37
+ "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt"
38
+ ),
39
+ },
40
+ "tokenizer_file": {
41
+ "facebook/dpr-ctx_encoder-single-nq-base": (
42
+ "https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json"
43
+ ),
44
+ "facebook/dpr-ctx_encoder-multiset-base": (
45
+ "https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json"
46
+ ),
47
+ },
48
+ }
49
+ QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP = {
50
+ "vocab_file": {
51
+ "facebook/dpr-question_encoder-single-nq-base": (
52
+ "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt"
53
+ ),
54
+ "facebook/dpr-question_encoder-multiset-base": (
55
+ "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt"
56
+ ),
57
+ },
58
+ "tokenizer_file": {
59
+ "facebook/dpr-question_encoder-single-nq-base": (
60
+ "https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json"
61
+ ),
62
+ "facebook/dpr-question_encoder-multiset-base": (
63
+ "https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json"
64
+ ),
65
+ },
66
+ }
67
+ READER_PRETRAINED_VOCAB_FILES_MAP = {
68
+ "vocab_file": {
69
+ "facebook/dpr-reader-single-nq-base": (
70
+ "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt"
71
+ ),
72
+ "facebook/dpr-reader-multiset-base": (
73
+ "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt"
74
+ ),
75
+ },
76
+ "tokenizer_file": {
77
+ "facebook/dpr-reader-single-nq-base": (
78
+ "https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json"
79
+ ),
80
+ "facebook/dpr-reader-multiset-base": (
81
+ "https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json"
82
+ ),
83
+ },
84
+ }
85
+
86
+ CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
87
+ "facebook/dpr-ctx_encoder-single-nq-base": 512,
88
+ "facebook/dpr-ctx_encoder-multiset-base": 512,
89
+ }
90
+ QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
91
+ "facebook/dpr-question_encoder-single-nq-base": 512,
92
+ "facebook/dpr-question_encoder-multiset-base": 512,
93
+ }
94
+ READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
95
+ "facebook/dpr-reader-single-nq-base": 512,
96
+ "facebook/dpr-reader-multiset-base": 512,
97
+ }
98
+
99
+
100
+ CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION = {
101
+ "facebook/dpr-ctx_encoder-single-nq-base": {"do_lower_case": True},
102
+ "facebook/dpr-ctx_encoder-multiset-base": {"do_lower_case": True},
103
+ }
104
+ QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION = {
105
+ "facebook/dpr-question_encoder-single-nq-base": {"do_lower_case": True},
106
+ "facebook/dpr-question_encoder-multiset-base": {"do_lower_case": True},
107
+ }
108
+ READER_PRETRAINED_INIT_CONFIGURATION = {
109
+ "facebook/dpr-reader-single-nq-base": {"do_lower_case": True},
110
+ "facebook/dpr-reader-multiset-base": {"do_lower_case": True},
111
+ }
112
+
113
+
114
+ class DPRContextEncoderTokenizerFast(BertTokenizerFast):
115
+ r"""
116
+ Construct a "fast" DPRContextEncoder tokenizer (backed by HuggingFace's *tokenizers* library).
117
+
118
+ [`DPRContextEncoderTokenizerFast`] is identical to [`BertTokenizerFast`] and runs end-to-end tokenization:
119
+ punctuation splitting and wordpiece.
120
+
121
+ Refer to superclass [`BertTokenizerFast`] for usage examples and documentation concerning parameters.
122
+ """
123
+
124
+ vocab_files_names = VOCAB_FILES_NAMES
125
+ pretrained_vocab_files_map = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP
126
+ max_model_input_sizes = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
127
+ pretrained_init_configuration = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION
128
+ slow_tokenizer_class = DPRContextEncoderTokenizer
129
+
130
+
131
+ class DPRQuestionEncoderTokenizerFast(BertTokenizerFast):
132
+ r"""
133
+ Constructs a "fast" DPRQuestionEncoder tokenizer (backed by HuggingFace's *tokenizers* library).
134
+
135
+ [`DPRQuestionEncoderTokenizerFast`] is identical to [`BertTokenizerFast`] and runs end-to-end tokenization:
136
+ punctuation splitting and wordpiece.
137
+
138
+ Refer to superclass [`BertTokenizerFast`] for usage examples and documentation concerning parameters.
139
+ """
140
+
141
+ vocab_files_names = VOCAB_FILES_NAMES
142
+ pretrained_vocab_files_map = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP
143
+ max_model_input_sizes = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
144
+ pretrained_init_configuration = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION
145
+ slow_tokenizer_class = DPRQuestionEncoderTokenizer
146
+
147
+
148
+ DPRSpanPrediction = collections.namedtuple(
149
+ "DPRSpanPrediction", ["span_score", "relevance_score", "doc_id", "start_index", "end_index", "text"]
150
+ )
151
+
152
+ DPRReaderOutput = collections.namedtuple("DPRReaderOutput", ["start_logits", "end_logits", "relevance_logits"])
153
+
154
+
155
+ CUSTOM_DPR_READER_DOCSTRING = r"""
156
+ Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.
157
+ It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),
158
+ using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`
159
+ with the format:
160
+
161
+ [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>
162
+
163
+ Args:
164
+ questions (`str` or `List[str]`):
165
+ The questions to be encoded. You can specify one question for many passages. In this case, the question
166
+ will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in
167
+ `titles` or `texts`.
168
+ titles (`str` or `List[str]`):
169
+ The passages titles to be encoded. This can be a string or a list of strings if there are several passages.
170
+ texts (`str` or `List[str]`):
171
+ The passages texts to be encoded. This can be a string or a list of strings if there are several passages.
172
+ padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):
173
+ Activates and controls padding. Accepts the following values:
174
+
175
+ - `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence
176
+ if provided).
177
+ - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum
178
+ acceptable input length for the model if that argument is not provided.
179
+ - `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different
180
+ lengths).
181
+ truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):
182
+ Activates and controls truncation. Accepts the following values:
183
+
184
+ - `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to
185
+ the maximum acceptable input length for the model if that argument is not provided. This will truncate
186
+ token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch
187
+ of pairs) is provided.
188
+ - `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
189
+ acceptable input length for the model if that argument is not provided. This will only truncate the first
190
+ sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
191
+ - `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum
192
+ acceptable input length for the model if that argument is not provided. This will only truncate the
193
+ second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
194
+ - `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths
195
+ greater than the model maximum admissible input size).
196
+ max_length (`int`, *optional*):
197
+ Controls the maximum length to use by one of the truncation/padding parameters.
198
+
199
+ If left unset or set to `None`, this will use the predefined model maximum length if a maximum length
200
+ is required by one of the truncation/padding parameters. If the model has no specific maximum input
201
+ length (like XLNet) truncation/padding to a maximum length will be deactivated.
202
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
203
+ If set, will return tensors instead of list of python integers. Acceptable values are:
204
+
205
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
206
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
207
+ - `'np'`: Return Numpy `np.ndarray` objects.
208
+ return_attention_mask (`bool`, *optional*):
209
+ Whether or not to return the attention mask. If not set, will return the attention mask according to the
210
+ specific tokenizer's default, defined by the `return_outputs` attribute.
211
+
212
+ [What are attention masks?](../glossary#attention-mask)
213
+
214
+ Return:
215
+ `Dict[str, List[List[int]]]`: A dictionary with the following keys:
216
+
217
+ - `input_ids`: List of token ids to be fed to a model.
218
+ - `attention_mask`: List of indices specifying which tokens should be attended to by the model.
219
+ """
220
+
221
+
222
+ @add_start_docstrings(CUSTOM_DPR_READER_DOCSTRING)
223
+ class CustomDPRReaderTokenizerMixin:
224
+ def __call__(
225
+ self,
226
+ questions,
227
+ titles: Optional[str] = None,
228
+ texts: Optional[str] = None,
229
+ padding: Union[bool, str] = False,
230
+ truncation: Union[bool, str] = False,
231
+ max_length: Optional[int] = None,
232
+ return_tensors: Optional[Union[str, TensorType]] = None,
233
+ return_attention_mask: Optional[bool] = None,
234
+ **kwargs,
235
+ ) -> BatchEncoding:
236
+ if titles is None and texts is None:
237
+ return super().__call__(
238
+ questions,
239
+ padding=padding,
240
+ truncation=truncation,
241
+ max_length=max_length,
242
+ return_tensors=return_tensors,
243
+ return_attention_mask=return_attention_mask,
244
+ **kwargs,
245
+ )
246
+ elif titles is None or texts is None:
247
+ text_pair = titles if texts is None else texts
248
+ return super().__call__(
249
+ questions,
250
+ text_pair,
251
+ padding=padding,
252
+ truncation=truncation,
253
+ max_length=max_length,
254
+ return_tensors=return_tensors,
255
+ return_attention_mask=return_attention_mask,
256
+ **kwargs,
257
+ )
258
+ titles = titles if not isinstance(titles, str) else [titles]
259
+ texts = texts if not isinstance(texts, str) else [texts]
260
+ n_passages = len(titles)
261
+ questions = questions if not isinstance(questions, str) else [questions] * n_passages
262
+ assert len(titles) == len(
263
+ texts
264
+ ), f"There should be as many titles than texts but got {len(titles)} titles and {len(texts)} texts."
265
+ encoded_question_and_titles = super().__call__(questions, titles, padding=False, truncation=False)["input_ids"]
266
+ encoded_texts = super().__call__(texts, add_special_tokens=False, padding=False, truncation=False)["input_ids"]
267
+ encoded_inputs = {
268
+ "input_ids": [
269
+ (encoded_question_and_title + encoded_text)[:max_length]
270
+ if max_length is not None and truncation
271
+ else encoded_question_and_title + encoded_text
272
+ for encoded_question_and_title, encoded_text in zip(encoded_question_and_titles, encoded_texts)
273
+ ]
274
+ }
275
+ if return_attention_mask is not False:
276
+ attention_mask = []
277
+ for input_ids in encoded_inputs["input_ids"]:
278
+ attention_mask.append([int(input_id != self.pad_token_id) for input_id in input_ids])
279
+ encoded_inputs["attention_mask"] = attention_mask
280
+ return self.pad(encoded_inputs, padding=padding, max_length=max_length, return_tensors=return_tensors)
281
+
282
+ def decode_best_spans(
283
+ self,
284
+ reader_input: BatchEncoding,
285
+ reader_output: DPRReaderOutput,
286
+ num_spans: int = 16,
287
+ max_answer_length: int = 64,
288
+ num_spans_per_passage: int = 4,
289
+ ) -> List[DPRSpanPrediction]:
290
+ """
291
+ Get the span predictions for the extractive Q&A model.
292
+
293
+ Returns: *List* of *DPRReaderOutput* sorted by descending *(relevance_score, span_score)*. Each
294
+ *DPRReaderOutput* is a *Tuple* with:
295
+
296
+ - **span_score**: `float` that corresponds to the score given by the reader for this span compared to other
297
+ spans in the same passage. It corresponds to the sum of the start and end logits of the span.
298
+ - **relevance_score**: `float` that corresponds to the score of the each passage to answer the question,
299
+ compared to all the other passages. It corresponds to the output of the QA classifier of the DPRReader.
300
+ - **doc_id**: `int` the id of the passage. - ***start_index**: `int` the start index of the span
301
+ (inclusive). - **end_index**: `int` the end index of the span (inclusive).
302
+
303
+ Examples:
304
+
305
+ ```python
306
+ >>> from transformers import DPRReader, DPRReaderTokenizer
307
+
308
+ >>> tokenizer = DPRReaderTokenizer.from_pretrained("facebook/dpr-reader-single-nq-base")
309
+ >>> model = DPRReader.from_pretrained("facebook/dpr-reader-single-nq-base")
310
+ >>> encoded_inputs = tokenizer(
311
+ ... questions=["What is love ?"],
312
+ ... titles=["Haddaway"],
313
+ ... texts=["'What Is Love' is a song recorded by the artist Haddaway"],
314
+ ... return_tensors="pt",
315
+ ... )
316
+ >>> outputs = model(**encoded_inputs)
317
+ >>> predicted_spans = tokenizer.decode_best_spans(encoded_inputs, outputs)
318
+ >>> print(predicted_spans[0].text) # best span
319
+ a song
320
+ ```"""
321
+ input_ids = reader_input["input_ids"]
322
+ start_logits, end_logits, relevance_logits = reader_output[:3]
323
+ n_passages = len(relevance_logits)
324
+ sorted_docs = sorted(range(n_passages), reverse=True, key=relevance_logits.__getitem__)
325
+ nbest_spans_predictions: List[DPRReaderOutput] = []
326
+ for doc_id in sorted_docs:
327
+ sequence_ids = list(input_ids[doc_id])
328
+ # assuming question & title information is at the beginning of the sequence
329
+ passage_offset = sequence_ids.index(self.sep_token_id, 2) + 1 # second sep id
330
+ if sequence_ids[-1] == self.pad_token_id:
331
+ sequence_len = sequence_ids.index(self.pad_token_id)
332
+ else:
333
+ sequence_len = len(sequence_ids)
334
+
335
+ best_spans = self._get_best_spans(
336
+ start_logits=start_logits[doc_id][passage_offset:sequence_len],
337
+ end_logits=end_logits[doc_id][passage_offset:sequence_len],
338
+ max_answer_length=max_answer_length,
339
+ top_spans=num_spans_per_passage,
340
+ )
341
+ for start_index, end_index in best_spans:
342
+ start_index += passage_offset
343
+ end_index += passage_offset
344
+ nbest_spans_predictions.append(
345
+ DPRSpanPrediction(
346
+ span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index],
347
+ relevance_score=relevance_logits[doc_id],
348
+ doc_id=doc_id,
349
+ start_index=start_index,
350
+ end_index=end_index,
351
+ text=self.decode(sequence_ids[start_index : end_index + 1]),
352
+ )
353
+ )
354
+ if len(nbest_spans_predictions) >= num_spans:
355
+ break
356
+ return nbest_spans_predictions[:num_spans]
357
+
358
+ def _get_best_spans(
359
+ self,
360
+ start_logits: List[int],
361
+ end_logits: List[int],
362
+ max_answer_length: int,
363
+ top_spans: int,
364
+ ) -> List[DPRSpanPrediction]:
365
+ """
366
+ Finds the best answer span for the extractive Q&A model for one passage. It returns the best span by descending
367
+ `span_score` order and keeping max `top_spans` spans. Spans longer that `max_answer_length` are ignored.
368
+ """
369
+ scores = []
370
+ for start_index, start_score in enumerate(start_logits):
371
+ for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length]):
372
+ scores.append(((start_index, start_index + answer_length), start_score + end_score))
373
+ scores = sorted(scores, key=lambda x: x[1], reverse=True)
374
+ chosen_span_intervals = []
375
+ for (start_index, end_index), score in scores:
376
+ assert start_index <= end_index, f"Wrong span indices: [{start_index}:{end_index}]"
377
+ length = end_index - start_index + 1
378
+ assert length <= max_answer_length, f"Span is too long: {length} > {max_answer_length}"
379
+ if any(
380
+ start_index <= prev_start_index <= prev_end_index <= end_index
381
+ or prev_start_index <= start_index <= end_index <= prev_end_index
382
+ for (prev_start_index, prev_end_index) in chosen_span_intervals
383
+ ):
384
+ continue
385
+ chosen_span_intervals.append((start_index, end_index))
386
+
387
+ if len(chosen_span_intervals) == top_spans:
388
+ break
389
+ return chosen_span_intervals
390
+
391
+
392
+ @add_end_docstrings(CUSTOM_DPR_READER_DOCSTRING)
393
+ class DPRReaderTokenizerFast(CustomDPRReaderTokenizerMixin, BertTokenizerFast):
394
+ r"""
395
+ Constructs a "fast" DPRReader tokenizer (backed by HuggingFace's *tokenizers* library).
396
+
397
+ [`DPRReaderTokenizerFast`] is almost identical to [`BertTokenizerFast`] and runs end-to-end tokenization:
398
+ punctuation splitting and wordpiece. The difference is that is has three inputs strings: question, titles and texts
399
+ that are combined to be fed to the [`DPRReader`] model.
400
+
401
+ Refer to superclass [`BertTokenizerFast`] for usage examples and documentation concerning parameters.
402
+
403
+ """
404
+
405
+ vocab_files_names = VOCAB_FILES_NAMES
406
+ pretrained_vocab_files_map = READER_PRETRAINED_VOCAB_FILES_MAP
407
+ max_model_input_sizes = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
408
+ pretrained_init_configuration = READER_PRETRAINED_INIT_CONFIGURATION
409
+ model_input_names = ["input_ids", "attention_mask"]
410
+ slow_tokenizer_class = DPRReaderTokenizer
SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/__init__.py ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available
17
+ from ...utils import OptionalDependencyNotAvailable
18
+
19
+
20
+ _import_structure = {"configuration_dpt": ["DPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DPTConfig"]}
21
+
22
+ try:
23
+ if not is_vision_available():
24
+ raise OptionalDependencyNotAvailable()
25
+ except OptionalDependencyNotAvailable:
26
+ pass
27
+ else:
28
+ _import_structure["feature_extraction_dpt"] = ["DPTFeatureExtractor"]
29
+ _import_structure["image_processing_dpt"] = ["DPTImageProcessor"]
30
+
31
+ try:
32
+ if not is_torch_available():
33
+ raise OptionalDependencyNotAvailable()
34
+ except OptionalDependencyNotAvailable:
35
+ pass
36
+ else:
37
+ _import_structure["modeling_dpt"] = [
38
+ "DPT_PRETRAINED_MODEL_ARCHIVE_LIST",
39
+ "DPTForDepthEstimation",
40
+ "DPTForSemanticSegmentation",
41
+ "DPTModel",
42
+ "DPTPreTrainedModel",
43
+ ]
44
+
45
+
46
+ if TYPE_CHECKING:
47
+ from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig
48
+
49
+ try:
50
+ if not is_vision_available():
51
+ raise OptionalDependencyNotAvailable()
52
+ except OptionalDependencyNotAvailable:
53
+ pass
54
+ else:
55
+ from .feature_extraction_dpt import DPTFeatureExtractor
56
+ from .image_processing_dpt import DPTImageProcessor
57
+
58
+ try:
59
+ if not is_torch_available():
60
+ raise OptionalDependencyNotAvailable()
61
+ except OptionalDependencyNotAvailable:
62
+ pass
63
+ else:
64
+ from .modeling_dpt import (
65
+ DPT_PRETRAINED_MODEL_ARCHIVE_LIST,
66
+ DPTForDepthEstimation,
67
+ DPTForSemanticSegmentation,
68
+ DPTModel,
69
+ DPTPreTrainedModel,
70
+ )
71
+
72
+
73
+ else:
74
+ import sys
75
+
76
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.31 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/__pycache__/configuration_dpt.cpython-310.pyc ADDED
Binary file (9.9 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/__pycache__/convert_dinov2_depth_to_hf.cpython-310.pyc ADDED
Binary file (12.2 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/__pycache__/convert_dpt_beit_to_hf.cpython-310.pyc ADDED
Binary file (9.4 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/__pycache__/convert_dpt_hybrid_to_pytorch.cpython-310.pyc ADDED
Binary file (8.56 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/__pycache__/convert_dpt_swinv2_to_hf.cpython-310.pyc ADDED
Binary file (9.67 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/__pycache__/convert_dpt_to_pytorch.cpython-310.pyc ADDED
Binary file (8.1 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/__pycache__/feature_extraction_dpt.cpython-310.pyc ADDED
Binary file (1.01 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/__pycache__/image_processing_dpt.cpython-310.pyc ADDED
Binary file (18.7 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/__pycache__/modeling_dpt.cpython-310.pyc ADDED
Binary file (42.1 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/configuration_dpt.py ADDED
@@ -0,0 +1,258 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 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
+ """ DPT model configuration"""
16
+
17
+ import copy
18
+
19
+ from ...configuration_utils import PretrainedConfig
20
+ from ...utils import logging
21
+ from ..auto.configuration_auto import CONFIG_MAPPING
22
+ from ..bit import BitConfig
23
+
24
+
25
+ logger = logging.get_logger(__name__)
26
+
27
+ DPT_PRETRAINED_CONFIG_ARCHIVE_MAP = {
28
+ "Intel/dpt-large": "https://huggingface.co/Intel/dpt-large/resolve/main/config.json",
29
+ # See all DPT models at https://huggingface.co/models?filter=dpt
30
+ }
31
+
32
+
33
+ class DPTConfig(PretrainedConfig):
34
+ r"""
35
+ This is the configuration class to store the configuration of a [`DPTModel`]. It is used to instantiate an DPT
36
+ model according to the specified arguments, defining the model architecture. Instantiating a configuration with the
37
+ defaults will yield a similar configuration to that of the DPT
38
+ [Intel/dpt-large](https://huggingface.co/Intel/dpt-large) architecture.
39
+
40
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
41
+ documentation from [`PretrainedConfig`] for more information.
42
+
43
+
44
+ Args:
45
+ hidden_size (`int`, *optional*, defaults to 768):
46
+ Dimensionality of the encoder layers and the pooler layer.
47
+ num_hidden_layers (`int`, *optional*, defaults to 12):
48
+ Number of hidden layers in the Transformer encoder.
49
+ num_attention_heads (`int`, *optional*, defaults to 12):
50
+ Number of attention heads for each attention layer in the Transformer encoder.
51
+ intermediate_size (`int`, *optional*, defaults to 3072):
52
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
53
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
54
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
55
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
56
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.0):
57
+ The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.
58
+ attention_probs_dropout_prob (`float`, *optional*, defaults to 0.0):
59
+ The dropout ratio for the attention probabilities.
60
+ initializer_range (`float`, *optional*, defaults to 0.02):
61
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
62
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
63
+ The epsilon used by the layer normalization layers.
64
+ image_size (`int`, *optional*, defaults to 384):
65
+ The size (resolution) of each image.
66
+ patch_size (`int`, *optional*, defaults to 16):
67
+ The size (resolution) of each patch.
68
+ num_channels (`int`, *optional*, defaults to 3):
69
+ The number of input channels.
70
+ is_hybrid (`bool`, *optional*, defaults to `False`):
71
+ Whether to use a hybrid backbone. Useful in the context of loading DPT-Hybrid models.
72
+ qkv_bias (`bool`, *optional*, defaults to `True`):
73
+ Whether to add a bias to the queries, keys and values.
74
+ backbone_out_indices (`List[int]`, *optional*, defaults to `[2, 5, 8, 11]`):
75
+ Indices of the intermediate hidden states to use from backbone.
76
+ readout_type (`str`, *optional*, defaults to `"project"`):
77
+ The readout type to use when processing the readout token (CLS token) of the intermediate hidden states of
78
+ the ViT backbone. Can be one of [`"ignore"`, `"add"`, `"project"`].
79
+
80
+ - "ignore" simply ignores the CLS token.
81
+ - "add" passes the information from the CLS token to all other tokens by adding the representations.
82
+ - "project" passes information to the other tokens by concatenating the readout to all other tokens before
83
+ projecting the
84
+ representation to the original feature dimension D using a linear layer followed by a GELU non-linearity.
85
+ reassemble_factors (`List[int]`, *optional*, defaults to `[4, 2, 1, 0.5]`):
86
+ The up/downsampling factors of the reassemble layers.
87
+ neck_hidden_sizes (`List[str]`, *optional*, defaults to `[96, 192, 384, 768]`):
88
+ The hidden sizes to project to for the feature maps of the backbone.
89
+ fusion_hidden_size (`int`, *optional*, defaults to 256):
90
+ The number of channels before fusion.
91
+ head_in_index (`int`, *optional*, defaults to -1):
92
+ The index of the features to use in the heads.
93
+ use_batch_norm_in_fusion_residual (`bool`, *optional*, defaults to `False`):
94
+ Whether to use batch normalization in the pre-activate residual units of the fusion blocks.
95
+ use_bias_in_fusion_residual (`bool`, *optional*, defaults to `True`):
96
+ Whether to use bias in the pre-activate residual units of the fusion blocks.
97
+ add_projection (`bool`, *optional*, defaults to `False`):
98
+ Whether to add a projection layer before the depth estimation head.
99
+ use_auxiliary_head (`bool`, *optional*, defaults to `True`):
100
+ Whether to use an auxiliary head during training.
101
+ auxiliary_loss_weight (`float`, *optional*, defaults to 0.4):
102
+ Weight of the cross-entropy loss of the auxiliary head.
103
+ semantic_loss_ignore_index (`int`, *optional*, defaults to 255):
104
+ The index that is ignored by the loss function of the semantic segmentation model.
105
+ semantic_classifier_dropout (`float`, *optional*, defaults to 0.1):
106
+ The dropout ratio for the semantic classification head.
107
+ backbone_featmap_shape (`List[int]`, *optional*, defaults to `[1, 1024, 24, 24]`):
108
+ Used only for the `hybrid` embedding type. The shape of the feature maps of the backbone.
109
+ neck_ignore_stages (`List[int]`, *optional*, defaults to `[0, 1]`):
110
+ Used only for the `hybrid` embedding type. The stages of the readout layers to ignore.
111
+ backbone_config (`Union[Dict[str, Any], PretrainedConfig]`, *optional*):
112
+ The configuration of the backbone model. Only used in case `is_hybrid` is `True` or in case you want to
113
+ leverage the [`AutoBackbone`] API.
114
+
115
+ Example:
116
+
117
+ ```python
118
+ >>> from transformers import DPTModel, DPTConfig
119
+
120
+ >>> # Initializing a DPT dpt-large style configuration
121
+ >>> configuration = DPTConfig()
122
+
123
+ >>> # Initializing a model from the dpt-large style configuration
124
+ >>> model = DPTModel(configuration)
125
+
126
+ >>> # Accessing the model configuration
127
+ >>> configuration = model.config
128
+ ```"""
129
+
130
+ model_type = "dpt"
131
+
132
+ def __init__(
133
+ self,
134
+ hidden_size=768,
135
+ num_hidden_layers=12,
136
+ num_attention_heads=12,
137
+ intermediate_size=3072,
138
+ hidden_act="gelu",
139
+ hidden_dropout_prob=0.0,
140
+ attention_probs_dropout_prob=0.0,
141
+ initializer_range=0.02,
142
+ layer_norm_eps=1e-12,
143
+ image_size=384,
144
+ patch_size=16,
145
+ num_channels=3,
146
+ is_hybrid=False,
147
+ qkv_bias=True,
148
+ backbone_out_indices=[2, 5, 8, 11],
149
+ readout_type="project",
150
+ reassemble_factors=[4, 2, 1, 0.5],
151
+ neck_hidden_sizes=[96, 192, 384, 768],
152
+ fusion_hidden_size=256,
153
+ head_in_index=-1,
154
+ use_batch_norm_in_fusion_residual=False,
155
+ use_bias_in_fusion_residual=None,
156
+ add_projection=False,
157
+ use_auxiliary_head=True,
158
+ auxiliary_loss_weight=0.4,
159
+ semantic_loss_ignore_index=255,
160
+ semantic_classifier_dropout=0.1,
161
+ backbone_featmap_shape=[1, 1024, 24, 24],
162
+ neck_ignore_stages=[0, 1],
163
+ backbone_config=None,
164
+ **kwargs,
165
+ ):
166
+ super().__init__(**kwargs)
167
+
168
+ self.hidden_size = hidden_size
169
+ self.is_hybrid = is_hybrid
170
+
171
+ use_autobackbone = False
172
+ if self.is_hybrid:
173
+ if backbone_config is None:
174
+ logger.info("Initializing the config with a `BiT` backbone.")
175
+ backbone_config = {
176
+ "global_padding": "same",
177
+ "layer_type": "bottleneck",
178
+ "depths": [3, 4, 9],
179
+ "out_features": ["stage1", "stage2", "stage3"],
180
+ "embedding_dynamic_padding": True,
181
+ }
182
+ self.backbone_config = BitConfig(**backbone_config)
183
+ elif isinstance(backbone_config, dict):
184
+ logger.info("Initializing the config with a `BiT` backbone.")
185
+ self.backbone_config = BitConfig(**backbone_config)
186
+ elif isinstance(backbone_config, PretrainedConfig):
187
+ self.backbone_config = backbone_config
188
+ else:
189
+ raise ValueError(
190
+ f"backbone_config must be a dictionary or a `PretrainedConfig`, got {backbone_config.__class__}."
191
+ )
192
+
193
+ self.backbone_featmap_shape = backbone_featmap_shape
194
+ self.neck_ignore_stages = neck_ignore_stages
195
+
196
+ if readout_type != "project":
197
+ raise ValueError("Readout type must be 'project' when using `DPT-hybrid` mode.")
198
+
199
+ elif backbone_config is not None:
200
+ use_autobackbone = True
201
+
202
+ if isinstance(backbone_config, dict):
203
+ backbone_model_type = backbone_config.get("model_type")
204
+ config_class = CONFIG_MAPPING[backbone_model_type]
205
+ backbone_config = config_class.from_dict(backbone_config)
206
+
207
+ self.backbone_config = backbone_config
208
+ self.backbone_featmap_shape = None
209
+ self.neck_ignore_stages = []
210
+
211
+ else:
212
+ self.backbone_config = backbone_config
213
+ self.backbone_featmap_shape = None
214
+ self.neck_ignore_stages = []
215
+
216
+ self.num_hidden_layers = None if use_autobackbone else num_hidden_layers
217
+ self.num_attention_heads = None if use_autobackbone else num_attention_heads
218
+ self.intermediate_size = None if use_autobackbone else intermediate_size
219
+ self.hidden_dropout_prob = None if use_autobackbone else hidden_dropout_prob
220
+ self.attention_probs_dropout_prob = None if use_autobackbone else attention_probs_dropout_prob
221
+ self.layer_norm_eps = None if use_autobackbone else layer_norm_eps
222
+ self.image_size = None if use_autobackbone else image_size
223
+ self.patch_size = None if use_autobackbone else patch_size
224
+ self.num_channels = None if use_autobackbone else num_channels
225
+ self.qkv_bias = None if use_autobackbone else qkv_bias
226
+ self.backbone_out_indices = None if use_autobackbone else backbone_out_indices
227
+
228
+ if readout_type not in ["ignore", "add", "project"]:
229
+ raise ValueError("Readout_type must be one of ['ignore', 'add', 'project']")
230
+ self.hidden_act = hidden_act
231
+ self.initializer_range = initializer_range
232
+ self.readout_type = readout_type
233
+ self.reassemble_factors = reassemble_factors
234
+ self.neck_hidden_sizes = neck_hidden_sizes
235
+ self.fusion_hidden_size = fusion_hidden_size
236
+ self.head_in_index = head_in_index
237
+ self.use_batch_norm_in_fusion_residual = use_batch_norm_in_fusion_residual
238
+ self.use_bias_in_fusion_residual = use_bias_in_fusion_residual
239
+ self.add_projection = add_projection
240
+
241
+ # auxiliary head attributes (semantic segmentation)
242
+ self.use_auxiliary_head = use_auxiliary_head
243
+ self.auxiliary_loss_weight = auxiliary_loss_weight
244
+ self.semantic_loss_ignore_index = semantic_loss_ignore_index
245
+ self.semantic_classifier_dropout = semantic_classifier_dropout
246
+
247
+ def to_dict(self):
248
+ """
249
+ Serializes this instance to a Python dictionary. Override the default [`~PretrainedConfig.to_dict`]. Returns:
250
+ `Dict[str, any]`: Dictionary of all the attributes that make up this configuration instance,
251
+ """
252
+ output = copy.deepcopy(self.__dict__)
253
+
254
+ if output["backbone_config"] is not None:
255
+ output["backbone_config"] = self.backbone_config.to_dict()
256
+
257
+ output["model_type"] = self.__class__.model_type
258
+ return output
SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/convert_dinov2_depth_to_hf.py ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Inc. team.
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
+ """Convert DINOv2 + DPT checkpoints from the original repository. URL:
16
+ https://github.com/facebookresearch/dinov2/tree/main"""
17
+
18
+
19
+ import argparse
20
+ import itertools
21
+ import math
22
+ from pathlib import Path
23
+
24
+ import requests
25
+ import torch
26
+ from PIL import Image
27
+ from torchvision import transforms
28
+
29
+ from transformers import Dinov2Config, DPTConfig, DPTForDepthEstimation, DPTImageProcessor
30
+ from transformers.utils import logging
31
+
32
+
33
+ logging.set_verbosity_info()
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ def get_dpt_config(model_name):
38
+ if "small" in model_name:
39
+ # equivalent to stage 3, stage 6, stage 9, stage 12
40
+ backbone_config = Dinov2Config.from_pretrained(
41
+ "facebook/dinov2-small", out_indices=[3, 6, 9, 12], apply_layernorm=False, reshape_hidden_states=False
42
+ )
43
+ neck_hidden_sizes = [48, 96, 192, 384]
44
+ elif "base" in model_name:
45
+ backbone_config = Dinov2Config.from_pretrained(
46
+ "facebook/dinov2-base", out_indices=[3, 6, 9, 12], apply_layernorm=False, reshape_hidden_states=False
47
+ )
48
+ neck_hidden_sizes = [96, 192, 384, 768]
49
+ elif "large" in model_name:
50
+ backbone_config = Dinov2Config.from_pretrained(
51
+ "facebook/dinov2-large", out_indices=[5, 12, 18, 24], apply_layernorm=False, reshape_hidden_states=False
52
+ )
53
+ neck_hidden_sizes = [128, 256, 512, 1024]
54
+ elif "giant" in model_name:
55
+ backbone_config = Dinov2Config.from_pretrained(
56
+ "facebook/dinov2-giant", out_indices=[10, 20, 30, 40], apply_layernorm=False, reshape_hidden_states=False
57
+ )
58
+ neck_hidden_sizes = [192, 384, 768, 1536]
59
+ else:
60
+ raise NotImplementedError("To do")
61
+
62
+ config = DPTConfig(
63
+ backbone_config=backbone_config,
64
+ neck_hidden_sizes=neck_hidden_sizes,
65
+ use_bias_in_fusion_residual=False,
66
+ add_projection=True,
67
+ )
68
+
69
+ return config
70
+
71
+
72
+ # here we list all DPT keys to be renamed (original name on the left, our name on the right)
73
+ def create_rename_keys_dpt(config):
74
+ rename_keys = []
75
+
76
+ # fmt: off
77
+ # activation postprocessing (projections, readout projections + resize blocks)
78
+ for i in range(4):
79
+ rename_keys.append((f"decode_head.reassemble_blocks.projects.{i}.conv.weight", f"neck.reassemble_stage.layers.{i}.projection.weight"))
80
+ rename_keys.append((f"decode_head.reassemble_blocks.projects.{i}.conv.bias", f"neck.reassemble_stage.layers.{i}.projection.bias"))
81
+
82
+ rename_keys.append((f"decode_head.reassemble_blocks.readout_projects.{i}.0.weight", f"neck.reassemble_stage.readout_projects.{i}.0.weight"))
83
+ rename_keys.append((f"decode_head.reassemble_blocks.readout_projects.{i}.0.bias", f"neck.reassemble_stage.readout_projects.{i}.0.bias"))
84
+
85
+ if i != 2:
86
+ rename_keys.append((f"decode_head.reassemble_blocks.resize_layers.{i}.weight", f"neck.reassemble_stage.layers.{i}.resize.weight"))
87
+ rename_keys.append((f"decode_head.reassemble_blocks.resize_layers.{i}.bias", f"neck.reassemble_stage.layers.{i}.resize.bias"))
88
+
89
+ # fusion layers
90
+ for i in range(4):
91
+ rename_keys.append((f"decode_head.fusion_blocks.{i}.project.conv.weight", f"neck.fusion_stage.layers.{i}.projection.weight"))
92
+ rename_keys.append((f"decode_head.fusion_blocks.{i}.project.conv.bias", f"neck.fusion_stage.layers.{i}.projection.bias"))
93
+ if i != 0:
94
+ rename_keys.append((f"decode_head.fusion_blocks.{i}.res_conv_unit1.conv1.conv.weight", f"neck.fusion_stage.layers.{i}.residual_layer1.convolution1.weight"))
95
+ rename_keys.append((f"decode_head.fusion_blocks.{i}.res_conv_unit1.conv2.conv.weight", f"neck.fusion_stage.layers.{i}.residual_layer1.convolution2.weight"))
96
+ rename_keys.append((f"decode_head.fusion_blocks.{i}.res_conv_unit2.conv1.conv.weight", f"neck.fusion_stage.layers.{i}.residual_layer2.convolution1.weight"))
97
+ rename_keys.append((f"decode_head.fusion_blocks.{i}.res_conv_unit2.conv2.conv.weight", f"neck.fusion_stage.layers.{i}.residual_layer2.convolution2.weight"))
98
+
99
+ # neck convolutions
100
+ for i in range(4):
101
+ rename_keys.append((f"decode_head.convs.{i}.conv.weight", f"neck.convs.{i}.weight"))
102
+
103
+ # head
104
+ rename_keys.append(("decode_head.project.conv.weight", "head.projection.weight"))
105
+ rename_keys.append(("decode_head.project.conv.bias", "head.projection.bias"))
106
+
107
+ for i in range(0, 5, 2):
108
+ rename_keys.append((f"decode_head.conv_depth.head.{i}.weight", f"head.head.{i}.weight"))
109
+ rename_keys.append((f"decode_head.conv_depth.head.{i}.bias", f"head.head.{i}.bias"))
110
+ # fmt: on
111
+
112
+ return rename_keys
113
+
114
+
115
+ # here we list all backbone keys to be renamed (original name on the left, our name on the right)
116
+ def create_rename_keys_backbone(config):
117
+ rename_keys = []
118
+
119
+ # fmt: off
120
+ # patch embedding layer
121
+ rename_keys.append(("cls_token", "backbone.embeddings.cls_token"))
122
+ rename_keys.append(("mask_token", "backbone.embeddings.mask_token"))
123
+ rename_keys.append(("pos_embed", "backbone.embeddings.position_embeddings"))
124
+ rename_keys.append(("patch_embed.proj.weight", "backbone.embeddings.patch_embeddings.projection.weight"))
125
+ rename_keys.append(("patch_embed.proj.bias", "backbone.embeddings.patch_embeddings.projection.bias"))
126
+
127
+ # Transfomer encoder
128
+ for i in range(config.backbone_config.num_hidden_layers):
129
+ # layernorms
130
+ rename_keys.append((f"blocks.{i}.norm1.weight", f"backbone.encoder.layer.{i}.norm1.weight"))
131
+ rename_keys.append((f"blocks.{i}.norm1.bias", f"backbone.encoder.layer.{i}.norm1.bias"))
132
+ rename_keys.append((f"blocks.{i}.norm2.weight", f"backbone.encoder.layer.{i}.norm2.weight"))
133
+ rename_keys.append((f"blocks.{i}.norm2.bias", f"backbone.encoder.layer.{i}.norm2.bias"))
134
+ # MLP
135
+ if config.backbone_config.use_swiglu_ffn:
136
+ rename_keys.append((f"blocks.{i}.mlp.w12.weight", f"backbone.encoder.layer.{i}.mlp.w12.weight"))
137
+ rename_keys.append((f"blocks.{i}.mlp.w12.bias", f"backbone.encoder.layer.{i}.mlp.w12.bias"))
138
+ rename_keys.append((f"blocks.{i}.mlp.w3.weight", f"backbone.encoder.layer.{i}.mlp.w3.weight"))
139
+ rename_keys.append((f"blocks.{i}.mlp.w3.bias", f"backbone.encoder.layer.{i}.mlp.w3.bias"))
140
+ else:
141
+ rename_keys.append((f"blocks.{i}.mlp.fc1.weight", f"backbone.encoder.layer.{i}.mlp.fc1.weight"))
142
+ rename_keys.append((f"blocks.{i}.mlp.fc1.bias", f"backbone.encoder.layer.{i}.mlp.fc1.bias"))
143
+ rename_keys.append((f"blocks.{i}.mlp.fc2.weight", f"backbone.encoder.layer.{i}.mlp.fc2.weight"))
144
+ rename_keys.append((f"blocks.{i}.mlp.fc2.bias", f"backbone.encoder.layer.{i}.mlp.fc2.bias"))
145
+ # layerscale
146
+ rename_keys.append((f"blocks.{i}.ls1.gamma", f"backbone.encoder.layer.{i}.layer_scale1.lambda1"))
147
+ rename_keys.append((f"blocks.{i}.ls2.gamma", f"backbone.encoder.layer.{i}.layer_scale2.lambda1"))
148
+ # attention projection layer
149
+ rename_keys.append((f"blocks.{i}.attn.proj.weight", f"backbone.encoder.layer.{i}.attention.output.dense.weight"))
150
+ rename_keys.append((f"blocks.{i}.attn.proj.bias", f"backbone.encoder.layer.{i}.attention.output.dense.bias"))
151
+ # fmt: on
152
+
153
+ rename_keys.append(("norm.weight", "backbone.layernorm.weight"))
154
+ rename_keys.append(("norm.bias", "backbone.layernorm.bias"))
155
+
156
+ return rename_keys
157
+
158
+
159
+ # we split up the matrix of each encoder layer into queries, keys and values
160
+ def read_in_q_k_v(state_dict, config):
161
+ for i in range(config.backbone_config.num_hidden_layers):
162
+ # read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
163
+ in_proj_weight = state_dict.pop(f"blocks.{i}.attn.qkv.weight")
164
+ in_proj_bias = state_dict.pop(f"blocks.{i}.attn.qkv.bias")
165
+ hidden_size = config.backbone_config.hidden_size
166
+ # next, add query, keys and values (in that order) to the state dict
167
+ state_dict[f"backbone.encoder.layer.{i}.attention.attention.query.weight"] = in_proj_weight[:hidden_size, :]
168
+ state_dict[f"backbone.encoder.layer.{i}.attention.attention.query.bias"] = in_proj_bias[:hidden_size]
169
+ state_dict[f"backbone.encoder.layer.{i}.attention.attention.key.weight"] = in_proj_weight[
170
+ hidden_size : hidden_size * 2, :
171
+ ]
172
+ state_dict[f"backbone.encoder.layer.{i}.attention.attention.key.bias"] = in_proj_bias[
173
+ hidden_size : hidden_size * 2
174
+ ]
175
+ state_dict[f"backbone.encoder.layer.{i}.attention.attention.value.weight"] = in_proj_weight[-hidden_size:, :]
176
+ state_dict[f"backbone.encoder.layer.{i}.attention.attention.value.bias"] = in_proj_bias[-hidden_size:]
177
+
178
+
179
+ def rename_key(dct, old, new):
180
+ val = dct.pop(old)
181
+ dct[new] = val
182
+
183
+
184
+ # We will verify our results on an image of cute cats
185
+ def prepare_img():
186
+ url = "https://dl.fbaipublicfiles.com/dinov2/images/example.jpg"
187
+ im = Image.open(requests.get(url, stream=True).raw)
188
+ return im
189
+
190
+
191
+ name_to_url = {
192
+ "dpt-dinov2-small-nyu": "https://dl.fbaipublicfiles.com/dinov2/dinov2_vits14/dinov2_vits14_nyu_dpt_head.pth",
193
+ "dpt-dinov2-small-kitti": "https://dl.fbaipublicfiles.com/dinov2/dinov2_vits14/dinov2_vits14_kitti_dpt_head.pth",
194
+ "dpt-dinov2-base-nyu": "https://dl.fbaipublicfiles.com/dinov2/dinov2_vitb14/dinov2_vitb14_nyu_dpt_head.pth",
195
+ "dpt-dinov2-base-kitti": "https://dl.fbaipublicfiles.com/dinov2/dinov2_vitb14/dinov2_vitb14_kitti_dpt_head.pth",
196
+ "dpt-dinov2-large-nyu": "https://dl.fbaipublicfiles.com/dinov2/dinov2_vitl14/dinov2_vitl14_nyu_dpt_head.pth",
197
+ "dpt-dinov2-large-kitti": "https://dl.fbaipublicfiles.com/dinov2/dinov2_vitl14/dinov2_vitl14_kitti_dpt_head.pth",
198
+ "dpt-dinov2-giant-nyu": "https://dl.fbaipublicfiles.com/dinov2/dinov2_vitg14/dinov2_vitg14_nyu_dpt_head.pth",
199
+ "dpt-dinov2-giant-kitti": "https://dl.fbaipublicfiles.com/dinov2/dinov2_vitg14/dinov2_vitg14_kitti_dpt_head.pth",
200
+ }
201
+
202
+
203
+ def get_original_pixel_values(image):
204
+ class CenterPadding(object):
205
+ def __init__(self, multiple):
206
+ super().__init__()
207
+ self.multiple = multiple
208
+
209
+ def _get_pad(self, size):
210
+ new_size = math.ceil(size / self.multiple) * self.multiple
211
+ pad_size = new_size - size
212
+ pad_size_left = pad_size // 2
213
+ pad_size_right = pad_size - pad_size_left
214
+ return pad_size_left, pad_size_right
215
+
216
+ def __call__(self, img):
217
+ pads = list(itertools.chain.from_iterable(self._get_pad(m) for m in img.shape[-2:][::-1]))
218
+ output = torch.nn.functional.pad(img, pads)
219
+ return output
220
+
221
+ def __repr__(self):
222
+ return self.__class__.__name__ + "()"
223
+
224
+ def make_depth_transform() -> transforms.Compose:
225
+ return transforms.Compose(
226
+ [
227
+ transforms.ToTensor(),
228
+ lambda x: 255.0 * x[:3], # Discard alpha component and scale by 255
229
+ transforms.Normalize(
230
+ mean=(123.675, 116.28, 103.53),
231
+ std=(58.395, 57.12, 57.375),
232
+ ),
233
+ CenterPadding(multiple=14),
234
+ ]
235
+ )
236
+
237
+ transform = make_depth_transform()
238
+ original_pixel_values = transform(image).unsqueeze(0)
239
+
240
+ return original_pixel_values
241
+
242
+
243
+ @torch.no_grad()
244
+ def convert_dpt_checkpoint(model_name, pytorch_dump_folder_path, push_to_hub, verify_logits):
245
+ """
246
+ Copy/paste/tweak model's weights to our DPT structure.
247
+ """
248
+
249
+ # define DPT configuration based on URL
250
+ checkpoint_url = name_to_url[model_name]
251
+ config = get_dpt_config(model_name)
252
+
253
+ # load original DPT state_dict from URL
254
+ print("URL:", checkpoint_url)
255
+ dpt_state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu")["state_dict"]
256
+ # rename keys
257
+ rename_keys = create_rename_keys_dpt(config)
258
+ for src, dest in rename_keys:
259
+ rename_key(dpt_state_dict, src, dest)
260
+
261
+ # load original backbone state_dict from URL
262
+ if "small" in model_name:
263
+ original_model = torch.hub.load("facebookresearch/dinov2", "dinov2_vits14")
264
+ elif "base" in model_name:
265
+ original_model = torch.hub.load("facebookresearch/dinov2", "dinov2_vitb14")
266
+ elif "large" in model_name:
267
+ original_model = torch.hub.load("facebookresearch/dinov2", "dinov2_vitl14")
268
+ elif "giant" in model_name:
269
+ original_model = torch.hub.load("facebookresearch/dinov2", "dinov2_vitg14")
270
+ else:
271
+ raise NotImplementedError("To do")
272
+ original_model.eval()
273
+ backbone_state_dict = original_model.state_dict()
274
+
275
+ # rename keys
276
+ rename_keys = create_rename_keys_backbone(config)
277
+ for src, dest in rename_keys:
278
+ rename_key(backbone_state_dict, src, dest)
279
+
280
+ # read in qkv matrices
281
+ read_in_q_k_v(backbone_state_dict, config)
282
+
283
+ for key, val in backbone_state_dict.copy().items():
284
+ val = backbone_state_dict.pop(key)
285
+ if "w12" in key:
286
+ key = key.replace("w12", "weights_in")
287
+ if "w3" in key:
288
+ key = key.replace("w3", "weights_out")
289
+ backbone_state_dict[key] = val
290
+
291
+ # merge state_dicts
292
+ state_dict = {**backbone_state_dict, **dpt_state_dict}
293
+
294
+ # load HuggingFace model
295
+ model = DPTForDepthEstimation(config)
296
+ missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False)
297
+ print("Missing keys:", missing_keys)
298
+ print("Unexpected keys:", unexpected_keys)
299
+ assert missing_keys == [
300
+ "neck.fusion_stage.layers.0.residual_layer1.convolution1.weight",
301
+ "neck.fusion_stage.layers.0.residual_layer1.convolution2.weight",
302
+ ]
303
+ model.eval()
304
+
305
+ # Verify image processor
306
+ processor = DPTImageProcessor(
307
+ do_resize=False,
308
+ do_rescale=False,
309
+ do_pad=True,
310
+ size_divisor=14,
311
+ do_normalize=True,
312
+ image_mean=(123.675, 116.28, 103.53),
313
+ image_std=(58.395, 57.12, 57.375),
314
+ )
315
+
316
+ image = prepare_img()
317
+ pixel_values = processor(image, return_tensors="pt").pixel_values.float()
318
+ original_pixel_values = get_original_pixel_values(image)
319
+
320
+ assert torch.allclose(pixel_values, original_pixel_values)
321
+
322
+ # Verify forward pass
323
+ with torch.no_grad():
324
+ outputs = model(pixel_values)
325
+
326
+ predicted_depth = outputs.predicted_depth
327
+
328
+ print("Shape of predicted depth:", predicted_depth.shape)
329
+ print("First values of predicted depth:", predicted_depth[0, :3, :3])
330
+
331
+ # assert logits
332
+ if verify_logits:
333
+ if model_name == "dpt-dinov2-small-nyu":
334
+ expected_shape = torch.Size([1, 576, 736])
335
+ expected_slice = torch.tensor(
336
+ [[3.3576, 3.4741, 3.4345], [3.4324, 3.5012, 3.2775], [3.2560, 3.3563, 3.2354]]
337
+ )
338
+
339
+ assert predicted_depth.shape == torch.Size(expected_shape)
340
+ assert torch.allclose(predicted_depth[0, :3, :3], expected_slice, atol=1e-5)
341
+ print("Looks ok!")
342
+
343
+ if pytorch_dump_folder_path is not None:
344
+ Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
345
+ print(f"Saving model and processor to {pytorch_dump_folder_path}")
346
+ model.save_pretrained(pytorch_dump_folder_path)
347
+ processor.save_pretrained(pytorch_dump_folder_path)
348
+
349
+ if push_to_hub:
350
+ print("Pushing model and processor to hub...")
351
+ model.push_to_hub(repo_id=f"facebook/{model_name}")
352
+ processor.push_to_hub(repo_id=f"facebook/{model_name}")
353
+
354
+
355
+ if __name__ == "__main__":
356
+ parser = argparse.ArgumentParser()
357
+ # Required parameters
358
+ parser.add_argument(
359
+ "--model_name",
360
+ default="dpt-dinov2-small-nyu",
361
+ type=str,
362
+ choices=name_to_url.keys(),
363
+ help="Name of the model you'd like to convert.",
364
+ )
365
+ parser.add_argument(
366
+ "--pytorch_dump_folder_path",
367
+ default=None,
368
+ type=str,
369
+ help="Path to the output PyTorch model directory.",
370
+ )
371
+ parser.add_argument(
372
+ "--push_to_hub",
373
+ action="store_true",
374
+ help="Whether to push the model to the hub after conversion.",
375
+ )
376
+ parser.add_argument(
377
+ "--verify_logits",
378
+ action="store_true",
379
+ required=False,
380
+ help="Path to the output PyTorch model directory.",
381
+ )
382
+
383
+ args = parser.parse_args()
384
+ convert_dpt_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub, args.verify_logits)
SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/convert_dpt_beit_to_hf.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Inc. team.
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
+ """Convert DPT 3.1 checkpoints from the MiDaS repository. URL: https://github.com/isl-org/MiDaS"""
16
+
17
+
18
+ import argparse
19
+ from pathlib import Path
20
+
21
+ import requests
22
+ import torch
23
+ from PIL import Image
24
+
25
+ from transformers import BeitConfig, DPTConfig, DPTForDepthEstimation, DPTImageProcessor
26
+ from transformers.utils import logging
27
+
28
+
29
+ logging.set_verbosity_info()
30
+ logger = logging.get_logger(__name__)
31
+
32
+
33
+ def get_dpt_config(model_name):
34
+ hidden_size = 768
35
+ num_hidden_layers = 12
36
+ num_attention_heads = 12
37
+ intermediate_size = 3072
38
+ out_features = ["stage3", "stage6", "stage9", "stage12"] # beit-base-384 uses [2, 5, 8, 11]
39
+
40
+ if "large" in model_name:
41
+ hidden_size = 1024
42
+ num_hidden_layers = 24
43
+ num_attention_heads = 16
44
+ intermediate_size = 4096
45
+ out_features = ["stage6", "stage12", "stage18", "stage24"] # beit-large-512 uses [5, 11, 17, 23]
46
+
47
+ if "512" in model_name:
48
+ image_size = 512
49
+ elif "384" in model_name:
50
+ image_size = 384
51
+ else:
52
+ raise ValueError("Model not supported")
53
+
54
+ backbone_config = BeitConfig(
55
+ image_size=image_size,
56
+ num_hidden_layers=num_hidden_layers,
57
+ hidden_size=hidden_size,
58
+ intermediate_size=intermediate_size,
59
+ num_attention_heads=num_attention_heads,
60
+ use_relative_position_bias=True,
61
+ reshape_hidden_states=False,
62
+ out_features=out_features,
63
+ )
64
+
65
+ neck_hidden_sizes = [256, 512, 1024, 1024] if "large" in model_name else [96, 192, 384, 768]
66
+ config = DPTConfig(backbone_config=backbone_config, neck_hidden_sizes=neck_hidden_sizes)
67
+
68
+ return config, image_size
69
+
70
+
71
+ # here we list all keys to be renamed (original name on the left, our name on the right)
72
+ def create_rename_keys(config):
73
+ rename_keys = []
74
+
75
+ # fmt: off
76
+ # stem
77
+ rename_keys.append(("pretrained.model.cls_token", "backbone.embeddings.cls_token"))
78
+ rename_keys.append(("pretrained.model.patch_embed.proj.weight", "backbone.embeddings.patch_embeddings.projection.weight"))
79
+ rename_keys.append(("pretrained.model.patch_embed.proj.bias", "backbone.embeddings.patch_embeddings.projection.bias"))
80
+
81
+ # Transfomer encoder
82
+ for i in range(config.backbone_config.num_hidden_layers):
83
+ rename_keys.append((f"pretrained.model.blocks.{i}.gamma_1", f"backbone.encoder.layer.{i}.lambda_1"))
84
+ rename_keys.append((f"pretrained.model.blocks.{i}.gamma_2", f"backbone.encoder.layer.{i}.lambda_2"))
85
+ rename_keys.append((f"pretrained.model.blocks.{i}.norm1.weight", f"backbone.encoder.layer.{i}.layernorm_before.weight"))
86
+ rename_keys.append((f"pretrained.model.blocks.{i}.norm1.bias", f"backbone.encoder.layer.{i}.layernorm_before.bias"))
87
+ rename_keys.append((f"pretrained.model.blocks.{i}.norm2.weight", f"backbone.encoder.layer.{i}.layernorm_after.weight"))
88
+ rename_keys.append((f"pretrained.model.blocks.{i}.norm2.bias", f"backbone.encoder.layer.{i}.layernorm_after.bias"))
89
+ rename_keys.append((f"pretrained.model.blocks.{i}.mlp.fc1.weight", f"backbone.encoder.layer.{i}.intermediate.dense.weight"))
90
+ rename_keys.append((f"pretrained.model.blocks.{i}.mlp.fc1.bias", f"backbone.encoder.layer.{i}.intermediate.dense.bias"))
91
+ rename_keys.append((f"pretrained.model.blocks.{i}.mlp.fc2.weight", f"backbone.encoder.layer.{i}.output.dense.weight"))
92
+ rename_keys.append((f"pretrained.model.blocks.{i}.mlp.fc2.bias", f"backbone.encoder.layer.{i}.output.dense.bias"))
93
+ rename_keys.append((f"pretrained.model.blocks.{i}.attn.proj.weight", f"backbone.encoder.layer.{i}.attention.output.dense.weight"))
94
+ rename_keys.append((f"pretrained.model.blocks.{i}.attn.proj.bias", f"backbone.encoder.layer.{i}.attention.output.dense.bias"))
95
+ rename_keys.append((f"pretrained.model.blocks.{i}.attn.relative_position_bias_table", f"backbone.encoder.layer.{i}.attention.attention.relative_position_bias.relative_position_bias_table"))
96
+ rename_keys.append((f"pretrained.model.blocks.{i}.attn.relative_position_index", f"backbone.encoder.layer.{i}.attention.attention.relative_position_bias.relative_position_index"))
97
+
98
+ # activation postprocessing (readout projections + resize blocks)
99
+ for i in range(4):
100
+ rename_keys.append((f"pretrained.act_postprocess{i+1}.0.project.0.weight", f"neck.reassemble_stage.readout_projects.{i}.0.weight"))
101
+ rename_keys.append((f"pretrained.act_postprocess{i+1}.0.project.0.bias", f"neck.reassemble_stage.readout_projects.{i}.0.bias"))
102
+
103
+ rename_keys.append((f"pretrained.act_postprocess{i+1}.3.weight", f"neck.reassemble_stage.layers.{i}.projection.weight"))
104
+ rename_keys.append((f"pretrained.act_postprocess{i+1}.3.bias", f"neck.reassemble_stage.layers.{i}.projection.bias"))
105
+
106
+ if i != 2:
107
+ rename_keys.append((f"pretrained.act_postprocess{i+1}.4.weight", f"neck.reassemble_stage.layers.{i}.resize.weight"))
108
+ rename_keys.append((f"pretrained.act_postprocess{i+1}.4.bias", f"neck.reassemble_stage.layers.{i}.resize.bias"))
109
+
110
+ # refinenet (tricky here)
111
+ mapping = {1:3, 2:2, 3:1, 4:0}
112
+
113
+ for i in range(1, 5):
114
+ j = mapping[i]
115
+ rename_keys.append((f"scratch.refinenet{i}.out_conv.weight", f"neck.fusion_stage.layers.{j}.projection.weight"))
116
+ rename_keys.append((f"scratch.refinenet{i}.out_conv.bias", f"neck.fusion_stage.layers.{j}.projection.bias"))
117
+ rename_keys.append((f"scratch.refinenet{i}.resConfUnit1.conv1.weight", f"neck.fusion_stage.layers.{j}.residual_layer1.convolution1.weight"))
118
+ rename_keys.append((f"scratch.refinenet{i}.resConfUnit1.conv1.bias", f"neck.fusion_stage.layers.{j}.residual_layer1.convolution1.bias"))
119
+ rename_keys.append((f"scratch.refinenet{i}.resConfUnit1.conv2.weight", f"neck.fusion_stage.layers.{j}.residual_layer1.convolution2.weight"))
120
+ rename_keys.append((f"scratch.refinenet{i}.resConfUnit1.conv2.bias", f"neck.fusion_stage.layers.{j}.residual_layer1.convolution2.bias"))
121
+ rename_keys.append((f"scratch.refinenet{i}.resConfUnit2.conv1.weight", f"neck.fusion_stage.layers.{j}.residual_layer2.convolution1.weight"))
122
+ rename_keys.append((f"scratch.refinenet{i}.resConfUnit2.conv1.bias", f"neck.fusion_stage.layers.{j}.residual_layer2.convolution1.bias"))
123
+ rename_keys.append((f"scratch.refinenet{i}.resConfUnit2.conv2.weight", f"neck.fusion_stage.layers.{j}.residual_layer2.convolution2.weight"))
124
+ rename_keys.append((f"scratch.refinenet{i}.resConfUnit2.conv2.bias", f"neck.fusion_stage.layers.{j}.residual_layer2.convolution2.bias"))
125
+
126
+ # scratch convolutions
127
+ for i in range(4):
128
+ rename_keys.append((f"scratch.layer{i+1}_rn.weight", f"neck.convs.{i}.weight"))
129
+
130
+ # head
131
+ for i in range(0, 5, 2):
132
+ rename_keys.append((f"scratch.output_conv.{i}.weight", f"head.head.{i}.weight"))
133
+ rename_keys.append((f"scratch.output_conv.{i}.bias", f"head.head.{i}.bias"))
134
+
135
+ return rename_keys
136
+
137
+
138
+ def remove_ignore_keys_(state_dict):
139
+ ignore_keys = ["pretrained.model.head.weight", "pretrained.model.head.bias"]
140
+ for k in ignore_keys:
141
+ state_dict.pop(k, None)
142
+
143
+
144
+ # we split up the matrix of each encoder layer into queries, keys and values
145
+ def read_in_q_k_v(state_dict, config):
146
+ hidden_size = config.backbone_config.hidden_size
147
+ for i in range(config.backbone_config.num_hidden_layers):
148
+ # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias)
149
+ in_proj_weight = state_dict.pop(f"pretrained.model.blocks.{i}.attn.qkv.weight")
150
+ q_bias = state_dict.pop(f"pretrained.model.blocks.{i}.attn.q_bias")
151
+ v_bias = state_dict.pop(f"pretrained.model.blocks.{i}.attn.v_bias")
152
+ # next, add query, keys and values (in that order) to the state dict
153
+ state_dict[f"backbone.encoder.layer.{i}.attention.attention.query.weight"] = in_proj_weight[:hidden_size, :]
154
+ state_dict[f"backbone.encoder.layer.{i}.attention.attention.query.bias"] = q_bias
155
+ state_dict[f"backbone.encoder.layer.{i}.attention.attention.key.weight"] = in_proj_weight[
156
+ hidden_size : hidden_size * 2, :
157
+ ]
158
+ state_dict[f"backbone.encoder.layer.{i}.attention.attention.value.weight"] = in_proj_weight[-hidden_size:, :]
159
+ state_dict[f"backbone.encoder.layer.{i}.attention.attention.value.bias"] = v_bias
160
+
161
+
162
+ def rename_key(dct, old, new):
163
+ val = dct.pop(old)
164
+ dct[new] = val
165
+
166
+
167
+ # We will verify our results on an image of cute cats
168
+ def prepare_img():
169
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
170
+ im = Image.open(requests.get(url, stream=True).raw)
171
+ return im
172
+
173
+
174
+ @torch.no_grad()
175
+ def convert_dpt_checkpoint(model_name, pytorch_dump_folder_path, push_to_hub):
176
+ """
177
+ Copy/paste/tweak model's weights to our DPT structure.
178
+ """
179
+
180
+ name_to_url = {
181
+ "dpt-beit-large-512": "https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_beit_large_512.pt",
182
+ "dpt-beit-large-384": "https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_beit_large_384.pt",
183
+ "dpt-beit-base-384": "https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_beit_base_384.pt",
184
+ }
185
+
186
+ # define DPT configuration based on URL
187
+ checkpoint_url = name_to_url[model_name]
188
+ config, image_size = get_dpt_config(model_name)
189
+ # load original state_dict from URL
190
+ state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu")
191
+ # remove certain keys
192
+ remove_ignore_keys_(state_dict)
193
+ # rename keys
194
+ rename_keys = create_rename_keys(config)
195
+ for src, dest in rename_keys:
196
+ rename_key(state_dict, src, dest)
197
+ # read in qkv matrices
198
+ read_in_q_k_v(state_dict, config)
199
+
200
+ # load HuggingFace model
201
+ model = DPTForDepthEstimation(config)
202
+ missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False)
203
+ print("Missing keys:", missing_keys)
204
+ print("Unexpected keys:", unexpected_keys)
205
+ assert missing_keys == []
206
+ # assert unexpected_keys == ["pretrained.model.fc_norm.weight", "pretrained.model.fc_norm.bias"]
207
+ model.eval()
208
+
209
+ # Check outputs on an image
210
+ # We set `keep_aspect_ratio=False` as our current BEiT does not support arbitrary window sizes
211
+ processor = DPTImageProcessor(
212
+ size={"height": image_size, "width": image_size}, keep_aspect_ratio=False, ensure_multiple_of=32
213
+ )
214
+
215
+ image = prepare_img()
216
+ pixel_values = processor(image, return_tensors="pt").pixel_values
217
+
218
+ print("First values of pixel values:", pixel_values[0, 0, :3, :3])
219
+ print("Mean of pixel values:", pixel_values.mean().item())
220
+ print("Shape of pixel values:", pixel_values.shape)
221
+
222
+ import requests
223
+ from PIL import Image
224
+ from torchvision import transforms
225
+
226
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
227
+ image = Image.open(requests.get(url, stream=True).raw)
228
+
229
+ transforms = transforms.Compose(
230
+ [
231
+ transforms.Resize((image_size, image_size)),
232
+ transforms.ToTensor(),
233
+ ]
234
+ )
235
+ pixel_values = transforms(image).unsqueeze(0)
236
+
237
+ # forward pass
238
+ with torch.no_grad():
239
+ outputs = model(pixel_values)
240
+
241
+ predicted_depth = outputs.predicted_depth
242
+
243
+ print("Shape of predicted depth:", predicted_depth.shape)
244
+ print("First values of predicted depth:", predicted_depth[0, :3, :3])
245
+
246
+ # assert logits
247
+ # TODO there's still a small difference with the original logits
248
+ if model_name == "dpt-beit-large-512":
249
+ # OK, checked
250
+ expected_shape = torch.Size([1, 512, 512])
251
+ expected_slice = torch.tensor(
252
+ [[2804.6260, 2792.5708, 2812.9263], [2772.0288, 2780.1118, 2796.2529], [2748.1094, 2766.6558, 2766.9834]]
253
+ )
254
+ elif model_name == "dpt-beit-large-384":
255
+ # OK, checked
256
+ expected_shape = torch.Size([1, 384, 384])
257
+ expected_slice = torch.tensor(
258
+ [[1783.2273, 1780.5729, 1792.6453], [1759.9817, 1765.5359, 1778.5002], [1739.1633, 1754.7903, 1757.1990]],
259
+ )
260
+ elif model_name == "dpt-beit-base-384":
261
+ # OK, checked
262
+ expected_shape = torch.Size([1, 384, 384])
263
+ expected_slice = torch.tensor(
264
+ [[2898.4482, 2891.3750, 2904.8079], [2858.6685, 2877.2615, 2894.4507], [2842.1235, 2854.1023, 2861.6328]],
265
+ )
266
+
267
+ assert predicted_depth.shape == torch.Size(expected_shape)
268
+ assert torch.allclose(predicted_depth[0, :3, :3], expected_slice)
269
+ print("Looks ok!")
270
+
271
+ if pytorch_dump_folder_path is not None:
272
+ Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
273
+ print(f"Saving model and processor to {pytorch_dump_folder_path}")
274
+ model.save_pretrained(pytorch_dump_folder_path)
275
+ processor.save_pretrained(pytorch_dump_folder_path)
276
+
277
+ if push_to_hub:
278
+ print("Pushing model and processor to hub...")
279
+ model.push_to_hub(repo_id=f"nielsr/{model_name}")
280
+ processor.push_to_hub(repo_id=f"nielsr/{model_name}")
281
+
282
+
283
+ if __name__ == "__main__":
284
+ parser = argparse.ArgumentParser()
285
+ # Required parameters
286
+ parser.add_argument(
287
+ "--model_name",
288
+ default="dpt-beit-large-512",
289
+ type=str,
290
+ choices=["dpt-beit-large-512", "dpt-beit-large-384", "dpt-beit-base-384"],
291
+ help="Name of the model you'd like to convert.",
292
+ )
293
+ parser.add_argument(
294
+ "--pytorch_dump_folder_path",
295
+ default=None,
296
+ type=str,
297
+ help="Path to the output PyTorch model directory.",
298
+ )
299
+ parser.add_argument(
300
+ "--push_to_hub",
301
+ action="store_true",
302
+ help="Whether to push the model to the hub after conversion.",
303
+ )
304
+
305
+ args = parser.parse_args()
306
+ convert_dpt_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/convert_dpt_hybrid_to_pytorch.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
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
+ """Convert DPT checkpoints from the original repository. URL: https://github.com/isl-org/DPT"""
16
+
17
+
18
+ import argparse
19
+ import json
20
+ from pathlib import Path
21
+
22
+ import requests
23
+ import torch
24
+ from huggingface_hub import cached_download, hf_hub_url
25
+ from PIL import Image
26
+
27
+ from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor
28
+ from transformers.utils import logging
29
+
30
+
31
+ logging.set_verbosity_info()
32
+ logger = logging.get_logger(__name__)
33
+
34
+
35
+ def get_dpt_config(checkpoint_url):
36
+ config = DPTConfig(embedding_type="hybrid")
37
+
38
+ if "large" in checkpoint_url:
39
+ config.hidden_size = 1024
40
+ config.intermediate_size = 4096
41
+ config.num_hidden_layers = 24
42
+ config.num_attention_heads = 16
43
+ config.backbone_out_indices = [5, 11, 17, 23]
44
+ config.neck_hidden_sizes = [256, 512, 1024, 1024]
45
+ expected_shape = (1, 384, 384)
46
+
47
+ if "nyu" or "midas" in checkpoint_url:
48
+ config.hidden_size = 768
49
+ config.reassemble_factors = [1, 1, 1, 0.5]
50
+ config.neck_hidden_sizes = [256, 512, 768, 768]
51
+ config.num_labels = 150
52
+ config.patch_size = 16
53
+ expected_shape = (1, 384, 384)
54
+ config.use_batch_norm_in_fusion_residual = False
55
+ config.readout_type = "project"
56
+
57
+ if "ade" in checkpoint_url:
58
+ config.use_batch_norm_in_fusion_residual = True
59
+ config.hidden_size = 768
60
+ config.reassemble_stage = [1, 1, 1, 0.5]
61
+ config.num_labels = 150
62
+ config.patch_size = 16
63
+ repo_id = "huggingface/label-files"
64
+ filename = "ade20k-id2label.json"
65
+ id2label = json.load(open(cached_download(hf_hub_url(repo_id, filename, repo_type="dataset")), "r"))
66
+ id2label = {int(k): v for k, v in id2label.items()}
67
+ config.id2label = id2label
68
+ config.label2id = {v: k for k, v in id2label.items()}
69
+ expected_shape = [1, 150, 480, 480]
70
+
71
+ return config, expected_shape
72
+
73
+
74
+ def remove_ignore_keys_(state_dict):
75
+ ignore_keys = ["pretrained.model.head.weight", "pretrained.model.head.bias"]
76
+ for k in ignore_keys:
77
+ state_dict.pop(k, None)
78
+
79
+
80
+ def rename_key(name):
81
+ if (
82
+ "pretrained.model" in name
83
+ and "cls_token" not in name
84
+ and "pos_embed" not in name
85
+ and "patch_embed" not in name
86
+ ):
87
+ name = name.replace("pretrained.model", "dpt.encoder")
88
+ if "pretrained.model" in name:
89
+ name = name.replace("pretrained.model", "dpt.embeddings")
90
+ if "patch_embed" in name:
91
+ name = name.replace("patch_embed", "")
92
+ if "pos_embed" in name:
93
+ name = name.replace("pos_embed", "position_embeddings")
94
+ if "attn.proj" in name:
95
+ name = name.replace("attn.proj", "attention.output.dense")
96
+ if "proj" in name and "project" not in name:
97
+ name = name.replace("proj", "projection")
98
+ if "blocks" in name:
99
+ name = name.replace("blocks", "layer")
100
+ if "mlp.fc1" in name:
101
+ name = name.replace("mlp.fc1", "intermediate.dense")
102
+ if "mlp.fc2" in name:
103
+ name = name.replace("mlp.fc2", "output.dense")
104
+ if "norm1" in name and "backbone" not in name:
105
+ name = name.replace("norm1", "layernorm_before")
106
+ if "norm2" in name and "backbone" not in name:
107
+ name = name.replace("norm2", "layernorm_after")
108
+ if "scratch.output_conv" in name:
109
+ name = name.replace("scratch.output_conv", "head")
110
+ if "scratch" in name:
111
+ name = name.replace("scratch", "neck")
112
+ if "layer1_rn" in name:
113
+ name = name.replace("layer1_rn", "convs.0")
114
+ if "layer2_rn" in name:
115
+ name = name.replace("layer2_rn", "convs.1")
116
+ if "layer3_rn" in name:
117
+ name = name.replace("layer3_rn", "convs.2")
118
+ if "layer4_rn" in name:
119
+ name = name.replace("layer4_rn", "convs.3")
120
+ if "refinenet" in name:
121
+ layer_idx = int(name[len("neck.refinenet") : len("neck.refinenet") + 1])
122
+ # tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3
123
+ name = name.replace(f"refinenet{layer_idx}", f"fusion_stage.layers.{abs(layer_idx-4)}")
124
+ if "out_conv" in name:
125
+ name = name.replace("out_conv", "projection")
126
+ if "resConfUnit1" in name:
127
+ name = name.replace("resConfUnit1", "residual_layer1")
128
+ if "resConfUnit2" in name:
129
+ name = name.replace("resConfUnit2", "residual_layer2")
130
+ if "conv1" in name:
131
+ name = name.replace("conv1", "convolution1")
132
+ if "conv2" in name:
133
+ name = name.replace("conv2", "convolution2")
134
+ # readout blocks
135
+ if "pretrained.act_postprocess1.0.project.0" in name:
136
+ name = name.replace("pretrained.act_postprocess1.0.project.0", "neck.reassemble_stage.readout_projects.0.0")
137
+ if "pretrained.act_postprocess2.0.project.0" in name:
138
+ name = name.replace("pretrained.act_postprocess2.0.project.0", "neck.reassemble_stage.readout_projects.1.0")
139
+ if "pretrained.act_postprocess3.0.project.0" in name:
140
+ name = name.replace("pretrained.act_postprocess3.0.project.0", "neck.reassemble_stage.readout_projects.2.0")
141
+ if "pretrained.act_postprocess4.0.project.0" in name:
142
+ name = name.replace("pretrained.act_postprocess4.0.project.0", "neck.reassemble_stage.readout_projects.3.0")
143
+
144
+ # resize blocks
145
+ if "pretrained.act_postprocess1.3" in name:
146
+ name = name.replace("pretrained.act_postprocess1.3", "neck.reassemble_stage.layers.0.projection")
147
+ if "pretrained.act_postprocess1.4" in name:
148
+ name = name.replace("pretrained.act_postprocess1.4", "neck.reassemble_stage.layers.0.resize")
149
+ if "pretrained.act_postprocess2.3" in name:
150
+ name = name.replace("pretrained.act_postprocess2.3", "neck.reassemble_stage.layers.1.projection")
151
+ if "pretrained.act_postprocess2.4" in name:
152
+ name = name.replace("pretrained.act_postprocess2.4", "neck.reassemble_stage.layers.1.resize")
153
+ if "pretrained.act_postprocess3.3" in name:
154
+ name = name.replace("pretrained.act_postprocess3.3", "neck.reassemble_stage.layers.2.projection")
155
+ if "pretrained.act_postprocess4.3" in name:
156
+ name = name.replace("pretrained.act_postprocess4.3", "neck.reassemble_stage.layers.3.projection")
157
+ if "pretrained.act_postprocess4.4" in name:
158
+ name = name.replace("pretrained.act_postprocess4.4", "neck.reassemble_stage.layers.3.resize")
159
+ if "pretrained" in name:
160
+ name = name.replace("pretrained", "dpt")
161
+ if "bn" in name:
162
+ name = name.replace("bn", "batch_norm")
163
+ if "head" in name:
164
+ name = name.replace("head", "head.head")
165
+ if "encoder.norm" in name:
166
+ name = name.replace("encoder.norm", "layernorm")
167
+ if "auxlayer" in name:
168
+ name = name.replace("auxlayer", "auxiliary_head.head")
169
+ if "backbone" in name:
170
+ name = name.replace("backbone", "backbone.bit.encoder")
171
+
172
+ if ".." in name:
173
+ name = name.replace("..", ".")
174
+
175
+ if "stem.conv" in name:
176
+ name = name.replace("stem.conv", "bit.embedder.convolution")
177
+ if "blocks" in name:
178
+ name = name.replace("blocks", "layers")
179
+ if "convolution" in name and "backbone" in name:
180
+ name = name.replace("convolution", "conv")
181
+ if "layer" in name and "backbone" in name:
182
+ name = name.replace("layer", "layers")
183
+ if "backbone.bit.encoder.bit" in name:
184
+ name = name.replace("backbone.bit.encoder.bit", "backbone.bit")
185
+ if "embedder.conv" in name:
186
+ name = name.replace("embedder.conv", "embedder.convolution")
187
+ if "backbone.bit.encoder.stem.norm" in name:
188
+ name = name.replace("backbone.bit.encoder.stem.norm", "backbone.bit.embedder.norm")
189
+ return name
190
+
191
+
192
+ # we split up the matrix of each encoder layer into queries, keys and values
193
+ def read_in_q_k_v(state_dict, config):
194
+ for i in range(config.num_hidden_layers):
195
+ # read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
196
+ in_proj_weight = state_dict.pop(f"dpt.encoder.layer.{i}.attn.qkv.weight")
197
+ in_proj_bias = state_dict.pop(f"dpt.encoder.layer.{i}.attn.qkv.bias")
198
+ # next, add query, keys and values (in that order) to the state dict
199
+ state_dict[f"dpt.encoder.layer.{i}.attention.attention.query.weight"] = in_proj_weight[: config.hidden_size, :]
200
+ state_dict[f"dpt.encoder.layer.{i}.attention.attention.query.bias"] = in_proj_bias[: config.hidden_size]
201
+ state_dict[f"dpt.encoder.layer.{i}.attention.attention.key.weight"] = in_proj_weight[
202
+ config.hidden_size : config.hidden_size * 2, :
203
+ ]
204
+ state_dict[f"dpt.encoder.layer.{i}.attention.attention.key.bias"] = in_proj_bias[
205
+ config.hidden_size : config.hidden_size * 2
206
+ ]
207
+ state_dict[f"dpt.encoder.layer.{i}.attention.attention.value.weight"] = in_proj_weight[
208
+ -config.hidden_size :, :
209
+ ]
210
+ state_dict[f"dpt.encoder.layer.{i}.attention.attention.value.bias"] = in_proj_bias[-config.hidden_size :]
211
+
212
+
213
+ # We will verify our results on an image of cute cats
214
+ def prepare_img():
215
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
216
+ im = Image.open(requests.get(url, stream=True).raw)
217
+ return im
218
+
219
+
220
+ @torch.no_grad()
221
+ def convert_dpt_checkpoint(checkpoint_url, pytorch_dump_folder_path, push_to_hub, model_name, show_prediction):
222
+ """
223
+ Copy/paste/tweak model's weights to our DPT structure.
224
+ """
225
+
226
+ # define DPT configuration based on URL
227
+ config, expected_shape = get_dpt_config(checkpoint_url)
228
+ # load original state_dict from URL
229
+ # state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu")
230
+ state_dict = torch.load(checkpoint_url, map_location="cpu")
231
+ # remove certain keys
232
+ remove_ignore_keys_(state_dict)
233
+ # rename keys
234
+ for key in state_dict.copy().keys():
235
+ val = state_dict.pop(key)
236
+ state_dict[rename_key(key)] = val
237
+ # read in qkv matrices
238
+ read_in_q_k_v(state_dict, config)
239
+
240
+ # load HuggingFace model
241
+ model = DPTForSemanticSegmentation(config) if "ade" in checkpoint_url else DPTForDepthEstimation(config)
242
+ model.load_state_dict(state_dict)
243
+ model.eval()
244
+
245
+ # Check outputs on an image
246
+ size = 480 if "ade" in checkpoint_url else 384
247
+ image_processor = DPTImageProcessor(size=size)
248
+
249
+ image = prepare_img()
250
+ encoding = image_processor(image, return_tensors="pt")
251
+
252
+ # forward pass
253
+ outputs = model(**encoding).logits if "ade" in checkpoint_url else model(**encoding).predicted_depth
254
+
255
+ if show_prediction:
256
+ prediction = (
257
+ torch.nn.functional.interpolate(
258
+ outputs.unsqueeze(1),
259
+ size=(image.size[1], image.size[0]),
260
+ mode="bicubic",
261
+ align_corners=False,
262
+ )
263
+ .squeeze()
264
+ .cpu()
265
+ .numpy()
266
+ )
267
+
268
+ Image.fromarray((prediction / prediction.max()) * 255).show()
269
+
270
+ if pytorch_dump_folder_path is not None:
271
+ Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
272
+ print(f"Saving model to {pytorch_dump_folder_path}")
273
+ model.save_pretrained(pytorch_dump_folder_path)
274
+ print(f"Saving image processor to {pytorch_dump_folder_path}")
275
+ image_processor.save_pretrained(pytorch_dump_folder_path)
276
+
277
+ if push_to_hub:
278
+ model.push_to_hub("ybelkada/dpt-hybrid-midas")
279
+ image_processor.push_to_hub("ybelkada/dpt-hybrid-midas")
280
+
281
+
282
+ if __name__ == "__main__":
283
+ parser = argparse.ArgumentParser()
284
+ # Required parameters
285
+ parser.add_argument(
286
+ "--checkpoint_url",
287
+ default="https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt",
288
+ type=str,
289
+ help="URL of the original DPT checkpoint you'd like to convert.",
290
+ )
291
+ parser.add_argument(
292
+ "--pytorch_dump_folder_path",
293
+ default=None,
294
+ type=str,
295
+ required=False,
296
+ help="Path to the output PyTorch model directory.",
297
+ )
298
+ parser.add_argument(
299
+ "--push_to_hub",
300
+ action="store_true",
301
+ )
302
+ parser.add_argument(
303
+ "--model_name",
304
+ default="dpt-large",
305
+ type=str,
306
+ help="Name of the model, in case you're pushing to the hub.",
307
+ )
308
+ parser.add_argument(
309
+ "--show_prediction",
310
+ action="store_true",
311
+ )
312
+
313
+ args = parser.parse_args()
314
+ convert_dpt_checkpoint(
315
+ args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name, args.show_prediction
316
+ )
SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/convert_dpt_swinv2_to_hf.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Inc. team.
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
+ """Convert DPT 3.1 checkpoints from the MiDaS repository. URL: https://github.com/isl-org/MiDaS"""
16
+
17
+
18
+ import argparse
19
+ from pathlib import Path
20
+
21
+ import requests
22
+ import torch
23
+ from PIL import Image
24
+
25
+ from transformers import DPTConfig, DPTForDepthEstimation, DPTImageProcessor, Swinv2Config
26
+ from transformers.utils import logging
27
+
28
+
29
+ logging.set_verbosity_info()
30
+ logger = logging.get_logger(__name__)
31
+
32
+
33
+ def get_dpt_config(model_name):
34
+ if "tiny" in model_name:
35
+ embed_dim = 96
36
+ depths = (2, 2, 6, 2)
37
+ num_heads = (3, 6, 12, 24)
38
+ window_size = 16
39
+ # note: for Swinv2-tiny authors used the window_size = 16 variant
40
+ # as seen here: https://github.com/isl-org/MiDaS/blob/bdc4ed64c095e026dc0a2f17cabb14d58263decb/midas/backbones/swin2.py#L26
41
+ pretrained_window_sizes = (0, 0, 0, 0)
42
+ elif "base" in model_name:
43
+ embed_dim = 128
44
+ depths = (2, 2, 18, 2)
45
+ num_heads = (4, 8, 16, 32)
46
+ window_size = 24
47
+ pretrained_window_sizes = (12, 12, 12, 6)
48
+ elif "large" in model_name:
49
+ embed_dim = 192
50
+ depths = (2, 2, 18, 2)
51
+ num_heads = (6, 12, 24, 48)
52
+ window_size = 24
53
+ pretrained_window_sizes = (12, 12, 12, 6)
54
+
55
+ if "384" in model_name:
56
+ image_size = 384
57
+ elif "256" in model_name:
58
+ image_size = 256
59
+ else:
60
+ raise ValueError("Model not supported, to do")
61
+
62
+ backbone_config = Swinv2Config(
63
+ image_size=image_size,
64
+ embed_dim=embed_dim,
65
+ depths=depths,
66
+ window_size=window_size,
67
+ pretrained_window_sizes=pretrained_window_sizes,
68
+ num_heads=num_heads,
69
+ out_features=["stage1", "stage2", "stage3", "stage4"],
70
+ )
71
+
72
+ if model_name == "dpt-swinv2-tiny-256":
73
+ neck_hidden_sizes = [96, 192, 384, 768]
74
+ elif model_name == "dpt-swinv2-base-384":
75
+ neck_hidden_sizes = [128, 256, 512, 1024]
76
+ elif model_name == "dpt-swinv2-large-384":
77
+ neck_hidden_sizes = [192, 384, 768, 1536]
78
+
79
+ config = DPTConfig(backbone_config=backbone_config, neck_hidden_sizes=neck_hidden_sizes)
80
+
81
+ return config, image_size
82
+
83
+
84
+ # here we list all keys to be renamed (original name on the left, our name on the right)
85
+ def create_rename_keys(config):
86
+ rename_keys = []
87
+
88
+ # fmt: off
89
+ # stem
90
+ rename_keys.append(("pretrained.model.patch_embed.proj.weight", "backbone.embeddings.patch_embeddings.projection.weight"))
91
+ rename_keys.append(("pretrained.model.patch_embed.proj.bias", "backbone.embeddings.patch_embeddings.projection.bias"))
92
+ rename_keys.append(("pretrained.model.patch_embed.norm.weight", "backbone.embeddings.norm.weight"))
93
+ rename_keys.append(("pretrained.model.patch_embed.norm.bias", "backbone.embeddings.norm.bias"))
94
+
95
+ # transformer encoder
96
+ for i in range(len(config.backbone_config.depths)):
97
+ for j in range(config.backbone_config.depths[i]):
98
+ rename_keys.append((f"pretrained.model.layers.{i}.blocks.{j}.attn.logit_scale", f"backbone.encoder.layers.{i}.blocks.{j}.attention.self.logit_scale"))
99
+ rename_keys.append((f"pretrained.model.layers.{i}.blocks.{j}.attn.cpb_mlp.0.weight", f"backbone.encoder.layers.{i}.blocks.{j}.attention.self.continuous_position_bias_mlp.0.weight"))
100
+ rename_keys.append((f"pretrained.model.layers.{i}.blocks.{j}.attn.cpb_mlp.0.bias", f"backbone.encoder.layers.{i}.blocks.{j}.attention.self.continuous_position_bias_mlp.0.bias"))
101
+ rename_keys.append((f"pretrained.model.layers.{i}.blocks.{j}.attn.cpb_mlp.2.weight", f"backbone.encoder.layers.{i}.blocks.{j}.attention.self.continuous_position_bias_mlp.2.weight"))
102
+ rename_keys.append((f"pretrained.model.layers.{i}.blocks.{j}.attn.q_bias", f"backbone.encoder.layers.{i}.blocks.{j}.attention.self.query.bias"))
103
+ rename_keys.append((f"pretrained.model.layers.{i}.blocks.{j}.attn.v_bias", f"backbone.encoder.layers.{i}.blocks.{j}.attention.self.value.bias"))
104
+ rename_keys.append((f"pretrained.model.layers.{i}.blocks.{j}.attn.proj.weight", f"backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.weight"))
105
+ rename_keys.append((f"pretrained.model.layers.{i}.blocks.{j}.attn.proj.bias", f"backbone.encoder.layers.{i}.blocks.{j}.attention.output.dense.bias"))
106
+ rename_keys.append((f"pretrained.model.layers.{i}.blocks.{j}.norm1.weight", f"backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.weight"))
107
+ rename_keys.append((f"pretrained.model.layers.{i}.blocks.{j}.norm1.bias", f"backbone.encoder.layers.{i}.blocks.{j}.layernorm_before.bias"))
108
+ rename_keys.append((f"pretrained.model.layers.{i}.blocks.{j}.mlp.fc1.weight", f"backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.weight"))
109
+ rename_keys.append((f"pretrained.model.layers.{i}.blocks.{j}.mlp.fc1.bias", f"backbone.encoder.layers.{i}.blocks.{j}.intermediate.dense.bias"))
110
+ rename_keys.append((f"pretrained.model.layers.{i}.blocks.{j}.mlp.fc2.weight", f"backbone.encoder.layers.{i}.blocks.{j}.output.dense.weight"))
111
+ rename_keys.append((f"pretrained.model.layers.{i}.blocks.{j}.mlp.fc2.bias", f"backbone.encoder.layers.{i}.blocks.{j}.output.dense.bias"))
112
+ rename_keys.append((f"pretrained.model.layers.{i}.blocks.{j}.norm2.weight", f"backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.weight"))
113
+ rename_keys.append((f"pretrained.model.layers.{i}.blocks.{j}.norm2.bias", f"backbone.encoder.layers.{i}.blocks.{j}.layernorm_after.bias"))
114
+
115
+ # downsample parameters
116
+ if i in [0,1,2]:
117
+ rename_keys.append((f"pretrained.model.layers.{i}.downsample.reduction.weight", f"backbone.encoder.layers.{i}.downsample.reduction.weight"))
118
+ rename_keys.append((f"pretrained.model.layers.{i}.downsample.norm.weight", f"backbone.encoder.layers.{i}.downsample.norm.weight"))
119
+ rename_keys.append((f"pretrained.model.layers.{i}.downsample.norm.bias", f"backbone.encoder.layers.{i}.downsample.norm.bias"))
120
+
121
+ # note: non-Transformer backbones like Swinv2, LeViT et al don't require activation postprocessing (readout projections + resize blocks)
122
+
123
+ # refinenet (tricky here)
124
+ mapping = {1:3, 2:2, 3:1, 4:0}
125
+
126
+ for i in range(1, 5):
127
+ j = mapping[i]
128
+ rename_keys.append((f"scratch.refinenet{i}.out_conv.weight", f"neck.fusion_stage.layers.{j}.projection.weight"))
129
+ rename_keys.append((f"scratch.refinenet{i}.out_conv.bias", f"neck.fusion_stage.layers.{j}.projection.bias"))
130
+ rename_keys.append((f"scratch.refinenet{i}.resConfUnit1.conv1.weight", f"neck.fusion_stage.layers.{j}.residual_layer1.convolution1.weight"))
131
+ rename_keys.append((f"scratch.refinenet{i}.resConfUnit1.conv1.bias", f"neck.fusion_stage.layers.{j}.residual_layer1.convolution1.bias"))
132
+ rename_keys.append((f"scratch.refinenet{i}.resConfUnit1.conv2.weight", f"neck.fusion_stage.layers.{j}.residual_layer1.convolution2.weight"))
133
+ rename_keys.append((f"scratch.refinenet{i}.resConfUnit1.conv2.bias", f"neck.fusion_stage.layers.{j}.residual_layer1.convolution2.bias"))
134
+ rename_keys.append((f"scratch.refinenet{i}.resConfUnit2.conv1.weight", f"neck.fusion_stage.layers.{j}.residual_layer2.convolution1.weight"))
135
+ rename_keys.append((f"scratch.refinenet{i}.resConfUnit2.conv1.bias", f"neck.fusion_stage.layers.{j}.residual_layer2.convolution1.bias"))
136
+ rename_keys.append((f"scratch.refinenet{i}.resConfUnit2.conv2.weight", f"neck.fusion_stage.layers.{j}.residual_layer2.convolution2.weight"))
137
+ rename_keys.append((f"scratch.refinenet{i}.resConfUnit2.conv2.bias", f"neck.fusion_stage.layers.{j}.residual_layer2.convolution2.bias"))
138
+
139
+ # scratch convolutions
140
+ for i in range(4):
141
+ rename_keys.append((f"scratch.layer{i+1}_rn.weight", f"neck.convs.{i}.weight"))
142
+
143
+ # head
144
+ for i in range(0, 5, 2):
145
+ rename_keys.append((f"scratch.output_conv.{i}.weight", f"head.head.{i}.weight"))
146
+ rename_keys.append((f"scratch.output_conv.{i}.bias", f"head.head.{i}.bias"))
147
+
148
+ return rename_keys
149
+
150
+
151
+ def remove_ignore_keys_(state_dict):
152
+ ignore_keys = ["pretrained.model.head.weight", "pretrained.model.head.bias"]
153
+ for k in ignore_keys:
154
+ state_dict.pop(k, None)
155
+
156
+
157
+ # we split up the matrix of each encoder layer into queries, keys and values
158
+ def read_in_q_k_v(state_dict, config, model):
159
+ for i in range(len(config.backbone_config.depths)):
160
+ for j in range(config.backbone_config.depths[i]):
161
+ dim = model.backbone.encoder.layers[i].blocks[j].attention.self.all_head_size
162
+ # read in weights + bias of input projection layer (in original implementation, this is a single matrix + bias)
163
+ in_proj_weight = state_dict.pop(f"pretrained.model.layers.{i}.blocks.{j}.attn.qkv.weight")
164
+ # next, add query, keys and values (in that order) to the state dict
165
+ state_dict[f"backbone.encoder.layers.{i}.blocks.{j}.attention.self.query.weight"] = in_proj_weight[:dim, :]
166
+ state_dict[f"backbone.encoder.layers.{i}.blocks.{j}.attention.self.key.weight"] = in_proj_weight[
167
+ dim : dim * 2, :
168
+ ]
169
+ state_dict[f"backbone.encoder.layers.{i}.blocks.{j}.attention.self.value.weight"] = in_proj_weight[
170
+ -dim:, :
171
+ ]
172
+
173
+
174
+ def rename_key(dct, old, new):
175
+ val = dct.pop(old)
176
+ dct[new] = val
177
+
178
+
179
+ # We will verify our results on an image of cute cats
180
+ def prepare_img():
181
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
182
+ im = Image.open(requests.get(url, stream=True).raw)
183
+ return im
184
+
185
+
186
+ @torch.no_grad()
187
+ def convert_dpt_checkpoint(model_name, pytorch_dump_folder_path, verify_logits, push_to_hub):
188
+ """
189
+ Copy/paste/tweak model's weights to our DPT structure.
190
+ """
191
+
192
+ name_to_url = {
193
+ "dpt-swinv2-tiny-256": "https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_swin2_tiny_256.pt",
194
+ "dpt-swinv2-base-384": "https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_swin2_base_384.pt",
195
+ "dpt-swinv2-large-384": "https://github.com/isl-org/MiDaS/releases/download/v3_1/dpt_swin2_large_384.pt",
196
+ }
197
+
198
+ # define DPT configuration based on URL
199
+ checkpoint_url = name_to_url[model_name]
200
+ config, image_size = get_dpt_config(model_name)
201
+ # load original state_dict from URL
202
+ state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu")
203
+
204
+ # load HuggingFace model
205
+ model = DPTForDepthEstimation(config)
206
+
207
+ # remove certain keys
208
+ remove_ignore_keys_(state_dict)
209
+ # rename keys
210
+ rename_keys = create_rename_keys(config)
211
+ for src, dest in rename_keys:
212
+ rename_key(state_dict, src, dest)
213
+ # read in qkv matrices
214
+ read_in_q_k_v(state_dict, config, model)
215
+
216
+ missing_keys, unexpected_keys = model.load_state_dict(state_dict, strict=False)
217
+ print("Missing keys:", missing_keys)
218
+ print("Unexpected keys:", unexpected_keys)
219
+ model.eval()
220
+
221
+ # Check outputs on an image
222
+ processor = DPTImageProcessor(size={"height": image_size, "width": image_size})
223
+
224
+ image = prepare_img()
225
+ processor(image, return_tensors="pt")
226
+
227
+ if verify_logits:
228
+ from torchvision import transforms
229
+
230
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
231
+ image = Image.open(requests.get(url, stream=True).raw)
232
+
233
+ transforms = transforms.Compose(
234
+ [
235
+ transforms.Resize((image_size, image_size)),
236
+ transforms.ToTensor(),
237
+ ]
238
+ )
239
+ pixel_values = transforms(image).unsqueeze(0)
240
+
241
+ # forward pass
242
+ with torch.no_grad():
243
+ outputs = model(pixel_values)
244
+
245
+ predicted_depth = outputs.predicted_depth
246
+
247
+ print("Shape of predicted depth:", predicted_depth.shape)
248
+ print("First values of predicted depth:", predicted_depth[0, :3, :3])
249
+
250
+ # assert logits
251
+ if model_name == "dpt-swinv2-base-384":
252
+ # OK, checked
253
+ expected_shape = torch.Size([1, 384, 384])
254
+ expected_slice = torch.tensor(
255
+ [
256
+ [1998.5575, 1997.3887, 2009.2981],
257
+ [1952.8607, 1979.6488, 2001.0854],
258
+ [1953.7697, 1961.7711, 1968.8904],
259
+ ],
260
+ )
261
+ elif model_name == "dpt-swinv2-tiny-256":
262
+ # OK, checked
263
+ expected_shape = torch.Size([1, 256, 256])
264
+ expected_slice = torch.tensor(
265
+ [[978.9163, 976.5215, 978.5349], [974.1859, 971.7249, 975.8046], [971.3419, 970.3118, 971.6830]],
266
+ )
267
+ elif model_name == "dpt-swinv2-large-384":
268
+ # OK, checked
269
+ expected_shape = torch.Size([1, 384, 384])
270
+ expected_slice = torch.tensor(
271
+ [
272
+ [1203.7206, 1200.1495, 1197.8234],
273
+ [1196.2484, 1183.5033, 1186.4640],
274
+ [1178.8131, 1182.3260, 1174.3975],
275
+ ],
276
+ )
277
+
278
+ assert predicted_depth.shape == torch.Size(expected_shape)
279
+ assert torch.allclose(predicted_depth[0, :3, :3], expected_slice)
280
+ print("Looks ok!")
281
+
282
+ if pytorch_dump_folder_path is not None:
283
+ Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
284
+ print(f"Saving model and processor to {pytorch_dump_folder_path}")
285
+ model.save_pretrained(pytorch_dump_folder_path)
286
+ processor.save_pretrained(pytorch_dump_folder_path)
287
+
288
+ if push_to_hub:
289
+ print("Pushing model and processor to hub...")
290
+ model.push_to_hub(repo_id=f"Intel/{model_name}")
291
+ processor.push_to_hub(repo_id=f"Intel/{model_name}")
292
+
293
+
294
+ if __name__ == "__main__":
295
+ parser = argparse.ArgumentParser()
296
+ # Required parameters
297
+ parser.add_argument(
298
+ "--model_name",
299
+ default="dpt-swinv2-base-384",
300
+ type=str,
301
+ choices=["dpt-swinv2-tiny-256", "dpt-swinv2-base-384", "dpt-swinv2-large-384"],
302
+ help="Name of the model you'd like to convert.",
303
+ )
304
+ parser.add_argument(
305
+ "--pytorch_dump_folder_path",
306
+ default=None,
307
+ type=str,
308
+ help="Path to the output PyTorch model directory.",
309
+ )
310
+ parser.add_argument(
311
+ "--verify_logits",
312
+ action="store_true",
313
+ help="Whether to verify logits after conversion.",
314
+ )
315
+ parser.add_argument(
316
+ "--push_to_hub",
317
+ action="store_true",
318
+ help="Whether to push the model to the hub after conversion.",
319
+ )
320
+
321
+ args = parser.parse_args()
322
+ convert_dpt_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.verify_logits, args.push_to_hub)
SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/convert_dpt_to_pytorch.py ADDED
@@ -0,0 +1,286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
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
+ """Convert DPT checkpoints from the original repository. URL: https://github.com/isl-org/DPT"""
16
+
17
+
18
+ import argparse
19
+ import json
20
+ from pathlib import Path
21
+
22
+ import requests
23
+ import torch
24
+ from huggingface_hub import cached_download, hf_hub_url
25
+ from PIL import Image
26
+
27
+ from transformers import DPTConfig, DPTForDepthEstimation, DPTForSemanticSegmentation, DPTImageProcessor
28
+ from transformers.utils import logging
29
+
30
+
31
+ logging.set_verbosity_info()
32
+ logger = logging.get_logger(__name__)
33
+
34
+
35
+ def get_dpt_config(checkpoint_url):
36
+ config = DPTConfig()
37
+
38
+ if "large" in checkpoint_url:
39
+ config.hidden_size = 1024
40
+ config.intermediate_size = 4096
41
+ config.num_hidden_layers = 24
42
+ config.num_attention_heads = 16
43
+ config.backbone_out_indices = [5, 11, 17, 23]
44
+ config.neck_hidden_sizes = [256, 512, 1024, 1024]
45
+ expected_shape = (1, 384, 384)
46
+
47
+ if "ade" in checkpoint_url:
48
+ config.use_batch_norm_in_fusion_residual = True
49
+
50
+ config.num_labels = 150
51
+ repo_id = "huggingface/label-files"
52
+ filename = "ade20k-id2label.json"
53
+ id2label = json.load(open(cached_download(hf_hub_url(repo_id, filename, repo_type="dataset")), "r"))
54
+ id2label = {int(k): v for k, v in id2label.items()}
55
+ config.id2label = id2label
56
+ config.label2id = {v: k for k, v in id2label.items()}
57
+ expected_shape = [1, 150, 480, 480]
58
+
59
+ return config, expected_shape
60
+
61
+
62
+ def remove_ignore_keys_(state_dict):
63
+ ignore_keys = ["pretrained.model.head.weight", "pretrained.model.head.bias"]
64
+ for k in ignore_keys:
65
+ state_dict.pop(k, None)
66
+
67
+
68
+ def rename_key(name):
69
+ if (
70
+ "pretrained.model" in name
71
+ and "cls_token" not in name
72
+ and "pos_embed" not in name
73
+ and "patch_embed" not in name
74
+ ):
75
+ name = name.replace("pretrained.model", "dpt.encoder")
76
+ if "pretrained.model" in name:
77
+ name = name.replace("pretrained.model", "dpt.embeddings")
78
+ if "patch_embed" in name:
79
+ name = name.replace("patch_embed", "patch_embeddings")
80
+ if "pos_embed" in name:
81
+ name = name.replace("pos_embed", "position_embeddings")
82
+ if "attn.proj" in name:
83
+ name = name.replace("attn.proj", "attention.output.dense")
84
+ if "proj" in name and "project" not in name:
85
+ name = name.replace("proj", "projection")
86
+ if "blocks" in name:
87
+ name = name.replace("blocks", "layer")
88
+ if "mlp.fc1" in name:
89
+ name = name.replace("mlp.fc1", "intermediate.dense")
90
+ if "mlp.fc2" in name:
91
+ name = name.replace("mlp.fc2", "output.dense")
92
+ if "norm1" in name:
93
+ name = name.replace("norm1", "layernorm_before")
94
+ if "norm2" in name:
95
+ name = name.replace("norm2", "layernorm_after")
96
+ if "scratch.output_conv" in name:
97
+ name = name.replace("scratch.output_conv", "head")
98
+ if "scratch" in name:
99
+ name = name.replace("scratch", "neck")
100
+ if "layer1_rn" in name:
101
+ name = name.replace("layer1_rn", "convs.0")
102
+ if "layer2_rn" in name:
103
+ name = name.replace("layer2_rn", "convs.1")
104
+ if "layer3_rn" in name:
105
+ name = name.replace("layer3_rn", "convs.2")
106
+ if "layer4_rn" in name:
107
+ name = name.replace("layer4_rn", "convs.3")
108
+ if "refinenet" in name:
109
+ layer_idx = int(name[len("neck.refinenet") : len("neck.refinenet") + 1])
110
+ # tricky here: we need to map 4 to 0, 3 to 1, 2 to 2 and 1 to 3
111
+ name = name.replace(f"refinenet{layer_idx}", f"fusion_stage.layers.{abs(layer_idx-4)}")
112
+ if "out_conv" in name:
113
+ name = name.replace("out_conv", "projection")
114
+ if "resConfUnit1" in name:
115
+ name = name.replace("resConfUnit1", "residual_layer1")
116
+ if "resConfUnit2" in name:
117
+ name = name.replace("resConfUnit2", "residual_layer2")
118
+ if "conv1" in name:
119
+ name = name.replace("conv1", "convolution1")
120
+ if "conv2" in name:
121
+ name = name.replace("conv2", "convolution2")
122
+ # readout blocks
123
+ if "pretrained.act_postprocess1.0.project.0" in name:
124
+ name = name.replace("pretrained.act_postprocess1.0.project.0", "neck.reassemble_stage.readout_projects.0.0")
125
+ if "pretrained.act_postprocess2.0.project.0" in name:
126
+ name = name.replace("pretrained.act_postprocess2.0.project.0", "neck.reassemble_stage.readout_projects.1.0")
127
+ if "pretrained.act_postprocess3.0.project.0" in name:
128
+ name = name.replace("pretrained.act_postprocess3.0.project.0", "neck.reassemble_stage.readout_projects.2.0")
129
+ if "pretrained.act_postprocess4.0.project.0" in name:
130
+ name = name.replace("pretrained.act_postprocess4.0.project.0", "neck.reassemble_stage.readout_projects.3.0")
131
+ # resize blocks
132
+ if "pretrained.act_postprocess1.3" in name:
133
+ name = name.replace("pretrained.act_postprocess1.3", "neck.reassemble_stage.layers.0.projection")
134
+ if "pretrained.act_postprocess1.4" in name:
135
+ name = name.replace("pretrained.act_postprocess1.4", "neck.reassemble_stage.layers.0.resize")
136
+ if "pretrained.act_postprocess2.3" in name:
137
+ name = name.replace("pretrained.act_postprocess2.3", "neck.reassemble_stage.layers.1.projection")
138
+ if "pretrained.act_postprocess2.4" in name:
139
+ name = name.replace("pretrained.act_postprocess2.4", "neck.reassemble_stage.layers.1.resize")
140
+ if "pretrained.act_postprocess3.3" in name:
141
+ name = name.replace("pretrained.act_postprocess3.3", "neck.reassemble_stage.layers.2.projection")
142
+ if "pretrained.act_postprocess4.3" in name:
143
+ name = name.replace("pretrained.act_postprocess4.3", "neck.reassemble_stage.layers.3.projection")
144
+ if "pretrained.act_postprocess4.4" in name:
145
+ name = name.replace("pretrained.act_postprocess4.4", "neck.reassemble_stage.layers.3.resize")
146
+ if "pretrained" in name:
147
+ name = name.replace("pretrained", "dpt")
148
+ if "bn" in name:
149
+ name = name.replace("bn", "batch_norm")
150
+ if "head" in name:
151
+ name = name.replace("head", "head.head")
152
+ if "encoder.norm" in name:
153
+ name = name.replace("encoder.norm", "layernorm")
154
+ if "auxlayer" in name:
155
+ name = name.replace("auxlayer", "auxiliary_head.head")
156
+
157
+ return name
158
+
159
+
160
+ # we split up the matrix of each encoder layer into queries, keys and values
161
+ def read_in_q_k_v(state_dict, config):
162
+ for i in range(config.num_hidden_layers):
163
+ # read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
164
+ in_proj_weight = state_dict.pop(f"dpt.encoder.layer.{i}.attn.qkv.weight")
165
+ in_proj_bias = state_dict.pop(f"dpt.encoder.layer.{i}.attn.qkv.bias")
166
+ # next, add query, keys and values (in that order) to the state dict
167
+ state_dict[f"dpt.encoder.layer.{i}.attention.attention.query.weight"] = in_proj_weight[: config.hidden_size, :]
168
+ state_dict[f"dpt.encoder.layer.{i}.attention.attention.query.bias"] = in_proj_bias[: config.hidden_size]
169
+ state_dict[f"dpt.encoder.layer.{i}.attention.attention.key.weight"] = in_proj_weight[
170
+ config.hidden_size : config.hidden_size * 2, :
171
+ ]
172
+ state_dict[f"dpt.encoder.layer.{i}.attention.attention.key.bias"] = in_proj_bias[
173
+ config.hidden_size : config.hidden_size * 2
174
+ ]
175
+ state_dict[f"dpt.encoder.layer.{i}.attention.attention.value.weight"] = in_proj_weight[
176
+ -config.hidden_size :, :
177
+ ]
178
+ state_dict[f"dpt.encoder.layer.{i}.attention.attention.value.bias"] = in_proj_bias[-config.hidden_size :]
179
+
180
+
181
+ # We will verify our results on an image of cute cats
182
+ def prepare_img():
183
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
184
+ im = Image.open(requests.get(url, stream=True).raw)
185
+ return im
186
+
187
+
188
+ @torch.no_grad()
189
+ def convert_dpt_checkpoint(checkpoint_url, pytorch_dump_folder_path, push_to_hub, model_name):
190
+ """
191
+ Copy/paste/tweak model's weights to our DPT structure.
192
+ """
193
+
194
+ # define DPT configuration based on URL
195
+ config, expected_shape = get_dpt_config(checkpoint_url)
196
+ # load original state_dict from URL
197
+ state_dict = torch.hub.load_state_dict_from_url(checkpoint_url, map_location="cpu")
198
+ # remove certain keys
199
+ remove_ignore_keys_(state_dict)
200
+ # rename keys
201
+ for key in state_dict.copy().keys():
202
+ val = state_dict.pop(key)
203
+ state_dict[rename_key(key)] = val
204
+ # read in qkv matrices
205
+ read_in_q_k_v(state_dict, config)
206
+
207
+ # load HuggingFace model
208
+ model = DPTForSemanticSegmentation(config) if "ade" in checkpoint_url else DPTForDepthEstimation(config)
209
+ model.load_state_dict(state_dict)
210
+ model.eval()
211
+
212
+ # Check outputs on an image
213
+ size = 480 if "ade" in checkpoint_url else 384
214
+ image_processor = DPTImageProcessor(size=size)
215
+
216
+ image = prepare_img()
217
+ encoding = image_processor(image, return_tensors="pt")
218
+
219
+ # forward pass
220
+ outputs = model(**encoding).logits if "ade" in checkpoint_url else model(**encoding).predicted_depth
221
+
222
+ # Assert logits
223
+ expected_slice = torch.tensor([[6.3199, 6.3629, 6.4148], [6.3850, 6.3615, 6.4166], [6.3519, 6.3176, 6.3575]])
224
+ if "ade" in checkpoint_url:
225
+ expected_slice = torch.tensor([[4.0480, 4.2420, 4.4360], [4.3124, 4.5693, 4.8261], [4.5768, 4.8965, 5.2163]])
226
+ assert outputs.shape == torch.Size(expected_shape)
227
+ assert (
228
+ torch.allclose(outputs[0, 0, :3, :3], expected_slice, atol=1e-4)
229
+ if "ade" in checkpoint_url
230
+ else torch.allclose(outputs[0, :3, :3], expected_slice)
231
+ )
232
+ print("Looks ok!")
233
+
234
+ if pytorch_dump_folder_path is not None:
235
+ Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
236
+ print(f"Saving model to {pytorch_dump_folder_path}")
237
+ model.save_pretrained(pytorch_dump_folder_path)
238
+ print(f"Saving image processor to {pytorch_dump_folder_path}")
239
+ image_processor.save_pretrained(pytorch_dump_folder_path)
240
+
241
+ if push_to_hub:
242
+ print("Pushing model to hub...")
243
+ model.push_to_hub(
244
+ repo_path_or_name=Path(pytorch_dump_folder_path, model_name),
245
+ organization="nielsr",
246
+ commit_message="Add model",
247
+ use_temp_dir=True,
248
+ )
249
+ image_processor.push_to_hub(
250
+ repo_path_or_name=Path(pytorch_dump_folder_path, model_name),
251
+ organization="nielsr",
252
+ commit_message="Add image processor",
253
+ use_temp_dir=True,
254
+ )
255
+
256
+
257
+ if __name__ == "__main__":
258
+ parser = argparse.ArgumentParser()
259
+ # Required parameters
260
+ parser.add_argument(
261
+ "--checkpoint_url",
262
+ default="https://github.com/intel-isl/DPT/releases/download/1_0/dpt_large-midas-2f21e586.pt",
263
+ type=str,
264
+ help="URL of the original DPT checkpoint you'd like to convert.",
265
+ )
266
+ parser.add_argument(
267
+ "--pytorch_dump_folder_path",
268
+ default=None,
269
+ type=str,
270
+ required=False,
271
+ help="Path to the output PyTorch model directory.",
272
+ )
273
+ parser.add_argument(
274
+ "--push_to_hub",
275
+ action="store_true",
276
+ )
277
+ parser.add_argument(
278
+ "--model_name",
279
+ default="dpt-large",
280
+ type=str,
281
+ required=False,
282
+ help="Name of the model, in case you're pushing to the hub.",
283
+ )
284
+
285
+ args = parser.parse_args()
286
+ convert_dpt_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub, args.model_name)
SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/feature_extraction_dpt.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 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
+ """Feature extractor class for DPT."""
16
+
17
+ import warnings
18
+
19
+ from ...utils import logging
20
+ from .image_processing_dpt import DPTImageProcessor
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+
26
+ class DPTFeatureExtractor(DPTImageProcessor):
27
+ def __init__(self, *args, **kwargs) -> None:
28
+ warnings.warn(
29
+ "The class DPTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please"
30
+ " use DPTImageProcessor instead.",
31
+ FutureWarning,
32
+ )
33
+ super().__init__(*args, **kwargs)
SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/image_processing_dpt.py ADDED
@@ -0,0 +1,463 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 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
+ """Image processor class for DPT."""
16
+
17
+ import math
18
+ from typing import Dict, Iterable, List, Optional, Tuple, Union
19
+
20
+ import numpy as np
21
+
22
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
23
+ from ...image_transforms import pad, resize, to_channel_dimension_format
24
+ from ...image_utils import (
25
+ IMAGENET_STANDARD_MEAN,
26
+ IMAGENET_STANDARD_STD,
27
+ ChannelDimension,
28
+ ImageInput,
29
+ PILImageResampling,
30
+ get_image_size,
31
+ infer_channel_dimension_format,
32
+ is_scaled_image,
33
+ is_torch_available,
34
+ is_torch_tensor,
35
+ make_list_of_images,
36
+ to_numpy_array,
37
+ valid_images,
38
+ )
39
+ from ...utils import TensorType, is_vision_available, logging
40
+
41
+
42
+ if is_torch_available():
43
+ import torch
44
+
45
+ if is_vision_available():
46
+ import PIL
47
+
48
+
49
+ logger = logging.get_logger(__name__)
50
+
51
+
52
+ def get_resize_output_image_size(
53
+ input_image: np.ndarray,
54
+ output_size: Union[int, Iterable[int]],
55
+ keep_aspect_ratio: bool,
56
+ multiple: int,
57
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
58
+ ) -> Tuple[int, int]:
59
+ def constraint_to_multiple_of(val, multiple, min_val=0, max_val=None):
60
+ x = round(val / multiple) * multiple
61
+
62
+ if max_val is not None and x > max_val:
63
+ x = math.floor(val / multiple) * multiple
64
+
65
+ if x < min_val:
66
+ x = math.ceil(val / multiple) * multiple
67
+
68
+ return x
69
+
70
+ output_size = (output_size, output_size) if isinstance(output_size, int) else output_size
71
+
72
+ input_height, input_width = get_image_size(input_image, input_data_format)
73
+ output_height, output_width = output_size
74
+
75
+ # determine new height and width
76
+ scale_height = output_height / input_height
77
+ scale_width = output_width / input_width
78
+
79
+ if keep_aspect_ratio:
80
+ # scale as little as possible
81
+ if abs(1 - scale_width) < abs(1 - scale_height):
82
+ # fit width
83
+ scale_height = scale_width
84
+ else:
85
+ # fit height
86
+ scale_width = scale_height
87
+
88
+ new_height = constraint_to_multiple_of(scale_height * input_height, multiple=multiple)
89
+ new_width = constraint_to_multiple_of(scale_width * input_width, multiple=multiple)
90
+
91
+ return (new_height, new_width)
92
+
93
+
94
+ class DPTImageProcessor(BaseImageProcessor):
95
+ r"""
96
+ Constructs a DPT image processor.
97
+
98
+ Args:
99
+ do_resize (`bool`, *optional*, defaults to `True`):
100
+ Whether to resize the image's (height, width) dimensions. Can be overidden by `do_resize` in `preprocess`.
101
+ size (`Dict[str, int]` *optional*, defaults to `{"height": 384, "width": 384}`):
102
+ Size of the image after resizing. Can be overidden by `size` in `preprocess`.
103
+ resample (`PILImageResampling`, *optional*, defaults to `Resampling.BICUBIC`):
104
+ Defines the resampling filter to use if resizing the image. Can be overidden by `resample` in `preprocess`.
105
+ keep_aspect_ratio (`bool`, *optional*, defaults to `False`):
106
+ If `True`, the image is resized to the largest possible size such that the aspect ratio is preserved. Can
107
+ be overidden by `keep_aspect_ratio` in `preprocess`.
108
+ ensure_multiple_of (`int`, *optional*, defaults to 1):
109
+ If `do_resize` is `True`, the image is resized to a size that is a multiple of this value. Can be overidden
110
+ by `ensure_multiple_of` in `preprocess`.
111
+ do_rescale (`bool`, *optional*, defaults to `True`):
112
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overidden by `do_rescale` in
113
+ `preprocess`.
114
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
115
+ Scale factor to use if rescaling the image. Can be overidden by `rescale_factor` in `preprocess`.
116
+ do_normalize (`bool`, *optional*, defaults to `True`):
117
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
118
+ method.
119
+ image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
120
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
121
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
122
+ image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
123
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
124
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
125
+ do_pad (`bool`, *optional*, defaults to `False`):
126
+ Whether to apply center padding. This was introduced in the DINOv2 paper, which uses the model in
127
+ combination with DPT.
128
+ size_divisor (`int`, *optional*):
129
+ If `do_pad` is `True`, pads the image dimensions to be divisible by this value. This was introduced in the
130
+ DINOv2 paper, which uses the model in combination with DPT.
131
+ """
132
+
133
+ model_input_names = ["pixel_values"]
134
+
135
+ def __init__(
136
+ self,
137
+ do_resize: bool = True,
138
+ size: Dict[str, int] = None,
139
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
140
+ keep_aspect_ratio: bool = False,
141
+ ensure_multiple_of: int = 1,
142
+ do_rescale: bool = True,
143
+ rescale_factor: Union[int, float] = 1 / 255,
144
+ do_normalize: bool = True,
145
+ image_mean: Optional[Union[float, List[float]]] = None,
146
+ image_std: Optional[Union[float, List[float]]] = None,
147
+ do_pad: bool = False,
148
+ size_divisor: int = None,
149
+ **kwargs,
150
+ ) -> None:
151
+ super().__init__(**kwargs)
152
+ size = size if size is not None else {"height": 384, "width": 384}
153
+ size = get_size_dict(size)
154
+ self.do_resize = do_resize
155
+ self.size = size
156
+ self.keep_aspect_ratio = keep_aspect_ratio
157
+ self.ensure_multiple_of = ensure_multiple_of
158
+ self.resample = resample
159
+ self.do_rescale = do_rescale
160
+ self.rescale_factor = rescale_factor
161
+ self.do_normalize = do_normalize
162
+ self.image_mean = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
163
+ self.image_std = image_std if image_std is not None else IMAGENET_STANDARD_STD
164
+ self.do_pad = do_pad
165
+ self.size_divisor = size_divisor
166
+
167
+ def resize(
168
+ self,
169
+ image: np.ndarray,
170
+ size: Dict[str, int],
171
+ keep_aspect_ratio: bool = False,
172
+ ensure_multiple_of: int = 1,
173
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
174
+ data_format: Optional[Union[str, ChannelDimension]] = None,
175
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
176
+ **kwargs,
177
+ ) -> np.ndarray:
178
+ """
179
+ Resize an image to target size `(size["height"], size["width"])`. If `keep_aspect_ratio` is `True`, the image
180
+ is resized to the largest possible size such that the aspect ratio is preserved. If `ensure_multiple_of` is
181
+ set, the image is resized to a size that is a multiple of this value.
182
+
183
+ Args:
184
+ image (`np.ndarray`):
185
+ Image to resize.
186
+ size (`Dict[str, int]`):
187
+ Target size of the output image.
188
+ keep_aspect_ratio (`bool`, *optional*, defaults to `False`):
189
+ If `True`, the image is resized to the largest possible size such that the aspect ratio is preserved.
190
+ ensure_multiple_of (`int`, *optional*, defaults to 1):
191
+ The image is resized to a size that is a multiple of this value.
192
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
193
+ Defines the resampling filter to use if resizing the image. Otherwise, the image is resized to size
194
+ specified in `size`.
195
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`):
196
+ Resampling filter to use when resiizing the image.
197
+ data_format (`str` or `ChannelDimension`, *optional*):
198
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
199
+ input_data_format (`str` or `ChannelDimension`, *optional*):
200
+ The channel dimension format of the input image. If not provided, it will be inferred.
201
+ """
202
+ size = get_size_dict(size)
203
+ if "height" not in size or "width" not in size:
204
+ raise ValueError(f"The size dictionary must contain the keys 'height' and 'width'. Got {size.keys()}")
205
+
206
+ output_size = get_resize_output_image_size(
207
+ image,
208
+ output_size=(size["height"], size["width"]),
209
+ keep_aspect_ratio=keep_aspect_ratio,
210
+ multiple=ensure_multiple_of,
211
+ input_data_format=input_data_format,
212
+ )
213
+ return resize(
214
+ image,
215
+ size=output_size,
216
+ resample=resample,
217
+ data_format=data_format,
218
+ input_data_format=input_data_format,
219
+ **kwargs,
220
+ )
221
+
222
+ def pad_image(
223
+ self,
224
+ image: np.array,
225
+ size_divisor: int,
226
+ data_format: Optional[Union[str, ChannelDimension]] = None,
227
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
228
+ ):
229
+ """
230
+ Center pad an image to be a multiple of `multiple`.
231
+
232
+ Args:
233
+ image (`np.ndarray`):
234
+ Image to pad.
235
+ size_divisor (`int`):
236
+ The width and height of the image will be padded to a multiple of this number.
237
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
238
+ The channel dimension format for the output image. Can be one of:
239
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
240
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
241
+ - Unset: Use the channel dimension format of the input image.
242
+ input_data_format (`ChannelDimension` or `str`, *optional*):
243
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
244
+ from the input image. Can be one of:
245
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
246
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
247
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
248
+ """
249
+
250
+ def _get_pad(size, size_divisor):
251
+ new_size = math.ceil(size / size_divisor) * size_divisor
252
+ pad_size = new_size - size
253
+ pad_size_left = pad_size // 2
254
+ pad_size_right = pad_size - pad_size_left
255
+ return pad_size_left, pad_size_right
256
+
257
+ if input_data_format is None:
258
+ input_data_format = infer_channel_dimension_format(image)
259
+
260
+ height, width = get_image_size(image, input_data_format)
261
+
262
+ pad_size_left, pad_size_right = _get_pad(height, size_divisor)
263
+ pad_size_top, pad_size_bottom = _get_pad(width, size_divisor)
264
+
265
+ return pad(image, ((pad_size_left, pad_size_right), (pad_size_top, pad_size_bottom)), data_format=data_format)
266
+
267
+ def preprocess(
268
+ self,
269
+ images: ImageInput,
270
+ do_resize: bool = None,
271
+ size: int = None,
272
+ keep_aspect_ratio: bool = None,
273
+ ensure_multiple_of: int = None,
274
+ resample: PILImageResampling = None,
275
+ do_rescale: bool = None,
276
+ rescale_factor: float = None,
277
+ do_normalize: bool = None,
278
+ image_mean: Optional[Union[float, List[float]]] = None,
279
+ image_std: Optional[Union[float, List[float]]] = None,
280
+ do_pad: bool = None,
281
+ size_divisor: int = None,
282
+ return_tensors: Optional[Union[str, TensorType]] = None,
283
+ data_format: ChannelDimension = ChannelDimension.FIRST,
284
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
285
+ **kwargs,
286
+ ) -> PIL.Image.Image:
287
+ """
288
+ Preprocess an image or batch of images.
289
+
290
+ Args:
291
+ images (`ImageInput`):
292
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
293
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
294
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
295
+ Whether to resize the image.
296
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
297
+ Size of the image after reszing. If `keep_aspect_ratio` is `True`, the image is resized to the largest
298
+ possible size such that the aspect ratio is preserved. If `ensure_multiple_of` is set, the image is
299
+ resized to a size that is a multiple of this value.
300
+ keep_aspect_ratio (`bool`, *optional*, defaults to `self.keep_aspect_ratio`):
301
+ Whether to keep the aspect ratio of the image. If False, the image will be resized to (size, size). If
302
+ True, the image will be resized to keep the aspect ratio and the size will be the maximum possible.
303
+ ensure_multiple_of (`int`, *optional*, defaults to `self.ensure_multiple_of`):
304
+ Ensure that the image size is a multiple of this value.
305
+ resample (`int`, *optional*, defaults to `self.resample`):
306
+ Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`, Only
307
+ has an effect if `do_resize` is set to `True`.
308
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
309
+ Whether to rescale the image values between [0 - 1].
310
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
311
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
312
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
313
+ Whether to normalize the image.
314
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
315
+ Image mean.
316
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
317
+ Image standard deviation.
318
+ return_tensors (`str` or `TensorType`, *optional*):
319
+ The type of tensors to return. Can be one of:
320
+ - Unset: Return a list of `np.ndarray`.
321
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
322
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
323
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
324
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
325
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
326
+ The channel dimension format for the output image. Can be one of:
327
+ - `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
328
+ - `ChannelDimension.LAST`: image in (height, width, num_channels) format.
329
+ input_data_format (`ChannelDimension` or `str`, *optional*):
330
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
331
+ from the input image. Can be one of:
332
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
333
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
334
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
335
+ """
336
+ do_resize = do_resize if do_resize is not None else self.do_resize
337
+ size = size if size is not None else self.size
338
+ size = get_size_dict(size)
339
+ keep_aspect_ratio = keep_aspect_ratio if keep_aspect_ratio is not None else self.keep_aspect_ratio
340
+ ensure_multiple_of = ensure_multiple_of if ensure_multiple_of is not None else self.ensure_multiple_of
341
+ resample = resample if resample is not None else self.resample
342
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
343
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
344
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
345
+ image_mean = image_mean if image_mean is not None else self.image_mean
346
+ image_std = image_std if image_std is not None else self.image_std
347
+ do_pad = do_pad if do_pad is not None else self.do_pad
348
+ size_divisor = size_divisor if size_divisor is not None else self.size_divisor
349
+
350
+ images = make_list_of_images(images)
351
+
352
+ if not valid_images(images):
353
+ raise ValueError(
354
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
355
+ "torch.Tensor, tf.Tensor or jax.ndarray."
356
+ )
357
+
358
+ if do_resize and size is None or resample is None:
359
+ raise ValueError("Size and resample must be specified if do_resize is True.")
360
+
361
+ if do_rescale and rescale_factor is None:
362
+ raise ValueError("Rescale factor must be specified if do_rescale is True.")
363
+
364
+ if do_normalize and (image_mean is None or image_std is None):
365
+ raise ValueError("Image mean and std must be specified if do_normalize is True.")
366
+
367
+ if do_pad and size_divisor is None:
368
+ raise ValueError("Size divisibility must be specified if do_pad is True.")
369
+
370
+ # All transformations expect numpy arrays.
371
+ images = [to_numpy_array(image) for image in images]
372
+
373
+ if is_scaled_image(images[0]) and do_rescale:
374
+ logger.warning_once(
375
+ "It looks like you are trying to rescale already rescaled images. If the input"
376
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
377
+ )
378
+
379
+ if input_data_format is None:
380
+ # We assume that all images have the same channel dimension format.
381
+ input_data_format = infer_channel_dimension_format(images[0])
382
+
383
+ if do_resize:
384
+ images = [
385
+ self.resize(
386
+ image=image,
387
+ size=size,
388
+ resample=resample,
389
+ keep_aspect_ratio=keep_aspect_ratio,
390
+ ensure_multiple_of=ensure_multiple_of,
391
+ input_data_format=input_data_format,
392
+ )
393
+ for image in images
394
+ ]
395
+
396
+ if do_rescale:
397
+ images = [
398
+ self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
399
+ for image in images
400
+ ]
401
+
402
+ if do_normalize:
403
+ images = [
404
+ self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
405
+ for image in images
406
+ ]
407
+
408
+ if do_pad:
409
+ images = [
410
+ self.pad_image(image=image, size_divisor=size_divisor, input_data_format=input_data_format)
411
+ for image in images
412
+ ]
413
+
414
+ images = [
415
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
416
+ ]
417
+
418
+ data = {"pixel_values": images}
419
+ return BatchFeature(data=data, tensor_type=return_tensors)
420
+
421
+ # Copied from transformers.models.beit.image_processing_beit.BeitImageProcessor.post_process_semantic_segmentation with Beit->DPT
422
+ def post_process_semantic_segmentation(self, outputs, target_sizes: List[Tuple] = None):
423
+ """
424
+ Converts the output of [`DPTForSemanticSegmentation`] into semantic segmentation maps. Only supports PyTorch.
425
+
426
+ Args:
427
+ outputs ([`DPTForSemanticSegmentation`]):
428
+ Raw outputs of the model.
429
+ target_sizes (`List[Tuple]` of length `batch_size`, *optional*):
430
+ List of tuples corresponding to the requested final size (height, width) of each prediction. If unset,
431
+ predictions will not be resized.
432
+
433
+ Returns:
434
+ semantic_segmentation: `List[torch.Tensor]` of length `batch_size`, where each item is a semantic
435
+ segmentation map of shape (height, width) corresponding to the target_sizes entry (if `target_sizes` is
436
+ specified). Each entry of each `torch.Tensor` correspond to a semantic class id.
437
+ """
438
+ # TODO: add support for other frameworks
439
+ logits = outputs.logits
440
+
441
+ # Resize logits and compute semantic segmentation maps
442
+ if target_sizes is not None:
443
+ if len(logits) != len(target_sizes):
444
+ raise ValueError(
445
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
446
+ )
447
+
448
+ if is_torch_tensor(target_sizes):
449
+ target_sizes = target_sizes.numpy()
450
+
451
+ semantic_segmentation = []
452
+
453
+ for idx in range(len(logits)):
454
+ resized_logits = torch.nn.functional.interpolate(
455
+ logits[idx].unsqueeze(dim=0), size=target_sizes[idx], mode="bilinear", align_corners=False
456
+ )
457
+ semantic_map = resized_logits[0].argmax(dim=0)
458
+ semantic_segmentation.append(semantic_map)
459
+ else:
460
+ semantic_segmentation = logits.argmax(dim=1)
461
+ semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
462
+
463
+ return semantic_segmentation
SupplementaryMaterial_Code/transformers-4.37.2/models/dpt/modeling_dpt.py ADDED
@@ -0,0 +1,1384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Intel Labs, OpenMMLab 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
+ """ PyTorch DPT (Dense Prediction Transformers) model.
16
+
17
+ This implementation is heavily inspired by OpenMMLab's implementation, found here:
18
+ https://github.com/open-mmlab/mmsegmentation/blob/master/mmseg/models/decode_heads/dpt_head.py.
19
+
20
+ """
21
+
22
+
23
+ import collections.abc
24
+ import math
25
+ from dataclasses import dataclass
26
+ from typing import List, Optional, Set, Tuple, Union
27
+
28
+ import torch
29
+ import torch.utils.checkpoint
30
+ from torch import nn
31
+ from torch.nn import CrossEntropyLoss
32
+
33
+ from ...activations import ACT2FN
34
+ from ...file_utils import (
35
+ add_code_sample_docstrings,
36
+ add_start_docstrings,
37
+ add_start_docstrings_to_model_forward,
38
+ replace_return_docstrings,
39
+ )
40
+ from ...modeling_outputs import BaseModelOutput, DepthEstimatorOutput, SemanticSegmenterOutput
41
+ from ...modeling_utils import PreTrainedModel
42
+ from ...pytorch_utils import find_pruneable_heads_and_indices, prune_linear_layer
43
+ from ...utils import ModelOutput, logging
44
+ from ..auto import AutoBackbone
45
+ from .configuration_dpt import DPTConfig
46
+
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+ # General docstring
51
+ _CONFIG_FOR_DOC = "DPTConfig"
52
+
53
+ # Base docstring
54
+ _CHECKPOINT_FOR_DOC = "Intel/dpt-large"
55
+ _EXPECTED_OUTPUT_SHAPE = [1, 577, 1024]
56
+
57
+
58
+ DPT_PRETRAINED_MODEL_ARCHIVE_LIST = [
59
+ "Intel/dpt-large",
60
+ "Intel/dpt-hybrid-midas",
61
+ # See all DPT models at https://huggingface.co/models?filter=dpt
62
+ ]
63
+
64
+
65
+ @dataclass
66
+ class BaseModelOutputWithIntermediateActivations(ModelOutput):
67
+ """
68
+ Base class for model's outputs that also contains intermediate activations that can be used at later stages. Useful
69
+ in the context of Vision models.:
70
+
71
+ Args:
72
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
73
+ Sequence of hidden-states at the output of the last layer of the model.
74
+ intermediate_activations (`tuple(torch.FloatTensor)`, *optional*):
75
+ Intermediate activations that can be used to compute hidden states of the model at various layers.
76
+ """
77
+
78
+ last_hidden_states: torch.FloatTensor = None
79
+ intermediate_activations: Optional[Tuple[torch.FloatTensor]] = None
80
+
81
+
82
+ @dataclass
83
+ class BaseModelOutputWithPoolingAndIntermediateActivations(ModelOutput):
84
+ """
85
+ Base class for model's outputs that also contains a pooling of the last hidden states as well as intermediate
86
+ activations that can be used by the model at later stages.
87
+
88
+ Args:
89
+ last_hidden_state (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
90
+ Sequence of hidden-states at the output of the last layer of the model.
91
+ pooler_output (`torch.FloatTensor` of shape `(batch_size, hidden_size)`):
92
+ Last layer hidden-state of the first token of the sequence (classification token) after further processing
93
+ through the layers used for the auxiliary pretraining task. E.g. for BERT-family of models, this returns
94
+ the classification token after processing through a linear layer and a tanh activation function. The linear
95
+ layer weights are trained from the next sentence prediction (classification) objective during pretraining.
96
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
97
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
98
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
99
+
100
+ Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.
101
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
102
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
103
+ sequence_length)`.
104
+
105
+ Attentions weights after the attention softmax, used to compute the weighted average in the self-attention
106
+ heads.
107
+ intermediate_activations (`tuple(torch.FloatTensor)`, *optional*):
108
+ Intermediate activations that can be used to compute hidden states of the model at various layers.
109
+ """
110
+
111
+ last_hidden_state: torch.FloatTensor = None
112
+ pooler_output: torch.FloatTensor = None
113
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
114
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
115
+ intermediate_activations: Optional[Tuple[torch.FloatTensor]] = None
116
+
117
+
118
+ class DPTViTHybridEmbeddings(nn.Module):
119
+ """
120
+ This class turns `pixel_values` of shape `(batch_size, num_channels, height, width)` into the initial
121
+ `hidden_states` (patch embeddings) of shape `(batch_size, seq_length, hidden_size)` to be consumed by a
122
+ Transformer.
123
+ """
124
+
125
+ def __init__(self, config, feature_size=None):
126
+ super().__init__()
127
+ image_size, patch_size = config.image_size, config.patch_size
128
+ num_channels, hidden_size = config.num_channels, config.hidden_size
129
+
130
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
131
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
132
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
133
+
134
+ self.backbone = AutoBackbone.from_config(config.backbone_config)
135
+ feature_dim = self.backbone.channels[-1]
136
+ if len(config.backbone_config.out_features) != 3:
137
+ raise ValueError(
138
+ f"Expected backbone to have 3 output features, got {len(config.backbone_config.out_features)}"
139
+ )
140
+ self.residual_feature_map_index = [0, 1] # Always take the output of the first and second backbone stage
141
+
142
+ if feature_size is None:
143
+ feat_map_shape = config.backbone_featmap_shape
144
+ feature_size = feat_map_shape[-2:]
145
+ feature_dim = feat_map_shape[1]
146
+ else:
147
+ feature_size = (
148
+ feature_size if isinstance(feature_size, collections.abc.Iterable) else (feature_size, feature_size)
149
+ )
150
+ feature_dim = self.backbone.channels[-1]
151
+
152
+ self.image_size = image_size
153
+ self.patch_size = patch_size[0]
154
+ self.num_channels = num_channels
155
+
156
+ self.projection = nn.Conv2d(feature_dim, hidden_size, kernel_size=1)
157
+
158
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
159
+ self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.hidden_size))
160
+
161
+ def _resize_pos_embed(self, posemb, grid_size_height, grid_size_width, start_index=1):
162
+ posemb_tok = posemb[:, :start_index]
163
+ posemb_grid = posemb[0, start_index:]
164
+
165
+ old_grid_size = int(math.sqrt(len(posemb_grid)))
166
+
167
+ posemb_grid = posemb_grid.reshape(1, old_grid_size, old_grid_size, -1).permute(0, 3, 1, 2)
168
+ posemb_grid = nn.functional.interpolate(posemb_grid, size=(grid_size_height, grid_size_width), mode="bilinear")
169
+ posemb_grid = posemb_grid.permute(0, 2, 3, 1).reshape(1, grid_size_height * grid_size_width, -1)
170
+
171
+ posemb = torch.cat([posemb_tok, posemb_grid], dim=1)
172
+
173
+ return posemb
174
+
175
+ def forward(
176
+ self, pixel_values: torch.Tensor, interpolate_pos_encoding: bool = False, return_dict: bool = False
177
+ ) -> torch.Tensor:
178
+ batch_size, num_channels, height, width = pixel_values.shape
179
+ if num_channels != self.num_channels:
180
+ raise ValueError(
181
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
182
+ )
183
+ if not interpolate_pos_encoding:
184
+ if height != self.image_size[0] or width != self.image_size[1]:
185
+ raise ValueError(
186
+ f"Input image size ({height}*{width}) doesn't match model"
187
+ f" ({self.image_size[0]}*{self.image_size[1]})."
188
+ )
189
+
190
+ position_embeddings = self._resize_pos_embed(
191
+ self.position_embeddings, height // self.patch_size, width // self.patch_size
192
+ )
193
+
194
+ backbone_output = self.backbone(pixel_values)
195
+
196
+ features = backbone_output.feature_maps[-1]
197
+
198
+ # Retrieve also the intermediate activations to use them at later stages
199
+ output_hidden_states = [backbone_output.feature_maps[index] for index in self.residual_feature_map_index]
200
+
201
+ embeddings = self.projection(features).flatten(2).transpose(1, 2)
202
+
203
+ cls_tokens = self.cls_token.expand(batch_size, -1, -1)
204
+ embeddings = torch.cat((cls_tokens, embeddings), dim=1)
205
+
206
+ # add positional encoding to each token
207
+ embeddings = embeddings + position_embeddings
208
+
209
+ if not return_dict:
210
+ return (embeddings, output_hidden_states)
211
+
212
+ # Return hidden states and intermediate activations
213
+ return BaseModelOutputWithIntermediateActivations(
214
+ last_hidden_states=embeddings,
215
+ intermediate_activations=output_hidden_states,
216
+ )
217
+
218
+
219
+ class DPTViTEmbeddings(nn.Module):
220
+ """
221
+ Construct the CLS token, position and patch embeddings.
222
+
223
+ """
224
+
225
+ def __init__(self, config):
226
+ super().__init__()
227
+
228
+ self.cls_token = nn.Parameter(torch.zeros(1, 1, config.hidden_size))
229
+ self.patch_embeddings = DPTViTPatchEmbeddings(config)
230
+ num_patches = self.patch_embeddings.num_patches
231
+ self.position_embeddings = nn.Parameter(torch.zeros(1, num_patches + 1, config.hidden_size))
232
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
233
+ self.config = config
234
+
235
+ def _resize_pos_embed(self, posemb, grid_size_height, grid_size_width, start_index=1):
236
+ posemb_tok = posemb[:, :start_index]
237
+ posemb_grid = posemb[0, start_index:]
238
+
239
+ old_grid_size = int(math.sqrt(len(posemb_grid)))
240
+
241
+ posemb_grid = posemb_grid.reshape(1, old_grid_size, old_grid_size, -1).permute(0, 3, 1, 2)
242
+ posemb_grid = nn.functional.interpolate(posemb_grid, size=(grid_size_height, grid_size_width), mode="bilinear")
243
+ posemb_grid = posemb_grid.permute(0, 2, 3, 1).reshape(1, grid_size_height * grid_size_width, -1)
244
+
245
+ posemb = torch.cat([posemb_tok, posemb_grid], dim=1)
246
+
247
+ return posemb
248
+
249
+ def forward(self, pixel_values, return_dict=False):
250
+ batch_size, num_channels, height, width = pixel_values.shape
251
+
252
+ # possibly interpolate position encodings to handle varying image sizes
253
+ patch_size = self.config.patch_size
254
+ position_embeddings = self._resize_pos_embed(
255
+ self.position_embeddings, height // patch_size, width // patch_size
256
+ )
257
+
258
+ embeddings = self.patch_embeddings(pixel_values)
259
+
260
+ batch_size, seq_len, _ = embeddings.size()
261
+
262
+ # add the [CLS] token to the embedded patch tokens
263
+ cls_tokens = self.cls_token.expand(batch_size, -1, -1)
264
+ embeddings = torch.cat((cls_tokens, embeddings), dim=1)
265
+
266
+ # add positional encoding to each token
267
+ embeddings = embeddings + position_embeddings
268
+
269
+ embeddings = self.dropout(embeddings)
270
+
271
+ if not return_dict:
272
+ return (embeddings,)
273
+
274
+ return BaseModelOutputWithIntermediateActivations(last_hidden_states=embeddings)
275
+
276
+
277
+ class DPTViTPatchEmbeddings(nn.Module):
278
+ """
279
+ Image to Patch Embedding.
280
+
281
+ """
282
+
283
+ def __init__(self, config):
284
+ super().__init__()
285
+ image_size, patch_size = config.image_size, config.patch_size
286
+ num_channels, hidden_size = config.num_channels, config.hidden_size
287
+
288
+ image_size = image_size if isinstance(image_size, collections.abc.Iterable) else (image_size, image_size)
289
+ patch_size = patch_size if isinstance(patch_size, collections.abc.Iterable) else (patch_size, patch_size)
290
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
291
+ self.image_size = image_size
292
+ self.patch_size = patch_size
293
+ self.num_channels = num_channels
294
+ self.num_patches = num_patches
295
+
296
+ self.projection = nn.Conv2d(num_channels, hidden_size, kernel_size=patch_size, stride=patch_size)
297
+
298
+ def forward(self, pixel_values):
299
+ batch_size, num_channels, height, width = pixel_values.shape
300
+ if num_channels != self.num_channels:
301
+ raise ValueError(
302
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
303
+ )
304
+ embeddings = self.projection(pixel_values).flatten(2).transpose(1, 2)
305
+ return embeddings
306
+
307
+
308
+ # Copied from transformers.models.vit.modeling_vit.ViTSelfAttention with ViT->DPT
309
+ class DPTViTSelfAttention(nn.Module):
310
+ def __init__(self, config: DPTConfig) -> None:
311
+ super().__init__()
312
+ if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"):
313
+ raise ValueError(
314
+ f"The hidden size {config.hidden_size,} is not a multiple of the number of attention "
315
+ f"heads {config.num_attention_heads}."
316
+ )
317
+
318
+ self.num_attention_heads = config.num_attention_heads
319
+ self.attention_head_size = int(config.hidden_size / config.num_attention_heads)
320
+ self.all_head_size = self.num_attention_heads * self.attention_head_size
321
+
322
+ self.query = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
323
+ self.key = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
324
+ self.value = nn.Linear(config.hidden_size, self.all_head_size, bias=config.qkv_bias)
325
+
326
+ self.dropout = nn.Dropout(config.attention_probs_dropout_prob)
327
+
328
+ def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor:
329
+ new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size)
330
+ x = x.view(new_x_shape)
331
+ return x.permute(0, 2, 1, 3)
332
+
333
+ def forward(
334
+ self, hidden_states, head_mask: Optional[torch.Tensor] = None, output_attentions: bool = False
335
+ ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
336
+ mixed_query_layer = self.query(hidden_states)
337
+
338
+ key_layer = self.transpose_for_scores(self.key(hidden_states))
339
+ value_layer = self.transpose_for_scores(self.value(hidden_states))
340
+ query_layer = self.transpose_for_scores(mixed_query_layer)
341
+
342
+ # Take the dot product between "query" and "key" to get the raw attention scores.
343
+ attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2))
344
+
345
+ attention_scores = attention_scores / math.sqrt(self.attention_head_size)
346
+
347
+ # Normalize the attention scores to probabilities.
348
+ attention_probs = nn.functional.softmax(attention_scores, dim=-1)
349
+
350
+ # This is actually dropping out entire tokens to attend to, which might
351
+ # seem a bit unusual, but is taken from the original Transformer paper.
352
+ attention_probs = self.dropout(attention_probs)
353
+
354
+ # Mask heads if we want to
355
+ if head_mask is not None:
356
+ attention_probs = attention_probs * head_mask
357
+
358
+ context_layer = torch.matmul(attention_probs, value_layer)
359
+
360
+ context_layer = context_layer.permute(0, 2, 1, 3).contiguous()
361
+ new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,)
362
+ context_layer = context_layer.view(new_context_layer_shape)
363
+
364
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
365
+
366
+ return outputs
367
+
368
+
369
+ # Copied from transformers.models.vit.modeling_vit.ViTSelfOutput with ViT->DPT
370
+ class DPTViTSelfOutput(nn.Module):
371
+ """
372
+ The residual connection is defined in DPTLayer instead of here (as is the case with other models), due to the
373
+ layernorm applied before each block.
374
+ """
375
+
376
+ def __init__(self, config: DPTConfig) -> None:
377
+ super().__init__()
378
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
379
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
380
+
381
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
382
+ hidden_states = self.dense(hidden_states)
383
+ hidden_states = self.dropout(hidden_states)
384
+
385
+ return hidden_states
386
+
387
+
388
+ class DPTViTAttention(nn.Module):
389
+ def __init__(self, config: DPTConfig) -> None:
390
+ super().__init__()
391
+ self.attention = DPTViTSelfAttention(config)
392
+ self.output = DPTViTSelfOutput(config)
393
+ self.pruned_heads = set()
394
+
395
+ # Copied from transformers.models.vit.modeling_vit.ViTAttention.prune_heads
396
+ def prune_heads(self, heads: Set[int]) -> None:
397
+ if len(heads) == 0:
398
+ return
399
+ heads, index = find_pruneable_heads_and_indices(
400
+ heads, self.attention.num_attention_heads, self.attention.attention_head_size, self.pruned_heads
401
+ )
402
+
403
+ # Prune linear layers
404
+ self.attention.query = prune_linear_layer(self.attention.query, index)
405
+ self.attention.key = prune_linear_layer(self.attention.key, index)
406
+ self.attention.value = prune_linear_layer(self.attention.value, index)
407
+ self.output.dense = prune_linear_layer(self.output.dense, index, dim=1)
408
+
409
+ # Update hyper params and store pruned heads
410
+ self.attention.num_attention_heads = self.attention.num_attention_heads - len(heads)
411
+ self.attention.all_head_size = self.attention.attention_head_size * self.attention.num_attention_heads
412
+ self.pruned_heads = self.pruned_heads.union(heads)
413
+
414
+ # Copied from transformers.models.vit.modeling_vit.ViTAttention.forward
415
+ def forward(
416
+ self,
417
+ hidden_states: torch.Tensor,
418
+ head_mask: Optional[torch.Tensor] = None,
419
+ output_attentions: bool = False,
420
+ ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
421
+ self_outputs = self.attention(hidden_states, head_mask, output_attentions)
422
+
423
+ attention_output = self.output(self_outputs[0], hidden_states)
424
+
425
+ outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them
426
+ return outputs
427
+
428
+
429
+ # Copied from transformers.models.vit.modeling_vit.ViTIntermediate with ViT->DPT
430
+ class DPTViTIntermediate(nn.Module):
431
+ def __init__(self, config: DPTConfig) -> None:
432
+ super().__init__()
433
+ self.dense = nn.Linear(config.hidden_size, config.intermediate_size)
434
+ if isinstance(config.hidden_act, str):
435
+ self.intermediate_act_fn = ACT2FN[config.hidden_act]
436
+ else:
437
+ self.intermediate_act_fn = config.hidden_act
438
+
439
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
440
+ hidden_states = self.dense(hidden_states)
441
+ hidden_states = self.intermediate_act_fn(hidden_states)
442
+
443
+ return hidden_states
444
+
445
+
446
+ # Copied from transformers.models.vit.modeling_vit.ViTOutput with ViT->DPT
447
+ class DPTViTOutput(nn.Module):
448
+ def __init__(self, config: DPTConfig) -> None:
449
+ super().__init__()
450
+ self.dense = nn.Linear(config.intermediate_size, config.hidden_size)
451
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
452
+
453
+ def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor:
454
+ hidden_states = self.dense(hidden_states)
455
+ hidden_states = self.dropout(hidden_states)
456
+
457
+ hidden_states = hidden_states + input_tensor
458
+
459
+ return hidden_states
460
+
461
+
462
+ # copied from transformers.models.vit.modeling_vit.ViTLayer with ViTConfig->DPTConfig, ViTAttention->DPTViTAttention, ViTIntermediate->DPTViTIntermediate, ViTOutput->DPTViTOutput
463
+ class DPTViTLayer(nn.Module):
464
+ """This corresponds to the Block class in the timm implementation."""
465
+
466
+ def __init__(self, config: DPTConfig) -> None:
467
+ super().__init__()
468
+ self.chunk_size_feed_forward = config.chunk_size_feed_forward
469
+ self.seq_len_dim = 1
470
+ self.attention = DPTViTAttention(config)
471
+ self.intermediate = DPTViTIntermediate(config)
472
+ self.output = DPTViTOutput(config)
473
+ self.layernorm_before = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
474
+ self.layernorm_after = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
475
+
476
+ def forward(
477
+ self,
478
+ hidden_states: torch.Tensor,
479
+ head_mask: Optional[torch.Tensor] = None,
480
+ output_attentions: bool = False,
481
+ ) -> Union[Tuple[torch.Tensor, torch.Tensor], Tuple[torch.Tensor]]:
482
+ self_attention_outputs = self.attention(
483
+ self.layernorm_before(hidden_states), # in ViT, layernorm is applied before self-attention
484
+ head_mask,
485
+ output_attentions=output_attentions,
486
+ )
487
+ attention_output = self_attention_outputs[0]
488
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
489
+
490
+ # first residual connection
491
+ hidden_states = attention_output + hidden_states
492
+
493
+ # in ViT, layernorm is also applied after self-attention
494
+ layer_output = self.layernorm_after(hidden_states)
495
+ layer_output = self.intermediate(layer_output)
496
+
497
+ # second residual connection is done here
498
+ layer_output = self.output(layer_output, hidden_states)
499
+
500
+ outputs = (layer_output,) + outputs
501
+
502
+ return outputs
503
+
504
+
505
+ # copied from transformers.models.vit.modeling_vit.ViTEncoder with ViTConfig -> DPTConfig, ViTLayer->DPTViTLayer
506
+ class DPTViTEncoder(nn.Module):
507
+ def __init__(self, config: DPTConfig) -> None:
508
+ super().__init__()
509
+ self.config = config
510
+ self.layer = nn.ModuleList([DPTViTLayer(config) for _ in range(config.num_hidden_layers)])
511
+ self.gradient_checkpointing = False
512
+
513
+ def forward(
514
+ self,
515
+ hidden_states: torch.Tensor,
516
+ head_mask: Optional[torch.Tensor] = None,
517
+ output_attentions: bool = False,
518
+ output_hidden_states: bool = False,
519
+ return_dict: bool = True,
520
+ ) -> Union[tuple, BaseModelOutput]:
521
+ all_hidden_states = () if output_hidden_states else None
522
+ all_self_attentions = () if output_attentions else None
523
+
524
+ for i, layer_module in enumerate(self.layer):
525
+ if output_hidden_states:
526
+ all_hidden_states = all_hidden_states + (hidden_states,)
527
+
528
+ layer_head_mask = head_mask[i] if head_mask is not None else None
529
+
530
+ if self.gradient_checkpointing and self.training:
531
+ layer_outputs = self._gradient_checkpointing_func(
532
+ layer_module.__call__,
533
+ hidden_states,
534
+ layer_head_mask,
535
+ output_attentions,
536
+ )
537
+ else:
538
+ layer_outputs = layer_module(hidden_states, layer_head_mask, output_attentions)
539
+
540
+ hidden_states = layer_outputs[0]
541
+
542
+ if output_attentions:
543
+ all_self_attentions = all_self_attentions + (layer_outputs[1],)
544
+
545
+ if output_hidden_states:
546
+ all_hidden_states = all_hidden_states + (hidden_states,)
547
+
548
+ if not return_dict:
549
+ return tuple(v for v in [hidden_states, all_hidden_states, all_self_attentions] if v is not None)
550
+ return BaseModelOutput(
551
+ last_hidden_state=hidden_states,
552
+ hidden_states=all_hidden_states,
553
+ attentions=all_self_attentions,
554
+ )
555
+
556
+
557
+ class DPTReassembleStage(nn.Module):
558
+ """
559
+ This class reassembles the hidden states of the backbone into image-like feature representations at various
560
+ resolutions.
561
+
562
+ This happens in 3 stages:
563
+ 1. Map the N + 1 tokens to a set of N tokens, by taking into account the readout ([CLS]) token according to
564
+ `config.readout_type`.
565
+ 2. Project the channel dimension of the hidden states according to `config.neck_hidden_sizes`.
566
+ 3. Resizing the spatial dimensions (height, width).
567
+
568
+ Args:
569
+ config (`[DPTConfig]`):
570
+ Model configuration class defining the model architecture.
571
+ """
572
+
573
+ def __init__(self, config):
574
+ super().__init__()
575
+
576
+ self.config = config
577
+ self.layers = nn.ModuleList()
578
+ if config.is_hybrid:
579
+ self._init_reassemble_dpt_hybrid(config)
580
+ else:
581
+ self._init_reassemble_dpt(config)
582
+
583
+ self.neck_ignore_stages = config.neck_ignore_stages
584
+
585
+ def _init_reassemble_dpt_hybrid(self, config):
586
+ r""" "
587
+ For DPT-Hybrid the first 2 reassemble layers are set to `nn.Identity()`, please check the official
588
+ implementation: https://github.com/isl-org/DPT/blob/f43ef9e08d70a752195028a51be5e1aff227b913/dpt/vit.py#L438
589
+ for more details.
590
+ """
591
+ for i, factor in zip(range(len(config.neck_hidden_sizes)), config.reassemble_factors):
592
+ if i <= 1:
593
+ self.layers.append(nn.Identity())
594
+ elif i > 1:
595
+ self.layers.append(DPTReassembleLayer(config, channels=config.neck_hidden_sizes[i], factor=factor))
596
+
597
+ if config.readout_type != "project":
598
+ raise ValueError(f"Readout type {config.readout_type} is not supported for DPT-Hybrid.")
599
+
600
+ # When using DPT-Hybrid the readout type is set to "project". The sanity check is done on the config file
601
+ self.readout_projects = nn.ModuleList()
602
+ hidden_size = _get_backbone_hidden_size(config)
603
+ for i in range(len(config.neck_hidden_sizes)):
604
+ if i <= 1:
605
+ self.readout_projects.append(nn.Sequential(nn.Identity()))
606
+ elif i > 1:
607
+ self.readout_projects.append(
608
+ nn.Sequential(nn.Linear(2 * hidden_size, hidden_size), ACT2FN[config.hidden_act])
609
+ )
610
+
611
+ def _init_reassemble_dpt(self, config):
612
+ for i, factor in zip(range(len(config.neck_hidden_sizes)), config.reassemble_factors):
613
+ self.layers.append(DPTReassembleLayer(config, channels=config.neck_hidden_sizes[i], factor=factor))
614
+
615
+ if config.readout_type == "project":
616
+ self.readout_projects = nn.ModuleList()
617
+ hidden_size = _get_backbone_hidden_size(config)
618
+ for _ in range(len(config.neck_hidden_sizes)):
619
+ self.readout_projects.append(
620
+ nn.Sequential(nn.Linear(2 * hidden_size, hidden_size), ACT2FN[config.hidden_act])
621
+ )
622
+
623
+ def forward(self, hidden_states: List[torch.Tensor], patch_height=None, patch_width=None) -> List[torch.Tensor]:
624
+ """
625
+ Args:
626
+ hidden_states (`List[torch.FloatTensor]`, each of shape `(batch_size, sequence_length + 1, hidden_size)`):
627
+ List of hidden states from the backbone.
628
+ """
629
+ out = []
630
+
631
+ for i, hidden_state in enumerate(hidden_states):
632
+ if i not in self.neck_ignore_stages:
633
+ # reshape to (batch_size, num_channels, height, width)
634
+ cls_token, hidden_state = hidden_state[:, 0], hidden_state[:, 1:]
635
+ batch_size, sequence_length, num_channels = hidden_state.shape
636
+ if patch_height is not None and patch_width is not None:
637
+ hidden_state = hidden_state.reshape(batch_size, patch_height, patch_width, num_channels)
638
+ else:
639
+ size = int(math.sqrt(sequence_length))
640
+ hidden_state = hidden_state.reshape(batch_size, size, size, num_channels)
641
+ hidden_state = hidden_state.permute(0, 3, 1, 2).contiguous()
642
+
643
+ feature_shape = hidden_state.shape
644
+ if self.config.readout_type == "project":
645
+ # reshape to (batch_size, height*width, num_channels)
646
+ hidden_state = hidden_state.flatten(2).permute((0, 2, 1))
647
+ readout = cls_token.unsqueeze(1).expand_as(hidden_state)
648
+ # concatenate the readout token to the hidden states and project
649
+ hidden_state = self.readout_projects[i](torch.cat((hidden_state, readout), -1))
650
+ # reshape back to (batch_size, num_channels, height, width)
651
+ hidden_state = hidden_state.permute(0, 2, 1).reshape(feature_shape)
652
+ elif self.config.readout_type == "add":
653
+ hidden_state = hidden_state.flatten(2) + cls_token.unsqueeze(-1)
654
+ hidden_state = hidden_state.reshape(feature_shape)
655
+ hidden_state = self.layers[i](hidden_state)
656
+ out.append(hidden_state)
657
+
658
+ return out
659
+
660
+
661
+ def _get_backbone_hidden_size(config):
662
+ if config.backbone_config is not None and config.is_hybrid is False:
663
+ return config.backbone_config.hidden_size
664
+ else:
665
+ return config.hidden_size
666
+
667
+
668
+ class DPTReassembleLayer(nn.Module):
669
+ def __init__(self, config, channels, factor):
670
+ super().__init__()
671
+ # projection
672
+ hidden_size = _get_backbone_hidden_size(config)
673
+ self.projection = nn.Conv2d(in_channels=hidden_size, out_channels=channels, kernel_size=1)
674
+
675
+ # up/down sampling depending on factor
676
+ if factor > 1:
677
+ self.resize = nn.ConvTranspose2d(channels, channels, kernel_size=factor, stride=factor, padding=0)
678
+ elif factor == 1:
679
+ self.resize = nn.Identity()
680
+ elif factor < 1:
681
+ # so should downsample
682
+ self.resize = nn.Conv2d(channels, channels, kernel_size=3, stride=int(1 / factor), padding=1)
683
+
684
+ def forward(self, hidden_state):
685
+ hidden_state = self.projection(hidden_state)
686
+ hidden_state = self.resize(hidden_state)
687
+ return hidden_state
688
+
689
+
690
+ class DPTFeatureFusionStage(nn.Module):
691
+ def __init__(self, config):
692
+ super().__init__()
693
+ self.layers = nn.ModuleList()
694
+ for _ in range(len(config.neck_hidden_sizes)):
695
+ self.layers.append(DPTFeatureFusionLayer(config))
696
+
697
+ def forward(self, hidden_states):
698
+ # reversing the hidden_states, we start from the last
699
+ hidden_states = hidden_states[::-1]
700
+
701
+ fused_hidden_states = []
702
+ # first layer only uses the last hidden_state
703
+ fused_hidden_state = self.layers[0](hidden_states[0])
704
+ fused_hidden_states.append(fused_hidden_state)
705
+ # looping from the last layer to the second
706
+ for hidden_state, layer in zip(hidden_states[1:], self.layers[1:]):
707
+ fused_hidden_state = layer(fused_hidden_state, hidden_state)
708
+ fused_hidden_states.append(fused_hidden_state)
709
+
710
+ return fused_hidden_states
711
+
712
+
713
+ class DPTPreActResidualLayer(nn.Module):
714
+ """
715
+ ResidualConvUnit, pre-activate residual unit.
716
+
717
+ Args:
718
+ config (`[DPTConfig]`):
719
+ Model configuration class defining the model architecture.
720
+ """
721
+
722
+ def __init__(self, config):
723
+ super().__init__()
724
+
725
+ self.use_batch_norm = config.use_batch_norm_in_fusion_residual
726
+ use_bias_in_fusion_residual = (
727
+ config.use_bias_in_fusion_residual
728
+ if config.use_bias_in_fusion_residual is not None
729
+ else not self.use_batch_norm
730
+ )
731
+
732
+ self.activation1 = nn.ReLU()
733
+ self.convolution1 = nn.Conv2d(
734
+ config.fusion_hidden_size,
735
+ config.fusion_hidden_size,
736
+ kernel_size=3,
737
+ stride=1,
738
+ padding=1,
739
+ bias=use_bias_in_fusion_residual,
740
+ )
741
+
742
+ self.activation2 = nn.ReLU()
743
+ self.convolution2 = nn.Conv2d(
744
+ config.fusion_hidden_size,
745
+ config.fusion_hidden_size,
746
+ kernel_size=3,
747
+ stride=1,
748
+ padding=1,
749
+ bias=use_bias_in_fusion_residual,
750
+ )
751
+
752
+ if self.use_batch_norm:
753
+ self.batch_norm1 = nn.BatchNorm2d(config.fusion_hidden_size)
754
+ self.batch_norm2 = nn.BatchNorm2d(config.fusion_hidden_size)
755
+
756
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
757
+ residual = hidden_state
758
+ hidden_state = self.activation1(hidden_state)
759
+
760
+ hidden_state = self.convolution1(hidden_state)
761
+
762
+ if self.use_batch_norm:
763
+ hidden_state = self.batch_norm1(hidden_state)
764
+
765
+ hidden_state = self.activation2(hidden_state)
766
+ hidden_state = self.convolution2(hidden_state)
767
+
768
+ if self.use_batch_norm:
769
+ hidden_state = self.batch_norm2(hidden_state)
770
+
771
+ return hidden_state + residual
772
+
773
+
774
+ class DPTFeatureFusionLayer(nn.Module):
775
+ """Feature fusion layer, merges feature maps from different stages.
776
+
777
+ Args:
778
+ config (`[DPTConfig]`):
779
+ Model configuration class defining the model architecture.
780
+ align_corners (`bool`, *optional*, defaults to `True`):
781
+ The align_corner setting for bilinear upsample.
782
+ """
783
+
784
+ def __init__(self, config, align_corners=True):
785
+ super().__init__()
786
+
787
+ self.align_corners = align_corners
788
+
789
+ self.projection = nn.Conv2d(config.fusion_hidden_size, config.fusion_hidden_size, kernel_size=1, bias=True)
790
+
791
+ self.residual_layer1 = DPTPreActResidualLayer(config)
792
+ self.residual_layer2 = DPTPreActResidualLayer(config)
793
+
794
+ def forward(self, hidden_state, residual=None):
795
+ if residual is not None:
796
+ if hidden_state.shape != residual.shape:
797
+ residual = nn.functional.interpolate(
798
+ residual, size=(hidden_state.shape[2], hidden_state.shape[3]), mode="bilinear", align_corners=False
799
+ )
800
+ hidden_state = hidden_state + self.residual_layer1(residual)
801
+
802
+ hidden_state = self.residual_layer2(hidden_state)
803
+ hidden_state = nn.functional.interpolate(
804
+ hidden_state, scale_factor=2, mode="bilinear", align_corners=self.align_corners
805
+ )
806
+ hidden_state = self.projection(hidden_state)
807
+
808
+ return hidden_state
809
+
810
+
811
+ class DPTPreTrainedModel(PreTrainedModel):
812
+ """
813
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
814
+ models.
815
+ """
816
+
817
+ config_class = DPTConfig
818
+ base_model_prefix = "dpt"
819
+ main_input_name = "pixel_values"
820
+ supports_gradient_checkpointing = True
821
+
822
+ def _init_weights(self, module):
823
+ """Initialize the weights"""
824
+ if isinstance(module, (nn.Linear, nn.Conv2d, nn.ConvTranspose2d)):
825
+ # Slightly different from the TF version which uses truncated_normal for initialization
826
+ # cf https://github.com/pytorch/pytorch/pull/5617
827
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
828
+ if module.bias is not None:
829
+ module.bias.data.zero_()
830
+ elif isinstance(module, nn.LayerNorm):
831
+ module.bias.data.zero_()
832
+ module.weight.data.fill_(1.0)
833
+
834
+
835
+ DPT_START_DOCSTRING = r"""
836
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
837
+ as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
838
+ behavior.
839
+
840
+ Parameters:
841
+ config ([`ViTConfig`]): Model configuration class with all the parameters of the model.
842
+ Initializing with a config file does not load the weights associated with the model, only the
843
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
844
+ """
845
+
846
+ DPT_INPUTS_DOCSTRING = r"""
847
+ Args:
848
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
849
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See [`DPTImageProcessor.__call__`]
850
+ for details.
851
+
852
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
853
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
854
+
855
+ - 1 indicates the head is **not masked**,
856
+ - 0 indicates the head is **masked**.
857
+
858
+ output_attentions (`bool`, *optional*):
859
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
860
+ tensors for more detail.
861
+ output_hidden_states (`bool`, *optional*):
862
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
863
+ more detail.
864
+ return_dict (`bool`, *optional*):
865
+ Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
866
+ """
867
+
868
+
869
+ @add_start_docstrings(
870
+ "The bare DPT Model transformer outputting raw hidden-states without any specific head on top.",
871
+ DPT_START_DOCSTRING,
872
+ )
873
+ class DPTModel(DPTPreTrainedModel):
874
+ def __init__(self, config, add_pooling_layer=True):
875
+ super().__init__(config)
876
+ self.config = config
877
+
878
+ # vit encoder
879
+ if config.is_hybrid:
880
+ self.embeddings = DPTViTHybridEmbeddings(config)
881
+ else:
882
+ self.embeddings = DPTViTEmbeddings(config)
883
+ self.encoder = DPTViTEncoder(config)
884
+
885
+ self.layernorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps)
886
+ self.pooler = DPTViTPooler(config) if add_pooling_layer else None
887
+
888
+ # Initialize weights and apply final processing
889
+ self.post_init()
890
+
891
+ def get_input_embeddings(self):
892
+ if self.config.is_hybrid:
893
+ return self.embeddings
894
+ else:
895
+ return self.embeddings.patch_embeddings
896
+
897
+ def _prune_heads(self, heads_to_prune):
898
+ """
899
+ Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
900
+ class PreTrainedModel
901
+ """
902
+ for layer, heads in heads_to_prune.items():
903
+ self.encoder.layer[layer].attention.prune_heads(heads)
904
+
905
+ @add_start_docstrings_to_model_forward(DPT_INPUTS_DOCSTRING)
906
+ @add_code_sample_docstrings(
907
+ checkpoint=_CHECKPOINT_FOR_DOC,
908
+ output_type=BaseModelOutputWithPoolingAndIntermediateActivations,
909
+ config_class=_CONFIG_FOR_DOC,
910
+ modality="vision",
911
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
912
+ )
913
+ def forward(
914
+ self,
915
+ pixel_values: torch.FloatTensor,
916
+ head_mask: Optional[torch.FloatTensor] = None,
917
+ output_attentions: Optional[bool] = None,
918
+ output_hidden_states: Optional[bool] = None,
919
+ return_dict: Optional[bool] = None,
920
+ ) -> Union[Tuple, BaseModelOutputWithPoolingAndIntermediateActivations]:
921
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
922
+ output_hidden_states = (
923
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
924
+ )
925
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
926
+
927
+ # Prepare head mask if needed
928
+ # 1.0 in head_mask indicate we keep the head
929
+ # attention_probs has shape bsz x n_heads x N x N
930
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
931
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
932
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
933
+
934
+ embedding_output = self.embeddings(pixel_values, return_dict=return_dict)
935
+
936
+ embedding_last_hidden_states = embedding_output[0] if not return_dict else embedding_output.last_hidden_states
937
+
938
+ encoder_outputs = self.encoder(
939
+ embedding_last_hidden_states,
940
+ head_mask=head_mask,
941
+ output_attentions=output_attentions,
942
+ output_hidden_states=output_hidden_states,
943
+ return_dict=return_dict,
944
+ )
945
+
946
+ sequence_output = encoder_outputs[0]
947
+ sequence_output = self.layernorm(sequence_output)
948
+ pooled_output = self.pooler(sequence_output) if self.pooler is not None else None
949
+
950
+ if not return_dict:
951
+ head_outputs = (sequence_output, pooled_output) if pooled_output is not None else (sequence_output,)
952
+ return head_outputs + encoder_outputs[1:] + embedding_output[1:]
953
+
954
+ return BaseModelOutputWithPoolingAndIntermediateActivations(
955
+ last_hidden_state=sequence_output,
956
+ pooler_output=pooled_output,
957
+ hidden_states=encoder_outputs.hidden_states,
958
+ attentions=encoder_outputs.attentions,
959
+ intermediate_activations=embedding_output.intermediate_activations,
960
+ )
961
+
962
+
963
+ # Copied from transformers.models.vit.modeling_vit.ViTPooler with ViT->DPT
964
+ class DPTViTPooler(nn.Module):
965
+ def __init__(self, config: DPTConfig):
966
+ super().__init__()
967
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
968
+ self.activation = nn.Tanh()
969
+
970
+ def forward(self, hidden_states):
971
+ # We "pool" the model by simply taking the hidden state corresponding
972
+ # to the first token.
973
+ first_token_tensor = hidden_states[:, 0]
974
+ pooled_output = self.dense(first_token_tensor)
975
+ pooled_output = self.activation(pooled_output)
976
+ return pooled_output
977
+
978
+
979
+ class DPTNeck(nn.Module):
980
+ """
981
+ DPTNeck. A neck is a module that is normally used between the backbone and the head. It takes a list of tensors as
982
+ input and produces another list of tensors as output. For DPT, it includes 2 stages:
983
+
984
+ * DPTReassembleStage
985
+ * DPTFeatureFusionStage.
986
+
987
+ Args:
988
+ config (dict): config dict.
989
+ """
990
+
991
+ def __init__(self, config):
992
+ super().__init__()
993
+ self.config = config
994
+
995
+ # postprocessing: only required in case of a non-hierarchical backbone (e.g. ViT, BEiT)
996
+ if config.backbone_config is not None and config.backbone_config.model_type in ["swinv2"]:
997
+ self.reassemble_stage = None
998
+ else:
999
+ self.reassemble_stage = DPTReassembleStage(config)
1000
+
1001
+ self.convs = nn.ModuleList()
1002
+ for channel in config.neck_hidden_sizes:
1003
+ self.convs.append(nn.Conv2d(channel, config.fusion_hidden_size, kernel_size=3, padding=1, bias=False))
1004
+
1005
+ # fusion
1006
+ self.fusion_stage = DPTFeatureFusionStage(config)
1007
+
1008
+ def forward(self, hidden_states: List[torch.Tensor], patch_height=None, patch_width=None) -> List[torch.Tensor]:
1009
+ """
1010
+ Args:
1011
+ hidden_states (`List[torch.FloatTensor]`, each of shape `(batch_size, sequence_length, hidden_size)` or `(batch_size, hidden_size, height, width)`):
1012
+ List of hidden states from the backbone.
1013
+ """
1014
+ if not isinstance(hidden_states, (tuple, list)):
1015
+ raise ValueError("hidden_states should be a tuple or list of tensors")
1016
+
1017
+ if len(hidden_states) != len(self.config.neck_hidden_sizes):
1018
+ raise ValueError("The number of hidden states should be equal to the number of neck hidden sizes.")
1019
+
1020
+ # postprocess hidden states
1021
+ if self.reassemble_stage is not None:
1022
+ hidden_states = self.reassemble_stage(hidden_states, patch_height, patch_width)
1023
+
1024
+ features = [self.convs[i](feature) for i, feature in enumerate(hidden_states)]
1025
+
1026
+ # fusion blocks
1027
+ output = self.fusion_stage(features)
1028
+
1029
+ return output
1030
+
1031
+
1032
+ class DPTDepthEstimationHead(nn.Module):
1033
+ """
1034
+ Output head head consisting of 3 convolutional layers. It progressively halves the feature dimension and upsamples
1035
+ the predictions to the input resolution after the first convolutional layer (details can be found in the paper's
1036
+ supplementary material).
1037
+ """
1038
+
1039
+ def __init__(self, config):
1040
+ super().__init__()
1041
+
1042
+ self.config = config
1043
+
1044
+ self.projection = None
1045
+ if config.add_projection:
1046
+ self.projection = nn.Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
1047
+
1048
+ features = config.fusion_hidden_size
1049
+ self.head = nn.Sequential(
1050
+ nn.Conv2d(features, features // 2, kernel_size=3, stride=1, padding=1),
1051
+ nn.Upsample(scale_factor=2, mode="bilinear", align_corners=True),
1052
+ nn.Conv2d(features // 2, 32, kernel_size=3, stride=1, padding=1),
1053
+ nn.ReLU(),
1054
+ nn.Conv2d(32, 1, kernel_size=1, stride=1, padding=0),
1055
+ nn.ReLU(),
1056
+ )
1057
+
1058
+ def forward(self, hidden_states: List[torch.Tensor]) -> torch.Tensor:
1059
+ # use last features
1060
+ hidden_states = hidden_states[self.config.head_in_index]
1061
+
1062
+ if self.projection is not None:
1063
+ hidden_states = self.projection(hidden_states)
1064
+ hidden_states = nn.ReLU()(hidden_states)
1065
+
1066
+ predicted_depth = self.head(hidden_states)
1067
+
1068
+ predicted_depth = predicted_depth.squeeze(dim=1)
1069
+
1070
+ return predicted_depth
1071
+
1072
+
1073
+ @add_start_docstrings(
1074
+ """
1075
+ DPT Model with a depth estimation head on top (consisting of 3 convolutional layers) e.g. for KITTI, NYUv2.
1076
+ """,
1077
+ DPT_START_DOCSTRING,
1078
+ )
1079
+ class DPTForDepthEstimation(DPTPreTrainedModel):
1080
+ def __init__(self, config):
1081
+ super().__init__(config)
1082
+
1083
+ self.backbone = None
1084
+ if config.backbone_config is not None and config.is_hybrid is False:
1085
+ self.backbone = AutoBackbone.from_config(config.backbone_config)
1086
+ else:
1087
+ self.dpt = DPTModel(config, add_pooling_layer=False)
1088
+
1089
+ # Neck
1090
+ self.neck = DPTNeck(config)
1091
+
1092
+ # Depth estimation head
1093
+ self.head = DPTDepthEstimationHead(config)
1094
+
1095
+ # Initialize weights and apply final processing
1096
+ self.post_init()
1097
+
1098
+ @add_start_docstrings_to_model_forward(DPT_INPUTS_DOCSTRING)
1099
+ @replace_return_docstrings(output_type=DepthEstimatorOutput, config_class=_CONFIG_FOR_DOC)
1100
+ def forward(
1101
+ self,
1102
+ pixel_values: torch.FloatTensor,
1103
+ head_mask: Optional[torch.FloatTensor] = None,
1104
+ labels: Optional[torch.LongTensor] = None,
1105
+ output_attentions: Optional[bool] = None,
1106
+ output_hidden_states: Optional[bool] = None,
1107
+ return_dict: Optional[bool] = None,
1108
+ ) -> Union[Tuple[torch.Tensor], DepthEstimatorOutput]:
1109
+ r"""
1110
+ labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
1111
+ Ground truth depth estimation maps for computing the loss.
1112
+
1113
+ Returns:
1114
+
1115
+ Examples:
1116
+ ```python
1117
+ >>> from transformers import AutoImageProcessor, DPTForDepthEstimation
1118
+ >>> import torch
1119
+ >>> import numpy as np
1120
+ >>> from PIL import Image
1121
+ >>> import requests
1122
+
1123
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1124
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1125
+
1126
+ >>> image_processor = AutoImageProcessor.from_pretrained("Intel/dpt-large")
1127
+ >>> model = DPTForDepthEstimation.from_pretrained("Intel/dpt-large")
1128
+
1129
+ >>> # prepare image for the model
1130
+ >>> inputs = image_processor(images=image, return_tensors="pt")
1131
+
1132
+ >>> with torch.no_grad():
1133
+ ... outputs = model(**inputs)
1134
+ ... predicted_depth = outputs.predicted_depth
1135
+
1136
+ >>> # interpolate to original size
1137
+ >>> prediction = torch.nn.functional.interpolate(
1138
+ ... predicted_depth.unsqueeze(1),
1139
+ ... size=image.size[::-1],
1140
+ ... mode="bicubic",
1141
+ ... align_corners=False,
1142
+ ... )
1143
+
1144
+ >>> # visualize the prediction
1145
+ >>> output = prediction.squeeze().cpu().numpy()
1146
+ >>> formatted = (output * 255 / np.max(output)).astype("uint8")
1147
+ >>> depth = Image.fromarray(formatted)
1148
+ ```"""
1149
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1150
+ output_hidden_states = (
1151
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1152
+ )
1153
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1154
+
1155
+ if self.backbone is not None:
1156
+ outputs = self.backbone.forward_with_filtered_kwargs(
1157
+ pixel_values, output_hidden_states=output_hidden_states, output_attentions=output_attentions
1158
+ )
1159
+ hidden_states = outputs.feature_maps
1160
+ else:
1161
+ outputs = self.dpt(
1162
+ pixel_values,
1163
+ head_mask=head_mask,
1164
+ output_attentions=output_attentions,
1165
+ output_hidden_states=True, # we need the intermediate hidden states
1166
+ return_dict=return_dict,
1167
+ )
1168
+ hidden_states = outputs.hidden_states if return_dict else outputs[1]
1169
+ # only keep certain features based on config.backbone_out_indices
1170
+ # note that the hidden_states also include the initial embeddings
1171
+ if not self.config.is_hybrid:
1172
+ hidden_states = [
1173
+ feature for idx, feature in enumerate(hidden_states[1:]) if idx in self.config.backbone_out_indices
1174
+ ]
1175
+ else:
1176
+ backbone_hidden_states = outputs.intermediate_activations if return_dict else list(outputs[-1])
1177
+ backbone_hidden_states.extend(
1178
+ feature
1179
+ for idx, feature in enumerate(hidden_states[1:])
1180
+ if idx in self.config.backbone_out_indices[2:]
1181
+ )
1182
+
1183
+ hidden_states = backbone_hidden_states
1184
+
1185
+ patch_height, patch_width = None, None
1186
+ if self.config.backbone_config is not None and self.config.is_hybrid is False:
1187
+ _, _, height, width = pixel_values.shape
1188
+ patch_size = self.config.backbone_config.patch_size
1189
+ patch_height = height // patch_size
1190
+ patch_width = width // patch_size
1191
+
1192
+ hidden_states = self.neck(hidden_states, patch_height, patch_width)
1193
+
1194
+ predicted_depth = self.head(hidden_states)
1195
+
1196
+ loss = None
1197
+ if labels is not None:
1198
+ raise NotImplementedError("Training is not implemented yet")
1199
+
1200
+ if not return_dict:
1201
+ if output_hidden_states:
1202
+ output = (predicted_depth,) + outputs[1:]
1203
+ else:
1204
+ output = (predicted_depth,) + outputs[2:]
1205
+ return ((loss,) + output) if loss is not None else output
1206
+
1207
+ return DepthEstimatorOutput(
1208
+ loss=loss,
1209
+ predicted_depth=predicted_depth,
1210
+ hidden_states=outputs.hidden_states if output_hidden_states else None,
1211
+ attentions=outputs.attentions,
1212
+ )
1213
+
1214
+
1215
+ class DPTSemanticSegmentationHead(nn.Module):
1216
+ def __init__(self, config):
1217
+ super().__init__()
1218
+
1219
+ self.config = config
1220
+
1221
+ features = config.fusion_hidden_size
1222
+ self.head = nn.Sequential(
1223
+ nn.Conv2d(features, features, kernel_size=3, padding=1, bias=False),
1224
+ nn.BatchNorm2d(features),
1225
+ nn.ReLU(),
1226
+ nn.Dropout(config.semantic_classifier_dropout),
1227
+ nn.Conv2d(features, config.num_labels, kernel_size=1),
1228
+ nn.Upsample(scale_factor=2, mode="bilinear", align_corners=True),
1229
+ )
1230
+
1231
+ def forward(self, hidden_states: List[torch.Tensor]) -> torch.Tensor:
1232
+ # use last features
1233
+ hidden_states = hidden_states[self.config.head_in_index]
1234
+
1235
+ logits = self.head(hidden_states)
1236
+
1237
+ return logits
1238
+
1239
+
1240
+ class DPTAuxiliaryHead(nn.Module):
1241
+ def __init__(self, config):
1242
+ super().__init__()
1243
+
1244
+ features = config.fusion_hidden_size
1245
+ self.head = nn.Sequential(
1246
+ nn.Conv2d(features, features, kernel_size=3, padding=1, bias=False),
1247
+ nn.BatchNorm2d(features),
1248
+ nn.ReLU(),
1249
+ nn.Dropout(0.1, False),
1250
+ nn.Conv2d(features, config.num_labels, kernel_size=1),
1251
+ )
1252
+
1253
+ def forward(self, hidden_states):
1254
+ logits = self.head(hidden_states)
1255
+
1256
+ return logits
1257
+
1258
+
1259
+ @add_start_docstrings(
1260
+ """
1261
+ DPT Model with a semantic segmentation head on top e.g. for ADE20k, CityScapes.
1262
+ """,
1263
+ DPT_START_DOCSTRING,
1264
+ )
1265
+ class DPTForSemanticSegmentation(DPTPreTrainedModel):
1266
+ def __init__(self, config):
1267
+ super().__init__(config)
1268
+
1269
+ self.dpt = DPTModel(config, add_pooling_layer=False)
1270
+
1271
+ # Neck
1272
+ self.neck = DPTNeck(config)
1273
+
1274
+ # Segmentation head(s)
1275
+ self.head = DPTSemanticSegmentationHead(config)
1276
+ self.auxiliary_head = DPTAuxiliaryHead(config) if config.use_auxiliary_head else None
1277
+
1278
+ # Initialize weights and apply final processing
1279
+ self.post_init()
1280
+
1281
+ @add_start_docstrings_to_model_forward(DPT_INPUTS_DOCSTRING)
1282
+ @replace_return_docstrings(output_type=SemanticSegmenterOutput, config_class=_CONFIG_FOR_DOC)
1283
+ def forward(
1284
+ self,
1285
+ pixel_values: Optional[torch.FloatTensor] = None,
1286
+ head_mask: Optional[torch.FloatTensor] = None,
1287
+ labels: Optional[torch.LongTensor] = None,
1288
+ output_attentions: Optional[bool] = None,
1289
+ output_hidden_states: Optional[bool] = None,
1290
+ return_dict: Optional[bool] = None,
1291
+ ) -> Union[Tuple[torch.Tensor], SemanticSegmenterOutput]:
1292
+ r"""
1293
+ labels (`torch.LongTensor` of shape `(batch_size, height, width)`, *optional*):
1294
+ Ground truth semantic segmentation maps for computing the loss. Indices should be in `[0, ...,
1295
+ config.num_labels - 1]`. If `config.num_labels > 1`, a classification loss is computed (Cross-Entropy).
1296
+
1297
+ Returns:
1298
+
1299
+ Examples:
1300
+ ```python
1301
+ >>> from transformers import AutoImageProcessor, DPTForSemanticSegmentation
1302
+ >>> from PIL import Image
1303
+ >>> import requests
1304
+
1305
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1306
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1307
+
1308
+ >>> image_processor = AutoImageProcessor.from_pretrained("Intel/dpt-large-ade")
1309
+ >>> model = DPTForSemanticSegmentation.from_pretrained("Intel/dpt-large-ade")
1310
+
1311
+ >>> inputs = image_processor(images=image, return_tensors="pt")
1312
+
1313
+ >>> outputs = model(**inputs)
1314
+ >>> logits = outputs.logits
1315
+ ```"""
1316
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1317
+ output_hidden_states = (
1318
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1319
+ )
1320
+
1321
+ outputs = self.dpt(
1322
+ pixel_values,
1323
+ head_mask=head_mask,
1324
+ output_attentions=output_attentions,
1325
+ output_hidden_states=True, # we need the intermediate hidden states
1326
+ return_dict=return_dict,
1327
+ )
1328
+
1329
+ hidden_states = outputs.hidden_states if return_dict else outputs[1]
1330
+
1331
+ # only keep certain features based on config.backbone_out_indices
1332
+ # note that the hidden_states also include the initial embeddings
1333
+ if not self.config.is_hybrid:
1334
+ hidden_states = [
1335
+ feature for idx, feature in enumerate(hidden_states[1:]) if idx in self.config.backbone_out_indices
1336
+ ]
1337
+ else:
1338
+ backbone_hidden_states = outputs.intermediate_activations if return_dict else list(outputs[-1])
1339
+ backbone_hidden_states.extend(
1340
+ feature for idx, feature in enumerate(hidden_states[1:]) if idx in self.config.backbone_out_indices[2:]
1341
+ )
1342
+
1343
+ hidden_states = backbone_hidden_states
1344
+
1345
+ hidden_states = self.neck(hidden_states=hidden_states)
1346
+
1347
+ logits = self.head(hidden_states)
1348
+
1349
+ auxiliary_logits = None
1350
+ if self.auxiliary_head is not None:
1351
+ auxiliary_logits = self.auxiliary_head(hidden_states[-1])
1352
+
1353
+ loss = None
1354
+ if labels is not None:
1355
+ if self.config.num_labels == 1:
1356
+ raise ValueError("The number of labels should be greater than one")
1357
+ else:
1358
+ # upsample logits to the images' original size
1359
+ upsampled_logits = nn.functional.interpolate(
1360
+ logits, size=labels.shape[-2:], mode="bilinear", align_corners=False
1361
+ )
1362
+ if auxiliary_logits is not None:
1363
+ upsampled_auxiliary_logits = nn.functional.interpolate(
1364
+ auxiliary_logits, size=labels.shape[-2:], mode="bilinear", align_corners=False
1365
+ )
1366
+ # compute weighted loss
1367
+ loss_fct = CrossEntropyLoss(ignore_index=self.config.semantic_loss_ignore_index)
1368
+ main_loss = loss_fct(upsampled_logits, labels)
1369
+ auxiliary_loss = loss_fct(upsampled_auxiliary_logits, labels)
1370
+ loss = main_loss + self.config.auxiliary_loss_weight * auxiliary_loss
1371
+
1372
+ if not return_dict:
1373
+ if output_hidden_states:
1374
+ output = (logits,) + outputs[1:]
1375
+ else:
1376
+ output = (logits,) + outputs[2:]
1377
+ return ((loss,) + output) if loss is not None else output
1378
+
1379
+ return SemanticSegmenterOutput(
1380
+ loss=loss,
1381
+ logits=logits,
1382
+ hidden_states=outputs.hidden_states if output_hidden_states else None,
1383
+ attentions=outputs.attentions,
1384
+ )
SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/__init__.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import TYPE_CHECKING
15
+
16
+ from ...utils import (
17
+ OptionalDependencyNotAvailable,
18
+ _LazyModule,
19
+ is_tf_available,
20
+ is_torch_available,
21
+ is_vision_available,
22
+ )
23
+
24
+
25
+ _import_structure = {
26
+ "configuration_efficientformer": [
27
+ "EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP",
28
+ "EfficientFormerConfig",
29
+ ]
30
+ }
31
+
32
+ try:
33
+ if not is_vision_available():
34
+ raise OptionalDependencyNotAvailable()
35
+ except OptionalDependencyNotAvailable:
36
+ pass
37
+ else:
38
+ _import_structure["image_processing_efficientformer"] = ["EfficientFormerImageProcessor"]
39
+
40
+ try:
41
+ if not is_torch_available():
42
+ raise OptionalDependencyNotAvailable()
43
+ except OptionalDependencyNotAvailable:
44
+ pass
45
+ else:
46
+ _import_structure["modeling_efficientformer"] = [
47
+ "EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
48
+ "EfficientFormerForImageClassification",
49
+ "EfficientFormerForImageClassificationWithTeacher",
50
+ "EfficientFormerModel",
51
+ "EfficientFormerPreTrainedModel",
52
+ ]
53
+
54
+ try:
55
+ if not is_tf_available():
56
+ raise OptionalDependencyNotAvailable()
57
+ except OptionalDependencyNotAvailable:
58
+ pass
59
+ else:
60
+ _import_structure["modeling_tf_efficientformer"] = [
61
+ "TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST",
62
+ "TFEfficientFormerForImageClassification",
63
+ "TFEfficientFormerForImageClassificationWithTeacher",
64
+ "TFEfficientFormerModel",
65
+ "TFEfficientFormerPreTrainedModel",
66
+ ]
67
+
68
+ if TYPE_CHECKING:
69
+ from .configuration_efficientformer import EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, EfficientFormerConfig
70
+
71
+ try:
72
+ if not is_vision_available():
73
+ raise OptionalDependencyNotAvailable()
74
+ except OptionalDependencyNotAvailable:
75
+ pass
76
+ else:
77
+ from .image_processing_efficientformer import EfficientFormerImageProcessor
78
+
79
+ try:
80
+ if not is_torch_available():
81
+ raise OptionalDependencyNotAvailable()
82
+ except OptionalDependencyNotAvailable:
83
+ pass
84
+ else:
85
+ from .modeling_efficientformer import (
86
+ EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
87
+ EfficientFormerForImageClassification,
88
+ EfficientFormerForImageClassificationWithTeacher,
89
+ EfficientFormerModel,
90
+ EfficientFormerPreTrainedModel,
91
+ )
92
+ try:
93
+ if not is_tf_available():
94
+ raise OptionalDependencyNotAvailable()
95
+ except OptionalDependencyNotAvailable:
96
+ pass
97
+ else:
98
+ from .modeling_tf_efficientformer import (
99
+ TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
100
+ TFEfficientFormerForImageClassification,
101
+ TFEfficientFormerForImageClassificationWithTeacher,
102
+ TFEfficientFormerModel,
103
+ TFEfficientFormerPreTrainedModel,
104
+ )
105
+
106
+ else:
107
+ import sys
108
+
109
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (1.76 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/__pycache__/configuration_efficientformer.cpython-310.pyc ADDED
Binary file (7.05 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/__pycache__/convert_efficientformer_original_pytorch_checkpoint_to_pytorch.cpython-310.pyc ADDED
Binary file (6.17 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/__pycache__/image_processing_efficientformer.cpython-310.pyc ADDED
Binary file (12.8 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/__pycache__/modeling_efficientformer.cpython-310.pyc ADDED
Binary file (27.9 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/__pycache__/modeling_tf_efficientformer.cpython-310.pyc ADDED
Binary file (37.3 kB). View file
 
SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/configuration_efficientformer.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 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
+ """ EfficientFormer model configuration"""
16
+
17
+ from typing import List
18
+
19
+ from ...configuration_utils import PretrainedConfig
20
+ from ...utils import logging
21
+
22
+
23
+ logger = logging.get_logger(__name__)
24
+
25
+ EFFICIENTFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP = {
26
+ "snap-research/efficientformer-l1-300": (
27
+ "https://huggingface.co/snap-research/efficientformer-l1-300/resolve/main/config.json"
28
+ ),
29
+ }
30
+
31
+
32
+ class EfficientFormerConfig(PretrainedConfig):
33
+ r"""
34
+ This is the configuration class to store the configuration of an [`EfficientFormerModel`]. It is used to
35
+ instantiate an EfficientFormer model according to the specified arguments, defining the model architecture.
36
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the EfficientFormer
37
+ [snap-research/efficientformer-l1](https://huggingface.co/snap-research/efficientformer-l1) architecture.
38
+
39
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
40
+ documentation from [`PretrainedConfig`] for more information.
41
+
42
+ Args:
43
+ depths (`List(int)`, *optional*, defaults to `[3, 2, 6, 4]`)
44
+ Depth of each stage.
45
+ hidden_sizes (`List(int)`, *optional*, defaults to `[48, 96, 224, 448]`)
46
+ Dimensionality of each stage.
47
+ downsamples (`List(bool)`, *optional*, defaults to `[True, True, True, True]`)
48
+ Whether or not to downsample inputs between two stages.
49
+ dim (`int`, *optional*, defaults to 448):
50
+ Number of channels in Meta3D layers
51
+ key_dim (`int`, *optional*, defaults to 32):
52
+ The size of the key in meta3D block.
53
+ attention_ratio (`int`, *optional*, defaults to 4):
54
+ Ratio of the dimension of the query and value to the dimension of the key in MSHA block
55
+ resolution (`int`, *optional*, defaults to 7)
56
+ Size of each patch
57
+ num_hidden_layers (`int`, *optional*, defaults to 5):
58
+ Number of hidden layers in the Transformer encoder.
59
+ num_attention_heads (`int`, *optional*, defaults to 8):
60
+ Number of attention heads for each attention layer in the 3D MetaBlock.
61
+ mlp_expansion_ratio (`int`, *optional*, defaults to 4):
62
+ Ratio of size of the hidden dimensionality of an MLP to the dimensionality of its input.
63
+ hidden_dropout_prob (`float`, *optional*, defaults to 0.1):
64
+ The dropout probability for all fully connected layers in the embeddings and encoder.
65
+ patch_size (`int`, *optional*, defaults to 16):
66
+ The size (resolution) of each patch.
67
+ num_channels (`int`, *optional*, defaults to 3):
68
+ The number of input channels.
69
+ pool_size (`int`, *optional*, defaults to 3):
70
+ Kernel size of pooling layers.
71
+ downsample_patch_size (`int`, *optional*, defaults to 3):
72
+ The size of patches in downsampling layers.
73
+ downsample_stride (`int`, *optional*, defaults to 2):
74
+ The stride of convolution kernels in downsampling layers.
75
+ downsample_pad (`int`, *optional*, defaults to 1):
76
+ Padding in downsampling layers.
77
+ drop_path_rate (`int`, *optional*, defaults to 0):
78
+ Rate at which to increase dropout probability in DropPath.
79
+ num_meta3d_blocks (`int`, *optional*, defaults to 1):
80
+ The number of 3D MetaBlocks in the last stage.
81
+ distillation (`bool`, *optional*, defaults to `True`):
82
+ Whether to add a distillation head.
83
+ use_layer_scale (`bool`, *optional*, defaults to `True`):
84
+ Whether to scale outputs from token mixers.
85
+ layer_scale_init_value (`float`, *optional*, defaults to 1e-5):
86
+ Factor by which outputs from token mixers are scaled.
87
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
88
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
89
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
90
+ initializer_range (`float`, *optional*, defaults to 0.02):
91
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
92
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
93
+ The epsilon used by the layer normalization layers.
94
+ image_size (`int`, *optional*, defaults to `224`):
95
+ The size (resolution) of each image.
96
+
97
+ Example:
98
+
99
+ ```python
100
+ >>> from transformers import EfficientFormerConfig, EfficientFormerModel
101
+
102
+ >>> # Initializing a EfficientFormer efficientformer-l1 style configuration
103
+ >>> configuration = EfficientFormerConfig()
104
+
105
+ >>> # Initializing a EfficientFormerModel (with random weights) from the efficientformer-l3 style configuration
106
+ >>> model = EfficientFormerModel(configuration)
107
+
108
+ >>> # Accessing the model configuration
109
+ >>> configuration = model.config
110
+ ```"""
111
+
112
+ model_type = "efficientformer"
113
+
114
+ def __init__(
115
+ self,
116
+ depths: List[int] = [3, 2, 6, 4],
117
+ hidden_sizes: List[int] = [48, 96, 224, 448],
118
+ downsamples: List[bool] = [True, True, True, True],
119
+ dim: int = 448,
120
+ key_dim: int = 32,
121
+ attention_ratio: int = 4,
122
+ resolution: int = 7,
123
+ num_hidden_layers: int = 5,
124
+ num_attention_heads: int = 8,
125
+ mlp_expansion_ratio: int = 4,
126
+ hidden_dropout_prob: float = 0.0,
127
+ patch_size: int = 16,
128
+ num_channels: int = 3,
129
+ pool_size: int = 3,
130
+ downsample_patch_size: int = 3,
131
+ downsample_stride: int = 2,
132
+ downsample_pad: int = 1,
133
+ drop_path_rate: float = 0.0,
134
+ num_meta3d_blocks: int = 1,
135
+ distillation: bool = True,
136
+ use_layer_scale: bool = True,
137
+ layer_scale_init_value: float = 1e-5,
138
+ hidden_act: str = "gelu",
139
+ initializer_range: float = 0.02,
140
+ layer_norm_eps: float = 1e-12,
141
+ image_size: int = 224,
142
+ batch_norm_eps: float = 1e-05,
143
+ **kwargs,
144
+ ) -> None:
145
+ super().__init__(**kwargs)
146
+
147
+ self.hidden_act = hidden_act
148
+ self.hidden_dropout_prob = hidden_dropout_prob
149
+ self.hidden_sizes = hidden_sizes
150
+ self.num_hidden_layers = num_hidden_layers
151
+ self.num_attention_heads = num_attention_heads
152
+ self.initializer_range = initializer_range
153
+ self.layer_norm_eps = layer_norm_eps
154
+ self.patch_size = patch_size
155
+ self.num_channels = num_channels
156
+ self.depths = depths
157
+ self.mlp_expansion_ratio = mlp_expansion_ratio
158
+ self.downsamples = downsamples
159
+ self.dim = dim
160
+ self.key_dim = key_dim
161
+ self.attention_ratio = attention_ratio
162
+ self.resolution = resolution
163
+ self.pool_size = pool_size
164
+ self.downsample_patch_size = downsample_patch_size
165
+ self.downsample_stride = downsample_stride
166
+ self.downsample_pad = downsample_pad
167
+ self.drop_path_rate = drop_path_rate
168
+ self.num_meta3d_blocks = num_meta3d_blocks
169
+ self.distillation = distillation
170
+ self.use_layer_scale = use_layer_scale
171
+ self.layer_scale_init_value = layer_scale_init_value
172
+ self.image_size = image_size
173
+ self.batch_norm_eps = batch_norm_eps
SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/convert_efficientformer_original_pytorch_checkpoint_to_pytorch.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The HuggingFace Inc. team.
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
+
16
+ """Convert EfficientFormer checkpoints from the original repository.
17
+
18
+ URL: https://github.com/snap-research/EfficientFormer
19
+ """
20
+
21
+ import argparse
22
+ import re
23
+ from pathlib import Path
24
+
25
+ import requests
26
+ import torch
27
+ from PIL import Image
28
+ from torchvision.transforms import CenterCrop, Compose, Normalize, Resize, ToTensor
29
+
30
+ from transformers import (
31
+ EfficientFormerConfig,
32
+ EfficientFormerForImageClassificationWithTeacher,
33
+ EfficientFormerImageProcessor,
34
+ )
35
+ from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, PILImageResampling
36
+
37
+
38
+ def rename_key(old_name, num_meta4D_last_stage):
39
+ new_name = old_name
40
+
41
+ if "patch_embed" in old_name:
42
+ _, layer, param = old_name.split(".")
43
+
44
+ if layer == "0":
45
+ new_name = old_name.replace("0", "convolution1")
46
+ elif layer == "1":
47
+ new_name = old_name.replace("1", "batchnorm_before")
48
+ elif layer == "3":
49
+ new_name = old_name.replace("3", "convolution2")
50
+ else:
51
+ new_name = old_name.replace("4", "batchnorm_after")
52
+
53
+ if "network" in old_name and re.search(r"\d\.\d", old_name):
54
+ two_digit_num = r"\b\d{2}\b"
55
+ if bool(re.search(two_digit_num, old_name)):
56
+ match = re.search(r"\d\.\d\d.", old_name).group()
57
+ else:
58
+ match = re.search(r"\d\.\d.", old_name).group()
59
+ if int(match[0]) < 6:
60
+ trimmed_name = old_name.replace(match, "")
61
+ trimmed_name = trimmed_name.replace("network", match[0] + ".meta4D_layers.blocks." + match[2:-1])
62
+ new_name = "intermediate_stages." + trimmed_name
63
+ else:
64
+ trimmed_name = old_name.replace(match, "")
65
+ if int(match[2]) < num_meta4D_last_stage:
66
+ trimmed_name = trimmed_name.replace("network", "meta4D_layers.blocks." + match[2])
67
+ else:
68
+ layer_index = str(int(match[2]) - num_meta4D_last_stage)
69
+ trimmed_name = trimmed_name.replace("network", "meta3D_layers.blocks." + layer_index)
70
+ if "norm1" in old_name:
71
+ trimmed_name = trimmed_name.replace("norm1", "layernorm1")
72
+ elif "norm2" in old_name:
73
+ trimmed_name = trimmed_name.replace("norm2", "layernorm2")
74
+ elif "fc1" in old_name:
75
+ trimmed_name = trimmed_name.replace("fc1", "linear_in")
76
+ elif "fc2" in old_name:
77
+ trimmed_name = trimmed_name.replace("fc2", "linear_out")
78
+
79
+ new_name = "last_stage." + trimmed_name
80
+
81
+ elif "network" in old_name and re.search(r".\d.", old_name):
82
+ new_name = old_name.replace("network", "intermediate_stages")
83
+
84
+ if "fc" in new_name:
85
+ new_name = new_name.replace("fc", "convolution")
86
+ elif ("norm1" in new_name) and ("layernorm1" not in new_name):
87
+ new_name = new_name.replace("norm1", "batchnorm_before")
88
+ elif ("norm2" in new_name) and ("layernorm2" not in new_name):
89
+ new_name = new_name.replace("norm2", "batchnorm_after")
90
+ if "proj" in new_name:
91
+ new_name = new_name.replace("proj", "projection")
92
+ if "dist_head" in new_name:
93
+ new_name = new_name.replace("dist_head", "distillation_classifier")
94
+ elif "head" in new_name:
95
+ new_name = new_name.replace("head", "classifier")
96
+ elif "patch_embed" in new_name:
97
+ new_name = "efficientformer." + new_name
98
+ elif new_name == "norm.weight" or new_name == "norm.bias":
99
+ new_name = new_name.replace("norm", "layernorm")
100
+ new_name = "efficientformer." + new_name
101
+ else:
102
+ new_name = "efficientformer.encoder." + new_name
103
+
104
+ return new_name
105
+
106
+
107
+ def convert_torch_checkpoint(checkpoint, num_meta4D_last_stage):
108
+ for key in checkpoint.copy().keys():
109
+ val = checkpoint.pop(key)
110
+ checkpoint[rename_key(key, num_meta4D_last_stage)] = val
111
+
112
+ return checkpoint
113
+
114
+
115
+ # We will verify our results on a COCO image
116
+ def prepare_img():
117
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
118
+ image = Image.open(requests.get(url, stream=True).raw)
119
+
120
+ return image
121
+
122
+
123
+ def convert_efficientformer_checkpoint(
124
+ checkpoint_path: Path, efficientformer_config_file: Path, pytorch_dump_path: Path, push_to_hub: bool
125
+ ):
126
+ orig_state_dict = torch.load(checkpoint_path, map_location="cpu")["model"]
127
+ config = EfficientFormerConfig.from_json_file(efficientformer_config_file)
128
+ model = EfficientFormerForImageClassificationWithTeacher(config)
129
+ model_name = "_".join(checkpoint_path.split("/")[-1].split(".")[0].split("_")[:-1])
130
+
131
+ num_meta4D_last_stage = config.depths[-1] - config.num_meta3d_blocks + 1
132
+ new_state_dict = convert_torch_checkpoint(orig_state_dict, num_meta4D_last_stage)
133
+
134
+ model.load_state_dict(new_state_dict)
135
+ model.eval()
136
+
137
+ pillow_resamplings = {
138
+ "bilinear": PILImageResampling.BILINEAR,
139
+ "bicubic": PILImageResampling.BICUBIC,
140
+ "nearest": PILImageResampling.NEAREST,
141
+ }
142
+
143
+ # prepare image
144
+ image = prepare_img()
145
+ image_size = 256
146
+ crop_size = 224
147
+ processor = EfficientFormerImageProcessor(
148
+ size={"shortest_edge": image_size},
149
+ crop_size={"height": crop_size, "width": crop_size},
150
+ resample=pillow_resamplings["bicubic"],
151
+ )
152
+ pixel_values = processor(images=image, return_tensors="pt").pixel_values
153
+
154
+ # original processing pipeline
155
+ image_transforms = Compose(
156
+ [
157
+ Resize(image_size, interpolation=pillow_resamplings["bicubic"]),
158
+ CenterCrop(crop_size),
159
+ ToTensor(),
160
+ Normalize(IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD),
161
+ ]
162
+ )
163
+ original_pixel_values = image_transforms(image).unsqueeze(0)
164
+
165
+ assert torch.allclose(original_pixel_values, pixel_values)
166
+
167
+ outputs = model(pixel_values)
168
+ logits = outputs.logits
169
+
170
+ expected_shape = (1, 1000)
171
+
172
+ if "l1" in model_name:
173
+ expected_logits = torch.Tensor(
174
+ [-0.1312, 0.4353, -1.0499, -0.5124, 0.4183, -0.6793, -1.3777, -0.0893, -0.7358, -2.4328]
175
+ )
176
+ assert torch.allclose(logits[0, :10], expected_logits, atol=1e-3)
177
+ assert logits.shape == expected_shape
178
+ elif "l3" in model_name:
179
+ expected_logits = torch.Tensor(
180
+ [-1.3150, -1.5456, -1.2556, -0.8496, -0.7127, -0.7897, -0.9728, -0.3052, 0.3751, -0.3127]
181
+ )
182
+ assert torch.allclose(logits[0, :10], expected_logits, atol=1e-3)
183
+ assert logits.shape == expected_shape
184
+ elif "l7" in model_name:
185
+ expected_logits = torch.Tensor(
186
+ [-1.0283, -1.4131, -0.5644, -1.3115, -0.5785, -1.2049, -0.7528, 0.1992, -0.3822, -0.0878]
187
+ )
188
+ assert logits.shape == expected_shape
189
+ else:
190
+ raise ValueError(
191
+ f"Unknown model checkpoint: {checkpoint_path}. Supported version of efficientformer are l1, l3 and l7"
192
+ )
193
+
194
+ # Save Checkpoints
195
+ Path(pytorch_dump_path).mkdir(exist_ok=True)
196
+ model.save_pretrained(pytorch_dump_path)
197
+ print(f"Checkpoint successfuly converted. Model saved at {pytorch_dump_path}")
198
+ processor.save_pretrained(pytorch_dump_path)
199
+ print(f"Processor successfuly saved at {pytorch_dump_path}")
200
+
201
+ if push_to_hub:
202
+ print("Pushing model to the hub...")
203
+
204
+ model.push_to_hub(
205
+ repo_id=f"Bearnardd/{pytorch_dump_path}",
206
+ commit_message="Add model",
207
+ use_temp_dir=True,
208
+ )
209
+ processor.push_to_hub(
210
+ repo_id=f"Bearnardd/{pytorch_dump_path}",
211
+ commit_message="Add image processor",
212
+ use_temp_dir=True,
213
+ )
214
+
215
+
216
+ if __name__ == "__main__":
217
+ parser = argparse.ArgumentParser()
218
+ # Required parameters
219
+ parser.add_argument(
220
+ "--pytorch_model_path",
221
+ default=None,
222
+ type=str,
223
+ required=True,
224
+ help="Path to EfficientFormer pytorch checkpoint.",
225
+ )
226
+ parser.add_argument(
227
+ "--config_file",
228
+ default=None,
229
+ type=str,
230
+ required=True,
231
+ help="The json file for EfficientFormer model config.",
232
+ )
233
+ parser.add_argument(
234
+ "--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
235
+ )
236
+
237
+ parser.add_argument("--push_to_hub", action="store_true", help="Push model and image processor to the hub")
238
+ parser.add_argument(
239
+ "--no-push_to_hub",
240
+ dest="push_to_hub",
241
+ action="store_false",
242
+ help="Do not push model and image processor to the hub",
243
+ )
244
+ parser.set_defaults(push_to_hub=True)
245
+
246
+ args = parser.parse_args()
247
+ convert_efficientformer_checkpoint(
248
+ checkpoint_path=args.pytorch_model_path,
249
+ efficientformer_config_file=args.config_file,
250
+ pytorch_dump_path=args.pytorch_dump_path,
251
+ push_to_hub=args.push_to_hub,
252
+ )
SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/image_processing_efficientformer.py ADDED
@@ -0,0 +1,299 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 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
+ """Image processor class for EfficientFormer."""
16
+
17
+ from typing import Dict, List, Optional, Union
18
+
19
+ import numpy as np
20
+
21
+ from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
22
+ from ...image_transforms import (
23
+ get_resize_output_image_size,
24
+ resize,
25
+ to_channel_dimension_format,
26
+ )
27
+ from ...image_utils import (
28
+ IMAGENET_DEFAULT_MEAN,
29
+ IMAGENET_DEFAULT_STD,
30
+ ChannelDimension,
31
+ ImageInput,
32
+ PILImageResampling,
33
+ infer_channel_dimension_format,
34
+ is_batched,
35
+ is_scaled_image,
36
+ to_numpy_array,
37
+ valid_images,
38
+ )
39
+ from ...utils import TensorType, logging
40
+
41
+
42
+ logger = logging.get_logger(__name__)
43
+
44
+
45
+ class EfficientFormerImageProcessor(BaseImageProcessor):
46
+ r"""
47
+ Constructs a EfficientFormer image processor.
48
+
49
+ Args:
50
+ do_resize (`bool`, *optional*, defaults to `True`):
51
+ Whether to resize the image's (height, width) dimensions to the specified `(size["height"],
52
+ size["width"])`. Can be overridden by the `do_resize` parameter in the `preprocess` method.
53
+ size (`dict`, *optional*, defaults to `{"height": 224, "width": 224}`):
54
+ Size of the output image after resizing. Can be overridden by the `size` parameter in the `preprocess`
55
+ method.
56
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
57
+ Resampling filter to use if resizing the image. Can be overridden by the `resample` parameter in the
58
+ `preprocess` method.
59
+ do_center_crop (`bool`, *optional*, defaults to `True`):
60
+ Whether to center crop the image to the specified `crop_size`. Can be overridden by `do_center_crop` in the
61
+ `preprocess` method.
62
+ crop_size (`Dict[str, int]` *optional*, defaults to 224):
63
+ Size of the output image after applying `center_crop`. Can be overridden by `crop_size` in the `preprocess`
64
+ method.
65
+ do_rescale (`bool`, *optional*, defaults to `True`):
66
+ Whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the `do_rescale`
67
+ parameter in the `preprocess` method.
68
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
69
+ Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
70
+ `preprocess` method.
71
+ do_normalize:
72
+ Whether to normalize the image. Can be overridden by the `do_normalize` parameter in the `preprocess`
73
+ method.
74
+ image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`):
75
+ Mean to use if normalizing the image. This is a float or list of floats the length of the number of
76
+ channels in the image. Can be overridden by the `image_mean` parameter in the `preprocess` method.
77
+ image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`):
78
+ Standard deviation to use if normalizing the image. This is a float or list of floats the length of the
79
+ number of channels in the image. Can be overridden by the `image_std` parameter in the `preprocess` method.
80
+ """
81
+
82
+ model_input_names = ["pixel_values"]
83
+
84
+ def __init__(
85
+ self,
86
+ do_resize: bool = True,
87
+ size: Optional[Dict[str, int]] = None,
88
+ resample: PILImageResampling = PILImageResampling.BICUBIC,
89
+ do_center_crop: bool = True,
90
+ do_rescale: bool = True,
91
+ rescale_factor: Union[int, float] = 1 / 255,
92
+ crop_size: Dict[str, int] = None,
93
+ do_normalize: bool = True,
94
+ image_mean: Optional[Union[float, List[float]]] = None,
95
+ image_std: Optional[Union[float, List[float]]] = None,
96
+ **kwargs,
97
+ ) -> None:
98
+ super().__init__(**kwargs)
99
+ size = size if size is not None else {"height": 224, "width": 224}
100
+ size = get_size_dict(size)
101
+ crop_size = crop_size if crop_size is not None else {"height": 224, "width": 224}
102
+ crop_size = get_size_dict(crop_size, default_to_square=True, param_name="crop_size")
103
+
104
+ self.do_resize = do_resize
105
+ self.do_rescale = do_rescale
106
+ self.do_normalize = do_normalize
107
+ self.do_center_crop = do_center_crop
108
+ self.crop_size = crop_size
109
+ self.size = size
110
+ self.resample = resample
111
+ self.rescale_factor = rescale_factor
112
+ self.image_mean = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
113
+ self.image_std = image_std if image_std is not None else IMAGENET_DEFAULT_STD
114
+
115
+ def resize(
116
+ self,
117
+ image: np.ndarray,
118
+ size: Dict[str, int],
119
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
120
+ data_format: Optional[Union[str, ChannelDimension]] = None,
121
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
122
+ **kwargs,
123
+ ) -> np.ndarray:
124
+ """
125
+ Resize an image to `(size["height"], size["width"])`.
126
+
127
+ Args:
128
+ image (`np.ndarray`):
129
+ Image to resize.
130
+ size (`Dict[str, int]`):
131
+ Dictionary in the format `{"height": int, "width": int}` specifying the size of the output image.
132
+ resample:
133
+ `PILImageResampling` filter to use when resizing the image e.g. `PILImageResampling.BILINEAR`.
134
+ data_format (`ChannelDimension` or `str`, *optional*):
135
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
136
+ image is used. Can be one of:
137
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
138
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
139
+ input_data_format (`ChannelDimension` or `str`, *optional*):
140
+ The channel dimension format of the input image. If not provided, it will be inferred.
141
+
142
+ Returns:
143
+ `np.ndarray`: The resized image.
144
+ """
145
+ size = get_size_dict(size)
146
+
147
+ if "shortest_edge" in size:
148
+ size = get_resize_output_image_size(
149
+ image, size=size["shortest_edge"], default_to_square=False, input_data_format=input_data_format
150
+ )
151
+ # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"])
152
+ elif "height" in size and "width" in size:
153
+ size = (size["height"], size["width"])
154
+ else:
155
+ raise ValueError(f"Size must contain 'height' and 'width' keys or 'shortest_edge' key. Got {size.keys()}")
156
+ return resize(
157
+ image, size=size, resample=resample, data_format=data_format, input_data_format=input_data_format, **kwargs
158
+ )
159
+
160
+ def preprocess(
161
+ self,
162
+ images: ImageInput,
163
+ do_resize: Optional[bool] = None,
164
+ size: Dict[str, int] = None,
165
+ resample: PILImageResampling = None,
166
+ do_center_crop: bool = None,
167
+ crop_size: int = None,
168
+ do_rescale: Optional[bool] = None,
169
+ rescale_factor: Optional[float] = None,
170
+ do_normalize: Optional[bool] = None,
171
+ image_mean: Optional[Union[float, List[float]]] = None,
172
+ image_std: Optional[Union[float, List[float]]] = None,
173
+ return_tensors: Optional[Union[str, TensorType]] = None,
174
+ data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,
175
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
176
+ **kwargs,
177
+ ) -> BatchFeature:
178
+ """
179
+ Preprocess an image or batch of images.
180
+
181
+ Args:
182
+ images (`ImageInput`):
183
+ Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If
184
+ passing in images with pixel values between 0 and 1, set `do_rescale=False`.
185
+ do_resize (`bool`, *optional*, defaults to `self.do_resize`):
186
+ Whether to resize the image.
187
+ size (`Dict[str, int]`, *optional*, defaults to `self.size`):
188
+ Dictionary in the format `{"height": h, "width": w}` specifying the size of the output image after
189
+ resizing.
190
+ resample (`PILImageResampling` filter, *optional*, defaults to `self.resample`):
191
+ `PILImageResampling` filter to use if resizing the image e.g. `PILImageResampling.BILINEAR`. Only has
192
+ an effect if `do_resize` is set to `True`.
193
+ do_center_crop (`bool`, *optional*, defaults to `self.do_center_crop`):
194
+ Whether to center crop the image.
195
+ do_rescale (`bool`, *optional*, defaults to `self.do_rescale`):
196
+ Whether to rescale the image values between [0 - 1].
197
+ rescale_factor (`float`, *optional*, defaults to `self.rescale_factor`):
198
+ Rescale factor to rescale the image by if `do_rescale` is set to `True`.
199
+ crop_size (`Dict[str, int]`, *optional*, defaults to `self.crop_size`):
200
+ Size of the center crop. Only has an effect if `do_center_crop` is set to `True`.
201
+ do_normalize (`bool`, *optional*, defaults to `self.do_normalize`):
202
+ Whether to normalize the image.
203
+ image_mean (`float` or `List[float]`, *optional*, defaults to `self.image_mean`):
204
+ Image mean to use if `do_normalize` is set to `True`.
205
+ image_std (`float` or `List[float]`, *optional*, defaults to `self.image_std`):
206
+ Image standard deviation to use if `do_normalize` is set to `True`.
207
+ return_tensors (`str` or `TensorType`, *optional*):
208
+ The type of tensors to return. Can be one of:
209
+ - Unset: Return a list of `np.ndarray`.
210
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
211
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
212
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
213
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
214
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
215
+ The channel dimension format for the output image. Can be one of:
216
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
217
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
218
+ - Unset: Use the channel dimension format of the input image.
219
+ input_data_format (`ChannelDimension` or `str`, *optional*):
220
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
221
+ from the input image. Can be one of:
222
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
223
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
224
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
225
+ """
226
+ do_resize = do_resize if do_resize is not None else self.do_resize
227
+ do_rescale = do_rescale if do_rescale is not None else self.do_rescale
228
+ do_normalize = do_normalize if do_normalize is not None else self.do_normalize
229
+ do_center_crop = do_center_crop if do_center_crop is not None else self.do_center_crop
230
+ crop_size = crop_size if crop_size is not None else self.crop_size
231
+ crop_size = get_size_dict(crop_size, param_name="crop_size", default_to_square=True)
232
+ resample = resample if resample is not None else self.resample
233
+ rescale_factor = rescale_factor if rescale_factor is not None else self.rescale_factor
234
+ image_mean = image_mean if image_mean is not None else self.image_mean
235
+ image_std = image_std if image_std is not None else self.image_std
236
+
237
+ size = size if size is not None else self.size
238
+ size_dict = get_size_dict(size)
239
+
240
+ if not is_batched(images):
241
+ images = [images]
242
+
243
+ if not valid_images(images):
244
+ raise ValueError(
245
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
246
+ "torch.Tensor, tf.Tensor or jax.ndarray."
247
+ )
248
+
249
+ if do_resize and size is None:
250
+ raise ValueError("Size must be specified if do_resize is True.")
251
+
252
+ if do_center_crop and crop_size is None:
253
+ raise ValueError("Crop size must be specified if do_center_crop is True.")
254
+
255
+ if do_rescale and rescale_factor is None:
256
+ raise ValueError("Rescale factor must be specified if do_rescale is True.")
257
+
258
+ # All transformations expect numpy arrays.
259
+ images = [to_numpy_array(image) for image in images]
260
+
261
+ if is_scaled_image(images[0]) and do_rescale:
262
+ logger.warning_once(
263
+ "It looks like you are trying to rescale already rescaled images. If the input"
264
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
265
+ )
266
+
267
+ if input_data_format is None:
268
+ # We assume that all images have the same channel dimension format.
269
+ input_data_format = infer_channel_dimension_format(images[0])
270
+
271
+ if do_resize:
272
+ images = [
273
+ self.resize(image=image, size=size_dict, resample=resample, input_data_format=input_data_format)
274
+ for image in images
275
+ ]
276
+
277
+ if do_center_crop:
278
+ images = [
279
+ self.center_crop(image=image, size=crop_size, input_data_format=input_data_format) for image in images
280
+ ]
281
+
282
+ if do_rescale:
283
+ images = [
284
+ self.rescale(image=image, scale=rescale_factor, input_data_format=input_data_format)
285
+ for image in images
286
+ ]
287
+
288
+ if do_normalize:
289
+ images = [
290
+ self.normalize(image=image, mean=image_mean, std=image_std, input_data_format=input_data_format)
291
+ for image in images
292
+ ]
293
+
294
+ images = [
295
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format) for image in images
296
+ ]
297
+
298
+ data = {"pixel_values": images}
299
+ return BatchFeature(data=data, tensor_type=return_tensors)
SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/modeling_efficientformer.py ADDED
@@ -0,0 +1,806 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Snapchat Research 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
+ """ PyTorch EfficientFormer model."""
16
+
17
+ import itertools
18
+ from dataclasses import dataclass
19
+ from typing import Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
25
+
26
+ from ...activations import ACT2FN
27
+ from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling, ImageClassifierOutput
28
+ from ...modeling_utils import PreTrainedModel
29
+ from ...utils import (
30
+ ModelOutput,
31
+ add_code_sample_docstrings,
32
+ add_start_docstrings,
33
+ add_start_docstrings_to_model_forward,
34
+ logging,
35
+ )
36
+ from .configuration_efficientformer import EfficientFormerConfig
37
+
38
+
39
+ logger = logging.get_logger(__name__)
40
+
41
+ # General docstring
42
+ _CONFIG_FOR_DOC = "EfficientFormerConfig"
43
+
44
+ # Base docstring
45
+ _CHECKPOINT_FOR_DOC = "snap-research/efficientformer-l1-300"
46
+ _EXPECTED_OUTPUT_SHAPE = [1, 49, 448]
47
+
48
+ # Image classification docstring
49
+ _IMAGE_CLASS_CHECKPOINT = "snap-research/efficientformer-l1-300"
50
+ _IMAGE_CLASS_EXPECTED_OUTPUT = "Egyptian cat"
51
+
52
+
53
+ EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST = [
54
+ "snap-research/efficientformer-l1-300",
55
+ # See all EfficientFormer models at https://huggingface.co/models?filter=efficientformer
56
+ ]
57
+
58
+
59
+ class EfficientFormerPatchEmbeddings(nn.Module):
60
+ """
61
+ This class performs downsampling between two stages. For the input tensor with the shape [batch_size, num_channels,
62
+ height, width] it produces output tensor with the shape [batch_size, num_channels, height/stride, width/stride]
63
+ """
64
+
65
+ def __init__(self, config: EfficientFormerConfig, num_channels: int, embed_dim: int, apply_norm: bool = True):
66
+ super().__init__()
67
+ self.num_channels = num_channels
68
+
69
+ self.projection = nn.Conv2d(
70
+ num_channels,
71
+ embed_dim,
72
+ kernel_size=config.downsample_patch_size,
73
+ stride=config.downsample_stride,
74
+ padding=config.downsample_pad,
75
+ )
76
+ self.norm = nn.BatchNorm2d(embed_dim, eps=config.batch_norm_eps) if apply_norm else nn.Identity()
77
+
78
+ def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
79
+ batch_size, num_channels, height, width = pixel_values.shape
80
+ if num_channels != self.num_channels:
81
+ raise ValueError(
82
+ "Make sure that the channel dimension of the pixel values match with the one set in the configuration."
83
+ )
84
+
85
+ embeddings = self.projection(pixel_values)
86
+ embeddings = self.norm(embeddings)
87
+
88
+ return embeddings
89
+
90
+
91
+ class EfficientFormerSelfAttention(nn.Module):
92
+ def __init__(self, dim: int, key_dim: int, num_heads: int, attention_ratio: int, resolution: int):
93
+ super().__init__()
94
+
95
+ self.num_heads = num_heads
96
+ self.key_dim = key_dim
97
+ self.attention_ratio = attention_ratio
98
+ self.scale = key_dim**-0.5
99
+ self.total_key_dim = key_dim * num_heads
100
+ self.expanded_key_dim = int(attention_ratio * key_dim)
101
+ self.total_expanded_key_dim = int(self.expanded_key_dim * num_heads)
102
+ hidden_size = self.total_expanded_key_dim + self.total_key_dim * 2
103
+ self.qkv = nn.Linear(dim, hidden_size)
104
+ self.projection = nn.Linear(self.total_expanded_key_dim, dim)
105
+ points = list(itertools.product(range(resolution), range(resolution)))
106
+ num_points = len(points)
107
+ attention_offsets = {}
108
+ idxs = []
109
+ for point_1 in points:
110
+ for point_2 in points:
111
+ offset = (abs(point_1[0] - point_2[0]), abs(point_1[1] - point_2[1]))
112
+ if offset not in attention_offsets:
113
+ attention_offsets[offset] = len(attention_offsets)
114
+ idxs.append(attention_offsets[offset])
115
+ self.attention_biases = torch.nn.Parameter(torch.zeros(num_heads, len(attention_offsets)))
116
+ self.register_buffer("attention_bias_idxs", torch.LongTensor(idxs).view(num_points, num_points))
117
+
118
+ @torch.no_grad()
119
+ def train(self, mode=True):
120
+ super().train(mode)
121
+ if mode and hasattr(self, "ab"):
122
+ del self.ab
123
+ else:
124
+ self.ab = self.attention_biases[:, self.attention_bias_idxs]
125
+
126
+ def forward(self, hidden_states: torch.Tensor, output_attentions: bool = False) -> Tuple[torch.Tensor]:
127
+ batch_size, sequence_length, num_channels = hidden_states.shape
128
+ qkv = self.qkv(hidden_states)
129
+ query_layer, key_layer, value_layer = qkv.reshape(batch_size, sequence_length, self.num_heads, -1).split(
130
+ [self.key_dim, self.key_dim, self.expanded_key_dim], dim=3
131
+ )
132
+ query_layer = query_layer.permute(0, 2, 1, 3)
133
+ key_layer = key_layer.permute(0, 2, 1, 3)
134
+ value_layer = value_layer.permute(0, 2, 1, 3)
135
+
136
+ # set `model.to(torch_device)` won't change `self.ab.device`, if there is no follow-up `train` or `eval` call.
137
+ # Let's do it manually here, so users won't have to do this everytime.
138
+ if not self.training:
139
+ self.ab = self.ab.to(self.attention_biases.device)
140
+ attention_probs = (torch.matmul(query_layer, key_layer.transpose(-2, -1))) * self.scale + (
141
+ self.attention_biases[:, self.attention_bias_idxs] if self.training else self.ab
142
+ )
143
+
144
+ attention_probs = attention_probs.softmax(dim=-1)
145
+
146
+ context_layer = torch.matmul(attention_probs, value_layer).transpose(1, 2)
147
+ context_layer = context_layer.reshape(batch_size, sequence_length, self.total_expanded_key_dim)
148
+ context_layer = self.projection(context_layer)
149
+
150
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
151
+
152
+ return outputs
153
+
154
+
155
+ class EfficientFormerConvStem(nn.Module):
156
+ def __init__(self, config: EfficientFormerConfig, out_channels: int):
157
+ super().__init__()
158
+
159
+ self.convolution1 = nn.Conv2d(config.num_channels, out_channels // 2, kernel_size=3, stride=2, padding=1)
160
+ self.batchnorm_before = nn.BatchNorm2d(out_channels // 2, eps=config.batch_norm_eps)
161
+
162
+ self.convolution2 = nn.Conv2d(out_channels // 2, out_channels, kernel_size=3, stride=2, padding=1)
163
+ self.batchnorm_after = nn.BatchNorm2d(out_channels, eps=config.batch_norm_eps)
164
+
165
+ self.activation = nn.ReLU()
166
+
167
+ def forward(self, pixel_values: torch.Tensor) -> torch.Tensor:
168
+ features = self.batchnorm_before(self.convolution1(pixel_values))
169
+ features = self.activation(features)
170
+ features = self.batchnorm_after(self.convolution2(features))
171
+ features = self.activation(features)
172
+
173
+ return features
174
+
175
+
176
+ class EfficientFormerPooling(nn.Module):
177
+ def __init__(self, pool_size: int):
178
+ super().__init__()
179
+ self.pool = nn.AvgPool2d(pool_size, stride=1, padding=pool_size // 2, count_include_pad=False)
180
+
181
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
182
+ output = self.pool(hidden_states) - hidden_states
183
+ return output
184
+
185
+
186
+ class EfficientFormerDenseMlp(nn.Module):
187
+ def __init__(
188
+ self,
189
+ config: EfficientFormerConfig,
190
+ in_features: int,
191
+ hidden_features: Optional[int] = None,
192
+ out_features: Optional[int] = None,
193
+ ):
194
+ super().__init__()
195
+ out_features = out_features or in_features
196
+ hidden_features = hidden_features or in_features
197
+
198
+ self.linear_in = nn.Linear(in_features, hidden_features)
199
+ self.activation = ACT2FN[config.hidden_act]
200
+ self.dropout = nn.Dropout(config.hidden_dropout_prob)
201
+ self.linear_out = nn.Linear(hidden_features, out_features)
202
+
203
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
204
+ hidden_states = self.linear_in(hidden_states)
205
+ hidden_states = self.activation(hidden_states)
206
+ hidden_states = self.dropout(hidden_states)
207
+ hidden_states = self.linear_out(hidden_states)
208
+ hidden_states = self.dropout(hidden_states)
209
+
210
+ return hidden_states
211
+
212
+
213
+ class EfficientFormerConvMlp(nn.Module):
214
+ def __init__(
215
+ self,
216
+ config: EfficientFormerConfig,
217
+ in_features: int,
218
+ hidden_features: Optional[int] = None,
219
+ out_features: Optional[int] = None,
220
+ drop: float = 0.0,
221
+ ):
222
+ super().__init__()
223
+ out_features = out_features or in_features
224
+ hidden_features = hidden_features or in_features
225
+
226
+ self.convolution1 = nn.Conv2d(in_features, hidden_features, 1)
227
+ self.activation = ACT2FN[config.hidden_act]
228
+ self.convolution2 = nn.Conv2d(hidden_features, out_features, 1)
229
+ self.dropout = nn.Dropout(drop)
230
+
231
+ self.batchnorm_before = nn.BatchNorm2d(hidden_features, eps=config.batch_norm_eps)
232
+ self.batchnorm_after = nn.BatchNorm2d(out_features, eps=config.batch_norm_eps)
233
+
234
+ def forward(self, hidden_state: torch.Tensor) -> torch.Tensor:
235
+ hidden_state = self.convolution1(hidden_state)
236
+ hidden_state = self.batchnorm_before(hidden_state)
237
+
238
+ hidden_state = self.activation(hidden_state)
239
+ hidden_state = self.dropout(hidden_state)
240
+ hidden_state = self.convolution2(hidden_state)
241
+
242
+ hidden_state = self.batchnorm_after(hidden_state)
243
+ hidden_state = self.dropout(hidden_state)
244
+
245
+ return hidden_state
246
+
247
+
248
+ # Copied from transformers.models.convnext.modeling_convnext.drop_path
249
+ def drop_path(input: torch.Tensor, drop_prob: float = 0.0, training: bool = False) -> torch.Tensor:
250
+ """
251
+ Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
252
+
253
+ Comment by Ross Wightman: This is the same as the DropConnect impl I created for EfficientNet, etc networks,
254
+ however, the original name is misleading as 'Drop Connect' is a different form of dropout in a separate paper...
255
+ See discussion: https://github.com/tensorflow/tpu/issues/494#issuecomment-532968956 ... I've opted for changing the
256
+ layer and argument names to 'drop path' rather than mix DropConnect as a layer name and use 'survival rate' as the
257
+ argument.
258
+ """
259
+ if drop_prob == 0.0 or not training:
260
+ return input
261
+ keep_prob = 1 - drop_prob
262
+ shape = (input.shape[0],) + (1,) * (input.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
263
+ random_tensor = keep_prob + torch.rand(shape, dtype=input.dtype, device=input.device)
264
+ random_tensor.floor_() # binarize
265
+ output = input.div(keep_prob) * random_tensor
266
+ return output
267
+
268
+
269
+ # Copied from transformers.models.beit.modeling_beit.BeitDropPath with Beit->EfficientFormer
270
+ class EfficientFormerDropPath(nn.Module):
271
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks)."""
272
+
273
+ def __init__(self, drop_prob: Optional[float] = None) -> None:
274
+ super().__init__()
275
+ self.drop_prob = drop_prob
276
+
277
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
278
+ return drop_path(hidden_states, self.drop_prob, self.training)
279
+
280
+ def extra_repr(self) -> str:
281
+ return "p={}".format(self.drop_prob)
282
+
283
+
284
+ class EfficientFormerFlat(nn.Module):
285
+ def __init__(self):
286
+ super().__init__()
287
+
288
+ def forward(self, hidden_states: torch.Tensor) -> Tuple[torch.Tensor]:
289
+ hidden_states = hidden_states.flatten(2).transpose(1, 2)
290
+ return hidden_states
291
+
292
+
293
+ class EfficientFormerMeta3D(nn.Module):
294
+ def __init__(self, config: EfficientFormerConfig, dim: int, drop_path: float = 0.0):
295
+ super().__init__()
296
+
297
+ self.token_mixer = EfficientFormerSelfAttention(
298
+ dim=config.dim,
299
+ key_dim=config.key_dim,
300
+ num_heads=config.num_attention_heads,
301
+ attention_ratio=config.attention_ratio,
302
+ resolution=config.resolution,
303
+ )
304
+
305
+ self.layernorm1 = nn.LayerNorm(dim, eps=config.layer_norm_eps)
306
+ self.layernorm2 = nn.LayerNorm(dim, eps=config.layer_norm_eps)
307
+
308
+ mlp_hidden_dim = int(dim * config.mlp_expansion_ratio)
309
+ self.mlp = EfficientFormerDenseMlp(config, in_features=dim, hidden_features=mlp_hidden_dim)
310
+
311
+ self.drop_path = EfficientFormerDropPath(drop_path) if drop_path > 0.0 else nn.Identity()
312
+ self.use_layer_scale = config.use_layer_scale
313
+ if config.use_layer_scale:
314
+ self.layer_scale_1 = nn.Parameter(config.layer_scale_init_value * torch.ones((dim)), requires_grad=True)
315
+ self.layer_scale_2 = nn.Parameter(config.layer_scale_init_value * torch.ones((dim)), requires_grad=True)
316
+
317
+ def forward(self, hidden_states: torch.Tensor, output_attentions: bool = False) -> Tuple[torch.Tensor]:
318
+ self_attention_outputs = self.token_mixer(self.layernorm1(hidden_states), output_attentions)
319
+ attention_output = self_attention_outputs[0]
320
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
321
+
322
+ if self.use_layer_scale:
323
+ layer_output = hidden_states + self.drop_path(
324
+ self.layer_scale_1.unsqueeze(0).unsqueeze(0) * attention_output
325
+ )
326
+ layer_output = layer_output + self.drop_path(
327
+ self.layer_scale_2.unsqueeze(0).unsqueeze(0) * self.mlp(self.layernorm2(layer_output))
328
+ )
329
+ else:
330
+ layer_output = hidden_states + self.drop_path(attention_output)
331
+ layer_output = layer_output + self.drop_path(self.mlp(self.layernorm2(layer_output)))
332
+
333
+ outputs = (layer_output,) + outputs
334
+
335
+ return outputs
336
+
337
+
338
+ class EfficientFormerMeta3DLayers(nn.Module):
339
+ def __init__(self, config: EfficientFormerConfig):
340
+ super().__init__()
341
+ drop_paths = [
342
+ config.drop_path_rate * (block_idx + sum(config.depths[:-1]))
343
+ for block_idx in range(config.num_meta3d_blocks)
344
+ ]
345
+ self.blocks = nn.ModuleList(
346
+ [EfficientFormerMeta3D(config, config.hidden_sizes[-1], drop_path=drop_path) for drop_path in drop_paths]
347
+ )
348
+
349
+ def forward(self, hidden_states: torch.Tensor, output_attentions: bool = False) -> Tuple[torch.Tensor]:
350
+ all_attention_outputs = () if output_attentions else None
351
+
352
+ for layer_module in self.blocks:
353
+ if isinstance(hidden_states, tuple):
354
+ hidden_states = hidden_states[0]
355
+
356
+ hidden_states = layer_module(hidden_states, output_attentions)
357
+
358
+ if output_attentions:
359
+ all_attention_outputs = all_attention_outputs + (hidden_states[1],)
360
+
361
+ if output_attentions:
362
+ outputs = (hidden_states[0],) + all_attention_outputs
363
+ return outputs
364
+
365
+ return hidden_states
366
+
367
+
368
+ class EfficientFormerMeta4D(nn.Module):
369
+ def __init__(self, config: EfficientFormerConfig, dim: int, drop_path: float = 0.0):
370
+ super().__init__()
371
+ pool_size = config.pool_size if config.pool_size is not None else 3
372
+ self.token_mixer = EfficientFormerPooling(pool_size=pool_size)
373
+ mlp_hidden_dim = int(dim * config.mlp_expansion_ratio)
374
+ self.mlp = EfficientFormerConvMlp(
375
+ config, in_features=dim, hidden_features=mlp_hidden_dim, drop=config.hidden_dropout_prob
376
+ )
377
+
378
+ self.drop_path = EfficientFormerDropPath(drop_path) if drop_path > 0.0 else nn.Identity()
379
+ self.use_layer_scale = config.use_layer_scale
380
+ if config.use_layer_scale:
381
+ self.layer_scale_1 = nn.Parameter(config.layer_scale_init_value * torch.ones((dim)), requires_grad=True)
382
+ self.layer_scale_2 = nn.Parameter(config.layer_scale_init_value * torch.ones((dim)), requires_grad=True)
383
+
384
+ def forward(self, hidden_states: torch.Tensor) -> Tuple[torch.Tensor]:
385
+ outputs = self.token_mixer(hidden_states)
386
+
387
+ if self.use_layer_scale:
388
+ layer_output = hidden_states + self.drop_path(self.layer_scale_1.unsqueeze(-1).unsqueeze(-1) * outputs)
389
+
390
+ layer_output = layer_output + self.drop_path(
391
+ self.layer_scale_2.unsqueeze(-1).unsqueeze(-1) * self.mlp(layer_output)
392
+ )
393
+ else:
394
+ layer_output = hidden_states + self.drop_path(outputs)
395
+ layer_output = layer_output + self.drop_path(self.mlp(layer_output))
396
+
397
+ return layer_output
398
+
399
+
400
+ class EfficientFormerMeta4DLayers(nn.Module):
401
+ def __init__(self, config: EfficientFormerConfig, stage_idx: int):
402
+ super().__init__()
403
+ num_layers = (
404
+ config.depths[stage_idx] if stage_idx != -1 else config.depths[stage_idx] - config.num_meta3d_blocks
405
+ )
406
+ drop_paths = [
407
+ config.drop_path_rate * (block_idx + sum(config.depths[:stage_idx])) for block_idx in range(num_layers)
408
+ ]
409
+
410
+ self.blocks = nn.ModuleList(
411
+ [
412
+ EfficientFormerMeta4D(config, config.hidden_sizes[stage_idx], drop_path=drop_path)
413
+ for drop_path in drop_paths
414
+ ]
415
+ )
416
+
417
+ def forward(self, hidden_states: torch.Tensor) -> Tuple[torch.Tensor]:
418
+ for layer_module in self.blocks:
419
+ hidden_states = layer_module(hidden_states)
420
+ return hidden_states
421
+
422
+
423
+ class EfficientFormerIntermediateStage(nn.Module):
424
+ def __init__(self, config: EfficientFormerConfig, index: int):
425
+ super().__init__()
426
+ self.meta4D_layers = EfficientFormerMeta4DLayers(config, index)
427
+
428
+ def forward(self, hidden_states: torch.Tensor) -> Tuple[torch.Tensor]:
429
+ hidden_states = self.meta4D_layers(hidden_states)
430
+ return hidden_states
431
+
432
+
433
+ class EfficientFormerLastStage(nn.Module):
434
+ def __init__(self, config: EfficientFormerConfig):
435
+ super().__init__()
436
+ self.meta4D_layers = EfficientFormerMeta4DLayers(config, -1)
437
+ self.flat = EfficientFormerFlat()
438
+ self.meta3D_layers = EfficientFormerMeta3DLayers(config)
439
+
440
+ def forward(self, hidden_states: torch.Tensor, output_attentions: bool = False) -> Tuple[torch.Tensor]:
441
+ hidden_states = self.meta4D_layers(hidden_states)
442
+ hidden_states = self.flat(hidden_states)
443
+ hidden_states = self.meta3D_layers(hidden_states, output_attentions)
444
+
445
+ return hidden_states
446
+
447
+
448
+ class EfficientFormerEncoder(nn.Module):
449
+ def __init__(self, config: EfficientFormerConfig):
450
+ super().__init__()
451
+ self.config = config
452
+ num_intermediate_stages = len(config.depths) - 1
453
+ downsamples = [
454
+ config.downsamples[i] or config.hidden_sizes[i] != config.hidden_sizes[i + 1]
455
+ for i in range(num_intermediate_stages)
456
+ ]
457
+ intermediate_stages = []
458
+
459
+ for i in range(num_intermediate_stages):
460
+ intermediate_stages.append(EfficientFormerIntermediateStage(config, i))
461
+ if downsamples[i]:
462
+ intermediate_stages.append(
463
+ EfficientFormerPatchEmbeddings(config, config.hidden_sizes[i], config.hidden_sizes[i + 1])
464
+ )
465
+
466
+ self.intermediate_stages = nn.ModuleList(intermediate_stages)
467
+ self.last_stage = EfficientFormerLastStage(config)
468
+
469
+ def forward(
470
+ self,
471
+ hidden_states: torch.Tensor,
472
+ output_hidden_states: bool = False,
473
+ output_attentions: bool = False,
474
+ return_dict: bool = True,
475
+ ) -> BaseModelOutput:
476
+ all_hidden_states = () if output_hidden_states else None
477
+ all_self_attentions = () if output_attentions else None
478
+
479
+ if output_hidden_states:
480
+ all_hidden_states = all_hidden_states + (hidden_states,)
481
+
482
+ for layer_module in self.intermediate_stages:
483
+ hidden_states = layer_module(hidden_states)
484
+ if output_hidden_states:
485
+ all_hidden_states = all_hidden_states + (hidden_states,)
486
+
487
+ layer_output = self.last_stage(hidden_states, output_attentions=output_attentions)
488
+
489
+ if output_attentions:
490
+ all_self_attentions = all_self_attentions + layer_output[1:]
491
+
492
+ if output_hidden_states:
493
+ all_hidden_states = all_hidden_states + (layer_output[0],)
494
+
495
+ if not return_dict:
496
+ return tuple(v for v in [layer_output[0], all_hidden_states, all_self_attentions] if v is not None)
497
+
498
+ return BaseModelOutput(
499
+ last_hidden_state=layer_output[0],
500
+ hidden_states=all_hidden_states,
501
+ attentions=all_self_attentions,
502
+ )
503
+
504
+
505
+ class EfficientFormerPreTrainedModel(PreTrainedModel):
506
+ """
507
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
508
+ models.
509
+ """
510
+
511
+ config_class = EfficientFormerConfig
512
+ base_model_prefix = "efficientformer"
513
+ main_input_name = "pixel_values"
514
+ supports_gradient_checkpointing = False
515
+
516
+ def _init_weights(self, module: nn.Module):
517
+ """Initialize the weights"""
518
+ if isinstance(module, (nn.Linear, nn.Conv2d)):
519
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
520
+ if module.bias is not None:
521
+ module.bias.data.zero_()
522
+ elif isinstance(module, nn.LayerNorm):
523
+ module.bias.data.zero_()
524
+ module.weight.data.fill_(1.0)
525
+
526
+
527
+ EFFICIENTFORMER_START_DOCSTRING = r"""
528
+ This model is a PyTorch [nn.Module](https://pytorch.org/docs/stable/nn.html#nn.Module) subclass. Use it as a
529
+ regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.
530
+
531
+ Parameters:
532
+ config ([`EfficientFormerConfig`]): Model configuration class with all the parameters of the model.
533
+ Initializing with a config file does not load the weights associated with the model, only the
534
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
535
+ """
536
+
537
+ EFFICIENTFORMER_INPUTS_DOCSTRING = r"""
538
+ Args:
539
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
540
+ Pixel values. Pixel values can be obtained using [`ViTImageProcessor`]. See
541
+ [`ViTImageProcessor.preprocess`] for details.
542
+ output_attentions (`bool`, *optional*):
543
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
544
+ tensors for more detail.
545
+ output_hidden_states (`bool`, *optional*):
546
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
547
+ more detail.
548
+ return_dict (`bool`, *optional*):
549
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
550
+ """
551
+
552
+
553
+ @add_start_docstrings(
554
+ "The bare EfficientFormer Model transformer outputting raw hidden-states without any specific head on top.",
555
+ EFFICIENTFORMER_START_DOCSTRING,
556
+ )
557
+ class EfficientFormerModel(EfficientFormerPreTrainedModel):
558
+ def __init__(self, config: EfficientFormerConfig):
559
+ super().__init__(config)
560
+ self.config = config
561
+
562
+ self.patch_embed = EfficientFormerConvStem(config, config.hidden_sizes[0])
563
+ self.encoder = EfficientFormerEncoder(config)
564
+ self.layernorm = nn.LayerNorm(config.hidden_sizes[-1], eps=config.layer_norm_eps)
565
+
566
+ # Initialize weights and apply final processing
567
+ self.post_init()
568
+
569
+ @add_start_docstrings_to_model_forward(EFFICIENTFORMER_INPUTS_DOCSTRING)
570
+ @add_code_sample_docstrings(
571
+ checkpoint=_CHECKPOINT_FOR_DOC,
572
+ output_type=BaseModelOutputWithPooling,
573
+ config_class=_CONFIG_FOR_DOC,
574
+ modality="vision",
575
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
576
+ )
577
+ def forward(
578
+ self,
579
+ pixel_values: Optional[torch.Tensor] = None,
580
+ output_attentions: Optional[bool] = None,
581
+ output_hidden_states: Optional[bool] = None,
582
+ return_dict: Optional[bool] = None,
583
+ ) -> Union[tuple, BaseModelOutput]:
584
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
585
+ output_hidden_states = (
586
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
587
+ )
588
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
589
+
590
+ if pixel_values is None:
591
+ raise ValueError("You have to specify pixel_values")
592
+
593
+ embedding_output = self.patch_embed(pixel_values)
594
+ encoder_outputs = self.encoder(
595
+ embedding_output, output_attentions=output_attentions, output_hidden_states=output_hidden_states
596
+ )
597
+
598
+ sequence_output = encoder_outputs[0]
599
+ sequence_output = self.layernorm(sequence_output)
600
+
601
+ if not return_dict:
602
+ head_outputs = (sequence_output,)
603
+ return head_outputs + encoder_outputs[1:]
604
+
605
+ return BaseModelOutput(
606
+ last_hidden_state=sequence_output,
607
+ hidden_states=encoder_outputs.hidden_states,
608
+ attentions=encoder_outputs.attentions,
609
+ )
610
+
611
+
612
+ @add_start_docstrings(
613
+ """
614
+ EfficientFormer Model transformer with an image classification head on top (a linear layer on top of the final
615
+ hidden state of the [CLS] token) e.g. for ImageNet.
616
+ """,
617
+ EFFICIENTFORMER_START_DOCSTRING,
618
+ )
619
+ class EfficientFormerForImageClassification(EfficientFormerPreTrainedModel):
620
+ def __init__(self, config: EfficientFormerConfig):
621
+ super().__init__(config)
622
+
623
+ self.num_labels = config.num_labels
624
+ self.efficientformer = EfficientFormerModel(config)
625
+
626
+ # Classifier head
627
+ self.classifier = (
628
+ nn.Linear(config.hidden_sizes[-1], config.num_labels) if config.num_labels > 0 else nn.Identity()
629
+ )
630
+
631
+ # Initialize weights and apply final processing
632
+ self.post_init()
633
+
634
+ @add_start_docstrings_to_model_forward(EFFICIENTFORMER_INPUTS_DOCSTRING)
635
+ @add_code_sample_docstrings(
636
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
637
+ output_type=ImageClassifierOutput,
638
+ config_class=_CONFIG_FOR_DOC,
639
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
640
+ )
641
+ def forward(
642
+ self,
643
+ pixel_values: Optional[torch.Tensor] = None,
644
+ labels: Optional[torch.Tensor] = None,
645
+ output_attentions: Optional[bool] = None,
646
+ output_hidden_states: Optional[bool] = None,
647
+ return_dict: Optional[bool] = None,
648
+ ) -> Union[tuple, ImageClassifierOutput]:
649
+ r"""
650
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
651
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
652
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
653
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
654
+ """
655
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
656
+
657
+ outputs = self.efficientformer(
658
+ pixel_values,
659
+ output_attentions=output_attentions,
660
+ output_hidden_states=output_hidden_states,
661
+ return_dict=return_dict,
662
+ )
663
+
664
+ sequence_output = outputs[0]
665
+
666
+ logits = self.classifier(sequence_output.mean(-2))
667
+
668
+ loss = None
669
+ if labels is not None:
670
+ if self.config.problem_type is None:
671
+ if self.num_labels == 1:
672
+ self.config.problem_type = "regression"
673
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
674
+ self.config.problem_type = "single_label_classification"
675
+ else:
676
+ self.config.problem_type = "multi_label_classification"
677
+
678
+ if self.config.problem_type == "regression":
679
+ loss_fct = MSELoss()
680
+ if self.num_labels == 1:
681
+ loss = loss_fct(logits.squeeze(), labels.squeeze())
682
+ else:
683
+ loss = loss_fct(logits, labels)
684
+ elif self.config.problem_type == "single_label_classification":
685
+ loss_fct = CrossEntropyLoss()
686
+ loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
687
+ elif self.config.problem_type == "multi_label_classification":
688
+ loss_fct = BCEWithLogitsLoss()
689
+ loss = loss_fct(logits, labels)
690
+
691
+ if not return_dict:
692
+ output = (logits,) + outputs[1:]
693
+ return ((loss,) + output) if loss is not None else output
694
+
695
+ return ImageClassifierOutput(
696
+ loss=loss,
697
+ logits=logits,
698
+ hidden_states=outputs.hidden_states,
699
+ attentions=outputs.attentions,
700
+ )
701
+
702
+
703
+ @dataclass
704
+ class EfficientFormerForImageClassificationWithTeacherOutput(ModelOutput):
705
+ """
706
+ Output type of [`EfficientFormerForImageClassificationWithTeacher`].
707
+
708
+ Args:
709
+ logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
710
+ Prediction scores as the average of the cls_logits and distillation logits.
711
+ cls_logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
712
+ Prediction scores of the classification head (i.e. the linear layer on top of the final hidden state of the
713
+ class token).
714
+ distillation_logits (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`):
715
+ Prediction scores of the distillation head (i.e. the linear layer on top of the final hidden state of the
716
+ distillation token).
717
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
718
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings + one for the output of each layer) of
719
+ shape `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer
720
+ plus the initial embedding outputs.
721
+ attentions (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`):
722
+ Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
723
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
724
+ the self-attention heads.
725
+ """
726
+
727
+ logits: torch.FloatTensor = None
728
+ cls_logits: torch.FloatTensor = None
729
+ distillation_logits: torch.FloatTensor = None
730
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
731
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
732
+
733
+
734
+ @add_start_docstrings(
735
+ """
736
+ EfficientFormer Model transformer with image classification heads on top (a linear layer on top of the final hidden
737
+ state of the [CLS] token and a linear layer on top of the final hidden state of the distillation token) e.g. for
738
+ ImageNet.
739
+
740
+ <Tip warning={true}>
741
+
742
+ This model supports inference-only. Fine-tuning with distillation (i.e. with a teacher) is not yet
743
+ supported.
744
+
745
+ </Tip>
746
+ """,
747
+ EFFICIENTFORMER_START_DOCSTRING,
748
+ )
749
+ class EfficientFormerForImageClassificationWithTeacher(EfficientFormerPreTrainedModel):
750
+ def __init__(self, config: EfficientFormerConfig):
751
+ super().__init__(config)
752
+
753
+ self.num_labels = config.num_labels
754
+ self.efficientformer = EfficientFormerModel(config)
755
+
756
+ # Classifier head
757
+ self.classifier = nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
758
+ # Distillation head
759
+ self.distillation_classifier = (
760
+ nn.Linear(config.hidden_size, config.num_labels) if config.num_labels > 0 else nn.Identity()
761
+ )
762
+
763
+ # Initialize weights and apply final processing
764
+ self.post_init()
765
+
766
+ @add_start_docstrings_to_model_forward(EFFICIENTFORMER_INPUTS_DOCSTRING)
767
+ @add_code_sample_docstrings(
768
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
769
+ output_type=EfficientFormerForImageClassificationWithTeacherOutput,
770
+ config_class=_CONFIG_FOR_DOC,
771
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
772
+ )
773
+ def forward(
774
+ self,
775
+ pixel_values: Optional[torch.Tensor] = None,
776
+ output_attentions: Optional[bool] = None,
777
+ output_hidden_states: Optional[bool] = None,
778
+ return_dict: Optional[bool] = None,
779
+ ) -> Union[tuple, EfficientFormerForImageClassificationWithTeacherOutput]:
780
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
781
+ outputs = self.efficientformer(
782
+ pixel_values,
783
+ output_attentions=output_attentions,
784
+ output_hidden_states=output_hidden_states,
785
+ return_dict=return_dict,
786
+ )
787
+
788
+ sequence_output = outputs[0]
789
+
790
+ cls_logits = self.classifier(sequence_output.mean(-2))
791
+ distillation_logits = self.distillation_classifier(sequence_output.mean(-2))
792
+
793
+ # during inference, return the average of both classifier predictions
794
+ logits = (cls_logits + distillation_logits) / 2
795
+
796
+ if not return_dict:
797
+ output = (logits, cls_logits, distillation_logits) + outputs[1:]
798
+ return output
799
+
800
+ return EfficientFormerForImageClassificationWithTeacherOutput(
801
+ logits=logits,
802
+ cls_logits=cls_logits,
803
+ distillation_logits=distillation_logits,
804
+ hidden_states=outputs.hidden_states,
805
+ attentions=outputs.attentions,
806
+ )
SupplementaryMaterial_Code/transformers-4.37.2/models/efficientformer/modeling_tf_efficientformer.py ADDED
@@ -0,0 +1,1195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Snapchat Research 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
+ """ TensorFlow EfficientFormer model."""
16
+
17
+ import itertools
18
+ from dataclasses import dataclass
19
+ from typing import Optional, Tuple, Union
20
+
21
+ import tensorflow as tf
22
+
23
+ from ...activations_tf import ACT2FN
24
+ from ...modeling_tf_outputs import (
25
+ TFBaseModelOutput,
26
+ TFBaseModelOutputWithPooling,
27
+ TFImageClassifierOutput,
28
+ )
29
+ from ...modeling_tf_utils import (
30
+ TFPreTrainedModel,
31
+ TFSequenceClassificationLoss,
32
+ get_initializer,
33
+ keras_serializable,
34
+ unpack_inputs,
35
+ )
36
+ from ...tf_utils import shape_list, stable_softmax
37
+ from ...utils import (
38
+ ModelOutput,
39
+ add_code_sample_docstrings,
40
+ add_start_docstrings,
41
+ add_start_docstrings_to_model_forward,
42
+ logging,
43
+ )
44
+ from .configuration_efficientformer import EfficientFormerConfig
45
+
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+ # General docstring
50
+ _CONFIG_FOR_DOC = "EfficientFormerConfig"
51
+
52
+ # Base docstring
53
+ _CHECKPOINT_FOR_DOC = "snap-research/efficientformer-l1-300"
54
+ _EXPECTED_OUTPUT_SHAPE = [1, 49, 448]
55
+
56
+ # Image classification docstring
57
+ _IMAGE_CLASS_CHECKPOINT = "snap-research/efficientformer-l1-300"
58
+ _IMAGE_CLASS_EXPECTED_OUTPUT = "LABEL_281"
59
+
60
+
61
+ TF_EFFICIENTFORMER_PRETRAINED_MODEL_ARCHIVE_LIST = [
62
+ "snap-research/efficientformer-l1-300",
63
+ # See all EfficientFormer models at https://huggingface.co/models?filter=efficientformer
64
+ ]
65
+
66
+
67
+ class TFEfficientFormerPatchEmbeddings(tf.keras.layers.Layer):
68
+ """
69
+ This class performs downsampling between two stages. For the input tensor with the shape [batch_size, num_channels,
70
+ height, width] it produces output tensor with the shape [batch_size, num_channels, height/stride, width/stride]
71
+ """
72
+
73
+ def __init__(
74
+ self, config: EfficientFormerConfig, num_channels: int, embed_dim: int, apply_norm: bool = True, **kwargs
75
+ ) -> None:
76
+ super().__init__(**kwargs)
77
+ self.num_channels = num_channels
78
+
79
+ self.padding = tf.keras.layers.ZeroPadding2D(padding=config.downsample_pad)
80
+ self.projection = tf.keras.layers.Conv2D(
81
+ filters=embed_dim,
82
+ kernel_size=config.downsample_patch_size,
83
+ strides=config.downsample_stride,
84
+ padding="valid",
85
+ name="projection",
86
+ )
87
+ # Use same default momentum and epsilon as PyTorch equivalent for BatchNormalization
88
+ self.norm = (
89
+ tf.keras.layers.BatchNormalization(axis=-1, epsilon=config.batch_norm_eps, momentum=0.9, name="norm")
90
+ if apply_norm
91
+ else tf.identity
92
+ )
93
+ self.embed_dim = embed_dim
94
+
95
+ def call(self, pixel_values: tf.Tensor, training: bool = False) -> tf.Tensor:
96
+ tf.debugging.assert_shapes(
97
+ [(pixel_values, (..., None, None, self.num_channels))],
98
+ message="Make sure that the channel dimension of the pixel values match with the one set in the configuration.",
99
+ )
100
+ embeddings = self.projection(self.padding(pixel_values))
101
+ embeddings = self.norm(embeddings, training=training)
102
+ return embeddings
103
+
104
+ def build(self, input_shape=None):
105
+ if self.built:
106
+ return
107
+ self.built = True
108
+ if getattr(self, "projection", None) is not None:
109
+ with tf.name_scope(self.projection.name):
110
+ self.projection.build([None, None, None, self.num_channels])
111
+ if getattr(self, "norm", None) is not None:
112
+ if hasattr(self.norm, "name"):
113
+ with tf.name_scope(self.norm.name):
114
+ self.norm.build([None, None, None, self.embed_dim])
115
+
116
+
117
+ class TFEfficientFormerSelfAttention(tf.keras.layers.Layer):
118
+ def __init__(
119
+ self,
120
+ dim: int,
121
+ key_dim: int,
122
+ num_heads: int,
123
+ attention_ratio: int,
124
+ resolution: int,
125
+ config: EfficientFormerConfig,
126
+ **kwargs,
127
+ ):
128
+ super().__init__(**kwargs)
129
+
130
+ self.num_heads = num_heads
131
+ self.key_dim = key_dim
132
+ self.attention_ratio = attention_ratio
133
+ self.scale = key_dim**-0.5
134
+ self.total_key_dim = key_dim * num_heads
135
+ self.expanded_key_dim = int(attention_ratio * key_dim)
136
+ self.total_expanded_key_dim = int(self.expanded_key_dim * num_heads)
137
+ hidden_size = self.total_expanded_key_dim + self.total_key_dim * 2
138
+
139
+ self.qkv = tf.keras.layers.Dense(
140
+ units=hidden_size, kernel_initializer=get_initializer(config.initializer_range), name="qkv"
141
+ )
142
+ self.projection = tf.keras.layers.Dense(
143
+ units=dim, kernel_initializer=get_initializer(config.initializer_range), name="projection"
144
+ )
145
+ self.resolution = resolution
146
+ self.dim = dim
147
+
148
+ def build(self, input_shape: tf.TensorShape) -> None:
149
+ points = list(itertools.product(range(self.resolution), range(self.resolution)))
150
+ num_points = len(points)
151
+ attention_offsets = {}
152
+
153
+ idxs = []
154
+
155
+ for point_1 in points:
156
+ for point_2 in points:
157
+ offset = (abs(point_1[0] - point_2[0]), abs(point_1[1] - point_2[1]))
158
+ if offset not in attention_offsets:
159
+ attention_offsets[offset] = len(attention_offsets)
160
+ idxs.append(attention_offsets[offset])
161
+
162
+ self.attention_biases = self.add_weight(
163
+ shape=(self.num_heads, len(attention_offsets)),
164
+ initializer=tf.keras.initializers.zeros(),
165
+ trainable=True,
166
+ name="attention_biases",
167
+ )
168
+ self.attention_bias_idxs = self.add_weight(
169
+ shape=(num_points, num_points),
170
+ trainable=False,
171
+ dtype=tf.int32,
172
+ name="attention_bias_idxs",
173
+ )
174
+
175
+ self.attention_bias_idxs.assign(tf.reshape(tf.cast(idxs, dtype=tf.int32), (num_points, num_points)))
176
+
177
+ if self.built:
178
+ return
179
+ self.built = True
180
+ if getattr(self, "qkv", None) is not None:
181
+ with tf.name_scope(self.qkv.name):
182
+ self.qkv.build([None, None, self.dim])
183
+ if getattr(self, "projection", None) is not None:
184
+ with tf.name_scope(self.projection.name):
185
+ self.projection.build([None, None, self.total_expanded_key_dim])
186
+
187
+ def call(
188
+ self, hidden_states: tf.Tensor, output_attentions: bool = False, training: bool = False
189
+ ) -> Tuple[tf.Tensor]:
190
+ batch_size, sequence_length, *_ = shape_list(hidden_states)
191
+ qkv = self.qkv(inputs=hidden_states)
192
+
193
+ query_layer, key_layer, value_layer = tf.split(
194
+ tf.reshape(tensor=qkv, shape=(batch_size, sequence_length, self.num_heads, -1)),
195
+ num_or_size_splits=[self.key_dim, self.key_dim, self.expanded_key_dim],
196
+ axis=3,
197
+ )
198
+
199
+ query_layer = tf.transpose(query_layer, perm=[0, 2, 1, 3])
200
+ key_layer = tf.transpose(key_layer, perm=[0, 2, 1, 3])
201
+ value_layer = tf.transpose(value_layer, perm=[0, 2, 1, 3])
202
+
203
+ attention_probs = tf.matmul(query_layer, tf.transpose(key_layer, perm=[0, 1, 3, 2]))
204
+ scale = tf.cast(self.scale, dtype=attention_probs.dtype)
205
+ attention_probs = tf.multiply(attention_probs, scale)
206
+
207
+ attention_biases = tf.gather(params=self.attention_biases, indices=self.attention_bias_idxs, axis=1)
208
+ attention_probs = attention_probs + attention_biases
209
+ attention_probs = stable_softmax(logits=attention_probs, axis=-1)
210
+
211
+ context_layer = tf.matmul(attention_probs, value_layer)
212
+ context_layer = tf.transpose(context_layer, perm=[0, 2, 1, 3])
213
+
214
+ context_layer = tf.reshape(
215
+ tensor=context_layer, shape=(batch_size, sequence_length, self.total_expanded_key_dim)
216
+ )
217
+ context_layer = self.projection(context_layer)
218
+
219
+ outputs = (context_layer, attention_probs) if output_attentions else (context_layer,)
220
+
221
+ return outputs
222
+
223
+
224
+ class TFEfficientFormerConvStem(tf.keras.layers.Layer):
225
+ def __init__(self, config: EfficientFormerConfig, out_channels: int, **kwargs):
226
+ super().__init__(**kwargs)
227
+
228
+ self.padding = tf.keras.layers.ZeroPadding2D(padding=1)
229
+ self.convolution1 = tf.keras.layers.Conv2D(
230
+ filters=out_channels // 2, kernel_size=3, strides=2, padding="valid", name="convolution1"
231
+ )
232
+ # Use same default momentum and epsilon as PyTorch equivalent for BatchNormalization
233
+ self.batchnorm_before = tf.keras.layers.BatchNormalization(
234
+ axis=-1, epsilon=config.batch_norm_eps, momentum=0.9, name="batchnorm_before"
235
+ )
236
+
237
+ self.convolution2 = tf.keras.layers.Conv2D(
238
+ filters=out_channels,
239
+ kernel_size=3,
240
+ strides=2,
241
+ padding="valid",
242
+ name="convolution2",
243
+ )
244
+ # Use same default momentum and epsilon as PyTorch equivalent for BatchNormalization
245
+ self.batchnorm_after = tf.keras.layers.BatchNormalization(
246
+ axis=-1, epsilon=config.batch_norm_eps, momentum=0.9, name="batchnorm_after"
247
+ )
248
+
249
+ self.activation = tf.keras.layers.Activation(activation=tf.keras.activations.relu, name="activation")
250
+ self.out_channels = out_channels
251
+ self.config = config
252
+
253
+ def call(self, pixel_values: tf.Tensor, training: bool = False) -> tf.Tensor:
254
+ features = self.batchnorm_before(self.convolution1(self.padding(pixel_values)), training=training)
255
+ features = self.activation(features)
256
+ features = self.batchnorm_after(self.convolution2(self.padding(features)), training=training)
257
+ features = self.activation(features)
258
+ return features
259
+
260
+ def build(self, input_shape=None):
261
+ if self.built:
262
+ return
263
+ self.built = True
264
+ if getattr(self, "convolution1", None) is not None:
265
+ with tf.name_scope(self.convolution1.name):
266
+ self.convolution1.build([None, None, None, self.config.num_channels])
267
+ if getattr(self, "batchnorm_before", None) is not None:
268
+ with tf.name_scope(self.batchnorm_before.name):
269
+ self.batchnorm_before.build([None, None, None, self.out_channels // 2])
270
+ if getattr(self, "convolution2", None) is not None:
271
+ with tf.name_scope(self.convolution2.name):
272
+ self.convolution2.build([None, None, None, self.out_channels // 2])
273
+ if getattr(self, "batchnorm_after", None) is not None:
274
+ with tf.name_scope(self.batchnorm_after.name):
275
+ self.batchnorm_after.build([None, None, None, self.out_channels])
276
+ if getattr(self, "activation", None) is not None:
277
+ with tf.name_scope(self.activation.name):
278
+ self.activation.build(None)
279
+
280
+
281
+ class TFEfficientFormerPooling(tf.keras.layers.Layer):
282
+ def __init__(self, pool_size: int, **kwargs):
283
+ super().__init__(**kwargs)
284
+ self.pool = tf.keras.layers.AveragePooling2D(pool_size=pool_size, strides=1, padding="same")
285
+
286
+ def call(self, hidden_states: tf.Tensor) -> tf.Tensor:
287
+ output = self.pool(hidden_states)
288
+ output = output - hidden_states
289
+ return output
290
+
291
+
292
+ class TFEfficientFormerDenseMlp(tf.keras.layers.Layer):
293
+ def __init__(
294
+ self,
295
+ config: EfficientFormerConfig,
296
+ in_features: int,
297
+ hidden_features: Optional[int] = None,
298
+ out_features: Optional[int] = None,
299
+ **kwargs,
300
+ ):
301
+ super().__init__(**kwargs)
302
+ out_features = out_features or in_features
303
+ hidden_features = hidden_features or in_features
304
+
305
+ self.linear_in = tf.keras.layers.Dense(
306
+ units=hidden_features, kernel_initializer=get_initializer(config.initializer_range), name="linear_in"
307
+ )
308
+ self.activation = ACT2FN[config.hidden_act]
309
+ self.dropout = tf.keras.layers.Dropout(rate=config.hidden_dropout_prob)
310
+
311
+ self.linear_out = tf.keras.layers.Dense(
312
+ units=out_features, kernel_initializer=get_initializer(config.initializer_range), name="linear_out"
313
+ )
314
+ self.hidden_features = hidden_features
315
+ self.in_features = in_features
316
+
317
+ def call(self, hidden_states: tf.Tensor, training: bool = False) -> tf.Tensor:
318
+ hidden_states = self.linear_in(inputs=hidden_states)
319
+ hidden_states = self.activation(hidden_states)
320
+ hidden_states = self.dropout(inputs=hidden_states, training=training)
321
+ hidden_states = self.linear_out(inputs=hidden_states)
322
+ hidden_states = self.dropout(inputs=hidden_states, training=training)
323
+
324
+ return hidden_states
325
+
326
+ def build(self, input_shape=None):
327
+ if self.built:
328
+ return
329
+ self.built = True
330
+ if getattr(self, "linear_in", None) is not None:
331
+ with tf.name_scope(self.linear_in.name):
332
+ self.linear_in.build([None, None, self.in_features])
333
+ if getattr(self, "linear_out", None) is not None:
334
+ with tf.name_scope(self.linear_out.name):
335
+ self.linear_out.build([None, None, self.hidden_features])
336
+
337
+
338
+ class TFEfficientFormerConvMlp(tf.keras.layers.Layer):
339
+ def __init__(
340
+ self,
341
+ config: EfficientFormerConfig,
342
+ in_features: int,
343
+ hidden_features: Optional[int] = None,
344
+ out_features: Optional[int] = None,
345
+ drop: float = 0.0,
346
+ **kwargs,
347
+ ):
348
+ super().__init__(**kwargs)
349
+ out_features = out_features or in_features
350
+ hidden_features = hidden_features or in_features
351
+
352
+ self.convolution1 = tf.keras.layers.Conv2D(
353
+ filters=hidden_features,
354
+ kernel_size=1,
355
+ name="convolution1",
356
+ padding="valid",
357
+ )
358
+
359
+ self.activation = ACT2FN[config.hidden_act]
360
+
361
+ self.convolution2 = tf.keras.layers.Conv2D(
362
+ filters=out_features,
363
+ kernel_size=1,
364
+ name="convolution2",
365
+ padding="valid",
366
+ )
367
+
368
+ self.dropout = tf.keras.layers.Dropout(rate=drop)
369
+
370
+ # Use same default momentum and epsilon as PyTorch equivalent for BatchNormalization
371
+ self.batchnorm_before = tf.keras.layers.BatchNormalization(
372
+ axis=-1, epsilon=config.batch_norm_eps, momentum=0.9, name="batchnorm_before"
373
+ )
374
+ # Use same default momentum and epsilon as PyTorch equivalent for BatchNormalization
375
+ self.batchnorm_after = tf.keras.layers.BatchNormalization(
376
+ axis=-1, epsilon=config.batch_norm_eps, momentum=0.9, name="batchnorm_after"
377
+ )
378
+ self.hidden_features = hidden_features
379
+ self.in_features = in_features
380
+ self.out_features = out_features
381
+
382
+ def call(self, hidden_state: tf.Tensor, training: bool = False) -> tf.Tensor:
383
+ hidden_state = self.convolution1(hidden_state)
384
+ hidden_state = self.batchnorm_before(hidden_state, training=training)
385
+ hidden_state = self.activation(hidden_state)
386
+ hidden_state = self.dropout(hidden_state, training=training)
387
+ hidden_state = self.convolution2(hidden_state)
388
+ hidden_state = self.batchnorm_after(hidden_state, training=training)
389
+ hidden_state = self.dropout(hidden_state, training=training)
390
+ return hidden_state
391
+
392
+ def build(self, input_shape=None):
393
+ if self.built:
394
+ return
395
+ self.built = True
396
+ if getattr(self, "convolution1", None) is not None:
397
+ with tf.name_scope(self.convolution1.name):
398
+ self.convolution1.build([None, None, None, self.in_features])
399
+ if getattr(self, "convolution2", None) is not None:
400
+ with tf.name_scope(self.convolution2.name):
401
+ self.convolution2.build([None, None, None, self.hidden_features])
402
+ if getattr(self, "batchnorm_before", None) is not None:
403
+ with tf.name_scope(self.batchnorm_before.name):
404
+ self.batchnorm_before.build([None, None, None, self.hidden_features])
405
+ if getattr(self, "batchnorm_after", None) is not None:
406
+ with tf.name_scope(self.batchnorm_after.name):
407
+ self.batchnorm_after.build([None, None, None, self.out_features])
408
+
409
+
410
+ # Copied from transformers.models.convnext.modeling_tf_convnext.TFConvNextDropPath with ConvNext->EfficientFormer
411
+ class TFEfficientFormerDropPath(tf.keras.layers.Layer):
412
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
413
+ References:
414
+ (1) github.com:rwightman/pytorch-image-models
415
+ """
416
+
417
+ def __init__(self, drop_path: float, **kwargs):
418
+ super().__init__(**kwargs)
419
+ self.drop_path = drop_path
420
+
421
+ def call(self, x: tf.Tensor, training=None):
422
+ if training:
423
+ keep_prob = 1 - self.drop_path
424
+ shape = (tf.shape(x)[0],) + (1,) * (len(tf.shape(x)) - 1)
425
+ random_tensor = keep_prob + tf.random.uniform(shape, 0, 1)
426
+ random_tensor = tf.floor(random_tensor)
427
+ return (x / keep_prob) * random_tensor
428
+ return x
429
+
430
+
431
+ class TFEfficientFormerFlat(tf.keras.layers.Layer):
432
+ def __init__(self, **kwargs):
433
+ super().__init__(**kwargs)
434
+
435
+ def call(self, hidden_states: tf.Tensor) -> Tuple[tf.Tensor]:
436
+ batch_size, _, _, in_channels = shape_list(hidden_states)
437
+ hidden_states = tf.reshape(hidden_states, shape=[batch_size, -1, in_channels])
438
+ return hidden_states
439
+
440
+
441
+ class TFEfficientFormerMeta3D(tf.keras.layers.Layer):
442
+ def __init__(self, config: EfficientFormerConfig, dim: int, drop_path: float = 0.0, **kwargs):
443
+ super().__init__(**kwargs)
444
+
445
+ self.token_mixer = TFEfficientFormerSelfAttention(
446
+ dim=config.dim,
447
+ key_dim=config.key_dim,
448
+ num_heads=config.num_attention_heads,
449
+ attention_ratio=config.attention_ratio,
450
+ resolution=config.resolution,
451
+ name="token_mixer",
452
+ config=config,
453
+ )
454
+ self.dim = dim
455
+ self.config = config
456
+
457
+ self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layernorm1")
458
+ self.layernorm2 = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layernorm2")
459
+ mlp_hidden_dim = int(dim * config.mlp_expansion_ratio)
460
+ self.mlp = TFEfficientFormerDenseMlp(config, in_features=dim, hidden_features=mlp_hidden_dim, name="mlp")
461
+
462
+ # Using `layers.Activation` instead of `tf.identity` to better control `training' behavior.
463
+ self.drop_path = (
464
+ TFEfficientFormerDropPath(drop_path)
465
+ if drop_path > 0.0
466
+ else tf.keras.layers.Activation("linear", name="drop_path")
467
+ )
468
+ self.config = config
469
+
470
+ def build(self, input_shape=None):
471
+ self.layer_scale_1 = None
472
+ self.layer_scale_2 = None
473
+
474
+ if self.config.use_layer_scale:
475
+ self.layer_scale_1 = self.add_weight(
476
+ shape=(self.dim,),
477
+ initializer=tf.keras.initializers.Constant(value=self.config.layer_scale_init_value),
478
+ trainable=True,
479
+ name="layer_scale_1",
480
+ )
481
+ self.layer_scale_2 = self.add_weight(
482
+ shape=(self.dim,),
483
+ initializer=tf.keras.initializers.Constant(value=self.config.layer_scale_init_value),
484
+ trainable=True,
485
+ name="layer_scale_2",
486
+ )
487
+
488
+ if self.built:
489
+ return
490
+ self.built = True
491
+ if getattr(self, "token_mixer", None) is not None:
492
+ with tf.name_scope(self.token_mixer.name):
493
+ self.token_mixer.build(None)
494
+ if getattr(self, "layernorm1", None) is not None:
495
+ with tf.name_scope(self.layernorm1.name):
496
+ self.layernorm1.build([None, None, self.dim])
497
+ if getattr(self, "layernorm2", None) is not None:
498
+ with tf.name_scope(self.layernorm2.name):
499
+ self.layernorm2.build([None, None, self.dim])
500
+ if getattr(self, "mlp", None) is not None:
501
+ with tf.name_scope(self.mlp.name):
502
+ self.mlp.build(None)
503
+ if getattr(self, "drop_path", None) is not None:
504
+ with tf.name_scope(self.drop_path.name):
505
+ self.drop_path.build(None)
506
+
507
+ def call(
508
+ self, hidden_states: tf.Tensor, output_attentions: bool = False, training: bool = False
509
+ ) -> Tuple[tf.Tensor]:
510
+ self_attention_outputs = self.token_mixer(
511
+ hidden_states=self.layernorm1(hidden_states, training=training),
512
+ output_attentions=output_attentions,
513
+ training=training,
514
+ )
515
+
516
+ attention_output = self_attention_outputs[0]
517
+ outputs = self_attention_outputs[1:] # add self attentions if we output attention weights
518
+
519
+ if self.config.use_layer_scale:
520
+ layer_output = hidden_states + self.drop_path(
521
+ tf.expand_dims(tf.expand_dims(self.layer_scale_1, 0), 0) * attention_output,
522
+ training=training,
523
+ )
524
+ layer_output = layer_output + self.drop_path(
525
+ tf.expand_dims(tf.expand_dims(self.layer_scale_2, 0), 0)
526
+ * self.mlp(hidden_states=self.layernorm2(inputs=layer_output, training=training), training=training),
527
+ training=training,
528
+ )
529
+ else:
530
+ layer_output = hidden_states + self.drop_path(attention_output, training=training)
531
+ layer_output = layer_output + self.drop_path(
532
+ self.mlp(hidden_states=self.layernorm2(inputs=layer_output, training=training), training=training),
533
+ training=training,
534
+ )
535
+
536
+ outputs = (layer_output,) + outputs
537
+
538
+ return outputs
539
+
540
+
541
+ class TFEfficientFormerMeta3DLayers(tf.keras.layers.Layer):
542
+ def __init__(self, config: EfficientFormerConfig, **kwargs):
543
+ super().__init__(**kwargs)
544
+ drop_paths = [
545
+ config.drop_path_rate * (block_idx + sum(config.depths[:-1]))
546
+ for block_idx in range(config.num_meta3d_blocks)
547
+ ]
548
+ self.blocks = [
549
+ TFEfficientFormerMeta3D(config, config.hidden_sizes[-1], drop_path=drop_path, name=f"blocks.{i}")
550
+ for i, drop_path in enumerate(drop_paths)
551
+ ]
552
+
553
+ def call(
554
+ self, hidden_states: tf.Tensor, output_attentions: bool = False, training: bool = False
555
+ ) -> Tuple[tf.Tensor]:
556
+ all_attention_outputs = () if output_attentions else None
557
+
558
+ for i, layer_module in enumerate(self.blocks):
559
+ if isinstance(hidden_states, tuple):
560
+ hidden_states = hidden_states[0]
561
+
562
+ hidden_states = layer_module(
563
+ hidden_states=hidden_states, output_attentions=output_attentions, training=training
564
+ )
565
+ if output_attentions:
566
+ all_attention_outputs = all_attention_outputs + (hidden_states[1],)
567
+
568
+ if output_attentions:
569
+ outputs = (hidden_states[0],) + all_attention_outputs
570
+ return outputs
571
+
572
+ return hidden_states
573
+
574
+ def build(self, input_shape=None):
575
+ if self.built:
576
+ return
577
+ self.built = True
578
+ if getattr(self, "blocks", None) is not None:
579
+ for layer in self.blocks:
580
+ with tf.name_scope(layer.name):
581
+ layer.build(None)
582
+
583
+
584
+ class TFEfficientFormerMeta4D(tf.keras.layers.Layer):
585
+ def __init__(self, config: EfficientFormerConfig, dim: int, drop_path: float = 0.0, **kwargs):
586
+ super().__init__(**kwargs)
587
+ pool_size = config.pool_size if config.pool_size is not None else 3
588
+ self.token_mixer = TFEfficientFormerPooling(pool_size=pool_size, name="token_mixer")
589
+ self.dim = dim
590
+ mlp_hidden_dim = int(dim * config.mlp_expansion_ratio)
591
+ self.mlp = TFEfficientFormerConvMlp(
592
+ config=config, in_features=dim, hidden_features=mlp_hidden_dim, drop=config.hidden_dropout_prob, name="mlp"
593
+ )
594
+
595
+ self.drop_path = (
596
+ TFEfficientFormerDropPath(drop_path, name="drop_path")
597
+ if drop_path > 0.0
598
+ else tf.keras.layers.Activation("linear", name="drop_path")
599
+ )
600
+ self.config = config
601
+
602
+ def build(self, input_shape=None):
603
+ self.layer_scale_1 = None
604
+ self.layer_scale_2 = None
605
+
606
+ if self.config.use_layer_scale:
607
+ self.layer_scale_1 = self.add_weight(
608
+ shape=(self.dim),
609
+ initializer=tf.keras.initializers.Constant(value=self.config.layer_scale_init_value),
610
+ trainable=True,
611
+ name="layer_scale_1",
612
+ )
613
+ self.layer_scale_2 = self.add_weight(
614
+ shape=(self.dim),
615
+ initializer=tf.keras.initializers.Constant(value=self.config.layer_scale_init_value),
616
+ trainable=True,
617
+ name="layer_scale_2",
618
+ )
619
+
620
+ if self.built:
621
+ return
622
+ self.built = True
623
+ if getattr(self, "token_mixer", None) is not None:
624
+ with tf.name_scope(self.token_mixer.name):
625
+ self.token_mixer.build(None)
626
+ if getattr(self, "mlp", None) is not None:
627
+ with tf.name_scope(self.mlp.name):
628
+ self.mlp.build(None)
629
+ if getattr(self, "drop_path", None) is not None:
630
+ with tf.name_scope(self.drop_path.name):
631
+ self.drop_path.build(None)
632
+
633
+ def call(self, hidden_states: tf.Tensor, training: bool = False) -> Tuple[tf.Tensor]:
634
+ outputs = self.token_mixer(hidden_states)
635
+
636
+ if self.config.use_layer_scale:
637
+ layer_output = hidden_states + self.drop_path(
638
+ tf.expand_dims(tf.expand_dims(self.layer_scale_1, 0), 0) * outputs,
639
+ training=training,
640
+ )
641
+
642
+ layer_output = layer_output + self.drop_path(
643
+ tf.expand_dims(tf.expand_dims(self.layer_scale_2, 0), 0)
644
+ * self.mlp(hidden_state=layer_output, training=training),
645
+ training=training,
646
+ )
647
+
648
+ else:
649
+ layer_output = hidden_states + self.drop_path(outputs, training=training)
650
+ layer_output = layer_output + self.drop_path(
651
+ self.mlp(hidden_state=layer_output, training=training), training=training
652
+ )
653
+
654
+ return layer_output
655
+
656
+
657
+ class TFEfficientFormerMeta4DLayers(tf.keras.layers.Layer):
658
+ def __init__(self, config: EfficientFormerConfig, stage_idx: int, **kwargs):
659
+ super().__init__(**kwargs)
660
+ num_layers = (
661
+ config.depths[stage_idx] if stage_idx != -1 else config.depths[stage_idx] - config.num_meta3d_blocks
662
+ )
663
+ drop_paths = [
664
+ config.drop_path_rate * (block_idx + sum(config.depths[:stage_idx])) for block_idx in range(num_layers)
665
+ ]
666
+
667
+ self.blocks = [
668
+ TFEfficientFormerMeta4D(
669
+ config=config, dim=config.hidden_sizes[stage_idx], drop_path=drop_paths[i], name=f"blocks.{i}"
670
+ )
671
+ for i in range(len(drop_paths))
672
+ ]
673
+
674
+ def call(self, hidden_states: tf.Tensor, training: bool = False) -> Tuple[tf.Tensor]:
675
+ for layer_module in self.blocks:
676
+ hidden_states = layer_module(hidden_states=hidden_states, training=training)
677
+ return hidden_states
678
+
679
+ def build(self, input_shape=None):
680
+ if self.built:
681
+ return
682
+ self.built = True
683
+ if getattr(self, "blocks", None) is not None:
684
+ for layer in self.blocks:
685
+ with tf.name_scope(layer.name):
686
+ layer.build(None)
687
+
688
+
689
+ class TFEfficientFormerIntermediateStage(tf.keras.layers.Layer):
690
+ def __init__(self, config: EfficientFormerConfig, index: int, **kwargs):
691
+ super().__init__(**kwargs)
692
+ self.meta4D_layers = TFEfficientFormerMeta4DLayers(config=config, stage_idx=index, name="meta4D_layers")
693
+
694
+ def call(self, hidden_states: tf.Tensor, training: bool = False) -> Tuple[tf.Tensor]:
695
+ hidden_states = self.meta4D_layers(hidden_states=hidden_states, training=training)
696
+ return hidden_states
697
+
698
+ def build(self, input_shape=None):
699
+ if self.built:
700
+ return
701
+ self.built = True
702
+ if getattr(self, "meta4D_layers", None) is not None:
703
+ with tf.name_scope(self.meta4D_layers.name):
704
+ self.meta4D_layers.build(None)
705
+
706
+
707
+ class TFEfficientFormerLastStage(tf.keras.layers.Layer):
708
+ def __init__(self, config: EfficientFormerConfig, **kwargs):
709
+ super().__init__(**kwargs)
710
+ self.meta4D_layers = TFEfficientFormerMeta4DLayers(config=config, stage_idx=-1, name="meta4D_layers")
711
+ self.flat = TFEfficientFormerFlat(name="flat")
712
+ self.meta3D_layers = TFEfficientFormerMeta3DLayers(config, name="meta3D_layers")
713
+
714
+ def call(
715
+ self, hidden_states: tf.Tensor, output_attentions: bool = False, training: bool = False
716
+ ) -> Tuple[tf.Tensor]:
717
+ hidden_states = self.meta4D_layers(hidden_states=hidden_states, training=training)
718
+ hidden_states = self.flat(hidden_states=hidden_states)
719
+ hidden_states = self.meta3D_layers(
720
+ hidden_states=hidden_states, output_attentions=output_attentions, training=training
721
+ )
722
+
723
+ return hidden_states
724
+
725
+ def build(self, input_shape=None):
726
+ if self.built:
727
+ return
728
+ self.built = True
729
+ if getattr(self, "meta4D_layers", None) is not None:
730
+ with tf.name_scope(self.meta4D_layers.name):
731
+ self.meta4D_layers.build(None)
732
+ if getattr(self, "flat", None) is not None:
733
+ with tf.name_scope(self.flat.name):
734
+ self.flat.build(None)
735
+ if getattr(self, "meta3D_layers", None) is not None:
736
+ with tf.name_scope(self.meta3D_layers.name):
737
+ self.meta3D_layers.build(None)
738
+
739
+
740
+ class TFEfficientFormerEncoder(tf.keras.layers.Layer):
741
+ def __init__(self, config: EfficientFormerConfig, **kwargs):
742
+ super().__init__(**kwargs)
743
+
744
+ self.config = config
745
+ num_intermediate_stages = len(config.depths) - 1
746
+ downsamples = [
747
+ config.downsamples[i] or config.hidden_sizes[i] != config.hidden_sizes[i + 1]
748
+ for i in range(num_intermediate_stages)
749
+ ]
750
+
751
+ intermediate_stages = []
752
+ layer_count = -1
753
+ for i in range(num_intermediate_stages):
754
+ layer_count += 1
755
+ intermediate_stages.append(
756
+ TFEfficientFormerIntermediateStage(config, i, name=f"intermediate_stages.{layer_count}")
757
+ )
758
+ if downsamples[i]:
759
+ layer_count += 1
760
+ intermediate_stages.append(
761
+ TFEfficientFormerPatchEmbeddings(
762
+ config,
763
+ config.hidden_sizes[i],
764
+ config.hidden_sizes[i + 1],
765
+ name=f"intermediate_stages.{layer_count}",
766
+ )
767
+ )
768
+ self.intermediate_stages = intermediate_stages
769
+ self.last_stage = TFEfficientFormerLastStage(config, name="last_stage")
770
+
771
+ def call(
772
+ self,
773
+ hidden_states: tf.Tensor,
774
+ output_hidden_states: bool,
775
+ output_attentions: bool,
776
+ return_dict: bool,
777
+ training: bool = False,
778
+ ) -> TFBaseModelOutput:
779
+ all_hidden_states = () if output_hidden_states else None
780
+ all_self_attentions = () if output_attentions else None
781
+
782
+ if output_hidden_states:
783
+ all_hidden_states = all_hidden_states + (hidden_states,)
784
+
785
+ for layer_module in self.intermediate_stages:
786
+ hidden_states = layer_module(hidden_states, training=training)
787
+
788
+ if output_hidden_states:
789
+ all_hidden_states = all_hidden_states + (hidden_states,)
790
+
791
+ layer_output = self.last_stage(hidden_states, output_attentions=output_attentions, training=training)
792
+
793
+ if output_attentions:
794
+ all_self_attentions = all_self_attentions + layer_output[1:]
795
+
796
+ if output_hidden_states:
797
+ all_hidden_states = all_hidden_states + (layer_output[0],)
798
+
799
+ if not return_dict:
800
+ return tuple(v for v in [layer_output[0], all_hidden_states, all_self_attentions] if v is not None)
801
+
802
+ return TFBaseModelOutput(
803
+ last_hidden_state=layer_output[0],
804
+ hidden_states=all_hidden_states,
805
+ attentions=all_self_attentions,
806
+ )
807
+
808
+ def build(self, input_shape=None):
809
+ if self.built:
810
+ return
811
+ self.built = True
812
+ if getattr(self, "last_stage", None) is not None:
813
+ with tf.name_scope(self.last_stage.name):
814
+ self.last_stage.build(None)
815
+ for layer in self.intermediate_stages:
816
+ with tf.name_scope(layer.name):
817
+ layer.build(None)
818
+
819
+
820
+ @keras_serializable
821
+ class TFEfficientFormerMainLayer(tf.keras.layers.Layer):
822
+ config_class = EfficientFormerConfig
823
+
824
+ def __init__(self, config: EfficientFormerConfig, **kwargs) -> None:
825
+ super().__init__(**kwargs)
826
+ self.config = config
827
+
828
+ self.patch_embed = TFEfficientFormerConvStem(config, config.hidden_sizes[0], name="patch_embed")
829
+ self.encoder = TFEfficientFormerEncoder(config, name="encoder")
830
+ self.layernorm = tf.keras.layers.LayerNormalization(epsilon=config.layer_norm_eps, name="layernorm")
831
+
832
+ @unpack_inputs
833
+ def call(
834
+ self,
835
+ pixel_values: Optional[tf.Tensor] = None,
836
+ output_attentions: Optional[tf.Tensor] = None,
837
+ output_hidden_states: Optional[tf.Tensor] = None,
838
+ return_dict: Optional[bool] = None,
839
+ training: bool = False,
840
+ ) -> Union[TFBaseModelOutput, Tuple[tf.Tensor, ...]]:
841
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
842
+
843
+ output_hidden_states = (
844
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
845
+ )
846
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
847
+
848
+ if pixel_values is None:
849
+ raise ValueError("You have to specify pixel_values")
850
+
851
+ # When running on CPU, tf.keras.layers.Conv2D and tf.keras.layers.AveragePool2D do not
852
+ # support channels first NCHW format. A number of blocks contain both.
853
+ # So change the input format from (batch_size, num_channels, height, width) to
854
+ # (batch_size, height, width, num_channels) here.
855
+ # shape = (batch_size, in_height, in_width, in_channels=num_channels)
856
+ pixel_values = tf.transpose(pixel_values, perm=(0, 2, 3, 1))
857
+ embedding_output = self.patch_embed(pixel_values, training=training)
858
+
859
+ encoder_outputs = self.encoder(
860
+ hidden_states=embedding_output,
861
+ output_attentions=output_attentions,
862
+ output_hidden_states=output_hidden_states,
863
+ return_dict=return_dict,
864
+ training=training,
865
+ )
866
+
867
+ sequence_output = encoder_outputs[0]
868
+ sequence_output = self.layernorm(sequence_output, training=training)
869
+
870
+ # Change the hidden states from (batch_size, height, width, num_channels) to
871
+ # (batch_size, num_channels, height, width).
872
+ # The hidden states are in (batch_size, height, width, num_channels)
873
+ # shape after all stages except the MB3D blocks.
874
+ if output_hidden_states:
875
+ hidden_states = tuple([tf.transpose(h, perm=(0, 3, 1, 2)) for h in encoder_outputs[1][:-1]]) + (
876
+ encoder_outputs[1][-1],
877
+ )
878
+
879
+ if not return_dict:
880
+ head_outputs = (sequence_output,)
881
+ return head_outputs + encoder_outputs[1:]
882
+
883
+ return TFBaseModelOutput(
884
+ last_hidden_state=sequence_output,
885
+ hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states,
886
+ attentions=encoder_outputs.attentions,
887
+ )
888
+
889
+ def build(self, input_shape=None):
890
+ if self.built:
891
+ return
892
+ self.built = True
893
+ if getattr(self, "patch_embed", None) is not None:
894
+ with tf.name_scope(self.patch_embed.name):
895
+ self.patch_embed.build(None)
896
+ if getattr(self, "encoder", None) is not None:
897
+ with tf.name_scope(self.encoder.name):
898
+ self.encoder.build(None)
899
+ if getattr(self, "layernorm", None) is not None:
900
+ with tf.name_scope(self.layernorm.name):
901
+ self.layernorm.build([None, None, self.config.hidden_sizes[-1]])
902
+
903
+
904
+ class TFEfficientFormerPreTrainedModel(TFPreTrainedModel):
905
+ """
906
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
907
+ models.
908
+ """
909
+
910
+ config_class = EfficientFormerConfig
911
+ base_model_prefix = "efficientformer"
912
+ main_input_name = "pixel_values"
913
+
914
+
915
+ EFFICIENTFORMER_START_DOCSTRING = r"""
916
+ This model is a TensorFlow
917
+ [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer). Use it as a regular
918
+ TensorFlow Module and refer to the TensorFlow documentation for all matter related to general usage and behavior.
919
+
920
+
921
+ Parameters:
922
+ config ([`EfficientFormerConfig`]): Model configuration class with all the parameters of the model.
923
+ Initializing with a config file does not load the weights associated with the model, only the
924
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
925
+ """
926
+
927
+ EFFICIENTFORMER_INPUTS_DOCSTRING = r"""
928
+ Args:
929
+ pixel_values ((`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
930
+ Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
931
+ [`EfficientFormerImageProcessor.__call__`] for details.
932
+ output_attentions (`bool`, *optional*):
933
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
934
+ tensors for more detail.
935
+ output_hidden_states (`bool`, *optional*):
936
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
937
+ more detail.
938
+ return_dict (`bool`, *optional*):
939
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
940
+ """
941
+
942
+
943
+ @add_start_docstrings(
944
+ "The bare EfficientFormer Model transformer outputting raw hidden-states without any specific head on top.",
945
+ EFFICIENTFORMER_START_DOCSTRING,
946
+ )
947
+ class TFEfficientFormerModel(TFEfficientFormerPreTrainedModel):
948
+ def __init__(self, config: EfficientFormerConfig, **kwargs) -> None:
949
+ super().__init__(config, **kwargs)
950
+
951
+ self.efficientformer = TFEfficientFormerMainLayer(config, name="efficientformer")
952
+
953
+ @unpack_inputs
954
+ @add_start_docstrings_to_model_forward(EFFICIENTFORMER_INPUTS_DOCSTRING)
955
+ @add_code_sample_docstrings(
956
+ checkpoint=_CHECKPOINT_FOR_DOC,
957
+ output_type=TFBaseModelOutputWithPooling,
958
+ config_class=_CONFIG_FOR_DOC,
959
+ modality="vision",
960
+ expected_output=_EXPECTED_OUTPUT_SHAPE,
961
+ )
962
+ def call(
963
+ self,
964
+ pixel_values: Optional[tf.Tensor] = None,
965
+ output_attentions: Optional[bool] = None,
966
+ output_hidden_states: Optional[bool] = None,
967
+ return_dict: Optional[bool] = None,
968
+ training: bool = False,
969
+ ) -> Union[Tuple, TFBaseModelOutput]:
970
+ outputs = self.efficientformer(
971
+ pixel_values=pixel_values,
972
+ output_attentions=output_attentions,
973
+ output_hidden_states=output_hidden_states,
974
+ return_dict=return_dict,
975
+ training=training,
976
+ )
977
+ return outputs
978
+
979
+ def build(self, input_shape=None):
980
+ if self.built:
981
+ return
982
+ self.built = True
983
+ if getattr(self, "efficientformer", None) is not None:
984
+ with tf.name_scope(self.efficientformer.name):
985
+ self.efficientformer.build(None)
986
+
987
+
988
+ @add_start_docstrings(
989
+ """
990
+ EfficientFormer Model transformer with an image classification head on top of pooled last hidden state, e.g. for
991
+ ImageNet.
992
+ """,
993
+ EFFICIENTFORMER_START_DOCSTRING,
994
+ )
995
+ class TFEfficientFormerForImageClassification(TFEfficientFormerPreTrainedModel, TFSequenceClassificationLoss):
996
+ def __init__(self, config: EfficientFormerConfig):
997
+ super().__init__(config)
998
+
999
+ self.num_labels = config.num_labels
1000
+ self.efficientformer = TFEfficientFormerMainLayer(config, name="efficientformer")
1001
+
1002
+ # Classifier head
1003
+ self.classifier = (
1004
+ tf.keras.layers.Dense(config.num_labels, name="classifier")
1005
+ if config.num_labels > 0
1006
+ else tf.keras.layers.Activation("linear", name="classifier")
1007
+ )
1008
+ self.config = config
1009
+
1010
+ @unpack_inputs
1011
+ @add_start_docstrings_to_model_forward(EFFICIENTFORMER_INPUTS_DOCSTRING)
1012
+ @add_code_sample_docstrings(
1013
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
1014
+ output_type=TFImageClassifierOutput,
1015
+ config_class=_CONFIG_FOR_DOC,
1016
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
1017
+ )
1018
+ def call(
1019
+ self,
1020
+ pixel_values: Optional[tf.Tensor] = None,
1021
+ labels: Optional[tf.Tensor] = None,
1022
+ output_attentions: Optional[bool] = None,
1023
+ output_hidden_states: Optional[bool] = None,
1024
+ return_dict: Optional[bool] = None,
1025
+ training: bool = False,
1026
+ ) -> Union[tf.Tensor, TFImageClassifierOutput]:
1027
+ r"""
1028
+ labels (`tf.Tensor` of shape `(batch_size,)`, *optional*):
1029
+ Labels for computing the image classification/regression loss. Indices should be in `[0, ...,
1030
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1031
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1032
+ """
1033
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1034
+
1035
+ outputs = self.efficientformer(
1036
+ pixel_values=pixel_values,
1037
+ output_attentions=output_attentions,
1038
+ output_hidden_states=output_hidden_states,
1039
+ return_dict=return_dict,
1040
+ training=training,
1041
+ )
1042
+
1043
+ sequence_output = outputs[0]
1044
+
1045
+ logits = self.classifier(tf.reduce_mean(sequence_output, axis=-2))
1046
+
1047
+ loss = None if labels is None else self.hf_compute_loss(labels, logits)
1048
+
1049
+ if not return_dict:
1050
+ output = (logits,) + outputs[1:]
1051
+ return ((loss,) + output) if loss is not None else output
1052
+
1053
+ return TFImageClassifierOutput(
1054
+ loss=loss, logits=logits, hidden_states=outputs.hidden_states, attentions=outputs.attentions
1055
+ )
1056
+
1057
+ def build(self, input_shape=None):
1058
+ if self.built:
1059
+ return
1060
+ self.built = True
1061
+ if getattr(self, "efficientformer", None) is not None:
1062
+ with tf.name_scope(self.efficientformer.name):
1063
+ self.efficientformer.build(None)
1064
+ if getattr(self, "classifier", None) is not None:
1065
+ if hasattr(self.classifier, "name"):
1066
+ with tf.name_scope(self.classifier.name):
1067
+ self.classifier.build([None, None, self.config.hidden_sizes[-1]])
1068
+
1069
+
1070
+ @dataclass
1071
+ class TFEfficientFormerForImageClassificationWithTeacherOutput(ModelOutput):
1072
+ """
1073
+ Args:
1074
+ Output type of [`EfficientFormerForImageClassificationWithTeacher`].
1075
+ logits (`tf.Tensor` of shape `(batch_size, config.num_labels)`):
1076
+ Prediction scores as the average of the cls_logits and distillation logits.
1077
+ cls_logits (`tf.Tensor` of shape `(batch_size, config.num_labels)`):
1078
+ Prediction scores of the classification head (i.e. the linear layer on top of the final hidden state of the
1079
+ class token).
1080
+ distillation_logits (`tf.Tensor` of shape `(batch_size, config.num_labels)`):
1081
+ Prediction scores of the distillation head (i.e. the linear layer on top of the final hidden state of the
1082
+ distillation token).
1083
+ hidden_states (`tuple(tf.Tensor)`, *optional*, returned when `output_hidden_states=True` is passed or when
1084
+ `config.output_hidden_states=True`):
1085
+ Tuple of `tf.Tensor` (one for the output of the embeddings + one for the output of each layer) of shape
1086
+ `(batch_size, sequence_length, hidden_size)`. Hidden-states of the model at the output of each layer plus
1087
+ the initial embedding outputs.
1088
+ attentions (`tuple(tf.Tensor)`, *optional*, returned when `output_attentions=True` is passed or when
1089
+ `config.output_attentions=True`):
1090
+ Tuple of `tf.Tensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,
1091
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
1092
+ the self-attention heads.
1093
+ """
1094
+
1095
+ logits: tf.Tensor = None
1096
+ cls_logits: tf.Tensor = None
1097
+ distillation_logits: tf.Tensor = None
1098
+ hidden_states: Optional[Tuple[tf.Tensor]] = None
1099
+ attentions: Optional[Tuple[tf.Tensor]] = None
1100
+
1101
+
1102
+ @add_start_docstrings(
1103
+ """
1104
+ EfficientFormer Model transformer with image classification heads on top (a linear layer on top of the final hidden
1105
+ state and a linear layer on top of the final hidden state of the distillation token) e.g. for ImageNet.
1106
+
1107
+ .. warning::
1108
+ This model supports inference-only. Fine-tuning with distillation (i.e. with a teacher) is not yet
1109
+ supported.
1110
+ """,
1111
+ EFFICIENTFORMER_START_DOCSTRING,
1112
+ )
1113
+ class TFEfficientFormerForImageClassificationWithTeacher(TFEfficientFormerPreTrainedModel):
1114
+ def __init__(self, config: EfficientFormerConfig) -> None:
1115
+ super().__init__(config)
1116
+
1117
+ self.num_labels = config.num_labels
1118
+ self.efficientformer = TFEfficientFormerMainLayer(config, name="efficientformer")
1119
+
1120
+ # Classifier heads
1121
+ self.classifier = (
1122
+ tf.keras.layers.Dense(config.num_labels, name="classifier")
1123
+ if config.num_labels > 0
1124
+ else tf.keras.layers.Activation("linear", name="classifier")
1125
+ )
1126
+ self.distillation_classifier = (
1127
+ tf.keras.layers.Dense(config.num_labels, name="distillation_classifier")
1128
+ if config.num_labels > 0
1129
+ else tf.keras.layers.Activation("linear", name="distillation_classifier")
1130
+ )
1131
+
1132
+ @unpack_inputs
1133
+ @add_start_docstrings_to_model_forward(EFFICIENTFORMER_INPUTS_DOCSTRING)
1134
+ @add_code_sample_docstrings(
1135
+ checkpoint=_IMAGE_CLASS_CHECKPOINT,
1136
+ output_type=TFEfficientFormerForImageClassificationWithTeacherOutput,
1137
+ config_class=_CONFIG_FOR_DOC,
1138
+ expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,
1139
+ )
1140
+ def call(
1141
+ self,
1142
+ pixel_values: Optional[tf.Tensor] = None,
1143
+ output_attentions: Optional[bool] = None,
1144
+ output_hidden_states: Optional[bool] = None,
1145
+ return_dict: Optional[bool] = None,
1146
+ training: bool = False,
1147
+ ) -> Union[tuple, TFEfficientFormerForImageClassificationWithTeacherOutput]:
1148
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1149
+
1150
+ if training:
1151
+ raise Exception(
1152
+ "This model supports inference-only. Fine-tuning with distillation (i.e. with a teacher) is not yet supported."
1153
+ )
1154
+
1155
+ outputs = self.efficientformer(
1156
+ pixel_values=pixel_values,
1157
+ output_attentions=output_attentions,
1158
+ output_hidden_states=output_hidden_states,
1159
+ return_dict=return_dict,
1160
+ training=training,
1161
+ )
1162
+
1163
+ sequence_output = outputs[0]
1164
+
1165
+ cls_logits = self.classifier(tf.reduce_mean(sequence_output, axis=-2))
1166
+ distillation_logits = self.distillation_classifier(tf.reduce_mean(sequence_output, axis=-2))
1167
+ logits = (cls_logits + distillation_logits) / 2
1168
+
1169
+ if not return_dict:
1170
+ output = (logits, cls_logits, distillation_logits) + outputs[1:]
1171
+ return output
1172
+
1173
+ return TFEfficientFormerForImageClassificationWithTeacherOutput(
1174
+ logits=logits,
1175
+ cls_logits=cls_logits,
1176
+ distillation_logits=distillation_logits,
1177
+ hidden_states=outputs.hidden_states,
1178
+ attentions=outputs.attentions,
1179
+ )
1180
+
1181
+ def build(self, input_shape=None):
1182
+ if self.built:
1183
+ return
1184
+ self.built = True
1185
+ if getattr(self, "efficientformer", None) is not None:
1186
+ with tf.name_scope(self.efficientformer.name):
1187
+ self.efficientformer.build(None)
1188
+ if getattr(self, "classifier", None) is not None:
1189
+ if hasattr(self.classifier, "name"):
1190
+ with tf.name_scope(self.classifier.name):
1191
+ self.classifier.build([None, None, self.config.hidden_sizes[-1]])
1192
+ if getattr(self, "distillation_classifier", None) is not None:
1193
+ if hasattr(self.distillation_classifier, "name"):
1194
+ with tf.name_scope(self.distillation_classifier.name):
1195
+ self.distillation_classifier.build([None, None, self.config.hidden_sizes[-1]])
SupplementaryMaterial_Code/transformers-4.37.2/models/efficientnet/__init__.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # flake8: noqa
2
+ # There's no way to ignore "F401 '...' imported but unused" warnings in this
3
+ # module, but to preserve other warnings. So, don't check this module at all.
4
+
5
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
6
+ #
7
+ # Licensed under the Apache License, Version 2.0 (the "License");
8
+ # you may not use this file except in compliance with the License.
9
+ # You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+ from typing import TYPE_CHECKING
19
+
20
+ # rely on isort to merge the imports
21
+ from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
22
+
23
+
24
+ _import_structure = {
25
+ "configuration_efficientnet": [
26
+ "EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP",
27
+ "EfficientNetConfig",
28
+ "EfficientNetOnnxConfig",
29
+ ]
30
+ }
31
+
32
+ try:
33
+ if not is_vision_available():
34
+ raise OptionalDependencyNotAvailable()
35
+ except OptionalDependencyNotAvailable:
36
+ pass
37
+ else:
38
+ _import_structure["image_processing_efficientnet"] = ["EfficientNetImageProcessor"]
39
+
40
+ try:
41
+ if not is_torch_available():
42
+ raise OptionalDependencyNotAvailable()
43
+ except OptionalDependencyNotAvailable:
44
+ pass
45
+ else:
46
+ _import_structure["modeling_efficientnet"] = [
47
+ "EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST",
48
+ "EfficientNetForImageClassification",
49
+ "EfficientNetModel",
50
+ "EfficientNetPreTrainedModel",
51
+ ]
52
+
53
+ if TYPE_CHECKING:
54
+ from .configuration_efficientnet import (
55
+ EFFICIENTNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
56
+ EfficientNetConfig,
57
+ EfficientNetOnnxConfig,
58
+ )
59
+
60
+ try:
61
+ if not is_vision_available():
62
+ raise OptionalDependencyNotAvailable()
63
+ except OptionalDependencyNotAvailable:
64
+ pass
65
+ else:
66
+ from .image_processing_efficientnet import EfficientNetImageProcessor
67
+
68
+ try:
69
+ if not is_torch_available():
70
+ raise OptionalDependencyNotAvailable()
71
+ except OptionalDependencyNotAvailable:
72
+ pass
73
+ else:
74
+ from .modeling_efficientnet import (
75
+ EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST,
76
+ EfficientNetForImageClassification,
77
+ EfficientNetModel,
78
+ EfficientNetPreTrainedModel,
79
+ )
80
+
81
+ else:
82
+ import sys
83
+
84
+ sys.modules[__name__] = _LazyModule(__name__, globals()["__file__"], _import_structure)