ZhengyangZhang commited on
Commit
ef9f3b2
·
verified ·
1 Parent(s): 44361f6

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. lib/python3.12/site-packages/transformers/models/blenderbot_small/__init__.py +31 -0
  2. lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/__init__.cpython-312.pyc +0 -0
  3. lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/configuration_blenderbot_small.cpython-312.pyc +0 -0
  4. lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_blenderbot_small.cpython-312.pyc +0 -0
  5. lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_flax_blenderbot_small.cpython-312.pyc +0 -0
  6. lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_tf_blenderbot_small.cpython-312.pyc +0 -0
  7. lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small.cpython-312.pyc +0 -0
  8. lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small_fast.cpython-312.pyc +0 -0
  9. lib/python3.12/site-packages/transformers/models/blenderbot_small/configuration_blenderbot_small.py +390 -0
  10. lib/python3.12/site-packages/transformers/models/blenderbot_small/modeling_blenderbot_small.py +1511 -0
  11. lib/python3.12/site-packages/transformers/models/blenderbot_small/modeling_flax_blenderbot_small.py +1528 -0
  12. lib/python3.12/site-packages/transformers/models/blenderbot_small/modeling_tf_blenderbot_small.py +1528 -0
  13. lib/python3.12/site-packages/transformers/models/blenderbot_small/tokenization_blenderbot_small.py +222 -0
  14. lib/python3.12/site-packages/transformers/models/blenderbot_small/tokenization_blenderbot_small_fast.py +103 -0
  15. lib/python3.12/site-packages/transformers/models/byt5/__init__.py +26 -0
  16. lib/python3.12/site-packages/transformers/models/byt5/__pycache__/__init__.cpython-312.pyc +0 -0
  17. lib/python3.12/site-packages/transformers/models/byt5/__pycache__/tokenization_byt5.cpython-312.pyc +0 -0
  18. lib/python3.12/site-packages/transformers/models/byt5/tokenization_byt5.py +236 -0
  19. lib/python3.12/site-packages/transformers/models/clipseg/__init__.py +28 -0
  20. lib/python3.12/site-packages/transformers/models/clipseg/__pycache__/__init__.cpython-312.pyc +0 -0
  21. lib/python3.12/site-packages/transformers/models/clipseg/__pycache__/configuration_clipseg.cpython-312.pyc +0 -0
  22. lib/python3.12/site-packages/transformers/models/clipseg/__pycache__/modeling_clipseg.cpython-312.pyc +0 -0
  23. lib/python3.12/site-packages/transformers/models/clipseg/__pycache__/processing_clipseg.cpython-312.pyc +0 -0
  24. lib/python3.12/site-packages/transformers/models/clipseg/configuration_clipseg.py +396 -0
  25. lib/python3.12/site-packages/transformers/models/clipseg/modeling_clipseg.py +1522 -0
  26. lib/python3.12/site-packages/transformers/models/clipseg/processing_clipseg.py +164 -0
  27. lib/python3.12/site-packages/transformers/models/codegen/__init__.py +29 -0
  28. lib/python3.12/site-packages/transformers/models/codegen/__pycache__/__init__.cpython-312.pyc +0 -0
  29. lib/python3.12/site-packages/transformers/models/codegen/__pycache__/configuration_codegen.cpython-312.pyc +0 -0
  30. lib/python3.12/site-packages/transformers/models/codegen/__pycache__/modeling_codegen.cpython-312.pyc +0 -0
  31. lib/python3.12/site-packages/transformers/models/codegen/__pycache__/tokenization_codegen.cpython-312.pyc +0 -0
  32. lib/python3.12/site-packages/transformers/models/codegen/__pycache__/tokenization_codegen_fast.cpython-312.pyc +0 -0
  33. lib/python3.12/site-packages/transformers/models/codegen/configuration_codegen.py +230 -0
  34. lib/python3.12/site-packages/transformers/models/codegen/modeling_codegen.py +835 -0
  35. lib/python3.12/site-packages/transformers/models/codegen/tokenization_codegen.py +419 -0
  36. lib/python3.12/site-packages/transformers/models/codegen/tokenization_codegen_fast.py +265 -0
  37. lib/python3.12/site-packages/transformers/models/conditional_detr/__init__.py +29 -0
  38. lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/__init__.cpython-312.pyc +0 -0
  39. lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/configuration_conditional_detr.cpython-312.pyc +0 -0
  40. lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/feature_extraction_conditional_detr.cpython-312.pyc +0 -0
  41. lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/image_processing_conditional_detr.cpython-312.pyc +0 -0
  42. lib/python3.12/site-packages/transformers/models/conditional_detr/configuration_conditional_detr.py +278 -0
  43. lib/python3.12/site-packages/transformers/models/conditional_detr/feature_extraction_conditional_detr.py +46 -0
  44. lib/python3.12/site-packages/transformers/models/conditional_detr/image_processing_conditional_detr.py +1855 -0
  45. lib/python3.12/site-packages/transformers/models/conditional_detr/modeling_conditional_detr.py +0 -0
  46. lib/python3.12/site-packages/transformers/models/convnext/__init__.py +31 -0
  47. lib/python3.12/site-packages/transformers/models/convnext/__pycache__/__init__.cpython-312.pyc +0 -0
  48. lib/python3.12/site-packages/transformers/models/convnext/__pycache__/configuration_convnext.cpython-312.pyc +0 -0
  49. lib/python3.12/site-packages/transformers/models/convnext/__pycache__/feature_extraction_convnext.cpython-312.pyc +0 -0
  50. lib/python3.12/site-packages/transformers/models/convnext/__pycache__/image_processing_convnext.cpython-312.pyc +0 -0
lib/python3.12/site-packages/transformers/models/blenderbot_small/__init__.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_blenderbot_small import *
22
+ from .modeling_blenderbot_small import *
23
+ from .modeling_flax_blenderbot_small import *
24
+ from .modeling_tf_blenderbot_small import *
25
+ from .tokenization_blenderbot_small import *
26
+ from .tokenization_blenderbot_small_fast import *
27
+ else:
28
+ import sys
29
+
30
+ _file = globals()["__file__"]
31
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (878 Bytes). View file
 
lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/configuration_blenderbot_small.cpython-312.pyc ADDED
Binary file (16.1 kB). View file
 
lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_blenderbot_small.cpython-312.pyc ADDED
Binary file (73.2 kB). View file
 
lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_flax_blenderbot_small.cpython-312.pyc ADDED
Binary file (66.7 kB). View file
 
lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/modeling_tf_blenderbot_small.cpython-312.pyc ADDED
Binary file (74.4 kB). View file
 
lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small.cpython-312.pyc ADDED
Binary file (11.1 kB). View file
 
lib/python3.12/site-packages/transformers/models/blenderbot_small/__pycache__/tokenization_blenderbot_small_fast.cpython-312.pyc ADDED
Binary file (3.48 kB). View file
 
lib/python3.12/site-packages/transformers/models/blenderbot_small/configuration_blenderbot_small.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Facebook, Inc. 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
+ """BlenderbotSmall model configuration"""
16
+
17
+ from collections import OrderedDict
18
+ from typing import Any, Mapping, Optional
19
+
20
+ from ... import PreTrainedTokenizer
21
+ from ...configuration_utils import PretrainedConfig
22
+ from ...file_utils import TensorType, is_torch_available
23
+ from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeq2SeqConfigWithPast
24
+ from ...onnx.utils import compute_effective_axis_dimension
25
+ from ...utils import logging
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+
31
+ class BlenderbotSmallConfig(PretrainedConfig):
32
+ r"""
33
+ This is the configuration class to store the configuration of a [`BlenderbotSmallModel`]. It is used to instantiate
34
+ an BlenderbotSmall model according to the specified arguments, defining the model architecture. Instantiating a
35
+ configuration with the defaults will yield a similar configuration to that of the BlenderbotSmall
36
+ [facebook/blenderbot_small-90M](https://huggingface.co/facebook/blenderbot_small-90M) architecture.
37
+
38
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
39
+ documentation from [`PretrainedConfig`] for more information.
40
+
41
+
42
+ Args:
43
+ vocab_size (`int`, *optional*, defaults to 50265):
44
+ Vocabulary size of the BlenderbotSmall model. Defines the number of different tokens that can be
45
+ represented by the `inputs_ids` passed when calling [`BlenderbotSmallModel`] or [`TFBlenderbotSmallModel`].
46
+ d_model (`int`, *optional*, defaults to 512):
47
+ Dimensionality of the layers and the pooler layer.
48
+ encoder_layers (`int`, *optional*, defaults to 8):
49
+ Number of encoder layers.
50
+ decoder_layers (`int`, *optional*, defaults to 8):
51
+ Number of decoder layers.
52
+ encoder_attention_heads (`int`, *optional*, defaults to 16):
53
+ Number of attention heads for each attention layer in the Transformer encoder.
54
+ decoder_attention_heads (`int`, *optional*, defaults to 16):
55
+ Number of attention heads for each attention layer in the Transformer decoder.
56
+ decoder_ffn_dim (`int`, *optional*, defaults to 2048):
57
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
58
+ encoder_ffn_dim (`int`, *optional*, defaults to 2048):
59
+ Dimensionality of the "intermediate" (often named feed-forward) layer in decoder.
60
+ activation_function (`str` or `function`, *optional*, defaults to `"gelu"`):
61
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
62
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
63
+ dropout (`float`, *optional*, defaults to 0.1):
64
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
65
+ attention_dropout (`float`, *optional*, defaults to 0.0):
66
+ The dropout ratio for the attention probabilities.
67
+ activation_dropout (`float`, *optional*, defaults to 0.0):
68
+ The dropout ratio for activations inside the fully connected layer.
69
+ max_position_embeddings (`int`, *optional*, defaults to 512):
70
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
71
+ just in case (e.g., 512 or 1024 or 2048).
72
+ init_std (`float`, *optional*, defaults to 0.02):
73
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
74
+ encoder_layerdrop (`float`, *optional*, defaults to 0.0):
75
+ The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
76
+ for more details.
77
+ decoder_layerdrop (`float`, *optional*, defaults to 0.0):
78
+ The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
79
+ for more details.
80
+ scale_embedding (`bool`, *optional*, defaults to `False`):
81
+ Scale embeddings by diving by sqrt(d_model).
82
+ use_cache (`bool`, *optional*, defaults to `True`):
83
+ Whether or not the model should return the last key/values attentions (not used by all models)
84
+ forced_eos_token_id (`int`, *optional*, defaults to 2):
85
+ The id of the token to force as the last generated token when `max_length` is reached. Usually set to
86
+ `eos_token_id`.
87
+
88
+ Example:
89
+
90
+ ```python
91
+ >>> from transformers import BlenderbotSmallConfig, BlenderbotSmallModel
92
+
93
+ >>> # Initializing a BlenderbotSmall facebook/blenderbot_small-90M style configuration
94
+ >>> configuration = BlenderbotSmallConfig()
95
+
96
+ >>> # Initializing a model (with random weights) from the facebook/blenderbot_small-90M style configuration
97
+ >>> model = BlenderbotSmallModel(configuration)
98
+
99
+ >>> # Accessing the model configuration
100
+ >>> configuration = model.config
101
+ ```"""
102
+
103
+ model_type = "blenderbot-small"
104
+ keys_to_ignore_at_inference = ["past_key_values"]
105
+ attribute_map = {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
106
+
107
+ def __init__(
108
+ self,
109
+ vocab_size=50265,
110
+ max_position_embeddings=512,
111
+ encoder_layers=8,
112
+ encoder_ffn_dim=2048,
113
+ encoder_attention_heads=16,
114
+ decoder_layers=8,
115
+ decoder_ffn_dim=2048,
116
+ decoder_attention_heads=16,
117
+ encoder_layerdrop=0.0,
118
+ decoder_layerdrop=0.0,
119
+ use_cache=True,
120
+ is_encoder_decoder=True,
121
+ activation_function="gelu",
122
+ d_model=512,
123
+ dropout=0.1,
124
+ attention_dropout=0.0,
125
+ activation_dropout=0.0,
126
+ init_std=0.02,
127
+ decoder_start_token_id=1,
128
+ scale_embedding=False,
129
+ pad_token_id=0,
130
+ bos_token_id=1,
131
+ eos_token_id=2,
132
+ forced_eos_token_id=2,
133
+ **kwargs,
134
+ ):
135
+ self.vocab_size = vocab_size
136
+ self.max_position_embeddings = max_position_embeddings
137
+ self.d_model = d_model
138
+ self.encoder_ffn_dim = encoder_ffn_dim
139
+ self.encoder_layers = encoder_layers
140
+ self.encoder_attention_heads = encoder_attention_heads
141
+ self.decoder_ffn_dim = decoder_ffn_dim
142
+ self.decoder_layers = decoder_layers
143
+ self.decoder_attention_heads = decoder_attention_heads
144
+ self.dropout = dropout
145
+ self.attention_dropout = attention_dropout
146
+ self.activation_dropout = activation_dropout
147
+ self.activation_function = activation_function
148
+ self.init_std = init_std
149
+ self.encoder_layerdrop = encoder_layerdrop
150
+ self.decoder_layerdrop = decoder_layerdrop
151
+ self.use_cache = use_cache
152
+ self.num_hidden_layers = encoder_layers
153
+ self.scale_embedding = scale_embedding # scale factor will be sqrt(d_model) if True
154
+
155
+ super().__init__(
156
+ pad_token_id=pad_token_id,
157
+ bos_token_id=bos_token_id,
158
+ eos_token_id=eos_token_id,
159
+ is_encoder_decoder=is_encoder_decoder,
160
+ decoder_start_token_id=decoder_start_token_id,
161
+ forced_eos_token_id=forced_eos_token_id,
162
+ **kwargs,
163
+ )
164
+
165
+
166
+ # Copied from transformers.models.bart.configuration_bart.BartOnnxConfig
167
+ class BlenderbotSmallOnnxConfig(OnnxSeq2SeqConfigWithPast):
168
+ @property
169
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
170
+ if self.task in ["default", "seq2seq-lm"]:
171
+ common_inputs = OrderedDict(
172
+ [
173
+ ("input_ids", {0: "batch", 1: "encoder_sequence"}),
174
+ ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
175
+ ]
176
+ )
177
+
178
+ if self.use_past:
179
+ common_inputs["decoder_input_ids"] = {0: "batch"}
180
+ common_inputs["decoder_attention_mask"] = {0: "batch", 1: "past_decoder_sequence + sequence"}
181
+ else:
182
+ common_inputs["decoder_input_ids"] = {0: "batch", 1: "decoder_sequence"}
183
+ common_inputs["decoder_attention_mask"] = {0: "batch", 1: "decoder_sequence"}
184
+
185
+ if self.use_past:
186
+ self.fill_with_past_key_values_(common_inputs, direction="inputs")
187
+ elif self.task == "causal-lm":
188
+ # TODO: figure this case out.
189
+ common_inputs = OrderedDict(
190
+ [
191
+ ("input_ids", {0: "batch", 1: "encoder_sequence"}),
192
+ ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
193
+ ]
194
+ )
195
+ if self.use_past:
196
+ num_encoder_layers, _ = self.num_layers
197
+ for i in range(num_encoder_layers):
198
+ common_inputs[f"past_key_values.{i}.key"] = {0: "batch", 2: "past_sequence + sequence"}
199
+ common_inputs[f"past_key_values.{i}.value"] = {0: "batch", 2: "past_sequence + sequence"}
200
+ else:
201
+ common_inputs = OrderedDict(
202
+ [
203
+ ("input_ids", {0: "batch", 1: "encoder_sequence"}),
204
+ ("attention_mask", {0: "batch", 1: "encoder_sequence"}),
205
+ ("decoder_input_ids", {0: "batch", 1: "decoder_sequence"}),
206
+ ("decoder_attention_mask", {0: "batch", 1: "decoder_sequence"}),
207
+ ]
208
+ )
209
+
210
+ return common_inputs
211
+
212
+ @property
213
+ def outputs(self) -> Mapping[str, Mapping[int, str]]:
214
+ if self.task in ["default", "seq2seq-lm"]:
215
+ common_outputs = super().outputs
216
+ else:
217
+ common_outputs = super(OnnxConfigWithPast, self).outputs
218
+ if self.use_past:
219
+ num_encoder_layers, _ = self.num_layers
220
+ for i in range(num_encoder_layers):
221
+ common_outputs[f"present.{i}.key"] = {0: "batch", 2: "past_sequence + sequence"}
222
+ common_outputs[f"present.{i}.value"] = {0: "batch", 2: "past_sequence + sequence"}
223
+ return common_outputs
224
+
225
+ def _generate_dummy_inputs_for_default_and_seq2seq_lm(
226
+ self,
227
+ tokenizer: PreTrainedTokenizer,
228
+ batch_size: int = -1,
229
+ seq_length: int = -1,
230
+ is_pair: bool = False,
231
+ framework: Optional[TensorType] = None,
232
+ ) -> Mapping[str, Any]:
233
+ encoder_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
234
+ tokenizer, batch_size, seq_length, is_pair, framework
235
+ )
236
+
237
+ # Generate decoder inputs
238
+ decoder_seq_length = seq_length if not self.use_past else 1
239
+ decoder_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
240
+ tokenizer, batch_size, decoder_seq_length, is_pair, framework
241
+ )
242
+ decoder_inputs = {f"decoder_{name}": tensor for name, tensor in decoder_inputs.items()}
243
+ common_inputs = dict(**encoder_inputs, **decoder_inputs)
244
+
245
+ if self.use_past:
246
+ if not is_torch_available():
247
+ raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
248
+ else:
249
+ import torch
250
+ batch, encoder_seq_length = common_inputs["input_ids"].shape
251
+ decoder_seq_length = common_inputs["decoder_input_ids"].shape[1]
252
+ num_encoder_attention_heads, num_decoder_attention_heads = self.num_attention_heads
253
+ encoder_shape = (
254
+ batch,
255
+ num_encoder_attention_heads,
256
+ encoder_seq_length,
257
+ self._config.hidden_size // num_encoder_attention_heads,
258
+ )
259
+ decoder_past_length = decoder_seq_length + 3
260
+ decoder_shape = (
261
+ batch,
262
+ num_decoder_attention_heads,
263
+ decoder_past_length,
264
+ self._config.hidden_size // num_decoder_attention_heads,
265
+ )
266
+
267
+ common_inputs["decoder_attention_mask"] = torch.cat(
268
+ [common_inputs["decoder_attention_mask"], torch.ones(batch, decoder_past_length)], dim=1
269
+ )
270
+
271
+ common_inputs["past_key_values"] = []
272
+ # If the number of encoder and decoder layers are present in the model configuration, both are considered
273
+ num_encoder_layers, num_decoder_layers = self.num_layers
274
+ min_num_layers = min(num_encoder_layers, num_decoder_layers)
275
+ max_num_layers = max(num_encoder_layers, num_decoder_layers) - min_num_layers
276
+ remaining_side_name = "encoder" if num_encoder_layers > num_decoder_layers else "decoder"
277
+
278
+ for _ in range(min_num_layers):
279
+ common_inputs["past_key_values"].append(
280
+ (
281
+ torch.zeros(decoder_shape),
282
+ torch.zeros(decoder_shape),
283
+ torch.zeros(encoder_shape),
284
+ torch.zeros(encoder_shape),
285
+ )
286
+ )
287
+ # TODO: test this.
288
+ shape = encoder_shape if remaining_side_name == "encoder" else decoder_shape
289
+ for _ in range(min_num_layers, max_num_layers):
290
+ common_inputs["past_key_values"].append((torch.zeros(shape), torch.zeros(shape)))
291
+ return common_inputs
292
+
293
+ def _generate_dummy_inputs_for_causal_lm(
294
+ self,
295
+ tokenizer: PreTrainedTokenizer,
296
+ batch_size: int = -1,
297
+ seq_length: int = -1,
298
+ is_pair: bool = False,
299
+ framework: Optional[TensorType] = None,
300
+ ) -> Mapping[str, Any]:
301
+ common_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
302
+ tokenizer, batch_size, seq_length, is_pair, framework
303
+ )
304
+
305
+ if self.use_past:
306
+ if not is_torch_available():
307
+ raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
308
+ else:
309
+ import torch
310
+ batch, seqlen = common_inputs["input_ids"].shape
311
+ # Not using the same length for past_key_values
312
+ past_key_values_length = seqlen + 2
313
+ num_encoder_layers, _ = self.num_layers
314
+ num_encoder_attention_heads, _ = self.num_attention_heads
315
+ past_shape = (
316
+ batch,
317
+ num_encoder_attention_heads,
318
+ past_key_values_length,
319
+ self._config.hidden_size // num_encoder_attention_heads,
320
+ )
321
+
322
+ mask_dtype = common_inputs["attention_mask"].dtype
323
+ common_inputs["attention_mask"] = torch.cat(
324
+ [common_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
325
+ )
326
+ common_inputs["past_key_values"] = [
327
+ (torch.zeros(past_shape), torch.zeros(past_shape)) for _ in range(num_encoder_layers)
328
+ ]
329
+ return common_inputs
330
+
331
+ def _generate_dummy_inputs_for_sequence_classification_and_question_answering(
332
+ self,
333
+ tokenizer: PreTrainedTokenizer,
334
+ batch_size: int = -1,
335
+ seq_length: int = -1,
336
+ is_pair: bool = False,
337
+ framework: Optional[TensorType] = None,
338
+ ) -> Mapping[str, Any]:
339
+ # Copied from OnnxConfig.generate_dummy_inputs
340
+ # Did not use super(OnnxConfigWithPast, self).generate_dummy_inputs for code clarity.
341
+ # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX
342
+ batch_size = compute_effective_axis_dimension(
343
+ batch_size, fixed_dimension=OnnxConfig.default_fixed_batch, num_token_to_add=0
344
+ )
345
+
346
+ # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
347
+ token_to_add = tokenizer.num_special_tokens_to_add(is_pair)
348
+ seq_length = compute_effective_axis_dimension(
349
+ seq_length, fixed_dimension=OnnxConfig.default_fixed_sequence, num_token_to_add=token_to_add
350
+ )
351
+
352
+ # Generate dummy inputs according to compute batch and sequence
353
+ dummy_input = [" ".join([tokenizer.unk_token]) * seq_length] * batch_size
354
+ common_inputs = dict(tokenizer(dummy_input, return_tensors=framework))
355
+ return common_inputs
356
+
357
+ def generate_dummy_inputs(
358
+ self,
359
+ tokenizer: PreTrainedTokenizer,
360
+ batch_size: int = -1,
361
+ seq_length: int = -1,
362
+ is_pair: bool = False,
363
+ framework: Optional[TensorType] = None,
364
+ ) -> Mapping[str, Any]:
365
+ if self.task in ["default", "seq2seq-lm"]:
366
+ common_inputs = self._generate_dummy_inputs_for_default_and_seq2seq_lm(
367
+ tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
368
+ )
369
+
370
+ elif self.task == "causal-lm":
371
+ common_inputs = self._generate_dummy_inputs_for_causal_lm(
372
+ tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
373
+ )
374
+ else:
375
+ common_inputs = self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
376
+ tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
377
+ )
378
+
379
+ return common_inputs
380
+
381
+ def _flatten_past_key_values_(self, flattened_output, name, idx, t):
382
+ if self.task in ["default", "seq2seq-lm"]:
383
+ flattened_output = super()._flatten_past_key_values_(flattened_output, name, idx, t)
384
+ else:
385
+ flattened_output = super(OnnxSeq2SeqConfigWithPast, self)._flatten_past_key_values_(
386
+ flattened_output, name, idx, t
387
+ )
388
+
389
+
390
+ __all__ = ["BlenderbotSmallConfig", "BlenderbotSmallOnnxConfig"]
lib/python3.12/site-packages/transformers/models/blenderbot_small/modeling_blenderbot_small.py ADDED
@@ -0,0 +1,1511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Facebook, Inc. 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 BlenderbotSmall model."""
16
+
17
+ import copy
18
+ import math
19
+ from typing import List, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.utils.checkpoint
23
+ from torch import nn
24
+ from torch.nn import CrossEntropyLoss
25
+
26
+ from ...activations import ACT2FN
27
+ from ...generation import GenerationMixin
28
+ from ...modeling_attn_mask_utils import _prepare_4d_attention_mask, _prepare_4d_causal_attention_mask
29
+ from ...modeling_outputs import (
30
+ BaseModelOutput,
31
+ BaseModelOutputWithPastAndCrossAttentions,
32
+ CausalLMOutputWithCrossAttentions,
33
+ Seq2SeqLMOutput,
34
+ Seq2SeqModelOutput,
35
+ )
36
+ from ...modeling_utils import PreTrainedModel
37
+ from ...utils import (
38
+ add_end_docstrings,
39
+ add_start_docstrings,
40
+ add_start_docstrings_to_model_forward,
41
+ logging,
42
+ replace_return_docstrings,
43
+ )
44
+ from .configuration_blenderbot_small import BlenderbotSmallConfig
45
+
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+ _CONFIG_FOR_DOC = "BlenderbotSmallConfig"
50
+
51
+
52
+ # Copied from transformers.models.bart.modeling_bart.shift_tokens_right
53
+ def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int):
54
+ """
55
+ Shift input ids one token to the right.
56
+ """
57
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
58
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
59
+ shifted_input_ids[:, 0] = decoder_start_token_id
60
+
61
+ if pad_token_id is None:
62
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
63
+ # replace possible -100 values in labels by `pad_token_id`
64
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
65
+
66
+ return shifted_input_ids
67
+
68
+
69
+ # Copied from transformers.models.blenderbot.modeling_blenderbot.BlenderbotLearnedPositionalEmbedding with Blenderbot->BlenderbotSmall
70
+ class BlenderbotSmallLearnedPositionalEmbedding(nn.Embedding):
71
+ """
72
+ This module learns positional embeddings up to a fixed maximum size.
73
+ """
74
+
75
+ def __init__(self, num_embeddings: int, embedding_dim: int):
76
+ super().__init__(num_embeddings, embedding_dim)
77
+
78
+ def forward(self, input_ids_shape: torch.Size, past_key_values_length: int = 0):
79
+ """`input_ids_shape` is expected to be [bsz x seqlen]."""
80
+ bsz, seq_len = input_ids_shape[:2]
81
+ positions = torch.arange(
82
+ past_key_values_length, past_key_values_length + seq_len, dtype=torch.long, device=self.weight.device
83
+ )
84
+ return super().forward(positions)
85
+
86
+
87
+ # Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->BlenderbotSmall
88
+ class BlenderbotSmallAttention(nn.Module):
89
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
90
+
91
+ def __init__(
92
+ self,
93
+ embed_dim: int,
94
+ num_heads: int,
95
+ dropout: float = 0.0,
96
+ is_decoder: bool = False,
97
+ bias: bool = True,
98
+ is_causal: bool = False,
99
+ config: Optional[BlenderbotSmallConfig] = None,
100
+ ):
101
+ super().__init__()
102
+ self.embed_dim = embed_dim
103
+ self.num_heads = num_heads
104
+ self.dropout = dropout
105
+ self.head_dim = embed_dim // num_heads
106
+ self.config = config
107
+
108
+ if (self.head_dim * num_heads) != self.embed_dim:
109
+ raise ValueError(
110
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
111
+ f" and `num_heads`: {num_heads})."
112
+ )
113
+ self.scaling = self.head_dim**-0.5
114
+ self.is_decoder = is_decoder
115
+ self.is_causal = is_causal
116
+
117
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
118
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
119
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
120
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
121
+
122
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
123
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
124
+
125
+ def forward(
126
+ self,
127
+ hidden_states: torch.Tensor,
128
+ key_value_states: Optional[torch.Tensor] = None,
129
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
130
+ attention_mask: Optional[torch.Tensor] = None,
131
+ layer_head_mask: Optional[torch.Tensor] = None,
132
+ output_attentions: bool = False,
133
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
134
+ """Input shape: Batch x Time x Channel"""
135
+
136
+ # if key_value_states are provided this layer is used as a cross-attention layer
137
+ # for the decoder
138
+ is_cross_attention = key_value_states is not None
139
+
140
+ bsz, tgt_len, _ = hidden_states.size()
141
+
142
+ # get query proj
143
+ query_states = self.q_proj(hidden_states) * self.scaling
144
+ # get key, value proj
145
+ # `past_key_value[0].shape[2] == key_value_states.shape[1]`
146
+ # is checking that the `sequence_length` of the `past_key_value` is the same as
147
+ # the provided `key_value_states` to support prefix tuning
148
+ if (
149
+ is_cross_attention
150
+ and past_key_value is not None
151
+ and past_key_value[0].shape[2] == key_value_states.shape[1]
152
+ ):
153
+ # reuse k,v, cross_attentions
154
+ key_states = past_key_value[0]
155
+ value_states = past_key_value[1]
156
+ elif is_cross_attention:
157
+ # cross_attentions
158
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
159
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
160
+ elif past_key_value is not None:
161
+ # reuse k, v, self_attention
162
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
163
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
164
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
165
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
166
+ else:
167
+ # self_attention
168
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
169
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
170
+
171
+ if self.is_decoder:
172
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
173
+ # Further calls to cross_attention layer can then reuse all cross-attention
174
+ # key/value_states (first "if" case)
175
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
176
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
177
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
178
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
179
+ past_key_value = (key_states, value_states)
180
+
181
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
182
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
183
+ key_states = key_states.reshape(*proj_shape)
184
+ value_states = value_states.reshape(*proj_shape)
185
+
186
+ src_len = key_states.size(1)
187
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
188
+
189
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
190
+ raise ValueError(
191
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
192
+ f" {attn_weights.size()}"
193
+ )
194
+
195
+ if attention_mask is not None:
196
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
197
+ raise ValueError(
198
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
199
+ )
200
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
201
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
202
+
203
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
204
+
205
+ if layer_head_mask is not None:
206
+ if layer_head_mask.size() != (self.num_heads,):
207
+ raise ValueError(
208
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
209
+ f" {layer_head_mask.size()}"
210
+ )
211
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
212
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
213
+
214
+ if output_attentions:
215
+ # this operation is a bit awkward, but it's required to
216
+ # make sure that attn_weights keeps its gradient.
217
+ # In order to do so, attn_weights have to be reshaped
218
+ # twice and have to be reused in the following
219
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
220
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
221
+ else:
222
+ attn_weights_reshaped = None
223
+
224
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
225
+
226
+ attn_output = torch.bmm(attn_probs, value_states)
227
+
228
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
229
+ raise ValueError(
230
+ f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
231
+ f" {attn_output.size()}"
232
+ )
233
+
234
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
235
+ attn_output = attn_output.transpose(1, 2)
236
+
237
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
238
+ # partitioned across GPUs when using tensor-parallelism.
239
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
240
+
241
+ attn_output = self.out_proj(attn_output)
242
+
243
+ return attn_output, attn_weights_reshaped, past_key_value
244
+
245
+
246
+ # Copied from transformers.models.bart.modeling_bart.BartEncoderLayer with Bart->BlenderbotSmall, BART->BLENDERBOT_SMALL
247
+ class BlenderbotSmallEncoderLayer(nn.Module):
248
+ def __init__(self, config: BlenderbotSmallConfig):
249
+ super().__init__()
250
+ self.embed_dim = config.d_model
251
+
252
+ self.self_attn = BLENDERBOT_SMALL_ATTENTION_CLASSES[config._attn_implementation](
253
+ embed_dim=self.embed_dim,
254
+ num_heads=config.encoder_attention_heads,
255
+ dropout=config.attention_dropout,
256
+ config=config,
257
+ )
258
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
259
+ self.dropout = config.dropout
260
+ self.activation_fn = ACT2FN[config.activation_function]
261
+ self.activation_dropout = config.activation_dropout
262
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
263
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
264
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
265
+
266
+ def forward(
267
+ self,
268
+ hidden_states: torch.FloatTensor,
269
+ attention_mask: torch.FloatTensor,
270
+ layer_head_mask: torch.FloatTensor,
271
+ output_attentions: Optional[bool] = False,
272
+ ) -> Tuple[torch.FloatTensor, Optional[torch.FloatTensor]]:
273
+ """
274
+ Args:
275
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
276
+ attention_mask (`torch.FloatTensor`): attention mask of size
277
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
278
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
279
+ `(encoder_attention_heads,)`.
280
+ output_attentions (`bool`, *optional*):
281
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
282
+ returned tensors for more detail.
283
+ """
284
+ residual = hidden_states
285
+ hidden_states, attn_weights, _ = self.self_attn(
286
+ hidden_states=hidden_states,
287
+ attention_mask=attention_mask,
288
+ layer_head_mask=layer_head_mask,
289
+ output_attentions=output_attentions,
290
+ )
291
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
292
+ hidden_states = residual + hidden_states
293
+ hidden_states = self.self_attn_layer_norm(hidden_states)
294
+
295
+ residual = hidden_states
296
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
297
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
298
+ hidden_states = self.fc2(hidden_states)
299
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
300
+ hidden_states = residual + hidden_states
301
+ hidden_states = self.final_layer_norm(hidden_states)
302
+
303
+ if hidden_states.dtype == torch.float16 and (
304
+ torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()
305
+ ):
306
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
307
+ hidden_states = torch.clamp(hidden_states, min=-clamp_value, max=clamp_value)
308
+
309
+ outputs = (hidden_states,)
310
+
311
+ if output_attentions:
312
+ outputs += (attn_weights,)
313
+
314
+ return outputs
315
+
316
+
317
+ # TODO: Implement attention with SDPA for TimeSeriesTransformer.
318
+ BLENDERBOT_SMALL_ATTENTION_CLASSES = {
319
+ "eager": BlenderbotSmallAttention,
320
+ }
321
+
322
+
323
+ # Copied from transformers.models.bart.modeling_bart.BartDecoderLayer with Bart->BlenderbotSmall, BART->BLENDERBOT_SMALL
324
+ class BlenderbotSmallDecoderLayer(nn.Module):
325
+ def __init__(self, config: BlenderbotSmallConfig):
326
+ super().__init__()
327
+ self.embed_dim = config.d_model
328
+
329
+ self.self_attn = BLENDERBOT_SMALL_ATTENTION_CLASSES[config._attn_implementation](
330
+ embed_dim=self.embed_dim,
331
+ num_heads=config.decoder_attention_heads,
332
+ dropout=config.attention_dropout,
333
+ is_decoder=True,
334
+ is_causal=True,
335
+ config=config,
336
+ )
337
+ self.dropout = config.dropout
338
+ self.activation_fn = ACT2FN[config.activation_function]
339
+ self.activation_dropout = config.activation_dropout
340
+
341
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
342
+ self.encoder_attn = BLENDERBOT_SMALL_ATTENTION_CLASSES[config._attn_implementation](
343
+ self.embed_dim,
344
+ config.decoder_attention_heads,
345
+ dropout=config.attention_dropout,
346
+ is_decoder=True,
347
+ config=config,
348
+ )
349
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
350
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
351
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
352
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
353
+
354
+ def forward(
355
+ self,
356
+ hidden_states: torch.Tensor,
357
+ attention_mask: Optional[torch.Tensor] = None,
358
+ encoder_hidden_states: Optional[torch.Tensor] = None,
359
+ encoder_attention_mask: Optional[torch.Tensor] = None,
360
+ layer_head_mask: Optional[torch.Tensor] = None,
361
+ cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
362
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
363
+ output_attentions: Optional[bool] = False,
364
+ use_cache: Optional[bool] = True,
365
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
366
+ """
367
+ Args:
368
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
369
+ attention_mask (`torch.FloatTensor`): attention mask of size
370
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
371
+ encoder_hidden_states (`torch.FloatTensor`):
372
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
373
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
374
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
375
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
376
+ `(encoder_attention_heads,)`.
377
+ cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
378
+ size `(decoder_attention_heads,)`.
379
+ past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
380
+ output_attentions (`bool`, *optional*):
381
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
382
+ returned tensors for more detail.
383
+ """
384
+ residual = hidden_states
385
+
386
+ # Self Attention
387
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
388
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
389
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
390
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
391
+ hidden_states=hidden_states,
392
+ past_key_value=self_attn_past_key_value,
393
+ attention_mask=attention_mask,
394
+ layer_head_mask=layer_head_mask,
395
+ output_attentions=output_attentions,
396
+ )
397
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
398
+ hidden_states = residual + hidden_states
399
+ hidden_states = self.self_attn_layer_norm(hidden_states)
400
+
401
+ # Cross-Attention Block
402
+ cross_attn_present_key_value = None
403
+ cross_attn_weights = None
404
+ if encoder_hidden_states is not None:
405
+ residual = hidden_states
406
+
407
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
408
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
409
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
410
+ hidden_states=hidden_states,
411
+ key_value_states=encoder_hidden_states,
412
+ attention_mask=encoder_attention_mask,
413
+ layer_head_mask=cross_attn_layer_head_mask,
414
+ past_key_value=cross_attn_past_key_value,
415
+ output_attentions=output_attentions,
416
+ )
417
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
418
+ hidden_states = residual + hidden_states
419
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
420
+
421
+ # add cross-attn to positions 3,4 of present_key_value tuple
422
+ present_key_value = present_key_value + cross_attn_present_key_value
423
+
424
+ # Fully Connected
425
+ residual = hidden_states
426
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
427
+ hidden_states = nn.functional.dropout(hidden_states, p=self.activation_dropout, training=self.training)
428
+ hidden_states = self.fc2(hidden_states)
429
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
430
+ hidden_states = residual + hidden_states
431
+ hidden_states = self.final_layer_norm(hidden_states)
432
+
433
+ outputs = (hidden_states,)
434
+
435
+ if output_attentions:
436
+ outputs += (self_attn_weights, cross_attn_weights)
437
+
438
+ if use_cache:
439
+ outputs += (present_key_value,)
440
+
441
+ return outputs
442
+
443
+
444
+ class BlenderbotSmallPreTrainedModel(PreTrainedModel):
445
+ config_class = BlenderbotSmallConfig
446
+ base_model_prefix = "model"
447
+ supports_gradient_checkpointing = True
448
+
449
+ def _init_weights(self, module):
450
+ std = self.config.init_std
451
+ if isinstance(module, nn.Linear):
452
+ module.weight.data.normal_(mean=0.0, std=std)
453
+ if module.bias is not None:
454
+ module.bias.data.zero_()
455
+ elif isinstance(module, nn.Embedding):
456
+ module.weight.data.normal_(mean=0.0, std=std)
457
+ if module.padding_idx is not None:
458
+ module.weight.data[module.padding_idx].zero_()
459
+
460
+ @property
461
+ def dummy_inputs(self):
462
+ pad_token = self.config.pad_token_id
463
+ input_ids = torch.tensor([[0, 6, 10, 4, 2], [0, 8, 12, 2, pad_token]], device=self.device)
464
+ dummy_inputs = {
465
+ "attention_mask": input_ids.ne(pad_token),
466
+ "input_ids": input_ids,
467
+ "decoder_input_ids": input_ids,
468
+ }
469
+ return dummy_inputs
470
+
471
+
472
+ BLENDERBOT_SMALL_START_DOCSTRING = r"""
473
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
474
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
475
+ etc.)
476
+
477
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
478
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
479
+ and behavior.
480
+
481
+ Parameters:
482
+ config ([`BlenderbotSmallConfig`]):
483
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
484
+ load the weights associated with the model, only the configuration. Check out the
485
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
486
+ """
487
+
488
+ BLENDERBOT_SMALL_GENERATION_EXAMPLE = r"""
489
+ Conversation example:
490
+
491
+ ```python
492
+ >>> from transformers import AutoTokenizer, BlenderbotSmallForConditionalGeneration
493
+
494
+ >>> mname = "facebook/blenderbot_small-90M"
495
+ >>> model = BlenderbotSmallForConditionalGeneration.from_pretrained(mname)
496
+ >>> tokenizer = AutoTokenizer.from_pretrained(mname)
497
+ >>> UTTERANCE = "My friends are cool but they eat too many carbs."
498
+ >>> print("Human: ", UTTERANCE)
499
+ Human: My friends are cool but they eat too many carbs.
500
+
501
+ >>> inputs = tokenizer([UTTERANCE], return_tensors="pt")
502
+ >>> reply_ids = model.generate(**inputs)
503
+ >>> print("Bot: ", tokenizer.batch_decode(reply_ids, skip_special_tokens=True)[0])
504
+ Bot: what kind of carbs do they eat? i don't know much about carbs.
505
+
506
+ >>> REPLY = "I'm not sure"
507
+ >>> print("Human: ", REPLY)
508
+ Human: I'm not sure
509
+
510
+ >>> NEXT_UTTERANCE = (
511
+ ... "My friends are cool but they eat too many carbs.__end__ __start__what kind of carbs do they eat? "
512
+ ... "i don't know much about carbs__end__ "
513
+ ... "__start__ I'm not sure."
514
+ ... )
515
+ >>> inputs = tokenizer([NEXT_UTTERANCE], return_tensors="pt")
516
+ >>> next_reply_ids = model.generate(**inputs)
517
+ >>> print("Bot: ", tokenizer.batch_decode(next_reply_ids, skip_special_tokens=True)[0])
518
+ Bot: they eat a lot of carbs. carbs are high in fat, protein, and fats.
519
+ ```
520
+ """
521
+
522
+ BLENDERBOT_SMALL_INPUTS_DOCSTRING = r"""
523
+ Args:
524
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
525
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
526
+ it.
527
+
528
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
529
+ [`PreTrainedTokenizer.__call__`] for details.
530
+
531
+ [What are input IDs?](../glossary#input-ids)
532
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
533
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
534
+
535
+ - 1 for tokens that are **not masked**,
536
+ - 0 for tokens that are **masked**.
537
+
538
+ [What are attention masks?](../glossary#attention-mask)
539
+ decoder_input_ids (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
540
+ Indices of decoder input sequence tokens in the vocabulary.
541
+
542
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
543
+ [`PreTrainedTokenizer.__call__`] for details.
544
+
545
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
546
+
547
+ BlenderbotSmall uses the `bos_token_id` as the starting token for `decoder_input_ids` generation. If
548
+ `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
549
+ `past_key_values`).
550
+ decoder_attention_mask (`torch.LongTensor` of shape `(batch_size, target_sequence_length)`, *optional*):
551
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
552
+ be used by default.
553
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
554
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
555
+
556
+ - 1 indicates the head is **not masked**,
557
+ - 0 indicates the head is **masked**.
558
+
559
+ decoder_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
560
+ Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
561
+
562
+ - 1 indicates the head is **not masked**,
563
+ - 0 indicates the head is **masked**.
564
+
565
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
566
+ Mask to nullify selected heads of the cross-attention modules in the decoder. Mask values selected in `[0,
567
+ 1]`:
568
+
569
+ - 1 indicates the head is **not masked**,
570
+ - 0 indicates the head is **masked**.
571
+
572
+ encoder_outputs (`tuple(tuple(torch.FloatTensor)`, *optional*):
573
+ Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
574
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
575
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
576
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
577
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
578
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
579
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
580
+
581
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
582
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
583
+
584
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
585
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
586
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
587
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
588
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
589
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
590
+ than the model's internal embedding lookup matrix.
591
+ decoder_inputs_embeds (`torch.FloatTensor` of shape `(batch_size, target_sequence_length, hidden_size)`, *optional*):
592
+ Optionally, instead of passing `decoder_input_ids` you can choose to directly pass an embedded
593
+ representation. If `past_key_values` is used, optionally only the last `decoder_inputs_embeds` have to be
594
+ input (see `past_key_values`). This is useful if you want more control over how to convert
595
+ `decoder_input_ids` indices into associated vectors than the model's internal embedding lookup matrix.
596
+
597
+ If `decoder_input_ids` and `decoder_inputs_embeds` are both unset, `decoder_inputs_embeds` takes the value
598
+ of `inputs_embeds`.
599
+ use_cache (`bool`, *optional*):
600
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
601
+ `past_key_values`).
602
+ output_attentions (`bool`, *optional*):
603
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
604
+ tensors for more detail.
605
+ output_hidden_states (`bool`, *optional*):
606
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
607
+ more detail.
608
+ return_dict (`bool`, *optional*):
609
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
610
+ """
611
+
612
+
613
+ class BlenderbotSmallEncoder(BlenderbotSmallPreTrainedModel):
614
+ """
615
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
616
+ [`BlenderbotSmallEncoderLayer`].
617
+
618
+ Args:
619
+ config: BlenderbotSmallConfig
620
+ embed_tokens (nn.Embedding): output embedding
621
+ """
622
+
623
+ def __init__(self, config: BlenderbotSmallConfig, embed_tokens: Optional[nn.Embedding] = None):
624
+ super().__init__(config)
625
+
626
+ self.dropout = config.dropout
627
+ self.layerdrop = config.encoder_layerdrop
628
+
629
+ embed_dim = config.d_model
630
+ self.padding_idx = config.pad_token_id
631
+ self.max_source_positions = config.max_position_embeddings
632
+ self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
633
+
634
+ if embed_tokens is not None:
635
+ self.embed_tokens = embed_tokens
636
+ else:
637
+ self.embed_tokens = nn.Embedding(config.vocab_size, embed_dim, self.padding_idx)
638
+
639
+ self.embed_positions = BlenderbotSmallLearnedPositionalEmbedding(
640
+ config.max_position_embeddings,
641
+ embed_dim,
642
+ )
643
+ self.layers = nn.ModuleList([BlenderbotSmallEncoderLayer(config) for _ in range(config.encoder_layers)])
644
+ self.layernorm_embedding = nn.LayerNorm(embed_dim)
645
+
646
+ self.gradient_checkpointing = False
647
+ # Initialize weights and apply final processing
648
+ self.post_init()
649
+
650
+ def forward(
651
+ self,
652
+ input_ids=None,
653
+ attention_mask=None,
654
+ head_mask=None,
655
+ inputs_embeds=None,
656
+ output_attentions=None,
657
+ output_hidden_states=None,
658
+ return_dict=None,
659
+ ):
660
+ r"""
661
+ Args:
662
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
663
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
664
+ provide it.
665
+
666
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
667
+ [`PreTrainedTokenizer.__call__`] for details.
668
+
669
+ [What are input IDs?](../glossary#input-ids)
670
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
671
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
672
+
673
+ - 1 for tokens that are **not masked**,
674
+ - 0 for tokens that are **masked**.
675
+
676
+ [What are attention masks?](../glossary#attention-mask)
677
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
678
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
679
+
680
+ - 1 indicates the head is **not masked**,
681
+ - 0 indicates the head is **masked**.
682
+
683
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
684
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
685
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
686
+ than the model's internal embedding lookup matrix.
687
+ output_attentions (`bool`, *optional*):
688
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
689
+ returned tensors for more detail.
690
+ output_hidden_states (`bool`, *optional*):
691
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
692
+ for more detail.
693
+ return_dict (`bool`, *optional*):
694
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
695
+ """
696
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
697
+ output_hidden_states = (
698
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
699
+ )
700
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
701
+
702
+ # retrieve input_ids and inputs_embeds
703
+ if input_ids is not None and inputs_embeds is not None:
704
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
705
+ elif input_ids is not None:
706
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
707
+ input_shape = input_ids.size()
708
+ input_ids = input_ids.view(-1, input_shape[-1])
709
+ elif inputs_embeds is not None:
710
+ input_shape = inputs_embeds.size()[:-1]
711
+ else:
712
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
713
+
714
+ if inputs_embeds is None:
715
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
716
+
717
+ embed_pos = self.embed_positions(input_shape)
718
+
719
+ hidden_states = inputs_embeds + embed_pos
720
+ hidden_states = self.layernorm_embedding(hidden_states)
721
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
722
+
723
+ # expand attention_mask
724
+ if attention_mask is not None:
725
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
726
+ attention_mask = _prepare_4d_attention_mask(attention_mask, inputs_embeds.dtype)
727
+
728
+ encoder_states = () if output_hidden_states else None
729
+ all_attentions = () if output_attentions else None
730
+
731
+ # check if head_mask has a correct number of layers specified if desired
732
+ if head_mask is not None:
733
+ if head_mask.size()[0] != len(self.layers):
734
+ raise ValueError(
735
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
736
+ f" {head_mask.size()[0]}."
737
+ )
738
+ for idx, encoder_layer in enumerate(self.layers):
739
+ if output_hidden_states:
740
+ encoder_states = encoder_states + (hidden_states,)
741
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
742
+ to_drop = False
743
+ if self.training:
744
+ dropout_probability = torch.rand([])
745
+ if dropout_probability < self.layerdrop: # skip the layer
746
+ to_drop = True
747
+
748
+ if to_drop:
749
+ layer_outputs = (None, None)
750
+ else:
751
+ if self.gradient_checkpointing and self.training:
752
+ layer_outputs = self._gradient_checkpointing_func(
753
+ encoder_layer.__call__,
754
+ hidden_states,
755
+ attention_mask,
756
+ (head_mask[idx] if head_mask is not None else None),
757
+ output_attentions,
758
+ )
759
+ else:
760
+ layer_outputs = encoder_layer(
761
+ hidden_states,
762
+ attention_mask,
763
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
764
+ output_attentions=output_attentions,
765
+ )
766
+
767
+ hidden_states = layer_outputs[0]
768
+
769
+ if output_attentions:
770
+ all_attentions = all_attentions + (layer_outputs[1],)
771
+
772
+ if output_hidden_states:
773
+ encoder_states = encoder_states + (hidden_states,)
774
+
775
+ if not return_dict:
776
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
777
+ return BaseModelOutput(
778
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
779
+ )
780
+
781
+
782
+ class BlenderbotSmallDecoder(BlenderbotSmallPreTrainedModel):
783
+ """
784
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`BlenderbotSmallDecoderLayer`]
785
+
786
+ Args:
787
+ config: BlenderbotSmallConfig
788
+ embed_tokens (nn.Embedding): output embedding
789
+ """
790
+
791
+ def __init__(self, config: BlenderbotSmallConfig, embed_tokens: Optional[nn.Embedding] = None):
792
+ super().__init__(config)
793
+ self.dropout = config.dropout
794
+ self.layerdrop = config.decoder_layerdrop
795
+ self.padding_idx = config.pad_token_id
796
+ self.max_target_positions = config.max_position_embeddings
797
+ self.embed_scale = math.sqrt(config.d_model) if config.scale_embedding else 1.0
798
+
799
+ if embed_tokens is not None:
800
+ self.embed_tokens = embed_tokens
801
+ else:
802
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.d_model, self.padding_idx)
803
+
804
+ self.embed_positions = BlenderbotSmallLearnedPositionalEmbedding(
805
+ config.max_position_embeddings,
806
+ config.d_model,
807
+ )
808
+ self.layers = nn.ModuleList([BlenderbotSmallDecoderLayer(config) for _ in range(config.decoder_layers)])
809
+ self.layernorm_embedding = nn.LayerNorm(config.d_model)
810
+
811
+ self.gradient_checkpointing = False
812
+ # Initialize weights and apply final processing
813
+ self.post_init()
814
+
815
+ def get_input_embeddings(self):
816
+ return self.embed_tokens
817
+
818
+ def set_input_embeddings(self, value):
819
+ self.embed_tokens = value
820
+
821
+ def forward(
822
+ self,
823
+ input_ids=None,
824
+ attention_mask=None,
825
+ encoder_hidden_states=None,
826
+ encoder_attention_mask=None,
827
+ head_mask=None,
828
+ cross_attn_head_mask=None,
829
+ past_key_values=None,
830
+ inputs_embeds=None,
831
+ use_cache=None,
832
+ output_attentions=None,
833
+ output_hidden_states=None,
834
+ return_dict=None,
835
+ ):
836
+ r"""
837
+ Args:
838
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
839
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
840
+ provide it.
841
+
842
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
843
+ [`PreTrainedTokenizer.__call__`] for details.
844
+
845
+ [What are input IDs?](../glossary#input-ids)
846
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
847
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
848
+
849
+ - 1 for tokens that are **not masked**,
850
+ - 0 for tokens that are **masked**.
851
+
852
+ [What are attention masks?](../glossary#attention-mask)
853
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
854
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
855
+ of the decoder.
856
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
857
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
858
+ selected in `[0, 1]`:
859
+
860
+ - 1 for tokens that are **not masked**,
861
+ - 0 for tokens that are **masked**.
862
+
863
+ [What are attention masks?](../glossary#attention-mask)
864
+ head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
865
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
866
+
867
+ - 1 indicates the head is **not masked**,
868
+ - 0 indicates the head is **masked**.
869
+
870
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
871
+ Mask to nullify selected heads of the cross-attention modules in the decoder to avoid performing
872
+ cross-attention on hidden heads. Mask values selected in `[0, 1]`:
873
+
874
+ - 1 indicates the head is **not masked**,
875
+ - 0 indicates the head is **masked**.
876
+
877
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
878
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
879
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
880
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
881
+
882
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
883
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
884
+
885
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
886
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
887
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
888
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
889
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
890
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
891
+ than the model's internal embedding lookup matrix.
892
+ output_attentions (`bool`, *optional*):
893
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
894
+ returned tensors for more detail.
895
+ output_hidden_states (`bool`, *optional*):
896
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
897
+ for more detail.
898
+ return_dict (`bool`, *optional*):
899
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
900
+ """
901
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
902
+ output_hidden_states = (
903
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
904
+ )
905
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
906
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
907
+
908
+ # retrieve input_ids and inputs_embeds
909
+ if input_ids is not None and inputs_embeds is not None:
910
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
911
+ elif input_ids is not None:
912
+ input_shape = input_ids.size()
913
+ input_ids = input_ids.view(-1, input_shape[-1])
914
+ elif inputs_embeds is not None:
915
+ input_shape = inputs_embeds.size()[:-1]
916
+ else:
917
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
918
+
919
+ # past_key_values_length
920
+ past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0
921
+
922
+ if inputs_embeds is None:
923
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
924
+
925
+ attention_mask = _prepare_4d_causal_attention_mask(
926
+ attention_mask, input_shape, inputs_embeds, past_key_values_length
927
+ )
928
+
929
+ # expand encoder attention mask
930
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
931
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
932
+ encoder_attention_mask = _prepare_4d_attention_mask(
933
+ encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
934
+ )
935
+
936
+ # embed positions
937
+ positions = self.embed_positions(input_shape, past_key_values_length)
938
+
939
+ # BlenderbotSmall applies layer norm on hidden_states
940
+ inputs_embeds = self.layernorm_embedding(inputs_embeds)
941
+ hidden_states = inputs_embeds + positions
942
+
943
+ hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training)
944
+
945
+ if self.gradient_checkpointing and self.training:
946
+ if use_cache:
947
+ logger.warning_once(
948
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
949
+ )
950
+ use_cache = False
951
+
952
+ # decoder layers
953
+ all_hidden_states = () if output_hidden_states else None
954
+ all_self_attns = () if output_attentions else None
955
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
956
+ next_decoder_cache = () if use_cache else None
957
+
958
+ # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
959
+ for attn_mask, mask_name in zip([head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]):
960
+ if attn_mask is not None:
961
+ if attn_mask.size()[0] != len(self.layers):
962
+ raise ValueError(
963
+ f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
964
+ f" {head_mask.size()[0]}."
965
+ )
966
+ for idx, decoder_layer in enumerate(self.layers):
967
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
968
+ if output_hidden_states:
969
+ all_hidden_states += (hidden_states,)
970
+ if self.training:
971
+ dropout_probability = torch.rand([])
972
+ if dropout_probability < self.layerdrop:
973
+ continue
974
+
975
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
976
+
977
+ if self.gradient_checkpointing and self.training:
978
+ layer_outputs = self._gradient_checkpointing_func(
979
+ decoder_layer.__call__,
980
+ hidden_states,
981
+ attention_mask,
982
+ encoder_hidden_states,
983
+ encoder_attention_mask,
984
+ head_mask[idx] if head_mask is not None else None,
985
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
986
+ None,
987
+ output_attentions,
988
+ use_cache,
989
+ )
990
+ else:
991
+ layer_outputs = decoder_layer(
992
+ hidden_states,
993
+ attention_mask=attention_mask,
994
+ encoder_hidden_states=encoder_hidden_states,
995
+ encoder_attention_mask=encoder_attention_mask,
996
+ layer_head_mask=(head_mask[idx] if head_mask is not None else None),
997
+ cross_attn_layer_head_mask=(
998
+ cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None
999
+ ),
1000
+ past_key_value=past_key_value,
1001
+ output_attentions=output_attentions,
1002
+ use_cache=use_cache,
1003
+ )
1004
+ hidden_states = layer_outputs[0]
1005
+
1006
+ if use_cache:
1007
+ next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
1008
+
1009
+ if output_attentions:
1010
+ all_self_attns += (layer_outputs[1],)
1011
+
1012
+ if encoder_hidden_states is not None:
1013
+ all_cross_attentions += (layer_outputs[2],)
1014
+
1015
+ # add hidden states from the last decoder layer
1016
+ if output_hidden_states:
1017
+ all_hidden_states += (hidden_states,)
1018
+
1019
+ next_cache = next_decoder_cache if use_cache else None
1020
+ if not return_dict:
1021
+ return tuple(
1022
+ v
1023
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns, all_cross_attentions]
1024
+ if v is not None
1025
+ )
1026
+ return BaseModelOutputWithPastAndCrossAttentions(
1027
+ last_hidden_state=hidden_states,
1028
+ past_key_values=next_cache,
1029
+ hidden_states=all_hidden_states,
1030
+ attentions=all_self_attns,
1031
+ cross_attentions=all_cross_attentions,
1032
+ )
1033
+
1034
+
1035
+ @add_start_docstrings(
1036
+ "The bare BlenderbotSmall Model outputting raw hidden-states without any specific head on top.",
1037
+ BLENDERBOT_SMALL_START_DOCSTRING,
1038
+ )
1039
+ class BlenderbotSmallModel(BlenderbotSmallPreTrainedModel):
1040
+ _tied_weights_keys = ["decoder.embed_tokens.weight", "encoder.embed_tokens.weight"]
1041
+
1042
+ def __init__(self, config: BlenderbotSmallConfig):
1043
+ super().__init__(config)
1044
+
1045
+ padding_idx, vocab_size = config.pad_token_id, config.vocab_size
1046
+ self.shared = nn.Embedding(vocab_size, config.d_model, padding_idx)
1047
+
1048
+ self.encoder = BlenderbotSmallEncoder(config, self.shared)
1049
+ self.decoder = BlenderbotSmallDecoder(config, self.shared)
1050
+
1051
+ # Initialize weights and apply final processing
1052
+ self.post_init()
1053
+
1054
+ def get_input_embeddings(self):
1055
+ return self.shared
1056
+
1057
+ def set_input_embeddings(self, value):
1058
+ self.shared = value
1059
+ self.encoder.embed_tokens = self.shared
1060
+ self.decoder.embed_tokens = self.shared
1061
+
1062
+ def get_encoder(self):
1063
+ return self.encoder
1064
+
1065
+ def get_decoder(self):
1066
+ return self.decoder
1067
+
1068
+ @add_start_docstrings_to_model_forward(BLENDERBOT_SMALL_INPUTS_DOCSTRING)
1069
+ @replace_return_docstrings(output_type=Seq2SeqModelOutput, config_class=_CONFIG_FOR_DOC)
1070
+ def forward(
1071
+ self,
1072
+ input_ids: Optional[torch.LongTensor] = None,
1073
+ attention_mask: Optional[torch.Tensor] = None,
1074
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1075
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1076
+ head_mask: Optional[torch.Tensor] = None,
1077
+ decoder_head_mask: Optional[torch.Tensor] = None,
1078
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1079
+ encoder_outputs: Optional[Union[Tuple, BaseModelOutput]] = None,
1080
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1081
+ inputs_embeds: Optional[torch.Tensor] = None,
1082
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1083
+ use_cache: Optional[bool] = None,
1084
+ output_attentions: Optional[bool] = None,
1085
+ output_hidden_states: Optional[bool] = None,
1086
+ return_dict: Optional[bool] = None,
1087
+ ) -> Union[Tuple[torch.FloatTensor], Seq2SeqModelOutput]:
1088
+ r"""
1089
+ Returns:
1090
+
1091
+ Example:
1092
+
1093
+ ```python
1094
+ >>> from transformers import AutoTokenizer, BlenderbotSmallModel
1095
+
1096
+ >>> model = BlenderbotSmallModel.from_pretrained("facebook/blenderbot_small-90M")
1097
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
1098
+
1099
+ >>> inputs = tokenizer("Studies have been shown that owning a dog is good for you", return_tensors="pt")
1100
+ >>> decoder_inputs = tokenizer("Studies show that", return_tensors="pt") # Batch size 1
1101
+ >>> outputs = model(input_ids=inputs.input_ids, decoder_input_ids=decoder_inputs.input_ids)
1102
+
1103
+ >>> last_hidden_states = outputs.last_hidden_state
1104
+ >>> list(last_hidden_states.shape)
1105
+ [1, 3, 512]
1106
+ ```"""
1107
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1108
+ output_hidden_states = (
1109
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1110
+ )
1111
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1112
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1113
+
1114
+ if encoder_outputs is None:
1115
+ encoder_outputs = self.encoder(
1116
+ input_ids=input_ids,
1117
+ attention_mask=attention_mask,
1118
+ head_mask=head_mask,
1119
+ inputs_embeds=inputs_embeds,
1120
+ output_attentions=output_attentions,
1121
+ output_hidden_states=output_hidden_states,
1122
+ return_dict=return_dict,
1123
+ )
1124
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
1125
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
1126
+ encoder_outputs = BaseModelOutput(
1127
+ last_hidden_state=encoder_outputs[0],
1128
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1129
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1130
+ )
1131
+
1132
+ # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
1133
+ decoder_outputs = self.decoder(
1134
+ input_ids=decoder_input_ids,
1135
+ attention_mask=decoder_attention_mask,
1136
+ encoder_hidden_states=encoder_outputs[0],
1137
+ encoder_attention_mask=attention_mask,
1138
+ head_mask=decoder_head_mask,
1139
+ cross_attn_head_mask=cross_attn_head_mask,
1140
+ past_key_values=past_key_values,
1141
+ inputs_embeds=decoder_inputs_embeds,
1142
+ use_cache=use_cache,
1143
+ output_attentions=output_attentions,
1144
+ output_hidden_states=output_hidden_states,
1145
+ return_dict=return_dict,
1146
+ )
1147
+
1148
+ if not return_dict:
1149
+ return decoder_outputs + encoder_outputs
1150
+
1151
+ return Seq2SeqModelOutput(
1152
+ last_hidden_state=decoder_outputs.last_hidden_state,
1153
+ past_key_values=decoder_outputs.past_key_values,
1154
+ decoder_hidden_states=decoder_outputs.hidden_states,
1155
+ decoder_attentions=decoder_outputs.attentions,
1156
+ cross_attentions=decoder_outputs.cross_attentions,
1157
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1158
+ encoder_hidden_states=encoder_outputs.hidden_states,
1159
+ encoder_attentions=encoder_outputs.attentions,
1160
+ )
1161
+
1162
+
1163
+ @add_start_docstrings(
1164
+ "The BlenderbotSmall Model with a language modeling head. Can be used for summarization.",
1165
+ BLENDERBOT_SMALL_START_DOCSTRING,
1166
+ )
1167
+ class BlenderbotSmallForConditionalGeneration(BlenderbotSmallPreTrainedModel, GenerationMixin):
1168
+ base_model_prefix = "model"
1169
+ _keys_to_ignore_on_load_missing = ["final_logits_bias"]
1170
+ _tied_weights_keys = ["decoder.embed_tokens.weight", "encoder.embed_tokens.weight", "lm_head.weight"]
1171
+
1172
+ def __init__(self, config: BlenderbotSmallConfig):
1173
+ super().__init__(config)
1174
+ self.model = BlenderbotSmallModel(config)
1175
+ self.register_buffer("final_logits_bias", torch.zeros((1, self.model.shared.num_embeddings)))
1176
+ self.lm_head = nn.Linear(config.d_model, self.model.shared.num_embeddings, bias=False)
1177
+
1178
+ # Initialize weights and apply final processing
1179
+ self.post_init()
1180
+
1181
+ def get_encoder(self):
1182
+ return self.model.get_encoder()
1183
+
1184
+ def get_decoder(self):
1185
+ return self.model.get_decoder()
1186
+
1187
+ def resize_token_embeddings(
1188
+ self, new_num_tokens: int, pad_to_multiple_of: Optional[int] = None, mean_resizing: bool = True
1189
+ ) -> nn.Embedding:
1190
+ new_embeddings = super().resize_token_embeddings(new_num_tokens, pad_to_multiple_of, mean_resizing)
1191
+ self._resize_final_logits_bias(new_embeddings.weight.shape[0])
1192
+ return new_embeddings
1193
+
1194
+ def _resize_final_logits_bias(self, new_num_tokens: int) -> None:
1195
+ old_num_tokens = self.final_logits_bias.shape[-1]
1196
+ if new_num_tokens <= old_num_tokens:
1197
+ new_bias = self.final_logits_bias[:, :new_num_tokens]
1198
+ else:
1199
+ extra_bias = torch.zeros((1, new_num_tokens - old_num_tokens), device=self.final_logits_bias.device)
1200
+ new_bias = torch.cat([self.final_logits_bias, extra_bias], dim=1)
1201
+ self.register_buffer("final_logits_bias", new_bias)
1202
+
1203
+ def get_output_embeddings(self):
1204
+ return self.lm_head
1205
+
1206
+ def set_output_embeddings(self, new_embeddings):
1207
+ self.lm_head = new_embeddings
1208
+
1209
+ @add_start_docstrings_to_model_forward(BLENDERBOT_SMALL_INPUTS_DOCSTRING)
1210
+ @replace_return_docstrings(output_type=Seq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
1211
+ @add_end_docstrings(BLENDERBOT_SMALL_GENERATION_EXAMPLE)
1212
+ def forward(
1213
+ self,
1214
+ input_ids: Optional[torch.LongTensor] = None,
1215
+ attention_mask: Optional[torch.Tensor] = None,
1216
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1217
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1218
+ head_mask: Optional[torch.Tensor] = None,
1219
+ decoder_head_mask: Optional[torch.Tensor] = None,
1220
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1221
+ encoder_outputs: Optional[Union[Tuple, BaseModelOutput]] = None,
1222
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1223
+ inputs_embeds: Optional[torch.Tensor] = None,
1224
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1225
+ labels: Optional[torch.LongTensor] = None,
1226
+ use_cache: Optional[bool] = None,
1227
+ output_attentions: Optional[bool] = None,
1228
+ output_hidden_states: Optional[bool] = None,
1229
+ return_dict: Optional[bool] = None,
1230
+ ) -> Union[Tuple[torch.FloatTensor], Seq2SeqLMOutput]:
1231
+ r"""
1232
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1233
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1234
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1235
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1236
+
1237
+ Returns:
1238
+ """
1239
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1240
+
1241
+ if labels is not None:
1242
+ if use_cache:
1243
+ logger.warning("The `use_cache` argument is changed to `False` since `labels` is provided.")
1244
+ use_cache = False
1245
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1246
+ decoder_input_ids = shift_tokens_right(
1247
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
1248
+ )
1249
+
1250
+ outputs = self.model(
1251
+ input_ids,
1252
+ attention_mask=attention_mask,
1253
+ decoder_input_ids=decoder_input_ids,
1254
+ encoder_outputs=encoder_outputs,
1255
+ decoder_attention_mask=decoder_attention_mask,
1256
+ head_mask=head_mask,
1257
+ decoder_head_mask=decoder_head_mask,
1258
+ cross_attn_head_mask=cross_attn_head_mask,
1259
+ past_key_values=past_key_values,
1260
+ inputs_embeds=inputs_embeds,
1261
+ decoder_inputs_embeds=decoder_inputs_embeds,
1262
+ use_cache=use_cache,
1263
+ output_attentions=output_attentions,
1264
+ output_hidden_states=output_hidden_states,
1265
+ return_dict=return_dict,
1266
+ )
1267
+ lm_logits = self.lm_head(outputs[0]) + self.final_logits_bias
1268
+
1269
+ masked_lm_loss = None
1270
+ if labels is not None:
1271
+ loss_fct = CrossEntropyLoss()
1272
+ masked_lm_loss = loss_fct(lm_logits.view(-1, self.config.vocab_size), labels.view(-1))
1273
+
1274
+ if not return_dict:
1275
+ output = (lm_logits,) + outputs[1:]
1276
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1277
+
1278
+ return Seq2SeqLMOutput(
1279
+ loss=masked_lm_loss,
1280
+ logits=lm_logits,
1281
+ past_key_values=outputs.past_key_values,
1282
+ decoder_hidden_states=outputs.decoder_hidden_states,
1283
+ decoder_attentions=outputs.decoder_attentions,
1284
+ cross_attentions=outputs.cross_attentions,
1285
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1286
+ encoder_hidden_states=outputs.encoder_hidden_states,
1287
+ encoder_attentions=outputs.encoder_attentions,
1288
+ )
1289
+
1290
+ @staticmethod
1291
+ def _reorder_cache(past_key_values, beam_idx):
1292
+ reordered_past = ()
1293
+ for layer_past in past_key_values:
1294
+ # cached cross_attention states don't have to be reordered -> they are always the same
1295
+ reordered_past += (
1296
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past[:2])
1297
+ + layer_past[2:],
1298
+ )
1299
+ return reordered_past
1300
+
1301
+
1302
+ # Copied from transformers.models.bart.modeling_bart.BartDecoderWrapper with Bart->BlenderbotSmall
1303
+ class BlenderbotSmallDecoderWrapper(BlenderbotSmallPreTrainedModel):
1304
+ """
1305
+ This wrapper class is a helper class to correctly load pretrained checkpoints when the causal language model is
1306
+ used in combination with the [`EncoderDecoderModel`] framework.
1307
+ """
1308
+
1309
+ def __init__(self, config):
1310
+ super().__init__(config)
1311
+ self.decoder = BlenderbotSmallDecoder(config)
1312
+
1313
+ def forward(self, *args, **kwargs):
1314
+ return self.decoder(*args, **kwargs)
1315
+
1316
+
1317
+ # Copied from transformers.models.bart.modeling_bart.BartForCausalLM with Bart->BlenderbotSmall, facebook/bart-base->facebook/blenderbot_small-90M
1318
+ class BlenderbotSmallForCausalLM(BlenderbotSmallPreTrainedModel, GenerationMixin):
1319
+ _tied_weights_keys = ["lm_head.weight"]
1320
+
1321
+ def __init__(self, config):
1322
+ config = copy.deepcopy(config)
1323
+ config.is_decoder = True
1324
+ config.is_encoder_decoder = False
1325
+ super().__init__(config)
1326
+ self.model = BlenderbotSmallDecoderWrapper(config)
1327
+
1328
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1329
+
1330
+ # Initialize weights and apply final processing
1331
+ self.post_init()
1332
+
1333
+ def get_input_embeddings(self):
1334
+ return self.model.decoder.embed_tokens
1335
+
1336
+ def set_input_embeddings(self, value):
1337
+ self.model.decoder.embed_tokens = value
1338
+
1339
+ def get_output_embeddings(self):
1340
+ return self.lm_head
1341
+
1342
+ def set_output_embeddings(self, new_embeddings):
1343
+ self.lm_head = new_embeddings
1344
+
1345
+ def set_decoder(self, decoder):
1346
+ self.model.decoder = decoder
1347
+
1348
+ def get_decoder(self):
1349
+ return self.model.decoder
1350
+
1351
+ @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC)
1352
+ def forward(
1353
+ self,
1354
+ input_ids: Optional[torch.LongTensor] = None,
1355
+ attention_mask: Optional[torch.Tensor] = None,
1356
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
1357
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
1358
+ head_mask: Optional[torch.Tensor] = None,
1359
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1360
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1361
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1362
+ labels: Optional[torch.LongTensor] = None,
1363
+ use_cache: Optional[bool] = None,
1364
+ output_attentions: Optional[bool] = None,
1365
+ output_hidden_states: Optional[bool] = None,
1366
+ return_dict: Optional[bool] = None,
1367
+ ) -> Union[Tuple, CausalLMOutputWithCrossAttentions]:
1368
+ r"""
1369
+ Args:
1370
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1371
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
1372
+ provide it.
1373
+
1374
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1375
+ [`PreTrainedTokenizer.__call__`] for details.
1376
+
1377
+ [What are input IDs?](../glossary#input-ids)
1378
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1379
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1380
+
1381
+ - 1 for tokens that are **not masked**,
1382
+ - 0 for tokens that are **masked**.
1383
+
1384
+ [What are attention masks?](../glossary#attention-mask)
1385
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1386
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
1387
+ if the model is configured as a decoder.
1388
+ encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*):
1389
+ Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used
1390
+ in the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`:
1391
+ head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1392
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
1393
+
1394
+ - 1 indicates the head is **not masked**,
1395
+ - 0 indicates the head is **masked**.
1396
+
1397
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1398
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
1399
+
1400
+ - 1 indicates the head is **not masked**,
1401
+ - 0 indicates the head is **masked**.
1402
+
1403
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1404
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1405
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
1406
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional
1407
+ tensors are only required when the model is used as a decoder in a Sequence to Sequence model.
1408
+
1409
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
1410
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
1411
+
1412
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
1413
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
1414
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
1415
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1416
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1417
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1418
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1419
+ use_cache (`bool`, *optional*):
1420
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
1421
+ (see `past_key_values`).
1422
+
1423
+ - 1 for tokens that are **not masked**,
1424
+ - 0 for tokens that are **masked**.
1425
+ output_attentions (`bool`, *optional*):
1426
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1427
+ returned tensors for more detail.
1428
+ output_hidden_states (`bool`, *optional*):
1429
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1430
+ for more detail.
1431
+ return_dict (`bool`, *optional*):
1432
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1433
+
1434
+ Returns:
1435
+
1436
+ Example:
1437
+
1438
+ ```python
1439
+ >>> from transformers import AutoTokenizer, BlenderbotSmallForCausalLM
1440
+
1441
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
1442
+ >>> model = BlenderbotSmallForCausalLM.from_pretrained("facebook/blenderbot_small-90M", add_cross_attention=False)
1443
+ >>> assert model.config.is_decoder, f"{model.__class__} has to be configured as a decoder."
1444
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
1445
+ >>> outputs = model(**inputs)
1446
+
1447
+ >>> logits = outputs.logits
1448
+ >>> expected_shape = [1, inputs.input_ids.shape[-1], model.config.vocab_size]
1449
+ >>> list(logits.shape) == expected_shape
1450
+ True
1451
+ ```"""
1452
+
1453
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1454
+ output_hidden_states = (
1455
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1456
+ )
1457
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1458
+
1459
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1460
+ outputs = self.model.decoder(
1461
+ input_ids=input_ids,
1462
+ attention_mask=attention_mask,
1463
+ encoder_hidden_states=encoder_hidden_states,
1464
+ encoder_attention_mask=encoder_attention_mask,
1465
+ head_mask=head_mask,
1466
+ cross_attn_head_mask=cross_attn_head_mask,
1467
+ past_key_values=past_key_values,
1468
+ inputs_embeds=inputs_embeds,
1469
+ use_cache=use_cache,
1470
+ output_attentions=output_attentions,
1471
+ output_hidden_states=output_hidden_states,
1472
+ return_dict=return_dict,
1473
+ )
1474
+
1475
+ logits = self.lm_head(outputs[0])
1476
+
1477
+ loss = None
1478
+ if labels is not None:
1479
+ labels = labels.to(logits.device)
1480
+ loss_fct = CrossEntropyLoss()
1481
+ loss = loss_fct(logits.view(-1, self.config.vocab_size), labels.view(-1))
1482
+
1483
+ if not return_dict:
1484
+ output = (logits,) + outputs[1:]
1485
+ return (loss,) + output if loss is not None else output
1486
+
1487
+ return CausalLMOutputWithCrossAttentions(
1488
+ loss=loss,
1489
+ logits=logits,
1490
+ past_key_values=outputs.past_key_values,
1491
+ hidden_states=outputs.hidden_states,
1492
+ attentions=outputs.attentions,
1493
+ cross_attentions=outputs.cross_attentions,
1494
+ )
1495
+
1496
+ @staticmethod
1497
+ def _reorder_cache(past_key_values, beam_idx):
1498
+ reordered_past = ()
1499
+ for layer_past in past_key_values:
1500
+ reordered_past += (
1501
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1502
+ )
1503
+ return reordered_past
1504
+
1505
+
1506
+ __all__ = [
1507
+ "BlenderbotSmallForCausalLM",
1508
+ "BlenderbotSmallForConditionalGeneration",
1509
+ "BlenderbotSmallModel",
1510
+ "BlenderbotSmallPreTrainedModel",
1511
+ ]
lib/python3.12/site-packages/transformers/models/blenderbot_small/modeling_flax_blenderbot_small.py ADDED
@@ -0,0 +1,1528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Facebook, Inc. 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
+ """Flax BlenderbotSmall model."""
16
+
17
+ import math
18
+ import random
19
+ from functools import partial
20
+ from typing import Callable, Optional, Tuple
21
+
22
+ import flax.linen as nn
23
+ import jax
24
+ import jax.numpy as jnp
25
+ from flax.core.frozen_dict import FrozenDict, freeze, unfreeze
26
+ from flax.linen import combine_masks, make_causal_mask
27
+ from flax.linen.attention import dot_product_attention_weights
28
+ from flax.traverse_util import flatten_dict, unflatten_dict
29
+ from jax import lax
30
+ from jax.random import PRNGKey
31
+
32
+ from ...modeling_flax_outputs import (
33
+ FlaxBaseModelOutput,
34
+ FlaxBaseModelOutputWithPastAndCrossAttentions,
35
+ FlaxCausalLMOutputWithCrossAttentions,
36
+ FlaxSeq2SeqLMOutput,
37
+ FlaxSeq2SeqModelOutput,
38
+ )
39
+ from ...modeling_flax_utils import (
40
+ ACT2FN,
41
+ FlaxPreTrainedModel,
42
+ append_call_sample_docstring,
43
+ append_replace_return_docstrings,
44
+ overwrite_call_docstring,
45
+ )
46
+ from ...utils import add_start_docstrings, logging, replace_return_docstrings
47
+ from .configuration_blenderbot_small import BlenderbotSmallConfig
48
+
49
+
50
+ logger = logging.get_logger(__name__)
51
+
52
+ _CHECKPOINT_FOR_DOC = "facebook/blenderbot_small-90M"
53
+ _CONFIG_FOR_DOC = "BlenderbotSmallConfig"
54
+
55
+ BLENDERBOT_SMALL_START_DOCSTRING = r"""
56
+ This model inherits from [`FlaxPreTrainedModel`]. Check the superclass documentation for the generic methods the
57
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
58
+ etc.)
59
+
60
+ This model is also a Flax Linen
61
+ [flax.nn.Module](https://flax.readthedocs.io/en/latest/_autosummary/flax.nn.module.html) subclass. Use it as a
62
+ regular Flax Module and refer to the Flax documentation for all matter related to general usage and behavior.
63
+
64
+ Finally, this model supports inherent JAX features such as:
65
+
66
+ - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
67
+ - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
68
+ - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
69
+ - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
70
+
71
+ Parameters:
72
+ config ([`BlenderbotSmallConfig`]): Model configuration class with all the parameters of the model.
73
+ Initializing with a config file does not load the weights associated with the model, only the
74
+ configuration. Check out the [`~FlaxPreTrainedModel.from_pretrained`] method to load the model weights.
75
+ dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
76
+ The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
77
+ `jax.numpy.bfloat16` (on TPUs).
78
+
79
+ This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
80
+ specified all the computation will be performed with the given `dtype`.
81
+
82
+ **Note that this only specifies the dtype of the computation and does not influence the dtype of model
83
+ parameters.**
84
+
85
+ If you wish to change the dtype of the model parameters, see [`~FlaxPreTrainedModel.to_fp16`] and
86
+ [`~FlaxPreTrainedModel.to_bf16`].
87
+ """
88
+
89
+ BLENDERBOT_SMALL_INPUTS_DOCSTRING = r"""
90
+ Args:
91
+ input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
92
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
93
+ it.
94
+
95
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
96
+ [`PreTrainedTokenizer.__call__`] for details.
97
+
98
+ [What are input IDs?](../glossary#input-ids)
99
+ attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
100
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
101
+
102
+ - 1 for tokens that are **not masked**,
103
+ - 0 for tokens that are **masked**.
104
+
105
+ [What are attention masks?](../glossary#attention-mask)
106
+ decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
107
+ Indices of decoder input sequence tokens in the vocabulary.
108
+
109
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
110
+ [`PreTrainedTokenizer.__call__`] for details.
111
+
112
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
113
+
114
+ For translation and summarization training, `decoder_input_ids` should be provided. If no
115
+ `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
116
+ for denoising pre-training following the paper.
117
+ decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
118
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
119
+ be used by default.
120
+
121
+ If you want to change padding behavior, you should modify to your needs. See diagram 1 in [the
122
+ paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.
123
+ position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
124
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
125
+ config.max_position_embeddings - 1]`.
126
+ decoder_position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
127
+ Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
128
+ range `[0, config.max_position_embeddings - 1]`.
129
+ output_attentions (`bool`, *optional*):
130
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
131
+ tensors for more detail.
132
+ output_hidden_states (`bool`, *optional*):
133
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
134
+ more detail.
135
+ return_dict (`bool`, *optional*):
136
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
137
+ """
138
+
139
+
140
+ BLENDERBOT_SMALL_ENCODE_INPUTS_DOCSTRING = r"""
141
+ Args:
142
+ input_ids (`jnp.ndarray` of shape `(batch_size, sequence_length)`):
143
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
144
+ it.
145
+
146
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
147
+ [`PreTrainedTokenizer.__call__`] for details.
148
+
149
+ [What are input IDs?](../glossary#input-ids)
150
+ attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
151
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
152
+
153
+ - 1 for tokens that are **not masked**,
154
+ - 0 for tokens that are **masked**.
155
+
156
+ [What are attention masks?](../glossary#attention-mask)
157
+ position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
158
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
159
+ config.max_position_embeddings - 1]`.
160
+ output_attentions (`bool`, *optional*):
161
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
162
+ tensors for more detail.
163
+ output_hidden_states (`bool`, *optional*):
164
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
165
+ more detail.
166
+ return_dict (`bool`, *optional*):
167
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
168
+ """
169
+
170
+ BLENDERBOT_SMALL_DECODE_INPUTS_DOCSTRING = r"""
171
+ Args:
172
+ decoder_input_ids (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`):
173
+ Indices of decoder input sequence tokens in the vocabulary.
174
+
175
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
176
+ [`PreTrainedTokenizer.__call__`] for details.
177
+
178
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
179
+
180
+ For translation and summarization training, `decoder_input_ids` should be provided. If no
181
+ `decoder_input_ids` is provided, the model will create this tensor by shifting the `input_ids` to the right
182
+ for denoising pre-training following the paper.
183
+ encoder_outputs (`tuple(tuple(jnp.ndarray)`):
184
+ Tuple consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*: `attentions`)
185
+ `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*) is a sequence of
186
+ hidden-states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
187
+ encoder_attention_mask (`jnp.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
188
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
189
+
190
+ - 1 for tokens that are **not masked**,
191
+ - 0 for tokens that are **masked**.
192
+
193
+ [What are attention masks?](../glossary#attention-mask)
194
+ decoder_attention_mask (`jnp.ndarray` of shape `(batch_size, target_sequence_length)`, *optional*):
195
+ Default behavior: generate a tensor that ignores pad tokens in `decoder_input_ids`. Causal mask will also
196
+ be used by default.
197
+
198
+ If you want to change padding behavior, you should modify to your needs. See diagram 1 in [the
199
+ paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy.
200
+ decoder_position_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`, *optional*):
201
+ Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
202
+ range `[0, config.max_position_embeddings - 1]`.
203
+ past_key_values (`Dict[str, np.ndarray]`, *optional*, returned by `init_cache` or when passing previous `past_key_values`):
204
+ Dictionary of pre-computed hidden-states (key and values in the attention blocks) that can be used for fast
205
+ auto-regressive decoding. Pre-computed key and value hidden-states are of shape *[batch_size, max_length]*.
206
+ output_attentions (`bool`, *optional*):
207
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
208
+ tensors for more detail.
209
+ output_hidden_states (`bool`, *optional*):
210
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
211
+ more detail.
212
+ return_dict (`bool`, *optional*):
213
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
214
+ """
215
+
216
+
217
+ # Copied from transformers.models.bart.modeling_flax_bart.shift_tokens_right
218
+ def shift_tokens_right(input_ids: jnp.ndarray, pad_token_id: int, decoder_start_token_id: int) -> jnp.ndarray:
219
+ """
220
+ Shift input ids one token to the right.
221
+ """
222
+ shifted_input_ids = jnp.zeros_like(input_ids)
223
+ shifted_input_ids = shifted_input_ids.at[:, 1:].set(input_ids[:, :-1])
224
+ shifted_input_ids = shifted_input_ids.at[:, 0].set(decoder_start_token_id)
225
+
226
+ shifted_input_ids = jnp.where(shifted_input_ids == -100, pad_token_id, shifted_input_ids)
227
+ return shifted_input_ids
228
+
229
+
230
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartAttention with Bart->BlenderbotSmall
231
+ class FlaxBlenderbotSmallAttention(nn.Module):
232
+ config: BlenderbotSmallConfig
233
+ embed_dim: int
234
+ num_heads: int
235
+ dropout: float = 0.0
236
+ causal: bool = False
237
+ bias: bool = True
238
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
239
+
240
+ def setup(self) -> None:
241
+ self.head_dim = self.embed_dim // self.num_heads
242
+ if self.head_dim * self.num_heads != self.embed_dim:
243
+ raise ValueError(
244
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
245
+ f" and `num_heads`: {self.num_heads})."
246
+ )
247
+
248
+ dense = partial(
249
+ nn.Dense,
250
+ self.embed_dim,
251
+ use_bias=self.bias,
252
+ dtype=self.dtype,
253
+ kernel_init=jax.nn.initializers.normal(self.config.init_std),
254
+ )
255
+
256
+ self.q_proj, self.k_proj, self.v_proj = dense(), dense(), dense()
257
+ self.out_proj = dense()
258
+
259
+ self.dropout_layer = nn.Dropout(rate=self.dropout)
260
+
261
+ if self.causal:
262
+ self.causal_mask = make_causal_mask(
263
+ jnp.ones((1, self.config.max_position_embeddings), dtype="bool"), dtype="bool"
264
+ )
265
+
266
+ def _split_heads(self, hidden_states):
267
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.num_heads, self.head_dim))
268
+
269
+ def _merge_heads(self, hidden_states):
270
+ return hidden_states.reshape(hidden_states.shape[:2] + (self.embed_dim,))
271
+
272
+ @nn.compact
273
+ def _concatenate_to_cache(self, key, value, query, attention_mask):
274
+ """
275
+ This function takes projected key, value states from a single input token and concatenates the states to cached
276
+ states from previous steps. This function is slightly adapted from the official Flax repository:
277
+ https://github.com/google/flax/blob/491ce18759622506588784b4fca0e4bf05f8c8cd/flax/linen/attention.py#L252
278
+ """
279
+ # detect if we're initializing by absence of existing cache data.
280
+ is_initialized = self.has_variable("cache", "cached_key")
281
+ cached_key = self.variable("cache", "cached_key", jnp.zeros, key.shape, key.dtype)
282
+ cached_value = self.variable("cache", "cached_value", jnp.zeros, value.shape, value.dtype)
283
+ cache_index = self.variable("cache", "cache_index", lambda: jnp.array(0, dtype=jnp.int32))
284
+
285
+ if is_initialized:
286
+ *batch_dims, max_length, num_heads, depth_per_head = cached_key.value.shape
287
+ # update key, value caches with our new 1d spatial slices
288
+ cur_index = cache_index.value
289
+ indices = (0,) * len(batch_dims) + (cur_index, 0, 0)
290
+ key = lax.dynamic_update_slice(cached_key.value, key, indices)
291
+ value = lax.dynamic_update_slice(cached_value.value, value, indices)
292
+ cached_key.value = key
293
+ cached_value.value = value
294
+ num_updated_cache_vectors = query.shape[1]
295
+ cache_index.value = cache_index.value + num_updated_cache_vectors
296
+ # causal mask for cached decoder self-attention: our single query position should only attend to those key positions that have already been generated and cached, not the remaining zero elements.
297
+ pad_mask = jnp.broadcast_to(
298
+ jnp.arange(max_length) < cur_index + num_updated_cache_vectors,
299
+ tuple(batch_dims) + (1, num_updated_cache_vectors, max_length),
300
+ )
301
+ attention_mask = combine_masks(pad_mask, attention_mask)
302
+ return key, value, attention_mask
303
+
304
+ def __call__(
305
+ self,
306
+ hidden_states: jnp.ndarray,
307
+ key_value_states: Optional[jnp.ndarray] = None,
308
+ attention_mask: Optional[jnp.ndarray] = None,
309
+ init_cache: bool = False,
310
+ deterministic: bool = True,
311
+ ) -> Tuple[jnp.ndarray]:
312
+ """Input shape: Batch x Time x Channel"""
313
+
314
+ # if key_value_states are provided this layer is used as a cross-attention layer
315
+ # for the decoder
316
+ is_cross_attention = key_value_states is not None
317
+ batch_size = hidden_states.shape[0]
318
+
319
+ # get query proj
320
+ query_states = self.q_proj(hidden_states)
321
+ # get key, value proj
322
+ if is_cross_attention:
323
+ # cross_attentions
324
+ key_states = self.k_proj(key_value_states)
325
+ value_states = self.v_proj(key_value_states)
326
+ else:
327
+ # self_attention
328
+ key_states = self.k_proj(hidden_states)
329
+ value_states = self.v_proj(hidden_states)
330
+
331
+ query_states = self._split_heads(query_states)
332
+ key_states = self._split_heads(key_states)
333
+ value_states = self._split_heads(value_states)
334
+
335
+ # handle cache prepare causal attention mask
336
+ if self.causal:
337
+ query_length, key_length = query_states.shape[1], key_states.shape[1]
338
+ if self.has_variable("cache", "cached_key"):
339
+ mask_shift = self.variables["cache"]["cache_index"]
340
+ max_decoder_length = self.variables["cache"]["cached_key"].shape[1]
341
+ causal_mask = lax.dynamic_slice(
342
+ self.causal_mask, (0, 0, mask_shift, 0), (1, 1, query_length, max_decoder_length)
343
+ )
344
+ else:
345
+ causal_mask = self.causal_mask[:, :, :query_length, :key_length]
346
+ causal_mask = jnp.broadcast_to(causal_mask, (batch_size,) + causal_mask.shape[1:])
347
+
348
+ # combine masks if needed
349
+ if attention_mask is not None and self.causal:
350
+ attention_mask = jnp.broadcast_to(jnp.expand_dims(attention_mask, axis=(-3, -2)), causal_mask.shape)
351
+ attention_mask = combine_masks(attention_mask, causal_mask)
352
+ elif self.causal:
353
+ attention_mask = causal_mask
354
+ elif attention_mask is not None:
355
+ attention_mask = jnp.expand_dims(attention_mask, axis=(-3, -2))
356
+
357
+ # During fast autoregressive decoding, we feed one position at a time,
358
+ # and cache the keys and values step by step.
359
+ if self.causal and (self.has_variable("cache", "cached_key") or init_cache):
360
+ key_states, value_states, attention_mask = self._concatenate_to_cache(
361
+ key_states, value_states, query_states, attention_mask
362
+ )
363
+
364
+ # Convert the boolean attention mask to an attention bias.
365
+ if attention_mask is not None:
366
+ # attention mask in the form of attention bias
367
+ attention_bias = lax.select(
368
+ attention_mask > 0,
369
+ jnp.full(attention_mask.shape, 0.0).astype(self.dtype),
370
+ jnp.full(attention_mask.shape, jnp.finfo(self.dtype).min).astype(self.dtype),
371
+ )
372
+ else:
373
+ attention_bias = None
374
+
375
+ dropout_rng = None
376
+ if not deterministic and self.dropout > 0.0:
377
+ dropout_rng = self.make_rng("dropout")
378
+
379
+ attn_weights = dot_product_attention_weights(
380
+ query_states,
381
+ key_states,
382
+ bias=attention_bias,
383
+ dropout_rng=dropout_rng,
384
+ dropout_rate=self.dropout,
385
+ broadcast_dropout=True,
386
+ deterministic=deterministic,
387
+ dtype=self.dtype,
388
+ precision=None,
389
+ )
390
+
391
+ attn_output = jnp.einsum("...hqk,...khd->...qhd", attn_weights, value_states)
392
+ attn_output = self._merge_heads(attn_output)
393
+ attn_output = self.out_proj(attn_output)
394
+
395
+ return attn_output, attn_weights
396
+
397
+
398
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartEncoderLayer with Bart->BlenderbotSmall
399
+ class FlaxBlenderbotSmallEncoderLayer(nn.Module):
400
+ config: BlenderbotSmallConfig
401
+ dtype: jnp.dtype = jnp.float32
402
+
403
+ def setup(self) -> None:
404
+ self.embed_dim = self.config.d_model
405
+ self.self_attn = FlaxBlenderbotSmallAttention(
406
+ config=self.config,
407
+ embed_dim=self.embed_dim,
408
+ num_heads=self.config.encoder_attention_heads,
409
+ dropout=self.config.attention_dropout,
410
+ dtype=self.dtype,
411
+ )
412
+ self.self_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
413
+ self.dropout_layer = nn.Dropout(rate=self.config.dropout)
414
+ self.activation_fn = ACT2FN[self.config.activation_function]
415
+ self.activation_dropout_layer = nn.Dropout(rate=self.config.activation_dropout)
416
+ self.fc1 = nn.Dense(
417
+ self.config.encoder_ffn_dim,
418
+ dtype=self.dtype,
419
+ kernel_init=jax.nn.initializers.normal(self.config.init_std),
420
+ )
421
+ self.fc2 = nn.Dense(
422
+ self.embed_dim, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(self.config.init_std)
423
+ )
424
+ self.final_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
425
+
426
+ def __call__(
427
+ self,
428
+ hidden_states: jnp.ndarray,
429
+ attention_mask: jnp.ndarray,
430
+ output_attentions: bool = True,
431
+ deterministic: bool = True,
432
+ ) -> Tuple[jnp.ndarray]:
433
+ residual = hidden_states
434
+ hidden_states, attn_weights = self.self_attn(hidden_states=hidden_states, attention_mask=attention_mask)
435
+
436
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
437
+ hidden_states = residual + hidden_states
438
+ hidden_states = self.self_attn_layer_norm(hidden_states)
439
+
440
+ residual = hidden_states
441
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
442
+ hidden_states = self.activation_dropout_layer(hidden_states, deterministic=deterministic)
443
+ hidden_states = self.fc2(hidden_states)
444
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
445
+ hidden_states = residual + hidden_states
446
+ hidden_states = self.final_layer_norm(hidden_states)
447
+
448
+ outputs = (hidden_states,)
449
+
450
+ if output_attentions:
451
+ outputs += (attn_weights,)
452
+
453
+ return outputs
454
+
455
+
456
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartEncoderLayerCollection with Bart->BlenderbotSmall
457
+ class FlaxBlenderbotSmallEncoderLayerCollection(nn.Module):
458
+ config: BlenderbotSmallConfig
459
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
460
+
461
+ def setup(self):
462
+ self.layers = [
463
+ FlaxBlenderbotSmallEncoderLayer(self.config, name=str(i), dtype=self.dtype)
464
+ for i in range(self.config.encoder_layers)
465
+ ]
466
+ self.layerdrop = self.config.encoder_layerdrop
467
+
468
+ def __call__(
469
+ self,
470
+ hidden_states,
471
+ attention_mask,
472
+ deterministic: bool = True,
473
+ output_attentions: bool = False,
474
+ output_hidden_states: bool = False,
475
+ return_dict: bool = True,
476
+ ):
477
+ all_attentions = () if output_attentions else None
478
+ all_hidden_states = () if output_hidden_states else None
479
+
480
+ for encoder_layer in self.layers:
481
+ if output_hidden_states:
482
+ all_hidden_states = all_hidden_states + (hidden_states,)
483
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
484
+ dropout_probability = random.uniform(0, 1)
485
+ if not deterministic and (dropout_probability < self.layerdrop): # skip the layer
486
+ layer_outputs = (None, None)
487
+ else:
488
+ layer_outputs = encoder_layer(
489
+ hidden_states,
490
+ attention_mask,
491
+ output_attentions,
492
+ deterministic,
493
+ )
494
+ hidden_states = layer_outputs[0]
495
+ if output_attentions:
496
+ all_attentions = all_attentions + (layer_outputs[1],)
497
+
498
+ if output_hidden_states:
499
+ all_hidden_states += (hidden_states,)
500
+
501
+ outputs = (hidden_states, all_hidden_states, all_attentions)
502
+
503
+ if not return_dict:
504
+ return tuple(v for v in outputs if v is not None)
505
+
506
+ return FlaxBaseModelOutput(
507
+ last_hidden_state=hidden_states, hidden_states=all_hidden_states, attentions=all_attentions
508
+ )
509
+
510
+
511
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartDecoderLayer with Bart->BlenderbotSmall
512
+ class FlaxBlenderbotSmallDecoderLayer(nn.Module):
513
+ config: BlenderbotSmallConfig
514
+ dtype: jnp.dtype = jnp.float32
515
+
516
+ def setup(self) -> None:
517
+ self.embed_dim = self.config.d_model
518
+ self.self_attn = FlaxBlenderbotSmallAttention(
519
+ config=self.config,
520
+ embed_dim=self.embed_dim,
521
+ num_heads=self.config.decoder_attention_heads,
522
+ dropout=self.config.attention_dropout,
523
+ causal=True,
524
+ dtype=self.dtype,
525
+ )
526
+ self.dropout_layer = nn.Dropout(rate=self.config.dropout)
527
+ self.activation_fn = ACT2FN[self.config.activation_function]
528
+ self.activation_dropout_layer = nn.Dropout(rate=self.config.activation_dropout)
529
+
530
+ self.self_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
531
+ self.encoder_attn = FlaxBlenderbotSmallAttention(
532
+ config=self.config,
533
+ embed_dim=self.embed_dim,
534
+ num_heads=self.config.decoder_attention_heads,
535
+ dropout=self.config.attention_dropout,
536
+ dtype=self.dtype,
537
+ )
538
+ self.encoder_attn_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
539
+ self.fc1 = nn.Dense(
540
+ self.config.decoder_ffn_dim,
541
+ dtype=self.dtype,
542
+ kernel_init=jax.nn.initializers.normal(self.config.init_std),
543
+ )
544
+ self.fc2 = nn.Dense(
545
+ self.embed_dim, dtype=self.dtype, kernel_init=jax.nn.initializers.normal(self.config.init_std)
546
+ )
547
+ self.final_layer_norm = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
548
+
549
+ def __call__(
550
+ self,
551
+ hidden_states: jnp.ndarray,
552
+ attention_mask: jnp.ndarray,
553
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
554
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
555
+ init_cache: bool = False,
556
+ output_attentions: bool = True,
557
+ deterministic: bool = True,
558
+ ) -> Tuple[jnp.ndarray]:
559
+ residual = hidden_states
560
+
561
+ # Self Attention
562
+ hidden_states, self_attn_weights = self.self_attn(
563
+ hidden_states=hidden_states, attention_mask=attention_mask, init_cache=init_cache
564
+ )
565
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
566
+ hidden_states = residual + hidden_states
567
+ hidden_states = self.self_attn_layer_norm(hidden_states)
568
+
569
+ # Cross-Attention Block
570
+ cross_attn_weights = None
571
+ if encoder_hidden_states is not None:
572
+ residual = hidden_states
573
+
574
+ hidden_states, cross_attn_weights = self.encoder_attn(
575
+ hidden_states=hidden_states,
576
+ key_value_states=encoder_hidden_states,
577
+ attention_mask=encoder_attention_mask,
578
+ )
579
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
580
+ hidden_states = residual + hidden_states
581
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
582
+
583
+ # Fully Connected
584
+ residual = hidden_states
585
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
586
+ hidden_states = self.activation_dropout_layer(hidden_states, deterministic=deterministic)
587
+ hidden_states = self.fc2(hidden_states)
588
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
589
+ hidden_states = residual + hidden_states
590
+ hidden_states = self.final_layer_norm(hidden_states)
591
+
592
+ outputs = (hidden_states,)
593
+
594
+ if output_attentions:
595
+ outputs += (self_attn_weights, cross_attn_weights)
596
+
597
+ return outputs
598
+
599
+
600
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartDecoderLayerCollection with Bart->BlenderbotSmall
601
+ class FlaxBlenderbotSmallDecoderLayerCollection(nn.Module):
602
+ config: BlenderbotSmallConfig
603
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
604
+
605
+ def setup(self):
606
+ self.layers = [
607
+ FlaxBlenderbotSmallDecoderLayer(self.config, name=str(i), dtype=self.dtype)
608
+ for i in range(self.config.decoder_layers)
609
+ ]
610
+ self.layerdrop = self.config.decoder_layerdrop
611
+
612
+ def __call__(
613
+ self,
614
+ hidden_states,
615
+ attention_mask,
616
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
617
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
618
+ deterministic: bool = True,
619
+ init_cache: bool = False,
620
+ output_attentions: bool = False,
621
+ output_hidden_states: bool = False,
622
+ return_dict: bool = True,
623
+ ):
624
+ # decoder layers
625
+ all_hidden_states = () if output_hidden_states else None
626
+ all_self_attns = () if output_attentions else None
627
+ all_cross_attentions = () if (output_attentions and encoder_hidden_states is not None) else None
628
+
629
+ for decoder_layer in self.layers:
630
+ if output_hidden_states:
631
+ all_hidden_states += (hidden_states,)
632
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
633
+ dropout_probability = random.uniform(0, 1)
634
+ if not deterministic and (dropout_probability < self.layerdrop):
635
+ layer_outputs = (None, None, None)
636
+ else:
637
+ layer_outputs = decoder_layer(
638
+ hidden_states,
639
+ attention_mask=attention_mask,
640
+ encoder_hidden_states=encoder_hidden_states,
641
+ encoder_attention_mask=encoder_attention_mask,
642
+ init_cache=init_cache,
643
+ output_attentions=output_attentions,
644
+ deterministic=deterministic,
645
+ )
646
+
647
+ hidden_states = layer_outputs[0]
648
+ if output_attentions:
649
+ all_self_attns += (layer_outputs[1],)
650
+
651
+ if encoder_hidden_states is not None:
652
+ all_cross_attentions += (layer_outputs[2],)
653
+
654
+ # add hidden states from the last decoder layer
655
+ if output_hidden_states:
656
+ all_hidden_states += (hidden_states,)
657
+
658
+ outputs = [hidden_states, all_hidden_states, all_self_attns, all_cross_attentions]
659
+
660
+ if not return_dict:
661
+ return tuple(v for v in outputs if v is not None)
662
+
663
+ return FlaxBaseModelOutputWithPastAndCrossAttentions(
664
+ last_hidden_state=hidden_states,
665
+ hidden_states=all_hidden_states,
666
+ attentions=all_self_attns,
667
+ cross_attentions=all_cross_attentions,
668
+ )
669
+
670
+
671
+ class FlaxBlenderbotSmallEncoder(nn.Module):
672
+ config: BlenderbotSmallConfig
673
+ embed_tokens: nn.Embed
674
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
675
+
676
+ def setup(self):
677
+ self.dropout_layer = nn.Dropout(rate=self.config.dropout)
678
+
679
+ embed_dim = self.config.d_model
680
+ self.padding_idx = self.config.pad_token_id
681
+ self.max_source_positions = self.config.max_position_embeddings
682
+ self.embed_scale = math.sqrt(embed_dim) if self.config.scale_embedding else 1.0
683
+
684
+ self.embed_positions = nn.Embed(
685
+ self.config.max_position_embeddings,
686
+ embed_dim,
687
+ embedding_init=jax.nn.initializers.normal(self.config.init_std),
688
+ )
689
+ self.layers = FlaxBlenderbotSmallEncoderLayerCollection(self.config, self.dtype)
690
+ self.layernorm_embedding = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
691
+
692
+ def __call__(
693
+ self,
694
+ input_ids,
695
+ attention_mask,
696
+ position_ids,
697
+ output_attentions: bool = False,
698
+ output_hidden_states: bool = False,
699
+ return_dict: bool = True,
700
+ deterministic: bool = True,
701
+ ):
702
+ input_shape = input_ids.shape
703
+ input_ids = input_ids.reshape(-1, input_shape[-1])
704
+
705
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
706
+
707
+ embed_pos = self.embed_positions(position_ids)
708
+
709
+ hidden_states = inputs_embeds + embed_pos
710
+ hidden_states = self.layernorm_embedding(hidden_states)
711
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
712
+
713
+ outputs = self.layers(
714
+ hidden_states,
715
+ attention_mask,
716
+ deterministic=deterministic,
717
+ output_attentions=output_attentions,
718
+ output_hidden_states=output_hidden_states,
719
+ return_dict=return_dict,
720
+ )
721
+
722
+ if not return_dict:
723
+ return outputs
724
+
725
+ return FlaxBaseModelOutput(
726
+ last_hidden_state=outputs.last_hidden_state,
727
+ hidden_states=outputs.hidden_states,
728
+ attentions=outputs.attentions,
729
+ )
730
+
731
+
732
+ class FlaxBlenderbotSmallDecoder(nn.Module):
733
+ config: BlenderbotSmallConfig
734
+ embed_tokens: nn.Embed
735
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
736
+
737
+ def setup(self):
738
+ self.dropout_layer = nn.Dropout(rate=self.config.dropout)
739
+
740
+ embed_dim = self.config.d_model
741
+ self.padding_idx = self.config.pad_token_id
742
+ self.max_target_positions = self.config.max_position_embeddings
743
+ self.embed_scale = math.sqrt(self.config.d_model) if self.config.scale_embedding else 1.0
744
+
745
+ self.embed_positions = nn.Embed(
746
+ self.config.max_position_embeddings,
747
+ embed_dim,
748
+ embedding_init=jax.nn.initializers.normal(self.config.init_std),
749
+ )
750
+
751
+ self.layers = FlaxBlenderbotSmallDecoderLayerCollection(self.config, self.dtype)
752
+ self.layernorm_embedding = nn.LayerNorm(dtype=self.dtype, epsilon=1e-05)
753
+
754
+ def __call__(
755
+ self,
756
+ input_ids,
757
+ attention_mask,
758
+ position_ids,
759
+ encoder_hidden_states: Optional[jnp.ndarray] = None,
760
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
761
+ init_cache: bool = False,
762
+ output_attentions: bool = False,
763
+ output_hidden_states: bool = False,
764
+ return_dict: bool = True,
765
+ deterministic: bool = True,
766
+ ):
767
+ input_shape = input_ids.shape
768
+ input_ids = input_ids.reshape(-1, input_shape[-1])
769
+
770
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
771
+
772
+ # embed positions
773
+ positions = self.embed_positions(position_ids)
774
+
775
+ # BlenderbotSmall applies layer norm on inputs_embeds in decoder
776
+ inputs_embeds = self.layernorm_embedding(inputs_embeds)
777
+ hidden_states = inputs_embeds + positions
778
+
779
+ hidden_states = self.dropout_layer(hidden_states, deterministic=deterministic)
780
+
781
+ outputs = self.layers(
782
+ hidden_states,
783
+ attention_mask,
784
+ encoder_hidden_states,
785
+ encoder_attention_mask,
786
+ deterministic=deterministic,
787
+ init_cache=init_cache,
788
+ output_attentions=output_attentions,
789
+ output_hidden_states=output_hidden_states,
790
+ return_dict=return_dict,
791
+ )
792
+
793
+ if not return_dict:
794
+ return outputs
795
+
796
+ return FlaxBaseModelOutputWithPastAndCrossAttentions(
797
+ last_hidden_state=outputs.last_hidden_state,
798
+ hidden_states=outputs.hidden_states,
799
+ attentions=outputs.attentions,
800
+ cross_attentions=outputs.cross_attentions,
801
+ )
802
+
803
+
804
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartModule with Bart->BlenderbotSmall
805
+ class FlaxBlenderbotSmallModule(nn.Module):
806
+ config: BlenderbotSmallConfig
807
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
808
+
809
+ def setup(self):
810
+ self.shared = nn.Embed(
811
+ self.config.vocab_size,
812
+ self.config.d_model,
813
+ embedding_init=jax.nn.initializers.normal(self.config.init_std),
814
+ dtype=self.dtype,
815
+ )
816
+
817
+ self.encoder = FlaxBlenderbotSmallEncoder(self.config, dtype=self.dtype, embed_tokens=self.shared)
818
+ self.decoder = FlaxBlenderbotSmallDecoder(self.config, dtype=self.dtype, embed_tokens=self.shared)
819
+
820
+ def _get_encoder_module(self):
821
+ return self.encoder
822
+
823
+ def _get_decoder_module(self):
824
+ return self.decoder
825
+
826
+ def __call__(
827
+ self,
828
+ input_ids,
829
+ attention_mask,
830
+ decoder_input_ids,
831
+ decoder_attention_mask,
832
+ position_ids,
833
+ decoder_position_ids,
834
+ output_attentions: bool = False,
835
+ output_hidden_states: bool = False,
836
+ return_dict: bool = True,
837
+ deterministic: bool = True,
838
+ ):
839
+ encoder_outputs = self.encoder(
840
+ input_ids=input_ids,
841
+ attention_mask=attention_mask,
842
+ position_ids=position_ids,
843
+ output_attentions=output_attentions,
844
+ output_hidden_states=output_hidden_states,
845
+ return_dict=return_dict,
846
+ deterministic=deterministic,
847
+ )
848
+
849
+ decoder_outputs = self.decoder(
850
+ input_ids=decoder_input_ids,
851
+ attention_mask=decoder_attention_mask,
852
+ position_ids=decoder_position_ids,
853
+ encoder_hidden_states=encoder_outputs[0],
854
+ encoder_attention_mask=attention_mask,
855
+ output_attentions=output_attentions,
856
+ output_hidden_states=output_hidden_states,
857
+ return_dict=return_dict,
858
+ deterministic=deterministic,
859
+ )
860
+
861
+ if not return_dict:
862
+ return decoder_outputs + encoder_outputs
863
+
864
+ return FlaxSeq2SeqModelOutput(
865
+ last_hidden_state=decoder_outputs.last_hidden_state,
866
+ decoder_hidden_states=decoder_outputs.hidden_states,
867
+ decoder_attentions=decoder_outputs.attentions,
868
+ cross_attentions=decoder_outputs.cross_attentions,
869
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
870
+ encoder_hidden_states=encoder_outputs.hidden_states,
871
+ encoder_attentions=encoder_outputs.attentions,
872
+ )
873
+
874
+
875
+ class FlaxBlenderbotSmallPreTrainedModel(FlaxPreTrainedModel):
876
+ config_class = BlenderbotSmallConfig
877
+ base_model_prefix: str = "model"
878
+ module_class: nn.Module = None
879
+
880
+ def __init__(
881
+ self,
882
+ config: BlenderbotSmallConfig,
883
+ input_shape: Tuple[int] = (1, 1),
884
+ seed: int = 0,
885
+ dtype: jnp.dtype = jnp.float32,
886
+ _do_init: bool = True,
887
+ **kwargs,
888
+ ):
889
+ module = self.module_class(config=config, dtype=dtype, **kwargs)
890
+ super().__init__(config, module, input_shape=input_shape, seed=seed, dtype=dtype, _do_init=_do_init)
891
+
892
+ def init_weights(self, rng: jax.random.PRNGKey, input_shape: Tuple, params: FrozenDict = None) -> FrozenDict:
893
+ # init input tensors
894
+ input_ids = jnp.zeros(input_shape, dtype="i4")
895
+ # make sure initialization pass will work for FlaxBlenderbotSmallForSequenceClassificationModule
896
+ input_ids = input_ids.at[(..., -1)].set(self.config.eos_token_id)
897
+ attention_mask = jnp.ones_like(input_ids)
898
+ decoder_input_ids = input_ids
899
+ decoder_attention_mask = jnp.ones_like(input_ids)
900
+
901
+ batch_size, sequence_length = input_ids.shape
902
+ position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
903
+ decoder_position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
904
+
905
+ params_rng, dropout_rng = jax.random.split(rng)
906
+ rngs = {"params": params_rng, "dropout": dropout_rng}
907
+
908
+ random_params = self.module.init(
909
+ rngs,
910
+ input_ids,
911
+ attention_mask,
912
+ decoder_input_ids,
913
+ decoder_attention_mask,
914
+ position_ids,
915
+ decoder_position_ids,
916
+ )["params"]
917
+
918
+ if params is not None:
919
+ random_params = flatten_dict(unfreeze(random_params))
920
+ params = flatten_dict(unfreeze(params))
921
+ for missing_key in self._missing_keys:
922
+ params[missing_key] = random_params[missing_key]
923
+ self._missing_keys = set()
924
+ return freeze(unflatten_dict(params))
925
+ else:
926
+ return random_params
927
+
928
+ def init_cache(self, batch_size, max_length, encoder_outputs):
929
+ r"""
930
+ Args:
931
+ batch_size (`int`):
932
+ batch_size used for fast auto-regressive decoding. Defines the batch size of the initialized cache.
933
+ max_length (`int`):
934
+ maximum possible length for auto-regressive decoding. Defines the sequence length of the initialized
935
+ cache.
936
+ encoder_outputs (`Union[FlaxBaseModelOutput, tuple(tuple(jnp.ndarray)]`):
937
+ `encoder_outputs` consists of (`last_hidden_state`, *optional*: `hidden_states`, *optional*:
938
+ `attentions`). `last_hidden_state` of shape `(batch_size, sequence_length, hidden_size)`, *optional*)
939
+ is a sequence of hidden-states at the output of the last layer of the encoder. Used in the
940
+ cross-attention of the decoder.
941
+ """
942
+ # init input variables to retrieve cache
943
+ decoder_input_ids = jnp.ones((batch_size, max_length), dtype="i4")
944
+ decoder_attention_mask = jnp.ones_like(decoder_input_ids)
945
+ decoder_position_ids = jnp.broadcast_to(
946
+ jnp.arange(jnp.atleast_2d(decoder_input_ids).shape[-1]), decoder_input_ids.shape
947
+ )
948
+
949
+ def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
950
+ decoder_module = module._get_decoder_module()
951
+ return decoder_module(
952
+ decoder_input_ids,
953
+ decoder_attention_mask,
954
+ decoder_position_ids,
955
+ **kwargs,
956
+ )
957
+
958
+ init_variables = self.module.init(
959
+ jax.random.PRNGKey(0),
960
+ decoder_input_ids=decoder_input_ids,
961
+ decoder_attention_mask=decoder_attention_mask,
962
+ decoder_position_ids=decoder_position_ids,
963
+ encoder_hidden_states=encoder_outputs[0],
964
+ init_cache=True,
965
+ method=_decoder_forward, # we only need to call the decoder to init the cache
966
+ )
967
+ return unfreeze(init_variables["cache"])
968
+
969
+ @add_start_docstrings(BLENDERBOT_SMALL_ENCODE_INPUTS_DOCSTRING)
970
+ @replace_return_docstrings(output_type=FlaxBaseModelOutput, config_class=BlenderbotSmallConfig)
971
+ def encode(
972
+ self,
973
+ input_ids: jnp.ndarray,
974
+ attention_mask: Optional[jnp.ndarray] = None,
975
+ position_ids: Optional[jnp.ndarray] = None,
976
+ output_attentions: Optional[bool] = None,
977
+ output_hidden_states: Optional[bool] = None,
978
+ return_dict: Optional[bool] = None,
979
+ train: bool = False,
980
+ params: dict = None,
981
+ dropout_rng: PRNGKey = None,
982
+ ):
983
+ r"""
984
+ Returns:
985
+
986
+ Example:
987
+
988
+ ```python
989
+ >>> from transformers import AutoTokenizer, FlaxBlenderbotSmallForConditionalGeneration
990
+
991
+ >>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained("facebook/blenderbot_small-90M")
992
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
993
+
994
+ >>> text = "My friends are cool but they eat too many carbs."
995
+ >>> inputs = tokenizer(text, max_length=1024, return_tensors="np")
996
+ >>> encoder_outputs = model.encode(**inputs)
997
+ ```"""
998
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
999
+ output_hidden_states = (
1000
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1001
+ )
1002
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1003
+
1004
+ if attention_mask is None:
1005
+ attention_mask = jnp.ones_like(input_ids)
1006
+ if position_ids is None:
1007
+ batch_size, sequence_length = input_ids.shape
1008
+ position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
1009
+
1010
+ # Handle any PRNG if needed
1011
+ rngs = {}
1012
+ if dropout_rng is not None:
1013
+ rngs["dropout"] = dropout_rng
1014
+
1015
+ def _encoder_forward(module, input_ids, attention_mask, position_ids, **kwargs):
1016
+ encode_module = module._get_encoder_module()
1017
+ return encode_module(input_ids, attention_mask, position_ids, **kwargs)
1018
+
1019
+ return self.module.apply(
1020
+ {"params": params or self.params},
1021
+ input_ids=jnp.array(input_ids, dtype="i4"),
1022
+ attention_mask=jnp.array(attention_mask, dtype="i4"),
1023
+ position_ids=jnp.array(position_ids, dtype="i4"),
1024
+ output_attentions=output_attentions,
1025
+ output_hidden_states=output_hidden_states,
1026
+ return_dict=return_dict,
1027
+ deterministic=not train,
1028
+ rngs=rngs,
1029
+ method=_encoder_forward,
1030
+ )
1031
+
1032
+ @add_start_docstrings(BLENDERBOT_SMALL_DECODE_INPUTS_DOCSTRING)
1033
+ @replace_return_docstrings(
1034
+ output_type=FlaxBaseModelOutputWithPastAndCrossAttentions, config_class=BlenderbotSmallConfig
1035
+ )
1036
+ def decode(
1037
+ self,
1038
+ decoder_input_ids,
1039
+ encoder_outputs,
1040
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
1041
+ decoder_attention_mask: Optional[jnp.ndarray] = None,
1042
+ decoder_position_ids: Optional[jnp.ndarray] = None,
1043
+ past_key_values: dict = None,
1044
+ output_attentions: Optional[bool] = None,
1045
+ output_hidden_states: Optional[bool] = None,
1046
+ return_dict: Optional[bool] = None,
1047
+ train: bool = False,
1048
+ params: dict = None,
1049
+ dropout_rng: PRNGKey = None,
1050
+ ):
1051
+ r"""
1052
+ Returns:
1053
+
1054
+ Example:
1055
+
1056
+ ```python
1057
+ >>> import jax.numpy as jnp
1058
+ >>> from transformers import AutoTokenizer, FlaxBlenderbotSmallForConditionalGeneration
1059
+
1060
+ >>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained("facebook/blenderbot_small-90M")
1061
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
1062
+
1063
+ >>> text = "My friends are cool but they eat too many carbs."
1064
+ >>> inputs = tokenizer(text, max_length=1024, return_tensors="np")
1065
+ >>> encoder_outputs = model.encode(**inputs)
1066
+
1067
+ >>> decoder_start_token_id = model.config.decoder_start_token_id
1068
+ >>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id
1069
+
1070
+ >>> outputs = model.decode(decoder_input_ids, encoder_outputs)
1071
+ >>> last_decoder_hidden_states = outputs.last_hidden_state
1072
+ ```"""
1073
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1074
+ output_hidden_states = (
1075
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1076
+ )
1077
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1078
+
1079
+ encoder_hidden_states = encoder_outputs[0]
1080
+ if encoder_attention_mask is None:
1081
+ batch_size, sequence_length = encoder_hidden_states.shape[:2]
1082
+ encoder_attention_mask = jnp.ones((batch_size, sequence_length))
1083
+
1084
+ batch_size, sequence_length = decoder_input_ids.shape
1085
+ if decoder_attention_mask is None:
1086
+ decoder_attention_mask = jnp.ones((batch_size, sequence_length))
1087
+
1088
+ if decoder_position_ids is None:
1089
+ if past_key_values is not None:
1090
+ raise ValueError("Make sure to provide `decoder_position_ids` when passing `past_key_values`.")
1091
+
1092
+ decoder_position_ids = jnp.broadcast_to(
1093
+ jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
1094
+ )
1095
+
1096
+ # Handle any PRNG if needed
1097
+ rngs = {}
1098
+ if dropout_rng is not None:
1099
+ rngs["dropout"] = dropout_rng
1100
+
1101
+ inputs = {"params": params or self.params}
1102
+
1103
+ # if past_key_values are passed then cache is already initialized a private flag init_cache has to be
1104
+ # passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that
1105
+ # it can be changed by FlaxBlenderbotSmallAttention module
1106
+ if past_key_values:
1107
+ inputs["cache"] = past_key_values
1108
+ mutable = ["cache"]
1109
+ else:
1110
+ mutable = False
1111
+
1112
+ def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
1113
+ decoder_module = module._get_decoder_module()
1114
+ return decoder_module(
1115
+ decoder_input_ids,
1116
+ decoder_attention_mask,
1117
+ decoder_position_ids,
1118
+ **kwargs,
1119
+ )
1120
+
1121
+ outputs = self.module.apply(
1122
+ inputs,
1123
+ decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
1124
+ decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
1125
+ decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
1126
+ encoder_hidden_states=encoder_hidden_states,
1127
+ encoder_attention_mask=jnp.array(encoder_attention_mask, dtype="i4"),
1128
+ output_attentions=output_attentions,
1129
+ output_hidden_states=output_hidden_states,
1130
+ return_dict=return_dict,
1131
+ deterministic=not train,
1132
+ rngs=rngs,
1133
+ mutable=mutable,
1134
+ method=_decoder_forward,
1135
+ )
1136
+
1137
+ # add updated cache to model output
1138
+ if past_key_values is not None and return_dict:
1139
+ outputs, past = outputs
1140
+ outputs["past_key_values"] = unfreeze(past["cache"])
1141
+ return outputs
1142
+ elif past_key_values is not None and not return_dict:
1143
+ outputs, past = outputs
1144
+ outputs = outputs[:1] + (unfreeze(past["cache"]),) + outputs[1:]
1145
+
1146
+ return outputs
1147
+
1148
+ def __call__(
1149
+ self,
1150
+ input_ids: jnp.ndarray,
1151
+ attention_mask: Optional[jnp.ndarray] = None,
1152
+ decoder_input_ids: Optional[jnp.ndarray] = None,
1153
+ decoder_attention_mask: Optional[jnp.ndarray] = None,
1154
+ position_ids: Optional[jnp.ndarray] = None,
1155
+ decoder_position_ids: Optional[jnp.ndarray] = None,
1156
+ output_attentions: Optional[bool] = None,
1157
+ output_hidden_states: Optional[bool] = None,
1158
+ return_dict: Optional[bool] = None,
1159
+ train: bool = False,
1160
+ params: dict = None,
1161
+ dropout_rng: PRNGKey = None,
1162
+ ):
1163
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1164
+ output_hidden_states = (
1165
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1166
+ )
1167
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1168
+
1169
+ # prepare encoder inputs
1170
+ if attention_mask is None:
1171
+ attention_mask = jnp.ones_like(input_ids)
1172
+ if position_ids is None:
1173
+ batch_size, sequence_length = input_ids.shape
1174
+ position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length))
1175
+
1176
+ # prepare decoder inputs
1177
+ if decoder_input_ids is None:
1178
+ decoder_input_ids = shift_tokens_right(
1179
+ input_ids, self.config.pad_token_id, decoder_start_token_id=self.config.decoder_start_token_id
1180
+ )
1181
+ if decoder_attention_mask is None:
1182
+ decoder_attention_mask = jnp.ones_like(decoder_input_ids)
1183
+ if decoder_position_ids is None:
1184
+ batch_size, sequence_length = decoder_input_ids.shape
1185
+ decoder_position_ids = jnp.broadcast_to(
1186
+ jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
1187
+ )
1188
+
1189
+ # Handle any PRNG if needed
1190
+ rngs = {"dropout": dropout_rng} if dropout_rng is not None else {}
1191
+
1192
+ return self.module.apply(
1193
+ {"params": params or self.params},
1194
+ input_ids=jnp.array(input_ids, dtype="i4"),
1195
+ attention_mask=jnp.array(attention_mask, dtype="i4"),
1196
+ position_ids=jnp.array(position_ids, dtype="i4"),
1197
+ decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
1198
+ decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
1199
+ decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
1200
+ output_attentions=output_attentions,
1201
+ output_hidden_states=output_hidden_states,
1202
+ return_dict=return_dict,
1203
+ deterministic=not train,
1204
+ rngs=rngs,
1205
+ )
1206
+
1207
+
1208
+ @add_start_docstrings(
1209
+ "The bare BlenderbotSmall Model transformer outputting raw hidden-states without any specific head on top.",
1210
+ BLENDERBOT_SMALL_START_DOCSTRING,
1211
+ )
1212
+ class FlaxBlenderbotSmallModel(FlaxBlenderbotSmallPreTrainedModel):
1213
+ config: BlenderbotSmallConfig
1214
+ dtype: jnp.dtype = jnp.float32 # the dtype of the computation
1215
+ module_class = FlaxBlenderbotSmallModule
1216
+
1217
+
1218
+ append_call_sample_docstring(FlaxBlenderbotSmallModel, _CHECKPOINT_FOR_DOC, FlaxSeq2SeqModelOutput, _CONFIG_FOR_DOC)
1219
+
1220
+
1221
+ # Copied from transformers.models.bart.modeling_flax_bart.FlaxBartForConditionalGenerationModule with Bart->BlenderbotSmall
1222
+ class FlaxBlenderbotSmallForConditionalGenerationModule(nn.Module):
1223
+ config: BlenderbotSmallConfig
1224
+ dtype: jnp.dtype = jnp.float32
1225
+ bias_init: Callable[..., jnp.ndarray] = jax.nn.initializers.zeros
1226
+
1227
+ def setup(self):
1228
+ self.model = FlaxBlenderbotSmallModule(config=self.config, dtype=self.dtype)
1229
+ self.lm_head = nn.Dense(
1230
+ self.model.shared.num_embeddings,
1231
+ use_bias=False,
1232
+ dtype=self.dtype,
1233
+ kernel_init=jax.nn.initializers.normal(self.config.init_std),
1234
+ )
1235
+ self.final_logits_bias = self.param("final_logits_bias", self.bias_init, (1, self.model.shared.num_embeddings))
1236
+
1237
+ def _get_encoder_module(self):
1238
+ return self.model.encoder
1239
+
1240
+ def _get_decoder_module(self):
1241
+ return self.model.decoder
1242
+
1243
+ def __call__(
1244
+ self,
1245
+ input_ids,
1246
+ attention_mask,
1247
+ decoder_input_ids,
1248
+ decoder_attention_mask,
1249
+ position_ids,
1250
+ decoder_position_ids,
1251
+ output_attentions: bool = False,
1252
+ output_hidden_states: bool = False,
1253
+ return_dict: bool = True,
1254
+ deterministic: bool = True,
1255
+ ):
1256
+ outputs = self.model(
1257
+ input_ids=input_ids,
1258
+ attention_mask=attention_mask,
1259
+ decoder_input_ids=decoder_input_ids,
1260
+ decoder_attention_mask=decoder_attention_mask,
1261
+ position_ids=position_ids,
1262
+ decoder_position_ids=decoder_position_ids,
1263
+ output_attentions=output_attentions,
1264
+ output_hidden_states=output_hidden_states,
1265
+ return_dict=return_dict,
1266
+ deterministic=deterministic,
1267
+ )
1268
+
1269
+ hidden_states = outputs[0]
1270
+
1271
+ if self.config.tie_word_embeddings:
1272
+ shared_embedding = self.model.variables["params"]["shared"]["embedding"]
1273
+ lm_logits = self.lm_head.apply({"params": {"kernel": shared_embedding.T}}, hidden_states)
1274
+ else:
1275
+ lm_logits = self.lm_head(hidden_states)
1276
+
1277
+ lm_logits += jax.lax.stop_gradient(self.final_logits_bias.astype(self.dtype))
1278
+
1279
+ if not return_dict:
1280
+ output = (lm_logits,) + outputs[1:]
1281
+ return output
1282
+
1283
+ return FlaxSeq2SeqLMOutput(
1284
+ logits=lm_logits,
1285
+ decoder_hidden_states=outputs.decoder_hidden_states,
1286
+ decoder_attentions=outputs.decoder_attentions,
1287
+ cross_attentions=outputs.cross_attentions,
1288
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1289
+ encoder_hidden_states=outputs.encoder_hidden_states,
1290
+ encoder_attentions=outputs.encoder_attentions,
1291
+ )
1292
+
1293
+
1294
+ @add_start_docstrings(
1295
+ "The BLENDERBOT_SMALL Model with a language modeling head. Can be used for summarization.",
1296
+ BLENDERBOT_SMALL_START_DOCSTRING,
1297
+ )
1298
+ class FlaxBlenderbotSmallForConditionalGeneration(FlaxBlenderbotSmallPreTrainedModel):
1299
+ module_class = FlaxBlenderbotSmallForConditionalGenerationModule
1300
+ dtype: jnp.dtype = jnp.float32
1301
+
1302
+ @add_start_docstrings(BLENDERBOT_SMALL_DECODE_INPUTS_DOCSTRING)
1303
+ @replace_return_docstrings(output_type=FlaxCausalLMOutputWithCrossAttentions, config_class=BlenderbotSmallConfig)
1304
+ def decode(
1305
+ self,
1306
+ decoder_input_ids,
1307
+ encoder_outputs,
1308
+ encoder_attention_mask: Optional[jnp.ndarray] = None,
1309
+ decoder_attention_mask: Optional[jnp.ndarray] = None,
1310
+ decoder_position_ids: Optional[jnp.ndarray] = None,
1311
+ past_key_values: dict = None,
1312
+ output_attentions: Optional[bool] = None,
1313
+ output_hidden_states: Optional[bool] = None,
1314
+ return_dict: Optional[bool] = None,
1315
+ deterministic: bool = True,
1316
+ params: dict = None,
1317
+ dropout_rng: PRNGKey = None,
1318
+ ):
1319
+ r"""
1320
+ Returns:
1321
+
1322
+ Example:
1323
+
1324
+ ```python
1325
+ >>> import jax.numpy as jnp
1326
+ >>> from transformers import AutoTokenizer, FlaxBlenderbotSmallForConditionalGeneration
1327
+
1328
+ >>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained("facebook/blenderbot_small-90M")
1329
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
1330
+
1331
+ >>> text = "My friends are cool but they eat too many carbs."
1332
+ >>> inputs = tokenizer(text, max_length=1024, return_tensors="np")
1333
+ >>> encoder_outputs = model.encode(**inputs)
1334
+
1335
+ >>> decoder_start_token_id = model.config.decoder_start_token_id
1336
+ >>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id
1337
+
1338
+ >>> outputs = model.decode(decoder_input_ids, encoder_outputs)
1339
+ >>> logits = outputs.logits
1340
+ ```"""
1341
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1342
+ output_hidden_states = (
1343
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1344
+ )
1345
+ return_dict = return_dict if return_dict is not None else self.config.return_dict
1346
+
1347
+ encoder_hidden_states = encoder_outputs[0]
1348
+ if encoder_attention_mask is None:
1349
+ batch_size, sequence_length = encoder_hidden_states.shape[:2]
1350
+ encoder_attention_mask = jnp.ones((batch_size, sequence_length))
1351
+
1352
+ batch_size, sequence_length = decoder_input_ids.shape
1353
+ if decoder_attention_mask is None:
1354
+ decoder_attention_mask = jnp.ones((batch_size, sequence_length))
1355
+
1356
+ if decoder_position_ids is None:
1357
+ if past_key_values is not None:
1358
+ raise ValueError("Make sure to provide `decoder_position_ids` when passing `past_key_values`.")
1359
+
1360
+ decoder_position_ids = jnp.broadcast_to(
1361
+ jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)
1362
+ )
1363
+
1364
+ # Handle any PRNG if needed
1365
+ rngs = {}
1366
+ if dropout_rng is not None:
1367
+ rngs["dropout"] = dropout_rng
1368
+
1369
+ inputs = {"params": params or self.params}
1370
+
1371
+ # if past_key_values are passed then cache is already initialized a private flag init_cache has to be
1372
+ # passed down to ensure cache is used. It has to be made sure that cache is marked as mutable so that
1373
+ # it can be changed by FlaxBlenderbotSmallAttention module
1374
+ if past_key_values:
1375
+ inputs["cache"] = past_key_values
1376
+ mutable = ["cache"]
1377
+ else:
1378
+ mutable = False
1379
+
1380
+ def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs):
1381
+ decoder_module = module._get_decoder_module()
1382
+ outputs = decoder_module(
1383
+ decoder_input_ids,
1384
+ decoder_attention_mask,
1385
+ decoder_position_ids,
1386
+ **kwargs,
1387
+ )
1388
+ hidden_states = outputs[0]
1389
+
1390
+ if self.config.tie_word_embeddings:
1391
+ shared_embedding = module.model.variables["params"]["shared"]["embedding"]
1392
+ lm_logits = module.lm_head.apply({"params": {"kernel": shared_embedding.T}}, hidden_states)
1393
+ else:
1394
+ lm_logits = module.lm_head(hidden_states)
1395
+
1396
+ lm_logits += module.final_logits_bias.astype(self.dtype)
1397
+ return lm_logits, outputs
1398
+
1399
+ outputs = self.module.apply(
1400
+ inputs,
1401
+ decoder_input_ids=jnp.array(decoder_input_ids, dtype="i4"),
1402
+ decoder_attention_mask=jnp.array(decoder_attention_mask, dtype="i4"),
1403
+ decoder_position_ids=jnp.array(decoder_position_ids, dtype="i4"),
1404
+ encoder_hidden_states=encoder_hidden_states,
1405
+ encoder_attention_mask=jnp.array(encoder_attention_mask, dtype="i4"),
1406
+ output_attentions=output_attentions,
1407
+ output_hidden_states=output_hidden_states,
1408
+ return_dict=return_dict,
1409
+ deterministic=deterministic,
1410
+ rngs=rngs,
1411
+ mutable=mutable,
1412
+ method=_decoder_forward,
1413
+ )
1414
+
1415
+ if past_key_values is None:
1416
+ lm_logits, decoder_outputs = outputs
1417
+ else:
1418
+ (lm_logits, decoder_outputs), past = outputs
1419
+
1420
+ if return_dict:
1421
+ outputs = FlaxCausalLMOutputWithCrossAttentions(
1422
+ logits=lm_logits,
1423
+ hidden_states=decoder_outputs.hidden_states,
1424
+ attentions=decoder_outputs.attentions,
1425
+ cross_attentions=decoder_outputs.cross_attentions,
1426
+ )
1427
+ else:
1428
+ outputs = (lm_logits,) + decoder_outputs[1:]
1429
+
1430
+ # add updated cache to model output
1431
+ if past_key_values is not None and return_dict:
1432
+ outputs["past_key_values"] = unfreeze(past["cache"])
1433
+ return outputs
1434
+ elif past_key_values is not None and not return_dict:
1435
+ outputs = outputs[:1] + (unfreeze(past["cache"]),) + outputs[1:]
1436
+
1437
+ return outputs
1438
+
1439
+ def prepare_inputs_for_generation(
1440
+ self,
1441
+ decoder_input_ids,
1442
+ max_length,
1443
+ attention_mask: Optional[jax.Array] = None,
1444
+ decoder_attention_mask: Optional[jax.Array] = None,
1445
+ encoder_outputs=None,
1446
+ **kwargs,
1447
+ ):
1448
+ # initializing the cache
1449
+ batch_size, seq_length = decoder_input_ids.shape
1450
+
1451
+ past_key_values = self.init_cache(batch_size, max_length, encoder_outputs)
1452
+ # Note that usually one would have to put 0's in the attention_mask for x > input_ids.shape[-1] and x < cache_length.
1453
+ # But since the decoder uses a causal mask, those positions are masked anyways.
1454
+ # Thus we can create a single static attention_mask here, which is more efficient for compilation
1455
+ extended_attention_mask = jnp.ones((batch_size, max_length), dtype="i4")
1456
+ if decoder_attention_mask is not None:
1457
+ position_ids = decoder_attention_mask.cumsum(axis=-1) - 1
1458
+ extended_attention_mask = lax.dynamic_update_slice(extended_attention_mask, decoder_attention_mask, (0, 0))
1459
+ else:
1460
+ position_ids = jnp.broadcast_to(jnp.arange(seq_length, dtype="i4")[None, :], (batch_size, seq_length))
1461
+
1462
+ return {
1463
+ "past_key_values": past_key_values,
1464
+ "encoder_outputs": encoder_outputs,
1465
+ "encoder_attention_mask": attention_mask,
1466
+ "decoder_attention_mask": extended_attention_mask,
1467
+ "decoder_position_ids": position_ids,
1468
+ }
1469
+
1470
+ def update_inputs_for_generation(self, model_outputs, model_kwargs):
1471
+ model_kwargs["past_key_values"] = model_outputs.past_key_values
1472
+ model_kwargs["decoder_position_ids"] = model_kwargs["decoder_position_ids"][:, -1:] + 1
1473
+ return model_kwargs
1474
+
1475
+
1476
+ FLAX_BLENDERBOT_SMALL_CONDITIONAL_GENERATION_DOCSTRING = """
1477
+ Returns:
1478
+
1479
+ Summarization example:
1480
+
1481
+ ```py
1482
+ >>> from transformers import AutoTokenizer, FlaxBlenderbotSmallForConditionalGeneration
1483
+
1484
+ >>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained("facebook/blenderbot_small-90M")
1485
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
1486
+
1487
+ >>> ARTICLE_TO_SUMMARIZE = "My friends are cool but they eat too many carbs."
1488
+ >>> inputs = tokenizer([ARTICLE_TO_SUMMARIZE], max_length=1024, return_tensors="np")
1489
+
1490
+ >>> # Generate Summary
1491
+ >>> summary_ids = model.generate(inputs["input_ids"]).sequences
1492
+ >>> print(tokenizer.batch_decode(summary_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False))
1493
+ ```
1494
+
1495
+ Mask filling example:
1496
+
1497
+ ```py
1498
+ >>> from transformers import AutoTokenizer, FlaxBlenderbotSmallForConditionalGeneration
1499
+
1500
+ >>> tokenizer = AutoTokenizer.from_pretrained("facebook/blenderbot_small-90M")
1501
+ >>> TXT = "My friends are <mask> but they eat too many carbs."
1502
+
1503
+ >>> model = FlaxBlenderbotSmallForConditionalGeneration.from_pretrained("facebook/blenderbot_small-90M")
1504
+ >>> input_ids = tokenizer([TXT], return_tensors="np")["input_ids"]
1505
+ >>> logits = model(input_ids).logits
1506
+
1507
+ >>> masked_index = (input_ids[0] == tokenizer.mask_token_id).nonzero().item()
1508
+ >>> probs = jax.nn.softmax(logits[0, masked_index], axis=0)
1509
+ >>> values, predictions = jax.lax.top_k(probs)
1510
+
1511
+ >>> tokenizer.decode(predictions).split()
1512
+ ```
1513
+ """
1514
+
1515
+ overwrite_call_docstring(
1516
+ FlaxBlenderbotSmallForConditionalGeneration,
1517
+ BLENDERBOT_SMALL_INPUTS_DOCSTRING + FLAX_BLENDERBOT_SMALL_CONDITIONAL_GENERATION_DOCSTRING,
1518
+ )
1519
+ append_replace_return_docstrings(
1520
+ FlaxBlenderbotSmallForConditionalGeneration, output_type=FlaxSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC
1521
+ )
1522
+
1523
+
1524
+ __all__ = [
1525
+ "FlaxBlenderbotSmallForConditionalGeneration",
1526
+ "FlaxBlenderbotSmallModel",
1527
+ "FlaxBlenderbotSmallPreTrainedModel",
1528
+ ]
lib/python3.12/site-packages/transformers/models/blenderbot_small/modeling_tf_blenderbot_small.py ADDED
@@ -0,0 +1,1528 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Facebook, Inc 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
+ """TF 2.0 BlenderbotSmall model."""
16
+
17
+ from __future__ import annotations
18
+
19
+ import random
20
+ from typing import List, Optional, Tuple, Union
21
+
22
+ import numpy as np
23
+ import tensorflow as tf
24
+
25
+ from ...activations_tf import get_tf_activation
26
+ from ...modeling_tf_outputs import (
27
+ TFBaseModelOutput,
28
+ TFBaseModelOutputWithPastAndCrossAttentions,
29
+ TFSeq2SeqLMOutput,
30
+ TFSeq2SeqModelOutput,
31
+ )
32
+
33
+ # Public API
34
+ from ...modeling_tf_utils import (
35
+ TFCausalLanguageModelingLoss,
36
+ TFPreTrainedModel,
37
+ keras,
38
+ keras_serializable,
39
+ unpack_inputs,
40
+ )
41
+ from ...tf_utils import check_embeddings_within_bounds, shape_list, stable_softmax
42
+ from ...utils import (
43
+ add_code_sample_docstrings,
44
+ add_end_docstrings,
45
+ add_start_docstrings,
46
+ add_start_docstrings_to_model_forward,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from .configuration_blenderbot_small import BlenderbotSmallConfig
51
+
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+ _CHECKPOINT_FOR_DOC = "facebook/blenderbot_small-90M"
56
+ _CONFIG_FOR_DOC = "BlenderbotSmallConfig"
57
+
58
+
59
+ LARGE_NEGATIVE = -1e8
60
+
61
+
62
+ # Copied from transformers.models.bart.modeling_tf_bart.shift_tokens_right
63
+ def shift_tokens_right(input_ids: tf.Tensor, pad_token_id: int, decoder_start_token_id: int):
64
+ pad_token_id = tf.cast(pad_token_id, input_ids.dtype)
65
+ decoder_start_token_id = tf.cast(decoder_start_token_id, input_ids.dtype)
66
+ start_tokens = tf.fill(
67
+ (shape_list(input_ids)[0], 1), tf.convert_to_tensor(decoder_start_token_id, input_ids.dtype)
68
+ )
69
+ shifted_input_ids = tf.concat([start_tokens, input_ids[:, :-1]], -1)
70
+ # replace possible -100 values in labels by `pad_token_id`
71
+ shifted_input_ids = tf.where(
72
+ shifted_input_ids == -100,
73
+ tf.fill(shape_list(shifted_input_ids), tf.convert_to_tensor(pad_token_id, input_ids.dtype)),
74
+ shifted_input_ids,
75
+ )
76
+
77
+ # "Verify that `labels` has only positive values and -100"
78
+ assert_gte0 = tf.debugging.assert_greater_equal(shifted_input_ids, tf.constant(0, dtype=input_ids.dtype))
79
+
80
+ # Make sure the assertion op is called by wrapping the result in an identity no-op
81
+ with tf.control_dependencies([assert_gte0]):
82
+ shifted_input_ids = tf.identity(shifted_input_ids)
83
+
84
+ return shifted_input_ids
85
+
86
+
87
+ # Copied from transformers.models.bart.modeling_tf_bart._make_causal_mask
88
+ def _make_causal_mask(input_ids_shape: tf.TensorShape, past_key_values_length: int = 0):
89
+ """
90
+ Make causal mask used for bi-directional self-attention.
91
+ """
92
+ bsz = input_ids_shape[0]
93
+ tgt_len = input_ids_shape[1]
94
+ mask = tf.ones((tgt_len, tgt_len)) * LARGE_NEGATIVE
95
+ mask_cond = tf.range(shape_list(mask)[-1])
96
+
97
+ mask = tf.where(mask_cond < tf.reshape(mask_cond + 1, (shape_list(mask)[-1], 1)), 0.0, mask)
98
+
99
+ if past_key_values_length > 0:
100
+ mask = tf.concat([tf.zeros((tgt_len, past_key_values_length)), mask], axis=-1)
101
+
102
+ return tf.tile(mask[None, None, :, :], (bsz, 1, 1, 1))
103
+
104
+
105
+ # Copied from transformers.models.bart.modeling_tf_bart._expand_mask
106
+ def _expand_mask(mask: tf.Tensor, tgt_len: Optional[int] = None):
107
+ """
108
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
109
+ """
110
+ src_len = shape_list(mask)[1]
111
+ tgt_len = tgt_len if tgt_len is not None else src_len
112
+ one_cst = tf.constant(1.0)
113
+ mask = tf.cast(mask, dtype=one_cst.dtype)
114
+ expanded_mask = tf.tile(mask[:, None, None, :], (1, 1, tgt_len, 1))
115
+
116
+ return (one_cst - expanded_mask) * LARGE_NEGATIVE
117
+
118
+
119
+ # Copied from transformers.models.blenderbot.modeling_tf_blenderbot.TFBlenderbotLearnedPositionalEmbedding with Blenderbot->BlenderbotSmall
120
+ class TFBlenderbotSmallLearnedPositionalEmbedding(keras.layers.Embedding):
121
+ """
122
+ This module learns positional embeddings up to a fixed maximum size.
123
+ """
124
+
125
+ def __init__(self, num_embeddings: int, embedding_dim: int, **kwargs):
126
+ super().__init__(num_embeddings, embedding_dim, **kwargs)
127
+
128
+ def call(
129
+ self, input_shape: tf.TensorShape, past_key_values_length: int = 0, position_ids: tf.Tensor | None = None
130
+ ):
131
+ """Input is expected to be of size [bsz x seqlen]."""
132
+ if position_ids is None:
133
+ seq_len = input_shape[1]
134
+ position_ids = tf.range(seq_len, delta=1, name="range")
135
+ position_ids += past_key_values_length
136
+
137
+ return super().call(tf.cast(position_ids, dtype=tf.int32))
138
+
139
+
140
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartAttention with Bart->BlenderbotSmall
141
+ class TFBlenderbotSmallAttention(keras.layers.Layer):
142
+ """Multi-headed attention from "Attention Is All You Need"""
143
+
144
+ def __init__(
145
+ self,
146
+ embed_dim: int,
147
+ num_heads: int,
148
+ dropout: float = 0.0,
149
+ is_decoder: bool = False,
150
+ bias: bool = True,
151
+ **kwargs,
152
+ ):
153
+ super().__init__(**kwargs)
154
+ self.embed_dim = embed_dim
155
+
156
+ self.num_heads = num_heads
157
+ self.dropout = keras.layers.Dropout(dropout)
158
+ self.head_dim = embed_dim // num_heads
159
+ if (self.head_dim * num_heads) != self.embed_dim:
160
+ raise ValueError(
161
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
162
+ f" and `num_heads`: {num_heads})."
163
+ )
164
+ self.scaling = self.head_dim**-0.5
165
+ self.is_decoder = is_decoder
166
+
167
+ self.k_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="k_proj")
168
+ self.q_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="q_proj")
169
+ self.v_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="v_proj")
170
+ self.out_proj = keras.layers.Dense(embed_dim, use_bias=bias, name="out_proj")
171
+
172
+ def _shape(self, tensor: tf.Tensor, seq_len: int, bsz: int):
173
+ return tf.transpose(tf.reshape(tensor, (bsz, seq_len, self.num_heads, self.head_dim)), (0, 2, 1, 3))
174
+
175
+ def call(
176
+ self,
177
+ hidden_states: tf.Tensor,
178
+ key_value_states: tf.Tensor | None = None,
179
+ past_key_value: Tuple[Tuple[tf.Tensor]] | None = None,
180
+ attention_mask: tf.Tensor | None = None,
181
+ layer_head_mask: tf.Tensor | None = None,
182
+ training: Optional[bool] = False,
183
+ ) -> Tuple[tf.Tensor, tf.Tensor | None]:
184
+ """Input shape: Batch x Time x Channel"""
185
+
186
+ # if key_value_states are provided this layer is used as a cross-attention layer
187
+ # for the decoder
188
+ is_cross_attention = key_value_states is not None
189
+ bsz, tgt_len, embed_dim = shape_list(hidden_states)
190
+
191
+ # get query proj
192
+ query_states = self.q_proj(hidden_states) * self.scaling
193
+ # get key, value proj
194
+ if is_cross_attention and past_key_value is not None:
195
+ # reuse k,v, cross_attentions
196
+ key_states = past_key_value[0]
197
+ value_states = past_key_value[1]
198
+ elif is_cross_attention:
199
+ # cross_attentions
200
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
201
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
202
+ elif past_key_value is not None:
203
+ # reuse k, v, self_attention
204
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
205
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
206
+ key_states = tf.concat([past_key_value[0], key_states], axis=2)
207
+ value_states = tf.concat([past_key_value[1], value_states], axis=2)
208
+ else:
209
+ # self_attention
210
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
211
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
212
+
213
+ if self.is_decoder:
214
+ # if cross_attention save Tuple(tf.Tensor, tf.Tensor) of all cross attention key/value_states.
215
+ # Further calls to cross_attention layer can then reuse all cross-attention
216
+ # key/value_states (first "if" case)
217
+ # if uni-directional self-attention (decoder) save Tuple(tf.Tensor, tf.Tensor) of
218
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
219
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
220
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
221
+ past_key_value = (key_states, value_states)
222
+
223
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
224
+ query_states = tf.reshape(self._shape(query_states, tgt_len, bsz), proj_shape)
225
+ key_states = tf.reshape(key_states, proj_shape)
226
+ value_states = tf.reshape(value_states, proj_shape)
227
+
228
+ src_len = shape_list(key_states)[1]
229
+ attn_weights = tf.matmul(query_states, key_states, transpose_b=True)
230
+
231
+ tf.debugging.assert_equal(
232
+ shape_list(attn_weights),
233
+ [bsz * self.num_heads, tgt_len, src_len],
234
+ message=(
235
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
236
+ f" {shape_list(attn_weights)}"
237
+ ),
238
+ )
239
+
240
+ if attention_mask is not None:
241
+ tf.debugging.assert_equal(
242
+ shape_list(attention_mask),
243
+ [bsz, 1, tgt_len, src_len],
244
+ message=(
245
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
246
+ f" {shape_list(attention_mask)}"
247
+ ),
248
+ )
249
+
250
+ attention_mask = tf.cast(attention_mask, dtype=attn_weights.dtype)
251
+ attn_weights = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len)) + attention_mask
252
+ attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))
253
+
254
+ attn_weights = stable_softmax(attn_weights, axis=-1)
255
+
256
+ if layer_head_mask is not None:
257
+ tf.debugging.assert_equal(
258
+ shape_list(layer_head_mask),
259
+ [self.num_heads],
260
+ message=(
261
+ f"Head mask for a single layer should be of size {(self.num_heads)}, but is"
262
+ f" {shape_list(layer_head_mask)}"
263
+ ),
264
+ )
265
+
266
+ attn_weights = tf.reshape(layer_head_mask, (1, -1, 1, 1)) * tf.reshape(
267
+ attn_weights, (bsz, self.num_heads, tgt_len, src_len)
268
+ )
269
+ attn_weights = tf.reshape(attn_weights, (bsz * self.num_heads, tgt_len, src_len))
270
+
271
+ attn_probs = self.dropout(attn_weights, training=training)
272
+ attn_output = tf.matmul(attn_probs, value_states)
273
+
274
+ tf.debugging.assert_equal(
275
+ shape_list(attn_output),
276
+ [bsz * self.num_heads, tgt_len, self.head_dim],
277
+ message=(
278
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
279
+ f" {shape_list(attn_output)}"
280
+ ),
281
+ )
282
+
283
+ attn_output = tf.transpose(
284
+ tf.reshape(attn_output, (bsz, self.num_heads, tgt_len, self.head_dim)), (0, 2, 1, 3)
285
+ )
286
+ attn_output = tf.reshape(attn_output, (bsz, tgt_len, embed_dim))
287
+
288
+ attn_output = self.out_proj(attn_output)
289
+ attn_weights: tf.Tensor = tf.reshape(attn_weights, (bsz, self.num_heads, tgt_len, src_len))
290
+
291
+ return attn_output, attn_weights, past_key_value
292
+
293
+ def build(self, input_shape=None):
294
+ if self.built:
295
+ return
296
+ self.built = True
297
+ if getattr(self, "k_proj", None) is not None:
298
+ with tf.name_scope(self.k_proj.name):
299
+ self.k_proj.build([None, None, self.embed_dim])
300
+ if getattr(self, "q_proj", None) is not None:
301
+ with tf.name_scope(self.q_proj.name):
302
+ self.q_proj.build([None, None, self.embed_dim])
303
+ if getattr(self, "v_proj", None) is not None:
304
+ with tf.name_scope(self.v_proj.name):
305
+ self.v_proj.build([None, None, self.embed_dim])
306
+ if getattr(self, "out_proj", None) is not None:
307
+ with tf.name_scope(self.out_proj.name):
308
+ self.out_proj.build([None, None, self.embed_dim])
309
+
310
+
311
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartEncoderLayer with Bart->BlenderbotSmall
312
+ class TFBlenderbotSmallEncoderLayer(keras.layers.Layer):
313
+ def __init__(self, config: BlenderbotSmallConfig, **kwargs):
314
+ super().__init__(**kwargs)
315
+ self.embed_dim = config.d_model
316
+ self.self_attn = TFBlenderbotSmallAttention(
317
+ self.embed_dim, config.encoder_attention_heads, dropout=config.attention_dropout, name="self_attn"
318
+ )
319
+ self.self_attn_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="self_attn_layer_norm")
320
+ self.dropout = keras.layers.Dropout(config.dropout)
321
+ self.activation_fn = get_tf_activation(config.activation_function)
322
+ self.activation_dropout = keras.layers.Dropout(config.activation_dropout)
323
+ self.fc1 = keras.layers.Dense(config.encoder_ffn_dim, name="fc1")
324
+ self.fc2 = keras.layers.Dense(self.embed_dim, name="fc2")
325
+ self.final_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm")
326
+ self.config = config
327
+
328
+ def call(
329
+ self,
330
+ hidden_states: tf.Tensor,
331
+ attention_mask: np.ndarray | tf.Tensor | None,
332
+ layer_head_mask: tf.Tensor | None,
333
+ training: Optional[bool] = False,
334
+ ) -> tf.Tensor:
335
+ """
336
+ Args:
337
+ hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
338
+ attention_mask (`tf.Tensor`): attention mask of size
339
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
340
+ layer_head_mask (`tf.Tensor`): mask for attention heads in a given layer of size
341
+ `(encoder_attention_heads,)`
342
+ """
343
+ residual = hidden_states
344
+ hidden_states, self_attn_weights, _ = self.self_attn(
345
+ hidden_states=hidden_states, attention_mask=attention_mask, layer_head_mask=layer_head_mask
346
+ )
347
+
348
+ tf.debugging.assert_equal(
349
+ shape_list(hidden_states),
350
+ shape_list(residual),
351
+ message=f"Self attn modified the shape of query {shape_list(residual)} to {shape_list(hidden_states)}",
352
+ )
353
+
354
+ hidden_states = self.dropout(hidden_states, training=training)
355
+ hidden_states = residual + hidden_states
356
+ hidden_states = self.self_attn_layer_norm(hidden_states)
357
+
358
+ residual = hidden_states
359
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
360
+ hidden_states = self.activation_dropout(hidden_states, training=training)
361
+ hidden_states = self.fc2(hidden_states)
362
+ hidden_states = self.dropout(hidden_states, training=training)
363
+ hidden_states = residual + hidden_states
364
+ hidden_states = self.final_layer_norm(hidden_states)
365
+
366
+ return hidden_states, self_attn_weights
367
+
368
+ def build(self, input_shape=None):
369
+ if self.built:
370
+ return
371
+ self.built = True
372
+ if getattr(self, "self_attn", None) is not None:
373
+ with tf.name_scope(self.self_attn.name):
374
+ self.self_attn.build(None)
375
+ if getattr(self, "self_attn_layer_norm", None) is not None:
376
+ with tf.name_scope(self.self_attn_layer_norm.name):
377
+ self.self_attn_layer_norm.build([None, None, self.embed_dim])
378
+ if getattr(self, "fc1", None) is not None:
379
+ with tf.name_scope(self.fc1.name):
380
+ self.fc1.build([None, None, self.embed_dim])
381
+ if getattr(self, "fc2", None) is not None:
382
+ with tf.name_scope(self.fc2.name):
383
+ self.fc2.build([None, None, self.config.encoder_ffn_dim])
384
+ if getattr(self, "final_layer_norm", None) is not None:
385
+ with tf.name_scope(self.final_layer_norm.name):
386
+ self.final_layer_norm.build([None, None, self.embed_dim])
387
+
388
+
389
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartDecoderLayer with Bart->BlenderbotSmall
390
+ class TFBlenderbotSmallDecoderLayer(keras.layers.Layer):
391
+ def __init__(self, config: BlenderbotSmallConfig, **kwargs):
392
+ super().__init__(**kwargs)
393
+ self.embed_dim = config.d_model
394
+ self.self_attn = TFBlenderbotSmallAttention(
395
+ embed_dim=self.embed_dim,
396
+ num_heads=config.decoder_attention_heads,
397
+ dropout=config.attention_dropout,
398
+ name="self_attn",
399
+ is_decoder=True,
400
+ )
401
+ self.dropout = keras.layers.Dropout(config.dropout)
402
+ self.activation_fn = get_tf_activation(config.activation_function)
403
+ self.activation_dropout = keras.layers.Dropout(config.activation_dropout)
404
+
405
+ self.self_attn_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="self_attn_layer_norm")
406
+ self.encoder_attn = TFBlenderbotSmallAttention(
407
+ self.embed_dim,
408
+ config.decoder_attention_heads,
409
+ dropout=config.attention_dropout,
410
+ name="encoder_attn",
411
+ is_decoder=True,
412
+ )
413
+ self.encoder_attn_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="encoder_attn_layer_norm")
414
+ self.fc1 = keras.layers.Dense(config.decoder_ffn_dim, name="fc1")
415
+ self.fc2 = keras.layers.Dense(self.embed_dim, name="fc2")
416
+ self.final_layer_norm = keras.layers.LayerNormalization(epsilon=1e-5, name="final_layer_norm")
417
+ self.config = config
418
+
419
+ def call(
420
+ self,
421
+ hidden_states: tf.Tensor,
422
+ attention_mask: np.ndarray | tf.Tensor | None = None,
423
+ encoder_hidden_states: np.ndarray | tf.Tensor | None = None,
424
+ encoder_attention_mask: np.ndarray | tf.Tensor | None = None,
425
+ layer_head_mask: tf.Tensor | None = None,
426
+ cross_attn_layer_head_mask: tf.Tensor | None = None,
427
+ past_key_value: Optional[Tuple[Tuple[Union[np.ndarray, tf.Tensor]]]] = None,
428
+ training: Optional[bool] = False,
429
+ ) -> Tuple[tf.Tensor, tf.Tensor, Tuple[Tuple[tf.Tensor]]]:
430
+ """
431
+ Args:
432
+ hidden_states (`tf.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
433
+ attention_mask (`tf.Tensor`): attention mask of size
434
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
435
+ encoder_hidden_states (`tf.Tensor`):
436
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
437
+ encoder_attention_mask (`tf.Tensor`): encoder attention mask of size
438
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
439
+ layer_head_mask (`tf.Tensor`): mask for attention heads in a given layer of size
440
+ `(decoder_attention_heads,)`
441
+ cross_attn_layer_head_mask (`tf.Tensor`): mask for heads of the cross-attention module.
442
+ `(decoder_attention_heads,)`
443
+ past_key_value (`Tuple(tf.Tensor)`): cached past key and value projection states
444
+ """
445
+ residual = hidden_states
446
+
447
+ # Self Attention
448
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
449
+ self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None
450
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
451
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
452
+ hidden_states=hidden_states,
453
+ past_key_value=self_attn_past_key_value,
454
+ attention_mask=attention_mask,
455
+ layer_head_mask=layer_head_mask,
456
+ )
457
+ hidden_states = self.dropout(hidden_states, training=training)
458
+ hidden_states = residual + hidden_states
459
+ hidden_states = self.self_attn_layer_norm(hidden_states)
460
+
461
+ # Cross-Attention Block
462
+ cross_attn_present_key_value = None
463
+ cross_attn_weights = None
464
+ if encoder_hidden_states is not None:
465
+ residual = hidden_states
466
+
467
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
468
+ cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None
469
+ hidden_states, cross_attn_weights, cross_attn_present_key_value = self.encoder_attn(
470
+ hidden_states=hidden_states,
471
+ key_value_states=encoder_hidden_states,
472
+ attention_mask=encoder_attention_mask,
473
+ layer_head_mask=cross_attn_layer_head_mask,
474
+ past_key_value=cross_attn_past_key_value,
475
+ )
476
+ hidden_states = self.dropout(hidden_states, training=training)
477
+ hidden_states = residual + hidden_states
478
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
479
+
480
+ # add cross-attn to positions 3,4 of present_key_value tuple
481
+ present_key_value = present_key_value + cross_attn_present_key_value
482
+
483
+ # Fully Connected
484
+ residual = hidden_states
485
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
486
+ hidden_states = self.activation_dropout(hidden_states, training=training)
487
+ hidden_states = self.fc2(hidden_states)
488
+ hidden_states = self.dropout(hidden_states, training=training)
489
+ hidden_states = residual + hidden_states
490
+ hidden_states = self.final_layer_norm(hidden_states)
491
+
492
+ return (
493
+ hidden_states,
494
+ self_attn_weights,
495
+ cross_attn_weights,
496
+ present_key_value,
497
+ )
498
+
499
+ def build(self, input_shape=None):
500
+ if self.built:
501
+ return
502
+ self.built = True
503
+ if getattr(self, "self_attn", None) is not None:
504
+ with tf.name_scope(self.self_attn.name):
505
+ self.self_attn.build(None)
506
+ if getattr(self, "self_attn_layer_norm", None) is not None:
507
+ with tf.name_scope(self.self_attn_layer_norm.name):
508
+ self.self_attn_layer_norm.build([None, None, self.embed_dim])
509
+ if getattr(self, "encoder_attn", None) is not None:
510
+ with tf.name_scope(self.encoder_attn.name):
511
+ self.encoder_attn.build(None)
512
+ if getattr(self, "encoder_attn_layer_norm", None) is not None:
513
+ with tf.name_scope(self.encoder_attn_layer_norm.name):
514
+ self.encoder_attn_layer_norm.build([None, None, self.embed_dim])
515
+ if getattr(self, "fc1", None) is not None:
516
+ with tf.name_scope(self.fc1.name):
517
+ self.fc1.build([None, None, self.embed_dim])
518
+ if getattr(self, "fc2", None) is not None:
519
+ with tf.name_scope(self.fc2.name):
520
+ self.fc2.build([None, None, self.config.decoder_ffn_dim])
521
+ if getattr(self, "final_layer_norm", None) is not None:
522
+ with tf.name_scope(self.final_layer_norm.name):
523
+ self.final_layer_norm.build([None, None, self.embed_dim])
524
+
525
+
526
+ class TFBlenderbotSmallPreTrainedModel(TFPreTrainedModel):
527
+ config_class = BlenderbotSmallConfig
528
+ base_model_prefix = "model"
529
+
530
+
531
+ BLENDERBOT_SMALL_START_DOCSTRING = r"""
532
+ This model inherits from [`TFPreTrainedModel`]. Check the superclass documentation for the generic methods the
533
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
534
+ etc.)
535
+
536
+ This model is also a [keras.Model](https://www.tensorflow.org/api_docs/python/tf/keras/Model) subclass. Use it
537
+ as a regular TF 2.0 Keras Model and refer to the TF 2.0 documentation for all matter related to general usage and
538
+ behavior.
539
+
540
+ <Tip>
541
+
542
+ TensorFlow models and layers in `transformers` accept two formats as input:
543
+
544
+ - having all inputs as keyword arguments (like PyTorch models), or
545
+ - having all inputs as a list, tuple or dict in the first positional argument.
546
+
547
+ The reason the second format is supported is that Keras methods prefer this format when passing inputs to models
548
+ and layers. Because of this support, when using methods like `model.fit()` things should "just work" for you - just
549
+ pass your inputs and labels in any format that `model.fit()` supports! If, however, you want to use the second
550
+ format outside of Keras methods like `fit()` and `predict()`, such as when creating your own layers or models with
551
+ the Keras `Functional` API, there are three possibilities you can use to gather all the input Tensors in the first
552
+ positional argument:
553
+
554
+ - a single Tensor with `input_ids` only and nothing else: `model(input_ids)`
555
+ - a list of varying length with one or several input Tensors IN THE ORDER given in the docstring:
556
+ `model([input_ids, attention_mask])` or `model([input_ids, attention_mask, token_type_ids])`
557
+ - a dictionary with one or several input Tensors associated to the input names given in the docstring:
558
+ `model({"input_ids": input_ids, "token_type_ids": token_type_ids})`
559
+
560
+ Note that when creating models and layers with
561
+ [subclassing](https://keras.io/guides/making_new_layers_and_models_via_subclassing/) then you don't need to worry
562
+ about any of this, as you can just pass inputs like you would to any other Python function!
563
+
564
+ </Tip>
565
+
566
+ Args:
567
+ config ([`BlenderbotSmallConfig`]): Model configuration class with all the parameters of the model.
568
+ Initializing with a config file does not load the weights associated with the model, only the
569
+ configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
570
+ """
571
+
572
+ BLENDERBOT_SMALL_GENERATION_EXAMPLE = r"""
573
+ Conversation example::
574
+
575
+ ```py
576
+ >>> from transformers import AutoTokenizer, TFBlenderbotSmallForConditionalGeneration
577
+
578
+ >>> mname = "facebook/blenderbot_small-90M"
579
+ >>> model = BlenderbotSmallForConditionalGeneration.from_pretrained(mname)
580
+ >>> tokenizer = AutoTokenizer.from_pretrained(mname)
581
+
582
+ >>> UTTERANCE = "My friends are cool but they eat too many carbs."
583
+ >>> print("Human: ", UTTERANCE)
584
+ >>> inputs = tokenizer([UTTERANCE], return_tensors="tf")
585
+
586
+ >>> reply_ids = model.generate(**inputs)
587
+ >>> print("Bot: ", tokenizer.batch_decode(reply_ids, skip_special_tokens=True)[0])
588
+ what kind of carbs do they eat? i don't know much about carbs.
589
+
590
+ >>> REPLY = "I'm not sure"
591
+ >>> print("Human: ", REPLY)
592
+ >>> NEXT_UTTERANCE = (
593
+ ... "My friends are cool but they eat too many carbs.</s> "
594
+ ... "<s>what kind of carbs do they eat? i don't know much about carbs.</s> "
595
+ ... "<s>I'm not sure."
596
+ ... )
597
+
598
+ >>> inputs = tokenizer([NEXT_UTTERANCE], return_tensors="tf")
599
+ >>> inputs.pop("token_type_ids")
600
+ >>> next_reply_ids = model.generate(**inputs)
601
+ >>> print("Bot: ", tokenizer.batch_decode(next_reply_ids, skip_special_tokens=True)[0])
602
+ ```
603
+ """
604
+
605
+ BLENDERBOT_SMALL_INPUTS_DOCSTRING = r"""
606
+ Args:
607
+ input_ids (`tf.Tensor` of shape `({0})`):
608
+ Indices of input sequence tokens in the vocabulary.
609
+
610
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
611
+ [`PreTrainedTokenizer.__call__`] for details.
612
+
613
+ [What are input IDs?](../glossary#input-ids)
614
+ attention_mask (`tf.Tensor` of shape `({0})`, *optional*):
615
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
616
+
617
+ - 1 for tokens that are **not masked**,
618
+ - 0 for tokens that are **masked**.
619
+
620
+ [What are attention masks?](../glossary#attention-mask)
621
+ decoder_input_ids (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*):
622
+ Indices of decoder input sequence tokens in the vocabulary.
623
+
624
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
625
+ [`PreTrainedTokenizer.__call__`] for details.
626
+
627
+ [What are decoder input IDs?](../glossary#decoder-input-ids)
628
+
629
+ BlenderbotSmall uses the `bos_token_id` as the starting token for `decoder_input_ids` generation. If
630
+ `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
631
+ `past_key_values`).
632
+ decoder_attention_mask (`tf.Tensor` of shape `(batch_size, target_sequence_length)`, *optional*):
633
+ will be made by default and ignore pad tokens. It is not recommended to set this for most use cases.
634
+ decoder_position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
635
+ Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
636
+ range `[0, config.max_position_embeddings - 1]`.
637
+ head_mask (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
638
+ Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`:
639
+
640
+ - 1 indicates the head is **not masked**,
641
+ - 0 indicates the head is **masked**.
642
+
643
+ decoder_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
644
+ Mask to nullify selected heads of the attention modules in the decoder. Mask values selected in `[0, 1]`:
645
+
646
+ - 1 indicates the head is **not masked**,
647
+ - 0 indicates the head is **masked**.
648
+
649
+ cross_attn_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
650
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
651
+
652
+ - 1 indicates the head is **not masked**,
653
+ - 0 indicates the head is **masked**.
654
+
655
+ encoder_outputs (`tf.FloatTensor`, *optional*):
656
+ hidden states at the output of the last layer of the encoder. Used in the cross-attention of the decoder.
657
+ of shape `(batch_size, sequence_length, hidden_size)` is a sequence of
658
+ past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers`)
659
+ contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
660
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
661
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
662
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
663
+ use_cache (`bool`, *optional*, defaults to `True`):
664
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
665
+ `past_key_values`). Set to `False` during training, `True` during generation
666
+ output_attentions (`bool`, *optional*):
667
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
668
+ tensors for more detail. This argument can be used only in eager mode, in graph mode the value in the
669
+ config will be used instead.
670
+ output_hidden_states (`bool`, *optional*):
671
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
672
+ more detail. This argument can be used only in eager mode, in graph mode the value in the config will be
673
+ used instead.
674
+ return_dict (`bool`, *optional*):
675
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used in
676
+ eager mode, in graph mode the value will always be set to True.
677
+ training (`bool`, *optional*, defaults to `False`):
678
+ Whether or not to use the model in training mode (some modules like dropout modules have different
679
+ behaviors between training and evaluation).
680
+ """
681
+
682
+
683
+ @keras_serializable
684
+ class TFBlenderbotSmallEncoder(keras.layers.Layer):
685
+ config_class = BlenderbotSmallConfig
686
+ """
687
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
688
+ [`TFBlenderbotSmallEncoderLayer`].
689
+
690
+ Args:
691
+ config: BlenderbotSmallConfig
692
+ """
693
+
694
+ def __init__(self, config: BlenderbotSmallConfig, embed_tokens: Optional[keras.layers.Embedding] = None, **kwargs):
695
+ super().__init__(**kwargs)
696
+ self.config = config
697
+ self.dropout = keras.layers.Dropout(config.dropout)
698
+ self.layerdrop = config.encoder_layerdrop
699
+ self.padding_idx = config.pad_token_id
700
+ self.max_source_positions = config.max_position_embeddings
701
+ self.embed_scale = tf.math.sqrt(float(config.d_model)) if config.scale_embedding else 1.0
702
+
703
+ self.embed_tokens = embed_tokens
704
+ self.embed_positions = TFBlenderbotSmallLearnedPositionalEmbedding(
705
+ config.max_position_embeddings,
706
+ config.d_model,
707
+ name="embed_positions",
708
+ )
709
+ self.layers = [TFBlenderbotSmallEncoderLayer(config, name=f"layers.{i}") for i in range(config.encoder_layers)]
710
+ self.layernorm_embedding = keras.layers.LayerNormalization(epsilon=1e-5, name="layernorm_embedding")
711
+ self.embed_dim = config.d_model
712
+
713
+ def get_embed_tokens(self):
714
+ return self.embed_tokens
715
+
716
+ def set_embed_tokens(self, embed_tokens):
717
+ self.embed_tokens = embed_tokens
718
+
719
+ @unpack_inputs
720
+ def call(
721
+ self,
722
+ input_ids=None,
723
+ inputs_embeds=None,
724
+ attention_mask=None,
725
+ head_mask=None,
726
+ output_attentions=None,
727
+ output_hidden_states=None,
728
+ return_dict=None,
729
+ training=False,
730
+ ):
731
+ """
732
+ Args:
733
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
734
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
735
+ provide it.
736
+
737
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
738
+ [`PreTrainedTokenizer.__call__`] for details.
739
+
740
+ [What are input IDs?](../glossary#input-ids)
741
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
742
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
743
+
744
+ - 1 for tokens that are **not masked**,
745
+ - 0 for tokens that are **masked**.
746
+
747
+ [What are attention masks?](../glossary#attention-mask)
748
+ head_mask (`tf.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, `optional):
749
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
750
+
751
+ - 1 indicates the head is **not masked**,
752
+ - 0 indicates the head is **masked**.
753
+
754
+ inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
755
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
756
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
757
+ than the model's internal embedding lookup matrix.
758
+ output_attentions (`bool`, *optional*):
759
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
760
+ returned tensors for more detail. This argument can be used only in eager mode, in graph mode the value
761
+ in the config will be used instead.
762
+ output_hidden_states (`bool`, *optional*):
763
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
764
+ for more detail. This argument can be used only in eager mode, in graph mode the value in the config
765
+ will be used instead.
766
+ return_dict (`bool`, *optional*):
767
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used
768
+ in eager mode, in graph mode the value will always be set to True.
769
+ training (`bool`, *optional*, defaults to `False`):
770
+ Whether or not to use the model in training mode (some modules like dropout modules have different
771
+ behaviors between training and evaluation).
772
+ """
773
+ if input_ids is not None and inputs_embeds is not None:
774
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
775
+ elif input_ids is not None:
776
+ input_shape = shape_list(input_ids)
777
+ elif inputs_embeds is not None:
778
+ input_shape = shape_list(inputs_embeds)[:-1]
779
+ else:
780
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
781
+
782
+ if inputs_embeds is None:
783
+ check_embeddings_within_bounds(input_ids, self.embed_tokens.input_dim)
784
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
785
+
786
+ embed_pos = self.embed_positions(input_shape)
787
+ hidden_states = inputs_embeds + embed_pos
788
+ hidden_states = self.layernorm_embedding(hidden_states)
789
+ hidden_states = self.dropout(hidden_states, training=training)
790
+
791
+ # check attention mask and invert
792
+ if attention_mask is not None:
793
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
794
+ attention_mask = _expand_mask(attention_mask)
795
+ else:
796
+ attention_mask = None
797
+
798
+ encoder_states = () if output_hidden_states else None
799
+ all_attentions = () if output_attentions else None
800
+
801
+ # check if head_mask has a correct number of layers specified if desired
802
+ if head_mask is not None:
803
+ tf.debugging.assert_equal(
804
+ shape_list(head_mask)[0],
805
+ len(self.layers),
806
+ message=(
807
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
808
+ f" {shape_list(head_mask)[0]}."
809
+ ),
810
+ )
811
+
812
+ # encoder layers
813
+ for idx, encoder_layer in enumerate(self.layers):
814
+ if output_hidden_states:
815
+ encoder_states = encoder_states + (hidden_states,)
816
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
817
+ dropout_probability = random.uniform(0, 1)
818
+ if training and (dropout_probability < self.layerdrop): # skip the layer
819
+ continue
820
+
821
+ hidden_states, attn = encoder_layer(
822
+ hidden_states,
823
+ attention_mask,
824
+ head_mask[idx] if head_mask is not None else None,
825
+ )
826
+
827
+ if output_attentions:
828
+ all_attentions += (attn,)
829
+
830
+ if output_hidden_states:
831
+ encoder_states = encoder_states + (hidden_states,)
832
+
833
+ if not return_dict:
834
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
835
+ return TFBaseModelOutput(
836
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
837
+ )
838
+
839
+ def build(self, input_shape=None):
840
+ if self.built:
841
+ return
842
+ self.built = True
843
+ if getattr(self, "embed_positions", None) is not None:
844
+ with tf.name_scope(self.embed_positions.name):
845
+ self.embed_positions.build(None)
846
+ if getattr(self, "layernorm_embedding", None) is not None:
847
+ with tf.name_scope(self.layernorm_embedding.name):
848
+ self.layernorm_embedding.build([None, None, self.embed_dim])
849
+ if getattr(self, "layers", None) is not None:
850
+ for layer in self.layers:
851
+ with tf.name_scope(layer.name):
852
+ layer.build(None)
853
+
854
+
855
+ @keras_serializable
856
+ class TFBlenderbotSmallDecoder(keras.layers.Layer):
857
+ config_class = BlenderbotSmallConfig
858
+ """
859
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`TFBlenderbotSmallDecoderLayer`]
860
+
861
+ Args:
862
+ config: BlenderbotSmallConfig
863
+ embed_tokens: output embedding
864
+ """
865
+
866
+ def __init__(self, config: BlenderbotSmallConfig, embed_tokens: Optional[keras.layers.Embedding] = None, **kwargs):
867
+ super().__init__(**kwargs)
868
+ self.config = config
869
+ self.padding_idx = config.pad_token_id
870
+ self.embed_tokens = embed_tokens
871
+ self.layerdrop = config.decoder_layerdrop
872
+ self.embed_positions = TFBlenderbotSmallLearnedPositionalEmbedding(
873
+ config.max_position_embeddings,
874
+ config.d_model,
875
+ name="embed_positions",
876
+ )
877
+ self.embed_scale = tf.math.sqrt(float(config.d_model)) if config.scale_embedding else 1.0
878
+ self.layers = [TFBlenderbotSmallDecoderLayer(config, name=f"layers.{i}") for i in range(config.decoder_layers)]
879
+ self.layernorm_embedding = keras.layers.LayerNormalization(epsilon=1e-5, name="layernorm_embedding")
880
+
881
+ self.dropout = keras.layers.Dropout(config.dropout)
882
+
883
+ def get_embed_tokens(self):
884
+ return self.embed_tokens
885
+
886
+ def set_embed_tokens(self, embed_tokens):
887
+ self.embed_tokens = embed_tokens
888
+
889
+ @unpack_inputs
890
+ def call(
891
+ self,
892
+ input_ids=None,
893
+ inputs_embeds=None,
894
+ attention_mask=None,
895
+ position_ids=None,
896
+ encoder_hidden_states=None,
897
+ encoder_attention_mask=None,
898
+ head_mask=None,
899
+ cross_attn_head_mask=None,
900
+ past_key_values=None,
901
+ use_cache=None,
902
+ output_attentions=None,
903
+ output_hidden_states=None,
904
+ return_dict=None,
905
+ training=False,
906
+ ):
907
+ r"""
908
+ Args:
909
+ input_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`):
910
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
911
+ provide it.
912
+
913
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
914
+ [`PreTrainedTokenizer.__call__`] for details.
915
+
916
+ [What are input IDs?](../glossary#input-ids)
917
+ attention_mask (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
918
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
919
+
920
+ - 1 for tokens that are **not masked**,
921
+ - 0 for tokens that are **masked**.
922
+
923
+ [What are attention masks?](../glossary#attention-mask)
924
+ position_ids (`tf.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
925
+ Indices of positions of each decoder input sequence tokens in the position embeddings. Selected in the
926
+ range `[0, config.max_position_embeddings - 1]`.
927
+ encoder_hidden_states (`tf.Tensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
928
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
929
+ of the decoder.
930
+ encoder_attention_mask (`tf.Tensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
931
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
932
+ selected in `[0, 1]`:
933
+
934
+ - 1 for tokens that are **not masked**,
935
+ - 0 for tokens that are **masked**.
936
+
937
+ [What are attention masks?](../glossary#attention-mask)
938
+ head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
939
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
940
+
941
+ - 1 indicates the head is **not masked**,
942
+ - 0 indicates the head is **masked**.
943
+
944
+ cross_attn_head_mask (`tf.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
945
+ Mask to nullify selected heads of the cross-attention modules. Mask values selected in `[0, 1]`:
946
+
947
+ - 1 indicates the head is **not masked**,
948
+ - 0 indicates the head is **masked**.
949
+
950
+ past_key_values (`Tuple[Tuple[tf.Tensor]]` of length `config.n_layers` with each tuple having 2 tuples each of which has 2 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
951
+ Contains precomputed key and value hidden-states of the attention blocks. Can be used to speed up
952
+ decoding.
953
+
954
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
955
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
956
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`.
957
+ inputs_embeds (`tf.Tensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
958
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
959
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
960
+ than the model's internal embedding lookup matrix.
961
+ output_attentions (`bool`, *optional*):
962
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
963
+ returned tensors for more detail. This argument can be used only in eager mode, in graph mode the value
964
+ in the config will be used instead.
965
+ output_hidden_states (`bool`, *optional*):
966
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
967
+ for more detail. This argument can be used only in eager mode, in graph mode the value in the config
968
+ will be used instead.
969
+ return_dict (`bool`, *optional*):
970
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. This argument can be used
971
+ in eager mode, in graph mode the value will always be set to True.
972
+ training (`bool`, *optional*, defaults to `False`):
973
+ Whether or not to use the model in training mode (some modules like dropout modules have different
974
+ behaviors between training and evaluation).
975
+ """
976
+ if input_ids is not None and inputs_embeds is not None:
977
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
978
+ elif input_ids is not None:
979
+ input_shape = shape_list(input_ids)
980
+ elif inputs_embeds is not None:
981
+ input_shape = shape_list(inputs_embeds)[:-1]
982
+ else:
983
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
984
+
985
+ past_key_values_length = shape_list(past_key_values[0][0])[2] if past_key_values is not None else 0
986
+
987
+ if inputs_embeds is None:
988
+ check_embeddings_within_bounds(input_ids, self.embed_tokens.input_dim)
989
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
990
+
991
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
992
+ if input_shape[-1] > 1:
993
+ combined_attention_mask = _make_causal_mask(input_shape, past_key_values_length=past_key_values_length)
994
+ else:
995
+ combined_attention_mask = _expand_mask(
996
+ tf.ones((input_shape[0], input_shape[1] + past_key_values_length)), tgt_len=input_shape[-1]
997
+ )
998
+
999
+ if attention_mask is not None:
1000
+ combined_attention_mask = combined_attention_mask + _expand_mask(attention_mask, tgt_len=input_shape[-1])
1001
+
1002
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
1003
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1004
+ encoder_attention_mask = _expand_mask(encoder_attention_mask, tgt_len=input_shape[-1])
1005
+
1006
+ # embed positions
1007
+ if position_ids is None:
1008
+ positions = self.embed_positions(input_shape, past_key_values_length)
1009
+ else:
1010
+ positions = self.embed_positions(input_shape, position_ids=position_ids)
1011
+
1012
+ hidden_states = self.layernorm_embedding(inputs_embeds) + positions
1013
+ hidden_states = self.dropout(hidden_states, training=training)
1014
+
1015
+ # decoder layers
1016
+ all_hidden_states = () if output_hidden_states else None
1017
+ all_self_attns = () if output_attentions else None
1018
+ all_cross_attns = () if (output_attentions and encoder_hidden_states is not None) else None
1019
+ present_key_values = () if use_cache else None
1020
+
1021
+ # check if head_mask and cross_attn_head_mask have a correct number of layers specified if desired
1022
+ for attn_mask_name, attn_mask in [("head_mask", head_mask), ("cross_attn_head_mask", cross_attn_head_mask)]:
1023
+ if attn_mask is not None:
1024
+ tf.debugging.assert_equal(
1025
+ shape_list(attn_mask)[0],
1026
+ len(self.layers),
1027
+ message=(
1028
+ f"The {attn_mask_name} should be specified for {len(self.layers)} layers, but it is for"
1029
+ f" {shape_list(attn_mask)[0]}."
1030
+ ),
1031
+ )
1032
+
1033
+ for idx, decoder_layer in enumerate(self.layers):
1034
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1035
+ if output_hidden_states:
1036
+ all_hidden_states += (hidden_states,)
1037
+ dropout_probability = random.uniform(0, 1)
1038
+
1039
+ if training and (dropout_probability < self.layerdrop):
1040
+ continue
1041
+
1042
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
1043
+
1044
+ hidden_states, layer_self_attn, layer_cross_attn, present_key_value = decoder_layer(
1045
+ hidden_states,
1046
+ attention_mask=combined_attention_mask,
1047
+ encoder_hidden_states=encoder_hidden_states,
1048
+ encoder_attention_mask=encoder_attention_mask,
1049
+ layer_head_mask=head_mask[idx] if head_mask is not None else None,
1050
+ cross_attn_layer_head_mask=cross_attn_head_mask[idx] if cross_attn_head_mask is not None else None,
1051
+ past_key_value=past_key_value,
1052
+ )
1053
+
1054
+ if use_cache:
1055
+ present_key_values += (present_key_value,)
1056
+
1057
+ if output_attentions:
1058
+ all_self_attns += (layer_self_attn,)
1059
+
1060
+ if encoder_hidden_states is not None:
1061
+ all_cross_attns += (layer_cross_attn,)
1062
+
1063
+ if output_hidden_states:
1064
+ all_hidden_states += (hidden_states,)
1065
+
1066
+ if not return_dict:
1067
+ return hidden_states, present_key_values, all_hidden_states, all_self_attns, all_cross_attns
1068
+ else:
1069
+ return TFBaseModelOutputWithPastAndCrossAttentions(
1070
+ last_hidden_state=hidden_states,
1071
+ past_key_values=present_key_values,
1072
+ hidden_states=all_hidden_states,
1073
+ attentions=all_self_attns,
1074
+ cross_attentions=all_cross_attns,
1075
+ )
1076
+
1077
+ def build(self, input_shape=None):
1078
+ if self.built:
1079
+ return
1080
+ self.built = True
1081
+ if getattr(self, "embed_positions", None) is not None:
1082
+ with tf.name_scope(self.embed_positions.name):
1083
+ self.embed_positions.build(None)
1084
+ if getattr(self, "layernorm_embedding", None) is not None:
1085
+ with tf.name_scope(self.layernorm_embedding.name):
1086
+ self.layernorm_embedding.build([None, None, self.config.d_model])
1087
+ if getattr(self, "layers", None) is not None:
1088
+ for layer in self.layers:
1089
+ with tf.name_scope(layer.name):
1090
+ layer.build(None)
1091
+
1092
+
1093
+ @keras_serializable
1094
+ class TFBlenderbotSmallMainLayer(keras.layers.Layer):
1095
+ config_class = BlenderbotSmallConfig
1096
+
1097
+ def __init__(self, config: BlenderbotSmallConfig, **kwargs):
1098
+ super().__init__(**kwargs)
1099
+
1100
+ self.config = config
1101
+ self.shared = keras.layers.Embedding(
1102
+ input_dim=config.vocab_size,
1103
+ output_dim=config.d_model,
1104
+ embeddings_initializer=keras.initializers.TruncatedNormal(stddev=self.config.init_std),
1105
+ name="model.shared",
1106
+ )
1107
+ # Additional attribute to specify the expected name scope of the layer (for loading/storing weights)
1108
+ self.shared.load_weight_prefix = "model.shared"
1109
+
1110
+ self.encoder = TFBlenderbotSmallEncoder(config, self.shared, name="encoder")
1111
+ self.decoder = TFBlenderbotSmallDecoder(config, self.shared, name="decoder")
1112
+
1113
+ def get_input_embeddings(self):
1114
+ return self.shared
1115
+
1116
+ def set_input_embeddings(self, new_embeddings):
1117
+ self.shared = new_embeddings
1118
+ self.encoder.embed_tokens = self.shared
1119
+ self.decoder.embed_tokens = self.shared
1120
+
1121
+ @unpack_inputs
1122
+ def call(
1123
+ self,
1124
+ input_ids=None,
1125
+ attention_mask=None,
1126
+ decoder_input_ids=None,
1127
+ decoder_attention_mask=None,
1128
+ decoder_position_ids=None,
1129
+ head_mask=None,
1130
+ decoder_head_mask=None,
1131
+ cross_attn_head_mask=None,
1132
+ encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,
1133
+ past_key_values=None,
1134
+ inputs_embeds=None,
1135
+ decoder_inputs_embeds=None,
1136
+ use_cache=None,
1137
+ output_attentions=None,
1138
+ output_hidden_states=None,
1139
+ return_dict=None,
1140
+ training=False,
1141
+ **kwargs,
1142
+ ):
1143
+ output_hidden_states = (
1144
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1145
+ )
1146
+
1147
+ if encoder_outputs is None:
1148
+ encoder_outputs = self.encoder(
1149
+ input_ids=input_ids,
1150
+ attention_mask=attention_mask,
1151
+ head_mask=head_mask,
1152
+ inputs_embeds=inputs_embeds,
1153
+ output_attentions=output_attentions,
1154
+ output_hidden_states=output_hidden_states,
1155
+ return_dict=return_dict,
1156
+ training=training,
1157
+ )
1158
+ # If the user passed a tuple for encoder_outputs, we wrap it in a TFBaseModelOutput when return_dict=True
1159
+ elif return_dict and not isinstance(encoder_outputs, TFBaseModelOutput):
1160
+ encoder_outputs = TFBaseModelOutput(
1161
+ last_hidden_state=encoder_outputs[0],
1162
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1163
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1164
+ )
1165
+ # If the user passed a TFBaseModelOutput for encoder_outputs, we wrap it in a tuple when return_dict=False
1166
+ elif not return_dict and not isinstance(encoder_outputs, tuple):
1167
+ encoder_outputs = encoder_outputs.to_tuple()
1168
+
1169
+ decoder_outputs = self.decoder(
1170
+ decoder_input_ids,
1171
+ attention_mask=decoder_attention_mask,
1172
+ position_ids=decoder_position_ids,
1173
+ encoder_hidden_states=encoder_outputs[0],
1174
+ encoder_attention_mask=attention_mask,
1175
+ head_mask=decoder_head_mask,
1176
+ cross_attn_head_mask=cross_attn_head_mask,
1177
+ past_key_values=past_key_values,
1178
+ inputs_embeds=decoder_inputs_embeds,
1179
+ use_cache=use_cache,
1180
+ output_attentions=output_attentions,
1181
+ output_hidden_states=output_hidden_states,
1182
+ return_dict=return_dict,
1183
+ training=training,
1184
+ )
1185
+
1186
+ if not return_dict:
1187
+ return decoder_outputs + encoder_outputs
1188
+
1189
+ return TFSeq2SeqModelOutput(
1190
+ last_hidden_state=decoder_outputs.last_hidden_state,
1191
+ past_key_values=decoder_outputs.past_key_values,
1192
+ decoder_hidden_states=decoder_outputs.hidden_states,
1193
+ decoder_attentions=decoder_outputs.attentions,
1194
+ cross_attentions=decoder_outputs.cross_attentions,
1195
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1196
+ encoder_hidden_states=encoder_outputs.hidden_states,
1197
+ encoder_attentions=encoder_outputs.attentions,
1198
+ )
1199
+
1200
+ def build(self, input_shape=None):
1201
+ if self.built:
1202
+ return
1203
+ self.built = True
1204
+ # The shared/tied weights expect to be in the model base namespace
1205
+ # Adding "/" to the end (not the start!) of a tf.name_scope puts it in the root namespace rather than
1206
+ # the current one.
1207
+ with tf.name_scope(self.shared.load_weight_prefix + "/" + self.shared.name + "/"):
1208
+ self.shared.build(None)
1209
+ if getattr(self, "encoder", None) is not None:
1210
+ with tf.name_scope(self.encoder.name):
1211
+ self.encoder.build(None)
1212
+ if getattr(self, "decoder", None) is not None:
1213
+ with tf.name_scope(self.decoder.name):
1214
+ self.decoder.build(None)
1215
+
1216
+
1217
+ @add_start_docstrings(
1218
+ "The bare BLENDERBOT_SMALL Model outputting raw hidden-states without any specific head on top.",
1219
+ BLENDERBOT_SMALL_START_DOCSTRING,
1220
+ )
1221
+ class TFBlenderbotSmallModel(TFBlenderbotSmallPreTrainedModel):
1222
+ def __init__(self, config: BlenderbotSmallConfig, *inputs, **kwargs):
1223
+ super().__init__(config, *inputs, **kwargs)
1224
+
1225
+ self.model = TFBlenderbotSmallMainLayer(config, name="model")
1226
+
1227
+ def get_encoder(self):
1228
+ return self.model.encoder
1229
+
1230
+ def get_decoder(self):
1231
+ return self.model.decoder
1232
+
1233
+ @unpack_inputs
1234
+ @add_start_docstrings_to_model_forward(BLENDERBOT_SMALL_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
1235
+ @add_code_sample_docstrings(
1236
+ checkpoint=_CHECKPOINT_FOR_DOC,
1237
+ output_type=TFSeq2SeqModelOutput,
1238
+ config_class=_CONFIG_FOR_DOC,
1239
+ )
1240
+ def call(
1241
+ self,
1242
+ input_ids: tf.Tensor | None = None,
1243
+ attention_mask: tf.Tensor | None = None,
1244
+ decoder_input_ids: tf.Tensor | None = None,
1245
+ decoder_attention_mask: tf.Tensor | None = None,
1246
+ decoder_position_ids: tf.Tensor | None = None,
1247
+ head_mask: tf.Tensor | None = None,
1248
+ decoder_head_mask: tf.Tensor | None = None,
1249
+ cross_attn_head_mask: tf.Tensor | None = None,
1250
+ encoder_outputs: Optional[Union[Tuple, TFBaseModelOutput]] = None,
1251
+ past_key_values: List[tf.Tensor] | None = None,
1252
+ inputs_embeds: tf.Tensor | None = None,
1253
+ decoder_inputs_embeds: tf.Tensor | None = None,
1254
+ use_cache: Optional[bool] = None,
1255
+ output_attentions: Optional[bool] = None,
1256
+ output_hidden_states: Optional[bool] = None,
1257
+ return_dict: Optional[bool] = None,
1258
+ training: Optional[bool] = False,
1259
+ **kwargs,
1260
+ ) -> Union[Tuple[tf.Tensor], TFSeq2SeqModelOutput]:
1261
+ outputs = self.model(
1262
+ input_ids=input_ids,
1263
+ attention_mask=attention_mask,
1264
+ decoder_input_ids=decoder_input_ids,
1265
+ decoder_attention_mask=decoder_attention_mask,
1266
+ decoder_position_ids=decoder_position_ids,
1267
+ head_mask=head_mask,
1268
+ decoder_head_mask=decoder_head_mask,
1269
+ cross_attn_head_mask=cross_attn_head_mask,
1270
+ encoder_outputs=encoder_outputs,
1271
+ past_key_values=past_key_values,
1272
+ inputs_embeds=inputs_embeds,
1273
+ decoder_inputs_embeds=decoder_inputs_embeds,
1274
+ use_cache=use_cache,
1275
+ output_attentions=output_attentions,
1276
+ output_hidden_states=output_hidden_states,
1277
+ return_dict=return_dict,
1278
+ training=training,
1279
+ )
1280
+
1281
+ return outputs
1282
+
1283
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartModel.serving_output
1284
+ def serving_output(self, output):
1285
+ pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None
1286
+ dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
1287
+ dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
1288
+ cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
1289
+ enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
1290
+ enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
1291
+
1292
+ return TFSeq2SeqModelOutput(
1293
+ last_hidden_state=output.last_hidden_state,
1294
+ past_key_values=pkv,
1295
+ decoder_hidden_states=dec_hs,
1296
+ decoder_attentions=dec_attns,
1297
+ cross_attentions=cross_attns,
1298
+ encoder_last_hidden_state=output.encoder_last_hidden_state,
1299
+ encoder_hidden_states=enc_hs,
1300
+ encoder_attentions=enc_attns,
1301
+ )
1302
+
1303
+ def build(self, input_shape=None):
1304
+ if self.built:
1305
+ return
1306
+ self.built = True
1307
+ if getattr(self, "model", None) is not None:
1308
+ with tf.name_scope(self.model.name):
1309
+ self.model.build(None)
1310
+
1311
+
1312
+ # Copied from transformers.models.bart.modeling_tf_bart.BiasLayer
1313
+ class BiasLayer(keras.layers.Layer):
1314
+ """
1315
+ Bias as a layer. It is used for serialization purposes: `keras.Model.save_weights` stores on a per-layer basis,
1316
+ so all weights have to be registered in a layer.
1317
+ """
1318
+
1319
+ def __init__(self, shape, initializer, trainable, name, **kwargs):
1320
+ super().__init__(name=name, **kwargs)
1321
+ # Note: the name of this variable will NOT be scoped when serialized, i.e. it will not be in the format of
1322
+ # "outer_layer/inner_layer/.../name:0". Instead, it will be "name:0". For further details, see:
1323
+ # https://github.com/huggingface/transformers/pull/18833#issuecomment-1233090214
1324
+ self.bias = self.add_weight(name=name, shape=shape, initializer=initializer, trainable=trainable)
1325
+
1326
+ def call(self, x):
1327
+ return x + self.bias
1328
+
1329
+
1330
+ @add_start_docstrings(
1331
+ "The BLENDERBOT_SMALL Model with a language modeling head. Can be used for summarization.",
1332
+ BLENDERBOT_SMALL_START_DOCSTRING,
1333
+ )
1334
+ class TFBlenderbotSmallForConditionalGeneration(TFBlenderbotSmallPreTrainedModel, TFCausalLanguageModelingLoss):
1335
+ _keys_to_ignore_on_load_unexpected = [
1336
+ r"model.encoder.embed_tokens.weight",
1337
+ r"model.decoder.embed_tokens.weight",
1338
+ ]
1339
+
1340
+ def __init__(self, config, *inputs, **kwargs):
1341
+ super().__init__(config, *inputs, **kwargs)
1342
+ self.model = TFBlenderbotSmallMainLayer(config, name="model")
1343
+ self.use_cache = config.use_cache
1344
+ # final_bias_logits is registered as a buffer in pytorch, so not trainable for the sake of consistency.
1345
+ self.bias_layer = BiasLayer(
1346
+ name="final_logits_bias", shape=[1, config.vocab_size], initializer="zeros", trainable=False
1347
+ )
1348
+
1349
+ def get_decoder(self):
1350
+ return self.model.decoder
1351
+
1352
+ def get_encoder(self):
1353
+ return self.model.encoder
1354
+
1355
+ def get_output_embeddings(self):
1356
+ return self.get_input_embeddings()
1357
+
1358
+ def set_output_embeddings(self, value):
1359
+ self.set_input_embeddings(value)
1360
+
1361
+ def get_bias(self):
1362
+ return {"final_logits_bias": self.bias_layer.bias}
1363
+
1364
+ def set_bias(self, value):
1365
+ # Replaces the existing layers containing bias for correct (de)serialization.
1366
+ vocab_size = value["final_logits_bias"].shape[-1]
1367
+ self.bias_layer = BiasLayer(
1368
+ name="final_logits_bias", shape=[1, vocab_size], initializer="zeros", trainable=False
1369
+ )
1370
+ self.bias_layer.bias.assign(value["final_logits_bias"])
1371
+
1372
+ @unpack_inputs
1373
+ @add_start_docstrings_to_model_forward(BLENDERBOT_SMALL_INPUTS_DOCSTRING)
1374
+ @replace_return_docstrings(output_type=TFSeq2SeqLMOutput, config_class=_CONFIG_FOR_DOC)
1375
+ @add_end_docstrings(BLENDERBOT_SMALL_GENERATION_EXAMPLE)
1376
+ def call(
1377
+ self,
1378
+ input_ids: tf.Tensor | None = None,
1379
+ attention_mask: tf.Tensor | None = None,
1380
+ decoder_input_ids: tf.Tensor | None = None,
1381
+ decoder_attention_mask: tf.Tensor | None = None,
1382
+ decoder_position_ids: tf.Tensor | None = None,
1383
+ head_mask: tf.Tensor | None = None,
1384
+ decoder_head_mask: tf.Tensor | None = None,
1385
+ cross_attn_head_mask: tf.Tensor | None = None,
1386
+ encoder_outputs: Optional[TFBaseModelOutput] = None,
1387
+ past_key_values: List[tf.Tensor] | None = None,
1388
+ inputs_embeds: tf.Tensor | None = None,
1389
+ decoder_inputs_embeds: tf.Tensor | None = None,
1390
+ use_cache: Optional[bool] = None,
1391
+ output_attentions: Optional[bool] = None,
1392
+ output_hidden_states: Optional[bool] = None,
1393
+ return_dict: Optional[bool] = None,
1394
+ labels: tf.Tensor | None = None,
1395
+ training: Optional[bool] = False,
1396
+ ) -> Union[Tuple[tf.Tensor], TFSeq2SeqLMOutput]:
1397
+ r"""
1398
+ labels (`tf.tensor` of shape `(batch_size, sequence_length)`, *optional*):
1399
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1400
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1401
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1402
+
1403
+ Returns:
1404
+
1405
+ """
1406
+
1407
+ if labels is not None:
1408
+ labels = tf.where(
1409
+ labels == self.config.pad_token_id,
1410
+ tf.cast(tf.fill(shape_list(labels), -100), labels.dtype),
1411
+ labels,
1412
+ )
1413
+ use_cache = False
1414
+ if decoder_input_ids is None and decoder_inputs_embeds is None:
1415
+ decoder_input_ids = shift_tokens_right(
1416
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
1417
+ )
1418
+
1419
+ outputs = self.model(
1420
+ input_ids,
1421
+ attention_mask=attention_mask,
1422
+ decoder_input_ids=decoder_input_ids,
1423
+ decoder_attention_mask=decoder_attention_mask,
1424
+ decoder_position_ids=decoder_position_ids,
1425
+ head_mask=head_mask,
1426
+ decoder_head_mask=decoder_head_mask,
1427
+ cross_attn_head_mask=cross_attn_head_mask,
1428
+ encoder_outputs=encoder_outputs,
1429
+ past_key_values=past_key_values,
1430
+ inputs_embeds=inputs_embeds,
1431
+ decoder_inputs_embeds=decoder_inputs_embeds,
1432
+ use_cache=use_cache,
1433
+ output_attentions=output_attentions,
1434
+ output_hidden_states=output_hidden_states,
1435
+ return_dict=return_dict,
1436
+ training=training,
1437
+ )
1438
+ lm_logits = tf.matmul(outputs[0], self.model.shared.weights, transpose_b=True)
1439
+ lm_logits = self.bias_layer(lm_logits)
1440
+ masked_lm_loss = None if labels is None else self.hf_compute_loss(labels, lm_logits)
1441
+
1442
+ if not return_dict:
1443
+ output = (lm_logits,) + outputs[1:]
1444
+ return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1445
+ return TFSeq2SeqLMOutput(
1446
+ loss=masked_lm_loss,
1447
+ logits=lm_logits,
1448
+ past_key_values=outputs.past_key_values, # index 1 of d outputs
1449
+ decoder_hidden_states=outputs.decoder_hidden_states, # index 2 of d outputs
1450
+ decoder_attentions=outputs.decoder_attentions, # index 3 of d outputs
1451
+ cross_attentions=outputs.cross_attentions, # index 4 of d outputs
1452
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state, # index 0 of encoder outputs
1453
+ encoder_hidden_states=outputs.encoder_hidden_states, # 1 of e out
1454
+ encoder_attentions=outputs.encoder_attentions, # 2 of e out
1455
+ )
1456
+
1457
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartForConditionalGeneration.serving_output
1458
+ def serving_output(self, output):
1459
+ pkv = tf.tuple(output.past_key_values)[1] if self.config.use_cache else None
1460
+ dec_hs = tf.convert_to_tensor(output.decoder_hidden_states) if self.config.output_hidden_states else None
1461
+ dec_attns = tf.convert_to_tensor(output.decoder_attentions) if self.config.output_attentions else None
1462
+ cross_attns = tf.convert_to_tensor(output.cross_attentions) if self.config.output_attentions else None
1463
+ enc_hs = tf.convert_to_tensor(output.encoder_hidden_states) if self.config.output_hidden_states else None
1464
+ enc_attns = tf.convert_to_tensor(output.encoder_attentions) if self.config.output_attentions else None
1465
+
1466
+ return TFSeq2SeqLMOutput(
1467
+ logits=output.logits,
1468
+ past_key_values=pkv,
1469
+ decoder_hidden_states=dec_hs,
1470
+ decoder_attentions=dec_attns,
1471
+ cross_attentions=cross_attns,
1472
+ encoder_last_hidden_state=output.encoder_last_hidden_state,
1473
+ encoder_hidden_states=enc_hs,
1474
+ encoder_attentions=enc_attns,
1475
+ )
1476
+
1477
+ # Copied from transformers.models.bart.modeling_tf_bart.TFBartForConditionalGeneration.prepare_inputs_for_generation
1478
+ def prepare_inputs_for_generation(
1479
+ self,
1480
+ decoder_input_ids,
1481
+ past_key_values=None,
1482
+ attention_mask=None,
1483
+ decoder_attention_mask=None,
1484
+ head_mask=None,
1485
+ decoder_head_mask=None,
1486
+ cross_attn_head_mask=None,
1487
+ use_cache=None,
1488
+ encoder_outputs=None,
1489
+ **kwargs,
1490
+ ):
1491
+ # cut decoder_input_ids if past_key_values is used
1492
+ if past_key_values is not None:
1493
+ decoder_input_ids = decoder_input_ids[:, -1:]
1494
+
1495
+ if decoder_attention_mask is not None: # xla
1496
+ decoder_position_ids = tf.math.cumsum(decoder_attention_mask, axis=-1, exclusive=True)[:, -1:]
1497
+ elif past_key_values is not None: # no xla + past_key_values
1498
+ decoder_position_ids = past_key_values[0][0].shape[2]
1499
+ else: # no xla + no past_key_values
1500
+ decoder_position_ids = tf.range(decoder_input_ids.shape[1])
1501
+
1502
+ return {
1503
+ "input_ids": None, # encoder_outputs is defined. input_ids not needed
1504
+ "encoder_outputs": encoder_outputs,
1505
+ "past_key_values": past_key_values,
1506
+ "decoder_input_ids": decoder_input_ids,
1507
+ "attention_mask": attention_mask,
1508
+ "decoder_attention_mask": decoder_attention_mask,
1509
+ "decoder_position_ids": decoder_position_ids,
1510
+ "head_mask": head_mask,
1511
+ "decoder_head_mask": decoder_head_mask,
1512
+ "cross_attn_head_mask": cross_attn_head_mask,
1513
+ "use_cache": use_cache, # change this to avoid caching (presumably for debugging)
1514
+ }
1515
+
1516
+ def build(self, input_shape=None):
1517
+ if self.built:
1518
+ return
1519
+ self.built = True
1520
+ if getattr(self, "model", None) is not None:
1521
+ with tf.name_scope(self.model.name):
1522
+ self.model.build(None)
1523
+ if getattr(self, "bias_layer", None) is not None:
1524
+ with tf.name_scope(self.bias_layer.name):
1525
+ self.bias_layer.build(None)
1526
+
1527
+
1528
+ __all__ = ["TFBlenderbotSmallForConditionalGeneration", "TFBlenderbotSmallModel", "TFBlenderbotSmallPreTrainedModel"]
lib/python3.12/site-packages/transformers/models/blenderbot_small/tokenization_blenderbot_small.py ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The Facebook Inc. 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
+ """Tokenization class for BlenderbotSmall."""
16
+
17
+ import json
18
+ import os
19
+ from typing import Dict, List, Optional, Tuple
20
+
21
+ import regex as re
22
+
23
+ from ...tokenization_utils import PreTrainedTokenizer
24
+ from ...utils import logging
25
+
26
+
27
+ logger = logging.get_logger(__name__)
28
+
29
+
30
+ VOCAB_FILES_NAMES = {
31
+ "vocab_file": "vocab.json",
32
+ "merges_file": "merges.txt",
33
+ "tokenizer_config_file": "tokenizer_config.json",
34
+ }
35
+
36
+
37
+ def get_pairs(word):
38
+ """
39
+ Return set of symbol pairs in a word.
40
+
41
+ Word is represented as tuple of symbols (symbols being variable-length strings).
42
+ """
43
+ pairs = set()
44
+ prev_char = word[0]
45
+ for char in word[1:]:
46
+ pairs.add((prev_char, char))
47
+ prev_char = char
48
+
49
+ pairs = set(pairs)
50
+ return pairs
51
+
52
+
53
+ class BlenderbotSmallTokenizer(PreTrainedTokenizer):
54
+ """
55
+ Constructs a Blenderbot-90M tokenizer based on BPE (Byte-Pair-Encoding)
56
+
57
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
58
+ the superclass for more information regarding methods.
59
+
60
+ Args:
61
+ vocab_file (`str`):
62
+ File containing the vocabulary.
63
+ merges_file (`str`):
64
+ Path to the merges file.
65
+ bos_token (`str`, *optional*, defaults to `"__start__"`):
66
+ The beginning of sentence token.
67
+ eos_token (`str`, *optional*, defaults to `"__end__"`):
68
+ The end of sentence token.
69
+ unk_token (`str`, *optional*, defaults to `"__unk__"`):
70
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
71
+ token instead.
72
+ pad_token (`str`, *optional*, defaults to `"__null__"`):
73
+ The token used for padding, for example when batching sequences of different lengths.
74
+ kwargs (*optional*):
75
+ Additional keyword arguments passed along to [`PreTrainedTokenizer`]
76
+ """
77
+
78
+ vocab_files_names = VOCAB_FILES_NAMES
79
+ model_input_names = ["input_ids", "attention_mask"]
80
+
81
+ def __init__(
82
+ self,
83
+ vocab_file,
84
+ merges_file,
85
+ bos_token="__start__",
86
+ eos_token="__end__",
87
+ unk_token="__unk__",
88
+ pad_token="__null__",
89
+ **kwargs,
90
+ ):
91
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
92
+ self.encoder = json.load(vocab_handle)
93
+ self.decoder = {v: k for k, v in self.encoder.items()}
94
+ with open(merges_file, encoding="utf-8") as merges_handle:
95
+ merges = merges_handle.read().split("\n")[1:-1]
96
+ merges = [tuple(merge.split()) for merge in merges]
97
+ self.bpe_ranks = dict(zip(merges, range(len(merges))))
98
+ self.cache = {}
99
+ super().__init__(unk_token=unk_token, bos_token=bos_token, eos_token=eos_token, pad_token=pad_token, **kwargs)
100
+
101
+ @property
102
+ def vocab_size(self) -> int:
103
+ return len(self.encoder)
104
+
105
+ def get_vocab(self) -> Dict:
106
+ return dict(self.encoder, **self.added_tokens_encoder)
107
+
108
+ def bpe(self, token: str) -> str:
109
+ if token in self.cache:
110
+ return self.cache[token]
111
+ token = re.sub("([.,!?()])", r" \1", token)
112
+ token = re.sub("(')", r" \1 ", token)
113
+ token = re.sub(r"\s{2,}", " ", token)
114
+ if "\n" in token:
115
+ token = token.replace("\n", " __newln__")
116
+
117
+ tokens = token.split(" ")
118
+ words = []
119
+ for token in tokens:
120
+ if not len(token):
121
+ continue
122
+
123
+ token = token.lower()
124
+ word = tuple(token)
125
+ word = tuple(list(word[:-1]) + [word[-1] + "</w>"])
126
+ pairs = get_pairs(word)
127
+
128
+ if not pairs:
129
+ words.append(token)
130
+ continue
131
+
132
+ while True:
133
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
134
+ if bigram not in self.bpe_ranks:
135
+ break
136
+ first, second = bigram
137
+ new_word = []
138
+ i = 0
139
+
140
+ while i < len(word):
141
+ try:
142
+ j = word.index(first, i)
143
+ new_word.extend(word[i:j])
144
+ i = j
145
+ except ValueError:
146
+ new_word.extend(word[i:])
147
+ break
148
+
149
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
150
+ new_word.append(first + second)
151
+ i += 2
152
+ else:
153
+ new_word.append(word[i])
154
+ i += 1
155
+ new_word = tuple(new_word)
156
+ word = new_word
157
+ if len(word) == 1:
158
+ break
159
+ else:
160
+ pairs = get_pairs(word)
161
+ word = "@@ ".join(word)
162
+ word = word[:-4]
163
+
164
+ self.cache[token] = word
165
+ words.append(word)
166
+ return " ".join(words)
167
+
168
+ def _tokenize(self, text: str) -> List[str]:
169
+ """Split a string into tokens using BPE."""
170
+ split_tokens = []
171
+
172
+ words = re.findall(r"\S+\n?", text)
173
+
174
+ for token in words:
175
+ split_tokens.extend(list(self.bpe(token).split(" ")))
176
+ return split_tokens
177
+
178
+ def _convert_token_to_id(self, token: str) -> int:
179
+ """Converts a token to an id using the vocab."""
180
+ token = token.lower()
181
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
182
+
183
+ def _convert_id_to_token(self, index: int) -> str:
184
+ """Converts an index (integer) in a token (str) using the vocab."""
185
+ return self.decoder.get(index, self.unk_token)
186
+
187
+ def convert_tokens_to_string(self, tokens: List[str]) -> str:
188
+ """Converts a sequence of tokens in a single string."""
189
+ out_string = " ".join(tokens).replace("@@ ", "").strip()
190
+ return out_string
191
+
192
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
193
+ if not os.path.isdir(save_directory):
194
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
195
+ return
196
+ vocab_file = os.path.join(
197
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
198
+ )
199
+ merge_file = os.path.join(
200
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
201
+ )
202
+
203
+ with open(vocab_file, "w", encoding="utf-8") as f:
204
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
205
+
206
+ index = 0
207
+ with open(merge_file, "w", encoding="utf-8") as writer:
208
+ writer.write("#version: 0.2\n")
209
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
210
+ if index != token_index:
211
+ logger.warning(
212
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
213
+ " Please check that the tokenizer is not corrupted!"
214
+ )
215
+ index = token_index
216
+ writer.write(" ".join(bpe_tokens) + "\n")
217
+ index += 1
218
+
219
+ return vocab_file, merge_file
220
+
221
+
222
+ __all__ = ["BlenderbotSmallTokenizer"]
lib/python3.12/site-packages/transformers/models/blenderbot_small/tokenization_blenderbot_small_fast.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021, The Facebook, Inc. 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
+ """Fast tokenization class for BlenderbotSmall."""
16
+
17
+ from typing import List, Optional
18
+
19
+ from tokenizers import ByteLevelBPETokenizer
20
+
21
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
22
+ from ...utils import logging
23
+ from .tokenization_blenderbot_small import BlenderbotSmallTokenizer
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+ VOCAB_FILES_NAMES = {
29
+ "vocab_file": "vocab.json",
30
+ "merges_file": "merges.txt",
31
+ "tokenizer_config_file": "tokenizer_config.json",
32
+ }
33
+
34
+
35
+ class BlenderbotSmallTokenizerFast(PreTrainedTokenizerFast):
36
+ """
37
+ Construct a "fast" BlenderbotSmall tokenizer (backed by HuggingFace's *tokenizers* library).
38
+
39
+ Args:
40
+ vocab_file (`str`):
41
+ Path to the vocabulary file.
42
+ """
43
+
44
+ vocab_files_names = VOCAB_FILES_NAMES
45
+ slow_tokenizer_class = BlenderbotSmallTokenizer
46
+
47
+ def __init__(
48
+ self,
49
+ vocab_file=None,
50
+ merges_file=None,
51
+ unk_token="<|endoftext|>",
52
+ bos_token="<|endoftext|>",
53
+ eos_token="<|endoftext|>",
54
+ add_prefix_space=False,
55
+ trim_offsets=True,
56
+ **kwargs,
57
+ ):
58
+ super().__init__(
59
+ ByteLevelBPETokenizer(
60
+ vocab=vocab_file,
61
+ merges=merges_file,
62
+ add_prefix_space=add_prefix_space,
63
+ trim_offsets=trim_offsets,
64
+ ),
65
+ bos_token=bos_token,
66
+ eos_token=eos_token,
67
+ unk_token=unk_token,
68
+ **kwargs,
69
+ )
70
+ self.add_prefix_space = add_prefix_space
71
+
72
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
73
+ output = [self.bos_token_id] + token_ids_0 + [self.eos_token_id]
74
+ if token_ids_1 is None:
75
+ return output
76
+
77
+ return output + [self.eos_token_id] + token_ids_1 + [self.eos_token_id]
78
+
79
+ def create_token_type_ids_from_sequences(
80
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
81
+ ) -> List[int]:
82
+ """
83
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. BlenderbotSmall
84
+ does not make use of token type ids, therefore a list of zeros is returned.
85
+
86
+ Args:
87
+ token_ids_0 (`List[int]`):
88
+ List of IDs.
89
+ token_ids_1 (`List[int]`, *optional*):
90
+ Optional second list of IDs for sequence pairs.
91
+
92
+ Returns:
93
+ `List[int]`: List of zeros.
94
+ """
95
+ sep = [self.sep_token_id]
96
+ cls = [self.cls_token_id]
97
+
98
+ if token_ids_1 is None:
99
+ return len(cls + token_ids_0 + sep) * [0]
100
+ return len(cls + token_ids_0 + sep + sep + token_ids_1 + sep) * [0]
101
+
102
+
103
+ __all__ = ["BlenderbotSmallTokenizerFast"]
lib/python3.12/site-packages/transformers/models/byt5/__init__.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .tokenization_byt5 import *
22
+ else:
23
+ import sys
24
+
25
+ _file = globals()["__file__"]
26
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
lib/python3.12/site-packages/transformers/models/byt5/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (632 Bytes). View file
 
lib/python3.12/site-packages/transformers/models/byt5/__pycache__/tokenization_byt5.cpython-312.pyc ADDED
Binary file (11.2 kB). View file
 
lib/python3.12/site-packages/transformers/models/byt5/tokenization_byt5.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 T5 Authors and 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
+ """Tokenization class for model ByT5."""
16
+
17
+ import warnings
18
+ from typing import List, Optional, Tuple
19
+
20
+ from ...tokenization_utils import AddedToken, PreTrainedTokenizer
21
+ from ...utils import logging
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ class ByT5Tokenizer(PreTrainedTokenizer):
28
+ """
29
+ Construct a ByT5 tokenizer. ByT5 simply uses raw bytes utf-8 encoding.
30
+
31
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
32
+ this superclass for more information regarding those methods.
33
+
34
+ Args:
35
+ eos_token (`str`, *optional*, defaults to `"</s>"`):
36
+ The end of sequence token.
37
+
38
+ <Tip>
39
+
40
+ When building a sequence using special tokens, this is not the token that is used for the end of sequence.
41
+ The token used is the `sep_token`.
42
+
43
+ </Tip>
44
+
45
+ unk_token (`str`, *optional*, defaults to `"<unk>"`):
46
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
47
+ token instead.
48
+ pad_token (`str`, *optional*, defaults to `"<pad>"`):
49
+ The token used for padding, for example when batching sequences of different lengths.
50
+ extra_ids (`int`, *optional*, defaults to 125):
51
+ Add a number of extra ids added to the end of the vocabulary for use as sentinels. These tokens are
52
+ accessible as "<extra_id_{%d}>" where "{%d}" is a number between 0 and extra_ids-1. Extra tokens are
53
+ indexed from the end of the vocabulary up to beginning ("<extra_id_0>" is the last token in the vocabulary
54
+ like in ByT5 preprocessing see
55
+ [here](https://github.com/google-research/text-to-text-transfer-transformer/blob/9fd7b14a769417be33bc6c850f9598764913c833/t5/data/preprocessors.py#L2117)).
56
+ additional_special_tokens (`List[str]`, *optional*):
57
+ Additional special tokens used by the tokenizer.
58
+ """
59
+
60
+ model_input_names = ["input_ids", "attention_mask"]
61
+
62
+ def __init__(
63
+ self,
64
+ eos_token="</s>",
65
+ unk_token="<unk>",
66
+ pad_token="<pad>",
67
+ extra_ids=125,
68
+ additional_special_tokens=None,
69
+ **kwargs,
70
+ ) -> None:
71
+ # Add extra_ids to the special token list
72
+ if extra_ids > 0 and additional_special_tokens is None:
73
+ additional_special_tokens = [f"<extra_id_{i}>" for i in range(extra_ids)]
74
+ elif extra_ids > 0 and additional_special_tokens is not None and len(additional_special_tokens) > 0:
75
+ # Check that we have the right number of extra_id special tokens
76
+ extra_tokens = len(set(filter(lambda x: bool("extra_id" in str(x)), additional_special_tokens)))
77
+ if extra_tokens != extra_ids:
78
+ raise ValueError(
79
+ f"Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are"
80
+ " provided to ByT5Tokenizer. In this case the additional_special_tokens must include the"
81
+ " extra_ids tokens"
82
+ )
83
+
84
+ pad_token = AddedToken(pad_token, lstrip=True, rstrip=True) if isinstance(pad_token, str) else pad_token
85
+ # we force left and right stripping for backward compatibility. The byt5tests depend on this.
86
+ eos_token = AddedToken(eos_token, lstrip=True, rstrip=True) if isinstance(eos_token, str) else eos_token
87
+ unk_token = AddedToken(unk_token, lstrip=True, rstrip=True) if isinstance(unk_token, str) else unk_token
88
+ # unk token needs to be in the vocab with correct index
89
+ self._added_tokens_decoder = {0: pad_token, 1: eos_token, 2: unk_token}
90
+ self.offset = len(self._added_tokens_decoder)
91
+ self._utf_vocab_size = 2**8 # utf is 8 bits
92
+ super().__init__(
93
+ eos_token=eos_token,
94
+ unk_token=unk_token,
95
+ pad_token=pad_token,
96
+ extra_ids=0,
97
+ additional_special_tokens=additional_special_tokens, # TODO extra ids are not used :sweatywmile:
98
+ **kwargs,
99
+ )
100
+
101
+ @property
102
+ def vocab_size(self):
103
+ return self._utf_vocab_size
104
+
105
+ def get_vocab(self):
106
+ vocab = {self.convert_ids_to_tokens(i): i for i in range(self.vocab_size + self.offset)}
107
+ vocab.update(self.added_tokens_encoder)
108
+ return vocab
109
+
110
+ def get_special_tokens_mask(
111
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None, already_has_special_tokens: bool = False
112
+ ) -> List[int]:
113
+ """
114
+ Retrieve sequence ids from a token list that has no special tokens added. This method is called when adding
115
+ special tokens using the tokenizer `prepare_for_model` method.
116
+
117
+ Args:
118
+ token_ids_0 (`List[int]`):
119
+ List of IDs.
120
+ token_ids_1 (`List[int]`, *optional*):
121
+ Optional second list of IDs for sequence pairs.
122
+ already_has_special_tokens (`bool`, *optional*, defaults to `False`):
123
+ Whether or not the token list is already formatted with special tokens for the model.
124
+
125
+ Returns:
126
+ `List[int]`: A list of integers in the range [0, 1]: 1 for a special token, 0 for a sequence token.
127
+ """
128
+ if already_has_special_tokens:
129
+ return super().get_special_tokens_mask(
130
+ token_ids_0=token_ids_0, token_ids_1=token_ids_1, already_has_special_tokens=True
131
+ )
132
+
133
+ # normal case: some special tokens
134
+ if token_ids_1 is None:
135
+ return ([0] * len(token_ids_0)) + [1]
136
+ return ([0] * len(token_ids_0)) + [1] + ([0] * len(token_ids_1)) + [1]
137
+
138
+ def _add_eos_if_not_present(self, token_ids: List[int]) -> List[int]:
139
+ """Do not add eos again if user already added it."""
140
+ if len(token_ids) > 0 and token_ids[-1] == self.eos_token_id:
141
+ warnings.warn(
142
+ f"This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated"
143
+ " eos tokens being added."
144
+ )
145
+ return token_ids
146
+ else:
147
+ return token_ids + [self.eos_token_id]
148
+
149
+ def create_token_type_ids_from_sequences(
150
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
151
+ ) -> List[int]:
152
+ """
153
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. ByT5 does not
154
+ make use of token type ids, therefore a list of zeros is returned.
155
+
156
+ Args:
157
+ token_ids_0 (`List[int]`):
158
+ List of IDs.
159
+ token_ids_1 (`List[int]`, *optional*):
160
+ Optional second list of IDs for sequence pairs.
161
+
162
+ Returns:
163
+ `List[int]`: List of zeros.
164
+ """
165
+ eos = [self.eos_token_id]
166
+
167
+ if token_ids_1 is None:
168
+ return len(token_ids_0 + eos) * [0]
169
+ return len(token_ids_0 + eos + token_ids_1 + eos) * [0]
170
+
171
+ def build_inputs_with_special_tokens(
172
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
173
+ ) -> List[int]:
174
+ """
175
+ Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and
176
+ adding special tokens. A sequence has the following format:
177
+
178
+ - single sequence: `X </s>`
179
+ - pair of sequences: `A </s> B </s>`
180
+
181
+ Args:
182
+ token_ids_0 (`List[int]`):
183
+ List of IDs to which the special tokens will be added.
184
+ token_ids_1 (`List[int]`, *optional*):
185
+ Optional second list of IDs for sequence pairs.
186
+
187
+ Returns:
188
+ `List[int]`: List of [input IDs](../glossary#input-ids) with the appropriate special tokens.
189
+ """
190
+ token_ids_0 = self._add_eos_if_not_present(token_ids_0)
191
+ if token_ids_1 is None:
192
+ return token_ids_0
193
+ else:
194
+ token_ids_1 = self._add_eos_if_not_present(token_ids_1)
195
+ return token_ids_0 + token_ids_1
196
+
197
+ def _tokenize(self, text: str) -> List[str]:
198
+ """Take as input a string and return a list of strings (tokens) for words/sub-words"""
199
+ tokens = [chr(i) for i in text.encode("utf-8")]
200
+ return tokens
201
+
202
+ def _convert_token_to_id(self, token):
203
+ """Converts a token (str) in an id using the vocab."""
204
+
205
+ if len(token) != 1:
206
+ token_id = None
207
+ else:
208
+ token_id = ord(token) + self.offset
209
+
210
+ return token_id
211
+
212
+ def _convert_id_to_token(self, index):
213
+ """Converts an index (integer) in a token (str) using the vocab."""
214
+ token = chr(index - self.offset)
215
+ return token
216
+
217
+ def convert_tokens_to_string(self, tokens):
218
+ """Converts a sequence of tokens (string) in a single string."""
219
+ bstring = b""
220
+ for token in tokens:
221
+ if token in self.added_tokens_decoder:
222
+ tok_string = self.added_tokens_decoder[token].encode("utf-8")
223
+ elif token in self.added_tokens_encoder:
224
+ tok_string = token.encode("utf-8")
225
+ else:
226
+ tok_string = bytes([ord(token)])
227
+ bstring += tok_string
228
+ string = bstring.decode("utf-8", errors="ignore")
229
+ return string
230
+
231
+ # ByT5Tokenizer has no vocab file
232
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
233
+ return ()
234
+
235
+
236
+ __all__ = ["ByT5Tokenizer"]
lib/python3.12/site-packages/transformers/models/clipseg/__init__.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_clipseg import *
22
+ from .modeling_clipseg import *
23
+ from .processing_clipseg import *
24
+ else:
25
+ import sys
26
+
27
+ _file = globals()["__file__"]
28
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
lib/python3.12/site-packages/transformers/models/clipseg/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (703 Bytes). View file
 
lib/python3.12/site-packages/transformers/models/clipseg/__pycache__/configuration_clipseg.cpython-312.pyc ADDED
Binary file (16.7 kB). View file
 
lib/python3.12/site-packages/transformers/models/clipseg/__pycache__/modeling_clipseg.cpython-312.pyc ADDED
Binary file (71.2 kB). View file
 
lib/python3.12/site-packages/transformers/models/clipseg/__pycache__/processing_clipseg.cpython-312.pyc ADDED
Binary file (7.71 kB). View file
 
lib/python3.12/site-packages/transformers/models/clipseg/configuration_clipseg.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """CLIPSeg model configuration"""
16
+
17
+ from ...configuration_utils import PretrainedConfig
18
+ from ...utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+
24
+ class CLIPSegTextConfig(PretrainedConfig):
25
+ r"""
26
+ This is the configuration class to store the configuration of a [`CLIPSegModel`]. It is used to instantiate an
27
+ CLIPSeg model according to the specified arguments, defining the model architecture. Instantiating a configuration
28
+ with the defaults will yield a similar configuration to that of the CLIPSeg
29
+ [CIDAS/clipseg-rd64](https://huggingface.co/CIDAS/clipseg-rd64) architecture.
30
+
31
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
32
+ documentation from [`PretrainedConfig`] for more information.
33
+
34
+ Args:
35
+ vocab_size (`int`, *optional*, defaults to 49408):
36
+ Vocabulary size of the CLIPSeg text model. Defines the number of different tokens that can be represented
37
+ by the `inputs_ids` passed when calling [`CLIPSegModel`].
38
+ hidden_size (`int`, *optional*, defaults to 512):
39
+ Dimensionality of the encoder layers and the pooler layer.
40
+ intermediate_size (`int`, *optional*, defaults to 2048):
41
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
42
+ num_hidden_layers (`int`, *optional*, defaults to 12):
43
+ Number of hidden layers in the Transformer encoder.
44
+ num_attention_heads (`int`, *optional*, defaults to 8):
45
+ Number of attention heads for each attention layer in the Transformer encoder.
46
+ max_position_embeddings (`int`, *optional*, defaults to 77):
47
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
48
+ just in case (e.g., 512 or 1024 or 2048).
49
+ hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
50
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
51
+ `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
52
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
53
+ The epsilon used by the layer normalization layers.
54
+ attention_dropout (`float`, *optional*, defaults to 0.0):
55
+ The dropout ratio for the attention probabilities.
56
+ initializer_range (`float`, *optional*, defaults to 0.02):
57
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
58
+ initializer_factor (`float`, *optional*, defaults to 1.0):
59
+ A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
60
+ testing).
61
+ pad_token_id (`int`, *optional*, defaults to 1):
62
+ Padding token id.
63
+ bos_token_id (`int`, *optional*, defaults to 49406):
64
+ Beginning of stream token id.
65
+ eos_token_id (`int`, *optional*, defaults to 49407):
66
+ End of stream token id.
67
+
68
+ Example:
69
+
70
+ ```python
71
+ >>> from transformers import CLIPSegTextConfig, CLIPSegTextModel
72
+
73
+ >>> # Initializing a CLIPSegTextConfig with CIDAS/clipseg-rd64 style configuration
74
+ >>> configuration = CLIPSegTextConfig()
75
+
76
+ >>> # Initializing a CLIPSegTextModel (with random weights) from the CIDAS/clipseg-rd64 style configuration
77
+ >>> model = CLIPSegTextModel(configuration)
78
+
79
+ >>> # Accessing the model configuration
80
+ >>> configuration = model.config
81
+ ```"""
82
+
83
+ model_type = "clipseg_text_model"
84
+ base_config_key = "text_config"
85
+
86
+ def __init__(
87
+ self,
88
+ vocab_size=49408,
89
+ hidden_size=512,
90
+ intermediate_size=2048,
91
+ num_hidden_layers=12,
92
+ num_attention_heads=8,
93
+ max_position_embeddings=77,
94
+ hidden_act="quick_gelu",
95
+ layer_norm_eps=1e-5,
96
+ attention_dropout=0.0,
97
+ initializer_range=0.02,
98
+ initializer_factor=1.0,
99
+ pad_token_id=1,
100
+ bos_token_id=49406,
101
+ eos_token_id=49407,
102
+ **kwargs,
103
+ ):
104
+ super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
105
+
106
+ self.vocab_size = vocab_size
107
+ self.hidden_size = hidden_size
108
+ self.intermediate_size = intermediate_size
109
+ self.num_hidden_layers = num_hidden_layers
110
+ self.num_attention_heads = num_attention_heads
111
+ self.max_position_embeddings = max_position_embeddings
112
+ self.layer_norm_eps = layer_norm_eps
113
+ self.hidden_act = hidden_act
114
+ self.initializer_range = initializer_range
115
+ self.initializer_factor = initializer_factor
116
+ self.attention_dropout = attention_dropout
117
+
118
+
119
+ class CLIPSegVisionConfig(PretrainedConfig):
120
+ r"""
121
+ This is the configuration class to store the configuration of a [`CLIPSegModel`]. It is used to instantiate an
122
+ CLIPSeg model according to the specified arguments, defining the model architecture. Instantiating a configuration
123
+ with the defaults will yield a similar configuration to that of the CLIPSeg
124
+ [CIDAS/clipseg-rd64](https://huggingface.co/CIDAS/clipseg-rd64) architecture.
125
+
126
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
127
+ documentation from [`PretrainedConfig`] for more information.
128
+
129
+ Args:
130
+ hidden_size (`int`, *optional*, defaults to 768):
131
+ Dimensionality of the encoder layers and the pooler layer.
132
+ intermediate_size (`int`, *optional*, defaults to 3072):
133
+ Dimensionality of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
134
+ num_hidden_layers (`int`, *optional*, defaults to 12):
135
+ Number of hidden layers in the Transformer encoder.
136
+ num_attention_heads (`int`, *optional*, defaults to 12):
137
+ Number of attention heads for each attention layer in the Transformer encoder.
138
+ num_channels (`int`, *optional*, defaults to 3):
139
+ The number of input channels.
140
+ image_size (`int`, *optional*, defaults to 224):
141
+ The size (resolution) of each image.
142
+ patch_size (`int`, *optional*, defaults to 32):
143
+ The size (resolution) of each patch.
144
+ hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
145
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
146
+ `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
147
+ layer_norm_eps (`float`, *optional*, defaults to 1e-05):
148
+ The epsilon used by the layer normalization layers.
149
+ attention_dropout (`float`, *optional*, defaults to 0.0):
150
+ The dropout ratio for the attention probabilities.
151
+ initializer_range (`float`, *optional*, defaults to 0.02):
152
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
153
+ initializer_factor (`float`, *optional*, defaults to 1.0):
154
+ A factor for initializing all weight matrices (should be kept to 1, used internally for initialization
155
+ testing).
156
+
157
+ Example:
158
+
159
+ ```python
160
+ >>> from transformers import CLIPSegVisionConfig, CLIPSegVisionModel
161
+
162
+ >>> # Initializing a CLIPSegVisionConfig with CIDAS/clipseg-rd64 style configuration
163
+ >>> configuration = CLIPSegVisionConfig()
164
+
165
+ >>> # Initializing a CLIPSegVisionModel (with random weights) from the CIDAS/clipseg-rd64 style configuration
166
+ >>> model = CLIPSegVisionModel(configuration)
167
+
168
+ >>> # Accessing the model configuration
169
+ >>> configuration = model.config
170
+ ```"""
171
+
172
+ model_type = "clipseg_vision_model"
173
+ base_config_key = "vision_config"
174
+
175
+ def __init__(
176
+ self,
177
+ hidden_size=768,
178
+ intermediate_size=3072,
179
+ num_hidden_layers=12,
180
+ num_attention_heads=12,
181
+ num_channels=3,
182
+ image_size=224,
183
+ patch_size=32,
184
+ hidden_act="quick_gelu",
185
+ layer_norm_eps=1e-5,
186
+ attention_dropout=0.0,
187
+ initializer_range=0.02,
188
+ initializer_factor=1.0,
189
+ **kwargs,
190
+ ):
191
+ super().__init__(**kwargs)
192
+
193
+ self.hidden_size = hidden_size
194
+ self.intermediate_size = intermediate_size
195
+ self.num_hidden_layers = num_hidden_layers
196
+ self.num_attention_heads = num_attention_heads
197
+ self.num_channels = num_channels
198
+ self.patch_size = patch_size
199
+ self.image_size = image_size
200
+ self.initializer_range = initializer_range
201
+ self.initializer_factor = initializer_factor
202
+ self.attention_dropout = attention_dropout
203
+ self.layer_norm_eps = layer_norm_eps
204
+ self.hidden_act = hidden_act
205
+
206
+
207
+ class CLIPSegConfig(PretrainedConfig):
208
+ r"""
209
+ [`CLIPSegConfig`] is the configuration class to store the configuration of a [`CLIPSegModel`]. It is used to
210
+ instantiate a CLIPSeg model according to the specified arguments, defining the text model and vision model configs.
211
+ Instantiating a configuration with the defaults will yield a similar configuration to that of the CLIPSeg
212
+ [CIDAS/clipseg-rd64](https://huggingface.co/CIDAS/clipseg-rd64) architecture.
213
+
214
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
215
+ documentation from [`PretrainedConfig`] for more information.
216
+
217
+ Args:
218
+ text_config (`dict`, *optional*):
219
+ Dictionary of configuration options used to initialize [`CLIPSegTextConfig`].
220
+ vision_config (`dict`, *optional*):
221
+ Dictionary of configuration options used to initialize [`CLIPSegVisionConfig`].
222
+ projection_dim (`int`, *optional*, defaults to 512):
223
+ Dimensionality of text and vision projection layers.
224
+ logit_scale_init_value (`float`, *optional*, defaults to 2.6592):
225
+ The initial value of the *logit_scale* parameter. Default is used as per the original CLIPSeg implementation.
226
+ extract_layers (`List[int]`, *optional*, defaults to `[3, 6, 9]`):
227
+ Layers to extract when forwarding the query image through the frozen visual backbone of CLIP.
228
+ reduce_dim (`int`, *optional*, defaults to 64):
229
+ Dimensionality to reduce the CLIP vision embedding.
230
+ decoder_num_attention_heads (`int`, *optional*, defaults to 4):
231
+ Number of attention heads in the decoder of CLIPSeg.
232
+ decoder_attention_dropout (`float`, *optional*, defaults to 0.0):
233
+ The dropout ratio for the attention probabilities.
234
+ decoder_hidden_act (`str` or `function`, *optional*, defaults to `"quick_gelu"`):
235
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
236
+ `"relu"`, `"selu"` and `"gelu_new"` `"quick_gelu"` are supported.
237
+ decoder_intermediate_size (`int`, *optional*, defaults to 2048):
238
+ Dimensionality of the "intermediate" (i.e., feed-forward) layers in the Transformer decoder.
239
+ conditional_layer (`int`, *optional*, defaults to 0):
240
+ The layer to use of the Transformer encoder whose activations will be combined with the condition
241
+ embeddings using FiLM (Feature-wise Linear Modulation). If 0, the last layer is used.
242
+ use_complex_transposed_convolution (`bool`, *optional*, defaults to `False`):
243
+ Whether to use a more complex transposed convolution in the decoder, enabling more fine-grained
244
+ segmentation.
245
+ kwargs (*optional*):
246
+ Dictionary of keyword arguments.
247
+
248
+ Example:
249
+
250
+ ```python
251
+ >>> from transformers import CLIPSegConfig, CLIPSegModel
252
+
253
+ >>> # Initializing a CLIPSegConfig with CIDAS/clipseg-rd64 style configuration
254
+ >>> configuration = CLIPSegConfig()
255
+
256
+ >>> # Initializing a CLIPSegModel (with random weights) from the CIDAS/clipseg-rd64 style configuration
257
+ >>> model = CLIPSegModel(configuration)
258
+
259
+ >>> # Accessing the model configuration
260
+ >>> configuration = model.config
261
+
262
+ >>> # We can also initialize a CLIPSegConfig from a CLIPSegTextConfig and a CLIPSegVisionConfig
263
+
264
+ >>> # Initializing a CLIPSegText and CLIPSegVision configuration
265
+ >>> config_text = CLIPSegTextConfig()
266
+ >>> config_vision = CLIPSegVisionConfig()
267
+
268
+ >>> config = CLIPSegConfig.from_text_vision_configs(config_text, config_vision)
269
+ ```"""
270
+
271
+ model_type = "clipseg"
272
+ sub_configs = {"text_config": CLIPSegTextConfig, "vision_config": CLIPSegVisionConfig}
273
+
274
+ def __init__(
275
+ self,
276
+ text_config=None,
277
+ vision_config=None,
278
+ projection_dim=512,
279
+ logit_scale_init_value=2.6592,
280
+ extract_layers=[3, 6, 9],
281
+ reduce_dim=64,
282
+ decoder_num_attention_heads=4,
283
+ decoder_attention_dropout=0.0,
284
+ decoder_hidden_act="quick_gelu",
285
+ decoder_intermediate_size=2048,
286
+ conditional_layer=0,
287
+ use_complex_transposed_convolution=False,
288
+ **kwargs,
289
+ ):
290
+ # If `_config_dict` exist, we use them for the backward compatibility.
291
+ # We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
292
+ # of confusion!).
293
+ text_config_dict = kwargs.pop("text_config_dict", None)
294
+ vision_config_dict = kwargs.pop("vision_config_dict", None)
295
+
296
+ super().__init__(**kwargs)
297
+
298
+ # Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
299
+ # `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
300
+ # cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
301
+ if text_config_dict is not None:
302
+ if text_config is None:
303
+ text_config = {}
304
+
305
+ # This is the complete result when using `text_config_dict`.
306
+ _text_config_dict = CLIPSegTextConfig(**text_config_dict).to_dict()
307
+
308
+ # Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
309
+ for key, value in _text_config_dict.items():
310
+ if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
311
+ # If specified in `text_config_dict`
312
+ if key in text_config_dict:
313
+ message = (
314
+ f"`{key}` is found in both `text_config_dict` and `text_config` but with different values. "
315
+ f'The value `text_config_dict["{key}"]` will be used instead.'
316
+ )
317
+ # If inferred from default argument values (just to be super careful)
318
+ else:
319
+ message = (
320
+ f"`text_config_dict` is provided which will be used to initialize `CLIPSegTextConfig`. The "
321
+ f'value `text_config["{key}"]` will be overridden.'
322
+ )
323
+ logger.info(message)
324
+
325
+ # Update all values in `text_config` with the ones in `_text_config_dict`.
326
+ text_config.update(_text_config_dict)
327
+
328
+ if vision_config_dict is not None:
329
+ if vision_config is None:
330
+ vision_config = {}
331
+
332
+ # This is the complete result when using `vision_config_dict`.
333
+ _vision_config_dict = CLIPSegVisionConfig(**vision_config_dict).to_dict()
334
+ # convert keys to string instead of integer
335
+ if "id2label" in _vision_config_dict:
336
+ _vision_config_dict["id2label"] = {
337
+ str(key): value for key, value in _vision_config_dict["id2label"].items()
338
+ }
339
+
340
+ # Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
341
+ for key, value in _vision_config_dict.items():
342
+ if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
343
+ # If specified in `vision_config_dict`
344
+ if key in vision_config_dict:
345
+ message = (
346
+ f"`{key}` is found in both `vision_config_dict` and `vision_config` but with different "
347
+ f'values. The value `vision_config_dict["{key}"]` will be used instead.'
348
+ )
349
+ # If inferred from default argument values (just to be super careful)
350
+ else:
351
+ message = (
352
+ f"`vision_config_dict` is provided which will be used to initialize `CLIPSegVisionConfig`. "
353
+ f'The value `vision_config["{key}"]` will be overridden.'
354
+ )
355
+ logger.info(message)
356
+
357
+ # Update all values in `vision_config` with the ones in `_vision_config_dict`.
358
+ vision_config.update(_vision_config_dict)
359
+
360
+ if text_config is None:
361
+ text_config = {}
362
+ logger.info("`text_config` is `None`. Initializing the `CLIPSegTextConfig` with default values.")
363
+
364
+ if vision_config is None:
365
+ vision_config = {}
366
+ logger.info("`vision_config` is `None`. initializing the `CLIPSegVisionConfig` with default values.")
367
+
368
+ self.text_config = CLIPSegTextConfig(**text_config)
369
+ self.vision_config = CLIPSegVisionConfig(**vision_config)
370
+
371
+ self.projection_dim = projection_dim
372
+ self.logit_scale_init_value = logit_scale_init_value
373
+ self.extract_layers = extract_layers
374
+ self.reduce_dim = reduce_dim
375
+ self.decoder_num_attention_heads = decoder_num_attention_heads
376
+ self.decoder_attention_dropout = decoder_attention_dropout
377
+ self.decoder_hidden_act = decoder_hidden_act
378
+ self.decoder_intermediate_size = decoder_intermediate_size
379
+ self.conditional_layer = conditional_layer
380
+ self.initializer_factor = 1.0
381
+ self.use_complex_transposed_convolution = use_complex_transposed_convolution
382
+
383
+ @classmethod
384
+ def from_text_vision_configs(cls, text_config: CLIPSegTextConfig, vision_config: CLIPSegVisionConfig, **kwargs):
385
+ r"""
386
+ Instantiate a [`CLIPSegConfig`] (or a derived class) from clipseg text model configuration and clipseg vision
387
+ model configuration.
388
+
389
+ Returns:
390
+ [`CLIPSegConfig`]: An instance of a configuration object
391
+ """
392
+
393
+ return cls(text_config=text_config.to_dict(), vision_config=vision_config.to_dict(), **kwargs)
394
+
395
+
396
+ __all__ = ["CLIPSegConfig", "CLIPSegTextConfig", "CLIPSegVisionConfig"]
lib/python3.12/site-packages/transformers/models/clipseg/modeling_clipseg.py ADDED
@@ -0,0 +1,1522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The OpenAI Team Authors and The HuggingFace 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 CLIPSeg model."""
16
+
17
+ import copy
18
+ import math
19
+ from dataclasses import dataclass
20
+ from typing import Any, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+
26
+ from ...activations import ACT2FN
27
+ from ...modeling_attn_mask_utils import _create_4d_causal_attention_mask, _prepare_4d_attention_mask
28
+ from ...modeling_outputs import BaseModelOutput, BaseModelOutputWithPooling
29
+ from ...modeling_utils import PreTrainedModel
30
+ from ...utils import (
31
+ ModelOutput,
32
+ add_start_docstrings,
33
+ add_start_docstrings_to_model_forward,
34
+ logging,
35
+ replace_return_docstrings,
36
+ torch_int,
37
+ )
38
+ from .configuration_clipseg import CLIPSegConfig, CLIPSegTextConfig, CLIPSegVisionConfig
39
+
40
+
41
+ logger = logging.get_logger(__name__)
42
+
43
+
44
+ _CHECKPOINT_FOR_DOC = "CIDAS/clipseg-rd64-refined"
45
+
46
+
47
+ # contrastive loss function, adapted from
48
+ # https://sachinruk.github.io/blog/pytorch/pytorch%20lightning/loss%20function/gpu/2021/03/07/CLIP.html
49
+ def contrastive_loss(logits: torch.Tensor) -> torch.Tensor:
50
+ return nn.functional.cross_entropy(logits, torch.arange(len(logits), device=logits.device))
51
+
52
+
53
+ # Copied from transformers.models.clip.modeling_clip.clip_loss with clip->clipseg
54
+ def clipseg_loss(similarity: torch.Tensor) -> torch.Tensor:
55
+ caption_loss = contrastive_loss(similarity)
56
+ image_loss = contrastive_loss(similarity.t())
57
+ return (caption_loss + image_loss) / 2.0
58
+
59
+
60
+ @dataclass
61
+ # Copied from transformers.models.clip.modeling_clip.CLIPOutput with CLIP->CLIPSeg
62
+ class CLIPSegOutput(ModelOutput):
63
+ """
64
+ Args:
65
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
66
+ Contrastive loss for image-text similarity.
67
+ logits_per_image (`torch.FloatTensor` of shape `(image_batch_size, text_batch_size)`):
68
+ The scaled dot product scores between `image_embeds` and `text_embeds`. This represents the image-text
69
+ similarity scores.
70
+ logits_per_text (`torch.FloatTensor` of shape `(text_batch_size, image_batch_size)`):
71
+ The scaled dot product scores between `text_embeds` and `image_embeds`. This represents the text-image
72
+ similarity scores.
73
+ text_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
74
+ The text embeddings obtained by applying the projection layer to the pooled output of [`CLIPSegTextModel`].
75
+ image_embeds (`torch.FloatTensor` of shape `(batch_size, output_dim`):
76
+ The image embeddings obtained by applying the projection layer to the pooled output of [`CLIPSegVisionModel`].
77
+ text_model_output (`BaseModelOutputWithPooling`):
78
+ The output of the [`CLIPSegTextModel`].
79
+ vision_model_output (`BaseModelOutputWithPooling`):
80
+ The output of the [`CLIPSegVisionModel`].
81
+ """
82
+
83
+ loss: Optional[torch.FloatTensor] = None
84
+ logits_per_image: Optional[torch.FloatTensor] = None
85
+ logits_per_text: Optional[torch.FloatTensor] = None
86
+ text_embeds: Optional[torch.FloatTensor] = None
87
+ image_embeds: Optional[torch.FloatTensor] = None
88
+ text_model_output: BaseModelOutputWithPooling = None
89
+ vision_model_output: BaseModelOutputWithPooling = None
90
+
91
+ def to_tuple(self) -> Tuple[Any]:
92
+ return tuple(
93
+ self[k] if k not in ["text_model_output", "vision_model_output"] else getattr(self, k).to_tuple()
94
+ for k in self.keys()
95
+ )
96
+
97
+
98
+ @dataclass
99
+ class CLIPSegDecoderOutput(ModelOutput):
100
+ """
101
+ Args:
102
+ logits (`torch.FloatTensor` of shape `(batch_size, height, width)`):
103
+ Classification scores for each pixel.
104
+ hidden_states (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`):
105
+ Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +
106
+ one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.
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 layer) of shape `(batch_size, num_heads, sequence_length,
109
+ sequence_length)`. Attentions weights after the attention softmax, used to compute the weighted average in
110
+ the self-attention heads.
111
+ """
112
+
113
+ logits: Optional[torch.FloatTensor] = None
114
+ hidden_states: Optional[Tuple[torch.FloatTensor]] = None
115
+ attentions: Optional[Tuple[torch.FloatTensor]] = None
116
+
117
+
118
+ @dataclass
119
+ class CLIPSegImageSegmentationOutput(ModelOutput):
120
+ """
121
+ Args:
122
+ loss (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `return_loss` is `True`):
123
+ Contrastive loss for image-text similarity.
124
+ ...
125
+ vision_model_output (`BaseModelOutputWithPooling`):
126
+ The output of the [`CLIPSegVisionModel`].
127
+ """
128
+
129
+ loss: Optional[torch.FloatTensor] = None
130
+ logits: Optional[torch.FloatTensor] = None
131
+ conditional_embeddings: Optional[torch.FloatTensor] = None
132
+ pooled_output: Optional[torch.FloatTensor] = None
133
+ vision_model_output: BaseModelOutputWithPooling = None
134
+ decoder_output: CLIPSegDecoderOutput = None
135
+
136
+ def to_tuple(self) -> Tuple[Any]:
137
+ return tuple(
138
+ self[k] if k not in ["vision_model_output", "decoder_output"] else getattr(self, k).to_tuple()
139
+ for k in self.keys()
140
+ )
141
+
142
+
143
+ class CLIPSegVisionEmbeddings(nn.Module):
144
+ # Copied from transformers.models.clip.modeling_clip.CLIPVisionEmbeddings.__init__ with CLIP->CLIPSeg
145
+ def __init__(self, config: CLIPSegVisionConfig):
146
+ super().__init__()
147
+ self.config = config
148
+ self.embed_dim = config.hidden_size
149
+ self.image_size = config.image_size
150
+ self.patch_size = config.patch_size
151
+
152
+ self.class_embedding = nn.Parameter(torch.randn(self.embed_dim))
153
+
154
+ self.patch_embedding = nn.Conv2d(
155
+ in_channels=config.num_channels,
156
+ out_channels=self.embed_dim,
157
+ kernel_size=self.patch_size,
158
+ stride=self.patch_size,
159
+ bias=False,
160
+ )
161
+
162
+ self.num_patches = (self.image_size // self.patch_size) ** 2
163
+ self.num_positions = self.num_patches + 1
164
+ self.position_embedding = nn.Embedding(self.num_positions, self.embed_dim)
165
+ self.register_buffer("position_ids", torch.arange(self.num_positions).expand((1, -1)), persistent=False)
166
+
167
+ def interpolate_pos_encoding(self, embeddings: torch.Tensor, height: int, width: int) -> torch.Tensor:
168
+ """
169
+ This method allows to interpolate the pre-trained position encodings, to be able to use the model on higher resolution
170
+ images. This method is also adapted to support torch.jit tracing.
171
+
172
+ Adapted from:
173
+ - https://github.com/facebookresearch/dino/blob/de9ee3df6cf39fac952ab558447af1fa1365362a/vision_transformer.py#L174-L194, and
174
+ - https://github.com/facebookresearch/dinov2/blob/e1277af2ba9496fbadf7aec6eba56e8d882d1e35/dinov2/models/vision_transformer.py#L179-L211
175
+ """
176
+
177
+ num_patches = embeddings.shape[1] - 1
178
+ position_embedding = self.position_embedding.weight.unsqueeze(0)
179
+ num_positions = position_embedding.shape[1] - 1
180
+
181
+ # always interpolate when tracing to ensure the exported model works for dynamic input shapes
182
+ if not torch.jit.is_tracing() and num_patches == num_positions and height == width:
183
+ return self.position_embedding(self.position_ids)
184
+
185
+ class_pos_embed = position_embedding[:, :1]
186
+ patch_pos_embed = position_embedding[:, 1:]
187
+
188
+ dim = embeddings.shape[-1]
189
+
190
+ new_height = height // self.patch_size
191
+ new_width = width // self.patch_size
192
+
193
+ sqrt_num_positions = torch_int(num_positions**0.5)
194
+ patch_pos_embed = patch_pos_embed.reshape(1, sqrt_num_positions, sqrt_num_positions, dim)
195
+ patch_pos_embed = patch_pos_embed.permute(0, 3, 1, 2)
196
+
197
+ patch_pos_embed = nn.functional.interpolate(
198
+ patch_pos_embed,
199
+ size=(new_height, new_width),
200
+ mode="bicubic",
201
+ align_corners=False,
202
+ )
203
+
204
+ patch_pos_embed = patch_pos_embed.permute(0, 2, 3, 1).view(1, -1, dim)
205
+
206
+ return torch.cat((class_pos_embed, patch_pos_embed), dim=1)
207
+
208
+ def forward(self, pixel_values: torch.FloatTensor, interpolate_pos_encoding=True) -> torch.Tensor:
209
+ batch_size, _, height, width = pixel_values.shape
210
+ if not interpolate_pos_encoding and (height != self.image_size or width != self.image_size):
211
+ raise ValueError(
212
+ f"Input image size ({height}*{width}) doesn't match model ({self.image_size}*{self.image_size})."
213
+ )
214
+ patch_embeds = self.patch_embedding(pixel_values) # shape = [*, width, grid, grid]
215
+ patch_embeds = patch_embeds.flatten(2).transpose(1, 2)
216
+
217
+ class_embeds = self.class_embedding.expand(batch_size, 1, -1)
218
+ embeddings = torch.cat([class_embeds, patch_embeds], dim=1)
219
+ if interpolate_pos_encoding:
220
+ embeddings = embeddings + self.interpolate_pos_encoding(embeddings, height, width)
221
+ else:
222
+ embeddings = embeddings + self.position_embedding(self.position_ids)
223
+ return embeddings
224
+
225
+
226
+ # Copied from transformers.models.clip.modeling_clip.CLIPTextEmbeddings with CLIP->CLIPSeg
227
+ class CLIPSegTextEmbeddings(nn.Module):
228
+ def __init__(self, config: CLIPSegTextConfig):
229
+ super().__init__()
230
+ embed_dim = config.hidden_size
231
+
232
+ self.token_embedding = nn.Embedding(config.vocab_size, embed_dim)
233
+ self.position_embedding = nn.Embedding(config.max_position_embeddings, embed_dim)
234
+
235
+ # position_ids (1, len position emb) is contiguous in memory and exported when serialized
236
+ self.register_buffer(
237
+ "position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
238
+ )
239
+
240
+ def forward(
241
+ self,
242
+ input_ids: Optional[torch.LongTensor] = None,
243
+ position_ids: Optional[torch.LongTensor] = None,
244
+ inputs_embeds: Optional[torch.FloatTensor] = None,
245
+ ) -> torch.Tensor:
246
+ seq_length = input_ids.shape[-1] if input_ids is not None else inputs_embeds.shape[-2]
247
+ max_position_embedding = self.position_embedding.weight.shape[0]
248
+
249
+ if seq_length > max_position_embedding:
250
+ raise ValueError(
251
+ f"Sequence length must be less than max_position_embeddings (got `sequence length`: "
252
+ f"{seq_length} and max_position_embeddings: {max_position_embedding}"
253
+ )
254
+
255
+ if position_ids is None:
256
+ position_ids = self.position_ids[:, :seq_length]
257
+
258
+ if inputs_embeds is None:
259
+ inputs_embeds = self.token_embedding(input_ids)
260
+
261
+ position_embeddings = self.position_embedding(position_ids)
262
+ embeddings = inputs_embeds + position_embeddings
263
+
264
+ return embeddings
265
+
266
+
267
+ # Copied from transformers.models.clip.modeling_clip.CLIPAttention with CLIP->CLIPSeg
268
+ class CLIPSegAttention(nn.Module):
269
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
270
+
271
+ def __init__(self, config):
272
+ super().__init__()
273
+ self.config = config
274
+ self.embed_dim = config.hidden_size
275
+ self.num_heads = config.num_attention_heads
276
+ self.head_dim = self.embed_dim // self.num_heads
277
+ if self.head_dim * self.num_heads != self.embed_dim:
278
+ raise ValueError(
279
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`:"
280
+ f" {self.num_heads})."
281
+ )
282
+ self.scale = self.head_dim**-0.5
283
+ self.dropout = config.attention_dropout
284
+
285
+ self.k_proj = nn.Linear(self.embed_dim, self.embed_dim)
286
+ self.v_proj = nn.Linear(self.embed_dim, self.embed_dim)
287
+ self.q_proj = nn.Linear(self.embed_dim, self.embed_dim)
288
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim)
289
+
290
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
291
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
292
+
293
+ def forward(
294
+ self,
295
+ hidden_states: torch.Tensor,
296
+ attention_mask: Optional[torch.Tensor] = None,
297
+ causal_attention_mask: Optional[torch.Tensor] = None,
298
+ output_attentions: Optional[bool] = False,
299
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
300
+ """Input shape: Batch x Time x Channel"""
301
+
302
+ bsz, tgt_len, embed_dim = hidden_states.size()
303
+
304
+ # get query proj
305
+ query_states = self.q_proj(hidden_states) * self.scale
306
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
307
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
308
+
309
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
310
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
311
+ key_states = key_states.view(*proj_shape)
312
+ value_states = value_states.view(*proj_shape)
313
+
314
+ src_len = key_states.size(1)
315
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
316
+
317
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
318
+ raise ValueError(
319
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
320
+ f" {attn_weights.size()}"
321
+ )
322
+
323
+ # apply the causal_attention_mask first
324
+ if causal_attention_mask is not None:
325
+ if causal_attention_mask.size() != (bsz, 1, tgt_len, src_len):
326
+ raise ValueError(
327
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is"
328
+ f" {causal_attention_mask.size()}"
329
+ )
330
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + causal_attention_mask
331
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
332
+
333
+ if attention_mask is not None:
334
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
335
+ raise ValueError(
336
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
337
+ )
338
+ attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask
339
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
340
+
341
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1)
342
+
343
+ if output_attentions:
344
+ # this operation is a bit awkward, but it's required to
345
+ # make sure that attn_weights keeps its gradient.
346
+ # In order to do so, attn_weights have to reshaped
347
+ # twice and have to be reused in the following
348
+ attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
349
+ attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len)
350
+ else:
351
+ attn_weights_reshaped = None
352
+
353
+ attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training)
354
+
355
+ attn_output = torch.bmm(attn_probs, value_states)
356
+
357
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
358
+ raise ValueError(
359
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
360
+ f" {attn_output.size()}"
361
+ )
362
+
363
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
364
+ attn_output = attn_output.transpose(1, 2)
365
+ attn_output = attn_output.reshape(bsz, tgt_len, embed_dim)
366
+
367
+ attn_output = self.out_proj(attn_output)
368
+
369
+ return attn_output, attn_weights_reshaped
370
+
371
+
372
+ # Copied from transformers.models.clip.modeling_clip.CLIPMLP with CLIP->CLIPSeg
373
+ class CLIPSegMLP(nn.Module):
374
+ def __init__(self, config):
375
+ super().__init__()
376
+ self.config = config
377
+ self.activation_fn = ACT2FN[config.hidden_act]
378
+ self.fc1 = nn.Linear(config.hidden_size, config.intermediate_size)
379
+ self.fc2 = nn.Linear(config.intermediate_size, config.hidden_size)
380
+
381
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
382
+ hidden_states = self.fc1(hidden_states)
383
+ hidden_states = self.activation_fn(hidden_states)
384
+ hidden_states = self.fc2(hidden_states)
385
+ return hidden_states
386
+
387
+
388
+ # Copied from transformers.models.altclip.modeling_altclip.AltCLIPEncoderLayer with AltCLIP->CLIPSeg
389
+ class CLIPSegEncoderLayer(nn.Module):
390
+ def __init__(self, config: CLIPSegConfig):
391
+ super().__init__()
392
+ self.embed_dim = config.hidden_size
393
+ self.self_attn = CLIPSegAttention(config)
394
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
395
+ self.mlp = CLIPSegMLP(config)
396
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
397
+
398
+ def forward(
399
+ self,
400
+ hidden_states: torch.Tensor,
401
+ attention_mask: torch.Tensor,
402
+ causal_attention_mask: torch.Tensor,
403
+ output_attentions: Optional[bool] = False,
404
+ ) -> Tuple[torch.FloatTensor]:
405
+ """
406
+ Args:
407
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
408
+ attention_mask (`torch.FloatTensor`): attention mask of size
409
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
410
+ `(config.encoder_attention_heads,)`.
411
+ output_attentions (`bool`, *optional*):
412
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
413
+ returned tensors for more detail.
414
+ """
415
+ residual = hidden_states
416
+
417
+ hidden_states = self.layer_norm1(hidden_states)
418
+ hidden_states, attn_weights = self.self_attn(
419
+ hidden_states=hidden_states,
420
+ attention_mask=attention_mask,
421
+ causal_attention_mask=causal_attention_mask,
422
+ output_attentions=output_attentions,
423
+ )
424
+ hidden_states = residual + hidden_states
425
+
426
+ residual = hidden_states
427
+ hidden_states = self.layer_norm2(hidden_states)
428
+ hidden_states = self.mlp(hidden_states)
429
+ hidden_states = residual + hidden_states
430
+
431
+ outputs = (hidden_states,)
432
+
433
+ if output_attentions:
434
+ outputs += (attn_weights,)
435
+
436
+ return outputs
437
+
438
+
439
+ class CLIPSegPreTrainedModel(PreTrainedModel):
440
+ """
441
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
442
+ models.
443
+ """
444
+
445
+ config_class = CLIPSegConfig
446
+ base_model_prefix = "clip"
447
+ supports_gradient_checkpointing = True
448
+
449
+ def _init_weights(self, module):
450
+ """Initialize the weights"""
451
+ factor = self.config.initializer_factor
452
+ if isinstance(module, CLIPSegTextEmbeddings):
453
+ module.token_embedding.weight.data.normal_(mean=0.0, std=factor * 0.02)
454
+ module.position_embedding.weight.data.normal_(mean=0.0, std=factor * 0.02)
455
+ elif isinstance(module, CLIPSegVisionEmbeddings):
456
+ factor = self.config.initializer_factor
457
+ nn.init.normal_(module.class_embedding, mean=0.0, std=module.embed_dim**-0.5 * factor)
458
+ nn.init.normal_(module.patch_embedding.weight, std=module.config.initializer_range * factor)
459
+ nn.init.normal_(module.position_embedding.weight, std=module.config.initializer_range * factor)
460
+ elif isinstance(module, CLIPSegAttention):
461
+ factor = self.config.initializer_factor
462
+ in_proj_std = (module.embed_dim**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
463
+ out_proj_std = (module.embed_dim**-0.5) * factor
464
+ nn.init.normal_(module.q_proj.weight, std=in_proj_std)
465
+ nn.init.normal_(module.k_proj.weight, std=in_proj_std)
466
+ nn.init.normal_(module.v_proj.weight, std=in_proj_std)
467
+ nn.init.normal_(module.out_proj.weight, std=out_proj_std)
468
+ elif isinstance(module, CLIPSegMLP):
469
+ factor = self.config.initializer_factor
470
+ in_proj_std = (module.config.hidden_size**-0.5) * ((2 * module.config.num_hidden_layers) ** -0.5) * factor
471
+ fc_std = (2 * module.config.hidden_size) ** -0.5 * factor
472
+ nn.init.normal_(module.fc1.weight, std=fc_std)
473
+ nn.init.normal_(module.fc2.weight, std=in_proj_std)
474
+ elif isinstance(module, CLIPSegModel):
475
+ nn.init.normal_(
476
+ module.text_projection.weight,
477
+ std=module.text_embed_dim**-0.5 * self.config.initializer_factor,
478
+ )
479
+ nn.init.normal_(
480
+ module.visual_projection.weight,
481
+ std=module.vision_embed_dim**-0.5 * self.config.initializer_factor,
482
+ )
483
+
484
+ if isinstance(module, nn.LayerNorm):
485
+ module.bias.data.zero_()
486
+ module.weight.data.fill_(1.0)
487
+ if isinstance(module, nn.Linear) and module.bias is not None:
488
+ module.bias.data.zero_()
489
+
490
+
491
+ CLIPSEG_START_DOCSTRING = r"""
492
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
493
+ as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
494
+ behavior.
495
+
496
+ Parameters:
497
+ config ([`CLIPSegConfig`]): Model configuration class with all the parameters of the model.
498
+ Initializing with a config file does not load the weights associated with the model, only the
499
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
500
+ """
501
+
502
+ CLIPSEG_TEXT_INPUTS_DOCSTRING = r"""
503
+ Args:
504
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
505
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
506
+ it.
507
+
508
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
509
+ [`PreTrainedTokenizer.__call__`] for details.
510
+
511
+ [What are input IDs?](../glossary#input-ids)
512
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
513
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
514
+
515
+ - 1 for tokens that are **not masked**,
516
+ - 0 for tokens that are **masked**.
517
+
518
+ [What are attention masks?](../glossary#attention-mask)
519
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
520
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
521
+ config.max_position_embeddings - 1]`.
522
+
523
+ [What are position IDs?](../glossary#position-ids)
524
+ output_attentions (`bool`, *optional*):
525
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
526
+ tensors for more detail.
527
+ output_hidden_states (`bool`, *optional*):
528
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
529
+ more detail.
530
+ return_dict (`bool`, *optional*):
531
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
532
+ """
533
+
534
+ CLIPSEG_VISION_INPUTS_DOCSTRING = r"""
535
+ Args:
536
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
537
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
538
+ [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
539
+ output_attentions (`bool`, *optional*):
540
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
541
+ tensors for more detail.
542
+ output_hidden_states (`bool`, *optional*):
543
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
544
+ more detail.
545
+ interpolate_pos_encoding (`bool`, *optional*, defaults to `True`):
546
+ Whether to interpolate the pre-trained position encodings.
547
+ return_dict (`bool`, *optional*):
548
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
549
+ """
550
+
551
+ CLIPSEG_INPUTS_DOCSTRING = r"""
552
+ Args:
553
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
554
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
555
+ it.
556
+
557
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
558
+ [`PreTrainedTokenizer.__call__`] for details.
559
+
560
+ [What are input IDs?](../glossary#input-ids)
561
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
562
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
563
+
564
+ - 1 for tokens that are **not masked**,
565
+ - 0 for tokens that are **masked**.
566
+
567
+ [What are attention masks?](../glossary#attention-mask)
568
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
569
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
570
+ config.max_position_embeddings - 1]`.
571
+
572
+ [What are position IDs?](../glossary#position-ids)
573
+ pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
574
+ Pixel values. Padding will be ignored by default should you provide it. Pixel values can be obtained using
575
+ [`AutoImageProcessor`]. See [`CLIPImageProcessor.__call__`] for details.
576
+ return_loss (`bool`, *optional*):
577
+ Whether or not to return the contrastive loss.
578
+ output_attentions (`bool`, *optional*):
579
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
580
+ tensors for more detail.
581
+ output_hidden_states (`bool`, *optional*):
582
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
583
+ more detail.
584
+ interpolate_pos_encoding (`bool`, *optional*, defaults to `True`):
585
+ Whether to interpolate the pre-trained position encodings.
586
+ return_dict (`bool`, *optional*):
587
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
588
+ """
589
+
590
+
591
+ # Copied from transformers.models.altclip.modeling_altclip.AltCLIPEncoder with AltCLIP->CLIPSeg
592
+ class CLIPSegEncoder(nn.Module):
593
+ """
594
+ Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a
595
+ [`CLIPSegEncoderLayer`].
596
+
597
+ Args:
598
+ config: CLIPSegConfig
599
+ """
600
+
601
+ def __init__(self, config: CLIPSegConfig):
602
+ super().__init__()
603
+ self.config = config
604
+ self.layers = nn.ModuleList([CLIPSegEncoderLayer(config) for _ in range(config.num_hidden_layers)])
605
+ self.gradient_checkpointing = False
606
+
607
+ def forward(
608
+ self,
609
+ inputs_embeds,
610
+ attention_mask: Optional[torch.Tensor] = None,
611
+ causal_attention_mask: Optional[torch.Tensor] = None,
612
+ output_attentions: Optional[bool] = None,
613
+ output_hidden_states: Optional[bool] = None,
614
+ return_dict: Optional[bool] = None,
615
+ ) -> Union[Tuple, BaseModelOutput]:
616
+ r"""
617
+ Args:
618
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`):
619
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
620
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
621
+ than the model's internal embedding lookup matrix.
622
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
623
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
624
+
625
+ - 1 for tokens that are **not masked**,
626
+ - 0 for tokens that are **masked**.
627
+
628
+ [What are attention masks?](../glossary#attention-mask)
629
+ causal_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
630
+ Causal mask for the text model. Mask values selected in `[0, 1]`:
631
+
632
+ - 1 for tokens that are **not masked**,
633
+ - 0 for tokens that are **masked**.
634
+
635
+ [What are attention masks?](../glossary#attention-mask)
636
+ output_attentions (`bool`, *optional*):
637
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
638
+ returned tensors for more detail.
639
+ output_hidden_states (`bool`, *optional*):
640
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
641
+ for more detail.
642
+ return_dict (`bool`, *optional*):
643
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
644
+ """
645
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
646
+ output_hidden_states = (
647
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
648
+ )
649
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
650
+
651
+ encoder_states = () if output_hidden_states else None
652
+ all_attentions = () if output_attentions else None
653
+
654
+ hidden_states = inputs_embeds
655
+ for idx, encoder_layer in enumerate(self.layers):
656
+ if output_hidden_states:
657
+ encoder_states = encoder_states + (hidden_states,)
658
+ if self.gradient_checkpointing and self.training:
659
+ layer_outputs = self._gradient_checkpointing_func(
660
+ encoder_layer.__call__,
661
+ hidden_states,
662
+ attention_mask,
663
+ causal_attention_mask,
664
+ output_attentions,
665
+ )
666
+ else:
667
+ layer_outputs = encoder_layer(
668
+ hidden_states,
669
+ attention_mask,
670
+ causal_attention_mask,
671
+ output_attentions=output_attentions,
672
+ )
673
+
674
+ hidden_states = layer_outputs[0]
675
+
676
+ if output_attentions:
677
+ all_attentions = all_attentions + (layer_outputs[1],)
678
+
679
+ if output_hidden_states:
680
+ encoder_states = encoder_states + (hidden_states,)
681
+
682
+ if not return_dict:
683
+ return tuple(v for v in [hidden_states, encoder_states, all_attentions] if v is not None)
684
+ return BaseModelOutput(
685
+ last_hidden_state=hidden_states, hidden_states=encoder_states, attentions=all_attentions
686
+ )
687
+
688
+
689
+ class CLIPSegTextTransformer(nn.Module):
690
+ def __init__(self, config: CLIPSegTextConfig):
691
+ super().__init__()
692
+ self.config = config
693
+ embed_dim = config.hidden_size
694
+ self.embeddings = CLIPSegTextEmbeddings(config)
695
+ self.encoder = CLIPSegEncoder(config)
696
+ self.final_layer_norm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
697
+
698
+ # For `pooled_output` computation
699
+ self.eos_token_id = config.eos_token_id
700
+
701
+ @add_start_docstrings_to_model_forward(CLIPSEG_TEXT_INPUTS_DOCSTRING)
702
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPSegTextConfig)
703
+ # Adapted from transformers.models.clip.modeling_clip.CLIPTextTransformer.forward with clip->clipseg, CLIP->CLIPSeg
704
+ def forward(
705
+ self,
706
+ input_ids: Optional[torch.Tensor] = None,
707
+ attention_mask: Optional[torch.Tensor] = None,
708
+ position_ids: Optional[torch.Tensor] = None,
709
+ output_attentions: Optional[bool] = None,
710
+ output_hidden_states: Optional[bool] = None,
711
+ return_dict: Optional[bool] = None,
712
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
713
+ r"""
714
+ Returns:
715
+
716
+ """
717
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
718
+ output_hidden_states = (
719
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
720
+ )
721
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
722
+
723
+ if input_ids is None:
724
+ raise ValueError("You have to specify input_ids")
725
+
726
+ input_shape = input_ids.size()
727
+ input_ids = input_ids.view(-1, input_shape[-1])
728
+
729
+ hidden_states = self.embeddings(input_ids=input_ids, position_ids=position_ids)
730
+
731
+ # CLIPSeg's text model uses causal mask, prepare it here.
732
+ # https://github.com/openai/CLIPSeg/blob/cfcffb90e69f37bf2ff1e988237a0fbe41f33c04/clipseg/model.py#L324
733
+ causal_attention_mask = _create_4d_causal_attention_mask(
734
+ input_shape, hidden_states.dtype, device=hidden_states.device
735
+ )
736
+ # expand attention_mask
737
+ if attention_mask is not None:
738
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
739
+ attention_mask = _prepare_4d_attention_mask(attention_mask, hidden_states.dtype)
740
+
741
+ encoder_outputs = self.encoder(
742
+ inputs_embeds=hidden_states,
743
+ attention_mask=attention_mask,
744
+ causal_attention_mask=causal_attention_mask,
745
+ output_attentions=output_attentions,
746
+ output_hidden_states=output_hidden_states,
747
+ return_dict=return_dict,
748
+ )
749
+
750
+ last_hidden_state = encoder_outputs[0]
751
+ last_hidden_state = self.final_layer_norm(last_hidden_state)
752
+
753
+ if self.eos_token_id == 2:
754
+ # The `eos_token_id` was incorrect before PR #24773: Let's keep what have been done here.
755
+ # A CLIPSeg model with such `eos_token_id` in the config can't work correctly with extra new tokens added
756
+ # ------------------------------------------------------------
757
+ # text_embeds.shape = [batch_size, sequence_length, transformer.width]
758
+ # take features from the eot embedding (eot_token is the highest number in each sequence)
759
+ # casting to torch.int for onnx compatibility: argmax doesn't support int64 inputs with opset 14
760
+ pooled_output = last_hidden_state[
761
+ torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device),
762
+ input_ids.to(dtype=torch.int, device=last_hidden_state.device).argmax(dim=-1),
763
+ ]
764
+ else:
765
+ # The config gets updated `eos_token_id` from PR #24773 (so the use of exta new tokens is possible)
766
+ pooled_output = last_hidden_state[
767
+ torch.arange(last_hidden_state.shape[0], device=last_hidden_state.device),
768
+ # We need to get the first position of `eos_token_id` value (`pad_token_ids` might equal to `eos_token_id`)
769
+ # Note: we assume each sequence (along batch dim.) contains an `eos_token_id` (e.g. prepared by the tokenizer)
770
+ (input_ids.to(dtype=torch.int, device=last_hidden_state.device) == self.eos_token_id)
771
+ .int()
772
+ .argmax(dim=-1),
773
+ ]
774
+
775
+ if not return_dict:
776
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
777
+
778
+ return BaseModelOutputWithPooling(
779
+ last_hidden_state=last_hidden_state,
780
+ pooler_output=pooled_output,
781
+ hidden_states=encoder_outputs.hidden_states,
782
+ attentions=encoder_outputs.attentions,
783
+ )
784
+
785
+
786
+ class CLIPSegTextModel(CLIPSegPreTrainedModel):
787
+ config_class = CLIPSegTextConfig
788
+
789
+ _no_split_modules = ["CLIPSegTextEmbeddings", "CLIPSegEncoderLayer"]
790
+
791
+ def __init__(self, config: CLIPSegTextConfig):
792
+ super().__init__(config)
793
+ self.text_model = CLIPSegTextTransformer(config)
794
+ # Initialize weights and apply final processing
795
+ self.post_init()
796
+
797
+ def get_input_embeddings(self) -> nn.Module:
798
+ return self.text_model.embeddings.token_embedding
799
+
800
+ def set_input_embeddings(self, value):
801
+ self.text_model.embeddings.token_embedding = value
802
+
803
+ @add_start_docstrings_to_model_forward(CLIPSEG_TEXT_INPUTS_DOCSTRING)
804
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPSegTextConfig)
805
+ def forward(
806
+ self,
807
+ input_ids: Optional[torch.Tensor] = None,
808
+ attention_mask: Optional[torch.Tensor] = None,
809
+ position_ids: Optional[torch.Tensor] = None,
810
+ output_attentions: Optional[bool] = None,
811
+ output_hidden_states: Optional[bool] = None,
812
+ return_dict: Optional[bool] = None,
813
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
814
+ r"""
815
+ Returns:
816
+
817
+ Examples:
818
+
819
+ ```python
820
+ >>> from transformers import AutoTokenizer, CLIPSegTextModel
821
+
822
+ >>> tokenizer = AutoTokenizer.from_pretrained("CIDAS/clipseg-rd64-refined")
823
+ >>> model = CLIPSegTextModel.from_pretrained("CIDAS/clipseg-rd64-refined")
824
+
825
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
826
+
827
+ >>> outputs = model(**inputs)
828
+ >>> last_hidden_state = outputs.last_hidden_state
829
+ >>> pooled_output = outputs.pooler_output # pooled (EOS token) states
830
+ ```"""
831
+ return self.text_model(
832
+ input_ids=input_ids,
833
+ attention_mask=attention_mask,
834
+ position_ids=position_ids,
835
+ output_attentions=output_attentions,
836
+ output_hidden_states=output_hidden_states,
837
+ return_dict=return_dict,
838
+ )
839
+
840
+
841
+ class CLIPSegVisionTransformer(nn.Module):
842
+ # Copied from transformers.models.altclip.modeling_altclip.AltCLIPVisionTransformer.__init__ with AltCLIP->CLIPSeg
843
+ def __init__(self, config: CLIPSegVisionConfig):
844
+ super().__init__()
845
+ self.config = config
846
+ embed_dim = config.hidden_size
847
+
848
+ self.embeddings = CLIPSegVisionEmbeddings(config)
849
+ self.pre_layrnorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
850
+ self.encoder = CLIPSegEncoder(config)
851
+ self.post_layernorm = nn.LayerNorm(embed_dim, eps=config.layer_norm_eps)
852
+
853
+ @add_start_docstrings_to_model_forward(CLIPSEG_VISION_INPUTS_DOCSTRING)
854
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPSegVisionConfig)
855
+ def forward(
856
+ self,
857
+ pixel_values: Optional[torch.FloatTensor],
858
+ output_attentions: Optional[bool] = None,
859
+ output_hidden_states: Optional[bool] = None,
860
+ return_dict: Optional[bool] = None,
861
+ interpolate_pos_encoding: Optional[bool] = True,
862
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
863
+ r"""
864
+ Returns:
865
+
866
+ """
867
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
868
+ output_hidden_states = (
869
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
870
+ )
871
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
872
+
873
+ hidden_states = self.embeddings(pixel_values, interpolate_pos_encoding=interpolate_pos_encoding)
874
+ hidden_states = self.pre_layrnorm(hidden_states)
875
+
876
+ encoder_outputs = self.encoder(
877
+ inputs_embeds=hidden_states,
878
+ output_attentions=output_attentions,
879
+ output_hidden_states=output_hidden_states,
880
+ return_dict=return_dict,
881
+ )
882
+
883
+ last_hidden_state = encoder_outputs[0]
884
+ pooled_output = last_hidden_state[:, 0, :]
885
+ pooled_output = self.post_layernorm(pooled_output)
886
+
887
+ if not return_dict:
888
+ return (last_hidden_state, pooled_output) + encoder_outputs[1:]
889
+
890
+ return BaseModelOutputWithPooling(
891
+ last_hidden_state=last_hidden_state,
892
+ pooler_output=pooled_output,
893
+ hidden_states=encoder_outputs.hidden_states,
894
+ attentions=encoder_outputs.attentions,
895
+ )
896
+
897
+
898
+ class CLIPSegVisionModel(CLIPSegPreTrainedModel):
899
+ config_class = CLIPSegVisionConfig
900
+ main_input_name = "pixel_values"
901
+
902
+ def __init__(self, config: CLIPSegVisionConfig):
903
+ super().__init__(config)
904
+ self.vision_model = CLIPSegVisionTransformer(config)
905
+ # Initialize weights and apply final processing
906
+ self.post_init()
907
+
908
+ def get_input_embeddings(self) -> nn.Module:
909
+ return self.vision_model.embeddings.patch_embedding
910
+
911
+ @add_start_docstrings_to_model_forward(CLIPSEG_VISION_INPUTS_DOCSTRING)
912
+ @replace_return_docstrings(output_type=BaseModelOutputWithPooling, config_class=CLIPSegVisionConfig)
913
+ def forward(
914
+ self,
915
+ pixel_values: Optional[torch.FloatTensor] = None,
916
+ output_attentions: Optional[bool] = None,
917
+ output_hidden_states: Optional[bool] = None,
918
+ interpolate_pos_encoding: Optional[bool] = True,
919
+ return_dict: Optional[bool] = None,
920
+ ) -> Union[Tuple, BaseModelOutputWithPooling]:
921
+ r"""
922
+ Returns:
923
+
924
+ Examples:
925
+
926
+ ```python
927
+ >>> from PIL import Image
928
+ >>> import requests
929
+ >>> from transformers import AutoProcessor, CLIPSegVisionModel
930
+
931
+ >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
932
+ >>> model = CLIPSegVisionModel.from_pretrained("CIDAS/clipseg-rd64-refined")
933
+
934
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
935
+ >>> image = Image.open(requests.get(url, stream=True).raw)
936
+
937
+ >>> inputs = processor(images=image, return_tensors="pt")
938
+
939
+ >>> outputs = model(**inputs)
940
+ >>> last_hidden_state = outputs.last_hidden_state
941
+ >>> pooled_output = outputs.pooler_output # pooled CLS states
942
+ ```"""
943
+ return self.vision_model(
944
+ pixel_values=pixel_values,
945
+ output_attentions=output_attentions,
946
+ output_hidden_states=output_hidden_states,
947
+ interpolate_pos_encoding=interpolate_pos_encoding,
948
+ return_dict=return_dict,
949
+ )
950
+
951
+
952
+ @add_start_docstrings(CLIPSEG_START_DOCSTRING)
953
+ class CLIPSegModel(CLIPSegPreTrainedModel):
954
+ config_class = CLIPSegConfig
955
+
956
+ def __init__(self, config: CLIPSegConfig):
957
+ super().__init__(config)
958
+
959
+ if not isinstance(config.text_config, CLIPSegTextConfig):
960
+ raise TypeError(
961
+ "config.text_config is expected to be of type CLIPSegTextConfig but is of type"
962
+ f" {type(config.text_config)}."
963
+ )
964
+
965
+ if not isinstance(config.vision_config, CLIPSegVisionConfig):
966
+ raise TypeError(
967
+ "config.vision_config is expected to be of type CLIPSegVisionConfig but is of type"
968
+ f" {type(config.vision_config)}."
969
+ )
970
+
971
+ text_config = config.text_config
972
+ vision_config = config.vision_config
973
+
974
+ self.projection_dim = config.projection_dim
975
+ self.text_embed_dim = text_config.hidden_size
976
+ self.vision_embed_dim = vision_config.hidden_size
977
+
978
+ self.text_model = CLIPSegTextTransformer(text_config)
979
+ self.vision_model = CLIPSegVisionTransformer(vision_config)
980
+
981
+ self.visual_projection = nn.Linear(self.vision_embed_dim, self.projection_dim, bias=False)
982
+ self.text_projection = nn.Linear(self.text_embed_dim, self.projection_dim, bias=False)
983
+ self.logit_scale = nn.Parameter(torch.tensor(self.config.logit_scale_init_value))
984
+
985
+ # Initialize weights and apply final processing
986
+ self.post_init()
987
+
988
+ @add_start_docstrings_to_model_forward(CLIPSEG_TEXT_INPUTS_DOCSTRING)
989
+ def get_text_features(
990
+ self,
991
+ input_ids: Optional[torch.Tensor] = None,
992
+ attention_mask: Optional[torch.Tensor] = None,
993
+ position_ids: Optional[torch.Tensor] = None,
994
+ output_attentions: Optional[bool] = None,
995
+ output_hidden_states: Optional[bool] = None,
996
+ return_dict: Optional[bool] = None,
997
+ ) -> torch.FloatTensor:
998
+ r"""
999
+ Returns:
1000
+ text_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The text embeddings obtained by
1001
+ applying the projection layer to the pooled output of [`CLIPSegTextModel`].
1002
+
1003
+ Examples:
1004
+
1005
+ ```python
1006
+ >>> from transformers import AutoTokenizer, CLIPSegModel
1007
+
1008
+ >>> tokenizer = AutoTokenizer.from_pretrained("CIDAS/clipseg-rd64-refined")
1009
+ >>> model = CLIPSegModel.from_pretrained("CIDAS/clipseg-rd64-refined")
1010
+
1011
+ >>> inputs = tokenizer(["a photo of a cat", "a photo of a dog"], padding=True, return_tensors="pt")
1012
+ >>> text_features = model.get_text_features(**inputs)
1013
+ ```"""
1014
+ # Use CLIPSEG model's config for some fields (if specified) instead of those of vision & text components.
1015
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1016
+ output_hidden_states = (
1017
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1018
+ )
1019
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1020
+
1021
+ text_outputs = self.text_model(
1022
+ input_ids=input_ids,
1023
+ attention_mask=attention_mask,
1024
+ position_ids=position_ids,
1025
+ output_attentions=output_attentions,
1026
+ output_hidden_states=output_hidden_states,
1027
+ return_dict=return_dict,
1028
+ )
1029
+
1030
+ pooled_output = text_outputs[1]
1031
+ text_features = self.text_projection(pooled_output)
1032
+
1033
+ return text_features
1034
+
1035
+ @add_start_docstrings_to_model_forward(CLIPSEG_VISION_INPUTS_DOCSTRING)
1036
+ def get_image_features(
1037
+ self,
1038
+ pixel_values: Optional[torch.FloatTensor] = None,
1039
+ output_attentions: Optional[bool] = None,
1040
+ output_hidden_states: Optional[bool] = None,
1041
+ interpolate_pos_encoding: bool = True,
1042
+ return_dict: Optional[bool] = None,
1043
+ ) -> torch.FloatTensor:
1044
+ r"""
1045
+ Returns:
1046
+ image_features (`torch.FloatTensor` of shape `(batch_size, output_dim`): The image embeddings obtained by
1047
+ applying the projection layer to the pooled output of [`CLIPSegVisionModel`].
1048
+
1049
+ Examples:
1050
+
1051
+ ```python
1052
+ >>> from PIL import Image
1053
+ >>> import requests
1054
+ >>> from transformers import AutoProcessor, CLIPSegModel
1055
+
1056
+ >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
1057
+ >>> model = CLIPSegModel.from_pretrained("CIDAS/clipseg-rd64-refined")
1058
+
1059
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1060
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1061
+
1062
+ >>> inputs = processor(images=image, return_tensors="pt")
1063
+
1064
+ >>> image_features = model.get_image_features(**inputs)
1065
+ ```"""
1066
+ # Use CLIPSEG model's config for some fields (if specified) instead of those of vision & text components.
1067
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1068
+ output_hidden_states = (
1069
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1070
+ )
1071
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1072
+
1073
+ vision_outputs = self.vision_model(
1074
+ pixel_values=pixel_values,
1075
+ output_attentions=output_attentions,
1076
+ output_hidden_states=output_hidden_states,
1077
+ interpolate_pos_encoding=interpolate_pos_encoding,
1078
+ return_dict=return_dict,
1079
+ )
1080
+
1081
+ pooled_output = vision_outputs[1] # pooled_output
1082
+ image_features = self.visual_projection(pooled_output)
1083
+
1084
+ return image_features
1085
+
1086
+ @add_start_docstrings_to_model_forward(CLIPSEG_INPUTS_DOCSTRING)
1087
+ @replace_return_docstrings(output_type=CLIPSegOutput, config_class=CLIPSegConfig)
1088
+ def forward(
1089
+ self,
1090
+ input_ids: Optional[torch.LongTensor] = None,
1091
+ pixel_values: Optional[torch.FloatTensor] = None,
1092
+ attention_mask: Optional[torch.Tensor] = None,
1093
+ position_ids: Optional[torch.LongTensor] = None,
1094
+ return_loss: Optional[bool] = None,
1095
+ output_attentions: Optional[bool] = None,
1096
+ output_hidden_states: Optional[bool] = None,
1097
+ interpolate_pos_encoding: bool = True,
1098
+ return_dict: Optional[bool] = None,
1099
+ ) -> Union[Tuple, CLIPSegOutput]:
1100
+ r"""
1101
+ Returns:
1102
+
1103
+ Examples:
1104
+
1105
+ ```python
1106
+ >>> from PIL import Image
1107
+ >>> import requests
1108
+ >>> from transformers import AutoProcessor, CLIPSegModel
1109
+
1110
+ >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
1111
+ >>> model = CLIPSegModel.from_pretrained("CIDAS/clipseg-rd64-refined")
1112
+
1113
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1114
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1115
+
1116
+ >>> inputs = processor(
1117
+ ... text=["a photo of a cat", "a photo of a dog"], images=image, return_tensors="pt", padding=True
1118
+ ... )
1119
+
1120
+ >>> outputs = model(**inputs)
1121
+ >>> logits_per_image = outputs.logits_per_image # this is the image-text similarity score
1122
+ >>> probs = logits_per_image.softmax(dim=1) # we can take the softmax to get the label probabilities
1123
+ ```"""
1124
+ # Use CLIPSEG model's config for some fields (if specified) instead of those of vision & text components.
1125
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1126
+ output_hidden_states = (
1127
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1128
+ )
1129
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1130
+
1131
+ vision_outputs = self.vision_model(
1132
+ pixel_values=pixel_values,
1133
+ output_attentions=output_attentions,
1134
+ output_hidden_states=output_hidden_states,
1135
+ interpolate_pos_encoding=interpolate_pos_encoding,
1136
+ return_dict=return_dict,
1137
+ )
1138
+
1139
+ text_outputs = self.text_model(
1140
+ input_ids=input_ids,
1141
+ attention_mask=attention_mask,
1142
+ position_ids=position_ids,
1143
+ output_attentions=output_attentions,
1144
+ output_hidden_states=output_hidden_states,
1145
+ return_dict=return_dict,
1146
+ )
1147
+
1148
+ image_embeds = vision_outputs[1]
1149
+ image_embeds = self.visual_projection(image_embeds)
1150
+
1151
+ text_embeds = text_outputs[1]
1152
+ text_embeds = self.text_projection(text_embeds)
1153
+
1154
+ # normalized features
1155
+ image_embeds = image_embeds / image_embeds.norm(p=2, dim=-1, keepdim=True)
1156
+ text_embeds = text_embeds / text_embeds.norm(p=2, dim=-1, keepdim=True)
1157
+
1158
+ # cosine similarity as logits
1159
+ logit_scale = self.logit_scale.exp()
1160
+ logits_per_text = torch.matmul(text_embeds, image_embeds.t()) * logit_scale
1161
+ logits_per_image = logits_per_text.t()
1162
+
1163
+ loss = None
1164
+ if return_loss:
1165
+ loss = clipseg_loss(logits_per_text)
1166
+
1167
+ if not return_dict:
1168
+ output = (logits_per_image, logits_per_text, text_embeds, image_embeds, text_outputs, vision_outputs)
1169
+ return ((loss,) + output) if loss is not None else output
1170
+
1171
+ return CLIPSegOutput(
1172
+ loss=loss,
1173
+ logits_per_image=logits_per_image,
1174
+ logits_per_text=logits_per_text,
1175
+ text_embeds=text_embeds,
1176
+ image_embeds=image_embeds,
1177
+ text_model_output=text_outputs,
1178
+ vision_model_output=vision_outputs,
1179
+ )
1180
+
1181
+
1182
+ class CLIPSegDecoderLayer(nn.Module):
1183
+ """
1184
+ CLIPSeg decoder layer, which is identical to `CLIPSegEncoderLayer`, except that normalization is applied after
1185
+ self-attention/MLP, rather than before.
1186
+ """
1187
+
1188
+ # Copied from transformers.models.altclip.modeling_altclip.AltCLIPEncoderLayer.__init__ with AltCLIP->CLIPSeg
1189
+ def __init__(self, config: CLIPSegConfig):
1190
+ super().__init__()
1191
+ self.embed_dim = config.hidden_size
1192
+ self.self_attn = CLIPSegAttention(config)
1193
+ self.layer_norm1 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
1194
+ self.mlp = CLIPSegMLP(config)
1195
+ self.layer_norm2 = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_eps)
1196
+
1197
+ def forward(
1198
+ self,
1199
+ hidden_states: torch.Tensor,
1200
+ attention_mask: torch.Tensor,
1201
+ causal_attention_mask: torch.Tensor,
1202
+ output_attentions: Optional[bool] = False,
1203
+ ) -> Tuple[torch.FloatTensor]:
1204
+ """
1205
+ Args:
1206
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
1207
+ attention_mask (`torch.FloatTensor`): attention mask of size
1208
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
1209
+ `(config.encoder_attention_heads,)`.
1210
+ output_attentions (`bool`, *optional*):
1211
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1212
+ returned tensors for more detail.
1213
+ """
1214
+ residual = hidden_states
1215
+
1216
+ hidden_states, attn_weights = self.self_attn(
1217
+ hidden_states=hidden_states,
1218
+ attention_mask=attention_mask,
1219
+ causal_attention_mask=causal_attention_mask,
1220
+ output_attentions=output_attentions,
1221
+ )
1222
+
1223
+ hidden_states = residual + hidden_states
1224
+ hidden_states = self.layer_norm1(hidden_states)
1225
+
1226
+ residual = hidden_states
1227
+ hidden_states = self.mlp(hidden_states)
1228
+ hidden_states = residual + hidden_states
1229
+ hidden_states = self.layer_norm2(hidden_states)
1230
+
1231
+ outputs = (hidden_states,)
1232
+
1233
+ if output_attentions:
1234
+ outputs += (attn_weights,)
1235
+
1236
+ return outputs
1237
+
1238
+
1239
+ class CLIPSegDecoder(CLIPSegPreTrainedModel):
1240
+ def __init__(self, config: CLIPSegConfig):
1241
+ super().__init__(config)
1242
+
1243
+ self.conditional_layer = config.conditional_layer
1244
+
1245
+ self.film_mul = nn.Linear(config.projection_dim, config.reduce_dim)
1246
+ self.film_add = nn.Linear(config.projection_dim, config.reduce_dim)
1247
+
1248
+ if config.use_complex_transposed_convolution:
1249
+ transposed_kernels = (config.vision_config.patch_size // 4, config.vision_config.patch_size // 4)
1250
+
1251
+ self.transposed_convolution = nn.Sequential(
1252
+ nn.Conv2d(config.reduce_dim, config.reduce_dim, kernel_size=3, padding=1),
1253
+ nn.ReLU(),
1254
+ nn.ConvTranspose2d(
1255
+ config.reduce_dim,
1256
+ config.reduce_dim // 2,
1257
+ kernel_size=transposed_kernels[0],
1258
+ stride=transposed_kernels[0],
1259
+ ),
1260
+ nn.ReLU(),
1261
+ nn.ConvTranspose2d(
1262
+ config.reduce_dim // 2, 1, kernel_size=transposed_kernels[1], stride=transposed_kernels[1]
1263
+ ),
1264
+ )
1265
+ else:
1266
+ self.transposed_convolution = nn.ConvTranspose2d(
1267
+ config.reduce_dim, 1, config.vision_config.patch_size, stride=config.vision_config.patch_size
1268
+ )
1269
+
1270
+ depth = len(config.extract_layers)
1271
+ self.reduces = nn.ModuleList(
1272
+ [nn.Linear(config.vision_config.hidden_size, config.reduce_dim) for _ in range(depth)]
1273
+ )
1274
+
1275
+ decoder_config = copy.deepcopy(config.vision_config)
1276
+ decoder_config.hidden_size = config.reduce_dim
1277
+ decoder_config.num_attention_heads = config.decoder_num_attention_heads
1278
+ decoder_config.intermediate_size = config.decoder_intermediate_size
1279
+ decoder_config.hidden_act = "relu"
1280
+ self.layers = nn.ModuleList([CLIPSegDecoderLayer(decoder_config) for _ in range(len(config.extract_layers))])
1281
+
1282
+ def forward(
1283
+ self,
1284
+ hidden_states: Tuple[torch.Tensor],
1285
+ conditional_embeddings: torch.Tensor,
1286
+ output_attentions: Optional[bool] = None,
1287
+ output_hidden_states: Optional[bool] = None,
1288
+ return_dict: Optional[bool] = True,
1289
+ ):
1290
+ all_hidden_states = () if output_hidden_states else None
1291
+ all_attentions = () if output_attentions else None
1292
+
1293
+ activations = hidden_states[::-1]
1294
+
1295
+ output = None
1296
+ for i, (activation, layer, reduce) in enumerate(zip(activations, self.layers, self.reduces)):
1297
+ if output is not None:
1298
+ output = reduce(activation) + output
1299
+ else:
1300
+ output = reduce(activation)
1301
+
1302
+ if i == self.conditional_layer:
1303
+ output = self.film_mul(conditional_embeddings) * output.permute(1, 0, 2) + self.film_add(
1304
+ conditional_embeddings
1305
+ )
1306
+ output = output.permute(1, 0, 2)
1307
+
1308
+ layer_outputs = layer(
1309
+ output, attention_mask=None, causal_attention_mask=None, output_attentions=output_attentions
1310
+ )
1311
+
1312
+ output = layer_outputs[0]
1313
+
1314
+ if output_hidden_states:
1315
+ all_hidden_states += (output,)
1316
+
1317
+ if output_attentions:
1318
+ all_attentions += (layer_outputs[1],)
1319
+
1320
+ output = output[:, 1:, :].permute(0, 2, 1) # remove cls token and reshape to [batch_size, reduce_dim, seq_len]
1321
+
1322
+ size = int(math.sqrt(output.shape[2]))
1323
+
1324
+ batch_size = conditional_embeddings.shape[0]
1325
+ output = output.view(batch_size, output.shape[1], size, size)
1326
+
1327
+ logits = self.transposed_convolution(output).squeeze(1)
1328
+
1329
+ if not return_dict:
1330
+ return tuple(v for v in [logits, all_hidden_states, all_attentions] if v is not None)
1331
+
1332
+ return CLIPSegDecoderOutput(
1333
+ logits=logits,
1334
+ hidden_states=all_hidden_states,
1335
+ attentions=all_attentions,
1336
+ )
1337
+
1338
+
1339
+ @add_start_docstrings(
1340
+ """
1341
+ CLIPSeg model with a Transformer-based decoder on top for zero-shot and one-shot image segmentation.
1342
+ """,
1343
+ CLIPSEG_START_DOCSTRING,
1344
+ )
1345
+ class CLIPSegForImageSegmentation(CLIPSegPreTrainedModel):
1346
+ config_class = CLIPSegConfig
1347
+
1348
+ def __init__(self, config: CLIPSegConfig):
1349
+ super().__init__(config)
1350
+
1351
+ self.config = config
1352
+
1353
+ self.clip = CLIPSegModel(config)
1354
+ self.extract_layers = config.extract_layers
1355
+
1356
+ self.decoder = CLIPSegDecoder(config)
1357
+
1358
+ # Initialize weights and apply final processing
1359
+ self.post_init()
1360
+
1361
+ def get_conditional_embeddings(
1362
+ self,
1363
+ batch_size: Optional[int] = None,
1364
+ input_ids: Optional[torch.Tensor] = None,
1365
+ attention_mask: Optional[torch.Tensor] = None,
1366
+ position_ids: Optional[torch.Tensor] = None,
1367
+ conditional_pixel_values: Optional[torch.Tensor] = None,
1368
+ ):
1369
+ if input_ids is not None:
1370
+ # compute conditional embeddings from texts
1371
+ if len(input_ids) != batch_size:
1372
+ raise ValueError("Make sure to pass as many prompt texts as there are query images")
1373
+ with torch.no_grad():
1374
+ conditional_embeddings = self.clip.get_text_features(
1375
+ input_ids, attention_mask=attention_mask, position_ids=position_ids
1376
+ )
1377
+ elif conditional_pixel_values is not None:
1378
+ # compute conditional embeddings from images
1379
+ if len(conditional_pixel_values) != batch_size:
1380
+ raise ValueError("Make sure to pass as many prompt images as there are query images")
1381
+ with torch.no_grad():
1382
+ conditional_embeddings = self.clip.get_image_features(conditional_pixel_values)
1383
+ else:
1384
+ raise ValueError(
1385
+ "Invalid conditional, should be either provided as `input_ids` or `conditional_pixel_values`"
1386
+ )
1387
+
1388
+ return conditional_embeddings
1389
+
1390
+ @add_start_docstrings_to_model_forward(CLIPSEG_INPUTS_DOCSTRING)
1391
+ @replace_return_docstrings(output_type=CLIPSegImageSegmentationOutput, config_class=CLIPSegTextConfig)
1392
+ def forward(
1393
+ self,
1394
+ input_ids: Optional[torch.FloatTensor] = None,
1395
+ pixel_values: Optional[torch.FloatTensor] = None,
1396
+ conditional_pixel_values: Optional[torch.FloatTensor] = None,
1397
+ conditional_embeddings: Optional[torch.FloatTensor] = None,
1398
+ attention_mask: Optional[torch.Tensor] = None,
1399
+ position_ids: Optional[torch.LongTensor] = None,
1400
+ labels: Optional[torch.LongTensor] = None,
1401
+ output_attentions: Optional[bool] = None,
1402
+ output_hidden_states: Optional[bool] = None,
1403
+ interpolate_pos_encoding: bool = True,
1404
+ return_dict: Optional[bool] = None,
1405
+ ) -> Union[Tuple, CLIPSegOutput]:
1406
+ r"""
1407
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1408
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1409
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1410
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1411
+
1412
+ Returns:
1413
+
1414
+ Examples:
1415
+
1416
+ ```python
1417
+ >>> from transformers import AutoProcessor, CLIPSegForImageSegmentation
1418
+ >>> from PIL import Image
1419
+ >>> import requests
1420
+
1421
+ >>> processor = AutoProcessor.from_pretrained("CIDAS/clipseg-rd64-refined")
1422
+ >>> model = CLIPSegForImageSegmentation.from_pretrained("CIDAS/clipseg-rd64-refined")
1423
+
1424
+ >>> url = "http://images.cocodataset.org/val2017/000000039769.jpg"
1425
+ >>> image = Image.open(requests.get(url, stream=True).raw)
1426
+ >>> texts = ["a cat", "a remote", "a blanket"]
1427
+ >>> inputs = processor(text=texts, images=[image] * len(texts), padding=True, return_tensors="pt")
1428
+
1429
+ >>> outputs = model(**inputs)
1430
+
1431
+ >>> logits = outputs.logits
1432
+ >>> print(logits.shape)
1433
+ torch.Size([3, 352, 352])
1434
+ ```"""
1435
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1436
+
1437
+ # step 1: forward the query images through the frozen CLIP vision encoder
1438
+ with torch.no_grad():
1439
+ vision_outputs = self.clip.vision_model(
1440
+ pixel_values=pixel_values,
1441
+ output_attentions=output_attentions,
1442
+ output_hidden_states=True, # we need the intermediate hidden states
1443
+ interpolate_pos_encoding=interpolate_pos_encoding,
1444
+ return_dict=return_dict,
1445
+ )
1446
+ pooled_output = self.clip.visual_projection(vision_outputs[1])
1447
+
1448
+ hidden_states = vision_outputs.hidden_states if return_dict else vision_outputs[2]
1449
+ # we add +1 here as the hidden states also include the initial embeddings
1450
+ activations = [hidden_states[i + 1] for i in self.extract_layers]
1451
+
1452
+ # update vision_outputs
1453
+ if return_dict:
1454
+ vision_outputs = BaseModelOutputWithPooling(
1455
+ last_hidden_state=vision_outputs.last_hidden_state,
1456
+ pooler_output=vision_outputs.pooler_output,
1457
+ hidden_states=vision_outputs.hidden_states if output_hidden_states else None,
1458
+ attentions=vision_outputs.attentions,
1459
+ )
1460
+ else:
1461
+ vision_outputs = (
1462
+ vision_outputs[:2] + vision_outputs[3:] if not output_hidden_states else vision_outputs
1463
+ )
1464
+
1465
+ # step 2: compute conditional embeddings, either from text, images or an own provided embedding
1466
+ if conditional_embeddings is None:
1467
+ conditional_embeddings = self.get_conditional_embeddings(
1468
+ batch_size=pixel_values.shape[0],
1469
+ input_ids=input_ids,
1470
+ attention_mask=attention_mask,
1471
+ position_ids=position_ids,
1472
+ conditional_pixel_values=conditional_pixel_values,
1473
+ )
1474
+ else:
1475
+ if conditional_embeddings.shape[0] != pixel_values.shape[0]:
1476
+ raise ValueError(
1477
+ "Make sure to pass as many conditional embeddings as there are query images in the batch"
1478
+ )
1479
+ if conditional_embeddings.shape[1] != self.config.projection_dim:
1480
+ raise ValueError(
1481
+ "Make sure that the feature dimension of the conditional embeddings matches"
1482
+ " `config.projection_dim`."
1483
+ )
1484
+
1485
+ # step 3: forward both the pooled output and the activations through the lightweight decoder to predict masks
1486
+ decoder_outputs = self.decoder(
1487
+ activations,
1488
+ conditional_embeddings,
1489
+ output_attentions=output_attentions,
1490
+ output_hidden_states=output_hidden_states,
1491
+ return_dict=return_dict,
1492
+ )
1493
+ logits = decoder_outputs.logits if return_dict else decoder_outputs[0]
1494
+
1495
+ loss = None
1496
+ if labels is not None:
1497
+ # move labels to the correct device to enable PP
1498
+ labels = labels.to(logits.device)
1499
+ loss_fn = nn.BCEWithLogitsLoss()
1500
+ loss = loss_fn(logits, labels)
1501
+
1502
+ if not return_dict:
1503
+ output = (logits, conditional_embeddings, pooled_output, vision_outputs, decoder_outputs)
1504
+ return ((loss,) + output) if loss is not None else output
1505
+
1506
+ return CLIPSegImageSegmentationOutput(
1507
+ loss=loss,
1508
+ logits=logits,
1509
+ conditional_embeddings=conditional_embeddings,
1510
+ pooled_output=pooled_output,
1511
+ vision_model_output=vision_outputs,
1512
+ decoder_output=decoder_outputs,
1513
+ )
1514
+
1515
+
1516
+ __all__ = [
1517
+ "CLIPSegModel",
1518
+ "CLIPSegPreTrainedModel",
1519
+ "CLIPSegTextModel",
1520
+ "CLIPSegVisionModel",
1521
+ "CLIPSegForImageSegmentation",
1522
+ ]
lib/python3.12/site-packages/transformers/models/clipseg/processing_clipseg.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ Image/Text processor class for CLIPSeg
17
+ """
18
+
19
+ import warnings
20
+
21
+ from ...processing_utils import ProcessorMixin
22
+ from ...tokenization_utils_base import BatchEncoding
23
+
24
+
25
+ class CLIPSegProcessor(ProcessorMixin):
26
+ r"""
27
+ Constructs a CLIPSeg processor which wraps a CLIPSeg image processor and a CLIP tokenizer into a single processor.
28
+
29
+ [`CLIPSegProcessor`] offers all the functionalities of [`ViTImageProcessor`] and [`CLIPTokenizerFast`]. See the
30
+ [`~CLIPSegProcessor.__call__`] and [`~CLIPSegProcessor.decode`] for more information.
31
+
32
+ Args:
33
+ image_processor ([`ViTImageProcessor`], *optional*):
34
+ The image processor is a required input.
35
+ tokenizer ([`CLIPTokenizerFast`], *optional*):
36
+ The tokenizer is a required input.
37
+ """
38
+
39
+ attributes = ["image_processor", "tokenizer"]
40
+ image_processor_class = ("ViTImageProcessor", "ViTImageProcessorFast")
41
+ tokenizer_class = ("CLIPTokenizer", "CLIPTokenizerFast")
42
+
43
+ def __init__(self, image_processor=None, tokenizer=None, **kwargs):
44
+ feature_extractor = None
45
+ if "feature_extractor" in kwargs:
46
+ warnings.warn(
47
+ "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
48
+ " instead.",
49
+ FutureWarning,
50
+ )
51
+ feature_extractor = kwargs.pop("feature_extractor")
52
+
53
+ image_processor = image_processor if image_processor is not None else feature_extractor
54
+ if image_processor is None:
55
+ raise ValueError("You need to specify an `image_processor`.")
56
+ if tokenizer is None:
57
+ raise ValueError("You need to specify a `tokenizer`.")
58
+
59
+ super().__init__(image_processor, tokenizer)
60
+
61
+ def __call__(self, text=None, images=None, visual_prompt=None, return_tensors=None, **kwargs):
62
+ """
63
+ Main method to prepare for the model one or several sequences(s) and image(s). This method forwards the `text`
64
+ and `kwargs` arguments to CLIPTokenizerFast's [`~CLIPTokenizerFast.__call__`] if `text` is not `None` to encode
65
+ the text. To prepare the image(s), this method forwards the `images` and `kwrags` arguments to
66
+ ViTImageProcessor's [`~ViTImageProcessor.__call__`] if `images` is not `None`. Please refer to the docstring of
67
+ the above two methods for more information.
68
+
69
+ Args:
70
+ text (`str`, `List[str]`, `List[List[str]]`):
71
+ The sequence or batch of sequences to be encoded. Each sequence can be a string or a list of strings
72
+ (pretokenized string). If the sequences are provided as list of strings (pretokenized), you must set
73
+ `is_split_into_words=True` (to lift the ambiguity with a batch of sequences).
74
+ images (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
75
+ The image or batch of images to be prepared. Each image can be a PIL image, NumPy array or PyTorch
76
+ tensor. Both channels-first and channels-last formats are supported.
77
+ visual_prompt (`PIL.Image.Image`, `np.ndarray`, `torch.Tensor`, `List[PIL.Image.Image]`, `List[np.ndarray]`, `List[torch.Tensor]`):
78
+ The visual prompt image or batch of images to be prepared. Each visual prompt image can be a PIL image,
79
+ NumPy array or PyTorch tensor. In case of a NumPy array/PyTorch tensor, each image should be of shape
80
+ (C, H, W), where C is a number of channels, H and W are image height and width.
81
+
82
+ return_tensors (`str` or [`~utils.TensorType`], *optional*):
83
+ If set, will return tensors of a particular framework. Acceptable values are:
84
+
85
+ - `'tf'`: Return TensorFlow `tf.constant` objects.
86
+ - `'pt'`: Return PyTorch `torch.Tensor` objects.
87
+ - `'np'`: Return NumPy `np.ndarray` objects.
88
+ - `'jax'`: Return JAX `jnp.ndarray` objects.
89
+
90
+ Returns:
91
+ [`BatchEncoding`]: A [`BatchEncoding`] with the following fields:
92
+
93
+ - **input_ids** -- List of token ids to be fed to a model. Returned when `text` is not `None`.
94
+ - **attention_mask** -- List of indices specifying which tokens should be attended to by the model (when
95
+ `return_attention_mask=True` or if *"attention_mask"* is in `self.model_input_names` and if `text` is not
96
+ `None`).
97
+ - **pixel_values** -- Pixel values to be fed to a model. Returned when `images` is not `None`.
98
+ """
99
+ if text is None and visual_prompt is None and images is None:
100
+ raise ValueError("You have to specify either text, visual prompt or images.")
101
+
102
+ if text is not None and visual_prompt is not None:
103
+ raise ValueError("You have to specify exactly one type of prompt. Either text or visual prompt.")
104
+
105
+ if text is not None:
106
+ encoding = self.tokenizer(text, return_tensors=return_tensors, **kwargs)
107
+
108
+ if visual_prompt is not None:
109
+ prompt_features = self.image_processor(visual_prompt, return_tensors=return_tensors, **kwargs)
110
+
111
+ if images is not None:
112
+ image_features = self.image_processor(images, return_tensors=return_tensors, **kwargs)
113
+
114
+ if visual_prompt is not None and images is not None:
115
+ encoding = {
116
+ "pixel_values": image_features.pixel_values,
117
+ "conditional_pixel_values": prompt_features.pixel_values,
118
+ }
119
+ return encoding
120
+ elif text is not None and images is not None:
121
+ encoding["pixel_values"] = image_features.pixel_values
122
+ return encoding
123
+ elif text is not None:
124
+ return encoding
125
+ elif visual_prompt is not None:
126
+ encoding = {
127
+ "conditional_pixel_values": prompt_features.pixel_values,
128
+ }
129
+ return encoding
130
+ else:
131
+ return BatchEncoding(data=dict(**image_features), tensor_type=return_tensors)
132
+
133
+ def batch_decode(self, *args, **kwargs):
134
+ """
135
+ This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.batch_decode`]. Please
136
+ refer to the docstring of this method for more information.
137
+ """
138
+ return self.tokenizer.batch_decode(*args, **kwargs)
139
+
140
+ def decode(self, *args, **kwargs):
141
+ """
142
+ This method forwards all its arguments to CLIPTokenizerFast's [`~PreTrainedTokenizer.decode`]. Please refer to
143
+ the docstring of this method for more information.
144
+ """
145
+ return self.tokenizer.decode(*args, **kwargs)
146
+
147
+ @property
148
+ def feature_extractor_class(self):
149
+ warnings.warn(
150
+ "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.",
151
+ FutureWarning,
152
+ )
153
+ return self.image_processor_class
154
+
155
+ @property
156
+ def feature_extractor(self):
157
+ warnings.warn(
158
+ "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.",
159
+ FutureWarning,
160
+ )
161
+ return self.image_processor
162
+
163
+
164
+ __all__ = ["CLIPSegProcessor"]
lib/python3.12/site-packages/transformers/models/codegen/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_codegen import *
22
+ from .modeling_codegen import *
23
+ from .tokenization_codegen import *
24
+ from .tokenization_codegen_fast import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
lib/python3.12/site-packages/transformers/models/codegen/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (745 Bytes). View file
 
lib/python3.12/site-packages/transformers/models/codegen/__pycache__/configuration_codegen.cpython-312.pyc ADDED
Binary file (9.87 kB). View file
 
lib/python3.12/site-packages/transformers/models/codegen/__pycache__/modeling_codegen.cpython-312.pyc ADDED
Binary file (40.1 kB). View file
 
lib/python3.12/site-packages/transformers/models/codegen/__pycache__/tokenization_codegen.cpython-312.pyc ADDED
Binary file (21 kB). View file
 
lib/python3.12/site-packages/transformers/models/codegen/__pycache__/tokenization_codegen_fast.cpython-312.pyc ADDED
Binary file (11.8 kB). View file
 
lib/python3.12/site-packages/transformers/models/codegen/configuration_codegen.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Salesforce authors, The EleutherAI, and HuggingFace Teams. 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
+ """CodeGen model configuration"""
16
+
17
+ from collections import OrderedDict
18
+ from typing import Any, List, Mapping, Optional
19
+
20
+ from ... import PreTrainedTokenizer, TensorType, is_torch_available
21
+ from ...configuration_utils import PretrainedConfig
22
+ from ...onnx import OnnxConfigWithPast, PatchingSpec
23
+ from ...utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+
29
+ class CodeGenConfig(PretrainedConfig):
30
+ r"""
31
+ This is the configuration class to store the configuration of a [`CodeGenModel`]. It is used to instantiate a
32
+ CodeGen model according to the specified arguments, defining the model architecture. Instantiating a configuration
33
+ with the defaults will yield a similar configuration to that of the CodeGen
34
+ [Salesforce/codegen-2B-mono](https://huggingface.co/Salesforce/codegen-2B-mono) architecture. Configuration objects
35
+ inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from
36
+ [`PretrainedConfig`] for more information.
37
+
38
+ Args:
39
+ vocab_size (`int`, *optional*, defaults to 50400):
40
+ Vocabulary size of the CodeGen model. Defines the number of different tokens that can be represented by the
41
+ `inputs_ids` passed when calling [`CodeGenModel`].
42
+ n_positions (`int`, *optional*, defaults to 2048):
43
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
44
+ just in case (e.g., 512 or 1024 or 2048).
45
+ n_ctx (`int`, *optional*, defaults to 2048):
46
+ This attribute is used in `CodeGenModel.__init__` without any real effect.
47
+ n_embd (`int`, *optional*, defaults to 4096):
48
+ Dimensionality of the embeddings and hidden states.
49
+ n_layer (`int`, *optional*, defaults to 28):
50
+ Number of hidden layers in the Transformer encoder.
51
+ n_head (`int`, *optional*, defaults to 16):
52
+ Number of attention heads for each attention layer in the Transformer encoder.
53
+ rotary_dim (`int`, *optional*, defaults to 64):
54
+ Number of dimensions in the embedding that Rotary Position Embedding is applied to.
55
+ n_inner (`int`, *optional*):
56
+ Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd
57
+ activation_function (`str`, *optional*, defaults to `"gelu_new"`):
58
+ Activation function, to be selected in the list `["relu", "silu", "gelu", "tanh", "gelu_new"]`.
59
+ resid_pdrop (`float`, *optional*, defaults to 0.0):
60
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
61
+ embd_pdrop (`int`, *optional*, defaults to 0.0):
62
+ The dropout ratio for the embeddings.
63
+ attn_pdrop (`float`, *optional*, defaults to 0.0):
64
+ The dropout ratio for the attention.
65
+ layer_norm_epsilon (`float`, *optional*, defaults to 1e-05):
66
+ The epsilon to use in the layer normalization layers.
67
+ initializer_range (`float`, *optional*, defaults to 0.02):
68
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
69
+ use_cache (`bool`, *optional*, defaults to `True`):
70
+ Whether or not the model should return the last key/values attentions (not used by all models).
71
+ bos_token_id (`int`, *optional*, defaults to 50256):
72
+ Beginning of stream token id.
73
+ eos_token_id (`int`, *optional*, defaults to 50256):
74
+ End of stream token id.
75
+ tie_word_embeddings (`bool`, *optional*, defaults to `False`):
76
+ Whether the model's input and output word embeddings should be tied. Note that this is only relevant if the
77
+ model has a output word embedding layer.
78
+
79
+ Example:
80
+
81
+ ```python
82
+ >>> from transformers import CodeGenConfig, CodeGenModel
83
+
84
+ >>> # Initializing a CodeGen 6B configuration
85
+ >>> configuration = CodeGenConfig()
86
+
87
+ >>> # Initializing a model (with random weights) from the configuration
88
+ >>> model = CodeGenModel(configuration)
89
+
90
+ >>> # Accessing the model configuration
91
+ >>> configuration = model.config
92
+ ```"""
93
+
94
+ model_type = "codegen"
95
+ attribute_map = {
96
+ "max_position_embeddings": "n_positions",
97
+ "hidden_size": "n_embd",
98
+ "num_attention_heads": "n_head",
99
+ "num_hidden_layers": "n_layer",
100
+ }
101
+
102
+ def __init__(
103
+ self,
104
+ vocab_size=50400,
105
+ n_positions=2048,
106
+ n_ctx=2048,
107
+ n_embd=4096,
108
+ n_layer=28,
109
+ n_head=16,
110
+ rotary_dim=64,
111
+ n_inner=None,
112
+ activation_function="gelu_new",
113
+ resid_pdrop=0.0,
114
+ embd_pdrop=0.0,
115
+ attn_pdrop=0.0,
116
+ layer_norm_epsilon=1e-5,
117
+ initializer_range=0.02,
118
+ use_cache=True,
119
+ bos_token_id=50256,
120
+ eos_token_id=50256,
121
+ tie_word_embeddings=False,
122
+ **kwargs,
123
+ ):
124
+ self.vocab_size = vocab_size
125
+ self.n_ctx = n_ctx
126
+ self.n_positions = n_positions
127
+ self.n_embd = n_embd
128
+ self.n_layer = n_layer
129
+ self.n_head = n_head
130
+ self.n_inner = n_inner
131
+ self.rotary_dim = rotary_dim
132
+ self.activation_function = activation_function
133
+ self.resid_pdrop = resid_pdrop
134
+ self.embd_pdrop = embd_pdrop
135
+ self.attn_pdrop = attn_pdrop
136
+ self.layer_norm_epsilon = layer_norm_epsilon
137
+ self.initializer_range = initializer_range
138
+ self.use_cache = use_cache
139
+
140
+ self.bos_token_id = bos_token_id
141
+ self.eos_token_id = eos_token_id
142
+
143
+ super().__init__(
144
+ bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs
145
+ )
146
+
147
+
148
+ # Copied from transformers.models.gpt2.configuration_gpt2.GPT2OnnxConfig
149
+ class CodeGenOnnxConfig(OnnxConfigWithPast):
150
+ def __init__(
151
+ self,
152
+ config: PretrainedConfig,
153
+ task: str = "default",
154
+ patching_specs: List[PatchingSpec] = None,
155
+ use_past: bool = False,
156
+ ):
157
+ super().__init__(config, task=task, patching_specs=patching_specs, use_past=use_past)
158
+ if not getattr(self._config, "pad_token_id", None):
159
+ # TODO: how to do that better?
160
+ self._config.pad_token_id = 0
161
+
162
+ @property
163
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
164
+ common_inputs = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}})
165
+ if self.use_past:
166
+ self.fill_with_past_key_values_(common_inputs, direction="inputs")
167
+ common_inputs["attention_mask"] = {0: "batch", 1: "past_sequence + sequence"}
168
+ else:
169
+ common_inputs["attention_mask"] = {0: "batch", 1: "sequence"}
170
+
171
+ return common_inputs
172
+
173
+ @property
174
+ def num_layers(self) -> int:
175
+ return self._config.n_layer
176
+
177
+ @property
178
+ def num_attention_heads(self) -> int:
179
+ return self._config.n_head
180
+
181
+ def generate_dummy_inputs(
182
+ self,
183
+ tokenizer: PreTrainedTokenizer,
184
+ batch_size: int = -1,
185
+ seq_length: int = -1,
186
+ is_pair: bool = False,
187
+ framework: Optional[TensorType] = None,
188
+ ) -> Mapping[str, Any]:
189
+ common_inputs = super(OnnxConfigWithPast, self).generate_dummy_inputs(
190
+ tokenizer, batch_size=batch_size, seq_length=seq_length, is_pair=is_pair, framework=framework
191
+ )
192
+
193
+ # We need to order the input in the way they appears in the forward()
194
+ ordered_inputs = OrderedDict({"input_ids": common_inputs["input_ids"]})
195
+
196
+ # Need to add the past_keys
197
+ if self.use_past:
198
+ if not is_torch_available():
199
+ raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed.")
200
+ else:
201
+ import torch
202
+
203
+ batch, seqlen = common_inputs["input_ids"].shape
204
+ # Not using the same length for past_key_values
205
+ past_key_values_length = seqlen + 2
206
+ past_shape = (
207
+ batch,
208
+ self.num_attention_heads,
209
+ past_key_values_length,
210
+ self._config.hidden_size // self.num_attention_heads,
211
+ )
212
+ ordered_inputs["past_key_values"] = [
213
+ (torch.zeros(past_shape), torch.zeros(past_shape)) for _ in range(self.num_layers)
214
+ ]
215
+
216
+ ordered_inputs["attention_mask"] = common_inputs["attention_mask"]
217
+ if self.use_past:
218
+ mask_dtype = ordered_inputs["attention_mask"].dtype
219
+ ordered_inputs["attention_mask"] = torch.cat(
220
+ [ordered_inputs["attention_mask"], torch.ones(batch, past_key_values_length, dtype=mask_dtype)], dim=1
221
+ )
222
+
223
+ return ordered_inputs
224
+
225
+ @property
226
+ def default_onnx_opset(self) -> int:
227
+ return 13
228
+
229
+
230
+ __all__ = ["CodeGenConfig", "CodeGenOnnxConfig"]
lib/python3.12/site-packages/transformers/models/codegen/modeling_codegen.py ADDED
@@ -0,0 +1,835 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Salesforce authors, The EleutherAI, and HuggingFace Teams. 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 CodeGen model."""
16
+
17
+ from typing import Optional, Tuple, Union
18
+
19
+ import torch
20
+ import torch.utils.checkpoint
21
+ from torch import nn
22
+
23
+ from ...activations import ACT2FN
24
+ from ...cache_utils import Cache, DynamicCache, StaticCache
25
+ from ...generation import GenerationMixin
26
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
27
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
28
+ from ...modeling_utils import PreTrainedModel
29
+ from ...utils import (
30
+ add_code_sample_docstrings,
31
+ add_start_docstrings,
32
+ add_start_docstrings_to_model_forward,
33
+ is_torch_flex_attn_available,
34
+ logging,
35
+ )
36
+ from .configuration_codegen import CodeGenConfig
37
+
38
+
39
+ if is_torch_flex_attn_available():
40
+ from torch.nn.attention.flex_attention import BlockMask
41
+
42
+ from ...integrations.flex_attention import make_flex_block_causal_mask
43
+
44
+
45
+ logger = logging.get_logger(__name__)
46
+
47
+ _CHECKPOINT_FOR_DOC = "Salesforce/codegen-2B-mono"
48
+ _CONFIG_FOR_DOC = "CodeGenConfig"
49
+
50
+
51
+ # Copied from transformers.models.gptj.modeling_gptj.create_sinusoidal_positions
52
+ def create_sinusoidal_positions(num_pos: int, dim: int) -> torch.Tensor:
53
+ inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2, dtype=torch.int64) / dim))
54
+ sinusoid_inp = torch.einsum("i , j -> i j", torch.arange(num_pos, dtype=torch.int64).float(), inv_freq).float()
55
+ return torch.cat((torch.sin(sinusoid_inp), torch.cos(sinusoid_inp)), dim=1)
56
+
57
+
58
+ # Copied from transformers.models.gptj.modeling_gptj.rotate_every_two
59
+ def rotate_every_two(x: torch.Tensor) -> torch.Tensor:
60
+ x1 = x[:, :, :, ::2]
61
+ x2 = x[:, :, :, 1::2]
62
+ x = torch.stack((-x2, x1), dim=-1)
63
+ return x.flatten(-2) # in einsum notation: rearrange(x, '... d j -> ... (d j)')
64
+
65
+
66
+ # Copied from transformers.models.gptj.modeling_gptj.apply_rotary_pos_emb
67
+ def apply_rotary_pos_emb(tensor: torch.Tensor, sin: torch.Tensor, cos: torch.Tensor) -> torch.Tensor:
68
+ sin = torch.repeat_interleave(sin[:, :, None, :], 2, 3)
69
+ cos = torch.repeat_interleave(cos[:, :, None, :], 2, 3)
70
+ return (tensor * cos) + (rotate_every_two(tensor) * sin)
71
+
72
+
73
+ class CodeGenAttention(nn.Module):
74
+ def __init__(self, config, layer_idx=None):
75
+ super().__init__()
76
+
77
+ max_positions = config.max_position_embeddings
78
+ self.attn_dropout = nn.Dropout(config.attn_pdrop)
79
+ self.resid_dropout = nn.Dropout(config.resid_pdrop)
80
+ self.layer_idx = layer_idx
81
+ if layer_idx is None:
82
+ logger.warning_once(
83
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
84
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
85
+ "when creating this class."
86
+ )
87
+
88
+ self.embed_dim = config.hidden_size
89
+ self.num_attention_heads = config.num_attention_heads
90
+ self.head_dim = self.embed_dim // self.num_attention_heads
91
+ if self.head_dim * self.num_attention_heads != self.embed_dim:
92
+ raise ValueError(
93
+ f"embed_dim must be divisible by num_attention_heads (got `embed_dim`: {self.embed_dim} and"
94
+ f" `num_attention_heads`: {self.num_attention_heads})."
95
+ )
96
+ self.scale_attn = torch.sqrt(torch.tensor(self.head_dim, dtype=torch.float32)).to(torch.get_default_dtype())
97
+ self.qkv_proj = nn.Linear(self.embed_dim, self.embed_dim * 3, bias=False)
98
+
99
+ self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
100
+ self.rotary_dim = config.rotary_dim
101
+ pos_embd_dim = self.rotary_dim or self.embed_dim
102
+ self.embed_positions = create_sinusoidal_positions(max_positions, pos_embd_dim)
103
+
104
+ def _split_heads(self, x, n_head, dim_head, mp_num):
105
+ reshaped = x.reshape(x.shape[:-1] + (n_head // mp_num, dim_head))
106
+ reshaped = reshaped.reshape(x.shape[:-2] + (-1,) + reshaped.shape[-1:])
107
+ return reshaped
108
+
109
+ def _merge_heads(self, tensor, num_attention_heads, attn_head_size):
110
+ """
111
+ Merges attn_head_size dim and num_attn_heads dim into n_ctx
112
+ """
113
+ if len(tensor.shape) == 5:
114
+ tensor = tensor.permute(0, 1, 3, 2, 4).contiguous()
115
+ elif len(tensor.shape) == 4:
116
+ tensor = tensor.permute(0, 2, 1, 3).contiguous()
117
+ else:
118
+ raise ValueError(f"Input tensor rank should be one of [4, 5], but is: {len(tensor.shape)}")
119
+ new_shape = tensor.size()[:-2] + (num_attention_heads * attn_head_size,)
120
+ return tensor.view(new_shape)
121
+
122
+ def _attn(
123
+ self,
124
+ query,
125
+ key,
126
+ value,
127
+ attention_mask=None,
128
+ head_mask=None,
129
+ ):
130
+ # Keep the attention weights computation in fp32 to avoid overflow issues
131
+ query = query.to(torch.float32)
132
+ key = key.to(torch.float32)
133
+
134
+ attn_weights = torch.matmul(query, key.transpose(-1, -2))
135
+
136
+ if attention_mask is not None:
137
+ causal_mask = attention_mask[:, :, :, : key.shape[-2]]
138
+ attn_weights += causal_mask
139
+
140
+ attn_weights = attn_weights / self.scale_attn
141
+ attn_weights = nn.Softmax(dim=-1)(attn_weights)
142
+ attn_weights = attn_weights.to(value.dtype)
143
+ attn_weights = self.attn_dropout(attn_weights)
144
+
145
+ # Mask heads if we want to
146
+ if head_mask is not None:
147
+ attn_weights = attn_weights * head_mask
148
+
149
+ attn_output = torch.matmul(attn_weights, value)
150
+
151
+ return attn_output, attn_weights
152
+
153
+ def forward(
154
+ self,
155
+ hidden_states: Optional[torch.FloatTensor],
156
+ layer_past: Optional[Cache] = None,
157
+ attention_mask: Optional[torch.FloatTensor] = None,
158
+ position_ids: Optional[torch.LongTensor] = None,
159
+ head_mask: Optional[torch.FloatTensor] = None,
160
+ use_cache: Optional[bool] = False,
161
+ output_attentions: Optional[bool] = False,
162
+ cache_position: Optional[torch.LongTensor] = None,
163
+ ) -> Union[
164
+ Tuple[torch.Tensor, Tuple[torch.Tensor]],
165
+ Optional[Tuple[torch.Tensor, Tuple[torch.Tensor], Tuple[torch.Tensor, ...]]],
166
+ ]:
167
+ qkv = self.qkv_proj(hidden_states)
168
+ # TODO(enijkamp): factor out number of logical TPU-v4 cores or make forward pass agnostic
169
+ mp_num = 4
170
+ qkv_split = qkv.reshape(qkv.shape[:-1] + (mp_num, -1))
171
+
172
+ local_dim = self.head_dim * self.num_attention_heads // mp_num
173
+ query, value, key = torch.split(qkv_split, local_dim, dim=-1)
174
+ query = self._split_heads(query, self.num_attention_heads, self.head_dim, mp_num=mp_num)
175
+ key = self._split_heads(key, self.num_attention_heads, self.head_dim, mp_num=mp_num)
176
+
177
+ value = self._split_heads(value, self.num_attention_heads, self.head_dim, mp_num=mp_num)
178
+ value = value.permute(0, 2, 1, 3)
179
+
180
+ embed_positions = self.embed_positions
181
+ if embed_positions.device != position_ids.device:
182
+ embed_positions = embed_positions.to(position_ids.device)
183
+ self.embed_positions = embed_positions
184
+
185
+ sincos = embed_positions[position_ids]
186
+ sin, cos = torch.split(sincos, sincos.shape[-1] // 2, dim=-1)
187
+
188
+ if self.rotary_dim is not None:
189
+ k_rot = key[:, :, :, : self.rotary_dim]
190
+ k_pass = key[:, :, :, self.rotary_dim :]
191
+
192
+ q_rot = query[:, :, :, : self.rotary_dim]
193
+ q_pass = query[:, :, :, self.rotary_dim :]
194
+
195
+ k_rot = apply_rotary_pos_emb(k_rot, sin, cos)
196
+ q_rot = apply_rotary_pos_emb(q_rot, sin, cos)
197
+
198
+ key = torch.cat([k_rot, k_pass], dim=-1)
199
+ query = torch.cat([q_rot, q_pass], dim=-1)
200
+ else:
201
+ key = apply_rotary_pos_emb(key, sin, cos)
202
+ query = apply_rotary_pos_emb(query, sin, cos)
203
+
204
+ key = key.permute(0, 2, 1, 3)
205
+ query = query.permute(0, 2, 1, 3)
206
+
207
+ # Note that this cast is quite ugly, but is not implemented before ROPE as k_rot in the original codebase is always in fp32.
208
+ # Reference: https://github.com/salesforce/CodeGen/blob/f210c3bb1216c975ad858cd4132c0fdeabf4bfc2/codegen1/jaxformer/hf/codegen/modeling_codegen.py#L38
209
+ if layer_past is not None:
210
+ cache_kwargs = {
211
+ "sin": sin,
212
+ "cos": cos,
213
+ "partial_rotation_size": self.rotary_dim,
214
+ "cache_position": cache_position,
215
+ }
216
+ key, value = layer_past.update(key.to(hidden_states.dtype), value, self.layer_idx, cache_kwargs)
217
+
218
+ # compute self-attention: V x Softmax(QK^T)
219
+ attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask)
220
+
221
+ attn_output = self._merge_heads(attn_output, self.num_attention_heads, self.head_dim)
222
+ attn_output = self.out_proj(attn_output)
223
+ attn_output = self.resid_dropout(attn_output)
224
+
225
+ outputs = (attn_output, layer_past)
226
+ if output_attentions:
227
+ outputs += (attn_weights,)
228
+
229
+ return outputs # a, present, (attentions)
230
+
231
+
232
+ # Copied from transformers.models.gptj.modeling_gptj.GPTJMLP with GPTJ->CodeGen
233
+ class CodeGenMLP(nn.Module):
234
+ def __init__(self, intermediate_size, config): # in MLP: intermediate_size= 4 * embed_dim
235
+ super().__init__()
236
+ embed_dim = config.n_embd
237
+
238
+ self.fc_in = nn.Linear(embed_dim, intermediate_size)
239
+ self.fc_out = nn.Linear(intermediate_size, embed_dim)
240
+
241
+ self.act = ACT2FN[config.activation_function]
242
+ self.dropout = nn.Dropout(config.resid_pdrop)
243
+
244
+ def forward(self, hidden_states: Optional[torch.FloatTensor]) -> torch.FloatTensor:
245
+ hidden_states = self.fc_in(hidden_states)
246
+ hidden_states = self.act(hidden_states)
247
+ hidden_states = self.fc_out(hidden_states)
248
+ hidden_states = self.dropout(hidden_states)
249
+ return hidden_states
250
+
251
+
252
+ # Copied from transformers.models.gptj.modeling_gptj.GPTJBlock with GPTJ->CodeGen
253
+ class CodeGenBlock(nn.Module):
254
+ # Ignore copy
255
+ def __init__(self, config, layer_idx=None):
256
+ super().__init__()
257
+ inner_dim = config.n_inner if config.n_inner is not None else 4 * config.n_embd
258
+ self.ln_1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
259
+ self.attn = CodeGenAttention(config, layer_idx)
260
+ self.mlp = CodeGenMLP(inner_dim, config)
261
+
262
+ def forward(
263
+ self,
264
+ hidden_states: Optional[torch.FloatTensor],
265
+ layer_past: Optional[Cache] = None,
266
+ attention_mask: Optional[torch.FloatTensor] = None,
267
+ position_ids: Optional[torch.LongTensor] = None,
268
+ head_mask: Optional[torch.FloatTensor] = None,
269
+ use_cache: Optional[bool] = False,
270
+ output_attentions: Optional[bool] = False,
271
+ cache_position: Optional[torch.LongTensor] = None,
272
+ ) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]:
273
+ residual = hidden_states
274
+ hidden_states = self.ln_1(hidden_states)
275
+ attn_outputs = self.attn(
276
+ hidden_states=hidden_states,
277
+ layer_past=layer_past,
278
+ attention_mask=attention_mask,
279
+ position_ids=position_ids,
280
+ head_mask=head_mask,
281
+ use_cache=use_cache,
282
+ output_attentions=output_attentions,
283
+ cache_position=cache_position,
284
+ )
285
+ attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
286
+ outputs = attn_outputs[1:]
287
+
288
+ feed_forward_hidden_states = self.mlp(hidden_states)
289
+ hidden_states = attn_output + feed_forward_hidden_states + residual
290
+
291
+ if use_cache:
292
+ outputs = (hidden_states,) + outputs
293
+ else:
294
+ outputs = (hidden_states,) + outputs[1:]
295
+
296
+ return outputs # hidden_states, present, (attentions)
297
+
298
+
299
+ class CodeGenPreTrainedModel(PreTrainedModel):
300
+ """
301
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
302
+ models.
303
+ """
304
+
305
+ config_class = CodeGenConfig
306
+ base_model_prefix = "transformer"
307
+ supports_gradient_checkpointing = True
308
+ _no_split_modules = ["CodeGenBlock"]
309
+ _skip_keys_device_placement = "past_key_values"
310
+ _supports_cache_class = True
311
+ _supports_quantized_cache = True
312
+ _supports_static_cache = True
313
+
314
+ def __init__(self, *inputs, **kwargs):
315
+ super().__init__(*inputs, **kwargs)
316
+
317
+ def _init_weights(self, module):
318
+ """Initialize the weights."""
319
+ if isinstance(module, (nn.Linear,)):
320
+ # Slightly different from Mesh Transformer JAX which uses truncated_normal for initialization
321
+ # cf https://github.com/pytorch/pytorch/pull/5617
322
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
323
+ if module.bias is not None:
324
+ module.bias.data.zero_()
325
+ elif isinstance(module, nn.Embedding):
326
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
327
+ if module.padding_idx is not None:
328
+ module.weight.data[module.padding_idx].zero_()
329
+ elif isinstance(module, nn.LayerNorm):
330
+ module.bias.data.zero_()
331
+ module.weight.data.fill_(1.0)
332
+
333
+
334
+ CODEGEN_START_DOCSTRING = r"""
335
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
336
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
337
+ behavior.
338
+
339
+ Parameters:
340
+ config ([`CodeGenConfig`]): Model configuration class with all the parameters of the model.
341
+ Initializing with a config file does not load the weights associated with the model, only the
342
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
343
+ """
344
+
345
+ CODEGEN_INPUTS_DOCSTRING = r"""
346
+ Args:
347
+ input_ids (`torch.LongTensor` of shape `({0})`):
348
+ Indices of input sequence tokens in the vocabulary.
349
+
350
+ Indices can be obtained using [`AutoProcenizer`]. See [`PreTrainedTokenizer.encode`] and
351
+ [`PreTrainedTokenizer.__call__`] for details.
352
+
353
+ [What are input IDs?](../glossary#input-ids)
354
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
355
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
356
+
357
+ - 1 for tokens that are **not masked**,
358
+ - 0 for tokens that are **masked**.
359
+
360
+ [What are attention masks?](../glossary#attention-mask)
361
+ token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
362
+ Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
363
+ 1]`:
364
+
365
+ - 0 corresponds to a *sentence A* token,
366
+ - 1 corresponds to a *sentence B* token.
367
+
368
+ [What are token type IDs?](../glossary#token-type-ids)
369
+ position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
370
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
371
+ config.n_positions - 1]`.
372
+
373
+ [What are position IDs?](../glossary#position-ids)
374
+ head_mask (`torch.FloatTensor` of shape `(num_attention_heads,)` or `(n_layer, num_attention_heads)`, *optional*):
375
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
376
+
377
+ - 1 indicates the head is **not masked**,
378
+ - 0 indicates the head is **masked**.
379
+
380
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_dim)`, *optional*):
381
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
382
+ is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
383
+ model's internal embedding lookup matrix.
384
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
385
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
386
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
387
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
388
+
389
+ Two formats are allowed:
390
+ - a [`~cache_utils.Cache`] instance, see our
391
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
392
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
393
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
394
+ cache format.
395
+
396
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
397
+ legacy cache format will be returned.
398
+
399
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
400
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
401
+ of shape `(batch_size, sequence_length)`.
402
+ output_attentions (`bool`, *optional*):
403
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
404
+ tensors for more detail.
405
+ output_hidden_states (`bool`, *optional*):
406
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
407
+ more detail.
408
+ return_dict (`bool`, *optional*):
409
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
410
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
411
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
412
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
413
+ the complete sequence length.
414
+ """
415
+
416
+
417
+ @add_start_docstrings(
418
+ "The bare CodeGen Model transformer outputting raw hidden-states without any specific head on top.",
419
+ CODEGEN_START_DOCSTRING,
420
+ )
421
+ class CodeGenModel(CodeGenPreTrainedModel):
422
+ def __init__(self, config):
423
+ super().__init__(config)
424
+
425
+ self.embed_dim = config.n_embd
426
+ self.vocab_size = config.vocab_size
427
+ self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
428
+ self.drop = nn.Dropout(config.embd_pdrop)
429
+ self.h = nn.ModuleList([CodeGenBlock(config, layer_idx=i) for i in range(config.n_layer)])
430
+ self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
431
+ self.rotary_dim = min(config.rotary_dim, config.n_ctx // config.num_attention_heads)
432
+
433
+ self.gradient_checkpointing = False
434
+
435
+ # Initialize weights and apply final processing
436
+ self.post_init()
437
+
438
+ def get_input_embeddings(self):
439
+ return self.wte
440
+
441
+ def set_input_embeddings(self, new_embeddings):
442
+ self.wte = new_embeddings
443
+
444
+ @add_start_docstrings_to_model_forward(CODEGEN_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
445
+ @add_code_sample_docstrings(
446
+ checkpoint=_CHECKPOINT_FOR_DOC,
447
+ output_type=BaseModelOutputWithPast,
448
+ config_class=_CONFIG_FOR_DOC,
449
+ )
450
+ def forward(
451
+ self,
452
+ input_ids: Optional[torch.LongTensor] = None,
453
+ past_key_values: Optional[Union[Cache, Tuple[Tuple[torch.Tensor]]]] = None,
454
+ attention_mask: Optional[torch.FloatTensor] = None,
455
+ token_type_ids: Optional[torch.LongTensor] = None,
456
+ position_ids: Optional[torch.LongTensor] = None,
457
+ head_mask: Optional[torch.FloatTensor] = None,
458
+ inputs_embeds: Optional[torch.FloatTensor] = None,
459
+ use_cache: Optional[bool] = None,
460
+ output_attentions: Optional[bool] = None,
461
+ output_hidden_states: Optional[bool] = None,
462
+ return_dict: Optional[bool] = None,
463
+ cache_position: Optional[torch.LongTensor] = None,
464
+ **kwargs, # NOOP kwargs, for now
465
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
466
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
467
+ output_hidden_states = (
468
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
469
+ )
470
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
471
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
472
+
473
+ if (input_ids is None) ^ (inputs_embeds is not None):
474
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
475
+
476
+ if self.gradient_checkpointing and self.training:
477
+ if use_cache:
478
+ logger.warning_once(
479
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
480
+ )
481
+ use_cache = False
482
+
483
+ if inputs_embeds is None:
484
+ inputs_embeds = self.wte(input_ids)
485
+
486
+ # kept for BC (non `Cache` `past_key_values` inputs)
487
+ return_legacy_cache = False
488
+ if use_cache and not isinstance(past_key_values, Cache):
489
+ return_legacy_cache = True
490
+ if past_key_values is None:
491
+ past_key_values = DynamicCache()
492
+ else:
493
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
494
+ logger.warning_once(
495
+ "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
496
+ "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
497
+ "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
498
+ )
499
+
500
+ seq_length = inputs_embeds.shape[1]
501
+ if cache_position is None:
502
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
503
+ cache_position = torch.arange(past_seen_tokens, past_seen_tokens + seq_length, device=inputs_embeds.device)
504
+
505
+ if position_ids is None:
506
+ position_ids = cache_position.unsqueeze(0)
507
+
508
+ causal_mask = self._update_causal_mask(
509
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
510
+ )
511
+
512
+ # Prepare head mask if needed
513
+ # 1.0 in head_mask indicate we keep the head
514
+ # attention_probs has shape bsz x num_attention_heads x N x N
515
+ # head_mask has shape n_layer x batch x num_attention_heads x N x N
516
+ head_mask = self.get_head_mask(head_mask, self.config.n_layer)
517
+ hidden_states = inputs_embeds
518
+
519
+ if token_type_ids is not None:
520
+ token_type_ids = token_type_ids.view(-1, seq_length)
521
+ token_type_embeds = self.wte(token_type_ids)
522
+ hidden_states = hidden_states + token_type_embeds
523
+
524
+ hidden_states = self.drop(hidden_states)
525
+ output_shape = (-1, seq_length, hidden_states.size(-1))
526
+
527
+ next_decoder_cache = None
528
+ all_self_attentions = () if output_attentions else None
529
+ all_hidden_states = () if output_hidden_states else None
530
+ for i, block in enumerate(self.h):
531
+ if output_hidden_states:
532
+ all_hidden_states = all_hidden_states + (hidden_states,)
533
+
534
+ if self.gradient_checkpointing and self.training:
535
+ outputs = self._gradient_checkpointing_func(
536
+ block.__call__,
537
+ hidden_states,
538
+ None,
539
+ causal_mask,
540
+ position_ids,
541
+ head_mask[i],
542
+ use_cache,
543
+ output_attentions,
544
+ cache_position,
545
+ )
546
+ else:
547
+ outputs = block(
548
+ hidden_states=hidden_states,
549
+ layer_past=past_key_values,
550
+ attention_mask=causal_mask,
551
+ position_ids=position_ids,
552
+ head_mask=head_mask[i],
553
+ use_cache=use_cache,
554
+ output_attentions=output_attentions,
555
+ cache_position=cache_position,
556
+ )
557
+
558
+ hidden_states = outputs[0]
559
+ if use_cache is True:
560
+ next_decoder_cache = outputs[1]
561
+
562
+ if output_attentions:
563
+ all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
564
+
565
+ hidden_states = self.ln_f(hidden_states)
566
+
567
+ hidden_states = hidden_states.view(output_shape)
568
+ # Add last hidden state
569
+ if output_hidden_states:
570
+ all_hidden_states = all_hidden_states + (hidden_states,)
571
+
572
+ next_cache = next_decoder_cache if use_cache else None
573
+ if return_legacy_cache:
574
+ next_cache = next_cache.to_legacy_cache()
575
+
576
+ if not return_dict:
577
+ return tuple(
578
+ v for v in [hidden_states, next_cache, all_hidden_states, all_self_attentions] if v is not None
579
+ )
580
+
581
+ return BaseModelOutputWithPast(
582
+ last_hidden_state=hidden_states,
583
+ past_key_values=next_cache,
584
+ hidden_states=all_hidden_states,
585
+ attentions=all_self_attentions,
586
+ )
587
+
588
+ # Copied from transformers.models.llama.modeling_llama.LlamaModel._update_causal_mask
589
+ def _update_causal_mask(
590
+ self,
591
+ attention_mask: torch.Tensor,
592
+ input_tensor: torch.Tensor,
593
+ cache_position: torch.Tensor,
594
+ past_key_values: Cache,
595
+ output_attentions: bool = False,
596
+ ):
597
+ if self.config._attn_implementation == "flash_attention_2":
598
+ if attention_mask is not None and (attention_mask == 0.0).any():
599
+ return attention_mask
600
+ return None
601
+ if self.config._attn_implementation == "flex_attention":
602
+ if isinstance(attention_mask, torch.Tensor):
603
+ attention_mask = make_flex_block_causal_mask(attention_mask)
604
+ if isinstance(attention_mask, BlockMask):
605
+ return attention_mask
606
+
607
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
608
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
609
+ # to infer the attention mask.
610
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
611
+ using_static_cache = isinstance(past_key_values, StaticCache)
612
+
613
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
614
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
615
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
616
+ attention_mask,
617
+ inputs_embeds=input_tensor,
618
+ past_key_values_length=past_seen_tokens,
619
+ is_training=self.training,
620
+ ):
621
+ return None
622
+
623
+ dtype, device = input_tensor.dtype, input_tensor.device
624
+ sequence_length = input_tensor.shape[1]
625
+ if using_static_cache:
626
+ target_length = past_key_values.get_max_cache_shape()
627
+ else:
628
+ target_length = (
629
+ attention_mask.shape[-1]
630
+ if isinstance(attention_mask, torch.Tensor)
631
+ else past_seen_tokens + sequence_length + 1
632
+ )
633
+
634
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
635
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
636
+ attention_mask,
637
+ sequence_length=sequence_length,
638
+ target_length=target_length,
639
+ dtype=dtype,
640
+ device=device,
641
+ cache_position=cache_position,
642
+ batch_size=input_tensor.shape[0],
643
+ )
644
+
645
+ if (
646
+ self.config._attn_implementation == "sdpa"
647
+ and attention_mask is not None
648
+ and attention_mask.device.type in ["cuda", "xpu"]
649
+ and not output_attentions
650
+ ):
651
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
652
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
653
+ # Details: https://github.com/pytorch/pytorch/issues/110213
654
+ min_dtype = torch.finfo(dtype).min
655
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
656
+
657
+ return causal_mask
658
+
659
+ @staticmethod
660
+ # Copied from transformers.models.llama.modeling_llama.LlamaPreTrainedModel._prepare_4d_causal_attention_mask_with_cache_position
661
+ def _prepare_4d_causal_attention_mask_with_cache_position(
662
+ attention_mask: torch.Tensor,
663
+ sequence_length: int,
664
+ target_length: int,
665
+ dtype: torch.dtype,
666
+ device: torch.device,
667
+ cache_position: torch.Tensor,
668
+ batch_size: int,
669
+ **kwargs,
670
+ ):
671
+ """
672
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
673
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
674
+
675
+ Args:
676
+ attention_mask (`torch.Tensor`):
677
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
678
+ `(batch_size, 1, query_length, key_value_length)`.
679
+ sequence_length (`int`):
680
+ The sequence length being processed.
681
+ target_length (`int`):
682
+ The target length: when generating with static cache, the mask should be as long as the static cache,
683
+ to account for the 0 padding, the part of the cache that is not filled yet.
684
+ dtype (`torch.dtype`):
685
+ The dtype to use for the 4D attention mask.
686
+ device (`torch.device`):
687
+ The device to place the 4D attention mask on.
688
+ cache_position (`torch.Tensor`):
689
+ Indices depicting the position of the input sequence tokens in the sequence.
690
+ batch_size (`torch.Tensor`):
691
+ Batch size.
692
+ """
693
+ if attention_mask is not None and attention_mask.dim() == 4:
694
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
695
+ causal_mask = attention_mask
696
+ else:
697
+ min_dtype = torch.finfo(dtype).min
698
+ causal_mask = torch.full(
699
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
700
+ )
701
+ if sequence_length != 1:
702
+ causal_mask = torch.triu(causal_mask, diagonal=1)
703
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
704
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
705
+ if attention_mask is not None:
706
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
707
+ mask_length = attention_mask.shape[-1]
708
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
709
+ causal_mask.device
710
+ )
711
+ padding_mask = padding_mask == 0
712
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
713
+ padding_mask, min_dtype
714
+ )
715
+
716
+ return causal_mask
717
+
718
+
719
+ @add_start_docstrings(
720
+ """
721
+ The CodeGen Model transformer with a language modeling head on top.
722
+ """,
723
+ CODEGEN_START_DOCSTRING,
724
+ )
725
+ class CodeGenForCausalLM(CodeGenPreTrainedModel, GenerationMixin):
726
+ _tied_weights_keys = ["lm_head.weight"]
727
+
728
+ def __init__(self, config):
729
+ super().__init__(config)
730
+ self.transformer = CodeGenModel(config)
731
+ self.lm_head = nn.Linear(config.n_embd, config.vocab_size)
732
+
733
+ # Initialize weights and apply final processing
734
+ self.post_init()
735
+
736
+ def get_output_embeddings(self):
737
+ return self.lm_head
738
+
739
+ def set_output_embeddings(self, new_embeddings):
740
+ self.lm_head = new_embeddings
741
+
742
+ @add_start_docstrings_to_model_forward(CODEGEN_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
743
+ @add_code_sample_docstrings(
744
+ checkpoint=_CHECKPOINT_FOR_DOC,
745
+ output_type=CausalLMOutputWithPast,
746
+ config_class=_CONFIG_FOR_DOC,
747
+ )
748
+ def forward(
749
+ self,
750
+ input_ids: Optional[torch.LongTensor] = None,
751
+ past_key_values: Optional[Union[Cache, Tuple[Tuple[torch.Tensor]]]] = None,
752
+ attention_mask: Optional[torch.FloatTensor] = None,
753
+ token_type_ids: Optional[torch.LongTensor] = None,
754
+ position_ids: Optional[torch.LongTensor] = None,
755
+ head_mask: Optional[torch.FloatTensor] = None,
756
+ inputs_embeds: Optional[torch.FloatTensor] = None,
757
+ labels: Optional[torch.LongTensor] = None,
758
+ use_cache: Optional[bool] = None,
759
+ output_attentions: Optional[bool] = None,
760
+ output_hidden_states: Optional[bool] = None,
761
+ return_dict: Optional[bool] = None,
762
+ cache_position: Optional[torch.LongTensor] = None,
763
+ **kwargs,
764
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
765
+ r"""
766
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
767
+ Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
768
+ `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
769
+ are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
770
+ """
771
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
772
+
773
+ transformer_outputs = self.transformer(
774
+ input_ids,
775
+ past_key_values=past_key_values,
776
+ attention_mask=attention_mask,
777
+ token_type_ids=token_type_ids,
778
+ position_ids=position_ids,
779
+ head_mask=head_mask,
780
+ inputs_embeds=inputs_embeds,
781
+ use_cache=use_cache,
782
+ output_attentions=output_attentions,
783
+ output_hidden_states=output_hidden_states,
784
+ return_dict=return_dict,
785
+ cache_position=cache_position,
786
+ )
787
+ hidden_states = transformer_outputs[0]
788
+
789
+ # make sure sampling in fp16 works correctly and
790
+ # compute loss in fp32 to match with mesh-tf version
791
+ # https://github.com/EleutherAI/gpt-neo/blob/89ce74164da2fb16179106f54e2269b5da8db333/models/gpt2/gpt2.py#L179
792
+ lm_logits = self.lm_head(hidden_states).to(torch.float32)
793
+
794
+ loss = None
795
+ if labels is not None:
796
+ # move labels to correct device to enable model parallelism
797
+ labels = labels.to(lm_logits.device)
798
+ # Flatten the tokens
799
+ loss = self.loss_function(
800
+ lm_logits,
801
+ labels,
802
+ vocab_size=self.config.vocab_size,
803
+ **kwargs,
804
+ )
805
+
806
+ loss = loss.to(hidden_states.dtype)
807
+
808
+ if not return_dict:
809
+ output = (lm_logits,) + transformer_outputs[1:]
810
+ return ((loss,) + output) if loss is not None else output
811
+
812
+ return CausalLMOutputWithPast(
813
+ loss=loss,
814
+ logits=lm_logits,
815
+ past_key_values=transformer_outputs.past_key_values,
816
+ hidden_states=transformer_outputs.hidden_states,
817
+ attentions=transformer_outputs.attentions,
818
+ )
819
+
820
+ @staticmethod
821
+ def _reorder_cache(
822
+ past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
823
+ ) -> Tuple[Tuple[torch.Tensor]]:
824
+ """
825
+ This function is used to re-order the `past_key_values` cache if [`~PretrainedModel.beam_search`] or
826
+ [`~PretrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
827
+ beam_idx at every generation step.
828
+ """
829
+ return tuple(
830
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
831
+ for layer_past in past_key_values
832
+ )
833
+
834
+
835
+ __all__ = ["CodeGenForCausalLM", "CodeGenModel", "CodeGenPreTrainedModel"]
lib/python3.12/site-packages/transformers/models/codegen/tokenization_codegen.py ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The Salesforce authors, The Open AI Team Authors and 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
+ """Tokenization classes for CodeGen"""
16
+
17
+ import json
18
+ import os
19
+ from functools import lru_cache
20
+ from typing import TYPE_CHECKING, List, Optional, Tuple, Union
21
+
22
+ import numpy as np
23
+ import regex as re
24
+
25
+ from ...utils import is_tf_available, is_torch_available, logging, to_py_obj
26
+
27
+
28
+ if TYPE_CHECKING:
29
+ if is_torch_available():
30
+ import torch
31
+ if is_tf_available():
32
+ import tensorflow as tf
33
+
34
+ from ...tokenization_utils import AddedToken, PreTrainedTokenizer
35
+
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+ VOCAB_FILES_NAMES = {
40
+ "vocab_file": "vocab.json",
41
+ "merges_file": "merges.txt",
42
+ }
43
+
44
+
45
+ @lru_cache()
46
+ def bytes_to_unicode():
47
+ """
48
+ Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
49
+ characters the bpe code barfs on.
50
+
51
+ The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
52
+ if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
53
+ decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
54
+ tables between utf-8 bytes and unicode strings.
55
+ """
56
+ bs = (
57
+ list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
58
+ )
59
+ cs = bs[:]
60
+ n = 0
61
+ for b in range(2**8):
62
+ if b not in bs:
63
+ bs.append(b)
64
+ cs.append(2**8 + n)
65
+ n += 1
66
+ cs = [chr(n) for n in cs]
67
+ return dict(zip(bs, cs))
68
+
69
+
70
+ def get_pairs(word):
71
+ """
72
+ Return set of symbol pairs in a word.
73
+
74
+ Word is represented as tuple of symbols (symbols being variable-length strings).
75
+ """
76
+ pairs = set()
77
+ prev_char = word[0]
78
+ for char in word[1:]:
79
+ pairs.add((prev_char, char))
80
+ prev_char = char
81
+ return pairs
82
+
83
+
84
+ class CodeGenTokenizer(PreTrainedTokenizer):
85
+ """
86
+ Construct a CodeGen tokenizer. Based on byte-level Byte-Pair-Encoding.
87
+
88
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
89
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
90
+
91
+ ```python
92
+ >>> from transformers import CodeGenTokenizer
93
+
94
+ >>> tokenizer = CodeGenTokenizer.from_pretrained("Salesforce/codegen-350M-mono")
95
+ >>> tokenizer("Hello world")["input_ids"]
96
+ [15496, 995]
97
+
98
+ >>> tokenizer(" Hello world")["input_ids"]
99
+ [18435, 995]
100
+ ```
101
+
102
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
103
+ call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
104
+
105
+ <Tip>
106
+
107
+ When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).
108
+
109
+ </Tip>
110
+
111
+ This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
112
+ this superclass for more information regarding those methods.
113
+
114
+ Args:
115
+ vocab_file (`str`):
116
+ Path to the vocabulary file.
117
+ merges_file (`str`):
118
+ Path to the merges file.
119
+ errors (`str`, *optional*, defaults to `"replace"`):
120
+ Paradigm to follow when decoding bytes to UTF-8. See
121
+ [bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
122
+ unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
123
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
124
+ token instead.
125
+ bos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
126
+ The beginning of sequence token.
127
+ eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
128
+ The end of sequence token.
129
+ pad_token (`str`, *optional*):
130
+ The token used for padding, for example when batching sequences of different lengths.
131
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
132
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
133
+ other word. (CodeGen tokenizer detect beginning of words by the preceding space).
134
+ add_bos_token (`bool`, *optional*, defaults to `False`):
135
+ Whether to add a beginning of sequence token at the start of sequences.
136
+ return_token_type_ids (`bool`, *optional*, defaults to `False`):
137
+ Whether to return token type IDs.
138
+ """
139
+
140
+ vocab_files_names = VOCAB_FILES_NAMES
141
+ model_input_names = ["input_ids", "attention_mask"]
142
+
143
+ def __init__(
144
+ self,
145
+ vocab_file,
146
+ merges_file,
147
+ errors="replace",
148
+ unk_token="<|endoftext|>",
149
+ bos_token="<|endoftext|>",
150
+ eos_token="<|endoftext|>",
151
+ pad_token=None,
152
+ add_prefix_space=False,
153
+ add_bos_token=False,
154
+ return_token_type_ids=False,
155
+ **kwargs,
156
+ ):
157
+ bos_token = AddedToken(bos_token, special=True) if isinstance(bos_token, str) else bos_token
158
+ eos_token = AddedToken(eos_token, special=True) if isinstance(eos_token, str) else eos_token
159
+ unk_token = AddedToken(unk_token, special=True) if isinstance(unk_token, str) else unk_token
160
+ pad_token = AddedToken(pad_token, special=True) if isinstance(pad_token, str) else pad_token
161
+ self.add_bos_token = add_bos_token
162
+ self.return_token_type_ids = return_token_type_ids
163
+ if self.return_token_type_ids:
164
+ self.model_input_names.append("token_type_ids")
165
+
166
+ with open(vocab_file, encoding="utf-8") as vocab_handle:
167
+ self.encoder = json.load(vocab_handle)
168
+ self.decoder = {v: k for k, v in self.encoder.items()}
169
+ self.errors = errors # how to handle errors in decoding
170
+ self.byte_encoder = bytes_to_unicode()
171
+ self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
172
+ with open(merges_file, encoding="utf-8") as merges_handle:
173
+ bpe_merges = merges_handle.read().split("\n")[1:-1]
174
+ bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
175
+ self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
176
+ self.cache = {}
177
+ self.add_prefix_space = add_prefix_space
178
+
179
+ # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
180
+ self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
181
+ super().__init__(
182
+ errors=errors,
183
+ unk_token=unk_token,
184
+ bos_token=bos_token,
185
+ eos_token=eos_token,
186
+ pad_token=pad_token,
187
+ add_prefix_space=add_prefix_space,
188
+ add_bos_token=add_bos_token,
189
+ return_token_type_ids=return_token_type_ids,
190
+ **kwargs,
191
+ )
192
+
193
+ @property
194
+ def vocab_size(self):
195
+ return len(self.encoder)
196
+
197
+ def get_vocab(self):
198
+ return dict(self.encoder, **self.added_tokens_encoder)
199
+
200
+ def bpe(self, token):
201
+ if token in self.cache:
202
+ return self.cache[token]
203
+ word = tuple(token)
204
+ pairs = get_pairs(word)
205
+
206
+ if not pairs:
207
+ return token
208
+
209
+ while True:
210
+ bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
211
+ if bigram not in self.bpe_ranks:
212
+ break
213
+ first, second = bigram
214
+ new_word = []
215
+ i = 0
216
+ while i < len(word):
217
+ try:
218
+ j = word.index(first, i)
219
+ except ValueError:
220
+ new_word.extend(word[i:])
221
+ break
222
+ else:
223
+ new_word.extend(word[i:j])
224
+ i = j
225
+
226
+ if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
227
+ new_word.append(first + second)
228
+ i += 2
229
+ else:
230
+ new_word.append(word[i])
231
+ i += 1
232
+ new_word = tuple(new_word)
233
+ word = new_word
234
+ if len(word) == 1:
235
+ break
236
+ else:
237
+ pairs = get_pairs(word)
238
+ word = " ".join(word)
239
+ self.cache[token] = word
240
+ return word
241
+
242
+ def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
243
+ if self.add_bos_token:
244
+ bos_token_ids = [self.bos_token_id]
245
+ else:
246
+ bos_token_ids = []
247
+
248
+ output = bos_token_ids + token_ids_0
249
+
250
+ if token_ids_1 is None:
251
+ return output
252
+
253
+ return output + bos_token_ids + token_ids_1
254
+
255
+ def _tokenize(self, text):
256
+ """Tokenize a string."""
257
+ bpe_tokens = []
258
+ for token in re.findall(self.pat, text):
259
+ token = "".join(
260
+ self.byte_encoder[b] for b in token.encode("utf-8")
261
+ ) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
262
+ bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
263
+ return bpe_tokens
264
+
265
+ def _convert_token_to_id(self, token):
266
+ """Converts a token (str) in an id using the vocab."""
267
+ return self.encoder.get(token, self.encoder.get(self.unk_token))
268
+
269
+ def _convert_id_to_token(self, index):
270
+ """Converts an index (integer) in a token (str) using the vocab."""
271
+ return self.decoder.get(index)
272
+
273
+ def convert_tokens_to_string(self, tokens):
274
+ """Converts a sequence of tokens (string) in a single string."""
275
+ text = "".join(tokens)
276
+ text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
277
+ return text
278
+
279
+ def create_token_type_ids_from_sequences(
280
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
281
+ ) -> List[int]:
282
+ """
283
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A sequence
284
+ pair mask has the following format:
285
+
286
+ ```
287
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
288
+ | first sequence | second sequence |
289
+ ```
290
+
291
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
292
+
293
+ Args:
294
+ token_ids_0 (`List[int]`):
295
+ List of IDs.
296
+ token_ids_1 (`List[int]`, *optional*):
297
+ Optional second list of IDs for sequence pairs.
298
+
299
+ Returns:
300
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
301
+ """
302
+ sep = [self.sep_token_id] if self.sep_token_id is not None else []
303
+ cls = [self.cls_token_id] if self.sep_token_id is not None else []
304
+ if token_ids_1 is None:
305
+ return len(cls + token_ids_0 + sep) * [0]
306
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
307
+
308
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
309
+ if not os.path.isdir(save_directory):
310
+ logger.error(f"Vocabulary path ({save_directory}) should be a directory")
311
+ return
312
+ vocab_file = os.path.join(
313
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
314
+ )
315
+ merge_file = os.path.join(
316
+ save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
317
+ )
318
+
319
+ with open(vocab_file, "w", encoding="utf-8") as f:
320
+ f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
321
+
322
+ index = 0
323
+ with open(merge_file, "w", encoding="utf-8") as writer:
324
+ writer.write("#version: 0.2\n")
325
+ for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
326
+ if index != token_index:
327
+ logger.warning(
328
+ f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
329
+ " Please check that the tokenizer is not corrupted!"
330
+ )
331
+ index = token_index
332
+ writer.write(" ".join(bpe_tokens) + "\n")
333
+ index += 1
334
+
335
+ return vocab_file, merge_file
336
+
337
+ def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
338
+ add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
339
+ if is_split_into_words or add_prefix_space:
340
+ text = " " + text
341
+ return (text, kwargs)
342
+
343
+ def decode(
344
+ self,
345
+ token_ids: Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"],
346
+ skip_special_tokens: bool = False,
347
+ clean_up_tokenization_spaces: Optional[bool] = None,
348
+ truncate_before_pattern: Optional[List[str]] = None,
349
+ **kwargs,
350
+ ) -> str:
351
+ """
352
+ Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special
353
+ tokens and clean up tokenization spaces.
354
+
355
+ Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.
356
+
357
+ Args:
358
+ token_ids (`Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]`):
359
+ List of tokenized input ids. Can be obtained using the `__call__` method.
360
+ skip_special_tokens (`bool`, *optional*, defaults to `False`):
361
+ Whether or not to remove special tokens in the decoding.
362
+ clean_up_tokenization_spaces (`bool`, *optional*):
363
+ Whether or not to clean up the tokenization spaces. If `None`, will default to
364
+ `self.clean_up_tokenization_spaces` (available in the `tokenizer_config`).
365
+ truncate_before_pattern (`List[str]`, *optional*, defaults to `None`):
366
+ A list of regular expression strings that will be used to truncate the returned string. This can be
367
+ used to remove extra pieces of code (e.g. truncate if observing a comment symbol "#" at the beginning
368
+ of a new line). An example pattern could be `["^#", re.escape("<|endoftext|>"), "^'''", "\n\n\n"]`.
369
+ kwargs (additional keyword arguments, *optional*):
370
+ Will be passed to the underlying model specific decode method.
371
+
372
+ Returns:
373
+ `str`: The decoded sentence.
374
+ """
375
+
376
+ token_ids = to_py_obj(token_ids)
377
+
378
+ decoded_text = super()._decode(
379
+ token_ids=token_ids,
380
+ skip_special_tokens=skip_special_tokens,
381
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
382
+ **kwargs,
383
+ )
384
+
385
+ if truncate_before_pattern is not None and len(truncate_before_pattern) > 0:
386
+ decoded_text = self.truncate(decoded_text, truncate_before_pattern)
387
+
388
+ return decoded_text
389
+
390
+ def truncate(self, completion, truncate_before_pattern):
391
+ def find_re(string, pattern, start_pos):
392
+ m = pattern.search(string, start_pos)
393
+ return m.start() if m else -1
394
+
395
+ terminals = [re.compile(pattern, re.MULTILINE) for pattern in truncate_before_pattern]
396
+
397
+ prints = list(re.finditer("^print", completion, re.MULTILINE))
398
+
399
+ if len(prints) > 1:
400
+ completion = completion[: prints[1].start()]
401
+
402
+ defs = list(re.finditer("^def", completion, re.MULTILINE))
403
+
404
+ if len(defs) > 1:
405
+ completion = completion[: defs[1].start()]
406
+
407
+ start_pos = 0
408
+
409
+ terminals_pos = [
410
+ pos for pos in [find_re(completion, terminal, start_pos) for terminal in terminals] if pos != -1
411
+ ]
412
+
413
+ if len(terminals_pos) > 0:
414
+ return completion[: min(terminals_pos)]
415
+ else:
416
+ return completion
417
+
418
+
419
+ __all__ = ["CodeGenTokenizer"]
lib/python3.12/site-packages/transformers/models/codegen/tokenization_codegen_fast.py ADDED
@@ -0,0 +1,265 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 The Salesforce authors, The Open AI Team Authors and 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
+ """Tokenization classes for OpenAI GPT."""
16
+
17
+ import re
18
+ from typing import TYPE_CHECKING, List, Optional, Tuple, Union
19
+
20
+ import numpy as np
21
+
22
+ from ...utils import is_tf_available, is_torch_available, logging
23
+
24
+
25
+ if TYPE_CHECKING:
26
+ if is_torch_available():
27
+ import torch
28
+ if is_tf_available():
29
+ import tensorflow as tf
30
+
31
+
32
+ from ...tokenization_utils_base import BatchEncoding
33
+ from ...tokenization_utils_fast import PreTrainedTokenizerFast
34
+ from .tokenization_codegen import CodeGenTokenizer
35
+
36
+
37
+ logger = logging.get_logger(__name__)
38
+
39
+ VOCAB_FILES_NAMES = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
40
+
41
+
42
+ class CodeGenTokenizerFast(PreTrainedTokenizerFast):
43
+ """
44
+ Construct a "fast" CodeGen tokenizer (backed by HuggingFace's *tokenizers* library). Based on byte-level
45
+ Byte-Pair-Encoding.
46
+
47
+ This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
48
+ be encoded differently whether it is at the beginning of the sentence (without space) or not:
49
+
50
+ ```python
51
+ >>> from transformers import CodeGenTokenizerFast
52
+
53
+ >>> tokenizer = CodeGenTokenizerFast.from_pretrained("Salesforce/codegen-350M-mono")
54
+ >>> tokenizer("Hello world")["input_ids"]
55
+ [15496, 995]
56
+
57
+ >>> tokenizer(" Hello world")["input_ids"]
58
+ [18435, 995]
59
+ ```
60
+
61
+ You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer, but since
62
+ the model was not pretrained this way, it might yield a decrease in performance.
63
+
64
+ <Tip>
65
+
66
+ When used with `is_split_into_words=True`, this tokenizer needs to be instantiated with `add_prefix_space=True`.
67
+
68
+ </Tip>
69
+
70
+ This tokenizer inherits from [`PreTrainedTokenizerFast`] which contains most of the main methods. Users should
71
+ refer to this superclass for more information regarding those methods.
72
+
73
+ Args:
74
+ vocab_file (`str`, *optional*):
75
+ Path to the vocabulary file.
76
+ merges_file (`str`, *optional*):
77
+ Path to the merges file.
78
+ tokenizer_file (`str`, *optional*):
79
+ Path to [tokenizers](https://github.com/huggingface/tokenizers) file (generally has a .json extension) that
80
+ contains everything needed to load the tokenizer.
81
+ unk_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
82
+ The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
83
+ token instead.
84
+ bos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
85
+ The beginning of sequence token.
86
+ eos_token (`str`, *optional*, defaults to `"<|endoftext|>"`):
87
+ The end of sequence token.
88
+ add_prefix_space (`bool`, *optional*, defaults to `False`):
89
+ Whether or not to add an initial space to the input. This allows to treat the leading word just as any
90
+ other word. (CodeGen tokenizer detect beginning of words by the preceding space).
91
+ return_token_type_ids (`bool`, *optional*, defaults to `False`):
92
+ Whether to return token type IDs.
93
+ """
94
+
95
+ vocab_files_names = VOCAB_FILES_NAMES
96
+ model_input_names = ["input_ids", "attention_mask"]
97
+ slow_tokenizer_class = CodeGenTokenizer
98
+
99
+ def __init__(
100
+ self,
101
+ vocab_file=None,
102
+ merges_file=None,
103
+ tokenizer_file=None,
104
+ unk_token="<|endoftext|>",
105
+ bos_token="<|endoftext|>",
106
+ eos_token="<|endoftext|>",
107
+ add_prefix_space=False,
108
+ return_token_type_ids=False,
109
+ **kwargs,
110
+ ):
111
+ self.return_token_type_ids = return_token_type_ids
112
+ if self.return_token_type_ids:
113
+ self.model_input_names.append("token_type_ids")
114
+
115
+ super().__init__(
116
+ vocab_file,
117
+ merges_file,
118
+ tokenizer_file=tokenizer_file,
119
+ unk_token=unk_token,
120
+ bos_token=bos_token,
121
+ eos_token=eos_token,
122
+ add_prefix_space=add_prefix_space,
123
+ return_token_type_ids=return_token_type_ids,
124
+ **kwargs,
125
+ )
126
+
127
+ if kwargs.pop("add_bos_token", False):
128
+ model_id = kwargs.pop("name_or_path", "")
129
+ raise ValueError(
130
+ "Currenty GPT2's fast tokenizer does NOT support adding a BOS token. "
131
+ "Instead you should use GPT2's slow tokenizer class `CodeGenTokenizer` as follows: \n"
132
+ f"`CodeGenTokenizer.from_pretrained('{model_id}')`\nor\n"
133
+ f"`AutoTokenizer.from_pretrained('{model_id}', use_fast=False)`\n"
134
+ "This issue will be fixed soon, see: https://github.com/huggingface/tokenizers/pull/1005."
135
+ " so that the fast tokenizer works correctly."
136
+ )
137
+
138
+ def _batch_encode_plus(self, *args, **kwargs) -> BatchEncoding:
139
+ is_split_into_words = kwargs.get("is_split_into_words", False)
140
+ assert self.add_prefix_space or not is_split_into_words, (
141
+ f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
142
+ "to use it with pretokenized inputs."
143
+ )
144
+
145
+ return super()._batch_encode_plus(*args, **kwargs)
146
+
147
+ def _encode_plus(self, *args, **kwargs) -> BatchEncoding:
148
+ is_split_into_words = kwargs.get("is_split_into_words", False)
149
+
150
+ assert self.add_prefix_space or not is_split_into_words, (
151
+ f"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
152
+ "to use it with pretokenized inputs."
153
+ )
154
+
155
+ return super()._encode_plus(*args, **kwargs)
156
+
157
+ # Copied from transformers.models.codegen.tokenization_codegen.CodeGenTokenizer.create_token_type_ids_from_sequences
158
+ def create_token_type_ids_from_sequences(
159
+ self, token_ids_0: List[int], token_ids_1: Optional[List[int]] = None
160
+ ) -> List[int]:
161
+ """
162
+ Create a mask from the two sequences passed to be used in a sequence-pair classification task. A sequence
163
+ pair mask has the following format:
164
+
165
+ ```
166
+ 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1
167
+ | first sequence | second sequence |
168
+ ```
169
+
170
+ If `token_ids_1` is `None`, this method only returns the first portion of the mask (0s).
171
+
172
+ Args:
173
+ token_ids_0 (`List[int]`):
174
+ List of IDs.
175
+ token_ids_1 (`List[int]`, *optional*):
176
+ Optional second list of IDs for sequence pairs.
177
+
178
+ Returns:
179
+ `List[int]`: List of [token type IDs](../glossary#token-type-ids) according to the given sequence(s).
180
+ """
181
+ sep = [self.sep_token_id] if self.sep_token_id is not None else []
182
+ cls = [self.cls_token_id] if self.sep_token_id is not None else []
183
+ if token_ids_1 is None:
184
+ return len(cls + token_ids_0 + sep) * [0]
185
+ return len(cls + token_ids_0 + sep) * [0] + len(token_ids_1 + sep) * [1]
186
+
187
+ def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
188
+ files = self._tokenizer.model.save(save_directory, name=filename_prefix)
189
+ return tuple(files)
190
+
191
+ def decode(
192
+ self,
193
+ token_ids: Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"],
194
+ skip_special_tokens: bool = False,
195
+ clean_up_tokenization_spaces: Optional[bool] = None,
196
+ truncate_before_pattern: Optional[List[str]] = None,
197
+ **kwargs,
198
+ ) -> str:
199
+ """
200
+ Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special
201
+ tokens and clean up tokenization spaces.
202
+
203
+ Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.
204
+
205
+ Args:
206
+ token_ids (`Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]`):
207
+ List of tokenized input ids. Can be obtained using the `__call__` method.
208
+ skip_special_tokens (`bool`, *optional*, defaults to `False`):
209
+ Whether or not to remove special tokens in the decoding.
210
+ clean_up_tokenization_spaces (`bool`, *optional*):
211
+ Whether or not to clean up the tokenization spaces. If `None`, will default to
212
+ `self.clean_up_tokenization_spaces` (available in the `tokenizer_config`).
213
+ truncate_before_pattern (`List[str]`, *optional*, defaults to `None`):
214
+ A list of regular expression strings that will be used to truncate the returned string. This can be
215
+ used to remove extra pieces of code (e.g. truncate if observing a comment symbol "#" at the beginning
216
+ of a new line). An example pattern could be `["^#", re.escape("<|endoftext|>"), "^'''", "\n\n\n"]`.
217
+ kwargs (additional keyword arguments, *optional*):
218
+ Will be passed to the underlying model specific decode method.
219
+
220
+ Returns:
221
+ `str`: The decoded sentence.
222
+ """
223
+
224
+ decoded_text = super().decode(
225
+ token_ids=token_ids,
226
+ skip_special_tokens=skip_special_tokens,
227
+ clean_up_tokenization_spaces=clean_up_tokenization_spaces,
228
+ **kwargs,
229
+ )
230
+
231
+ if truncate_before_pattern is not None and len(truncate_before_pattern) > 0:
232
+ decoded_text = self.truncate(decoded_text, truncate_before_pattern)
233
+
234
+ return decoded_text
235
+
236
+ def truncate(self, completion, truncate_before_pattern):
237
+ def find_re(string, pattern, start_pos):
238
+ m = pattern.search(string, start_pos)
239
+ return m.start() if m else -1
240
+
241
+ terminals = [re.compile(pattern, re.MULTILINE) for pattern in truncate_before_pattern]
242
+
243
+ prints = list(re.finditer("^print", completion, re.MULTILINE))
244
+
245
+ if len(prints) > 1:
246
+ completion = completion[: prints[1].start()]
247
+
248
+ defs = list(re.finditer("^def", completion, re.MULTILINE))
249
+
250
+ if len(defs) > 1:
251
+ completion = completion[: defs[1].start()]
252
+
253
+ start_pos = 0
254
+
255
+ terminals_pos = [
256
+ pos for pos in [find_re(completion, terminal, start_pos) for terminal in terminals] if pos != -1
257
+ ]
258
+
259
+ if len(terminals_pos) > 0:
260
+ return completion[: min(terminals_pos)]
261
+ else:
262
+ return completion
263
+
264
+
265
+ __all__ = ["CodeGenTokenizerFast"]
lib/python3.12/site-packages/transformers/models/conditional_detr/__init__.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_conditional_detr import *
22
+ from .feature_extraction_conditional_detr import *
23
+ from .image_processing_conditional_detr import *
24
+ from .modeling_conditional_detr import *
25
+ else:
26
+ import sys
27
+
28
+ _file = globals()["__file__"]
29
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (795 Bytes). View file
 
lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/configuration_conditional_detr.cpython-312.pyc ADDED
Binary file (12.9 kB). View file
 
lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/feature_extraction_conditional_detr.cpython-312.pyc ADDED
Binary file (1.71 kB). View file
 
lib/python3.12/site-packages/transformers/models/conditional_detr/__pycache__/image_processing_conditional_detr.cpython-312.pyc ADDED
Binary file (84.1 kB). View file
 
lib/python3.12/site-packages/transformers/models/conditional_detr/configuration_conditional_detr.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Conditional DETR model configuration"""
16
+
17
+ from collections import OrderedDict
18
+ from typing import Mapping
19
+
20
+ from packaging import version
21
+
22
+ from ...configuration_utils import PretrainedConfig
23
+ from ...onnx import OnnxConfig
24
+ from ...utils import logging
25
+ from ...utils.backbone_utils import verify_backbone_config_arguments
26
+ from ..auto import CONFIG_MAPPING
27
+
28
+
29
+ logger = logging.get_logger(__name__)
30
+
31
+
32
+ class ConditionalDetrConfig(PretrainedConfig):
33
+ r"""
34
+ This is the configuration class to store the configuration of a [`ConditionalDetrModel`]. It is used to instantiate
35
+ a Conditional DETR model according to the specified arguments, defining the model architecture. Instantiating a
36
+ configuration with the defaults will yield a similar configuration to that of the Conditional DETR
37
+ [microsoft/conditional-detr-resnet-50](https://huggingface.co/microsoft/conditional-detr-resnet-50) 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
+ use_timm_backbone (`bool`, *optional*, defaults to `True`):
44
+ Whether or not to use the `timm` library for the backbone. If set to `False`, will use the [`AutoBackbone`]
45
+ API.
46
+ backbone_config (`PretrainedConfig` or `dict`, *optional*):
47
+ The configuration of the backbone model. Only used in case `use_timm_backbone` is set to `False` in which
48
+ case it will default to `ResNetConfig()`.
49
+ num_channels (`int`, *optional*, defaults to 3):
50
+ The number of input channels.
51
+ num_queries (`int`, *optional*, defaults to 100):
52
+ Number of object queries, i.e. detection slots. This is the maximal number of objects
53
+ [`ConditionalDetrModel`] can detect in a single image. For COCO, we recommend 100 queries.
54
+ d_model (`int`, *optional*, defaults to 256):
55
+ This parameter is a general dimension parameter, defining dimensions for components such as the encoder layer and projection parameters in the decoder layer, among others.
56
+ encoder_layers (`int`, *optional*, defaults to 6):
57
+ Number of encoder layers.
58
+ decoder_layers (`int`, *optional*, defaults to 6):
59
+ Number of decoder layers.
60
+ encoder_attention_heads (`int`, *optional*, defaults to 8):
61
+ Number of attention heads for each attention layer in the Transformer encoder.
62
+ decoder_attention_heads (`int`, *optional*, defaults to 8):
63
+ Number of attention heads for each attention layer in the Transformer decoder.
64
+ decoder_ffn_dim (`int`, *optional*, defaults to 2048):
65
+ Dimension of the "intermediate" (often named feed-forward) layer in decoder.
66
+ encoder_ffn_dim (`int`, *optional*, defaults to 2048):
67
+ Dimension of the "intermediate" (often named feed-forward) layer in decoder.
68
+ activation_function (`str` or `function`, *optional*, defaults to `"relu"`):
69
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
70
+ `"relu"`, `"silu"` and `"gelu_new"` are supported.
71
+ dropout (`float`, *optional*, defaults to 0.1):
72
+ The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
73
+ attention_dropout (`float`, *optional*, defaults to 0.0):
74
+ The dropout ratio for the attention probabilities.
75
+ activation_dropout (`float`, *optional*, defaults to 0.0):
76
+ The dropout ratio for activations inside the fully connected layer.
77
+ init_std (`float`, *optional*, defaults to 0.02):
78
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
79
+ init_xavier_std (`float`, *optional*, defaults to 1):
80
+ The scaling factor used for the Xavier initialization gain in the HM Attention map module.
81
+ encoder_layerdrop (`float`, *optional*, defaults to 0.0):
82
+ The LayerDrop probability for the encoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
83
+ for more details.
84
+ decoder_layerdrop (`float`, *optional*, defaults to 0.0):
85
+ The LayerDrop probability for the decoder. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556)
86
+ for more details.
87
+ auxiliary_loss (`bool`, *optional*, defaults to `False`):
88
+ Whether auxiliary decoding losses (loss at each decoder layer) are to be used.
89
+ position_embedding_type (`str`, *optional*, defaults to `"sine"`):
90
+ Type of position embeddings to be used on top of the image features. One of `"sine"` or `"learned"`.
91
+ backbone (`str`, *optional*, defaults to `"resnet50"`):
92
+ Name of backbone to use when `backbone_config` is `None`. If `use_pretrained_backbone` is `True`, this
93
+ will load the corresponding pretrained weights from the timm or transformers library. If `use_pretrained_backbone`
94
+ is `False`, this loads the backbone's config and uses that to initialize the backbone with random weights.
95
+ use_pretrained_backbone (`bool`, *optional*, defaults to `True`):
96
+ Whether to use pretrained weights for the backbone.
97
+ backbone_kwargs (`dict`, *optional*):
98
+ Keyword arguments to be passed to AutoBackbone when loading from a checkpoint
99
+ e.g. `{'out_indices': (0, 1, 2, 3)}`. Cannot be specified if `backbone_config` is set.
100
+ dilation (`bool`, *optional*, defaults to `False`):
101
+ Whether to replace stride with dilation in the last convolutional block (DC5). Only supported when
102
+ `use_timm_backbone` = `True`.
103
+ class_cost (`float`, *optional*, defaults to 1):
104
+ Relative weight of the classification error in the Hungarian matching cost.
105
+ bbox_cost (`float`, *optional*, defaults to 5):
106
+ Relative weight of the L1 error of the bounding box coordinates in the Hungarian matching cost.
107
+ giou_cost (`float`, *optional*, defaults to 2):
108
+ Relative weight of the generalized IoU loss of the bounding box in the Hungarian matching cost.
109
+ mask_loss_coefficient (`float`, *optional*, defaults to 1):
110
+ Relative weight of the Focal loss in the panoptic segmentation loss.
111
+ dice_loss_coefficient (`float`, *optional*, defaults to 1):
112
+ Relative weight of the DICE/F-1 loss in the panoptic segmentation loss.
113
+ bbox_loss_coefficient (`float`, *optional*, defaults to 5):
114
+ Relative weight of the L1 bounding box loss in the object detection loss.
115
+ giou_loss_coefficient (`float`, *optional*, defaults to 2):
116
+ Relative weight of the generalized IoU loss in the object detection loss.
117
+ eos_coefficient (`float`, *optional*, defaults to 0.1):
118
+ Relative classification weight of the 'no-object' class in the object detection loss.
119
+ focal_alpha (`float`, *optional*, defaults to 0.25):
120
+ Alpha parameter in the focal loss.
121
+
122
+ Examples:
123
+
124
+ ```python
125
+ >>> from transformers import ConditionalDetrConfig, ConditionalDetrModel
126
+
127
+ >>> # Initializing a Conditional DETR microsoft/conditional-detr-resnet-50 style configuration
128
+ >>> configuration = ConditionalDetrConfig()
129
+
130
+ >>> # Initializing a model (with random weights) from the microsoft/conditional-detr-resnet-50 style configuration
131
+ >>> model = ConditionalDetrModel(configuration)
132
+
133
+ >>> # Accessing the model configuration
134
+ >>> configuration = model.config
135
+ ```"""
136
+
137
+ model_type = "conditional_detr"
138
+ keys_to_ignore_at_inference = ["past_key_values"]
139
+ attribute_map = {
140
+ "hidden_size": "d_model",
141
+ "num_attention_heads": "encoder_attention_heads",
142
+ }
143
+
144
+ def __init__(
145
+ self,
146
+ use_timm_backbone=True,
147
+ backbone_config=None,
148
+ num_channels=3,
149
+ num_queries=300,
150
+ encoder_layers=6,
151
+ encoder_ffn_dim=2048,
152
+ encoder_attention_heads=8,
153
+ decoder_layers=6,
154
+ decoder_ffn_dim=2048,
155
+ decoder_attention_heads=8,
156
+ encoder_layerdrop=0.0,
157
+ decoder_layerdrop=0.0,
158
+ is_encoder_decoder=True,
159
+ activation_function="relu",
160
+ d_model=256,
161
+ dropout=0.1,
162
+ attention_dropout=0.0,
163
+ activation_dropout=0.0,
164
+ init_std=0.02,
165
+ init_xavier_std=1.0,
166
+ auxiliary_loss=False,
167
+ position_embedding_type="sine",
168
+ backbone="resnet50",
169
+ use_pretrained_backbone=True,
170
+ backbone_kwargs=None,
171
+ dilation=False,
172
+ class_cost=2,
173
+ bbox_cost=5,
174
+ giou_cost=2,
175
+ mask_loss_coefficient=1,
176
+ dice_loss_coefficient=1,
177
+ cls_loss_coefficient=2,
178
+ bbox_loss_coefficient=5,
179
+ giou_loss_coefficient=2,
180
+ focal_alpha=0.25,
181
+ **kwargs,
182
+ ):
183
+ # We default to values which were previously hard-coded in the model. This enables configurability of the config
184
+ # while keeping the default behavior the same.
185
+ if use_timm_backbone and backbone_kwargs is None:
186
+ backbone_kwargs = {}
187
+ if dilation:
188
+ backbone_kwargs["output_stride"] = 16
189
+ backbone_kwargs["out_indices"] = [1, 2, 3, 4]
190
+ backbone_kwargs["in_chans"] = num_channels
191
+ # Backwards compatibility
192
+ elif not use_timm_backbone and backbone in (None, "resnet50"):
193
+ if backbone_config is None:
194
+ logger.info("`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.")
195
+ backbone_config = CONFIG_MAPPING["resnet"](out_features=["stage4"])
196
+ elif isinstance(backbone_config, dict):
197
+ backbone_model_type = backbone_config.get("model_type")
198
+ config_class = CONFIG_MAPPING[backbone_model_type]
199
+ backbone_config = config_class.from_dict(backbone_config)
200
+
201
+ verify_backbone_config_arguments(
202
+ use_timm_backbone=use_timm_backbone,
203
+ use_pretrained_backbone=use_pretrained_backbone,
204
+ backbone=backbone,
205
+ backbone_config=backbone_config,
206
+ backbone_kwargs=backbone_kwargs,
207
+ )
208
+
209
+ self.use_timm_backbone = use_timm_backbone
210
+ self.backbone_config = backbone_config
211
+ self.num_channels = num_channels
212
+ self.num_queries = num_queries
213
+ self.d_model = d_model
214
+ self.encoder_ffn_dim = encoder_ffn_dim
215
+ self.encoder_layers = encoder_layers
216
+ self.encoder_attention_heads = encoder_attention_heads
217
+ self.decoder_ffn_dim = decoder_ffn_dim
218
+ self.decoder_layers = decoder_layers
219
+ self.decoder_attention_heads = decoder_attention_heads
220
+ self.dropout = dropout
221
+ self.attention_dropout = attention_dropout
222
+ self.activation_dropout = activation_dropout
223
+ self.activation_function = activation_function
224
+ self.init_std = init_std
225
+ self.init_xavier_std = init_xavier_std
226
+ self.encoder_layerdrop = encoder_layerdrop
227
+ self.decoder_layerdrop = decoder_layerdrop
228
+ self.num_hidden_layers = encoder_layers
229
+ self.auxiliary_loss = auxiliary_loss
230
+ self.position_embedding_type = position_embedding_type
231
+ self.backbone = backbone
232
+ self.use_pretrained_backbone = use_pretrained_backbone
233
+ self.backbone_kwargs = backbone_kwargs
234
+ self.dilation = dilation
235
+ # Hungarian matcher
236
+ self.class_cost = class_cost
237
+ self.bbox_cost = bbox_cost
238
+ self.giou_cost = giou_cost
239
+ # Loss coefficients
240
+ self.mask_loss_coefficient = mask_loss_coefficient
241
+ self.dice_loss_coefficient = dice_loss_coefficient
242
+ self.cls_loss_coefficient = cls_loss_coefficient
243
+ self.bbox_loss_coefficient = bbox_loss_coefficient
244
+ self.giou_loss_coefficient = giou_loss_coefficient
245
+ self.focal_alpha = focal_alpha
246
+ super().__init__(is_encoder_decoder=is_encoder_decoder, **kwargs)
247
+
248
+ @property
249
+ def num_attention_heads(self) -> int:
250
+ return self.encoder_attention_heads
251
+
252
+ @property
253
+ def hidden_size(self) -> int:
254
+ return self.d_model
255
+
256
+
257
+ class ConditionalDetrOnnxConfig(OnnxConfig):
258
+ torch_onnx_minimum_version = version.parse("1.11")
259
+
260
+ @property
261
+ def inputs(self) -> Mapping[str, Mapping[int, str]]:
262
+ return OrderedDict(
263
+ [
264
+ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
265
+ ("pixel_mask", {0: "batch"}),
266
+ ]
267
+ )
268
+
269
+ @property
270
+ def atol_for_validation(self) -> float:
271
+ return 1e-5
272
+
273
+ @property
274
+ def default_onnx_opset(self) -> int:
275
+ return 12
276
+
277
+
278
+ __all__ = ["ConditionalDetrConfig", "ConditionalDetrOnnxConfig"]
lib/python3.12/site-packages/transformers/models/conditional_detr/feature_extraction_conditional_detr.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Conditional DETR."""
16
+
17
+ import warnings
18
+
19
+ from ...image_transforms import rgb_to_id as _rgb_to_id
20
+ from ...utils import logging
21
+ from .image_processing_conditional_detr import ConditionalDetrImageProcessor
22
+
23
+
24
+ logger = logging.get_logger(__name__)
25
+
26
+
27
+ def rgb_to_id(x):
28
+ warnings.warn(
29
+ "rgb_to_id has moved and will not be importable from this module from v5. "
30
+ "Please import from transformers.image_transforms instead.",
31
+ FutureWarning,
32
+ )
33
+ return _rgb_to_id(x)
34
+
35
+
36
+ class ConditionalDetrFeatureExtractor(ConditionalDetrImageProcessor):
37
+ def __init__(self, *args, **kwargs) -> None:
38
+ warnings.warn(
39
+ "The class ConditionalDetrFeatureExtractor is deprecated and will be removed in version 5 of Transformers."
40
+ " Please use ConditionalDetrImageProcessor instead.",
41
+ FutureWarning,
42
+ )
43
+ super().__init__(*args, **kwargs)
44
+
45
+
46
+ __all__ = ["ConditionalDetrFeatureExtractor"]
lib/python3.12/site-packages/transformers/models/conditional_detr/image_processing_conditional_detr.py ADDED
@@ -0,0 +1,1855 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Conditional DETR."""
16
+
17
+ import io
18
+ import pathlib
19
+ from collections import defaultdict
20
+ from typing import Any, Callable, Dict, Iterable, List, Optional, Set, Tuple, Union
21
+
22
+ import numpy as np
23
+
24
+ from ...feature_extraction_utils import BatchFeature
25
+ from ...image_processing_utils import BaseImageProcessor, get_size_dict
26
+ from ...image_transforms import (
27
+ PaddingMode,
28
+ center_to_corners_format,
29
+ corners_to_center_format,
30
+ id_to_rgb,
31
+ pad,
32
+ rescale,
33
+ resize,
34
+ rgb_to_id,
35
+ to_channel_dimension_format,
36
+ )
37
+ from ...image_utils import (
38
+ IMAGENET_DEFAULT_MEAN,
39
+ IMAGENET_DEFAULT_STD,
40
+ AnnotationFormat,
41
+ AnnotationType,
42
+ ChannelDimension,
43
+ ImageInput,
44
+ PILImageResampling,
45
+ get_image_size,
46
+ infer_channel_dimension_format,
47
+ is_scaled_image,
48
+ make_list_of_images,
49
+ to_numpy_array,
50
+ valid_images,
51
+ validate_annotations,
52
+ validate_kwargs,
53
+ validate_preprocess_arguments,
54
+ )
55
+ from ...utils import (
56
+ TensorType,
57
+ is_flax_available,
58
+ is_jax_tensor,
59
+ is_scipy_available,
60
+ is_tf_available,
61
+ is_tf_tensor,
62
+ is_torch_available,
63
+ is_torch_tensor,
64
+ is_vision_available,
65
+ logging,
66
+ )
67
+
68
+
69
+ if is_torch_available():
70
+ import torch
71
+ from torch import nn
72
+
73
+
74
+ if is_vision_available():
75
+ import PIL
76
+
77
+
78
+ if is_scipy_available():
79
+ import scipy.special
80
+ import scipy.stats
81
+
82
+
83
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
84
+
85
+
86
+ SUPPORTED_ANNOTATION_FORMATS = (AnnotationFormat.COCO_DETECTION, AnnotationFormat.COCO_PANOPTIC)
87
+
88
+
89
+ # Copied from transformers.models.detr.image_processing_detr.get_size_with_aspect_ratio
90
+ def get_size_with_aspect_ratio(image_size, size, max_size=None) -> Tuple[int, int]:
91
+ """
92
+ Computes the output image size given the input image size and the desired output size.
93
+
94
+ Args:
95
+ image_size (`Tuple[int, int]`):
96
+ The input image size.
97
+ size (`int`):
98
+ The desired output size.
99
+ max_size (`int`, *optional*):
100
+ The maximum allowed output size.
101
+ """
102
+ height, width = image_size
103
+ raw_size = None
104
+ if max_size is not None:
105
+ min_original_size = float(min((height, width)))
106
+ max_original_size = float(max((height, width)))
107
+ if max_original_size / min_original_size * size > max_size:
108
+ raw_size = max_size * min_original_size / max_original_size
109
+ size = int(round(raw_size))
110
+
111
+ if (height <= width and height == size) or (width <= height and width == size):
112
+ oh, ow = height, width
113
+ elif width < height:
114
+ ow = size
115
+ if max_size is not None and raw_size is not None:
116
+ oh = int(raw_size * height / width)
117
+ else:
118
+ oh = int(size * height / width)
119
+ else:
120
+ oh = size
121
+ if max_size is not None and raw_size is not None:
122
+ ow = int(raw_size * width / height)
123
+ else:
124
+ ow = int(size * width / height)
125
+
126
+ return (oh, ow)
127
+
128
+
129
+ # Copied from transformers.models.detr.image_processing_detr.get_resize_output_image_size
130
+ def get_resize_output_image_size(
131
+ input_image: np.ndarray,
132
+ size: Union[int, Tuple[int, int], List[int]],
133
+ max_size: Optional[int] = None,
134
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
135
+ ) -> Tuple[int, int]:
136
+ """
137
+ Computes the output image size given the input image size and the desired output size. If the desired output size
138
+ is a tuple or list, the output image size is returned as is. If the desired output size is an integer, the output
139
+ image size is computed by keeping the aspect ratio of the input image size.
140
+
141
+ Args:
142
+ input_image (`np.ndarray`):
143
+ The image to resize.
144
+ size (`int` or `Tuple[int, int]` or `List[int]`):
145
+ The desired output size.
146
+ max_size (`int`, *optional*):
147
+ The maximum allowed output size.
148
+ input_data_format (`ChannelDimension` or `str`, *optional*):
149
+ The channel dimension format of the input image. If not provided, it will be inferred from the input image.
150
+ """
151
+ image_size = get_image_size(input_image, input_data_format)
152
+ if isinstance(size, (list, tuple)):
153
+ return size
154
+
155
+ return get_size_with_aspect_ratio(image_size, size, max_size)
156
+
157
+
158
+ # Copied from transformers.models.detr.image_processing_detr.get_image_size_for_max_height_width
159
+ def get_image_size_for_max_height_width(
160
+ input_image: np.ndarray,
161
+ max_height: int,
162
+ max_width: int,
163
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
164
+ ) -> Tuple[int, int]:
165
+ """
166
+ Computes the output image size given the input image and the maximum allowed height and width. Keep aspect ratio.
167
+ Important, even if image_height < max_height and image_width < max_width, the image will be resized
168
+ to at least one of the edges be equal to max_height or max_width.
169
+
170
+ For example:
171
+ - input_size: (100, 200), max_height: 50, max_width: 50 -> output_size: (25, 50)
172
+ - input_size: (100, 200), max_height: 200, max_width: 500 -> output_size: (200, 400)
173
+
174
+ Args:
175
+ input_image (`np.ndarray`):
176
+ The image to resize.
177
+ max_height (`int`):
178
+ The maximum allowed height.
179
+ max_width (`int`):
180
+ The maximum allowed width.
181
+ input_data_format (`ChannelDimension` or `str`, *optional*):
182
+ The channel dimension format of the input image. If not provided, it will be inferred from the input image.
183
+ """
184
+ image_size = get_image_size(input_image, input_data_format)
185
+ height, width = image_size
186
+ height_scale = max_height / height
187
+ width_scale = max_width / width
188
+ min_scale = min(height_scale, width_scale)
189
+ new_height = int(height * min_scale)
190
+ new_width = int(width * min_scale)
191
+ return new_height, new_width
192
+
193
+
194
+ # Copied from transformers.models.detr.image_processing_detr.get_numpy_to_framework_fn
195
+ def get_numpy_to_framework_fn(arr) -> Callable:
196
+ """
197
+ Returns a function that converts a numpy array to the framework of the input array.
198
+
199
+ Args:
200
+ arr (`np.ndarray`): The array to convert.
201
+ """
202
+ if isinstance(arr, np.ndarray):
203
+ return np.array
204
+ if is_tf_available() and is_tf_tensor(arr):
205
+ import tensorflow as tf
206
+
207
+ return tf.convert_to_tensor
208
+ if is_torch_available() and is_torch_tensor(arr):
209
+ import torch
210
+
211
+ return torch.tensor
212
+ if is_flax_available() and is_jax_tensor(arr):
213
+ import jax.numpy as jnp
214
+
215
+ return jnp.array
216
+ raise ValueError(f"Cannot convert arrays of type {type(arr)}")
217
+
218
+
219
+ # Copied from transformers.models.detr.image_processing_detr.safe_squeeze
220
+ def safe_squeeze(arr: np.ndarray, axis: Optional[int] = None) -> np.ndarray:
221
+ """
222
+ Squeezes an array, but only if the axis specified has dim 1.
223
+ """
224
+ if axis is None:
225
+ return arr.squeeze()
226
+
227
+ try:
228
+ return arr.squeeze(axis=axis)
229
+ except ValueError:
230
+ return arr
231
+
232
+
233
+ # Copied from transformers.models.detr.image_processing_detr.normalize_annotation
234
+ def normalize_annotation(annotation: Dict, image_size: Tuple[int, int]) -> Dict:
235
+ image_height, image_width = image_size
236
+ norm_annotation = {}
237
+ for key, value in annotation.items():
238
+ if key == "boxes":
239
+ boxes = value
240
+ boxes = corners_to_center_format(boxes)
241
+ boxes /= np.asarray([image_width, image_height, image_width, image_height], dtype=np.float32)
242
+ norm_annotation[key] = boxes
243
+ else:
244
+ norm_annotation[key] = value
245
+ return norm_annotation
246
+
247
+
248
+ # Copied from transformers.models.detr.image_processing_detr.max_across_indices
249
+ def max_across_indices(values: Iterable[Any]) -> List[Any]:
250
+ """
251
+ Return the maximum value across all indices of an iterable of values.
252
+ """
253
+ return [max(values_i) for values_i in zip(*values)]
254
+
255
+
256
+ # Copied from transformers.models.detr.image_processing_detr.get_max_height_width
257
+ def get_max_height_width(
258
+ images: List[np.ndarray], input_data_format: Optional[Union[str, ChannelDimension]] = None
259
+ ) -> List[int]:
260
+ """
261
+ Get the maximum height and width across all images in a batch.
262
+ """
263
+ if input_data_format is None:
264
+ input_data_format = infer_channel_dimension_format(images[0])
265
+
266
+ if input_data_format == ChannelDimension.FIRST:
267
+ _, max_height, max_width = max_across_indices([img.shape for img in images])
268
+ elif input_data_format == ChannelDimension.LAST:
269
+ max_height, max_width, _ = max_across_indices([img.shape for img in images])
270
+ else:
271
+ raise ValueError(f"Invalid channel dimension format: {input_data_format}")
272
+ return (max_height, max_width)
273
+
274
+
275
+ # Copied from transformers.models.detr.image_processing_detr.make_pixel_mask
276
+ def make_pixel_mask(
277
+ image: np.ndarray, output_size: Tuple[int, int], input_data_format: Optional[Union[str, ChannelDimension]] = None
278
+ ) -> np.ndarray:
279
+ """
280
+ Make a pixel mask for the image, where 1 indicates a valid pixel and 0 indicates padding.
281
+
282
+ Args:
283
+ image (`np.ndarray`):
284
+ Image to make the pixel mask for.
285
+ output_size (`Tuple[int, int]`):
286
+ Output size of the mask.
287
+ """
288
+ input_height, input_width = get_image_size(image, channel_dim=input_data_format)
289
+ mask = np.zeros(output_size, dtype=np.int64)
290
+ mask[:input_height, :input_width] = 1
291
+ return mask
292
+
293
+
294
+ # Copied from transformers.models.detr.image_processing_detr.convert_coco_poly_to_mask
295
+ def convert_coco_poly_to_mask(segmentations, height: int, width: int) -> np.ndarray:
296
+ """
297
+ Convert a COCO polygon annotation to a mask.
298
+
299
+ Args:
300
+ segmentations (`List[List[float]]`):
301
+ List of polygons, each polygon represented by a list of x-y coordinates.
302
+ height (`int`):
303
+ Height of the mask.
304
+ width (`int`):
305
+ Width of the mask.
306
+ """
307
+ try:
308
+ from pycocotools import mask as coco_mask
309
+ except ImportError:
310
+ raise ImportError("Pycocotools is not installed in your environment.")
311
+
312
+ masks = []
313
+ for polygons in segmentations:
314
+ rles = coco_mask.frPyObjects(polygons, height, width)
315
+ mask = coco_mask.decode(rles)
316
+ if len(mask.shape) < 3:
317
+ mask = mask[..., None]
318
+ mask = np.asarray(mask, dtype=np.uint8)
319
+ mask = np.any(mask, axis=2)
320
+ masks.append(mask)
321
+ if masks:
322
+ masks = np.stack(masks, axis=0)
323
+ else:
324
+ masks = np.zeros((0, height, width), dtype=np.uint8)
325
+
326
+ return masks
327
+
328
+
329
+ # Copied from transformers.models.detr.image_processing_detr.prepare_coco_detection_annotation with DETR->ConditionalDetr
330
+ def prepare_coco_detection_annotation(
331
+ image,
332
+ target,
333
+ return_segmentation_masks: bool = False,
334
+ input_data_format: Optional[Union[ChannelDimension, str]] = None,
335
+ ):
336
+ """
337
+ Convert the target in COCO format into the format expected by ConditionalDetr.
338
+ """
339
+ image_height, image_width = get_image_size(image, channel_dim=input_data_format)
340
+
341
+ image_id = target["image_id"]
342
+ image_id = np.asarray([image_id], dtype=np.int64)
343
+
344
+ # Get all COCO annotations for the given image.
345
+ annotations = target["annotations"]
346
+ annotations = [obj for obj in annotations if "iscrowd" not in obj or obj["iscrowd"] == 0]
347
+
348
+ classes = [obj["category_id"] for obj in annotations]
349
+ classes = np.asarray(classes, dtype=np.int64)
350
+
351
+ # for conversion to coco api
352
+ area = np.asarray([obj["area"] for obj in annotations], dtype=np.float32)
353
+ iscrowd = np.asarray([obj["iscrowd"] if "iscrowd" in obj else 0 for obj in annotations], dtype=np.int64)
354
+
355
+ boxes = [obj["bbox"] for obj in annotations]
356
+ # guard against no boxes via resizing
357
+ boxes = np.asarray(boxes, dtype=np.float32).reshape(-1, 4)
358
+ boxes[:, 2:] += boxes[:, :2]
359
+ boxes[:, 0::2] = boxes[:, 0::2].clip(min=0, max=image_width)
360
+ boxes[:, 1::2] = boxes[:, 1::2].clip(min=0, max=image_height)
361
+
362
+ keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0])
363
+
364
+ new_target = {}
365
+ new_target["image_id"] = image_id
366
+ new_target["class_labels"] = classes[keep]
367
+ new_target["boxes"] = boxes[keep]
368
+ new_target["area"] = area[keep]
369
+ new_target["iscrowd"] = iscrowd[keep]
370
+ new_target["orig_size"] = np.asarray([int(image_height), int(image_width)], dtype=np.int64)
371
+
372
+ if annotations and "keypoints" in annotations[0]:
373
+ keypoints = [obj["keypoints"] for obj in annotations]
374
+ # Converting the filtered keypoints list to a numpy array
375
+ keypoints = np.asarray(keypoints, dtype=np.float32)
376
+ # Apply the keep mask here to filter the relevant annotations
377
+ keypoints = keypoints[keep]
378
+ num_keypoints = keypoints.shape[0]
379
+ keypoints = keypoints.reshape((-1, 3)) if num_keypoints else keypoints
380
+ new_target["keypoints"] = keypoints
381
+
382
+ if return_segmentation_masks:
383
+ segmentation_masks = [obj["segmentation"] for obj in annotations]
384
+ masks = convert_coco_poly_to_mask(segmentation_masks, image_height, image_width)
385
+ new_target["masks"] = masks[keep]
386
+
387
+ return new_target
388
+
389
+
390
+ # Copied from transformers.models.detr.image_processing_detr.masks_to_boxes
391
+ def masks_to_boxes(masks: np.ndarray) -> np.ndarray:
392
+ """
393
+ Compute the bounding boxes around the provided panoptic segmentation masks.
394
+
395
+ Args:
396
+ masks: masks in format `[number_masks, height, width]` where N is the number of masks
397
+
398
+ Returns:
399
+ boxes: bounding boxes in format `[number_masks, 4]` in xyxy format
400
+ """
401
+ if masks.size == 0:
402
+ return np.zeros((0, 4))
403
+
404
+ h, w = masks.shape[-2:]
405
+ y = np.arange(0, h, dtype=np.float32)
406
+ x = np.arange(0, w, dtype=np.float32)
407
+ # see https://github.com/pytorch/pytorch/issues/50276
408
+ y, x = np.meshgrid(y, x, indexing="ij")
409
+
410
+ x_mask = masks * np.expand_dims(x, axis=0)
411
+ x_max = x_mask.reshape(x_mask.shape[0], -1).max(-1)
412
+ x = np.ma.array(x_mask, mask=~(np.array(masks, dtype=bool)))
413
+ x_min = x.filled(fill_value=1e8)
414
+ x_min = x_min.reshape(x_min.shape[0], -1).min(-1)
415
+
416
+ y_mask = masks * np.expand_dims(y, axis=0)
417
+ y_max = y_mask.reshape(x_mask.shape[0], -1).max(-1)
418
+ y = np.ma.array(y_mask, mask=~(np.array(masks, dtype=bool)))
419
+ y_min = y.filled(fill_value=1e8)
420
+ y_min = y_min.reshape(y_min.shape[0], -1).min(-1)
421
+
422
+ return np.stack([x_min, y_min, x_max, y_max], 1)
423
+
424
+
425
+ # Copied from transformers.models.detr.image_processing_detr.prepare_coco_panoptic_annotation with DETR->ConditionalDetr
426
+ def prepare_coco_panoptic_annotation(
427
+ image: np.ndarray,
428
+ target: Dict,
429
+ masks_path: Union[str, pathlib.Path],
430
+ return_masks: bool = True,
431
+ input_data_format: Union[ChannelDimension, str] = None,
432
+ ) -> Dict:
433
+ """
434
+ Prepare a coco panoptic annotation for ConditionalDetr.
435
+ """
436
+ image_height, image_width = get_image_size(image, channel_dim=input_data_format)
437
+ annotation_path = pathlib.Path(masks_path) / target["file_name"]
438
+
439
+ new_target = {}
440
+ new_target["image_id"] = np.asarray([target["image_id"] if "image_id" in target else target["id"]], dtype=np.int64)
441
+ new_target["size"] = np.asarray([image_height, image_width], dtype=np.int64)
442
+ new_target["orig_size"] = np.asarray([image_height, image_width], dtype=np.int64)
443
+
444
+ if "segments_info" in target:
445
+ masks = np.asarray(PIL.Image.open(annotation_path), dtype=np.uint32)
446
+ masks = rgb_to_id(masks)
447
+
448
+ ids = np.array([segment_info["id"] for segment_info in target["segments_info"]])
449
+ masks = masks == ids[:, None, None]
450
+ masks = masks.astype(np.uint8)
451
+ if return_masks:
452
+ new_target["masks"] = masks
453
+ new_target["boxes"] = masks_to_boxes(masks)
454
+ new_target["class_labels"] = np.array(
455
+ [segment_info["category_id"] for segment_info in target["segments_info"]], dtype=np.int64
456
+ )
457
+ new_target["iscrowd"] = np.asarray(
458
+ [segment_info["iscrowd"] for segment_info in target["segments_info"]], dtype=np.int64
459
+ )
460
+ new_target["area"] = np.asarray(
461
+ [segment_info["area"] for segment_info in target["segments_info"]], dtype=np.float32
462
+ )
463
+
464
+ return new_target
465
+
466
+
467
+ # Copied from transformers.models.detr.image_processing_detr.get_segmentation_image
468
+ def get_segmentation_image(
469
+ masks: np.ndarray, input_size: Tuple, target_size: Tuple, stuff_equiv_classes, deduplicate=False
470
+ ):
471
+ h, w = input_size
472
+ final_h, final_w = target_size
473
+
474
+ m_id = scipy.special.softmax(masks.transpose(0, 1), -1)
475
+
476
+ if m_id.shape[-1] == 0:
477
+ # We didn't detect any mask :(
478
+ m_id = np.zeros((h, w), dtype=np.int64)
479
+ else:
480
+ m_id = m_id.argmax(-1).reshape(h, w)
481
+
482
+ if deduplicate:
483
+ # Merge the masks corresponding to the same stuff class
484
+ for equiv in stuff_equiv_classes.values():
485
+ for eq_id in equiv:
486
+ m_id[m_id == eq_id] = equiv[0]
487
+
488
+ seg_img = id_to_rgb(m_id)
489
+ seg_img = resize(seg_img, (final_w, final_h), resample=PILImageResampling.NEAREST)
490
+ return seg_img
491
+
492
+
493
+ # Copied from transformers.models.detr.image_processing_detr.get_mask_area
494
+ def get_mask_area(seg_img: np.ndarray, target_size: Tuple[int, int], n_classes: int) -> np.ndarray:
495
+ final_h, final_w = target_size
496
+ np_seg_img = seg_img.astype(np.uint8)
497
+ np_seg_img = np_seg_img.reshape(final_h, final_w, 3)
498
+ m_id = rgb_to_id(np_seg_img)
499
+ area = [(m_id == i).sum() for i in range(n_classes)]
500
+ return area
501
+
502
+
503
+ # Copied from transformers.models.detr.image_processing_detr.score_labels_from_class_probabilities
504
+ def score_labels_from_class_probabilities(logits: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
505
+ probs = scipy.special.softmax(logits, axis=-1)
506
+ labels = probs.argmax(-1, keepdims=True)
507
+ scores = np.take_along_axis(probs, labels, axis=-1)
508
+ scores, labels = scores.squeeze(-1), labels.squeeze(-1)
509
+ return scores, labels
510
+
511
+
512
+ # Copied from transformers.models.detr.image_processing_detr.post_process_panoptic_sample with DetrForSegmentation->ConditionalDetrForSegmentation
513
+ def post_process_panoptic_sample(
514
+ out_logits: np.ndarray,
515
+ masks: np.ndarray,
516
+ boxes: np.ndarray,
517
+ processed_size: Tuple[int, int],
518
+ target_size: Tuple[int, int],
519
+ is_thing_map: Dict,
520
+ threshold=0.85,
521
+ ) -> Dict:
522
+ """
523
+ Converts the output of [`ConditionalDetrForSegmentation`] into panoptic segmentation predictions for a single sample.
524
+
525
+ Args:
526
+ out_logits (`torch.Tensor`):
527
+ The logits for this sample.
528
+ masks (`torch.Tensor`):
529
+ The predicted segmentation masks for this sample.
530
+ boxes (`torch.Tensor`):
531
+ The prediced bounding boxes for this sample. The boxes are in the normalized format `(center_x, center_y,
532
+ width, height)` and values between `[0, 1]`, relative to the size the image (disregarding padding).
533
+ processed_size (`Tuple[int, int]`):
534
+ The processed size of the image `(height, width)`, as returned by the preprocessing step i.e. the size
535
+ after data augmentation but before batching.
536
+ target_size (`Tuple[int, int]`):
537
+ The target size of the image, `(height, width)` corresponding to the requested final size of the
538
+ prediction.
539
+ is_thing_map (`Dict`):
540
+ A dictionary mapping class indices to a boolean value indicating whether the class is a thing or not.
541
+ threshold (`float`, *optional*, defaults to 0.85):
542
+ The threshold used to binarize the segmentation masks.
543
+ """
544
+ # we filter empty queries and detection below threshold
545
+ scores, labels = score_labels_from_class_probabilities(out_logits)
546
+ keep = (labels != out_logits.shape[-1] - 1) & (scores > threshold)
547
+
548
+ cur_scores = scores[keep]
549
+ cur_classes = labels[keep]
550
+ cur_boxes = center_to_corners_format(boxes[keep])
551
+
552
+ if len(cur_boxes) != len(cur_classes):
553
+ raise ValueError("Not as many boxes as there are classes")
554
+
555
+ cur_masks = masks[keep]
556
+ cur_masks = resize(cur_masks[:, None], processed_size, resample=PILImageResampling.BILINEAR)
557
+ cur_masks = safe_squeeze(cur_masks, 1)
558
+ b, h, w = cur_masks.shape
559
+
560
+ # It may be that we have several predicted masks for the same stuff class.
561
+ # In the following, we track the list of masks ids for each stuff class (they are merged later on)
562
+ cur_masks = cur_masks.reshape(b, -1)
563
+ stuff_equiv_classes = defaultdict(list)
564
+ for k, label in enumerate(cur_classes):
565
+ if not is_thing_map[label]:
566
+ stuff_equiv_classes[label].append(k)
567
+
568
+ seg_img = get_segmentation_image(cur_masks, processed_size, target_size, stuff_equiv_classes, deduplicate=True)
569
+ area = get_mask_area(cur_masks, processed_size, n_classes=len(cur_scores))
570
+
571
+ # We filter out any mask that is too small
572
+ if cur_classes.size() > 0:
573
+ # We know filter empty masks as long as we find some
574
+ filtered_small = np.array([a <= 4 for a in area], dtype=bool)
575
+ while filtered_small.any():
576
+ cur_masks = cur_masks[~filtered_small]
577
+ cur_scores = cur_scores[~filtered_small]
578
+ cur_classes = cur_classes[~filtered_small]
579
+ seg_img = get_segmentation_image(cur_masks, (h, w), target_size, stuff_equiv_classes, deduplicate=True)
580
+ area = get_mask_area(seg_img, target_size, n_classes=len(cur_scores))
581
+ filtered_small = np.array([a <= 4 for a in area], dtype=bool)
582
+ else:
583
+ cur_classes = np.ones((1, 1), dtype=np.int64)
584
+
585
+ segments_info = [
586
+ {"id": i, "isthing": is_thing_map[cat], "category_id": int(cat), "area": a}
587
+ for i, (cat, a) in enumerate(zip(cur_classes, area))
588
+ ]
589
+ del cur_classes
590
+
591
+ with io.BytesIO() as out:
592
+ PIL.Image.fromarray(seg_img).save(out, format="PNG")
593
+ predictions = {"png_string": out.getvalue(), "segments_info": segments_info}
594
+
595
+ return predictions
596
+
597
+
598
+ # Copied from transformers.models.detr.image_processing_detr.resize_annotation
599
+ def resize_annotation(
600
+ annotation: Dict[str, Any],
601
+ orig_size: Tuple[int, int],
602
+ target_size: Tuple[int, int],
603
+ threshold: float = 0.5,
604
+ resample: PILImageResampling = PILImageResampling.NEAREST,
605
+ ):
606
+ """
607
+ Resizes an annotation to a target size.
608
+
609
+ Args:
610
+ annotation (`Dict[str, Any]`):
611
+ The annotation dictionary.
612
+ orig_size (`Tuple[int, int]`):
613
+ The original size of the input image.
614
+ target_size (`Tuple[int, int]`):
615
+ The target size of the image, as returned by the preprocessing `resize` step.
616
+ threshold (`float`, *optional*, defaults to 0.5):
617
+ The threshold used to binarize the segmentation masks.
618
+ resample (`PILImageResampling`, defaults to `PILImageResampling.NEAREST`):
619
+ The resampling filter to use when resizing the masks.
620
+ """
621
+ ratios = tuple(float(s) / float(s_orig) for s, s_orig in zip(target_size, orig_size))
622
+ ratio_height, ratio_width = ratios
623
+
624
+ new_annotation = {}
625
+ new_annotation["size"] = target_size
626
+
627
+ for key, value in annotation.items():
628
+ if key == "boxes":
629
+ boxes = value
630
+ scaled_boxes = boxes * np.asarray([ratio_width, ratio_height, ratio_width, ratio_height], dtype=np.float32)
631
+ new_annotation["boxes"] = scaled_boxes
632
+ elif key == "area":
633
+ area = value
634
+ scaled_area = area * (ratio_width * ratio_height)
635
+ new_annotation["area"] = scaled_area
636
+ elif key == "masks":
637
+ masks = value[:, None]
638
+ masks = np.array([resize(mask, target_size, resample=resample) for mask in masks])
639
+ masks = masks.astype(np.float32)
640
+ masks = masks[:, 0] > threshold
641
+ new_annotation["masks"] = masks
642
+ elif key == "size":
643
+ new_annotation["size"] = target_size
644
+ else:
645
+ new_annotation[key] = value
646
+
647
+ return new_annotation
648
+
649
+
650
+ # Copied from transformers.models.detr.image_processing_detr.binary_mask_to_rle
651
+ def binary_mask_to_rle(mask):
652
+ """
653
+ Converts given binary mask of shape `(height, width)` to the run-length encoding (RLE) format.
654
+
655
+ Args:
656
+ mask (`torch.Tensor` or `numpy.array`):
657
+ A binary mask tensor of shape `(height, width)` where 0 denotes background and 1 denotes the target
658
+ segment_id or class_id.
659
+ Returns:
660
+ `List`: Run-length encoded list of the binary mask. Refer to COCO API for more information about the RLE
661
+ format.
662
+ """
663
+ if is_torch_tensor(mask):
664
+ mask = mask.numpy()
665
+
666
+ pixels = mask.flatten()
667
+ pixels = np.concatenate([[0], pixels, [0]])
668
+ runs = np.where(pixels[1:] != pixels[:-1])[0] + 1
669
+ runs[1::2] -= runs[::2]
670
+ return list(runs)
671
+
672
+
673
+ # Copied from transformers.models.detr.image_processing_detr.convert_segmentation_to_rle
674
+ def convert_segmentation_to_rle(segmentation):
675
+ """
676
+ Converts given segmentation map of shape `(height, width)` to the run-length encoding (RLE) format.
677
+
678
+ Args:
679
+ segmentation (`torch.Tensor` or `numpy.array`):
680
+ A segmentation map of shape `(height, width)` where each value denotes a segment or class id.
681
+ Returns:
682
+ `List[List]`: A list of lists, where each list is the run-length encoding of a segment / class id.
683
+ """
684
+ segment_ids = torch.unique(segmentation)
685
+
686
+ run_length_encodings = []
687
+ for idx in segment_ids:
688
+ mask = torch.where(segmentation == idx, 1, 0)
689
+ rle = binary_mask_to_rle(mask)
690
+ run_length_encodings.append(rle)
691
+
692
+ return run_length_encodings
693
+
694
+
695
+ # Copied from transformers.models.detr.image_processing_detr.remove_low_and_no_objects
696
+ def remove_low_and_no_objects(masks, scores, labels, object_mask_threshold, num_labels):
697
+ """
698
+ Binarize the given masks using `object_mask_threshold`, it returns the associated values of `masks`, `scores` and
699
+ `labels`.
700
+
701
+ Args:
702
+ masks (`torch.Tensor`):
703
+ A tensor of shape `(num_queries, height, width)`.
704
+ scores (`torch.Tensor`):
705
+ A tensor of shape `(num_queries)`.
706
+ labels (`torch.Tensor`):
707
+ A tensor of shape `(num_queries)`.
708
+ object_mask_threshold (`float`):
709
+ A number between 0 and 1 used to binarize the masks.
710
+ Raises:
711
+ `ValueError`: Raised when the first dimension doesn't match in all input tensors.
712
+ Returns:
713
+ `Tuple[`torch.Tensor`, `torch.Tensor`, `torch.Tensor`]`: The `masks`, `scores` and `labels` without the region
714
+ < `object_mask_threshold`.
715
+ """
716
+ if not (masks.shape[0] == scores.shape[0] == labels.shape[0]):
717
+ raise ValueError("mask, scores and labels must have the same shape!")
718
+
719
+ to_keep = labels.ne(num_labels) & (scores > object_mask_threshold)
720
+
721
+ return masks[to_keep], scores[to_keep], labels[to_keep]
722
+
723
+
724
+ # Copied from transformers.models.detr.image_processing_detr.check_segment_validity
725
+ def check_segment_validity(mask_labels, mask_probs, k, mask_threshold=0.5, overlap_mask_area_threshold=0.8):
726
+ # Get the mask associated with the k class
727
+ mask_k = mask_labels == k
728
+ mask_k_area = mask_k.sum()
729
+
730
+ # Compute the area of all the stuff in query k
731
+ original_area = (mask_probs[k] >= mask_threshold).sum()
732
+ mask_exists = mask_k_area > 0 and original_area > 0
733
+
734
+ # Eliminate disconnected tiny segments
735
+ if mask_exists:
736
+ area_ratio = mask_k_area / original_area
737
+ if not area_ratio.item() > overlap_mask_area_threshold:
738
+ mask_exists = False
739
+
740
+ return mask_exists, mask_k
741
+
742
+
743
+ # Copied from transformers.models.detr.image_processing_detr.compute_segments
744
+ def compute_segments(
745
+ mask_probs,
746
+ pred_scores,
747
+ pred_labels,
748
+ mask_threshold: float = 0.5,
749
+ overlap_mask_area_threshold: float = 0.8,
750
+ label_ids_to_fuse: Optional[Set[int]] = None,
751
+ target_size: Tuple[int, int] = None,
752
+ ):
753
+ height = mask_probs.shape[1] if target_size is None else target_size[0]
754
+ width = mask_probs.shape[2] if target_size is None else target_size[1]
755
+
756
+ segmentation = torch.zeros((height, width), dtype=torch.int32, device=mask_probs.device)
757
+ segments: List[Dict] = []
758
+
759
+ if target_size is not None:
760
+ mask_probs = nn.functional.interpolate(
761
+ mask_probs.unsqueeze(0), size=target_size, mode="bilinear", align_corners=False
762
+ )[0]
763
+
764
+ current_segment_id = 0
765
+
766
+ # Weigh each mask by its prediction score
767
+ mask_probs *= pred_scores.view(-1, 1, 1)
768
+ mask_labels = mask_probs.argmax(0) # [height, width]
769
+
770
+ # Keep track of instances of each class
771
+ stuff_memory_list: Dict[str, int] = {}
772
+ for k in range(pred_labels.shape[0]):
773
+ pred_class = pred_labels[k].item()
774
+ should_fuse = pred_class in label_ids_to_fuse
775
+
776
+ # Check if mask exists and large enough to be a segment
777
+ mask_exists, mask_k = check_segment_validity(
778
+ mask_labels, mask_probs, k, mask_threshold, overlap_mask_area_threshold
779
+ )
780
+
781
+ if mask_exists:
782
+ if pred_class in stuff_memory_list:
783
+ current_segment_id = stuff_memory_list[pred_class]
784
+ else:
785
+ current_segment_id += 1
786
+
787
+ # Add current object segment to final segmentation map
788
+ segmentation[mask_k] = current_segment_id
789
+ segment_score = round(pred_scores[k].item(), 6)
790
+ segments.append(
791
+ {
792
+ "id": current_segment_id,
793
+ "label_id": pred_class,
794
+ "was_fused": should_fuse,
795
+ "score": segment_score,
796
+ }
797
+ )
798
+ if should_fuse:
799
+ stuff_memory_list[pred_class] = current_segment_id
800
+
801
+ return segmentation, segments
802
+
803
+
804
+ class ConditionalDetrImageProcessor(BaseImageProcessor):
805
+ r"""
806
+ Constructs a Conditional Detr image processor.
807
+
808
+ Args:
809
+ format (`str`, *optional*, defaults to `"coco_detection"`):
810
+ Data format of the annotations. One of "coco_detection" or "coco_panoptic".
811
+ do_resize (`bool`, *optional*, defaults to `True`):
812
+ Controls whether to resize the image's (height, width) dimensions to the specified `size`. Can be
813
+ overridden by the `do_resize` parameter in the `preprocess` method.
814
+ size (`Dict[str, int]` *optional*, defaults to `{"shortest_edge": 800, "longest_edge": 1333}`):
815
+ Size of the image's `(height, width)` dimensions after resizing. Can be overridden by the `size` parameter
816
+ in the `preprocess` method. Available options are:
817
+ - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
818
+ Do NOT keep the aspect ratio.
819
+ - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
820
+ the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
821
+ less or equal to `longest_edge`.
822
+ - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
823
+ aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
824
+ `max_width`.
825
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
826
+ Resampling filter to use if resizing the image.
827
+ do_rescale (`bool`, *optional*, defaults to `True`):
828
+ Controls whether to rescale the image by the specified scale `rescale_factor`. Can be overridden by the
829
+ `do_rescale` parameter in the `preprocess` method.
830
+ rescale_factor (`int` or `float`, *optional*, defaults to `1/255`):
831
+ Scale factor to use if rescaling the image. Can be overridden by the `rescale_factor` parameter in the
832
+ `preprocess` method.
833
+ do_normalize:
834
+ Controls whether to normalize the image. Can be overridden by the `do_normalize` parameter in the
835
+ `preprocess` method.
836
+ image_mean (`float` or `List[float]`, *optional*, defaults to `IMAGENET_DEFAULT_MEAN`):
837
+ Mean values to use when normalizing the image. Can be a single value or a list of values, one for each
838
+ channel. Can be overridden by the `image_mean` parameter in the `preprocess` method.
839
+ image_std (`float` or `List[float]`, *optional*, defaults to `IMAGENET_DEFAULT_STD`):
840
+ Standard deviation values to use when normalizing the image. Can be a single value or a list of values, one
841
+ for each channel. Can be overridden by the `image_std` parameter in the `preprocess` method.
842
+ do_convert_annotations (`bool`, *optional*, defaults to `True`):
843
+ Controls whether to convert the annotations to the format expected by the DETR model. Converts the
844
+ bounding boxes to the format `(center_x, center_y, width, height)` and in the range `[0, 1]`.
845
+ Can be overridden by the `do_convert_annotations` parameter in the `preprocess` method.
846
+ do_pad (`bool`, *optional*, defaults to `True`):
847
+ Controls whether to pad the image. Can be overridden by the `do_pad` parameter in the `preprocess`
848
+ method. If `True`, padding will be applied to the bottom and right of the image with zeros.
849
+ If `pad_size` is provided, the image will be padded to the specified dimensions.
850
+ Otherwise, the image will be padded to the maximum height and width of the batch.
851
+ pad_size (`Dict[str, int]`, *optional*):
852
+ The size `{"height": int, "width" int}` to pad the images to. Must be larger than any image size
853
+ provided for preprocessing. If `pad_size` is not provided, images will be padded to the largest
854
+ height and width in the batch.
855
+ """
856
+
857
+ model_input_names = ["pixel_values", "pixel_mask"]
858
+
859
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.__init__
860
+ def __init__(
861
+ self,
862
+ format: Union[str, AnnotationFormat] = AnnotationFormat.COCO_DETECTION,
863
+ do_resize: bool = True,
864
+ size: Dict[str, int] = None,
865
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
866
+ do_rescale: bool = True,
867
+ rescale_factor: Union[int, float] = 1 / 255,
868
+ do_normalize: bool = True,
869
+ image_mean: Union[float, List[float]] = None,
870
+ image_std: Union[float, List[float]] = None,
871
+ do_convert_annotations: Optional[bool] = None,
872
+ do_pad: bool = True,
873
+ pad_size: Optional[Dict[str, int]] = None,
874
+ **kwargs,
875
+ ) -> None:
876
+ if "pad_and_return_pixel_mask" in kwargs:
877
+ do_pad = kwargs.pop("pad_and_return_pixel_mask")
878
+
879
+ if "max_size" in kwargs:
880
+ logger.warning_once(
881
+ "The `max_size` parameter is deprecated and will be removed in v4.26. "
882
+ "Please specify in `size['longest_edge'] instead`.",
883
+ )
884
+ max_size = kwargs.pop("max_size")
885
+ else:
886
+ max_size = None if size is None else 1333
887
+
888
+ size = size if size is not None else {"shortest_edge": 800, "longest_edge": 1333}
889
+ size = get_size_dict(size, max_size=max_size, default_to_square=False)
890
+
891
+ # Backwards compatibility
892
+ if do_convert_annotations is None:
893
+ do_convert_annotations = do_normalize
894
+
895
+ super().__init__(**kwargs)
896
+ self.format = format
897
+ self.do_resize = do_resize
898
+ self.size = size
899
+ self.resample = resample
900
+ self.do_rescale = do_rescale
901
+ self.rescale_factor = rescale_factor
902
+ self.do_normalize = do_normalize
903
+ self.do_convert_annotations = do_convert_annotations
904
+ self.image_mean = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
905
+ self.image_std = image_std if image_std is not None else IMAGENET_DEFAULT_STD
906
+ self.do_pad = do_pad
907
+ self.pad_size = pad_size
908
+ self._valid_processor_keys = [
909
+ "images",
910
+ "annotations",
911
+ "return_segmentation_masks",
912
+ "masks_path",
913
+ "do_resize",
914
+ "size",
915
+ "resample",
916
+ "do_rescale",
917
+ "rescale_factor",
918
+ "do_normalize",
919
+ "do_convert_annotations",
920
+ "image_mean",
921
+ "image_std",
922
+ "do_pad",
923
+ "pad_size",
924
+ "format",
925
+ "return_tensors",
926
+ "data_format",
927
+ "input_data_format",
928
+ ]
929
+
930
+ @classmethod
931
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.from_dict with Detr->ConditionalDetr
932
+ def from_dict(cls, image_processor_dict: Dict[str, Any], **kwargs):
933
+ """
934
+ Overrides the `from_dict` method from the base class to make sure parameters are updated if image processor is
935
+ created using from_dict and kwargs e.g. `ConditionalDetrImageProcessor.from_pretrained(checkpoint, size=600,
936
+ max_size=800)`
937
+ """
938
+ image_processor_dict = image_processor_dict.copy()
939
+ if "max_size" in kwargs:
940
+ image_processor_dict["max_size"] = kwargs.pop("max_size")
941
+ if "pad_and_return_pixel_mask" in kwargs:
942
+ image_processor_dict["pad_and_return_pixel_mask"] = kwargs.pop("pad_and_return_pixel_mask")
943
+ return super().from_dict(image_processor_dict, **kwargs)
944
+
945
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.prepare_annotation with DETR->ConditionalDetr
946
+ def prepare_annotation(
947
+ self,
948
+ image: np.ndarray,
949
+ target: Dict,
950
+ format: Optional[AnnotationFormat] = None,
951
+ return_segmentation_masks: Optional[bool] = None,
952
+ masks_path: Optional[Union[str, pathlib.Path]] = None,
953
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
954
+ ) -> Dict:
955
+ """
956
+ Prepare an annotation for feeding into ConditionalDetr model.
957
+ """
958
+ format = format if format is not None else self.format
959
+
960
+ if format == AnnotationFormat.COCO_DETECTION:
961
+ return_segmentation_masks = False if return_segmentation_masks is None else return_segmentation_masks
962
+ target = prepare_coco_detection_annotation(
963
+ image, target, return_segmentation_masks, input_data_format=input_data_format
964
+ )
965
+ elif format == AnnotationFormat.COCO_PANOPTIC:
966
+ return_segmentation_masks = True if return_segmentation_masks is None else return_segmentation_masks
967
+ target = prepare_coco_panoptic_annotation(
968
+ image,
969
+ target,
970
+ masks_path=masks_path,
971
+ return_masks=return_segmentation_masks,
972
+ input_data_format=input_data_format,
973
+ )
974
+ else:
975
+ raise ValueError(f"Format {format} is not supported.")
976
+ return target
977
+
978
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.resize
979
+ def resize(
980
+ self,
981
+ image: np.ndarray,
982
+ size: Dict[str, int],
983
+ resample: PILImageResampling = PILImageResampling.BILINEAR,
984
+ data_format: Optional[ChannelDimension] = None,
985
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
986
+ **kwargs,
987
+ ) -> np.ndarray:
988
+ """
989
+ Resize the image to the given size. Size can be `min_size` (scalar) or `(height, width)` tuple. If size is an
990
+ int, smaller edge of the image will be matched to this number.
991
+
992
+ Args:
993
+ image (`np.ndarray`):
994
+ Image to resize.
995
+ size (`Dict[str, int]`):
996
+ Size of the image's `(height, width)` dimensions after resizing. Available options are:
997
+ - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
998
+ Do NOT keep the aspect ratio.
999
+ - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
1000
+ the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
1001
+ less or equal to `longest_edge`.
1002
+ - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
1003
+ aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
1004
+ `max_width`.
1005
+ resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BILINEAR`):
1006
+ Resampling filter to use if resizing the image.
1007
+ data_format (`str` or `ChannelDimension`, *optional*):
1008
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
1009
+ image is used.
1010
+ input_data_format (`ChannelDimension` or `str`, *optional*):
1011
+ The channel dimension format of the input image. If not provided, it will be inferred.
1012
+ """
1013
+ if "max_size" in kwargs:
1014
+ logger.warning_once(
1015
+ "The `max_size` parameter is deprecated and will be removed in v4.26. "
1016
+ "Please specify in `size['longest_edge'] instead`.",
1017
+ )
1018
+ max_size = kwargs.pop("max_size")
1019
+ else:
1020
+ max_size = None
1021
+ size = get_size_dict(size, max_size=max_size, default_to_square=False)
1022
+ if "shortest_edge" in size and "longest_edge" in size:
1023
+ new_size = get_resize_output_image_size(
1024
+ image, size["shortest_edge"], size["longest_edge"], input_data_format=input_data_format
1025
+ )
1026
+ elif "max_height" in size and "max_width" in size:
1027
+ new_size = get_image_size_for_max_height_width(
1028
+ image, size["max_height"], size["max_width"], input_data_format=input_data_format
1029
+ )
1030
+ elif "height" in size and "width" in size:
1031
+ new_size = (size["height"], size["width"])
1032
+ else:
1033
+ raise ValueError(
1034
+ "Size must contain 'height' and 'width' keys or 'shortest_edge' and 'longest_edge' keys. Got"
1035
+ f" {size.keys()}."
1036
+ )
1037
+ image = resize(
1038
+ image,
1039
+ size=new_size,
1040
+ resample=resample,
1041
+ data_format=data_format,
1042
+ input_data_format=input_data_format,
1043
+ **kwargs,
1044
+ )
1045
+ return image
1046
+
1047
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.resize_annotation
1048
+ def resize_annotation(
1049
+ self,
1050
+ annotation,
1051
+ orig_size,
1052
+ size,
1053
+ resample: PILImageResampling = PILImageResampling.NEAREST,
1054
+ ) -> Dict:
1055
+ """
1056
+ Resize the annotation to match the resized image. If size is an int, smaller edge of the mask will be matched
1057
+ to this number.
1058
+ """
1059
+ return resize_annotation(annotation, orig_size=orig_size, target_size=size, resample=resample)
1060
+
1061
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.rescale
1062
+ def rescale(
1063
+ self,
1064
+ image: np.ndarray,
1065
+ rescale_factor: float,
1066
+ data_format: Optional[Union[str, ChannelDimension]] = None,
1067
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
1068
+ ) -> np.ndarray:
1069
+ """
1070
+ Rescale the image by the given factor. image = image * rescale_factor.
1071
+
1072
+ Args:
1073
+ image (`np.ndarray`):
1074
+ Image to rescale.
1075
+ rescale_factor (`float`):
1076
+ The value to use for rescaling.
1077
+ data_format (`str` or `ChannelDimension`, *optional*):
1078
+ The channel dimension format for the output image. If unset, the channel dimension format of the input
1079
+ image is used. Can be one of:
1080
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
1081
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
1082
+ input_data_format (`str` or `ChannelDimension`, *optional*):
1083
+ The channel dimension format for the input image. If unset, is inferred from the input image. Can be
1084
+ one of:
1085
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
1086
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
1087
+ """
1088
+ return rescale(image, rescale_factor, data_format=data_format, input_data_format=input_data_format)
1089
+
1090
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.normalize_annotation
1091
+ def normalize_annotation(self, annotation: Dict, image_size: Tuple[int, int]) -> Dict:
1092
+ """
1093
+ Normalize the boxes in the annotation from `[top_left_x, top_left_y, bottom_right_x, bottom_right_y]` to
1094
+ `[center_x, center_y, width, height]` format and from absolute to relative pixel values.
1095
+ """
1096
+ return normalize_annotation(annotation, image_size=image_size)
1097
+
1098
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor._update_annotation_for_padded_image
1099
+ def _update_annotation_for_padded_image(
1100
+ self,
1101
+ annotation: Dict,
1102
+ input_image_size: Tuple[int, int],
1103
+ output_image_size: Tuple[int, int],
1104
+ padding,
1105
+ update_bboxes,
1106
+ ) -> Dict:
1107
+ """
1108
+ Update the annotation for a padded image.
1109
+ """
1110
+ new_annotation = {}
1111
+ new_annotation["size"] = output_image_size
1112
+
1113
+ for key, value in annotation.items():
1114
+ if key == "masks":
1115
+ masks = value
1116
+ masks = pad(
1117
+ masks,
1118
+ padding,
1119
+ mode=PaddingMode.CONSTANT,
1120
+ constant_values=0,
1121
+ input_data_format=ChannelDimension.FIRST,
1122
+ )
1123
+ masks = safe_squeeze(masks, 1)
1124
+ new_annotation["masks"] = masks
1125
+ elif key == "boxes" and update_bboxes:
1126
+ boxes = value
1127
+ boxes *= np.asarray(
1128
+ [
1129
+ input_image_size[1] / output_image_size[1],
1130
+ input_image_size[0] / output_image_size[0],
1131
+ input_image_size[1] / output_image_size[1],
1132
+ input_image_size[0] / output_image_size[0],
1133
+ ]
1134
+ )
1135
+ new_annotation["boxes"] = boxes
1136
+ elif key == "size":
1137
+ new_annotation["size"] = output_image_size
1138
+ else:
1139
+ new_annotation[key] = value
1140
+ return new_annotation
1141
+
1142
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor._pad_image
1143
+ def _pad_image(
1144
+ self,
1145
+ image: np.ndarray,
1146
+ output_size: Tuple[int, int],
1147
+ annotation: Optional[Dict[str, Any]] = None,
1148
+ constant_values: Union[float, Iterable[float]] = 0,
1149
+ data_format: Optional[ChannelDimension] = None,
1150
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
1151
+ update_bboxes: bool = True,
1152
+ ) -> np.ndarray:
1153
+ """
1154
+ Pad an image with zeros to the given size.
1155
+ """
1156
+ input_height, input_width = get_image_size(image, channel_dim=input_data_format)
1157
+ output_height, output_width = output_size
1158
+
1159
+ pad_bottom = output_height - input_height
1160
+ pad_right = output_width - input_width
1161
+ padding = ((0, pad_bottom), (0, pad_right))
1162
+ padded_image = pad(
1163
+ image,
1164
+ padding,
1165
+ mode=PaddingMode.CONSTANT,
1166
+ constant_values=constant_values,
1167
+ data_format=data_format,
1168
+ input_data_format=input_data_format,
1169
+ )
1170
+ if annotation is not None:
1171
+ annotation = self._update_annotation_for_padded_image(
1172
+ annotation, (input_height, input_width), (output_height, output_width), padding, update_bboxes
1173
+ )
1174
+ return padded_image, annotation
1175
+
1176
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.pad
1177
+ def pad(
1178
+ self,
1179
+ images: List[np.ndarray],
1180
+ annotations: Optional[Union[AnnotationType, List[AnnotationType]]] = None,
1181
+ constant_values: Union[float, Iterable[float]] = 0,
1182
+ return_pixel_mask: bool = True,
1183
+ return_tensors: Optional[Union[str, TensorType]] = None,
1184
+ data_format: Optional[ChannelDimension] = None,
1185
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
1186
+ update_bboxes: bool = True,
1187
+ pad_size: Optional[Dict[str, int]] = None,
1188
+ ) -> BatchFeature:
1189
+ """
1190
+ Pads a batch of images to the bottom and right of the image with zeros to the size of largest height and width
1191
+ in the batch and optionally returns their corresponding pixel mask.
1192
+
1193
+ Args:
1194
+ images (List[`np.ndarray`]):
1195
+ Images to pad.
1196
+ annotations (`AnnotationType` or `List[AnnotationType]`, *optional*):
1197
+ Annotations to transform according to the padding that is applied to the images.
1198
+ constant_values (`float` or `Iterable[float]`, *optional*):
1199
+ The value to use for the padding if `mode` is `"constant"`.
1200
+ return_pixel_mask (`bool`, *optional*, defaults to `True`):
1201
+ Whether to return a pixel mask.
1202
+ return_tensors (`str` or `TensorType`, *optional*):
1203
+ The type of tensors to return. Can be one of:
1204
+ - Unset: Return a list of `np.ndarray`.
1205
+ - `TensorType.TENSORFLOW` or `'tf'`: Return a batch of type `tf.Tensor`.
1206
+ - `TensorType.PYTORCH` or `'pt'`: Return a batch of type `torch.Tensor`.
1207
+ - `TensorType.NUMPY` or `'np'`: Return a batch of type `np.ndarray`.
1208
+ - `TensorType.JAX` or `'jax'`: Return a batch of type `jax.numpy.ndarray`.
1209
+ data_format (`str` or `ChannelDimension`, *optional*):
1210
+ The channel dimension format of the image. If not provided, it will be the same as the input image.
1211
+ input_data_format (`ChannelDimension` or `str`, *optional*):
1212
+ The channel dimension format of the input image. If not provided, it will be inferred.
1213
+ update_bboxes (`bool`, *optional*, defaults to `True`):
1214
+ Whether to update the bounding boxes in the annotations to match the padded images. If the
1215
+ bounding boxes have not been converted to relative coordinates and `(centre_x, centre_y, width, height)`
1216
+ format, the bounding boxes will not be updated.
1217
+ pad_size (`Dict[str, int]`, *optional*):
1218
+ The size `{"height": int, "width" int}` to pad the images to. Must be larger than any image size
1219
+ provided for preprocessing. If `pad_size` is not provided, images will be padded to the largest
1220
+ height and width in the batch.
1221
+ """
1222
+ pad_size = pad_size if pad_size is not None else self.pad_size
1223
+ if pad_size is not None:
1224
+ padded_size = (pad_size["height"], pad_size["width"])
1225
+ else:
1226
+ padded_size = get_max_height_width(images, input_data_format=input_data_format)
1227
+
1228
+ annotation_list = annotations if annotations is not None else [None] * len(images)
1229
+ padded_images = []
1230
+ padded_annotations = []
1231
+ for image, annotation in zip(images, annotation_list):
1232
+ padded_image, padded_annotation = self._pad_image(
1233
+ image,
1234
+ padded_size,
1235
+ annotation,
1236
+ constant_values=constant_values,
1237
+ data_format=data_format,
1238
+ input_data_format=input_data_format,
1239
+ update_bboxes=update_bboxes,
1240
+ )
1241
+ padded_images.append(padded_image)
1242
+ padded_annotations.append(padded_annotation)
1243
+
1244
+ data = {"pixel_values": padded_images}
1245
+
1246
+ if return_pixel_mask:
1247
+ masks = [
1248
+ make_pixel_mask(image=image, output_size=padded_size, input_data_format=input_data_format)
1249
+ for image in images
1250
+ ]
1251
+ data["pixel_mask"] = masks
1252
+
1253
+ encoded_inputs = BatchFeature(data=data, tensor_type=return_tensors)
1254
+
1255
+ if annotations is not None:
1256
+ encoded_inputs["labels"] = [
1257
+ BatchFeature(annotation, tensor_type=return_tensors) for annotation in padded_annotations
1258
+ ]
1259
+
1260
+ return encoded_inputs
1261
+
1262
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.preprocess
1263
+ def preprocess(
1264
+ self,
1265
+ images: ImageInput,
1266
+ annotations: Optional[Union[AnnotationType, List[AnnotationType]]] = None,
1267
+ return_segmentation_masks: Optional[bool] = None,
1268
+ masks_path: Optional[Union[str, pathlib.Path]] = None,
1269
+ do_resize: Optional[bool] = None,
1270
+ size: Optional[Dict[str, int]] = None,
1271
+ resample=None, # PILImageResampling
1272
+ do_rescale: Optional[bool] = None,
1273
+ rescale_factor: Optional[Union[int, float]] = None,
1274
+ do_normalize: Optional[bool] = None,
1275
+ do_convert_annotations: Optional[bool] = None,
1276
+ image_mean: Optional[Union[float, List[float]]] = None,
1277
+ image_std: Optional[Union[float, List[float]]] = None,
1278
+ do_pad: Optional[bool] = None,
1279
+ format: Optional[Union[str, AnnotationFormat]] = None,
1280
+ return_tensors: Optional[Union[TensorType, str]] = None,
1281
+ data_format: Union[str, ChannelDimension] = ChannelDimension.FIRST,
1282
+ input_data_format: Optional[Union[str, ChannelDimension]] = None,
1283
+ pad_size: Optional[Dict[str, int]] = None,
1284
+ **kwargs,
1285
+ ) -> BatchFeature:
1286
+ """
1287
+ Preprocess an image or a batch of images so that it can be used by the model.
1288
+
1289
+ Args:
1290
+ images (`ImageInput`):
1291
+ Image or batch of images to preprocess. Expects a single or batch of images with pixel values ranging
1292
+ from 0 to 255. If passing in images with pixel values between 0 and 1, set `do_rescale=False`.
1293
+ annotations (`AnnotationType` or `List[AnnotationType]`, *optional*):
1294
+ List of annotations associated with the image or batch of images. If annotation is for object
1295
+ detection, the annotations should be a dictionary with the following keys:
1296
+ - "image_id" (`int`): The image id.
1297
+ - "annotations" (`List[Dict]`): List of annotations for an image. Each annotation should be a
1298
+ dictionary. An image can have no annotations, in which case the list should be empty.
1299
+ If annotation is for segmentation, the annotations should be a dictionary with the following keys:
1300
+ - "image_id" (`int`): The image id.
1301
+ - "segments_info" (`List[Dict]`): List of segments for an image. Each segment should be a dictionary.
1302
+ An image can have no segments, in which case the list should be empty.
1303
+ - "file_name" (`str`): The file name of the image.
1304
+ return_segmentation_masks (`bool`, *optional*, defaults to self.return_segmentation_masks):
1305
+ Whether to return segmentation masks.
1306
+ masks_path (`str` or `pathlib.Path`, *optional*):
1307
+ Path to the directory containing the segmentation masks.
1308
+ do_resize (`bool`, *optional*, defaults to self.do_resize):
1309
+ Whether to resize the image.
1310
+ size (`Dict[str, int]`, *optional*, defaults to self.size):
1311
+ Size of the image's `(height, width)` dimensions after resizing. Available options are:
1312
+ - `{"height": int, "width": int}`: The image will be resized to the exact size `(height, width)`.
1313
+ Do NOT keep the aspect ratio.
1314
+ - `{"shortest_edge": int, "longest_edge": int}`: The image will be resized to a maximum size respecting
1315
+ the aspect ratio and keeping the shortest edge less or equal to `shortest_edge` and the longest edge
1316
+ less or equal to `longest_edge`.
1317
+ - `{"max_height": int, "max_width": int}`: The image will be resized to the maximum size respecting the
1318
+ aspect ratio and keeping the height less or equal to `max_height` and the width less or equal to
1319
+ `max_width`.
1320
+ resample (`PILImageResampling`, *optional*, defaults to self.resample):
1321
+ Resampling filter to use when resizing the image.
1322
+ do_rescale (`bool`, *optional*, defaults to self.do_rescale):
1323
+ Whether to rescale the image.
1324
+ rescale_factor (`float`, *optional*, defaults to self.rescale_factor):
1325
+ Rescale factor to use when rescaling the image.
1326
+ do_normalize (`bool`, *optional*, defaults to self.do_normalize):
1327
+ Whether to normalize the image.
1328
+ do_convert_annotations (`bool`, *optional*, defaults to self.do_convert_annotations):
1329
+ Whether to convert the annotations to the format expected by the model. Converts the bounding
1330
+ boxes from the format `(top_left_x, top_left_y, width, height)` to `(center_x, center_y, width, height)`
1331
+ and in relative coordinates.
1332
+ image_mean (`float` or `List[float]`, *optional*, defaults to self.image_mean):
1333
+ Mean to use when normalizing the image.
1334
+ image_std (`float` or `List[float]`, *optional*, defaults to self.image_std):
1335
+ Standard deviation to use when normalizing the image.
1336
+ do_pad (`bool`, *optional*, defaults to self.do_pad):
1337
+ Whether to pad the image. If `True`, padding will be applied to the bottom and right of
1338
+ the image with zeros. If `pad_size` is provided, the image will be padded to the specified
1339
+ dimensions. Otherwise, the image will be padded to the maximum height and width of the batch.
1340
+ format (`str` or `AnnotationFormat`, *optional*, defaults to self.format):
1341
+ Format of the annotations.
1342
+ return_tensors (`str` or `TensorType`, *optional*, defaults to self.return_tensors):
1343
+ Type of tensors to return. If `None`, will return the list of images.
1344
+ data_format (`ChannelDimension` or `str`, *optional*, defaults to `ChannelDimension.FIRST`):
1345
+ The channel dimension format for the output image. Can be one of:
1346
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
1347
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
1348
+ - Unset: Use the channel dimension format of the input image.
1349
+ input_data_format (`ChannelDimension` or `str`, *optional*):
1350
+ The channel dimension format for the input image. If unset, the channel dimension format is inferred
1351
+ from the input image. Can be one of:
1352
+ - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.
1353
+ - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.
1354
+ - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.
1355
+ pad_size (`Dict[str, int]`, *optional*):
1356
+ The size `{"height": int, "width" int}` to pad the images to. Must be larger than any image size
1357
+ provided for preprocessing. If `pad_size` is not provided, images will be padded to the largest
1358
+ height and width in the batch.
1359
+ """
1360
+ if "pad_and_return_pixel_mask" in kwargs:
1361
+ logger.warning_once(
1362
+ "The `pad_and_return_pixel_mask` argument is deprecated and will be removed in a future version, "
1363
+ "use `do_pad` instead."
1364
+ )
1365
+ do_pad = kwargs.pop("pad_and_return_pixel_mask")
1366
+
1367
+ if "max_size" in kwargs:
1368
+ logger.warning_once(
1369
+ "The `max_size` argument is deprecated and will be removed in a future version, use"
1370
+ " `size['longest_edge']` instead."
1371
+ )
1372
+ size = kwargs.pop("max_size")
1373
+
1374
+ do_resize = self.do_resize if do_resize is None else do_resize
1375
+ size = self.size if size is None else size
1376
+ size = get_size_dict(size=size, default_to_square=False)
1377
+ resample = self.resample if resample is None else resample
1378
+ do_rescale = self.do_rescale if do_rescale is None else do_rescale
1379
+ rescale_factor = self.rescale_factor if rescale_factor is None else rescale_factor
1380
+ do_normalize = self.do_normalize if do_normalize is None else do_normalize
1381
+ image_mean = self.image_mean if image_mean is None else image_mean
1382
+ image_std = self.image_std if image_std is None else image_std
1383
+ do_convert_annotations = (
1384
+ self.do_convert_annotations if do_convert_annotations is None else do_convert_annotations
1385
+ )
1386
+ do_pad = self.do_pad if do_pad is None else do_pad
1387
+ pad_size = self.pad_size if pad_size is None else pad_size
1388
+ format = self.format if format is None else format
1389
+
1390
+ images = make_list_of_images(images)
1391
+
1392
+ if not valid_images(images):
1393
+ raise ValueError(
1394
+ "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
1395
+ "torch.Tensor, tf.Tensor or jax.ndarray."
1396
+ )
1397
+ validate_kwargs(captured_kwargs=kwargs.keys(), valid_processor_keys=self._valid_processor_keys)
1398
+
1399
+ # Here, the pad() method pads to the maximum of (width, height). It does not need to be validated.
1400
+ validate_preprocess_arguments(
1401
+ do_rescale=do_rescale,
1402
+ rescale_factor=rescale_factor,
1403
+ do_normalize=do_normalize,
1404
+ image_mean=image_mean,
1405
+ image_std=image_std,
1406
+ do_resize=do_resize,
1407
+ size=size,
1408
+ resample=resample,
1409
+ )
1410
+
1411
+ if annotations is not None and isinstance(annotations, dict):
1412
+ annotations = [annotations]
1413
+
1414
+ if annotations is not None and len(images) != len(annotations):
1415
+ raise ValueError(
1416
+ f"The number of images ({len(images)}) and annotations ({len(annotations)}) do not match."
1417
+ )
1418
+
1419
+ format = AnnotationFormat(format)
1420
+ if annotations is not None:
1421
+ validate_annotations(format, SUPPORTED_ANNOTATION_FORMATS, annotations)
1422
+
1423
+ if (
1424
+ masks_path is not None
1425
+ and format == AnnotationFormat.COCO_PANOPTIC
1426
+ and not isinstance(masks_path, (pathlib.Path, str))
1427
+ ):
1428
+ raise ValueError(
1429
+ "The path to the directory containing the mask PNG files should be provided as a"
1430
+ f" `pathlib.Path` or string object, but is {type(masks_path)} instead."
1431
+ )
1432
+
1433
+ # All transformations expect numpy arrays
1434
+ images = [to_numpy_array(image) for image in images]
1435
+
1436
+ if do_rescale and is_scaled_image(images[0]):
1437
+ logger.warning_once(
1438
+ "It looks like you are trying to rescale already rescaled images. If the input"
1439
+ " images have pixel values between 0 and 1, set `do_rescale=False` to avoid rescaling them again."
1440
+ )
1441
+
1442
+ if input_data_format is None:
1443
+ # We assume that all images have the same channel dimension format.
1444
+ input_data_format = infer_channel_dimension_format(images[0])
1445
+
1446
+ # prepare (COCO annotations as a list of Dict -> DETR target as a single Dict per image)
1447
+ if annotations is not None:
1448
+ prepared_images = []
1449
+ prepared_annotations = []
1450
+ for image, target in zip(images, annotations):
1451
+ target = self.prepare_annotation(
1452
+ image,
1453
+ target,
1454
+ format,
1455
+ return_segmentation_masks=return_segmentation_masks,
1456
+ masks_path=masks_path,
1457
+ input_data_format=input_data_format,
1458
+ )
1459
+ prepared_images.append(image)
1460
+ prepared_annotations.append(target)
1461
+ images = prepared_images
1462
+ annotations = prepared_annotations
1463
+ del prepared_images, prepared_annotations
1464
+
1465
+ # transformations
1466
+ if do_resize:
1467
+ if annotations is not None:
1468
+ resized_images, resized_annotations = [], []
1469
+ for image, target in zip(images, annotations):
1470
+ orig_size = get_image_size(image, input_data_format)
1471
+ resized_image = self.resize(
1472
+ image, size=size, resample=resample, input_data_format=input_data_format
1473
+ )
1474
+ resized_annotation = self.resize_annotation(
1475
+ target, orig_size, get_image_size(resized_image, input_data_format)
1476
+ )
1477
+ resized_images.append(resized_image)
1478
+ resized_annotations.append(resized_annotation)
1479
+ images = resized_images
1480
+ annotations = resized_annotations
1481
+ del resized_images, resized_annotations
1482
+ else:
1483
+ images = [
1484
+ self.resize(image, size=size, resample=resample, input_data_format=input_data_format)
1485
+ for image in images
1486
+ ]
1487
+
1488
+ if do_rescale:
1489
+ images = [self.rescale(image, rescale_factor, input_data_format=input_data_format) for image in images]
1490
+
1491
+ if do_normalize:
1492
+ images = [
1493
+ self.normalize(image, image_mean, image_std, input_data_format=input_data_format) for image in images
1494
+ ]
1495
+
1496
+ if do_convert_annotations and annotations is not None:
1497
+ annotations = [
1498
+ self.normalize_annotation(annotation, get_image_size(image, input_data_format))
1499
+ for annotation, image in zip(annotations, images)
1500
+ ]
1501
+
1502
+ if do_pad:
1503
+ # Pads images and returns their mask: {'pixel_values': ..., 'pixel_mask': ...}
1504
+ encoded_inputs = self.pad(
1505
+ images,
1506
+ annotations=annotations,
1507
+ return_pixel_mask=True,
1508
+ data_format=data_format,
1509
+ input_data_format=input_data_format,
1510
+ update_bboxes=do_convert_annotations,
1511
+ return_tensors=return_tensors,
1512
+ pad_size=pad_size,
1513
+ )
1514
+ else:
1515
+ images = [
1516
+ to_channel_dimension_format(image, data_format, input_channel_dim=input_data_format)
1517
+ for image in images
1518
+ ]
1519
+ encoded_inputs = BatchFeature(data={"pixel_values": images}, tensor_type=return_tensors)
1520
+ if annotations is not None:
1521
+ encoded_inputs["labels"] = [
1522
+ BatchFeature(annotation, tensor_type=return_tensors) for annotation in annotations
1523
+ ]
1524
+
1525
+ return encoded_inputs
1526
+
1527
+ # POSTPROCESSING METHODS - TODO: add support for other frameworks
1528
+ def post_process(self, outputs, target_sizes):
1529
+ """
1530
+ Converts the output of [`ConditionalDetrForObjectDetection`] into the format expected by the Pascal VOC format (xmin, ymin, xmax, ymax).
1531
+ Only supports PyTorch.
1532
+
1533
+ Args:
1534
+ outputs ([`ConditionalDetrObjectDetectionOutput`]):
1535
+ Raw outputs of the model.
1536
+ target_sizes (`torch.Tensor` of shape `(batch_size, 2)`):
1537
+ Tensor containing the size (h, w) of each image of the batch. For evaluation, this must be the original
1538
+ image size (before any data augmentation). For visualization, this should be the image size after data
1539
+ augment, but before padding.
1540
+ Returns:
1541
+ `List[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
1542
+ in the batch as predicted by the model.
1543
+ """
1544
+ logging.warning_once(
1545
+ "`post_process` is deprecated and will be removed in v5 of Transformers, please use"
1546
+ " `post_process_object_detection` instead, with `threshold=0.` for equivalent results.",
1547
+ )
1548
+
1549
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
1550
+
1551
+ if len(out_logits) != len(target_sizes):
1552
+ raise ValueError("Make sure that you pass in as many target sizes as the batch dimension of the logits")
1553
+ if target_sizes.shape[1] != 2:
1554
+ raise ValueError("Each element of target_sizes must contain the size (h, w) of each image of the batch")
1555
+
1556
+ prob = out_logits.sigmoid()
1557
+ topk_values, topk_indexes = torch.topk(prob.view(out_logits.shape[0], -1), 300, dim=1)
1558
+ scores = topk_values
1559
+ topk_boxes = torch.div(topk_indexes, out_logits.shape[2], rounding_mode="floor")
1560
+ labels = topk_indexes % out_logits.shape[2]
1561
+ boxes = center_to_corners_format(out_bbox)
1562
+ boxes = torch.gather(boxes, 1, topk_boxes.unsqueeze(-1).repeat(1, 1, 4))
1563
+
1564
+ # and from relative [0, 1] to absolute [0, height] coordinates
1565
+ img_h, img_w = target_sizes.unbind(1)
1566
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1)
1567
+ boxes = boxes * scale_fct[:, None, :]
1568
+
1569
+ results = [{"scores": s, "labels": l, "boxes": b} for s, l, b in zip(scores, labels, boxes)]
1570
+
1571
+ return results
1572
+
1573
+ # Copied from transformers.models.deformable_detr.image_processing_deformable_detr.DeformableDetrImageProcessor.post_process_object_detection with DeformableDetr->ConditionalDetr
1574
+ def post_process_object_detection(
1575
+ self, outputs, threshold: float = 0.5, target_sizes: Union[TensorType, List[Tuple]] = None, top_k: int = 100
1576
+ ):
1577
+ """
1578
+ Converts the raw output of [`ConditionalDetrForObjectDetection`] into final bounding boxes in (top_left_x,
1579
+ top_left_y, bottom_right_x, bottom_right_y) format. Only supports PyTorch.
1580
+
1581
+ Args:
1582
+ outputs ([`DetrObjectDetectionOutput`]):
1583
+ Raw outputs of the model.
1584
+ threshold (`float`, *optional*):
1585
+ Score threshold to keep object detection predictions.
1586
+ target_sizes (`torch.Tensor` or `List[Tuple[int, int]]`, *optional*):
1587
+ Tensor of shape `(batch_size, 2)` or list of tuples (`Tuple[int, int]`) containing the target size
1588
+ (height, width) of each image in the batch. If left to None, predictions will not be resized.
1589
+ top_k (`int`, *optional*, defaults to 100):
1590
+ Keep only top k bounding boxes before filtering by thresholding.
1591
+
1592
+ Returns:
1593
+ `List[Dict]`: A list of dictionaries, each dictionary containing the scores, labels and boxes for an image
1594
+ in the batch as predicted by the model.
1595
+ """
1596
+ out_logits, out_bbox = outputs.logits, outputs.pred_boxes
1597
+
1598
+ if target_sizes is not None:
1599
+ if len(out_logits) != len(target_sizes):
1600
+ raise ValueError(
1601
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
1602
+ )
1603
+
1604
+ prob = out_logits.sigmoid()
1605
+ prob = prob.view(out_logits.shape[0], -1)
1606
+ k_value = min(top_k, prob.size(1))
1607
+ topk_values, topk_indexes = torch.topk(prob, k_value, dim=1)
1608
+ scores = topk_values
1609
+ topk_boxes = torch.div(topk_indexes, out_logits.shape[2], rounding_mode="floor")
1610
+ labels = topk_indexes % out_logits.shape[2]
1611
+ boxes = center_to_corners_format(out_bbox)
1612
+ boxes = torch.gather(boxes, 1, topk_boxes.unsqueeze(-1).repeat(1, 1, 4))
1613
+
1614
+ # and from relative [0, 1] to absolute [0, height] coordinates
1615
+ if target_sizes is not None:
1616
+ if isinstance(target_sizes, List):
1617
+ img_h = torch.Tensor([i[0] for i in target_sizes])
1618
+ img_w = torch.Tensor([i[1] for i in target_sizes])
1619
+ else:
1620
+ img_h, img_w = target_sizes.unbind(1)
1621
+ scale_fct = torch.stack([img_w, img_h, img_w, img_h], dim=1).to(boxes.device)
1622
+ boxes = boxes * scale_fct[:, None, :]
1623
+
1624
+ results = []
1625
+ for s, l, b in zip(scores, labels, boxes):
1626
+ score = s[s > threshold]
1627
+ label = l[s > threshold]
1628
+ box = b[s > threshold]
1629
+ results.append({"scores": score, "labels": label, "boxes": box})
1630
+
1631
+ return results
1632
+
1633
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.post_process_semantic_segmentation with Detr->ConditionalDetr
1634
+ def post_process_semantic_segmentation(self, outputs, target_sizes: List[Tuple[int, int]] = None):
1635
+ """
1636
+ Converts the output of [`ConditionalDetrForSegmentation`] into semantic segmentation maps. Only supports PyTorch.
1637
+
1638
+ Args:
1639
+ outputs ([`ConditionalDetrForSegmentation`]):
1640
+ Raw outputs of the model.
1641
+ target_sizes (`List[Tuple[int, int]]`, *optional*):
1642
+ A list of tuples (`Tuple[int, int]`) containing the target size (height, width) of each image in the
1643
+ batch. If unset, predictions will not be resized.
1644
+ Returns:
1645
+ `List[torch.Tensor]`:
1646
+ A list of length `batch_size`, where each item is a semantic segmentation map of shape (height, width)
1647
+ corresponding to the target_sizes entry (if `target_sizes` is specified). Each entry of each
1648
+ `torch.Tensor` correspond to a semantic class id.
1649
+ """
1650
+ class_queries_logits = outputs.logits # [batch_size, num_queries, num_classes+1]
1651
+ masks_queries_logits = outputs.pred_masks # [batch_size, num_queries, height, width]
1652
+
1653
+ # Remove the null class `[..., :-1]`
1654
+ masks_classes = class_queries_logits.softmax(dim=-1)[..., :-1]
1655
+ masks_probs = masks_queries_logits.sigmoid() # [batch_size, num_queries, height, width]
1656
+
1657
+ # Semantic segmentation logits of shape (batch_size, num_classes, height, width)
1658
+ segmentation = torch.einsum("bqc, bqhw -> bchw", masks_classes, masks_probs)
1659
+ batch_size = class_queries_logits.shape[0]
1660
+
1661
+ # Resize logits and compute semantic segmentation maps
1662
+ if target_sizes is not None:
1663
+ if batch_size != len(target_sizes):
1664
+ raise ValueError(
1665
+ "Make sure that you pass in as many target sizes as the batch dimension of the logits"
1666
+ )
1667
+
1668
+ semantic_segmentation = []
1669
+ for idx in range(batch_size):
1670
+ resized_logits = nn.functional.interpolate(
1671
+ segmentation[idx].unsqueeze(dim=0), size=target_sizes[idx], mode="bilinear", align_corners=False
1672
+ )
1673
+ semantic_map = resized_logits[0].argmax(dim=0)
1674
+ semantic_segmentation.append(semantic_map)
1675
+ else:
1676
+ semantic_segmentation = segmentation.argmax(dim=1)
1677
+ semantic_segmentation = [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0])]
1678
+
1679
+ return semantic_segmentation
1680
+
1681
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.post_process_instance_segmentation with Detr->ConditionalDetr
1682
+ def post_process_instance_segmentation(
1683
+ self,
1684
+ outputs,
1685
+ threshold: float = 0.5,
1686
+ mask_threshold: float = 0.5,
1687
+ overlap_mask_area_threshold: float = 0.8,
1688
+ target_sizes: Optional[List[Tuple[int, int]]] = None,
1689
+ return_coco_annotation: Optional[bool] = False,
1690
+ ) -> List[Dict]:
1691
+ """
1692
+ Converts the output of [`ConditionalDetrForSegmentation`] into instance segmentation predictions. Only supports PyTorch.
1693
+
1694
+ Args:
1695
+ outputs ([`ConditionalDetrForSegmentation`]):
1696
+ Raw outputs of the model.
1697
+ threshold (`float`, *optional*, defaults to 0.5):
1698
+ The probability score threshold to keep predicted instance masks.
1699
+ mask_threshold (`float`, *optional*, defaults to 0.5):
1700
+ Threshold to use when turning the predicted masks into binary values.
1701
+ overlap_mask_area_threshold (`float`, *optional*, defaults to 0.8):
1702
+ The overlap mask area threshold to merge or discard small disconnected parts within each binary
1703
+ instance mask.
1704
+ target_sizes (`List[Tuple]`, *optional*):
1705
+ List of length (batch_size), where each list item (`Tuple[int, int]]`) corresponds to the requested
1706
+ final size (height, width) of each prediction. If unset, predictions will not be resized.
1707
+ return_coco_annotation (`bool`, *optional*):
1708
+ Defaults to `False`. If set to `True`, segmentation maps are returned in COCO run-length encoding (RLE)
1709
+ format.
1710
+ Returns:
1711
+ `List[Dict]`: A list of dictionaries, one per image, each dictionary containing two keys:
1712
+ - **segmentation** -- A tensor of shape `(height, width)` where each pixel represents a `segment_id` or
1713
+ `List[List]` run-length encoding (RLE) of the segmentation map if return_coco_annotation is set to
1714
+ `True`. Set to `None` if no mask if found above `threshold`.
1715
+ - **segments_info** -- A dictionary that contains additional information on each segment.
1716
+ - **id** -- An integer representing the `segment_id`.
1717
+ - **label_id** -- An integer representing the label / semantic class id corresponding to `segment_id`.
1718
+ - **score** -- Prediction score of segment with `segment_id`.
1719
+ """
1720
+ class_queries_logits = outputs.logits # [batch_size, num_queries, num_classes+1]
1721
+ masks_queries_logits = outputs.pred_masks # [batch_size, num_queries, height, width]
1722
+
1723
+ batch_size = class_queries_logits.shape[0]
1724
+ num_labels = class_queries_logits.shape[-1] - 1
1725
+
1726
+ mask_probs = masks_queries_logits.sigmoid() # [batch_size, num_queries, height, width]
1727
+
1728
+ # Predicted label and score of each query (batch_size, num_queries)
1729
+ pred_scores, pred_labels = nn.functional.softmax(class_queries_logits, dim=-1).max(-1)
1730
+
1731
+ # Loop over items in batch size
1732
+ results: List[Dict[str, TensorType]] = []
1733
+
1734
+ for i in range(batch_size):
1735
+ mask_probs_item, pred_scores_item, pred_labels_item = remove_low_and_no_objects(
1736
+ mask_probs[i], pred_scores[i], pred_labels[i], threshold, num_labels
1737
+ )
1738
+
1739
+ # No mask found
1740
+ if mask_probs_item.shape[0] <= 0:
1741
+ height, width = target_sizes[i] if target_sizes is not None else mask_probs_item.shape[1:]
1742
+ segmentation = torch.zeros((height, width)) - 1
1743
+ results.append({"segmentation": segmentation, "segments_info": []})
1744
+ continue
1745
+
1746
+ # Get segmentation map and segment information of batch item
1747
+ target_size = target_sizes[i] if target_sizes is not None else None
1748
+ segmentation, segments = compute_segments(
1749
+ mask_probs=mask_probs_item,
1750
+ pred_scores=pred_scores_item,
1751
+ pred_labels=pred_labels_item,
1752
+ mask_threshold=mask_threshold,
1753
+ overlap_mask_area_threshold=overlap_mask_area_threshold,
1754
+ label_ids_to_fuse=[],
1755
+ target_size=target_size,
1756
+ )
1757
+
1758
+ # Return segmentation map in run-length encoding (RLE) format
1759
+ if return_coco_annotation:
1760
+ segmentation = convert_segmentation_to_rle(segmentation)
1761
+
1762
+ results.append({"segmentation": segmentation, "segments_info": segments})
1763
+ return results
1764
+
1765
+ # Copied from transformers.models.detr.image_processing_detr.DetrImageProcessor.post_process_panoptic_segmentation with Detr->ConditionalDetr
1766
+ def post_process_panoptic_segmentation(
1767
+ self,
1768
+ outputs,
1769
+ threshold: float = 0.5,
1770
+ mask_threshold: float = 0.5,
1771
+ overlap_mask_area_threshold: float = 0.8,
1772
+ label_ids_to_fuse: Optional[Set[int]] = None,
1773
+ target_sizes: Optional[List[Tuple[int, int]]] = None,
1774
+ ) -> List[Dict]:
1775
+ """
1776
+ Converts the output of [`ConditionalDetrForSegmentation`] into image panoptic segmentation predictions. Only supports
1777
+ PyTorch.
1778
+
1779
+ Args:
1780
+ outputs ([`ConditionalDetrForSegmentation`]):
1781
+ The outputs from [`ConditionalDetrForSegmentation`].
1782
+ threshold (`float`, *optional*, defaults to 0.5):
1783
+ The probability score threshold to keep predicted instance masks.
1784
+ mask_threshold (`float`, *optional*, defaults to 0.5):
1785
+ Threshold to use when turning the predicted masks into binary values.
1786
+ overlap_mask_area_threshold (`float`, *optional*, defaults to 0.8):
1787
+ The overlap mask area threshold to merge or discard small disconnected parts within each binary
1788
+ instance mask.
1789
+ label_ids_to_fuse (`Set[int]`, *optional*):
1790
+ The labels in this state will have all their instances be fused together. For instance we could say
1791
+ there can only be one sky in an image, but several persons, so the label ID for sky would be in that
1792
+ set, but not the one for person.
1793
+ target_sizes (`List[Tuple]`, *optional*):
1794
+ List of length (batch_size), where each list item (`Tuple[int, int]]`) corresponds to the requested
1795
+ final size (height, width) of each prediction in batch. If unset, predictions will not be resized.
1796
+ Returns:
1797
+ `List[Dict]`: A list of dictionaries, one per image, each dictionary containing two keys:
1798
+ - **segmentation** -- a tensor of shape `(height, width)` where each pixel represents a `segment_id` or
1799
+ `None` if no mask if found above `threshold`. If `target_sizes` is specified, segmentation is resized to
1800
+ the corresponding `target_sizes` entry.
1801
+ - **segments_info** -- A dictionary that contains additional information on each segment.
1802
+ - **id** -- an integer representing the `segment_id`.
1803
+ - **label_id** -- An integer representing the label / semantic class id corresponding to `segment_id`.
1804
+ - **was_fused** -- a boolean, `True` if `label_id` was in `label_ids_to_fuse`, `False` otherwise.
1805
+ Multiple instances of the same class / label were fused and assigned a single `segment_id`.
1806
+ - **score** -- Prediction score of segment with `segment_id`.
1807
+ """
1808
+
1809
+ if label_ids_to_fuse is None:
1810
+ logger.warning_once("`label_ids_to_fuse` unset. No instance will be fused.")
1811
+ label_ids_to_fuse = set()
1812
+
1813
+ class_queries_logits = outputs.logits # [batch_size, num_queries, num_classes+1]
1814
+ masks_queries_logits = outputs.pred_masks # [batch_size, num_queries, height, width]
1815
+
1816
+ batch_size = class_queries_logits.shape[0]
1817
+ num_labels = class_queries_logits.shape[-1] - 1
1818
+
1819
+ mask_probs = masks_queries_logits.sigmoid() # [batch_size, num_queries, height, width]
1820
+
1821
+ # Predicted label and score of each query (batch_size, num_queries)
1822
+ pred_scores, pred_labels = nn.functional.softmax(class_queries_logits, dim=-1).max(-1)
1823
+
1824
+ # Loop over items in batch size
1825
+ results: List[Dict[str, TensorType]] = []
1826
+
1827
+ for i in range(batch_size):
1828
+ mask_probs_item, pred_scores_item, pred_labels_item = remove_low_and_no_objects(
1829
+ mask_probs[i], pred_scores[i], pred_labels[i], threshold, num_labels
1830
+ )
1831
+
1832
+ # No mask found
1833
+ if mask_probs_item.shape[0] <= 0:
1834
+ height, width = target_sizes[i] if target_sizes is not None else mask_probs_item.shape[1:]
1835
+ segmentation = torch.zeros((height, width)) - 1
1836
+ results.append({"segmentation": segmentation, "segments_info": []})
1837
+ continue
1838
+
1839
+ # Get segmentation map and segment information of batch item
1840
+ target_size = target_sizes[i] if target_sizes is not None else None
1841
+ segmentation, segments = compute_segments(
1842
+ mask_probs=mask_probs_item,
1843
+ pred_scores=pred_scores_item,
1844
+ pred_labels=pred_labels_item,
1845
+ mask_threshold=mask_threshold,
1846
+ overlap_mask_area_threshold=overlap_mask_area_threshold,
1847
+ label_ids_to_fuse=label_ids_to_fuse,
1848
+ target_size=target_size,
1849
+ )
1850
+
1851
+ results.append({"segmentation": segmentation, "segments_info": segments})
1852
+ return results
1853
+
1854
+
1855
+ __all__ = ["ConditionalDetrImageProcessor"]
lib/python3.12/site-packages/transformers/models/conditional_detr/modeling_conditional_detr.py ADDED
The diff for this file is too large to render. See raw diff
 
lib/python3.12/site-packages/transformers/models/convnext/__init__.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 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 _LazyModule
17
+ from ...utils.import_utils import define_import_structure
18
+
19
+
20
+ if TYPE_CHECKING:
21
+ from .configuration_convnext import *
22
+ from .feature_extraction_convnext import *
23
+ from .image_processing_convnext import *
24
+ from .image_processing_convnext_fast import *
25
+ from .modeling_convnext import *
26
+ from .modeling_tf_convnext import *
27
+ else:
28
+ import sys
29
+
30
+ _file = globals()["__file__"]
31
+ sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__)
lib/python3.12/site-packages/transformers/models/convnext/__pycache__/__init__.cpython-312.pyc ADDED
Binary file (835 Bytes). View file
 
lib/python3.12/site-packages/transformers/models/convnext/__pycache__/configuration_convnext.cpython-312.pyc ADDED
Binary file (6.52 kB). View file
 
lib/python3.12/site-packages/transformers/models/convnext/__pycache__/feature_extraction_convnext.cpython-312.pyc ADDED
Binary file (1.24 kB). View file
 
lib/python3.12/site-packages/transformers/models/convnext/__pycache__/image_processing_convnext.cpython-312.pyc ADDED
Binary file (14.8 kB). View file