AdithyaSK HF Staff commited on
Commit
496153a
·
verified ·
1 Parent(s): 8bc33d3

Stage Harbor release files 50501-51000

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/big_bird/test_modeling_big_bird.py +969 -0
  2. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/big_bird/test_modeling_flax_big_bird.py +224 -0
  3. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/big_bird/test_tokenization_big_bird.py +233 -0
  4. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bigbird_pegasus/__init__.py +0 -0
  5. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bigbird_pegasus/test_modeling_bigbird_pegasus.py +0 -0
  6. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/biogpt/__init__.py +0 -0
  7. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/biogpt/test_modeling_biogpt.py +461 -0
  8. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/biogpt/test_tokenization_biogpt.py +99 -0
  9. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bit/__init__.py +0 -0
  10. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bit/test_modeling_bit.py +310 -0
  11. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blenderbot/__init__.py +0 -0
  12. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blenderbot/test_modeling_blenderbot.py +559 -0
  13. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blenderbot/test_modeling_flax_blenderbot.py +418 -0
  14. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blenderbot/test_modeling_tf_blenderbot.py +235 -0
  15. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blenderbot/test_tokenization_blenderbot.py +75 -0
  16. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blenderbot_small/__init__.py +0 -0
  17. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blenderbot_small/test_modeling_blenderbot_small.py +568 -0
  18. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blenderbot_small/test_modeling_flax_blenderbot_small.py +411 -0
  19. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blenderbot_small/test_modeling_tf_blenderbot_small.py +257 -0
  20. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blenderbot_small/test_tokenization_blenderbot_small.py +88 -0
  21. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blip/__init__.py +0 -0
  22. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blip/test_image_processing_blip.py +148 -0
  23. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blip/test_modeling_blip.py +1435 -0
  24. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blip/test_modeling_blip_text.py +183 -0
  25. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blip/test_modeling_tf_blip.py +901 -0
  26. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blip/test_modeling_tf_blip_text.py +181 -0
  27. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blip/test_processor_blip.py +167 -0
  28. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blip_2/__init__.py +0 -0
  29. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blip_2/test_modeling_blip_2.py +0 -0
  30. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blip_2/test_processor_blip_2.py +141 -0
  31. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bloom/__init__.py +0 -0
  32. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bloom/test_modeling_bloom.py +825 -0
  33. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bloom/test_modeling_flax_bloom.py +251 -0
  34. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bloom/test_tokenization_bloom.py +162 -0
  35. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bridgetower/__init__.py +0 -0
  36. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bridgetower/test_image_processing_bridgetower.py +158 -0
  37. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bridgetower/test_modeling_bridgetower.py +692 -0
  38. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bridgetower/test_processor_bridgetower.py +203 -0
  39. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bros/__init__.py +0 -0
  40. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bros/test_modeling_bros.py +455 -0
  41. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/byt5/__init__.py +0 -0
  42. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/byt5/test_tokenization_byt5.py +362 -0
  43. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/camembert/__init__.py +0 -0
  44. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/camembert/test_modeling_camembert.py +84 -0
  45. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/camembert/test_modeling_tf_camembert.py +56 -0
  46. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/camembert/test_tokenization_camembert.py +220 -0
  47. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/canine/__init__.py +0 -0
  48. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/canine/test_modeling_canine.py +573 -0
  49. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/canine/test_tokenization_canine.py +334 -0
  50. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/chameleon/__init__.py +0 -0
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/big_bird/test_modeling_big_bird.py ADDED
@@ -0,0 +1,969 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Testing suite for the PyTorch BigBird model."""
16
+
17
+ import unittest
18
+
19
+ from transformers import BigBirdConfig, is_torch_available
20
+ from transformers.models.auto import get_values
21
+ from transformers.models.big_bird.tokenization_big_bird import BigBirdTokenizer
22
+ from transformers.testing_utils import require_torch, slow, torch_device
23
+
24
+ from ...test_configuration_common import ConfigTester
25
+ from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
26
+ from ...test_pipeline_mixin import PipelineTesterMixin
27
+
28
+
29
+ if is_torch_available():
30
+ import torch
31
+
32
+ from transformers import (
33
+ MODEL_FOR_PRETRAINING_MAPPING,
34
+ BigBirdForCausalLM,
35
+ BigBirdForMaskedLM,
36
+ BigBirdForMultipleChoice,
37
+ BigBirdForPreTraining,
38
+ BigBirdForQuestionAnswering,
39
+ BigBirdForSequenceClassification,
40
+ BigBirdForTokenClassification,
41
+ BigBirdModel,
42
+ )
43
+
44
+
45
+ class BigBirdModelTester:
46
+ def __init__(
47
+ self,
48
+ parent,
49
+ batch_size=7,
50
+ seq_length=128,
51
+ is_training=True,
52
+ use_input_mask=True,
53
+ use_token_type_ids=True,
54
+ use_labels=True,
55
+ vocab_size=99,
56
+ hidden_size=32,
57
+ num_hidden_layers=2,
58
+ num_attention_heads=4,
59
+ intermediate_size=37,
60
+ hidden_act="gelu_new",
61
+ hidden_dropout_prob=0.1,
62
+ attention_probs_dropout_prob=0.1,
63
+ max_position_embeddings=256,
64
+ type_vocab_size=16,
65
+ type_sequence_label_size=2,
66
+ initializer_range=0.02,
67
+ num_labels=3,
68
+ num_choices=4,
69
+ attention_type="block_sparse",
70
+ use_bias=True,
71
+ rescale_embeddings=False,
72
+ block_size=8,
73
+ num_rand_blocks=3,
74
+ position_embedding_type="absolute",
75
+ scope=None,
76
+ ):
77
+ self.parent = parent
78
+ self.batch_size = batch_size
79
+ self.seq_length = seq_length
80
+ self.is_training = is_training
81
+ self.use_input_mask = use_input_mask
82
+ self.use_token_type_ids = use_token_type_ids
83
+ self.use_labels = use_labels
84
+ self.vocab_size = vocab_size
85
+ self.hidden_size = hidden_size
86
+ self.num_hidden_layers = num_hidden_layers
87
+ self.num_attention_heads = num_attention_heads
88
+ self.intermediate_size = intermediate_size
89
+ self.hidden_act = hidden_act
90
+ self.hidden_dropout_prob = hidden_dropout_prob
91
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
92
+ self.max_position_embeddings = max_position_embeddings
93
+ self.type_vocab_size = type_vocab_size
94
+ self.type_sequence_label_size = type_sequence_label_size
95
+ self.initializer_range = initializer_range
96
+ self.num_labels = num_labels
97
+ self.num_choices = num_choices
98
+ self.scope = scope
99
+
100
+ self.attention_type = attention_type
101
+ self.use_bias = use_bias
102
+ self.rescale_embeddings = rescale_embeddings
103
+ self.block_size = block_size
104
+ self.num_rand_blocks = num_rand_blocks
105
+ self.position_embedding_type = position_embedding_type
106
+
107
+ def prepare_config_and_inputs(self):
108
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
109
+
110
+ input_mask = None
111
+ if self.use_input_mask:
112
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
113
+
114
+ token_type_ids = None
115
+ if self.use_token_type_ids:
116
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
117
+
118
+ sequence_labels = None
119
+ token_labels = None
120
+ choice_labels = None
121
+ if self.use_labels:
122
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
123
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
124
+ choice_labels = ids_tensor([self.batch_size], self.num_choices)
125
+
126
+ config = self.get_config()
127
+
128
+ return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
129
+
130
+ def get_config(self):
131
+ return BigBirdConfig(
132
+ vocab_size=self.vocab_size,
133
+ hidden_size=self.hidden_size,
134
+ num_hidden_layers=self.num_hidden_layers,
135
+ num_attention_heads=self.num_attention_heads,
136
+ intermediate_size=self.intermediate_size,
137
+ hidden_act=self.hidden_act,
138
+ hidden_dropout_prob=self.hidden_dropout_prob,
139
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
140
+ max_position_embeddings=self.max_position_embeddings,
141
+ type_vocab_size=self.type_vocab_size,
142
+ is_encoder_decoder=False,
143
+ initializer_range=self.initializer_range,
144
+ attention_type=self.attention_type,
145
+ use_bias=self.use_bias,
146
+ rescale_embeddings=self.rescale_embeddings,
147
+ block_size=self.block_size,
148
+ num_random_blocks=self.num_rand_blocks,
149
+ position_embedding_type=self.position_embedding_type,
150
+ )
151
+
152
+ def prepare_config_and_inputs_for_decoder(self):
153
+ (
154
+ config,
155
+ input_ids,
156
+ token_type_ids,
157
+ input_mask,
158
+ sequence_labels,
159
+ token_labels,
160
+ choice_labels,
161
+ ) = self.prepare_config_and_inputs()
162
+
163
+ config.is_decoder = True
164
+ encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
165
+ encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
166
+
167
+ return (
168
+ config,
169
+ input_ids,
170
+ token_type_ids,
171
+ input_mask,
172
+ sequence_labels,
173
+ token_labels,
174
+ choice_labels,
175
+ encoder_hidden_states,
176
+ encoder_attention_mask,
177
+ )
178
+
179
+ def create_and_check_model(
180
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
181
+ ):
182
+ model = BigBirdModel(config=config)
183
+ model.to(torch_device)
184
+ model.eval()
185
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
186
+ result = model(input_ids, token_type_ids=token_type_ids)
187
+ result = model(input_ids)
188
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
189
+
190
+ def create_and_check_for_pretraining(
191
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
192
+ ):
193
+ model = BigBirdForPreTraining(config=config)
194
+ model.to(torch_device)
195
+ model.eval()
196
+ result = model(
197
+ input_ids,
198
+ attention_mask=input_mask,
199
+ token_type_ids=token_type_ids,
200
+ labels=token_labels,
201
+ next_sentence_label=sequence_labels,
202
+ )
203
+ self.parent.assertEqual(result.prediction_logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
204
+ self.parent.assertEqual(result.seq_relationship_logits.shape, (self.batch_size, config.num_labels))
205
+
206
+ def create_and_check_model_as_decoder(
207
+ self,
208
+ config,
209
+ input_ids,
210
+ token_type_ids,
211
+ input_mask,
212
+ sequence_labels,
213
+ token_labels,
214
+ choice_labels,
215
+ encoder_hidden_states,
216
+ encoder_attention_mask,
217
+ ):
218
+ config.add_cross_attention = True
219
+ model = BigBirdModel(config)
220
+ model.to(torch_device)
221
+ model.eval()
222
+ result = model(
223
+ input_ids,
224
+ attention_mask=input_mask,
225
+ token_type_ids=token_type_ids,
226
+ encoder_hidden_states=encoder_hidden_states,
227
+ encoder_attention_mask=encoder_attention_mask,
228
+ )
229
+ result = model(
230
+ input_ids,
231
+ attention_mask=input_mask,
232
+ token_type_ids=token_type_ids,
233
+ encoder_hidden_states=encoder_hidden_states,
234
+ )
235
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
236
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
237
+
238
+ def create_and_check_for_causal_lm(
239
+ self,
240
+ config,
241
+ input_ids,
242
+ token_type_ids,
243
+ input_mask,
244
+ sequence_labels,
245
+ token_labels,
246
+ choice_labels,
247
+ encoder_hidden_states,
248
+ encoder_attention_mask,
249
+ ):
250
+ model = BigBirdForCausalLM(config=config)
251
+ model.to(torch_device)
252
+ model.eval()
253
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
254
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
255
+
256
+ def create_and_check_for_masked_lm(
257
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
258
+ ):
259
+ model = BigBirdForMaskedLM(config=config)
260
+ model.to(torch_device)
261
+ model.eval()
262
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
263
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
264
+
265
+ def create_and_check_decoder_model_past_large_inputs(
266
+ self,
267
+ config,
268
+ input_ids,
269
+ token_type_ids,
270
+ input_mask,
271
+ sequence_labels,
272
+ token_labels,
273
+ choice_labels,
274
+ encoder_hidden_states,
275
+ encoder_attention_mask,
276
+ ):
277
+ config.is_decoder = True
278
+ config.add_cross_attention = True
279
+ model = BigBirdForCausalLM(config=config)
280
+ model.to(torch_device)
281
+ model.eval()
282
+
283
+ # first forward pass
284
+ outputs = model(
285
+ input_ids,
286
+ attention_mask=input_mask,
287
+ encoder_hidden_states=encoder_hidden_states,
288
+ encoder_attention_mask=encoder_attention_mask,
289
+ use_cache=True,
290
+ )
291
+ past_key_values = outputs.past_key_values
292
+
293
+ # create hypothetical multiple next token and extent to next_input_ids
294
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
295
+ next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
296
+
297
+ # append to next input_ids and
298
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
299
+ next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
300
+
301
+ output_from_no_past = model(
302
+ next_input_ids,
303
+ attention_mask=next_attention_mask,
304
+ encoder_hidden_states=encoder_hidden_states,
305
+ encoder_attention_mask=encoder_attention_mask,
306
+ output_hidden_states=True,
307
+ )["hidden_states"][0]
308
+ output_from_past = model(
309
+ next_tokens,
310
+ attention_mask=next_attention_mask,
311
+ encoder_hidden_states=encoder_hidden_states,
312
+ encoder_attention_mask=encoder_attention_mask,
313
+ past_key_values=past_key_values,
314
+ output_hidden_states=True,
315
+ )["hidden_states"][0]
316
+
317
+ # select random slice
318
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
319
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
320
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
321
+
322
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
323
+
324
+ # test that outputs are equal for slice
325
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
326
+
327
+ def create_and_check_for_question_answering(
328
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
329
+ ):
330
+ model = BigBirdForQuestionAnswering(config=config)
331
+ model.to(torch_device)
332
+ model.eval()
333
+ result = model(
334
+ input_ids,
335
+ attention_mask=input_mask,
336
+ token_type_ids=token_type_ids,
337
+ start_positions=sequence_labels,
338
+ end_positions=sequence_labels,
339
+ )
340
+ self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
341
+ self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
342
+
343
+ def create_and_check_for_sequence_classification(
344
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
345
+ ):
346
+ config.num_labels = self.num_labels
347
+ model = BigBirdForSequenceClassification(config)
348
+ model.to(torch_device)
349
+ model.eval()
350
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels)
351
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
352
+
353
+ def create_and_check_for_token_classification(
354
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
355
+ ):
356
+ config.num_labels = self.num_labels
357
+ model = BigBirdForTokenClassification(config=config)
358
+ model.to(torch_device)
359
+ model.eval()
360
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
361
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
362
+
363
+ def create_and_check_for_multiple_choice(
364
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
365
+ ):
366
+ config.num_choices = self.num_choices
367
+ model = BigBirdForMultipleChoice(config=config)
368
+ model.to(torch_device)
369
+ model.eval()
370
+ multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
371
+ multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
372
+ multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
373
+ result = model(
374
+ multiple_choice_inputs_ids,
375
+ attention_mask=multiple_choice_input_mask,
376
+ token_type_ids=multiple_choice_token_type_ids,
377
+ labels=choice_labels,
378
+ )
379
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
380
+
381
+ def prepare_config_and_inputs_for_common(self):
382
+ config_and_inputs = self.prepare_config_and_inputs()
383
+ (
384
+ config,
385
+ input_ids,
386
+ token_type_ids,
387
+ input_mask,
388
+ sequence_labels,
389
+ token_labels,
390
+ choice_labels,
391
+ ) = config_and_inputs
392
+ inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
393
+ return config, inputs_dict
394
+
395
+ def create_and_check_for_auto_padding(
396
+ self,
397
+ config,
398
+ input_ids,
399
+ token_type_ids,
400
+ input_mask,
401
+ sequence_labels,
402
+ token_labels,
403
+ choice_labels,
404
+ ):
405
+ model = BigBirdModel(config)
406
+ model.to(torch_device)
407
+ model.eval()
408
+ result = model(input_ids)
409
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
410
+
411
+ def create_and_check_for_change_to_full_attn(
412
+ self,
413
+ config,
414
+ input_ids,
415
+ token_type_ids,
416
+ input_mask,
417
+ sequence_labels,
418
+ token_labels,
419
+ choice_labels,
420
+ ):
421
+ model = BigBirdModel(config)
422
+ model.to(torch_device)
423
+ model.eval()
424
+ result = model(input_ids)
425
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
426
+ # the config should not be changed
427
+ self.parent.assertTrue(model.config.attention_type == "block_sparse")
428
+
429
+
430
+ @require_torch
431
+ class BigBirdModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
432
+ # head masking & pruning is currently not supported for big bird
433
+ test_head_masking = False
434
+ test_pruning = False
435
+
436
+ # torchscript should be possible, but takes prohibitively long to test.
437
+ # Also torchscript is not an important feature to have in the beginning.
438
+ test_torchscript = False
439
+
440
+ all_model_classes = (
441
+ (
442
+ BigBirdModel,
443
+ BigBirdForPreTraining,
444
+ BigBirdForMaskedLM,
445
+ BigBirdForCausalLM,
446
+ BigBirdForMultipleChoice,
447
+ BigBirdForQuestionAnswering,
448
+ BigBirdForSequenceClassification,
449
+ BigBirdForTokenClassification,
450
+ )
451
+ if is_torch_available()
452
+ else ()
453
+ )
454
+ all_generative_model_classes = (BigBirdForCausalLM,) if is_torch_available() else ()
455
+ pipeline_model_mapping = (
456
+ {
457
+ "feature-extraction": BigBirdModel,
458
+ "fill-mask": BigBirdForMaskedLM,
459
+ "question-answering": BigBirdForQuestionAnswering,
460
+ "text-classification": BigBirdForSequenceClassification,
461
+ "text-generation": BigBirdForCausalLM,
462
+ "token-classification": BigBirdForTokenClassification,
463
+ "zero-shot": BigBirdForSequenceClassification,
464
+ }
465
+ if is_torch_available()
466
+ else {}
467
+ )
468
+
469
+ # special case for ForPreTraining model
470
+ def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
471
+ inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
472
+
473
+ if return_labels:
474
+ if model_class in get_values(MODEL_FOR_PRETRAINING_MAPPING):
475
+ inputs_dict["labels"] = torch.zeros(
476
+ (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device
477
+ )
478
+ inputs_dict["next_sentence_label"] = torch.zeros(
479
+ self.model_tester.batch_size, dtype=torch.long, device=torch_device
480
+ )
481
+ return inputs_dict
482
+
483
+ def setUp(self):
484
+ self.model_tester = BigBirdModelTester(self)
485
+ self.config_tester = ConfigTester(self, config_class=BigBirdConfig, hidden_size=37)
486
+
487
+ def test_config(self):
488
+ self.config_tester.run_common_tests()
489
+
490
+ def test_model(self):
491
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
492
+ self.model_tester.create_and_check_model(*config_and_inputs)
493
+
494
+ def test_for_pretraining(self):
495
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
496
+ self.model_tester.create_and_check_for_pretraining(*config_and_inputs)
497
+
498
+ def test_for_masked_lm(self):
499
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
500
+ self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
501
+
502
+ def test_for_multiple_choice(self):
503
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
504
+ self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
505
+
506
+ def test_decoder_model_past_with_large_inputs(self):
507
+ config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
508
+ self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
509
+
510
+ def test_for_question_answering(self):
511
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
512
+ self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
513
+
514
+ def test_for_sequence_classification(self):
515
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
516
+ self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs)
517
+
518
+ def test_for_token_classification(self):
519
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
520
+ self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
521
+
522
+ def test_model_as_decoder(self):
523
+ config_and_inputs = self.model_tester.prepare_config_and_inputs_for_decoder()
524
+ self.model_tester.create_and_check_model_as_decoder(*config_and_inputs)
525
+
526
+ def test_model_as_decoder_with_default_input_mask(self):
527
+ # This regression test was failing with PyTorch < 1.3
528
+ (
529
+ config,
530
+ input_ids,
531
+ token_type_ids,
532
+ input_mask,
533
+ sequence_labels,
534
+ token_labels,
535
+ choice_labels,
536
+ encoder_hidden_states,
537
+ encoder_attention_mask,
538
+ ) = self.model_tester.prepare_config_and_inputs_for_decoder()
539
+
540
+ input_mask = None
541
+
542
+ self.model_tester.create_and_check_model_as_decoder(
543
+ config,
544
+ input_ids,
545
+ token_type_ids,
546
+ input_mask,
547
+ sequence_labels,
548
+ token_labels,
549
+ choice_labels,
550
+ encoder_hidden_states,
551
+ encoder_attention_mask,
552
+ )
553
+
554
+ def test_retain_grad_hidden_states_attentions(self):
555
+ # bigbird cannot keep gradients in attentions when `attention_type=block_sparse`
556
+
557
+ if self.model_tester.attention_type == "original_full":
558
+ super().test_retain_grad_hidden_states_attentions()
559
+
560
+ @slow
561
+ def test_model_from_pretrained(self):
562
+ model_name = "google/bigbird-roberta-base"
563
+ model = BigBirdForPreTraining.from_pretrained(model_name)
564
+ self.assertIsNotNone(model)
565
+
566
+ def test_model_various_attn_type(self):
567
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
568
+ for type in ["original_full", "block_sparse"]:
569
+ config_and_inputs[0].attention_type = type
570
+ self.model_tester.create_and_check_model(*config_and_inputs)
571
+
572
+ def test_fast_integration(self):
573
+ # fmt: off
574
+ input_ids = torch.tensor(
575
+ [[6, 117, 33, 36, 70, 22, 63, 31, 71, 72, 88, 58, 109, 49, 48, 116, 92, 6, 19, 95, 118, 100, 80, 111, 93, 2, 31, 84, 26, 5, 6, 82, 46, 96, 109, 4, 39, 19, 109, 13, 92, 31, 36, 90, 111, 18, 75, 6, 56, 74, 16, 42, 56, 92, 69, 108, 127, 81, 82, 41, 106, 19, 44, 24, 82, 121, 120, 65, 36, 26, 72, 13, 36, 98, 43, 64, 8, 53, 100, 92, 51, 122, 66, 17, 61, 50, 104, 127, 26, 35, 94, 23, 110, 71, 80, 67, 109, 111, 44, 19, 51, 41, 86, 71, 76, 44, 18, 68, 44, 77, 107, 81, 98, 126, 100, 2, 49, 98, 84, 39, 23, 98, 52, 46, 10, 82, 121, 73],[6, 117, 33, 36, 70, 22, 63, 31, 71, 72, 88, 58, 109, 49, 48, 116, 92, 6, 19, 95, 118, 100, 80, 111, 93, 2, 31, 84, 26, 5, 6, 82, 46, 96, 109, 4, 39, 19, 109, 13, 92, 31, 36, 90, 111, 18, 75, 6, 56, 74, 16, 42, 56, 92, 69, 108, 127, 81, 82, 41, 106, 19, 44, 24, 82, 121, 120, 65, 36, 26, 72, 13, 36, 98, 43, 64, 8, 53, 100, 92, 51, 12, 66, 17, 61, 50, 104, 127, 26, 35, 94, 23, 110, 71, 80, 67, 109, 111, 44, 19, 51, 41, 86, 71, 76, 28, 18, 68, 44, 77, 107, 81, 98, 126, 100, 2, 49, 18, 84, 39, 23, 98, 52, 46, 10, 82, 121, 73]], # noqa: E231
576
+ dtype=torch.long,
577
+ device=torch_device,
578
+ )
579
+ # fmt: on
580
+ input_ids = input_ids % self.model_tester.vocab_size
581
+ input_ids[1] = input_ids[1] - 1
582
+
583
+ attention_mask = torch.ones((input_ids.shape), device=torch_device)
584
+ attention_mask[:, :-10] = 0
585
+
586
+ config, _, _, _, _, _, _ = self.model_tester.prepare_config_and_inputs()
587
+ torch.manual_seed(0)
588
+ model = BigBirdModel(config).eval().to(torch_device)
589
+
590
+ with torch.no_grad():
591
+ hidden_states = model(input_ids, attention_mask=attention_mask).last_hidden_state
592
+ self.assertTrue(
593
+ torch.allclose(
594
+ hidden_states[0, 0, :5],
595
+ torch.tensor([1.4825, 0.0774, 0.8226, -0.2962, -0.9593], device=torch_device),
596
+ atol=1e-3,
597
+ )
598
+ )
599
+
600
+ def test_auto_padding(self):
601
+ self.model_tester.seq_length = 241
602
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
603
+ self.model_tester.create_and_check_for_auto_padding(*config_and_inputs)
604
+
605
+ def test_for_change_to_full_attn(self):
606
+ self.model_tester.seq_length = 9
607
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
608
+ self.model_tester.create_and_check_for_change_to_full_attn(*config_and_inputs)
609
+
610
+ @unittest.skip(
611
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
612
+ )
613
+ def test_training_gradient_checkpointing(self):
614
+ pass
615
+
616
+ @unittest.skip(
617
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
618
+ )
619
+ def test_training_gradient_checkpointing_use_reentrant(self):
620
+ pass
621
+
622
+ @unittest.skip(
623
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
624
+ )
625
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
626
+ pass
627
+
628
+ # overwrite from common in order to skip the check on `attentions`
629
+ def check_pt_flax_outputs(self, fx_outputs, pt_outputs, model_class, tol=1e-5, name="outputs", attributes=None):
630
+ # `bigbird_block_sparse_attention` in `FlaxBigBird` returns `attention_probs = None`, while in PyTorch version,
631
+ # an effort was done to return `attention_probs` (yet to be verified).
632
+ if name.startswith("outputs.attentions"):
633
+ return
634
+ else:
635
+ super().check_pt_flax_outputs(fx_outputs, pt_outputs, model_class, tol, name, attributes)
636
+
637
+
638
+ @require_torch
639
+ @slow
640
+ class BigBirdModelIntegrationTest(unittest.TestCase):
641
+ # we can have this true once block_sparse attn_probs works accurately
642
+ test_attention_probs = False
643
+
644
+ def _get_dummy_input_ids(self):
645
+ # fmt: off
646
+ ids = torch.tensor(
647
+ [[6, 117, 33, 36, 70, 22, 63, 31, 71, 72, 88, 58, 109, 49, 48, 116, 92, 6, 19, 95, 118, 100, 80, 111, 93, 2, 31, 84, 26, 5, 6, 82, 46, 96, 109, 4, 39, 19, 109, 13, 92, 31, 36, 90, 111, 18, 75, 6, 56, 74, 16, 42, 56, 92, 69, 108, 127, 81, 82, 41, 106, 19, 44, 24, 82, 121, 120, 65, 36, 26, 72, 13, 36, 98, 43, 64, 8, 53, 100, 92, 51, 122, 66, 17, 61, 50, 104, 127, 26, 35, 94, 23, 110, 71, 80, 67, 109, 111, 44, 19, 51, 41, 86, 71, 76, 44, 18, 68, 44, 77, 107, 81, 98, 126, 100, 2, 49, 98, 84, 39, 23, 98, 52, 46, 10, 82, 121, 73]], # noqa: E231
648
+ dtype=torch.long,
649
+ device=torch_device,
650
+ )
651
+ # fmt: on
652
+ return ids
653
+
654
+ def test_inference_block_sparse_pretraining(self):
655
+ model = BigBirdForPreTraining.from_pretrained("google/bigbird-roberta-base", attention_type="block_sparse")
656
+ model.to(torch_device)
657
+
658
+ input_ids = torch.tensor([[20920, 232, 328, 1437] * 1024], dtype=torch.long, device=torch_device)
659
+ with torch.no_grad():
660
+ outputs = model(input_ids)
661
+ prediction_logits = outputs.prediction_logits
662
+ seq_relationship_logits = outputs.seq_relationship_logits
663
+
664
+ self.assertEqual(prediction_logits.shape, torch.Size((1, 4096, 50358)))
665
+ self.assertEqual(seq_relationship_logits.shape, torch.Size((1, 2)))
666
+
667
+ expected_prediction_logits_slice = torch.tensor(
668
+ [
669
+ [-0.5583, 0.0475, -0.2508, 7.4423],
670
+ [0.7409, 1.4460, -0.7593, 7.7010],
671
+ [1.9150, 3.1395, 5.8840, 9.3498],
672
+ [-0.1854, -1.4640, -2.2052, 3.7968],
673
+ ],
674
+ device=torch_device,
675
+ )
676
+
677
+ self.assertTrue(
678
+ torch.allclose(prediction_logits[0, 128:132, 128:132], expected_prediction_logits_slice, atol=1e-4)
679
+ )
680
+
681
+ expected_seq_relationship_logits = torch.tensor([[46.9465, 47.9517]], device=torch_device)
682
+ self.assertTrue(torch.allclose(seq_relationship_logits, expected_seq_relationship_logits, atol=1e-4))
683
+
684
+ def test_inference_full_pretraining(self):
685
+ model = BigBirdForPreTraining.from_pretrained("google/bigbird-roberta-base", attention_type="original_full")
686
+ model.to(torch_device)
687
+
688
+ input_ids = torch.tensor([[20920, 232, 328, 1437] * 512], dtype=torch.long, device=torch_device)
689
+ with torch.no_grad():
690
+ outputs = model(input_ids)
691
+ prediction_logits = outputs.prediction_logits
692
+ seq_relationship_logits = outputs.seq_relationship_logits
693
+
694
+ self.assertEqual(prediction_logits.shape, torch.Size((1, 512 * 4, 50358)))
695
+ self.assertEqual(seq_relationship_logits.shape, torch.Size((1, 2)))
696
+
697
+ expected_prediction_logits_slice = torch.tensor(
698
+ [
699
+ [0.1499, -1.1217, 0.1990, 8.4499],
700
+ [-2.7757, -3.0687, -4.8577, 7.5156],
701
+ [1.5446, 0.1982, 4.3016, 10.4281],
702
+ [-1.3705, -4.0130, -3.9629, 5.1526],
703
+ ],
704
+ device=torch_device,
705
+ )
706
+ self.assertTrue(
707
+ torch.allclose(prediction_logits[0, 128:132, 128:132], expected_prediction_logits_slice, atol=1e-4)
708
+ )
709
+
710
+ expected_seq_relationship_logits = torch.tensor([[41.4503, 41.2406]], device=torch_device)
711
+ self.assertTrue(torch.allclose(seq_relationship_logits, expected_seq_relationship_logits, atol=1e-4))
712
+
713
+ def test_block_sparse_attention_probs(self):
714
+ """
715
+ Asserting if outputted attention matrix is similar to hard coded attention matrix
716
+ """
717
+
718
+ if not self.test_attention_probs:
719
+ self.skipTest("test_attention_probs is set to False")
720
+
721
+ model = BigBirdModel.from_pretrained(
722
+ "google/bigbird-roberta-base", attention_type="block_sparse", num_random_blocks=3, block_size=16
723
+ )
724
+ model.to(torch_device)
725
+ model.eval()
726
+ config = model.config
727
+
728
+ input_ids = self._get_dummy_input_ids()
729
+
730
+ hidden_states = model.embeddings(input_ids)
731
+
732
+ batch_size, seqlen, _ = hidden_states.size()
733
+ attn_mask = torch.ones(batch_size, seqlen, device=torch_device, dtype=torch.float)
734
+ to_seq_length = from_seq_length = seqlen
735
+ from_block_size = to_block_size = config.block_size
736
+
737
+ blocked_mask, band_mask, from_mask, to_mask = model.create_masks_for_block_sparse_attn(
738
+ attn_mask, config.block_size
739
+ )
740
+ from_blocked_mask = to_blocked_mask = blocked_mask
741
+
742
+ for i in range(config.num_hidden_layers):
743
+ pointer = model.encoder.layer[i].attention.self
744
+
745
+ query_layer = pointer.transpose_for_scores(pointer.query(hidden_states))
746
+ key_layer = pointer.transpose_for_scores(pointer.key(hidden_states))
747
+ value_layer = pointer.transpose_for_scores(pointer.value(hidden_states))
748
+
749
+ context_layer, attention_probs = pointer.bigbird_block_sparse_attention(
750
+ query_layer,
751
+ key_layer,
752
+ value_layer,
753
+ band_mask,
754
+ from_mask,
755
+ to_mask,
756
+ from_blocked_mask,
757
+ to_blocked_mask,
758
+ pointer.num_attention_heads,
759
+ pointer.num_random_blocks,
760
+ pointer.attention_head_size,
761
+ from_block_size,
762
+ to_block_size,
763
+ batch_size,
764
+ from_seq_length,
765
+ to_seq_length,
766
+ seed=pointer.seed,
767
+ plan_from_length=None,
768
+ plan_num_rand_blocks=None,
769
+ output_attentions=True,
770
+ )
771
+
772
+ context_layer = context_layer.contiguous().view(batch_size, from_seq_length, -1)
773
+ cl = torch.einsum("bhqk,bhkd->bhqd", attention_probs, value_layer)
774
+ cl = cl.view(context_layer.size())
775
+
776
+ self.assertTrue(torch.allclose(context_layer, cl, atol=0.001))
777
+
778
+ def test_block_sparse_context_layer(self):
779
+ model = BigBirdModel.from_pretrained(
780
+ "google/bigbird-roberta-base", attention_type="block_sparse", num_random_blocks=3, block_size=16
781
+ )
782
+ model.to(torch_device)
783
+ model.eval()
784
+ config = model.config
785
+
786
+ input_ids = self._get_dummy_input_ids()
787
+ dummy_hidden_states = model.embeddings(input_ids)
788
+
789
+ attn_mask = torch.ones_like(input_ids, device=torch_device)
790
+ blocked_mask, band_mask, from_mask, to_mask = model.create_masks_for_block_sparse_attn(
791
+ attn_mask, config.block_size
792
+ )
793
+
794
+ targeted_cl = torch.tensor(
795
+ [
796
+ [0.1870, 1.5248, 0.2333, -0.0483, -0.0952, 1.8359, -0.0142, 0.1239, 0.0083, -0.0045],
797
+ [-0.0601, 0.1243, 0.1329, -0.1524, 0.2347, 0.0894, -0.2248, -0.2461, -0.0645, -0.0109],
798
+ [-0.0418, 0.1463, 0.1290, -0.1638, 0.2489, 0.0799, -0.2341, -0.2406, -0.0524, 0.0106],
799
+ [0.1859, 1.5182, 0.2324, -0.0473, -0.0952, 1.8295, -0.0148, 0.1242, 0.0080, -0.0045],
800
+ [0.1879, 1.5300, 0.2334, -0.0480, -0.0967, 1.8428, -0.0137, 0.1256, 0.0087, -0.0050],
801
+ [0.1852, 1.5149, 0.2330, -0.0492, -0.0936, 1.8236, -0.0154, 0.1210, 0.0080, -0.0048],
802
+ [0.1857, 1.5186, 0.2331, -0.0484, -0.0940, 1.8285, -0.0148, 0.1224, 0.0077, -0.0045],
803
+ [0.1884, 1.5336, 0.2334, -0.0469, -0.0974, 1.8477, -0.0132, 0.1266, 0.0085, -0.0046],
804
+ [0.1881, 1.5308, 0.2334, -0.0479, -0.0969, 1.8438, -0.0136, 0.1258, 0.0088, -0.0050],
805
+ [0.1849, 1.5143, 0.2329, -0.0491, -0.0930, 1.8230, -0.0156, 0.1209, 0.0074, -0.0047],
806
+ [0.1878, 1.5299, 0.2333, -0.0472, -0.0967, 1.8434, -0.0137, 0.1257, 0.0084, -0.0048],
807
+ [0.1873, 1.5260, 0.2333, -0.0478, -0.0961, 1.8383, -0.0142, 0.1245, 0.0083, -0.0048],
808
+ [0.1849, 1.5145, 0.2327, -0.0491, -0.0935, 1.8237, -0.0156, 0.1215, 0.0083, -0.0046],
809
+ [0.1866, 1.5232, 0.2332, -0.0488, -0.0950, 1.8342, -0.0143, 0.1237, 0.0084, -0.0047],
810
+ ],
811
+ device=torch_device,
812
+ )
813
+
814
+ context_layer = model.encoder.layer[0].attention.self(
815
+ dummy_hidden_states,
816
+ band_mask=band_mask,
817
+ from_mask=from_mask,
818
+ to_mask=to_mask,
819
+ from_blocked_mask=blocked_mask,
820
+ to_blocked_mask=blocked_mask,
821
+ )
822
+ context_layer = context_layer[0]
823
+
824
+ self.assertEqual(context_layer.shape, torch.Size((1, 128, 768)))
825
+ self.assertTrue(torch.allclose(context_layer[0, 64:78, 300:310], targeted_cl, atol=0.0001))
826
+
827
+ def test_tokenizer_inference(self):
828
+ tokenizer = BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base")
829
+ model = BigBirdModel.from_pretrained(
830
+ "google/bigbird-roberta-base", attention_type="block_sparse", num_random_blocks=3, block_size=16
831
+ )
832
+ model.to(torch_device)
833
+
834
+ text = [
835
+ "Transformer-based models are unable to process long sequences due to their self-attention operation,"
836
+ " which scales quadratically with the sequence length. To address this limitation, we introduce the"
837
+ " Longformer with an attention mechanism that scales linearly with sequence length, making it easy to"
838
+ " process documents of thousands of tokens or longer. Longformer’s attention mechanism is a drop-in"
839
+ " replacement for the standard self-attention and combines a local windowed attention with a task"
840
+ " motivated global attention. Following prior work on long-sequence transformers, we evaluate Longformer"
841
+ " on character-level language modeling and achieve state-of-the-art results on text8 and enwik8. In"
842
+ " contrast to most prior work, we also pretrain Longformer and finetune it on a variety of downstream"
843
+ " tasks. Our pretrained Longformer consistently outperforms RoBERTa on long document tasks and sets new"
844
+ " state-of-the-art results on WikiHop and TriviaQA."
845
+ ]
846
+ inputs = tokenizer(text)
847
+
848
+ for k in inputs:
849
+ inputs[k] = torch.tensor(inputs[k], device=torch_device, dtype=torch.long)
850
+
851
+ prediction = model(**inputs)
852
+ prediction = prediction[0]
853
+
854
+ self.assertEqual(prediction.shape, torch.Size((1, 199, 768)))
855
+
856
+ expected_prediction = torch.tensor(
857
+ [
858
+ [0.1887, -0.0474, 0.2604, 0.1453],
859
+ [0.0651, 0.1999, 0.1797, 0.1161],
860
+ [0.2833, -0.3036, 0.6910, 0.1123],
861
+ [0.2836, -0.4644, -0.0111, 0.1530],
862
+ [0.3919, -0.2823, 0.4192, 0.1687],
863
+ [0.2168, -0.1956, 0.4050, 0.0925],
864
+ [0.2597, -0.0884, 0.1258, 0.1119],
865
+ [0.1127, -0.1203, 0.1924, 0.2859],
866
+ [0.1362, -0.1315, 0.2693, 0.1027],
867
+ [-0.3169, -0.2266, 0.4419, 0.6740],
868
+ [0.2366, -0.1452, 0.2589, 0.0579],
869
+ [0.0358, -0.2021, 0.3112, -0.1392],
870
+ ],
871
+ device=torch_device,
872
+ )
873
+
874
+ self.assertTrue(torch.allclose(prediction[0, 52:64, 320:324], expected_prediction, atol=1e-4))
875
+
876
+ def test_inference_question_answering(self):
877
+ tokenizer = BigBirdTokenizer.from_pretrained("google/bigbird-base-trivia-itc")
878
+ model = BigBirdForQuestionAnswering.from_pretrained(
879
+ "google/bigbird-base-trivia-itc", attention_type="block_sparse", block_size=16, num_random_blocks=3
880
+ )
881
+ model.to(torch_device)
882
+
883
+ context = (
884
+ "The BigBird model was proposed in Big Bird: Transformers for Longer Sequences by Zaheer, Manzil and"
885
+ " Guruganesh, Guru and Dubey, Kumar Avinava and Ainslie, Joshua and Alberti, Chris and Ontanon, Santiago"
886
+ " and Pham, Philip and Ravula, Anirudh and Wang, Qifan and Yang, Li and others. BigBird, is a"
887
+ " sparse-attention based transformer which extends Transformer based models, such as BERT to much longer"
888
+ " sequences. In addition to sparse attention, BigBird also applies global attention as well as random"
889
+ " attention to the input sequence. Theoretically, it has been shown that applying sparse, global, and"
890
+ " random attention approximates full attention, while being computationally much more efficient for longer"
891
+ " sequences. As a consequence of the capability to handle longer context, BigBird has shown improved"
892
+ " performance on various long document NLP tasks, such as question answering and summarization, compared"
893
+ " to BERT or RoBERTa."
894
+ )
895
+
896
+ question = [
897
+ "Which is better for longer sequences- BigBird or BERT?",
898
+ "What is the benefit of using BigBird over BERT?",
899
+ ]
900
+ inputs = tokenizer(
901
+ question,
902
+ [context, context],
903
+ padding=True,
904
+ return_tensors="pt",
905
+ add_special_tokens=True,
906
+ max_length=256,
907
+ truncation=True,
908
+ )
909
+
910
+ inputs = {k: v.to(torch_device) for k, v in inputs.items()}
911
+
912
+ start_logits, end_logits = model(**inputs).to_tuple()
913
+
914
+ # fmt: off
915
+ target_start_logits = torch.tensor(
916
+ [[-8.5622, -9.6209, -14.3351, -8.7032, -11.8596, -7.7446, -9.6730, -13.6063, -8.9651, -11.7417, -8.2641, -8.7056, -13.4116, -5.6600, -8.8316, -10.4148, -12.2180, -7.7979, -12.5274, -6.0685, -10.3373, -11.3128, -6.6456, -14.4030, -6.8292, -14.5383, -11.5638, -6.3326, 11.5293, -1.8434, -10.0013, -7.6150], [-10.7384, -13.1179, -10.1837, -13.7700, -10.0186, -11.7335, -13.3411, -10.0188, -13.4235, -9.9381, -10.4252, -13.1281, -8.2022, -10.4326, -11.5542, -14.1549, -10.7546, -13.4691, -8.2744, -11.4324, -13.3773, -9.8284, -14.5825, -8.7471, -14.7050, -8.0364, -11.3627, -6.4638, -11.7031, -14.3446, -9.9425, -8.0088]], # noqa: E231
917
+ device=torch_device,
918
+ )
919
+
920
+ target_end_logits = torch.tensor(
921
+ [[-12.1736, -8.8487, -14.8877, -11.6713, -15.1165, -12.2396, -7.6828, -15.4153, -12.2528, -14.3671, -12.3596, -7.4272, -14.9615, -13.6356, -11.7939, -9.9767, -14.8112, -8.9567, -15.8798, -11.5291, -9.4249, -14.7544, -7.9387, -16.2789, -8.9702, -15.3111, -11.5585, -7.9992, -4.1127, 10.3209, -8.3926, -10.2005], [-11.1375, -15.4027, -12.6861, -16.9884, -13.7093, -10.3560, -15.7228, -12.9290, -15.8519, -13.7953, -10.2460, -15.7198, -14.2078, -12.8477, -11.4861, -16.1017, -11.8900, -16.4488, -13.2959, -10.3980, -15.4874, -10.3539, -16.8263, -10.9973, -17.0344, -9.2751, -10.1196, -13.8907, -12.1025, -13.0628, -12.8530, -13.8173]], # noqa: E321
922
+ device=torch_device,
923
+ )
924
+ # fmt: on
925
+
926
+ self.assertTrue(torch.allclose(start_logits[:, 64:96], target_start_logits, atol=1e-4))
927
+ self.assertTrue(torch.allclose(end_logits[:, 64:96], target_end_logits, atol=1e-4))
928
+
929
+ input_ids = inputs["input_ids"].tolist()
930
+ answer = [
931
+ input_ids[i][torch.argmax(start_logits, dim=-1)[i] : torch.argmax(end_logits, dim=-1)[i] + 1]
932
+ for i in range(len(input_ids))
933
+ ]
934
+ answer = tokenizer.batch_decode(answer)
935
+
936
+ self.assertTrue(answer == ["BigBird", "global attention"])
937
+
938
+ def test_fill_mask(self):
939
+ tokenizer = BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base")
940
+ model = BigBirdForMaskedLM.from_pretrained("google/bigbird-roberta-base")
941
+ model.to(torch_device)
942
+
943
+ input_ids = tokenizer("The goal of life is [MASK] .", return_tensors="pt").input_ids.to(torch_device)
944
+ logits = model(input_ids).logits
945
+
946
+ # [MASK] is token at 6th position
947
+ pred_token = tokenizer.decode(torch.argmax(logits[0, 6:7], axis=-1))
948
+ self.assertEqual(pred_token, "happiness")
949
+
950
+ def test_auto_padding(self):
951
+ model = BigBirdModel.from_pretrained(
952
+ "google/bigbird-roberta-base", attention_type="block_sparse", num_random_blocks=3, block_size=16
953
+ )
954
+ model.to(torch_device)
955
+ model.eval()
956
+
957
+ input_ids = torch.tensor([200 * [10] + 40 * [2] + [1]], device=torch_device, dtype=torch.long)
958
+ with torch.no_grad():
959
+ output = model(input_ids).to_tuple()[0]
960
+
961
+ # fmt: off
962
+ target = torch.tensor(
963
+ [[-0.129420, -0.164740, 0.042422, -0.336030, 0.094379, 0.033794, 0.384590, 0.229660, -0.196500, 0.108020], [-0.000154, -0.168800, 0.165820, -0.313670, 0.101240, 0.035145, 0.381880, 0.213730, -0.201080, 0.077443], [0.053754, -0.166350, 0.225520, -0.272900, 0.119670, 0.019987, 0.348670, 0.199190, -0.181600, 0.084640], [0.063636, -0.187110, 0.237010, -0.297380, 0.126300, 0.020025, 0.268490, 0.191820, -0.192300, 0.035077], [0.073893, -0.184790, 0.188870, -0.297860, 0.134280, 0.028972, 0.174650, 0.186890, -0.180530, 0.006851], [0.005253, -0.169360, 0.123100, -0.302550, 0.126930, 0.024188, 0.133410, 0.200600, -0.168210, -0.001006], [-0.093336, -0.175370, -0.004768, -0.333170, 0.114330, 0.034168, 0.120960, 0.203570, -0.162810, -0.005757], [-0.160210, -0.169310, -0.049064, -0.331950, 0.115730, 0.027062, 0.143600, 0.205310, -0.144580, 0.026746], [-0.193200, -0.156820, -0.079422, -0.351600, 0.106450, 0.032174, 0.245690, 0.210250, -0.173480, 0.043914], [-0.167980, -0.153050, -0.059764, -0.357890,0.103910, 0.031481, 0.334190, 0.208960,-0.178180, 0.072165], [-0.136990, -0.156950, -0.012099, -0.353140,0.096996, 0.025864, 0.376340, 0.216050, -0.171820, 0.089963], [-0.041143, -0.167060, 0.079754, -0.353220, 0.093247, 0.019867, 0.385810, 0.214340, -0.191800, 0.065946],[0.040373, -0.158610, 0.152570, -0.312930, 0.110590, 0.012282, 0.345270, 0.204040, -0.176500, 0.064972], [0.043762, -0.166450, 0.179500, -0.317930, 0.117280, -0.004040, 0.304490, 0.201380, -0.182780, 0.044000]], # noqa: E231
964
+ device=torch_device,
965
+ )
966
+ # fmt: on
967
+
968
+ self.assertEqual(output.shape, torch.Size((1, 241, 768)))
969
+ self.assertTrue(torch.allclose(output[0, 64:78, 300:310], target, atol=0.0001))
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/big_bird/test_modeling_flax_big_bird.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import unittest
16
+
17
+ from transformers import BigBirdConfig, is_flax_available
18
+ from transformers.testing_utils import require_flax, slow
19
+
20
+ from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask
21
+
22
+
23
+ if is_flax_available():
24
+ import jax
25
+
26
+ from transformers.models.big_bird.modeling_flax_big_bird import (
27
+ FlaxBigBirdForCausalLM,
28
+ FlaxBigBirdForMaskedLM,
29
+ FlaxBigBirdForMultipleChoice,
30
+ FlaxBigBirdForPreTraining,
31
+ FlaxBigBirdForQuestionAnswering,
32
+ FlaxBigBirdForSequenceClassification,
33
+ FlaxBigBirdForTokenClassification,
34
+ FlaxBigBirdModel,
35
+ )
36
+
37
+
38
+ class FlaxBigBirdModelTester(unittest.TestCase):
39
+ def __init__(
40
+ self,
41
+ parent,
42
+ batch_size=2,
43
+ seq_length=56,
44
+ is_training=True,
45
+ use_attention_mask=True,
46
+ use_token_type_ids=True,
47
+ use_labels=True,
48
+ vocab_size=99,
49
+ hidden_size=32,
50
+ num_hidden_layers=2,
51
+ num_attention_heads=2,
52
+ intermediate_size=7,
53
+ hidden_act="gelu_new",
54
+ hidden_dropout_prob=0.1,
55
+ attention_probs_dropout_prob=0.1,
56
+ max_position_embeddings=512,
57
+ type_vocab_size=16,
58
+ type_sequence_label_size=2,
59
+ initializer_range=0.02,
60
+ num_choices=4,
61
+ attention_type="block_sparse",
62
+ use_bias=True,
63
+ rescale_embeddings=False,
64
+ block_size=2,
65
+ num_random_blocks=3,
66
+ ):
67
+ self.parent = parent
68
+ self.batch_size = batch_size
69
+ self.seq_length = seq_length
70
+ self.is_training = is_training
71
+ self.use_attention_mask = use_attention_mask
72
+ self.use_token_type_ids = use_token_type_ids
73
+ self.use_labels = use_labels
74
+ self.vocab_size = vocab_size
75
+ self.hidden_size = hidden_size
76
+ self.num_hidden_layers = num_hidden_layers
77
+ self.num_attention_heads = num_attention_heads
78
+ self.intermediate_size = intermediate_size
79
+ self.hidden_act = hidden_act
80
+ self.hidden_dropout_prob = hidden_dropout_prob
81
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
82
+ self.max_position_embeddings = max_position_embeddings
83
+ self.type_vocab_size = type_vocab_size
84
+ self.type_sequence_label_size = type_sequence_label_size
85
+ self.initializer_range = initializer_range
86
+ self.num_choices = num_choices
87
+
88
+ self.rescale_embeddings = rescale_embeddings
89
+ self.attention_type = attention_type
90
+ self.use_bias = use_bias
91
+ self.block_size = block_size
92
+ self.num_random_blocks = num_random_blocks
93
+ super().__init__()
94
+
95
+ def prepare_config_and_inputs(self):
96
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
97
+
98
+ attention_mask = None
99
+ if self.use_attention_mask:
100
+ attention_mask = random_attention_mask([self.batch_size, self.seq_length])
101
+
102
+ token_type_ids = None
103
+ if self.use_token_type_ids:
104
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
105
+
106
+ config = BigBirdConfig(
107
+ vocab_size=self.vocab_size,
108
+ hidden_size=self.hidden_size,
109
+ num_hidden_layers=self.num_hidden_layers,
110
+ num_attention_heads=self.num_attention_heads,
111
+ intermediate_size=self.intermediate_size,
112
+ hidden_act=self.hidden_act,
113
+ hidden_dropout_prob=self.hidden_dropout_prob,
114
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
115
+ max_position_embeddings=self.max_position_embeddings,
116
+ type_vocab_size=self.type_vocab_size,
117
+ is_decoder=False,
118
+ initializer_range=self.initializer_range,
119
+ attention_type=self.attention_type,
120
+ block_size=self.block_size,
121
+ num_random_blocks=self.num_random_blocks,
122
+ use_bias=self.use_bias,
123
+ rescale_embeddings=self.rescale_embeddings,
124
+ )
125
+
126
+ return config, input_ids, token_type_ids, attention_mask
127
+
128
+ def prepare_config_and_inputs_for_common(self):
129
+ config_and_inputs = self.prepare_config_and_inputs()
130
+ config, input_ids, token_type_ids, attention_mask = config_and_inputs
131
+ inputs_dict = {
132
+ "input_ids": input_ids,
133
+ "token_type_ids": token_type_ids,
134
+ "attention_mask": attention_mask,
135
+ }
136
+ return config, inputs_dict
137
+
138
+
139
+ @require_flax
140
+ class FlaxBigBirdModelTest(FlaxModelTesterMixin, unittest.TestCase):
141
+ all_model_classes = (
142
+ (
143
+ FlaxBigBirdForCausalLM,
144
+ FlaxBigBirdModel,
145
+ FlaxBigBirdForPreTraining,
146
+ FlaxBigBirdForMaskedLM,
147
+ FlaxBigBirdForMultipleChoice,
148
+ FlaxBigBirdForQuestionAnswering,
149
+ FlaxBigBirdForSequenceClassification,
150
+ FlaxBigBirdForTokenClassification,
151
+ )
152
+ if is_flax_available()
153
+ else ()
154
+ )
155
+
156
+ test_attn_probs = False
157
+ test_mismatched_shapes = False
158
+
159
+ def setUp(self):
160
+ self.model_tester = FlaxBigBirdModelTester(self)
161
+
162
+ @slow
163
+ # copied from `test_modeling_flax_common` because it takes much longer than other models
164
+ def test_from_pretrained_save_pretrained(self):
165
+ super().test_from_pretrained_save_pretrained()
166
+
167
+ @slow
168
+ # copied from `test_modeling_flax_common` because it takes much longer than other models
169
+ def test_from_pretrained_with_no_automatic_init(self):
170
+ super().test_from_pretrained_with_no_automatic_init()
171
+
172
+ @slow
173
+ # copied from `test_modeling_flax_common` because it takes much longer than other models
174
+ def test_no_automatic_init(self):
175
+ super().test_no_automatic_init()
176
+
177
+ @slow
178
+ # copied from `test_modeling_flax_common` because it takes much longer than other models
179
+ def test_hidden_states_output(self):
180
+ super().test_hidden_states_output()
181
+
182
+ @slow
183
+ def test_model_from_pretrained(self):
184
+ for model_class_name in self.all_model_classes:
185
+ model = model_class_name.from_pretrained("google/bigbird-roberta-base")
186
+ self.assertIsNotNone(model)
187
+
188
+ def test_attention_outputs(self):
189
+ if self.test_attn_probs:
190
+ super().test_attention_outputs()
191
+
192
+ @slow
193
+ # copied from `test_modeling_flax_common` because it takes much longer than other models
194
+ def test_jit_compilation(self):
195
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
196
+
197
+ for model_class in self.all_model_classes:
198
+ with self.subTest(model_class.__name__):
199
+ prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class)
200
+ model = model_class(config)
201
+
202
+ @jax.jit
203
+ def model_jitted(input_ids, attention_mask=None, **kwargs):
204
+ return model(input_ids=input_ids, attention_mask=attention_mask, **kwargs)
205
+
206
+ with self.subTest("JIT Enabled"):
207
+ jitted_outputs = model_jitted(**prepared_inputs_dict).to_tuple()
208
+
209
+ with self.subTest("JIT Disabled"):
210
+ with jax.disable_jit():
211
+ outputs = model_jitted(**prepared_inputs_dict).to_tuple()
212
+
213
+ self.assertEqual(len(outputs), len(jitted_outputs))
214
+ for jitted_output, output in zip(jitted_outputs, outputs):
215
+ self.assertEqual(jitted_output.shape, output.shape)
216
+
217
+ # overwrite from common in order to skip the check on `attentions`
218
+ def check_pt_flax_outputs(self, fx_outputs, pt_outputs, model_class, tol=1e-5, name="outputs", attributes=None):
219
+ # `bigbird_block_sparse_attention` in `FlaxBigBird` returns `attention_probs = None`, while in PyTorch version,
220
+ # an effort was done to return `attention_probs` (yet to be verified).
221
+ if name.startswith("outputs.attentions"):
222
+ return
223
+ else:
224
+ super().check_pt_flax_outputs(fx_outputs, pt_outputs, model_class, tol, name, attributes)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/big_bird/test_tokenization_big_bird.py ADDED
@@ -0,0 +1,233 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 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
+
16
+ import unittest
17
+
18
+ from transformers import BigBirdTokenizer, BigBirdTokenizerFast
19
+ from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow
20
+ from transformers.utils import cached_property
21
+
22
+ from ...test_tokenization_common import TokenizerTesterMixin
23
+
24
+
25
+ SPIECE_UNDERLINE = "▁"
26
+
27
+ SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model")
28
+
29
+
30
+ @require_sentencepiece
31
+ @require_tokenizers
32
+ class BigBirdTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
33
+ from_pretrained_id = "google/bigbird-roberta-base"
34
+ tokenizer_class = BigBirdTokenizer
35
+ rust_tokenizer_class = BigBirdTokenizerFast
36
+ test_rust_tokenizer = True
37
+ test_sentencepiece = True
38
+
39
+ def setUp(self):
40
+ super().setUp()
41
+
42
+ tokenizer = self.tokenizer_class(SAMPLE_VOCAB, keep_accents=True)
43
+ tokenizer.save_pretrained(self.tmpdirname)
44
+
45
+ def test_convert_token_and_id(self):
46
+ """Test ``_convert_token_to_id`` and ``_convert_id_to_token``."""
47
+ token = "<s>"
48
+ token_id = 1
49
+
50
+ self.assertEqual(self.get_tokenizer()._convert_token_to_id(token), token_id)
51
+ self.assertEqual(self.get_tokenizer()._convert_id_to_token(token_id), token)
52
+
53
+ def test_get_vocab(self):
54
+ vocab_keys = list(self.get_tokenizer().get_vocab().keys())
55
+
56
+ self.assertEqual(vocab_keys[0], "<unk>")
57
+ self.assertEqual(vocab_keys[1], "<s>")
58
+ self.assertEqual(vocab_keys[-1], "[MASK]")
59
+ self.assertEqual(len(vocab_keys), 1_004)
60
+
61
+ def test_vocab_size(self):
62
+ self.assertEqual(self.get_tokenizer().vocab_size, 1_000)
63
+
64
+ def test_rust_and_python_full_tokenizers(self):
65
+ if not self.test_rust_tokenizer:
66
+ self.skipTest(reason="test_rust_tokenizer is set to False")
67
+
68
+ tokenizer = self.get_tokenizer()
69
+ rust_tokenizer = self.get_rust_tokenizer()
70
+
71
+ sequence = "I was born in 92000, and this is falsé."
72
+
73
+ tokens = tokenizer.tokenize(sequence)
74
+ rust_tokens = rust_tokenizer.tokenize(sequence)
75
+ self.assertListEqual(tokens, rust_tokens)
76
+
77
+ ids = tokenizer.encode(sequence, add_special_tokens=False)
78
+ rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False)
79
+ self.assertListEqual(ids, rust_ids)
80
+
81
+ rust_tokenizer = self.get_rust_tokenizer()
82
+ ids = tokenizer.encode(sequence)
83
+ rust_ids = rust_tokenizer.encode(sequence)
84
+ self.assertListEqual(ids, rust_ids)
85
+
86
+ def test_full_tokenizer(self):
87
+ tokenizer = BigBirdTokenizer(SAMPLE_VOCAB, keep_accents=True)
88
+
89
+ tokens = tokenizer.tokenize("This is a test")
90
+ self.assertListEqual(tokens, ["▁This", "▁is", "▁a", "▁t", "est"])
91
+
92
+ self.assertListEqual(
93
+ tokenizer.convert_tokens_to_ids(tokens),
94
+ [285, 46, 10, 170, 382],
95
+ )
96
+
97
+ tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.")
98
+ self.assertListEqual(
99
+ tokens,
100
+ [
101
+ SPIECE_UNDERLINE + "I",
102
+ SPIECE_UNDERLINE + "was",
103
+ SPIECE_UNDERLINE + "b",
104
+ "or",
105
+ "n",
106
+ SPIECE_UNDERLINE + "in",
107
+ SPIECE_UNDERLINE + "",
108
+ "9",
109
+ "2",
110
+ "0",
111
+ "0",
112
+ "0",
113
+ ",",
114
+ SPIECE_UNDERLINE + "and",
115
+ SPIECE_UNDERLINE + "this",
116
+ SPIECE_UNDERLINE + "is",
117
+ SPIECE_UNDERLINE + "f",
118
+ "al",
119
+ "s",
120
+ "é",
121
+ ".",
122
+ ],
123
+ )
124
+ ids = tokenizer.convert_tokens_to_ids(tokens)
125
+ self.assertListEqual(
126
+ ids,
127
+ [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4],
128
+ )
129
+
130
+ back_tokens = tokenizer.convert_ids_to_tokens(ids)
131
+ self.assertListEqual(
132
+ back_tokens,
133
+ [
134
+ SPIECE_UNDERLINE + "I",
135
+ SPIECE_UNDERLINE + "was",
136
+ SPIECE_UNDERLINE + "b",
137
+ "or",
138
+ "n",
139
+ SPIECE_UNDERLINE + "in",
140
+ SPIECE_UNDERLINE + "",
141
+ "<unk>",
142
+ "2",
143
+ "0",
144
+ "0",
145
+ "0",
146
+ ",",
147
+ SPIECE_UNDERLINE + "and",
148
+ SPIECE_UNDERLINE + "this",
149
+ SPIECE_UNDERLINE + "is",
150
+ SPIECE_UNDERLINE + "f",
151
+ "al",
152
+ "s",
153
+ "<unk>",
154
+ ".",
155
+ ],
156
+ )
157
+
158
+ @cached_property
159
+ def big_tokenizer(self):
160
+ return BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base")
161
+
162
+ @slow
163
+ def test_tokenization_base_easy_symbols(self):
164
+ symbols = "Hello World!"
165
+ original_tokenizer_encodings = [65, 18536, 2260, 101, 66]
166
+
167
+ self.assertListEqual(original_tokenizer_encodings, self.big_tokenizer.encode(symbols))
168
+
169
+ @slow
170
+ def test_tokenization_base_hard_symbols(self):
171
+ symbols = (
172
+ 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will'
173
+ " add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth"
174
+ )
175
+ original_tokenizer_encodings = [65, 871, 419, 358, 946, 991, 2521, 452, 358, 1357, 387, 7751, 3536, 112, 985, 456, 126, 865, 938, 5400, 5734, 458, 1368, 467, 786, 2462, 5246, 1159, 633, 865, 4519, 457, 582, 852, 2557, 427, 916, 508, 405, 34324, 497, 391, 408, 11342, 1244, 385, 100, 938, 985, 456, 574, 362, 12597, 3200, 3129, 1172, 66] # fmt: skip
176
+ self.assertListEqual(original_tokenizer_encodings, self.big_tokenizer.encode(symbols))
177
+
178
+ @require_torch
179
+ @slow
180
+ def test_torch_encode_plus_sent_to_model(self):
181
+ import torch
182
+
183
+ from transformers import BigBirdConfig, BigBirdModel
184
+
185
+ # Build sequence
186
+ first_ten_tokens = list(self.big_tokenizer.get_vocab().keys())[:10]
187
+ sequence = " ".join(first_ten_tokens)
188
+ encoded_sequence = self.big_tokenizer.encode_plus(sequence, return_tensors="pt", return_token_type_ids=False)
189
+ batch_encoded_sequence = self.big_tokenizer.batch_encode_plus(
190
+ [sequence + " " + sequence], return_tensors="pt", return_token_type_ids=False
191
+ )
192
+
193
+ config = BigBirdConfig(attention_type="original_full")
194
+ model = BigBirdModel(config)
195
+
196
+ assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size
197
+
198
+ with torch.no_grad():
199
+ model(**encoded_sequence)
200
+ model(**batch_encoded_sequence)
201
+
202
+ @slow
203
+ def test_special_tokens(self):
204
+ """
205
+ To reproduce:
206
+
207
+ $ wget https://github.com/google-research/bigbird/blob/master/bigbird/vocab/gpt2.model?raw=true
208
+ $ mv gpt2.model?raw=true gpt2.model
209
+
210
+ ```
211
+ import tensorflow_text as tft
212
+ import tensorflow as tf
213
+
214
+ vocab_model_file = "./gpt2.model"
215
+ tokenizer = tft.SentencepieceTokenizer(model=tf.io.gfile.GFile(vocab_model_file, "rb").read()))
216
+ ids = tokenizer.tokenize("Paris is the [MASK].")
217
+ ids = tf.concat([tf.constant([65]), ids, tf.constant([66])], axis=0)
218
+ detokenized = tokenizer.detokenize(ids) # should give [CLS] Paris is the [MASK].[SEP]
219
+ """
220
+ tokenizer = BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base")
221
+ decoded_text = tokenizer.decode(tokenizer("Paris is the [MASK].").input_ids)
222
+
223
+ self.assertTrue(decoded_text == "[CLS] Paris is the[MASK].[SEP]")
224
+
225
+ @slow
226
+ def test_tokenizer_integration(self):
227
+ expected_encoding = {'input_ids': [[65, 39286, 458, 36335, 2001, 456, 13073, 13266, 455, 113, 7746, 1741, 11157, 391, 13073, 13266, 455, 113, 3967, 35412, 113, 4936, 109, 3870, 2377, 113, 30084, 45720, 458, 134, 17496, 112, 503, 11672, 113, 118, 112, 5665, 13347, 38687, 112, 1496, 31389, 112, 3268, 47264, 134, 962, 112, 16377, 8035, 23130, 430, 12169, 15518, 28592, 458, 146, 41697, 109, 391, 12169, 15518, 16689, 458, 146, 41358, 109, 452, 726, 4034, 111, 763, 35412, 5082, 388, 1903, 111, 9051, 391, 2870, 48918, 1900, 1123, 550, 998, 112, 9586, 15985, 455, 391, 410, 22955, 37636, 114, 66], [65, 448, 17496, 419, 3663, 385, 763, 113, 27533, 2870, 3283, 13043, 1639, 24713, 523, 656, 24013, 18550, 2521, 517, 27014, 21244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 11786, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [65, 484, 2169, 7687, 21932, 18146, 726, 363, 17032, 3391, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # fmt: skip
228
+
229
+ self.tokenizer_integration_test_util(
230
+ expected_encoding=expected_encoding,
231
+ model_name="google/bigbird-roberta-base",
232
+ revision="215c99f1600e06f83acce68422f2035b2b5c3510",
233
+ )
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bigbird_pegasus/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bigbird_pegasus/test_modeling_bigbird_pegasus.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/biogpt/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/biogpt/test_modeling_biogpt.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Testing suite for the PyTorch BioGPT model."""
16
+
17
+ import math
18
+ import unittest
19
+
20
+ from transformers import BioGptConfig, is_sacremoses_available, is_torch_available
21
+ from transformers.testing_utils import require_torch, slow, torch_device
22
+
23
+ from ...generation.test_utils import GenerationTesterMixin
24
+ from ...test_configuration_common import ConfigTester
25
+ from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
26
+ from ...test_pipeline_mixin import PipelineTesterMixin
27
+
28
+
29
+ if is_torch_available():
30
+ import torch
31
+
32
+ from transformers import (
33
+ BioGptForCausalLM,
34
+ BioGptForSequenceClassification,
35
+ BioGptForTokenClassification,
36
+ BioGptModel,
37
+ BioGptTokenizer,
38
+ )
39
+
40
+
41
+ class BioGptModelTester:
42
+ def __init__(
43
+ self,
44
+ parent,
45
+ batch_size=13,
46
+ seq_length=7,
47
+ is_training=True,
48
+ use_input_mask=True,
49
+ use_token_type_ids=False,
50
+ use_labels=True,
51
+ vocab_size=99,
52
+ hidden_size=32,
53
+ num_hidden_layers=2,
54
+ num_attention_heads=4,
55
+ intermediate_size=37,
56
+ hidden_act="gelu",
57
+ hidden_dropout_prob=0.1,
58
+ attention_probs_dropout_prob=0.1,
59
+ max_position_embeddings=512,
60
+ type_vocab_size=16,
61
+ type_sequence_label_size=2,
62
+ initializer_range=0.02,
63
+ num_labels=3,
64
+ num_choices=4,
65
+ scope=None,
66
+ ):
67
+ self.parent = parent
68
+ self.batch_size = batch_size
69
+ self.seq_length = seq_length
70
+ self.is_training = is_training
71
+ self.use_input_mask = use_input_mask
72
+ self.use_token_type_ids = use_token_type_ids
73
+ self.use_labels = use_labels
74
+ self.vocab_size = vocab_size
75
+ self.hidden_size = hidden_size
76
+ self.num_hidden_layers = num_hidden_layers
77
+ self.num_attention_heads = num_attention_heads
78
+ self.intermediate_size = intermediate_size
79
+ self.hidden_act = hidden_act
80
+ self.hidden_dropout_prob = hidden_dropout_prob
81
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
82
+ self.max_position_embeddings = max_position_embeddings
83
+ self.type_vocab_size = type_vocab_size
84
+ self.type_sequence_label_size = type_sequence_label_size
85
+ self.initializer_range = initializer_range
86
+ self.num_labels = num_labels
87
+ self.num_choices = num_choices
88
+ self.scope = scope
89
+
90
+ def prepare_config_and_inputs(self):
91
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
92
+
93
+ input_mask = None
94
+ if self.use_input_mask:
95
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
96
+
97
+ token_type_ids = None
98
+ if self.use_token_type_ids:
99
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
100
+
101
+ sequence_labels = None
102
+ token_labels = None
103
+ choice_labels = None
104
+ if self.use_labels:
105
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
106
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
107
+ choice_labels = ids_tensor([self.batch_size], self.num_choices)
108
+
109
+ config = self.get_config()
110
+
111
+ return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
112
+
113
+ def get_config(self):
114
+ return BioGptConfig(
115
+ vocab_size=self.vocab_size,
116
+ hidden_size=self.hidden_size,
117
+ num_hidden_layers=self.num_hidden_layers,
118
+ num_attention_heads=self.num_attention_heads,
119
+ intermediate_size=self.intermediate_size,
120
+ hidden_act=self.hidden_act,
121
+ hidden_dropout_prob=self.hidden_dropout_prob,
122
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
123
+ max_position_embeddings=self.max_position_embeddings,
124
+ type_vocab_size=self.type_vocab_size,
125
+ is_decoder=False,
126
+ initializer_range=self.initializer_range,
127
+ )
128
+
129
+ def create_and_check_model(
130
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
131
+ ):
132
+ model = BioGptModel(config=config)
133
+ model.to(torch_device)
134
+ model.eval()
135
+ result = model(input_ids, attention_mask=input_mask)
136
+ result = model(input_ids)
137
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
138
+
139
+ def create_and_check_for_causal_lm(
140
+ self,
141
+ config,
142
+ input_ids,
143
+ token_type_ids,
144
+ input_mask,
145
+ sequence_labels,
146
+ token_labels,
147
+ choice_labels,
148
+ encoder_hidden_states,
149
+ encoder_attention_mask,
150
+ ):
151
+ model = BioGptForCausalLM(config=config)
152
+ model.to(torch_device)
153
+ model.eval()
154
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
155
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
156
+
157
+ def create_and_check_biogpt_model_attention_mask_past(
158
+ self, config, input_ids, input_mask, head_mask, token_type_ids, *args
159
+ ):
160
+ model = BioGptModel(config=config)
161
+ model.to(torch_device)
162
+ model.eval()
163
+
164
+ # create attention mask
165
+ attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
166
+ half_seq_length = self.seq_length // 2
167
+ attn_mask[:, half_seq_length:] = 0
168
+
169
+ # first forward pass
170
+ output, past = model(input_ids, attention_mask=attn_mask).to_tuple()
171
+
172
+ # create hypothetical next token and extent to next_input_ids
173
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
174
+
175
+ # change a random masked slice from input_ids
176
+ random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1
177
+ random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1)
178
+ input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens
179
+
180
+ # append to next input_ids and attn_mask
181
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
182
+ attn_mask = torch.cat(
183
+ [attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)],
184
+ dim=1,
185
+ )
186
+
187
+ # get two different outputs
188
+ output_from_no_past = model(next_input_ids, attention_mask=attn_mask)["last_hidden_state"]
189
+ output_from_past = model(next_tokens, past_key_values=past, attention_mask=attn_mask)["last_hidden_state"]
190
+
191
+ # select random slice
192
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
193
+ output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach()
194
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
195
+
196
+ # test that outputs are equal for slice
197
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
198
+
199
+ def create_and_check_biogpt_model_past_large_inputs(
200
+ self, config, input_ids, input_mask, head_mask, token_type_ids, *args
201
+ ):
202
+ model = BioGptModel(config=config).to(torch_device).eval()
203
+
204
+ attention_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
205
+
206
+ # first forward pass
207
+ outputs = model(input_ids, attention_mask=attention_mask, use_cache=True)
208
+
209
+ output, past_key_values = outputs.to_tuple()
210
+
211
+ # create hypothetical multiple next token and extent to next_input_ids
212
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
213
+ next_attn_mask = ids_tensor((self.batch_size, 3), 2)
214
+
215
+ # append to next input_ids and
216
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
217
+ next_attention_mask = torch.cat([attention_mask, next_attn_mask], dim=-1)
218
+
219
+ output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"]
220
+ output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[
221
+ "last_hidden_state"
222
+ ]
223
+
224
+ # select random slice
225
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
226
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
227
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
228
+
229
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
230
+
231
+ # test that outputs are equal for slice
232
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
233
+
234
+ def create_and_check_forward_and_backwards(
235
+ self, config, input_ids, input_mask, head_mask, token_type_ids, *args, gradient_checkpointing=False
236
+ ):
237
+ model = BioGptForCausalLM(config)
238
+ model.to(torch_device)
239
+ if gradient_checkpointing:
240
+ model.gradient_checkpointing_enable()
241
+
242
+ result = model(input_ids, labels=input_ids)
243
+ self.parent.assertEqual(result.loss.shape, ())
244
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
245
+ result.loss.backward()
246
+
247
+ def create_and_check_biogpt_weight_initialization(self, config, *args):
248
+ model = BioGptModel(config)
249
+ model_std = model.config.initializer_range / math.sqrt(2 * model.config.num_hidden_layers)
250
+ for key in model.state_dict().keys():
251
+ if "c_proj" in key and "weight" in key:
252
+ self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key]) - model_std), 0.001)
253
+ self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key]) - 0.0), 0.01)
254
+
255
+ def create_and_check_biogpt_for_token_classification(
256
+ self, config, input_ids, input_mask, head_mask, token_type_ids, *args
257
+ ):
258
+ config.num_labels = self.num_labels
259
+ model = BioGptForTokenClassification(config)
260
+ model.to(torch_device)
261
+ model.eval()
262
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
263
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
264
+
265
+ def prepare_config_and_inputs_for_common(self):
266
+ config_and_inputs = self.prepare_config_and_inputs()
267
+ (
268
+ config,
269
+ input_ids,
270
+ token_type_ids,
271
+ input_mask,
272
+ sequence_labels,
273
+ token_labels,
274
+ choice_labels,
275
+ ) = config_and_inputs
276
+ inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
277
+ return config, inputs_dict
278
+
279
+
280
+ @require_torch
281
+ class BioGptModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
282
+ all_model_classes = (
283
+ (BioGptModel, BioGptForCausalLM, BioGptForSequenceClassification, BioGptForTokenClassification)
284
+ if is_torch_available()
285
+ else ()
286
+ )
287
+ all_generative_model_classes = (BioGptForCausalLM,) if is_torch_available() else ()
288
+ pipeline_model_mapping = (
289
+ {
290
+ "feature-extraction": BioGptModel,
291
+ "text-classification": BioGptForSequenceClassification,
292
+ "text-generation": BioGptForCausalLM,
293
+ "token-classification": BioGptForTokenClassification,
294
+ "zero-shot": BioGptForSequenceClassification,
295
+ }
296
+ if is_torch_available() and is_sacremoses_available()
297
+ else {}
298
+ )
299
+ test_pruning = False
300
+
301
+ def setUp(self):
302
+ self.model_tester = BioGptModelTester(self)
303
+ self.config_tester = ConfigTester(self, config_class=BioGptConfig, hidden_size=37)
304
+
305
+ def test_config(self):
306
+ self.config_tester.run_common_tests()
307
+
308
+ def test_model(self):
309
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
310
+ self.model_tester.create_and_check_model(*config_and_inputs)
311
+
312
+ def test_model_various_embeddings(self):
313
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
314
+ for type in ["absolute", "relative_key", "relative_key_query"]:
315
+ config_and_inputs[0].position_embedding_type = type
316
+ self.model_tester.create_and_check_model(*config_and_inputs)
317
+
318
+ def test_biogpt_model_att_mask_past(self):
319
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
320
+ self.model_tester.create_and_check_biogpt_model_attention_mask_past(*config_and_inputs)
321
+
322
+ def test_biogpt_gradient_checkpointing(self):
323
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
324
+ self.model_tester.create_and_check_forward_and_backwards(*config_and_inputs, gradient_checkpointing=True)
325
+
326
+ def test_biogpt_model_past_with_large_inputs(self):
327
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
328
+ self.model_tester.create_and_check_biogpt_model_past_large_inputs(*config_and_inputs)
329
+
330
+ def test_biogpt_weight_initialization(self):
331
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
332
+ self.model_tester.create_and_check_biogpt_weight_initialization(*config_and_inputs)
333
+
334
+ def test_biogpt_token_classification_model(self):
335
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
336
+ self.model_tester.create_and_check_biogpt_for_token_classification(*config_and_inputs)
337
+
338
+ @slow
339
+ def test_batch_generation(self):
340
+ model = BioGptForCausalLM.from_pretrained("microsoft/biogpt")
341
+ model.to(torch_device)
342
+ tokenizer = BioGptTokenizer.from_pretrained("microsoft/biogpt")
343
+
344
+ tokenizer.padding_side = "left"
345
+
346
+ # Define PAD Token = EOS Token = 50256
347
+ tokenizer.pad_token = tokenizer.eos_token
348
+ model.config.pad_token_id = model.config.eos_token_id
349
+
350
+ # use different length sentences to test batching
351
+ sentences = [
352
+ "Hello, my dog is a little",
353
+ "Today, I",
354
+ ]
355
+
356
+ inputs = tokenizer(sentences, return_tensors="pt", padding=True)
357
+ input_ids = inputs["input_ids"].to(torch_device)
358
+
359
+ outputs = model.generate(
360
+ input_ids=input_ids,
361
+ attention_mask=inputs["attention_mask"].to(torch_device),
362
+ )
363
+
364
+ inputs_non_padded = tokenizer(sentences[0], return_tensors="pt").input_ids.to(torch_device)
365
+ output_non_padded = model.generate(input_ids=inputs_non_padded)
366
+
367
+ num_paddings = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item()
368
+ inputs_padded = tokenizer(sentences[1], return_tensors="pt").input_ids.to(torch_device)
369
+ output_padded = model.generate(input_ids=inputs_padded, max_length=model.config.max_length - num_paddings)
370
+
371
+ batch_out_sentence = tokenizer.batch_decode(outputs, skip_special_tokens=True)
372
+ non_padded_sentence = tokenizer.decode(output_non_padded[0], skip_special_tokens=True)
373
+ padded_sentence = tokenizer.decode(output_padded[0], skip_special_tokens=True)
374
+
375
+ expected_output_sentence = [
376
+ "Hello, my dog is a little bit bigger than a little bit.",
377
+ "Today, I have a good idea of how to use the information",
378
+ ]
379
+ self.assertListEqual(expected_output_sentence, batch_out_sentence)
380
+ self.assertListEqual(expected_output_sentence, [non_padded_sentence, padded_sentence])
381
+
382
+ @slow
383
+ def test_model_from_pretrained(self):
384
+ model_name = "microsoft/biogpt"
385
+ model = BioGptModel.from_pretrained(model_name)
386
+ self.assertIsNotNone(model)
387
+
388
+ # Copied from tests.models.opt.test_modeling_opt.OPTModelTest.test_opt_sequence_classification_model with OPT->BioGpt,opt->biogpt,prepare_config_and_inputs->prepare_config_and_inputs_for_common
389
+ def test_biogpt_sequence_classification_model(self):
390
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
391
+ config.num_labels = 3
392
+ input_ids = input_dict["input_ids"]
393
+ attention_mask = input_ids.ne(1).to(torch_device)
394
+ sequence_labels = ids_tensor([self.model_tester.batch_size], self.model_tester.type_sequence_label_size)
395
+ model = BioGptForSequenceClassification(config)
396
+ model.to(torch_device)
397
+ model.eval()
398
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
399
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
400
+
401
+ # Copied from tests.models.opt.test_modeling_opt.OPTModelTest.test_opt_sequence_classification_model_for_multi_label with OPT->BioGpt,opt->biogpt,prepare_config_and_inputs->prepare_config_and_inputs_for_common
402
+ def test_biogpt_sequence_classification_model_for_multi_label(self):
403
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
404
+ config.num_labels = 3
405
+ config.problem_type = "multi_label_classification"
406
+ input_ids = input_dict["input_ids"]
407
+ attention_mask = input_ids.ne(1).to(torch_device)
408
+ sequence_labels = ids_tensor(
409
+ [self.model_tester.batch_size, config.num_labels], self.model_tester.type_sequence_label_size
410
+ ).to(torch.float)
411
+ model = BioGptForSequenceClassification(config)
412
+ model.to(torch_device)
413
+ model.eval()
414
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
415
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
416
+
417
+
418
+ @require_torch
419
+ class BioGptModelIntegrationTest(unittest.TestCase):
420
+ @slow
421
+ def test_inference_lm_head_model(self):
422
+ model = BioGptForCausalLM.from_pretrained("microsoft/biogpt")
423
+ input_ids = torch.tensor([[2, 4805, 9, 656, 21]])
424
+ output = model(input_ids)[0]
425
+
426
+ vocab_size = 42384
427
+
428
+ expected_shape = torch.Size((1, 5, vocab_size))
429
+ self.assertEqual(output.shape, expected_shape)
430
+
431
+ expected_slice = torch.tensor(
432
+ [[[-9.5236, -9.8918, 10.4557], [-11.0469, -9.6423, 8.1022], [-8.8664, -7.8826, 5.5325]]]
433
+ )
434
+
435
+ self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4))
436
+
437
+ @slow
438
+ def test_biogpt_generation(self):
439
+ tokenizer = BioGptTokenizer.from_pretrained("microsoft/biogpt")
440
+ model = BioGptForCausalLM.from_pretrained("microsoft/biogpt")
441
+ model.to(torch_device)
442
+
443
+ torch.manual_seed(0)
444
+ tokenized = tokenizer("COVID-19 is", return_tensors="pt").to(torch_device)
445
+ output_ids = model.generate(
446
+ **tokenized,
447
+ min_length=100,
448
+ max_length=1024,
449
+ num_beams=5,
450
+ early_stopping=True,
451
+ )
452
+ output_str = tokenizer.decode(output_ids[0], skip_special_tokens=True)
453
+
454
+ EXPECTED_OUTPUT_STR = (
455
+ "COVID-19 is a global pandemic caused by severe acute respiratory syndrome coronavirus 2 (SARS-CoV-2), the"
456
+ " causative agent of coronavirus disease 2019 (COVID-19), which has spread to more than 200 countries and"
457
+ " territories, including the United States (US), Canada, Australia, New Zealand, the United Kingdom (UK),"
458
+ " and the United States of America (USA), as of March 11, 2020, with more than 800,000 confirmed cases and"
459
+ " more than 800,000 deaths."
460
+ )
461
+ self.assertEqual(output_str, EXPECTED_OUTPUT_STR)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/biogpt/test_tokenization_biogpt.py ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 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
+
16
+
17
+ import json
18
+ import os
19
+ import unittest
20
+
21
+ from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer
22
+ from transformers.testing_utils import require_sacremoses, slow
23
+
24
+ from ...test_tokenization_common import TokenizerTesterMixin
25
+
26
+
27
+ @require_sacremoses
28
+ class BioGptTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
29
+ from_pretrained_id = "microsoft/biogpt"
30
+ tokenizer_class = BioGptTokenizer
31
+ test_rust_tokenizer = False
32
+
33
+ def setUp(self):
34
+ super().setUp()
35
+
36
+ # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
37
+ vocab = [
38
+ "l",
39
+ "o",
40
+ "w",
41
+ "e",
42
+ "r",
43
+ "s",
44
+ "t",
45
+ "i",
46
+ "d",
47
+ "n",
48
+ "w</w>",
49
+ "r</w>",
50
+ "t</w>",
51
+ "lo",
52
+ "low",
53
+ "er</w>",
54
+ "low</w>",
55
+ "lowest</w>",
56
+ "newer</w>",
57
+ "wider</w>",
58
+ "<unk>",
59
+ ]
60
+ vocab_tokens = dict(zip(vocab, range(len(vocab))))
61
+ merges = ["l o 123", "lo w 1456", "e r</w> 1789", ""]
62
+
63
+ self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"])
64
+ self.merges_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["merges_file"])
65
+ with open(self.vocab_file, "w") as fp:
66
+ fp.write(json.dumps(vocab_tokens))
67
+ with open(self.merges_file, "w") as fp:
68
+ fp.write("\n".join(merges))
69
+
70
+ def get_input_output_texts(self, tokenizer):
71
+ input_text = "lower newer"
72
+ output_text = "lower newer"
73
+ return input_text, output_text
74
+
75
+ def test_full_tokenizer(self):
76
+ """Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt"""
77
+ tokenizer = BioGptTokenizer(self.vocab_file, self.merges_file)
78
+
79
+ text = "lower"
80
+ bpe_tokens = ["low", "er</w>"]
81
+ tokens = tokenizer.tokenize(text)
82
+ self.assertListEqual(tokens, bpe_tokens)
83
+
84
+ input_tokens = tokens + ["<unk>"]
85
+ input_bpe_tokens = [14, 15, 20]
86
+ self.assertListEqual(tokenizer.convert_tokens_to_ids(input_tokens), input_bpe_tokens)
87
+
88
+ @slow
89
+ def test_sequence_builders(self):
90
+ tokenizer = BioGptTokenizer.from_pretrained("microsoft/biogpt")
91
+
92
+ text = tokenizer.encode("sequence builders", add_special_tokens=False)
93
+ text_2 = tokenizer.encode("multi-sequence build", add_special_tokens=False)
94
+
95
+ encoded_sentence = tokenizer.build_inputs_with_special_tokens(text)
96
+ encoded_pair = tokenizer.build_inputs_with_special_tokens(text, text_2)
97
+
98
+ self.assertTrue(encoded_sentence == [2] + text)
99
+ self.assertTrue(encoded_pair == [2] + text + [2] + text_2)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bit/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bit/test_modeling_bit.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Testing suite for the PyTorch Bit model."""
16
+
17
+ import unittest
18
+
19
+ from transformers import BitConfig
20
+ from transformers.testing_utils import require_torch, require_vision, slow, torch_device
21
+ from transformers.utils import cached_property, is_torch_available, is_vision_available
22
+
23
+ from ...test_backbone_common import BackboneTesterMixin
24
+ from ...test_configuration_common import ConfigTester
25
+ from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
26
+ from ...test_pipeline_mixin import PipelineTesterMixin
27
+
28
+
29
+ if is_torch_available():
30
+ import torch
31
+ from torch import nn
32
+
33
+ from transformers import BitBackbone, BitForImageClassification, BitImageProcessor, BitModel
34
+
35
+
36
+ if is_vision_available():
37
+ from PIL import Image
38
+
39
+
40
+ class BitModelTester:
41
+ def __init__(
42
+ self,
43
+ parent,
44
+ batch_size=3,
45
+ image_size=32,
46
+ num_channels=3,
47
+ embeddings_size=10,
48
+ hidden_sizes=[8, 16, 32, 64],
49
+ depths=[1, 1, 2, 1],
50
+ is_training=True,
51
+ use_labels=True,
52
+ hidden_act="relu",
53
+ num_labels=3,
54
+ scope=None,
55
+ out_features=["stage2", "stage3", "stage4"],
56
+ out_indices=[2, 3, 4],
57
+ num_groups=1,
58
+ ):
59
+ self.parent = parent
60
+ self.batch_size = batch_size
61
+ self.image_size = image_size
62
+ self.num_channels = num_channels
63
+ self.embeddings_size = embeddings_size
64
+ self.hidden_sizes = hidden_sizes
65
+ self.depths = depths
66
+ self.is_training = is_training
67
+ self.use_labels = use_labels
68
+ self.hidden_act = hidden_act
69
+ self.num_labels = num_labels
70
+ self.scope = scope
71
+ self.num_stages = len(hidden_sizes)
72
+ self.out_features = out_features
73
+ self.out_indices = out_indices
74
+ self.num_groups = num_groups
75
+
76
+ def prepare_config_and_inputs(self):
77
+ pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
78
+
79
+ labels = None
80
+ if self.use_labels:
81
+ labels = ids_tensor([self.batch_size], self.num_labels)
82
+
83
+ config = self.get_config()
84
+
85
+ return config, pixel_values, labels
86
+
87
+ def get_config(self):
88
+ return BitConfig(
89
+ num_channels=self.num_channels,
90
+ embeddings_size=self.embeddings_size,
91
+ hidden_sizes=self.hidden_sizes,
92
+ depths=self.depths,
93
+ hidden_act=self.hidden_act,
94
+ num_labels=self.num_labels,
95
+ out_features=self.out_features,
96
+ out_indices=self.out_indices,
97
+ num_groups=self.num_groups,
98
+ )
99
+
100
+ def create_and_check_model(self, config, pixel_values, labels):
101
+ model = BitModel(config=config)
102
+ model.to(torch_device)
103
+ model.eval()
104
+ result = model(pixel_values)
105
+ self.parent.assertEqual(
106
+ result.last_hidden_state.shape,
107
+ (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32),
108
+ )
109
+
110
+ def create_and_check_for_image_classification(self, config, pixel_values, labels):
111
+ config.num_labels = self.num_labels
112
+ model = BitForImageClassification(config)
113
+ model.to(torch_device)
114
+ model.eval()
115
+ result = model(pixel_values, labels=labels)
116
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
117
+
118
+ def create_and_check_backbone(self, config, pixel_values, labels):
119
+ model = BitBackbone(config=config)
120
+ model.to(torch_device)
121
+ model.eval()
122
+ result = model(pixel_values)
123
+
124
+ # verify feature maps
125
+ self.parent.assertEqual(len(result.feature_maps), len(config.out_features))
126
+ self.parent.assertListEqual(list(result.feature_maps[0].shape), [self.batch_size, self.hidden_sizes[1], 4, 4])
127
+
128
+ # verify channels
129
+ self.parent.assertEqual(len(model.channels), len(config.out_features))
130
+ self.parent.assertListEqual(model.channels, config.hidden_sizes[1:])
131
+
132
+ # verify backbone works with out_features=None
133
+ config.out_features = None
134
+ model = BitBackbone(config=config)
135
+ model.to(torch_device)
136
+ model.eval()
137
+ result = model(pixel_values)
138
+
139
+ # verify feature maps
140
+ self.parent.assertEqual(len(result.feature_maps), 1)
141
+ self.parent.assertListEqual(list(result.feature_maps[0].shape), [self.batch_size, self.hidden_sizes[-1], 1, 1])
142
+
143
+ # verify channels
144
+ self.parent.assertEqual(len(model.channels), 1)
145
+ self.parent.assertListEqual(model.channels, [config.hidden_sizes[-1]])
146
+
147
+ def prepare_config_and_inputs_for_common(self):
148
+ config_and_inputs = self.prepare_config_and_inputs()
149
+ config, pixel_values, labels = config_and_inputs
150
+ inputs_dict = {"pixel_values": pixel_values}
151
+ return config, inputs_dict
152
+
153
+
154
+ @require_torch
155
+ class BitModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
156
+ """
157
+ Here we also overwrite some of the tests of test_modeling_common.py, as Bit does not use input_ids, inputs_embeds,
158
+ attention_mask and seq_length.
159
+ """
160
+
161
+ all_model_classes = (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else ()
162
+ pipeline_model_mapping = (
163
+ {"image-feature-extraction": BitModel, "image-classification": BitForImageClassification}
164
+ if is_torch_available()
165
+ else {}
166
+ )
167
+
168
+ fx_compatible = False
169
+ test_pruning = False
170
+ test_resize_embeddings = False
171
+ test_head_masking = False
172
+ has_attentions = False
173
+
174
+ def setUp(self):
175
+ self.model_tester = BitModelTester(self)
176
+ self.config_tester = ConfigTester(
177
+ self, config_class=BitConfig, has_text_modality=False, common_properties=["num_channels"]
178
+ )
179
+
180
+ def test_config(self):
181
+ self.config_tester.run_common_tests()
182
+
183
+ @unittest.skip(reason="Bit does not output attentions")
184
+ def test_attention_outputs(self):
185
+ pass
186
+
187
+ @unittest.skip(reason="Bit does not use inputs_embeds")
188
+ def test_inputs_embeds(self):
189
+ pass
190
+
191
+ @unittest.skip(reason="Bit does not support input and output embeddings")
192
+ def test_model_get_set_embeddings(self):
193
+ pass
194
+
195
+ def test_model(self):
196
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
197
+ self.model_tester.create_and_check_model(*config_and_inputs)
198
+
199
+ def test_backbone(self):
200
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
201
+ self.model_tester.create_and_check_backbone(*config_and_inputs)
202
+
203
+ def test_initialization(self):
204
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
205
+
206
+ for model_class in self.all_model_classes:
207
+ model = model_class(config=config)
208
+ for name, module in model.named_modules():
209
+ if isinstance(module, (nn.BatchNorm2d, nn.GroupNorm)):
210
+ self.assertTrue(
211
+ torch.all(module.weight == 1),
212
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
213
+ )
214
+ self.assertTrue(
215
+ torch.all(module.bias == 0),
216
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
217
+ )
218
+
219
+ def test_hidden_states_output(self):
220
+ def check_hidden_states_output(inputs_dict, config, model_class):
221
+ model = model_class(config)
222
+ model.to(torch_device)
223
+ model.eval()
224
+
225
+ with torch.no_grad():
226
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
227
+
228
+ hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
229
+
230
+ expected_num_stages = self.model_tester.num_stages
231
+ self.assertEqual(len(hidden_states), expected_num_stages + 1)
232
+
233
+ # Bit's feature maps are of shape (batch_size, num_channels, height, width)
234
+ self.assertListEqual(
235
+ list(hidden_states[0].shape[-2:]),
236
+ [self.model_tester.image_size // 4, self.model_tester.image_size // 4],
237
+ )
238
+
239
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
240
+ layers_type = ["preactivation", "bottleneck"]
241
+ for model_class in self.all_model_classes:
242
+ for layer_type in layers_type:
243
+ config.layer_type = layer_type
244
+ inputs_dict["output_hidden_states"] = True
245
+ check_hidden_states_output(inputs_dict, config, model_class)
246
+
247
+ # check that output_hidden_states also work using config
248
+ del inputs_dict["output_hidden_states"]
249
+ config.output_hidden_states = True
250
+
251
+ check_hidden_states_output(inputs_dict, config, model_class)
252
+
253
+ @unittest.skip(reason="Bit does not use feedforward chunking")
254
+ def test_feed_forward_chunking(self):
255
+ pass
256
+
257
+ def test_for_image_classification(self):
258
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
259
+ self.model_tester.create_and_check_for_image_classification(*config_and_inputs)
260
+
261
+ @slow
262
+ def test_model_from_pretrained(self):
263
+ model_name = "google/bit-50"
264
+ model = BitModel.from_pretrained(model_name)
265
+ self.assertIsNotNone(model)
266
+
267
+
268
+ # We will verify our results on an image of cute cats
269
+ def prepare_img():
270
+ image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
271
+ return image
272
+
273
+
274
+ @require_torch
275
+ @require_vision
276
+ class BitModelIntegrationTest(unittest.TestCase):
277
+ @cached_property
278
+ def default_image_processor(self):
279
+ return BitImageProcessor.from_pretrained("google/bit-50") if is_vision_available() else None
280
+
281
+ @slow
282
+ def test_inference_image_classification_head(self):
283
+ model = BitForImageClassification.from_pretrained("google/bit-50").to(torch_device)
284
+
285
+ image_processor = self.default_image_processor
286
+ image = prepare_img()
287
+ inputs = image_processor(images=image, return_tensors="pt").to(torch_device)
288
+
289
+ # forward pass
290
+ with torch.no_grad():
291
+ outputs = model(**inputs)
292
+
293
+ # verify the logits
294
+ expected_shape = torch.Size((1, 1000))
295
+ self.assertEqual(outputs.logits.shape, expected_shape)
296
+
297
+ expected_slice = torch.tensor([[-0.6526, -0.5263, -1.4398]]).to(torch_device)
298
+
299
+ self.assertTrue(torch.allclose(outputs.logits[0, :3], expected_slice, atol=1e-4))
300
+
301
+
302
+ @require_torch
303
+ class BitBackboneTest(BackboneTesterMixin, unittest.TestCase):
304
+ all_model_classes = (BitBackbone,) if is_torch_available() else ()
305
+ config_class = BitConfig
306
+
307
+ has_attentions = False
308
+
309
+ def setUp(self):
310
+ self.model_tester = BitModelTester(self)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blenderbot/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blenderbot/test_modeling_blenderbot.py ADDED
@@ -0,0 +1,559 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021, The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Testing suite for the PyTorch Blenderbot model."""
16
+
17
+ import tempfile
18
+ import unittest
19
+
20
+ from transformers import BlenderbotConfig, is_torch_available
21
+ from transformers.testing_utils import (
22
+ backend_empty_cache,
23
+ require_sentencepiece,
24
+ require_tokenizers,
25
+ require_torch,
26
+ require_torch_fp16,
27
+ slow,
28
+ torch_device,
29
+ )
30
+ from transformers.utils import cached_property
31
+
32
+ from ...generation.test_utils import GenerationTesterMixin
33
+ from ...test_configuration_common import ConfigTester
34
+ from ...test_modeling_common import ModelTesterMixin, ids_tensor
35
+ from ...test_pipeline_mixin import PipelineTesterMixin
36
+
37
+
38
+ if is_torch_available():
39
+ import torch
40
+
41
+ from transformers import BlenderbotForConditionalGeneration, BlenderbotModel, BlenderbotTokenizer
42
+ from transformers.models.blenderbot.modeling_blenderbot import (
43
+ BlenderbotDecoder,
44
+ BlenderbotEncoder,
45
+ BlenderbotForCausalLM,
46
+ )
47
+
48
+
49
+ def prepare_blenderbot_inputs_dict(
50
+ config,
51
+ input_ids,
52
+ decoder_input_ids,
53
+ attention_mask=None,
54
+ decoder_attention_mask=None,
55
+ head_mask=None,
56
+ decoder_head_mask=None,
57
+ cross_attn_head_mask=None,
58
+ ):
59
+ if attention_mask is None:
60
+ attention_mask = input_ids.ne(config.pad_token_id)
61
+ if decoder_attention_mask is None:
62
+ decoder_attention_mask = decoder_input_ids.ne(config.pad_token_id)
63
+ if head_mask is None:
64
+ head_mask = torch.ones(config.encoder_layers, config.encoder_attention_heads, device=torch_device)
65
+ if decoder_head_mask is None:
66
+ decoder_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads, device=torch_device)
67
+ if cross_attn_head_mask is None:
68
+ cross_attn_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads, device=torch_device)
69
+ return {
70
+ "input_ids": input_ids,
71
+ "decoder_input_ids": decoder_input_ids,
72
+ "attention_mask": attention_mask,
73
+ "decoder_attention_mask": attention_mask,
74
+ "head_mask": head_mask,
75
+ "decoder_head_mask": decoder_head_mask,
76
+ "cross_attn_head_mask": cross_attn_head_mask,
77
+ }
78
+
79
+
80
+ class BlenderbotModelTester:
81
+ def __init__(
82
+ self,
83
+ parent,
84
+ batch_size=13,
85
+ seq_length=7,
86
+ is_training=True,
87
+ use_labels=False,
88
+ vocab_size=99,
89
+ hidden_size=16,
90
+ num_hidden_layers=2,
91
+ num_attention_heads=4,
92
+ intermediate_size=4,
93
+ hidden_act="gelu",
94
+ hidden_dropout_prob=0.1,
95
+ attention_probs_dropout_prob=0.1,
96
+ max_position_embeddings=50,
97
+ eos_token_id=2,
98
+ pad_token_id=1,
99
+ bos_token_id=0,
100
+ ):
101
+ self.parent = parent
102
+ self.batch_size = batch_size
103
+ self.seq_length = seq_length
104
+ self.is_training = is_training
105
+ self.use_labels = use_labels
106
+ self.vocab_size = vocab_size
107
+ self.hidden_size = hidden_size
108
+ self.num_hidden_layers = num_hidden_layers
109
+ self.num_attention_heads = num_attention_heads
110
+ self.intermediate_size = intermediate_size
111
+ self.hidden_act = hidden_act
112
+ self.hidden_dropout_prob = hidden_dropout_prob
113
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
114
+ self.max_position_embeddings = max_position_embeddings
115
+ self.eos_token_id = eos_token_id
116
+ self.pad_token_id = pad_token_id
117
+ self.bos_token_id = bos_token_id
118
+
119
+ def prepare_config_and_inputs(self):
120
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size).clamp(
121
+ 3,
122
+ )
123
+ input_ids[:, -1] = self.eos_token_id # Eos Token
124
+
125
+ decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
126
+
127
+ config = self.get_config()
128
+ inputs_dict = prepare_blenderbot_inputs_dict(config, input_ids, decoder_input_ids)
129
+ return config, inputs_dict
130
+
131
+ def get_config(self):
132
+ return BlenderbotConfig(
133
+ vocab_size=self.vocab_size,
134
+ d_model=self.hidden_size,
135
+ encoder_layers=self.num_hidden_layers,
136
+ decoder_layers=self.num_hidden_layers,
137
+ encoder_attention_heads=self.num_attention_heads,
138
+ decoder_attention_heads=self.num_attention_heads,
139
+ encoder_ffn_dim=self.intermediate_size,
140
+ decoder_ffn_dim=self.intermediate_size,
141
+ dropout=self.hidden_dropout_prob,
142
+ attention_dropout=self.attention_probs_dropout_prob,
143
+ max_position_embeddings=self.max_position_embeddings,
144
+ eos_token_id=self.eos_token_id,
145
+ bos_token_id=self.bos_token_id,
146
+ pad_token_id=self.pad_token_id,
147
+ )
148
+
149
+ def get_pipeline_config(self):
150
+ config = self.get_config()
151
+ config.max_position_embeddings = 100
152
+ config.vocab_size = 300
153
+ return config
154
+
155
+ def prepare_config_and_inputs_for_common(self):
156
+ config, inputs_dict = self.prepare_config_and_inputs()
157
+ return config, inputs_dict
158
+
159
+ def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict):
160
+ model = BlenderbotModel(config=config).get_decoder().to(torch_device).eval()
161
+ input_ids = inputs_dict["input_ids"]
162
+ attention_mask = inputs_dict["attention_mask"]
163
+ head_mask = inputs_dict["head_mask"]
164
+
165
+ # first forward pass
166
+ outputs = model(input_ids, attention_mask=attention_mask, head_mask=head_mask, use_cache=True)
167
+
168
+ output, past_key_values = outputs.to_tuple()
169
+
170
+ # create hypothetical multiple next token and extent to next_input_ids
171
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
172
+ next_attn_mask = ids_tensor((self.batch_size, 3), 2)
173
+
174
+ # append to next input_ids and
175
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
176
+ next_attention_mask = torch.cat([attention_mask, next_attn_mask], dim=-1)
177
+
178
+ output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"]
179
+ output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[
180
+ "last_hidden_state"
181
+ ]
182
+
183
+ # select random slice
184
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
185
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
186
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
187
+
188
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
189
+
190
+ # test that outputs are equal for slice
191
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
192
+
193
+ def check_encoder_decoder_model_standalone(self, config, inputs_dict):
194
+ model = BlenderbotModel(config=config).to(torch_device).eval()
195
+ outputs = model(**inputs_dict)
196
+
197
+ encoder_last_hidden_state = outputs.encoder_last_hidden_state
198
+ last_hidden_state = outputs.last_hidden_state
199
+
200
+ with tempfile.TemporaryDirectory() as tmpdirname:
201
+ encoder = model.get_encoder()
202
+ encoder.save_pretrained(tmpdirname)
203
+ encoder = BlenderbotEncoder.from_pretrained(tmpdirname).to(torch_device)
204
+
205
+ encoder_last_hidden_state_2 = encoder(inputs_dict["input_ids"], attention_mask=inputs_dict["attention_mask"])[
206
+ 0
207
+ ]
208
+
209
+ self.parent.assertTrue((encoder_last_hidden_state_2 - encoder_last_hidden_state).abs().max().item() < 1e-3)
210
+
211
+ with tempfile.TemporaryDirectory() as tmpdirname:
212
+ decoder = model.get_decoder()
213
+ decoder.save_pretrained(tmpdirname)
214
+ decoder = BlenderbotDecoder.from_pretrained(tmpdirname).to(torch_device)
215
+
216
+ last_hidden_state_2 = decoder(
217
+ input_ids=inputs_dict["decoder_input_ids"],
218
+ attention_mask=inputs_dict["decoder_attention_mask"],
219
+ encoder_hidden_states=encoder_last_hidden_state,
220
+ encoder_attention_mask=inputs_dict["attention_mask"],
221
+ )[0]
222
+
223
+ self.parent.assertTrue((last_hidden_state_2 - last_hidden_state).abs().max().item() < 1e-3)
224
+
225
+
226
+ @require_torch
227
+ class BlenderbotModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
228
+ all_model_classes = (BlenderbotModel, BlenderbotForConditionalGeneration) if is_torch_available() else ()
229
+ all_generative_model_classes = (BlenderbotForConditionalGeneration,) if is_torch_available() else ()
230
+ pipeline_model_mapping = (
231
+ {
232
+ "feature-extraction": BlenderbotModel,
233
+ "summarization": BlenderbotForConditionalGeneration,
234
+ "text-generation": BlenderbotForCausalLM,
235
+ "text2text-generation": BlenderbotForConditionalGeneration,
236
+ "translation": BlenderbotForConditionalGeneration,
237
+ }
238
+ if is_torch_available()
239
+ else {}
240
+ )
241
+ is_encoder_decoder = True
242
+ fx_compatible = True
243
+ test_pruning = False
244
+ test_missing_keys = False
245
+
246
+ def setUp(self):
247
+ self.model_tester = BlenderbotModelTester(self)
248
+ self.config_tester = ConfigTester(self, config_class=BlenderbotConfig)
249
+
250
+ def test_config(self):
251
+ self.config_tester.run_common_tests()
252
+
253
+ def test_save_load_strict(self):
254
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
255
+ for model_class in self.all_model_classes:
256
+ model = model_class(config)
257
+
258
+ with tempfile.TemporaryDirectory() as tmpdirname:
259
+ model.save_pretrained(tmpdirname)
260
+ model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True)
261
+ self.assertEqual(info["missing_keys"], [])
262
+
263
+ def test_decoder_model_past_with_large_inputs(self):
264
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
265
+ self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
266
+
267
+ def test_encoder_decoder_model_standalone(self):
268
+ config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common()
269
+ self.model_tester.check_encoder_decoder_model_standalone(*config_and_inputs)
270
+
271
+ @require_torch_fp16
272
+ def test_generate_fp16(self):
273
+ config, input_dict = self.model_tester.prepare_config_and_inputs()
274
+ input_ids = input_dict["input_ids"]
275
+ attention_mask = input_ids.ne(1).to(torch_device)
276
+ model = BlenderbotForConditionalGeneration(config).eval().to(torch_device)
277
+ model.half()
278
+ model.generate(input_ids, attention_mask=attention_mask)
279
+ model.generate(num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3)
280
+
281
+
282
+ def assert_tensors_close(a, b, atol=1e-12, prefix=""):
283
+ """If tensors have different shapes, different values or a and b are not both tensors, raise a nice Assertion error."""
284
+ if a is None and b is None:
285
+ return True
286
+ try:
287
+ if torch.allclose(a, b, atol=atol):
288
+ return True
289
+ raise
290
+ except Exception:
291
+ pct_different = (torch.gt((a - b).abs(), atol)).float().mean().item()
292
+ if a.numel() > 100:
293
+ msg = f"tensor values are {pct_different:.1%} percent different."
294
+ else:
295
+ msg = f"{a} != {b}"
296
+ if prefix:
297
+ msg = prefix + ": " + msg
298
+ raise AssertionError(msg)
299
+
300
+
301
+ @unittest.skipUnless(torch_device != "cpu", "3B test too slow on CPU.")
302
+ @require_torch
303
+ @require_sentencepiece
304
+ @require_tokenizers
305
+ class Blenderbot3BIntegrationTests(unittest.TestCase):
306
+ ckpt = "facebook/blenderbot-3B"
307
+
308
+ @cached_property
309
+ def tokenizer(self):
310
+ return BlenderbotTokenizer.from_pretrained(self.ckpt)
311
+
312
+ @slow
313
+ def test_generation_from_short_input_same_as_parlai_3B(self):
314
+ FASTER_GEN_KWARGS = {"num_beams": 1, "early_stopping": True, "min_length": 15, "max_length": 25}
315
+ TOK_DECODE_KW = {"skip_special_tokens": True, "clean_up_tokenization_spaces": True}
316
+
317
+ backend_empty_cache(torch_device)
318
+ model = BlenderbotForConditionalGeneration.from_pretrained(self.ckpt).half().to(torch_device)
319
+
320
+ src_text = ["Sam"]
321
+ model_inputs = self.tokenizer(src_text, return_tensors="pt").to(torch_device)
322
+
323
+ generated_utterances = model.generate(**model_inputs, **FASTER_GEN_KWARGS)
324
+ tgt_text = 'Sam is a great name. It means "sun" in Gaelic.'
325
+
326
+ generated_txt = self.tokenizer.batch_decode(generated_utterances, **TOK_DECODE_KW)
327
+ assert generated_txt[0].strip() == tgt_text
328
+
329
+ src_text = (
330
+ "Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel"
331
+ " like i'm going to throw up.\nand why is that?"
332
+ )
333
+
334
+ model_inputs = self.tokenizer([src_text], return_tensors="pt").to(torch_device)
335
+
336
+ generated_ids = model.generate(**model_inputs, **FASTER_GEN_KWARGS)[0]
337
+ reply = self.tokenizer.decode(generated_ids, **TOK_DECODE_KW)
338
+
339
+ assert "I think it's because we are so worried about what people think of us." == reply.strip()
340
+ del model
341
+
342
+
343
+ class BlenderbotStandaloneDecoderModelTester:
344
+ def __init__(
345
+ self,
346
+ parent,
347
+ vocab_size=99,
348
+ batch_size=13,
349
+ d_model=16,
350
+ decoder_seq_length=7,
351
+ is_training=True,
352
+ is_decoder=True,
353
+ use_attention_mask=True,
354
+ use_cache=False,
355
+ use_labels=True,
356
+ decoder_start_token_id=2,
357
+ decoder_ffn_dim=32,
358
+ decoder_layers=2,
359
+ encoder_attention_heads=4,
360
+ decoder_attention_heads=4,
361
+ max_position_embeddings=30,
362
+ is_encoder_decoder=False,
363
+ pad_token_id=0,
364
+ bos_token_id=1,
365
+ eos_token_id=2,
366
+ scope=None,
367
+ ):
368
+ self.parent = parent
369
+ self.batch_size = batch_size
370
+ self.decoder_seq_length = decoder_seq_length
371
+ # For common tests
372
+ self.seq_length = self.decoder_seq_length
373
+ self.is_training = is_training
374
+ self.use_attention_mask = use_attention_mask
375
+ self.use_labels = use_labels
376
+
377
+ self.vocab_size = vocab_size
378
+ self.d_model = d_model
379
+ self.hidden_size = d_model
380
+ self.num_hidden_layers = decoder_layers
381
+ self.decoder_layers = decoder_layers
382
+ self.decoder_ffn_dim = decoder_ffn_dim
383
+ self.encoder_attention_heads = encoder_attention_heads
384
+ self.decoder_attention_heads = decoder_attention_heads
385
+ self.num_attention_heads = decoder_attention_heads
386
+ self.eos_token_id = eos_token_id
387
+ self.bos_token_id = bos_token_id
388
+ self.pad_token_id = pad_token_id
389
+ self.decoder_start_token_id = decoder_start_token_id
390
+ self.use_cache = use_cache
391
+ self.max_position_embeddings = max_position_embeddings
392
+ self.is_encoder_decoder = is_encoder_decoder
393
+
394
+ self.scope = None
395
+ self.decoder_key_length = decoder_seq_length
396
+ self.base_model_out_len = 2
397
+ self.decoder_attention_idx = 1
398
+
399
+ def prepare_config_and_inputs(self):
400
+ input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)
401
+
402
+ attention_mask = None
403
+ if self.use_attention_mask:
404
+ attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2)
405
+
406
+ lm_labels = None
407
+ if self.use_labels:
408
+ lm_labels = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)
409
+
410
+ config = BlenderbotConfig(
411
+ vocab_size=self.vocab_size,
412
+ d_model=self.d_model,
413
+ decoder_layers=self.decoder_layers,
414
+ decoder_ffn_dim=self.decoder_ffn_dim,
415
+ encoder_attention_heads=self.encoder_attention_heads,
416
+ decoder_attention_heads=self.decoder_attention_heads,
417
+ eos_token_id=self.eos_token_id,
418
+ bos_token_id=self.bos_token_id,
419
+ use_cache=self.use_cache,
420
+ pad_token_id=self.pad_token_id,
421
+ decoder_start_token_id=self.decoder_start_token_id,
422
+ max_position_embeddings=self.max_position_embeddings,
423
+ is_encoder_decoder=self.is_encoder_decoder,
424
+ )
425
+
426
+ return (
427
+ config,
428
+ input_ids,
429
+ attention_mask,
430
+ lm_labels,
431
+ )
432
+
433
+ def create_and_check_decoder_model_past(
434
+ self,
435
+ config,
436
+ input_ids,
437
+ attention_mask,
438
+ lm_labels,
439
+ ):
440
+ config.use_cache = True
441
+ model = BlenderbotDecoder(config=config).to(torch_device).eval()
442
+ # first forward pass
443
+ outputs = model(input_ids, use_cache=True)
444
+ outputs_use_cache_conf = model(input_ids)
445
+ outputs_no_past = model(input_ids, use_cache=False)
446
+
447
+ self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))
448
+ self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)
449
+
450
+ past_key_values = outputs["past_key_values"]
451
+
452
+ # create hypothetical next token and extent to next_input_ids
453
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
454
+
455
+ # append to next input_ids and
456
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
457
+
458
+ output_from_no_past = model(next_input_ids)["last_hidden_state"]
459
+ output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"]
460
+
461
+ # select random slice
462
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
463
+ output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
464
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
465
+
466
+ # test that outputs are equal for slice
467
+ assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)
468
+
469
+ def create_and_check_decoder_model_attention_mask_past(
470
+ self,
471
+ config,
472
+ input_ids,
473
+ attention_mask,
474
+ lm_labels,
475
+ ):
476
+ model = BlenderbotDecoder(config=config).to(torch_device).eval()
477
+
478
+ # create attention mask
479
+ attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
480
+
481
+ half_seq_length = input_ids.shape[-1] // 2
482
+ attn_mask[:, half_seq_length:] = 0
483
+
484
+ # first forward pass
485
+ past_key_values = model(input_ids, attention_mask=attn_mask, use_cache=True)["past_key_values"]
486
+ # past_key_values = model(input_ids, use_cache=True)["past_key_values"]
487
+
488
+ # create hypothetical next token and extent to next_input_ids
489
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
490
+
491
+ # change a random masked slice from input_ids
492
+ random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1
493
+ random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1)
494
+ input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens
495
+
496
+ # append to next input_ids and attn_mask
497
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
498
+ attn_mask = torch.cat(
499
+ [attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)],
500
+ dim=1,
501
+ )
502
+
503
+ # get two different outputs
504
+ output_from_no_past = model(next_input_ids, attention_mask=attn_mask)["last_hidden_state"]
505
+ output_from_past = model(next_tokens, past_key_values=past_key_values, attention_mask=attn_mask)[
506
+ "last_hidden_state"
507
+ ]
508
+
509
+ # select random slice
510
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
511
+ output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
512
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
513
+
514
+ # test that outputs are equal for slice
515
+ assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)
516
+
517
+ def prepare_config_and_inputs_for_common(self):
518
+ config_and_inputs = self.prepare_config_and_inputs()
519
+ (
520
+ config,
521
+ input_ids,
522
+ attention_mask,
523
+ lm_labels,
524
+ ) = config_and_inputs
525
+
526
+ inputs_dict = {
527
+ "input_ids": input_ids,
528
+ "attention_mask": attention_mask,
529
+ }
530
+ return config, inputs_dict
531
+
532
+
533
+ @require_torch
534
+ class BlenderbotStandaloneDecoderModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
535
+ all_model_classes = (BlenderbotDecoder, BlenderbotForCausalLM) if is_torch_available() else ()
536
+ all_generative_model_classes = (BlenderbotForCausalLM,) if is_torch_available() else ()
537
+ test_pruning = False
538
+ is_encoder_decoder = False
539
+
540
+ def setUp(
541
+ self,
542
+ ):
543
+ self.model_tester = BlenderbotStandaloneDecoderModelTester(self, is_training=False)
544
+ self.config_tester = ConfigTester(self, config_class=BlenderbotConfig)
545
+
546
+ def test_config(self):
547
+ self.config_tester.run_common_tests()
548
+
549
+ def test_decoder_model_past(self):
550
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
551
+ self.model_tester.create_and_check_decoder_model_past(*config_and_inputs)
552
+
553
+ def test_decoder_model_attn_mask_past(self):
554
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
555
+ self.model_tester.create_and_check_decoder_model_attention_mask_past(*config_and_inputs)
556
+
557
+ @unittest.skip(reason="decoder cannot keep gradients")
558
+ def test_retain_grad_hidden_states_attentions(self):
559
+ return
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blenderbot/test_modeling_flax_blenderbot.py ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import unittest
16
+
17
+ import numpy as np
18
+ import timeout_decorator # noqa
19
+
20
+ from transformers import BlenderbotConfig, is_flax_available
21
+ from transformers.testing_utils import jax_device, require_flax, slow
22
+
23
+ from ...generation.test_flax_utils import FlaxGenerationTesterMixin
24
+ from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor
25
+
26
+
27
+ if is_flax_available():
28
+ import os
29
+
30
+ # The slow tests are often failing with OOM error on GPU
31
+ # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
32
+ # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
33
+ os.environ["XLA_PYTHON_CLIENT_ALLOCATOR"] = "platform"
34
+
35
+ import jax
36
+ import jax.numpy as jnp
37
+
38
+ from transformers import BlenderbotTokenizer
39
+ from transformers.models.blenderbot.modeling_flax_blenderbot import (
40
+ FlaxBlenderbotForConditionalGeneration,
41
+ FlaxBlenderbotModel,
42
+ shift_tokens_right,
43
+ )
44
+
45
+
46
+ def prepare_blenderbot_inputs_dict(
47
+ config,
48
+ input_ids,
49
+ decoder_input_ids=None,
50
+ attention_mask=None,
51
+ decoder_attention_mask=None,
52
+ head_mask=None,
53
+ decoder_head_mask=None,
54
+ cross_attn_head_mask=None,
55
+ ):
56
+ if attention_mask is None:
57
+ attention_mask = np.where(input_ids != config.pad_token_id, 1, 0)
58
+ if decoder_attention_mask is None:
59
+ decoder_attention_mask = np.where(decoder_input_ids != config.pad_token_id, 1, 0)
60
+ if head_mask is None:
61
+ head_mask = np.ones((config.encoder_layers, config.encoder_attention_heads))
62
+ if decoder_head_mask is None:
63
+ decoder_head_mask = np.ones((config.decoder_layers, config.decoder_attention_heads))
64
+ if cross_attn_head_mask is None:
65
+ cross_attn_head_mask = np.ones((config.decoder_layers, config.decoder_attention_heads))
66
+ return {
67
+ "input_ids": input_ids,
68
+ "decoder_input_ids": decoder_input_ids,
69
+ "attention_mask": attention_mask,
70
+ "decoder_attention_mask": attention_mask,
71
+ }
72
+
73
+
74
+ class FlaxBlenderbotModelTester:
75
+ def __init__(
76
+ self,
77
+ parent,
78
+ batch_size=13,
79
+ seq_length=7,
80
+ is_training=True,
81
+ use_labels=False,
82
+ vocab_size=99,
83
+ hidden_size=16,
84
+ num_hidden_layers=2,
85
+ num_attention_heads=4,
86
+ intermediate_size=4,
87
+ hidden_act="gelu",
88
+ hidden_dropout_prob=0.1,
89
+ attention_probs_dropout_prob=0.1,
90
+ max_position_embeddings=50,
91
+ eos_token_id=2,
92
+ pad_token_id=1,
93
+ bos_token_id=0,
94
+ initializer_range=0.02,
95
+ ):
96
+ self.parent = parent
97
+ self.batch_size = batch_size
98
+ self.seq_length = seq_length
99
+ self.is_training = is_training
100
+ self.use_labels = use_labels
101
+ self.vocab_size = vocab_size
102
+ self.hidden_size = hidden_size
103
+ self.num_hidden_layers = num_hidden_layers
104
+ self.num_attention_heads = num_attention_heads
105
+ self.intermediate_size = intermediate_size
106
+ self.hidden_act = hidden_act
107
+ self.hidden_dropout_prob = hidden_dropout_prob
108
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
109
+ self.max_position_embeddings = max_position_embeddings
110
+ self.eos_token_id = eos_token_id
111
+ self.pad_token_id = pad_token_id
112
+ self.bos_token_id = bos_token_id
113
+ self.initializer_range = initializer_range
114
+
115
+ def prepare_config_and_inputs(self):
116
+ input_ids = np.clip(ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size), 3, self.vocab_size)
117
+ input_ids = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1), dtype=np.int64)), -1)
118
+
119
+ decoder_input_ids = shift_tokens_right(input_ids, 1, 2)
120
+
121
+ config = BlenderbotConfig(
122
+ vocab_size=self.vocab_size,
123
+ d_model=self.hidden_size,
124
+ encoder_layers=self.num_hidden_layers,
125
+ decoder_layers=self.num_hidden_layers,
126
+ encoder_attention_heads=self.num_attention_heads,
127
+ decoder_attention_heads=self.num_attention_heads,
128
+ encoder_ffn_dim=self.intermediate_size,
129
+ decoder_ffn_dim=self.intermediate_size,
130
+ dropout=self.hidden_dropout_prob,
131
+ attention_dropout=self.attention_probs_dropout_prob,
132
+ max_position_embeddings=self.max_position_embeddings,
133
+ eos_token_id=self.eos_token_id,
134
+ bos_token_id=self.bos_token_id,
135
+ pad_token_id=self.pad_token_id,
136
+ initializer_range=self.initializer_range,
137
+ use_cache=False,
138
+ )
139
+ inputs_dict = prepare_blenderbot_inputs_dict(config, input_ids, decoder_input_ids)
140
+ return config, inputs_dict
141
+
142
+ def prepare_config_and_inputs_for_common(self):
143
+ config, inputs_dict = self.prepare_config_and_inputs()
144
+ return config, inputs_dict
145
+
146
+ def check_use_cache_forward(self, model_class_name, config, inputs_dict):
147
+ max_decoder_length = 20
148
+ model = model_class_name(config)
149
+
150
+ encoder_outputs = model.encode(inputs_dict["input_ids"])
151
+
152
+ decoder_input_ids, decoder_attention_mask = (
153
+ inputs_dict["decoder_input_ids"],
154
+ inputs_dict["decoder_attention_mask"],
155
+ )
156
+
157
+ past_key_values = model.init_cache(decoder_input_ids.shape[0], max_decoder_length, encoder_outputs)
158
+ decoder_attention_mask = jnp.ones((decoder_input_ids.shape[0], max_decoder_length), dtype="i4")
159
+
160
+ decoder_position_ids = jnp.broadcast_to(
161
+ jnp.arange(decoder_input_ids.shape[-1] - 1)[None, :],
162
+ (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1),
163
+ )
164
+ outputs_cache = model.decode(
165
+ decoder_input_ids[:, :-1],
166
+ encoder_outputs,
167
+ decoder_attention_mask=decoder_attention_mask,
168
+ past_key_values=past_key_values,
169
+ decoder_position_ids=decoder_position_ids,
170
+ )
171
+
172
+ decoder_position_ids = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]], dtype="i4")
173
+ outputs_cache_next = model.decode(
174
+ decoder_input_ids[:, -1:],
175
+ encoder_outputs,
176
+ decoder_attention_mask=decoder_attention_mask,
177
+ past_key_values=outputs_cache.past_key_values,
178
+ decoder_position_ids=decoder_position_ids,
179
+ )
180
+
181
+ outputs = model.decode(decoder_input_ids, encoder_outputs)
182
+
183
+ diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
184
+ self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}")
185
+
186
+ def check_use_cache_forward_with_attn_mask(self, model_class_name, config, inputs_dict):
187
+ max_decoder_length = 20
188
+ model = model_class_name(config)
189
+
190
+ encoder_outputs = model.encode(inputs_dict["input_ids"])
191
+
192
+ decoder_input_ids, decoder_attention_mask = (
193
+ inputs_dict["decoder_input_ids"],
194
+ inputs_dict["decoder_attention_mask"],
195
+ )
196
+
197
+ decoder_attention_mask_cache = jnp.concatenate(
198
+ [
199
+ decoder_attention_mask,
200
+ jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])),
201
+ ],
202
+ axis=-1,
203
+ )
204
+
205
+ past_key_values = model.init_cache(decoder_input_ids.shape[0], max_decoder_length, encoder_outputs)
206
+ decoder_position_ids = jnp.broadcast_to(
207
+ jnp.arange(decoder_input_ids.shape[-1] - 1)[None, :],
208
+ (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1),
209
+ )
210
+
211
+ outputs_cache = model.decode(
212
+ decoder_input_ids[:, :-1],
213
+ encoder_outputs,
214
+ decoder_attention_mask=decoder_attention_mask_cache,
215
+ past_key_values=past_key_values,
216
+ decoder_position_ids=decoder_position_ids,
217
+ )
218
+ decoder_position_ids = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]], dtype="i4")
219
+ outputs_cache_next = model.decode(
220
+ decoder_input_ids[:, -1:],
221
+ encoder_outputs,
222
+ past_key_values=outputs_cache.past_key_values,
223
+ decoder_attention_mask=decoder_attention_mask_cache,
224
+ decoder_position_ids=decoder_position_ids,
225
+ )
226
+
227
+ outputs = model.decode(decoder_input_ids, encoder_outputs, decoder_attention_mask=decoder_attention_mask)
228
+
229
+ diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
230
+ self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}")
231
+
232
+
233
+ @require_flax
234
+ class BlenderbotHeadTests(unittest.TestCase):
235
+ vocab_size = 99
236
+
237
+ def _get_config_and_data(self):
238
+ input_ids = np.array(
239
+ [
240
+ [71, 82, 18, 33, 46, 91, 2],
241
+ [68, 34, 26, 58, 30, 82, 2],
242
+ [5, 97, 17, 39, 94, 40, 2],
243
+ [76, 83, 94, 25, 70, 78, 2],
244
+ [87, 59, 41, 35, 48, 66, 2],
245
+ [55, 13, 16, 58, 5, 2, 1], # note padding
246
+ [64, 27, 31, 51, 12, 75, 2],
247
+ [52, 64, 86, 17, 83, 39, 2],
248
+ [48, 61, 9, 24, 71, 82, 2],
249
+ [26, 1, 60, 48, 22, 13, 2],
250
+ [21, 5, 62, 28, 14, 76, 2],
251
+ [45, 98, 37, 86, 59, 48, 2],
252
+ [70, 70, 50, 9, 28, 0, 2],
253
+ ],
254
+ dtype=np.int64,
255
+ )
256
+
257
+ batch_size = input_ids.shape[0]
258
+ config = BlenderbotConfig(
259
+ vocab_size=self.vocab_size,
260
+ d_model=24,
261
+ encoder_layers=2,
262
+ decoder_layers=2,
263
+ encoder_attention_heads=2,
264
+ decoder_attention_heads=2,
265
+ encoder_ffn_dim=32,
266
+ decoder_ffn_dim=32,
267
+ max_position_embeddings=48,
268
+ eos_token_id=2,
269
+ pad_token_id=1,
270
+ bos_token_id=0,
271
+ )
272
+ return config, input_ids, batch_size
273
+
274
+ # @timeout_decorator.timeout(1) # not working with the decorator so far
275
+ def test_lm_forward(self):
276
+ config, input_ids, batch_size = self._get_config_and_data()
277
+ lm_model = FlaxBlenderbotForConditionalGeneration(config)
278
+ outputs = lm_model(input_ids=input_ids)
279
+ expected_shape = (batch_size, input_ids.shape[1], config.vocab_size)
280
+ self.assertEqual(outputs["logits"].shape, expected_shape)
281
+
282
+ def test_lm_uneven_forward(self):
283
+ config = BlenderbotConfig(
284
+ vocab_size=self.vocab_size,
285
+ d_model=14,
286
+ encoder_layers=2,
287
+ decoder_layers=2,
288
+ encoder_attention_heads=2,
289
+ decoder_attention_heads=2,
290
+ encoder_ffn_dim=8,
291
+ decoder_ffn_dim=8,
292
+ max_position_embeddings=48,
293
+ )
294
+ lm_model = FlaxBlenderbotForConditionalGeneration(config)
295
+ context = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]], dtype=np.int64)
296
+ summary = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]], dtype=np.int64)
297
+ outputs = lm_model(input_ids=context, decoder_input_ids=summary)
298
+ expected_shape = (*summary.shape, config.vocab_size)
299
+ self.assertEqual(outputs["logits"].shape, expected_shape)
300
+
301
+ def test_shift_tokens_right(self):
302
+ input_ids = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]], dtype=np.int64)
303
+ shifted = shift_tokens_right(input_ids, 1, 2)
304
+ n_pad_before = np.equal(input_ids, 1).astype(np.float32).sum()
305
+ n_pad_after = np.equal(shifted, 1).astype(np.float32).sum()
306
+ self.assertEqual(shifted.shape, input_ids.shape)
307
+ self.assertEqual(n_pad_after, n_pad_before - 1)
308
+ self.assertTrue(np.equal(shifted[:, 0], 2).all())
309
+
310
+
311
+ @require_flax
312
+ class FlaxBlenderbotModelTest(FlaxModelTesterMixin, unittest.TestCase, FlaxGenerationTesterMixin):
313
+ is_encoder_decoder = True
314
+ all_model_classes = (
315
+ (
316
+ FlaxBlenderbotModel,
317
+ FlaxBlenderbotForConditionalGeneration,
318
+ )
319
+ if is_flax_available()
320
+ else ()
321
+ )
322
+ all_generative_model_classes = (FlaxBlenderbotForConditionalGeneration,) if is_flax_available() else ()
323
+
324
+ def setUp(self):
325
+ self.model_tester = FlaxBlenderbotModelTester(self)
326
+
327
+ def test_use_cache_forward(self):
328
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
329
+ for model_class in self.all_model_classes:
330
+ self.model_tester.check_use_cache_forward(model_class, config, inputs_dict)
331
+
332
+ def test_use_cache_forward_with_attn_mask(self):
333
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
334
+ for model_class in self.all_model_classes:
335
+ self.model_tester.check_use_cache_forward_with_attn_mask(model_class, config, inputs_dict)
336
+
337
+ def test_encode(self):
338
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
339
+
340
+ for model_class in self.all_model_classes:
341
+ with self.subTest(model_class.__name__):
342
+ prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class)
343
+ model = model_class(config)
344
+
345
+ @jax.jit
346
+ def encode_jitted(input_ids, attention_mask=None, **kwargs):
347
+ return model.encode(input_ids=input_ids, attention_mask=attention_mask)
348
+
349
+ with self.subTest("JIT Enabled"):
350
+ jitted_outputs = encode_jitted(**prepared_inputs_dict).to_tuple()
351
+
352
+ with self.subTest("JIT Disabled"):
353
+ with jax.disable_jit():
354
+ outputs = encode_jitted(**prepared_inputs_dict).to_tuple()
355
+
356
+ self.assertEqual(len(outputs), len(jitted_outputs))
357
+ for jitted_output, output in zip(jitted_outputs, outputs):
358
+ self.assertEqual(jitted_output.shape, output.shape)
359
+
360
+ def test_decode(self):
361
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
362
+
363
+ for model_class in self.all_model_classes:
364
+ with self.subTest(model_class.__name__):
365
+ model = model_class(config)
366
+ encoder_outputs = model.encode(inputs_dict["input_ids"], inputs_dict["attention_mask"])
367
+
368
+ prepared_inputs_dict = {
369
+ "decoder_input_ids": inputs_dict["decoder_input_ids"],
370
+ "decoder_attention_mask": inputs_dict["decoder_attention_mask"],
371
+ "encoder_outputs": encoder_outputs,
372
+ }
373
+
374
+ @jax.jit
375
+ def decode_jitted(decoder_input_ids, decoder_attention_mask, encoder_outputs):
376
+ return model.decode(
377
+ decoder_input_ids=decoder_input_ids,
378
+ decoder_attention_mask=decoder_attention_mask,
379
+ encoder_outputs=encoder_outputs,
380
+ )
381
+
382
+ with self.subTest("JIT Enabled"):
383
+ jitted_outputs = decode_jitted(**prepared_inputs_dict).to_tuple()
384
+
385
+ with self.subTest("JIT Disabled"):
386
+ with jax.disable_jit():
387
+ outputs = decode_jitted(**prepared_inputs_dict).to_tuple()
388
+
389
+ self.assertEqual(len(outputs), len(jitted_outputs))
390
+ for jitted_output, output in zip(jitted_outputs, outputs):
391
+ self.assertEqual(jitted_output.shape, output.shape)
392
+
393
+ @slow
394
+ def test_model_from_pretrained(self):
395
+ for model_class_name in self.all_model_classes:
396
+ model = model_class_name.from_pretrained("facebook/blenderbot-400M-distill")
397
+ # FlaxBlenderbotForSequenceClassification expects eos token in input_ids
398
+ input_ids = np.ones((1, 1)) * model.config.eos_token_id
399
+ outputs = model(input_ids)
400
+ self.assertIsNotNone(outputs)
401
+
402
+ @unittest.skipUnless(jax_device != "cpu", "3B test too slow on CPU.")
403
+ @slow
404
+ def test_generation_from_short_input_same_as_parlai_3B(self):
405
+ FASTER_GEN_KWARGS = {"num_beams": 1, "early_stopping": True, "min_length": 15, "max_length": 25}
406
+ TOK_DECODE_KW = {"skip_special_tokens": True, "clean_up_tokenization_spaces": True}
407
+
408
+ model = FlaxBlenderbotForConditionalGeneration.from_pretrained("facebook/blenderbot-3B", from_pt=True)
409
+ tokenizer = BlenderbotTokenizer.from_pretrained("facebook/blenderbot-3B")
410
+
411
+ src_text = ["Sam"]
412
+ model_inputs = tokenizer(src_text, return_tensors="jax")
413
+
414
+ generated_utterances = model.generate(**model_inputs, **FASTER_GEN_KWARGS)
415
+ tgt_text = 'Sam is a great name. It means "sun" in Gaelic.'
416
+
417
+ generated_txt = tokenizer.batch_decode(generated_utterances, **TOK_DECODE_KW)
418
+ assert generated_txt[0].strip() == tgt_text
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blenderbot/test_modeling_tf_blenderbot.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+
17
+ from __future__ import annotations
18
+
19
+ import unittest
20
+
21
+ from transformers import BlenderbotConfig, BlenderbotTokenizer, is_tf_available
22
+ from transformers.testing_utils import require_tf, require_tokenizers, slow
23
+ from transformers.utils import cached_property
24
+
25
+ from ...test_configuration_common import ConfigTester
26
+ from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
27
+ from ...test_pipeline_mixin import PipelineTesterMixin
28
+
29
+
30
+ if is_tf_available():
31
+ import tensorflow as tf
32
+
33
+ from transformers import TFAutoModelForSeq2SeqLM, TFBlenderbotForConditionalGeneration, TFBlenderbotModel
34
+
35
+
36
+ @require_tf
37
+ class TFBlenderbotModelTester:
38
+ config_cls = BlenderbotConfig
39
+ config_updates = {}
40
+ hidden_act = "gelu"
41
+
42
+ def __init__(
43
+ self,
44
+ parent,
45
+ batch_size=13,
46
+ seq_length=7,
47
+ is_training=True,
48
+ use_labels=False,
49
+ vocab_size=99,
50
+ hidden_size=32,
51
+ num_hidden_layers=2,
52
+ num_attention_heads=4,
53
+ intermediate_size=37,
54
+ hidden_dropout_prob=0.1,
55
+ attention_probs_dropout_prob=0.1,
56
+ max_position_embeddings=50,
57
+ eos_token_id=2,
58
+ pad_token_id=1,
59
+ bos_token_id=0,
60
+ ):
61
+ self.parent = parent
62
+ self.batch_size = batch_size
63
+ self.seq_length = seq_length
64
+ self.is_training = is_training
65
+ self.use_labels = use_labels
66
+ self.vocab_size = vocab_size
67
+ self.hidden_size = hidden_size
68
+ self.num_hidden_layers = num_hidden_layers
69
+ self.num_attention_heads = num_attention_heads
70
+ self.intermediate_size = intermediate_size
71
+
72
+ self.hidden_dropout_prob = hidden_dropout_prob
73
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
74
+ self.max_position_embeddings = max_position_embeddings
75
+ self.eos_token_id = eos_token_id
76
+ self.pad_token_id = pad_token_id
77
+ self.bos_token_id = bos_token_id
78
+
79
+ def prepare_config_and_inputs_for_common(self):
80
+ input_ids = ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size)
81
+ eos_tensor = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size), 1)
82
+ input_ids = tf.concat([input_ids, eos_tensor], axis=1)
83
+
84
+ decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
85
+
86
+ config = self.config_cls(
87
+ vocab_size=self.vocab_size,
88
+ d_model=self.hidden_size,
89
+ encoder_layers=self.num_hidden_layers,
90
+ decoder_layers=self.num_hidden_layers,
91
+ encoder_attention_heads=self.num_attention_heads,
92
+ decoder_attention_heads=self.num_attention_heads,
93
+ encoder_ffn_dim=self.intermediate_size,
94
+ decoder_ffn_dim=self.intermediate_size,
95
+ dropout=self.hidden_dropout_prob,
96
+ attention_dropout=self.attention_probs_dropout_prob,
97
+ max_position_embeddings=self.max_position_embeddings,
98
+ eos_token_ids=[2],
99
+ bos_token_id=self.bos_token_id,
100
+ pad_token_id=self.pad_token_id,
101
+ decoder_start_token_id=self.pad_token_id,
102
+ **self.config_updates,
103
+ )
104
+ inputs_dict = prepare_blenderbot_inputs_dict(config, input_ids, decoder_input_ids)
105
+ return config, inputs_dict
106
+
107
+ def check_decoder_model_past_large_inputs(self, config, inputs_dict):
108
+ model = TFBlenderbotModel(config=config).get_decoder()
109
+ input_ids = inputs_dict["input_ids"]
110
+
111
+ input_ids = input_ids[:1, :]
112
+ attention_mask = inputs_dict["attention_mask"][:1, :]
113
+ head_mask = inputs_dict["head_mask"]
114
+ self.batch_size = 1
115
+
116
+ # first forward pass
117
+ outputs = model(input_ids, attention_mask=attention_mask, head_mask=head_mask, use_cache=True)
118
+
119
+ output, past_key_values = outputs.to_tuple()
120
+
121
+ # create hypothetical next token and extent to next_input_ids
122
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
123
+ next_attn_mask = tf.cast(ids_tensor((self.batch_size, 3), 2), tf.int8)
124
+
125
+ # append to next input_ids and
126
+ next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
127
+ next_attention_mask = tf.concat([attention_mask, next_attn_mask], axis=-1)
128
+
129
+ output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)[0]
130
+ output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[0]
131
+
132
+ self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1])
133
+
134
+ # select random slice
135
+ random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1]))
136
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx]
137
+ output_from_past_slice = output_from_past[:, :, random_slice_idx]
138
+
139
+ # test that outputs are equal for slice
140
+ tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3)
141
+
142
+
143
+ def prepare_blenderbot_inputs_dict(
144
+ config,
145
+ input_ids,
146
+ decoder_input_ids,
147
+ attention_mask=None,
148
+ decoder_attention_mask=None,
149
+ head_mask=None,
150
+ decoder_head_mask=None,
151
+ cross_attn_head_mask=None,
152
+ ):
153
+ if attention_mask is None:
154
+ attention_mask = tf.cast(tf.math.not_equal(input_ids, config.pad_token_id), tf.int8)
155
+ if decoder_attention_mask is None:
156
+ decoder_attention_mask = tf.concat(
157
+ [
158
+ tf.ones(decoder_input_ids[:, :1].shape, dtype=tf.int8),
159
+ tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:], config.pad_token_id), tf.int8),
160
+ ],
161
+ axis=-1,
162
+ )
163
+ if head_mask is None:
164
+ head_mask = tf.ones((config.encoder_layers, config.encoder_attention_heads))
165
+ if decoder_head_mask is None:
166
+ decoder_head_mask = tf.ones((config.decoder_layers, config.decoder_attention_heads))
167
+ if cross_attn_head_mask is None:
168
+ cross_attn_head_mask = tf.ones((config.decoder_layers, config.decoder_attention_heads))
169
+ return {
170
+ "input_ids": input_ids,
171
+ "decoder_input_ids": decoder_input_ids,
172
+ "attention_mask": attention_mask,
173
+ "decoder_attention_mask": decoder_attention_mask,
174
+ "head_mask": head_mask,
175
+ "decoder_head_mask": decoder_head_mask,
176
+ "cross_attn_head_mask": cross_attn_head_mask,
177
+ }
178
+
179
+
180
+ @require_tf
181
+ class TFBlenderbotModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
182
+ all_model_classes = (TFBlenderbotForConditionalGeneration, TFBlenderbotModel) if is_tf_available() else ()
183
+ all_generative_model_classes = (TFBlenderbotForConditionalGeneration,) if is_tf_available() else ()
184
+ pipeline_model_mapping = (
185
+ {
186
+ "feature-extraction": TFBlenderbotModel,
187
+ "summarization": TFBlenderbotForConditionalGeneration,
188
+ "text2text-generation": TFBlenderbotForConditionalGeneration,
189
+ "translation": TFBlenderbotForConditionalGeneration,
190
+ }
191
+ if is_tf_available()
192
+ else {}
193
+ )
194
+ is_encoder_decoder = True
195
+ test_pruning = False
196
+ test_onnx = False
197
+
198
+ def setUp(self):
199
+ self.model_tester = TFBlenderbotModelTester(self)
200
+ self.config_tester = ConfigTester(self, config_class=BlenderbotConfig)
201
+
202
+ def test_config(self):
203
+ self.config_tester.run_common_tests()
204
+
205
+ def test_decoder_model_past_large_inputs(self):
206
+ config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common()
207
+ self.model_tester.check_decoder_model_past_large_inputs(*config_and_inputs)
208
+
209
+
210
+ @require_tokenizers
211
+ @require_tf
212
+ class TFBlenderbot400MIntegrationTests(unittest.TestCase):
213
+ src_text = ["My friends are cool but they eat too many carbs."]
214
+ model_name = "facebook/blenderbot-400M-distill"
215
+
216
+ @cached_property
217
+ def tokenizer(self):
218
+ return BlenderbotTokenizer.from_pretrained(self.model_name)
219
+
220
+ @cached_property
221
+ def model(self):
222
+ model = TFAutoModelForSeq2SeqLM.from_pretrained(self.model_name)
223
+ return model
224
+
225
+ @slow
226
+ def test_generation_from_long_input(self):
227
+ model_inputs = self.tokenizer(self.src_text, return_tensors="tf")
228
+ generated_ids = self.model.generate(
229
+ model_inputs.input_ids,
230
+ )
231
+ generated_words = self.tokenizer.batch_decode(generated_ids.numpy(), skip_special_tokens=True)[0]
232
+ assert (
233
+ generated_words
234
+ == " That's unfortunate. Are they trying to lose weight or are they just trying to be healthier?"
235
+ )
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blenderbot/test_tokenization_blenderbot.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # coding=utf-8
3
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """Tests for Blenderbot Tokenizers, including common tests for BlenderbotSmallTokenizer."""
17
+
18
+ import unittest
19
+
20
+ from transformers import BlenderbotTokenizer, BlenderbotTokenizerFast
21
+ from transformers.testing_utils import require_jinja
22
+ from transformers.utils import cached_property
23
+
24
+
25
+ class Blenderbot3BTokenizerTests(unittest.TestCase):
26
+ @cached_property
27
+ def tokenizer_3b(self):
28
+ return BlenderbotTokenizer.from_pretrained("facebook/blenderbot-3B")
29
+
30
+ @cached_property
31
+ def rust_tokenizer_3b(self):
32
+ return BlenderbotTokenizerFast.from_pretrained("facebook/blenderbot-3B")
33
+
34
+ def test_encode_decode_cycle(self):
35
+ tok = self.tokenizer_3b
36
+ src_text = " I am a small frog."
37
+ encoded = tok([src_text], padding=False, truncation=False)["input_ids"]
38
+ decoded = tok.batch_decode(encoded, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
39
+ assert src_text == decoded
40
+
41
+ def test_encode_decode_cycle_rust_tokenizer(self):
42
+ tok = self.rust_tokenizer_3b
43
+ src_text = " I am a small frog."
44
+ encoded = tok([src_text], padding=False, truncation=False)["input_ids"]
45
+ decoded = tok.batch_decode(encoded, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
46
+ assert src_text == decoded
47
+
48
+ def test_3B_tokenization_same_as_parlai(self):
49
+ assert self.tokenizer_3b.add_prefix_space
50
+ assert self.tokenizer_3b([" Sam", "Sam"]).input_ids == [[5502, 2], [5502, 2]]
51
+
52
+ def test_3B_tokenization_same_as_parlai_rust_tokenizer(self):
53
+ assert self.rust_tokenizer_3b.add_prefix_space
54
+ assert self.rust_tokenizer_3b([" Sam", "Sam"]).input_ids == [[5502, 2], [5502, 2]]
55
+
56
+ @require_jinja
57
+ def test_tokenization_for_chat(self):
58
+ tok = self.tokenizer_3b
59
+ test_chats = [
60
+ [{"role": "system", "content": "You are a helpful chatbot."}, {"role": "user", "content": "Hello!"}],
61
+ [
62
+ {"role": "system", "content": "You are a helpful chatbot."},
63
+ {"role": "user", "content": "Hello!"},
64
+ {"role": "assistant", "content": "Nice to meet you."},
65
+ ],
66
+ [{"role": "assistant", "content": "Nice to meet you."}, {"role": "user", "content": "Hello!"}],
67
+ ]
68
+ tokenized_chats = [tok.apply_chat_template(test_chat) for test_chat in test_chats]
69
+ expected_tokens = [
70
+ [553, 366, 265, 4792, 3879, 73, 311, 21, 228, 228, 6950, 8, 2],
71
+ [553, 366, 265, 4792, 3879, 73, 311, 21, 228, 228, 6950, 8, 228, 3490, 287, 2273, 304, 21, 2],
72
+ [3490, 287, 2273, 304, 21, 228, 228, 6950, 8, 2],
73
+ ]
74
+ for tokenized_chat, expected_tokens in zip(tokenized_chats, expected_tokens):
75
+ self.assertListEqual(tokenized_chat, expected_tokens)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blenderbot_small/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blenderbot_small/test_modeling_blenderbot_small.py ADDED
@@ -0,0 +1,568 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021, The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Testing suite for the PyTorch BlenderbotSmall model."""
16
+
17
+ import tempfile
18
+ import unittest
19
+
20
+ from transformers import BlenderbotSmallConfig, is_torch_available
21
+ from transformers.testing_utils import (
22
+ require_torch,
23
+ require_torch_fp16,
24
+ slow,
25
+ torch_device,
26
+ )
27
+ from transformers.utils import cached_property
28
+
29
+ from ...generation.test_utils import GenerationTesterMixin
30
+ from ...test_configuration_common import ConfigTester
31
+ from ...test_modeling_common import ModelTesterMixin, ids_tensor
32
+ from ...test_pipeline_mixin import PipelineTesterMixin
33
+
34
+
35
+ if is_torch_available():
36
+ import torch
37
+
38
+ from transformers import BlenderbotSmallForConditionalGeneration, BlenderbotSmallModel, BlenderbotSmallTokenizer
39
+ from transformers.models.blenderbot_small.modeling_blenderbot_small import (
40
+ BlenderbotSmallDecoder,
41
+ BlenderbotSmallEncoder,
42
+ BlenderbotSmallForCausalLM,
43
+ )
44
+
45
+
46
+ def prepare_blenderbot_small_inputs_dict(
47
+ config,
48
+ input_ids,
49
+ decoder_input_ids,
50
+ attention_mask=None,
51
+ decoder_attention_mask=None,
52
+ head_mask=None,
53
+ decoder_head_mask=None,
54
+ cross_attn_head_mask=None,
55
+ ):
56
+ if attention_mask is None:
57
+ attention_mask = input_ids.ne(config.pad_token_id)
58
+ if decoder_attention_mask is None:
59
+ decoder_attention_mask = decoder_input_ids.ne(config.pad_token_id)
60
+ if head_mask is None:
61
+ head_mask = torch.ones(config.encoder_layers, config.encoder_attention_heads, device=torch_device)
62
+ if decoder_head_mask is None:
63
+ decoder_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads, device=torch_device)
64
+ if cross_attn_head_mask is None:
65
+ cross_attn_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads, device=torch_device)
66
+ return {
67
+ "input_ids": input_ids,
68
+ "decoder_input_ids": decoder_input_ids,
69
+ "attention_mask": attention_mask,
70
+ "decoder_attention_mask": attention_mask,
71
+ "head_mask": head_mask,
72
+ "decoder_head_mask": decoder_head_mask,
73
+ "cross_attn_head_mask": cross_attn_head_mask,
74
+ }
75
+
76
+
77
+ class BlenderbotSmallModelTester:
78
+ def __init__(
79
+ self,
80
+ parent,
81
+ batch_size=13,
82
+ seq_length=7,
83
+ is_training=True,
84
+ use_labels=False,
85
+ vocab_size=99,
86
+ hidden_size=16,
87
+ num_hidden_layers=2,
88
+ num_attention_heads=4,
89
+ intermediate_size=4,
90
+ hidden_act="gelu",
91
+ hidden_dropout_prob=0.1,
92
+ attention_probs_dropout_prob=0.1,
93
+ max_position_embeddings=50,
94
+ eos_token_id=2,
95
+ pad_token_id=1,
96
+ bos_token_id=0,
97
+ ):
98
+ self.parent = parent
99
+ self.batch_size = batch_size
100
+ self.seq_length = seq_length
101
+ self.is_training = is_training
102
+ self.use_labels = use_labels
103
+ self.vocab_size = vocab_size
104
+ self.hidden_size = hidden_size
105
+ self.num_hidden_layers = num_hidden_layers
106
+ self.num_attention_heads = num_attention_heads
107
+ self.intermediate_size = intermediate_size
108
+ self.hidden_act = hidden_act
109
+ self.hidden_dropout_prob = hidden_dropout_prob
110
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
111
+ self.max_position_embeddings = max_position_embeddings
112
+ self.eos_token_id = eos_token_id
113
+ self.pad_token_id = pad_token_id
114
+ self.bos_token_id = bos_token_id
115
+
116
+ def prepare_config_and_inputs(self):
117
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size).clamp(
118
+ 3,
119
+ )
120
+ input_ids[:, -1] = self.eos_token_id # Eos Token
121
+
122
+ decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
123
+
124
+ config = self.get_config()
125
+ inputs_dict = prepare_blenderbot_small_inputs_dict(config, input_ids, decoder_input_ids)
126
+ return config, inputs_dict
127
+
128
+ def get_config(self):
129
+ return BlenderbotSmallConfig(
130
+ vocab_size=self.vocab_size,
131
+ d_model=self.hidden_size,
132
+ encoder_layers=self.num_hidden_layers,
133
+ decoder_layers=self.num_hidden_layers,
134
+ encoder_attention_heads=self.num_attention_heads,
135
+ decoder_attention_heads=self.num_attention_heads,
136
+ encoder_ffn_dim=self.intermediate_size,
137
+ decoder_ffn_dim=self.intermediate_size,
138
+ dropout=self.hidden_dropout_prob,
139
+ attention_dropout=self.attention_probs_dropout_prob,
140
+ max_position_embeddings=self.max_position_embeddings,
141
+ eos_token_id=self.eos_token_id,
142
+ bos_token_id=self.bos_token_id,
143
+ pad_token_id=self.pad_token_id,
144
+ )
145
+
146
+ def prepare_config_and_inputs_for_common(self):
147
+ config, inputs_dict = self.prepare_config_and_inputs()
148
+ return config, inputs_dict
149
+
150
+ def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict):
151
+ model = BlenderbotSmallModel(config=config).get_decoder().to(torch_device).eval()
152
+ input_ids = inputs_dict["input_ids"]
153
+ attention_mask = inputs_dict["attention_mask"]
154
+ head_mask = inputs_dict["head_mask"]
155
+
156
+ # first forward pass
157
+ outputs = model(input_ids, attention_mask=attention_mask, head_mask=head_mask, use_cache=True)
158
+
159
+ output, past_key_values = outputs.to_tuple()
160
+
161
+ # create hypothetical multiple next token and extent to next_input_ids
162
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
163
+ next_attn_mask = ids_tensor((self.batch_size, 3), 2)
164
+
165
+ # append to next input_ids and
166
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
167
+ next_attention_mask = torch.cat([attention_mask, next_attn_mask], dim=-1)
168
+
169
+ output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"]
170
+ output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[
171
+ "last_hidden_state"
172
+ ]
173
+
174
+ # select random slice
175
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
176
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
177
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
178
+
179
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
180
+
181
+ # test that outputs are equal for slice
182
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
183
+
184
+ def check_encoder_decoder_model_standalone(self, config, inputs_dict):
185
+ model = BlenderbotSmallModel(config=config).to(torch_device).eval()
186
+ outputs = model(**inputs_dict)
187
+
188
+ encoder_last_hidden_state = outputs.encoder_last_hidden_state
189
+ last_hidden_state = outputs.last_hidden_state
190
+
191
+ with tempfile.TemporaryDirectory() as tmpdirname:
192
+ encoder = model.get_encoder()
193
+ encoder.save_pretrained(tmpdirname)
194
+ encoder = BlenderbotSmallEncoder.from_pretrained(tmpdirname).to(torch_device)
195
+
196
+ encoder_last_hidden_state_2 = encoder(inputs_dict["input_ids"], attention_mask=inputs_dict["attention_mask"])[
197
+ 0
198
+ ]
199
+
200
+ self.parent.assertTrue((encoder_last_hidden_state_2 - encoder_last_hidden_state).abs().max().item() < 1e-3)
201
+
202
+ with tempfile.TemporaryDirectory() as tmpdirname:
203
+ decoder = model.get_decoder()
204
+ decoder.save_pretrained(tmpdirname)
205
+ decoder = BlenderbotSmallDecoder.from_pretrained(tmpdirname).to(torch_device)
206
+
207
+ last_hidden_state_2 = decoder(
208
+ input_ids=inputs_dict["decoder_input_ids"],
209
+ attention_mask=inputs_dict["decoder_attention_mask"],
210
+ encoder_hidden_states=encoder_last_hidden_state,
211
+ encoder_attention_mask=inputs_dict["attention_mask"],
212
+ )[0]
213
+
214
+ self.parent.assertTrue((last_hidden_state_2 - last_hidden_state).abs().max().item() < 1e-3)
215
+
216
+
217
+ @require_torch
218
+ class BlenderbotSmallModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
219
+ all_model_classes = (BlenderbotSmallModel, BlenderbotSmallForConditionalGeneration) if is_torch_available() else ()
220
+ all_generative_model_classes = (BlenderbotSmallForConditionalGeneration,) if is_torch_available() else ()
221
+ pipeline_model_mapping = (
222
+ {
223
+ "feature-extraction": BlenderbotSmallModel,
224
+ "summarization": BlenderbotSmallForConditionalGeneration,
225
+ "text-generation": BlenderbotSmallForCausalLM,
226
+ "text2text-generation": BlenderbotSmallForConditionalGeneration,
227
+ "translation": BlenderbotSmallForConditionalGeneration,
228
+ }
229
+ if is_torch_available()
230
+ else {}
231
+ )
232
+ is_encoder_decoder = True
233
+ fx_compatible = True
234
+ test_pruning = False
235
+ test_missing_keys = False
236
+
237
+ # TODO: Fix the failed tests when this model gets more usage
238
+ def is_pipeline_test_to_skip(
239
+ self,
240
+ pipeline_test_case_name,
241
+ config_class,
242
+ model_architecture,
243
+ tokenizer_name,
244
+ image_processor_name,
245
+ feature_extractor_name,
246
+ processor_name,
247
+ ):
248
+ return pipeline_test_case_name == "TextGenerationPipelineTests"
249
+
250
+ def setUp(self):
251
+ self.model_tester = BlenderbotSmallModelTester(self)
252
+ self.config_tester = ConfigTester(self, config_class=BlenderbotSmallConfig)
253
+
254
+ def test_config(self):
255
+ self.config_tester.run_common_tests()
256
+
257
+ def test_save_load_strict(self):
258
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
259
+ for model_class in self.all_model_classes:
260
+ model = model_class(config)
261
+
262
+ with tempfile.TemporaryDirectory() as tmpdirname:
263
+ model.save_pretrained(tmpdirname)
264
+ model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True)
265
+ self.assertEqual(info["missing_keys"], [])
266
+
267
+ def test_decoder_model_past_with_large_inputs(self):
268
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
269
+ self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
270
+
271
+ def test_encoder_decoder_model_standalone(self):
272
+ config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common()
273
+ self.model_tester.check_encoder_decoder_model_standalone(*config_and_inputs)
274
+
275
+ @require_torch_fp16
276
+ def test_generate_fp16(self):
277
+ config, input_dict = self.model_tester.prepare_config_and_inputs()
278
+ input_ids = input_dict["input_ids"]
279
+ attention_mask = input_ids.ne(1).to(torch_device)
280
+ model = BlenderbotSmallForConditionalGeneration(config).eval().to(torch_device)
281
+ model.half()
282
+ model.generate(input_ids, attention_mask=attention_mask)
283
+ model.generate(num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3)
284
+
285
+
286
+ def assert_tensors_close(a, b, atol=1e-12, prefix=""):
287
+ """If tensors have different shapes, different values or a and b are not both tensors, raise a nice Assertion error."""
288
+ if a is None and b is None:
289
+ return True
290
+ try:
291
+ if torch.allclose(a, b, atol=atol):
292
+ return True
293
+ raise
294
+ except Exception:
295
+ pct_different = (torch.gt((a - b).abs(), atol)).float().mean().item()
296
+ if a.numel() > 100:
297
+ msg = f"tensor values are {pct_different:.1%} percent different."
298
+ else:
299
+ msg = f"{a} != {b}"
300
+ if prefix:
301
+ msg = prefix + ": " + msg
302
+ raise AssertionError(msg)
303
+
304
+
305
+ @require_torch
306
+ class Blenderbot90MIntegrationTests(unittest.TestCase):
307
+ ckpt = "facebook/blenderbot-90M"
308
+
309
+ @cached_property
310
+ def model(self):
311
+ model = BlenderbotSmallForConditionalGeneration.from_pretrained(self.ckpt).to(torch_device)
312
+ if torch_device == "cuda":
313
+ model = model.half()
314
+ return model
315
+
316
+ @cached_property
317
+ def tokenizer(self):
318
+ return BlenderbotSmallTokenizer.from_pretrained(self.ckpt)
319
+
320
+ @slow
321
+ def test_90_generation_from_long_input(self):
322
+ src_text = [
323
+ "Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel"
324
+ " like i'm going to throw up.\nand why is that?"
325
+ ]
326
+
327
+ model_inputs = self.tokenizer(src_text, return_tensors="pt").to(torch_device)
328
+
329
+ assert isinstance(self.tokenizer, BlenderbotSmallTokenizer)
330
+ generated_ids = self.model.generate(**model_inputs)[0]
331
+ reply = self.tokenizer.decode(generated_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True)
332
+
333
+ assert reply in (
334
+ "i don't know. i just feel like i'm going to throw up. it's not fun.",
335
+ "i'm not sure. i just feel like i've been feeling like i have to be in a certain place",
336
+ )
337
+
338
+ @slow
339
+ def test_90_generation_from_short_input(self):
340
+ model_inputs = self.tokenizer(["sam"], return_tensors="pt").to(torch_device)
341
+
342
+ generated_utterances = self.model.generate(**model_inputs)
343
+
344
+ clean_txt = self.tokenizer.decode(
345
+ generated_utterances[0], skip_special_tokens=True, clean_up_tokenization_spaces=True
346
+ )
347
+ assert clean_txt in (
348
+ "have you ever been to a sam club? it's a great club in the south.",
349
+ "have you ever heard of sam harris? he's an american singer, songwriter, and actor.",
350
+ )
351
+
352
+
353
+ class BlenderbotSmallStandaloneDecoderModelTester:
354
+ def __init__(
355
+ self,
356
+ parent,
357
+ vocab_size=99,
358
+ batch_size=13,
359
+ d_model=16,
360
+ decoder_seq_length=7,
361
+ is_training=True,
362
+ is_decoder=True,
363
+ use_attention_mask=True,
364
+ use_cache=False,
365
+ use_labels=True,
366
+ decoder_start_token_id=2,
367
+ decoder_ffn_dim=32,
368
+ decoder_layers=2,
369
+ encoder_attention_heads=4,
370
+ decoder_attention_heads=4,
371
+ max_position_embeddings=30,
372
+ is_encoder_decoder=False,
373
+ pad_token_id=0,
374
+ bos_token_id=1,
375
+ eos_token_id=2,
376
+ scope=None,
377
+ ):
378
+ self.parent = parent
379
+ self.batch_size = batch_size
380
+ self.decoder_seq_length = decoder_seq_length
381
+ # For common tests
382
+ self.seq_length = self.decoder_seq_length
383
+ self.is_training = is_training
384
+ self.use_attention_mask = use_attention_mask
385
+ self.use_labels = use_labels
386
+
387
+ self.vocab_size = vocab_size
388
+ self.d_model = d_model
389
+ self.hidden_size = d_model
390
+ self.num_hidden_layers = decoder_layers
391
+ self.decoder_layers = decoder_layers
392
+ self.decoder_ffn_dim = decoder_ffn_dim
393
+ self.encoder_attention_heads = encoder_attention_heads
394
+ self.decoder_attention_heads = decoder_attention_heads
395
+ self.num_attention_heads = decoder_attention_heads
396
+ self.eos_token_id = eos_token_id
397
+ self.bos_token_id = bos_token_id
398
+ self.pad_token_id = pad_token_id
399
+ self.decoder_start_token_id = decoder_start_token_id
400
+ self.use_cache = use_cache
401
+ self.max_position_embeddings = max_position_embeddings
402
+ self.is_encoder_decoder = is_encoder_decoder
403
+
404
+ self.scope = None
405
+ self.decoder_key_length = decoder_seq_length
406
+ self.base_model_out_len = 2
407
+ self.decoder_attention_idx = 1
408
+
409
+ def prepare_config_and_inputs(self):
410
+ input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)
411
+
412
+ attention_mask = None
413
+ if self.use_attention_mask:
414
+ attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2)
415
+
416
+ lm_labels = None
417
+ if self.use_labels:
418
+ lm_labels = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)
419
+
420
+ config = BlenderbotSmallConfig(
421
+ vocab_size=self.vocab_size,
422
+ d_model=self.d_model,
423
+ decoder_layers=self.decoder_layers,
424
+ decoder_ffn_dim=self.decoder_ffn_dim,
425
+ encoder_attention_heads=self.encoder_attention_heads,
426
+ decoder_attention_heads=self.decoder_attention_heads,
427
+ eos_token_id=self.eos_token_id,
428
+ bos_token_id=self.bos_token_id,
429
+ use_cache=self.use_cache,
430
+ pad_token_id=self.pad_token_id,
431
+ decoder_start_token_id=self.decoder_start_token_id,
432
+ max_position_embeddings=self.max_position_embeddings,
433
+ is_encoder_decoder=self.is_encoder_decoder,
434
+ )
435
+
436
+ return (
437
+ config,
438
+ input_ids,
439
+ attention_mask,
440
+ lm_labels,
441
+ )
442
+
443
+ def create_and_check_decoder_model_past(
444
+ self,
445
+ config,
446
+ input_ids,
447
+ attention_mask,
448
+ lm_labels,
449
+ ):
450
+ config.use_cache = True
451
+ model = BlenderbotSmallDecoder(config=config).to(torch_device).eval()
452
+ # first forward pass
453
+ outputs = model(input_ids, use_cache=True)
454
+ outputs_use_cache_conf = model(input_ids)
455
+ outputs_no_past = model(input_ids, use_cache=False)
456
+
457
+ self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))
458
+ self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)
459
+
460
+ past_key_values = outputs["past_key_values"]
461
+
462
+ # create hypothetical next token and extent to next_input_ids
463
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
464
+
465
+ # append to next input_ids and
466
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
467
+
468
+ output_from_no_past = model(next_input_ids)["last_hidden_state"]
469
+ output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"]
470
+
471
+ # select random slice
472
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
473
+ output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
474
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
475
+
476
+ # test that outputs are equal for slice
477
+ assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)
478
+
479
+ def create_and_check_decoder_model_attention_mask_past(
480
+ self,
481
+ config,
482
+ input_ids,
483
+ attention_mask,
484
+ lm_labels,
485
+ ):
486
+ model = BlenderbotSmallDecoder(config=config).to(torch_device).eval()
487
+
488
+ # create attention mask
489
+ attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
490
+
491
+ half_seq_length = input_ids.shape[-1] // 2
492
+ attn_mask[:, half_seq_length:] = 0
493
+
494
+ # first forward pass
495
+ past_key_values = model(input_ids, attention_mask=attn_mask, use_cache=True)["past_key_values"]
496
+
497
+ # create hypothetical next token and extent to next_input_ids
498
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
499
+
500
+ # change a random masked slice from input_ids
501
+ random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1
502
+ random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1)
503
+ input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens
504
+
505
+ # append to next input_ids and attn_mask
506
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
507
+ attn_mask = torch.cat(
508
+ [attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)],
509
+ dim=1,
510
+ )
511
+
512
+ # get two different outputs
513
+ output_from_no_past = model(next_input_ids, attention_mask=attn_mask)["last_hidden_state"]
514
+ output_from_past = model(next_tokens, past_key_values=past_key_values, attention_mask=attn_mask)[
515
+ "last_hidden_state"
516
+ ]
517
+
518
+ # select random slice
519
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
520
+ output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
521
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
522
+
523
+ # test that outputs are equal for slice
524
+ assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)
525
+
526
+ def prepare_config_and_inputs_for_common(self):
527
+ config_and_inputs = self.prepare_config_and_inputs()
528
+ (
529
+ config,
530
+ input_ids,
531
+ attention_mask,
532
+ lm_labels,
533
+ ) = config_and_inputs
534
+
535
+ inputs_dict = {
536
+ "input_ids": input_ids,
537
+ "attention_mask": attention_mask,
538
+ }
539
+ return config, inputs_dict
540
+
541
+
542
+ @require_torch
543
+ class BlenderbotSmallStandaloneDecoderModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
544
+ all_model_classes = (BlenderbotSmallDecoder, BlenderbotSmallForCausalLM) if is_torch_available() else ()
545
+ all_generative_model_classes = (BlenderbotSmallForCausalLM,) if is_torch_available() else ()
546
+ test_pruning = False
547
+ is_encoder_decoder = False
548
+
549
+ def setUp(
550
+ self,
551
+ ):
552
+ self.model_tester = BlenderbotSmallStandaloneDecoderModelTester(self, is_training=False)
553
+ self.config_tester = ConfigTester(self, config_class=BlenderbotSmallConfig)
554
+
555
+ def test_config(self):
556
+ self.config_tester.run_common_tests()
557
+
558
+ def test_decoder_model_past(self):
559
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
560
+ self.model_tester.create_and_check_decoder_model_past(*config_and_inputs)
561
+
562
+ def test_decoder_model_attn_mask_past(self):
563
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
564
+ self.model_tester.create_and_check_decoder_model_attention_mask_past(*config_and_inputs)
565
+
566
+ @unittest.skip(reason="decoder cannot keep gradients")
567
+ def test_retain_grad_hidden_states_attentions(self):
568
+ return
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blenderbot_small/test_modeling_flax_blenderbot_small.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2021 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import unittest
16
+
17
+ import numpy as np
18
+ import timeout_decorator # noqa
19
+
20
+ from transformers import BlenderbotSmallConfig, is_flax_available
21
+ from transformers.testing_utils import require_flax, slow
22
+
23
+ from ...generation.test_flax_utils import FlaxGenerationTesterMixin
24
+ from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor
25
+
26
+
27
+ if is_flax_available():
28
+ import os
29
+
30
+ # The slow tests are often failing with OOM error on GPU
31
+ # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
32
+ # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
33
+ os.environ["XLA_PYTHON_CLIENT_ALLOCATOR"] = "platform"
34
+
35
+ import jax
36
+ import jax.numpy as jnp
37
+
38
+ from transformers.models.blenderbot_small.modeling_flax_blenderbot_small import (
39
+ FlaxBlenderbotSmallForConditionalGeneration,
40
+ FlaxBlenderbotSmallModel,
41
+ shift_tokens_right,
42
+ )
43
+
44
+
45
+ def prepare_blenderbot_inputs_dict(
46
+ config,
47
+ input_ids,
48
+ decoder_input_ids=None,
49
+ attention_mask=None,
50
+ decoder_attention_mask=None,
51
+ head_mask=None,
52
+ decoder_head_mask=None,
53
+ cross_attn_head_mask=None,
54
+ ):
55
+ if attention_mask is None:
56
+ attention_mask = np.where(input_ids != config.pad_token_id, 1, 0)
57
+ if decoder_attention_mask is None:
58
+ decoder_attention_mask = np.where(decoder_input_ids != config.pad_token_id, 1, 0)
59
+ if head_mask is None:
60
+ head_mask = np.ones((config.encoder_layers, config.encoder_attention_heads))
61
+ if decoder_head_mask is None:
62
+ decoder_head_mask = np.ones((config.decoder_layers, config.decoder_attention_heads))
63
+ if cross_attn_head_mask is None:
64
+ cross_attn_head_mask = np.ones((config.decoder_layers, config.decoder_attention_heads))
65
+ return {
66
+ "input_ids": input_ids,
67
+ "decoder_input_ids": decoder_input_ids,
68
+ "attention_mask": attention_mask,
69
+ "decoder_attention_mask": attention_mask,
70
+ }
71
+
72
+
73
+ class FlaxBlenderbotSmallModelTester:
74
+ def __init__(
75
+ self,
76
+ parent,
77
+ batch_size=13,
78
+ seq_length=7,
79
+ is_training=True,
80
+ use_labels=False,
81
+ vocab_size=99,
82
+ hidden_size=16,
83
+ num_hidden_layers=2,
84
+ num_attention_heads=4,
85
+ intermediate_size=4,
86
+ hidden_act="gelu",
87
+ hidden_dropout_prob=0.1,
88
+ attention_probs_dropout_prob=0.1,
89
+ max_position_embeddings=50,
90
+ eos_token_id=2,
91
+ pad_token_id=1,
92
+ bos_token_id=0,
93
+ initializer_range=0.02,
94
+ ):
95
+ self.parent = parent
96
+ self.batch_size = batch_size
97
+ self.seq_length = seq_length
98
+ self.is_training = is_training
99
+ self.use_labels = use_labels
100
+ self.vocab_size = vocab_size
101
+ self.hidden_size = hidden_size
102
+ self.num_hidden_layers = num_hidden_layers
103
+ self.num_attention_heads = num_attention_heads
104
+ self.intermediate_size = intermediate_size
105
+ self.hidden_act = hidden_act
106
+ self.hidden_dropout_prob = hidden_dropout_prob
107
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
108
+ self.max_position_embeddings = max_position_embeddings
109
+ self.eos_token_id = eos_token_id
110
+ self.pad_token_id = pad_token_id
111
+ self.bos_token_id = bos_token_id
112
+ self.initializer_range = initializer_range
113
+
114
+ def prepare_config_and_inputs(self):
115
+ input_ids = np.clip(ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size), 3, self.vocab_size)
116
+ input_ids = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1), dtype=np.int64)), -1)
117
+
118
+ decoder_input_ids = shift_tokens_right(input_ids, 1, 2)
119
+
120
+ config = BlenderbotSmallConfig(
121
+ vocab_size=self.vocab_size,
122
+ d_model=self.hidden_size,
123
+ encoder_layers=self.num_hidden_layers,
124
+ decoder_layers=self.num_hidden_layers,
125
+ encoder_attention_heads=self.num_attention_heads,
126
+ decoder_attention_heads=self.num_attention_heads,
127
+ encoder_ffn_dim=self.intermediate_size,
128
+ decoder_ffn_dim=self.intermediate_size,
129
+ dropout=self.hidden_dropout_prob,
130
+ attention_dropout=self.attention_probs_dropout_prob,
131
+ max_position_embeddings=self.max_position_embeddings,
132
+ eos_token_id=self.eos_token_id,
133
+ bos_token_id=self.bos_token_id,
134
+ pad_token_id=self.pad_token_id,
135
+ initializer_range=self.initializer_range,
136
+ use_cache=False,
137
+ )
138
+ inputs_dict = prepare_blenderbot_inputs_dict(config, input_ids, decoder_input_ids)
139
+ return config, inputs_dict
140
+
141
+ def prepare_config_and_inputs_for_common(self):
142
+ config, inputs_dict = self.prepare_config_and_inputs()
143
+ return config, inputs_dict
144
+
145
+ def check_use_cache_forward(self, model_class_name, config, inputs_dict):
146
+ max_decoder_length = 20
147
+ model = model_class_name(config)
148
+
149
+ encoder_outputs = model.encode(inputs_dict["input_ids"])
150
+
151
+ decoder_input_ids, decoder_attention_mask = (
152
+ inputs_dict["decoder_input_ids"],
153
+ inputs_dict["decoder_attention_mask"],
154
+ )
155
+
156
+ past_key_values = model.init_cache(decoder_input_ids.shape[0], max_decoder_length, encoder_outputs)
157
+ decoder_attention_mask = jnp.ones((decoder_input_ids.shape[0], max_decoder_length), dtype="i4")
158
+
159
+ decoder_position_ids = jnp.broadcast_to(
160
+ jnp.arange(decoder_input_ids.shape[-1] - 1)[None, :],
161
+ (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1),
162
+ )
163
+ outputs_cache = model.decode(
164
+ decoder_input_ids[:, :-1],
165
+ encoder_outputs,
166
+ decoder_attention_mask=decoder_attention_mask,
167
+ past_key_values=past_key_values,
168
+ decoder_position_ids=decoder_position_ids,
169
+ )
170
+
171
+ decoder_position_ids = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]], dtype="i4")
172
+ outputs_cache_next = model.decode(
173
+ decoder_input_ids[:, -1:],
174
+ encoder_outputs,
175
+ decoder_attention_mask=decoder_attention_mask,
176
+ past_key_values=outputs_cache.past_key_values,
177
+ decoder_position_ids=decoder_position_ids,
178
+ )
179
+
180
+ outputs = model.decode(decoder_input_ids, encoder_outputs)
181
+
182
+ diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
183
+ self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}")
184
+
185
+ def check_use_cache_forward_with_attn_mask(self, model_class_name, config, inputs_dict):
186
+ max_decoder_length = 20
187
+ model = model_class_name(config)
188
+
189
+ encoder_outputs = model.encode(inputs_dict["input_ids"])
190
+
191
+ decoder_input_ids, decoder_attention_mask = (
192
+ inputs_dict["decoder_input_ids"],
193
+ inputs_dict["decoder_attention_mask"],
194
+ )
195
+
196
+ decoder_attention_mask_cache = jnp.concatenate(
197
+ [
198
+ decoder_attention_mask,
199
+ jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])),
200
+ ],
201
+ axis=-1,
202
+ )
203
+
204
+ past_key_values = model.init_cache(decoder_input_ids.shape[0], max_decoder_length, encoder_outputs)
205
+ decoder_position_ids = jnp.broadcast_to(
206
+ jnp.arange(decoder_input_ids.shape[-1] - 1)[None, :],
207
+ (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1),
208
+ )
209
+
210
+ outputs_cache = model.decode(
211
+ decoder_input_ids[:, :-1],
212
+ encoder_outputs,
213
+ decoder_attention_mask=decoder_attention_mask_cache,
214
+ past_key_values=past_key_values,
215
+ decoder_position_ids=decoder_position_ids,
216
+ )
217
+ decoder_position_ids = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]], dtype="i4")
218
+ outputs_cache_next = model.decode(
219
+ decoder_input_ids[:, -1:],
220
+ encoder_outputs,
221
+ past_key_values=outputs_cache.past_key_values,
222
+ decoder_attention_mask=decoder_attention_mask_cache,
223
+ decoder_position_ids=decoder_position_ids,
224
+ )
225
+
226
+ outputs = model.decode(decoder_input_ids, encoder_outputs, decoder_attention_mask=decoder_attention_mask)
227
+
228
+ diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
229
+ self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}")
230
+
231
+
232
+ @require_flax
233
+ class BlenderbotHeadTests(unittest.TestCase):
234
+ vocab_size = 99
235
+
236
+ def _get_config_and_data(self):
237
+ input_ids = np.array(
238
+ [
239
+ [71, 82, 18, 33, 46, 91, 2],
240
+ [68, 34, 26, 58, 30, 82, 2],
241
+ [5, 97, 17, 39, 94, 40, 2],
242
+ [76, 83, 94, 25, 70, 78, 2],
243
+ [87, 59, 41, 35, 48, 66, 2],
244
+ [55, 13, 16, 58, 5, 2, 1], # note padding
245
+ [64, 27, 31, 51, 12, 75, 2],
246
+ [52, 64, 86, 17, 83, 39, 2],
247
+ [48, 61, 9, 24, 71, 82, 2],
248
+ [26, 1, 60, 48, 22, 13, 2],
249
+ [21, 5, 62, 28, 14, 76, 2],
250
+ [45, 98, 37, 86, 59, 48, 2],
251
+ [70, 70, 50, 9, 28, 0, 2],
252
+ ],
253
+ dtype=np.int64,
254
+ )
255
+
256
+ batch_size = input_ids.shape[0]
257
+ config = BlenderbotSmallConfig(
258
+ vocab_size=self.vocab_size,
259
+ d_model=24,
260
+ encoder_layers=2,
261
+ decoder_layers=2,
262
+ encoder_attention_heads=2,
263
+ decoder_attention_heads=2,
264
+ encoder_ffn_dim=32,
265
+ decoder_ffn_dim=32,
266
+ max_position_embeddings=48,
267
+ eos_token_id=2,
268
+ pad_token_id=1,
269
+ bos_token_id=0,
270
+ )
271
+ return config, input_ids, batch_size
272
+
273
+ # @timeout_decorator.timeout(1) # not working with the decorator so far
274
+ def test_lm_forward(self):
275
+ config, input_ids, batch_size = self._get_config_and_data()
276
+ lm_model = FlaxBlenderbotSmallForConditionalGeneration(config)
277
+ outputs = lm_model(input_ids=input_ids)
278
+ expected_shape = (batch_size, input_ids.shape[1], config.vocab_size)
279
+ self.assertEqual(outputs["logits"].shape, expected_shape)
280
+
281
+ def test_lm_uneven_forward(self):
282
+ config = BlenderbotSmallConfig(
283
+ vocab_size=self.vocab_size,
284
+ d_model=14,
285
+ encoder_layers=2,
286
+ decoder_layers=2,
287
+ encoder_attention_heads=2,
288
+ decoder_attention_heads=2,
289
+ encoder_ffn_dim=8,
290
+ decoder_ffn_dim=8,
291
+ max_position_embeddings=48,
292
+ )
293
+ lm_model = FlaxBlenderbotSmallForConditionalGeneration(config)
294
+ context = np.array([[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]], dtype=np.int64)
295
+ summary = np.array([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]], dtype=np.int64)
296
+ outputs = lm_model(input_ids=context, decoder_input_ids=summary)
297
+ expected_shape = (*summary.shape, config.vocab_size)
298
+ self.assertEqual(outputs["logits"].shape, expected_shape)
299
+
300
+ def test_shift_tokens_right(self):
301
+ input_ids = np.array([[71, 82, 18, 33, 2, 1, 1], [68, 34, 26, 58, 30, 82, 2]], dtype=np.int64)
302
+ shifted = shift_tokens_right(input_ids, 1, 2)
303
+ n_pad_before = np.equal(input_ids, 1).astype(np.float32).sum()
304
+ n_pad_after = np.equal(shifted, 1).astype(np.float32).sum()
305
+ self.assertEqual(shifted.shape, input_ids.shape)
306
+ self.assertEqual(n_pad_after, n_pad_before - 1)
307
+ self.assertTrue(np.equal(shifted[:, 0], 2).all())
308
+
309
+
310
+ @require_flax
311
+ class FlaxBlenderbotSmallModelTest(FlaxModelTesterMixin, unittest.TestCase, FlaxGenerationTesterMixin):
312
+ is_encoder_decoder = True
313
+ all_model_classes = (
314
+ (
315
+ FlaxBlenderbotSmallModel,
316
+ FlaxBlenderbotSmallForConditionalGeneration,
317
+ )
318
+ if is_flax_available()
319
+ else ()
320
+ )
321
+ all_generative_model_classes = (FlaxBlenderbotSmallForConditionalGeneration,) if is_flax_available() else ()
322
+
323
+ def is_pipeline_test_to_skip(
324
+ self,
325
+ pipeline_test_case_name,
326
+ config_class,
327
+ model_architecture,
328
+ tokenizer_name,
329
+ image_processor_name,
330
+ feature_extractor_name,
331
+ processor_name,
332
+ ):
333
+ return pipeline_test_case_name == "TextGenerationPipelineTests"
334
+
335
+ def setUp(self):
336
+ self.model_tester = FlaxBlenderbotSmallModelTester(self)
337
+
338
+ def test_use_cache_forward(self):
339
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
340
+ for model_class in self.all_model_classes:
341
+ self.model_tester.check_use_cache_forward(model_class, config, inputs_dict)
342
+
343
+ def test_use_cache_forward_with_attn_mask(self):
344
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
345
+ for model_class in self.all_model_classes:
346
+ self.model_tester.check_use_cache_forward_with_attn_mask(model_class, config, inputs_dict)
347
+
348
+ def test_encode(self):
349
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
350
+
351
+ for model_class in self.all_model_classes:
352
+ with self.subTest(model_class.__name__):
353
+ prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class)
354
+ model = model_class(config)
355
+
356
+ @jax.jit
357
+ def encode_jitted(input_ids, attention_mask=None, **kwargs):
358
+ return model.encode(input_ids=input_ids, attention_mask=attention_mask)
359
+
360
+ with self.subTest("JIT Enabled"):
361
+ jitted_outputs = encode_jitted(**prepared_inputs_dict).to_tuple()
362
+
363
+ with self.subTest("JIT Disabled"):
364
+ with jax.disable_jit():
365
+ outputs = encode_jitted(**prepared_inputs_dict).to_tuple()
366
+
367
+ self.assertEqual(len(outputs), len(jitted_outputs))
368
+ for jitted_output, output in zip(jitted_outputs, outputs):
369
+ self.assertEqual(jitted_output.shape, output.shape)
370
+
371
+ def test_decode(self):
372
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
373
+
374
+ for model_class in self.all_model_classes:
375
+ with self.subTest(model_class.__name__):
376
+ model = model_class(config)
377
+ encoder_outputs = model.encode(inputs_dict["input_ids"], inputs_dict["attention_mask"])
378
+
379
+ prepared_inputs_dict = {
380
+ "decoder_input_ids": inputs_dict["decoder_input_ids"],
381
+ "decoder_attention_mask": inputs_dict["decoder_attention_mask"],
382
+ "encoder_outputs": encoder_outputs,
383
+ }
384
+
385
+ @jax.jit
386
+ def decode_jitted(decoder_input_ids, decoder_attention_mask, encoder_outputs):
387
+ return model.decode(
388
+ decoder_input_ids=decoder_input_ids,
389
+ decoder_attention_mask=decoder_attention_mask,
390
+ encoder_outputs=encoder_outputs,
391
+ )
392
+
393
+ with self.subTest("JIT Enabled"):
394
+ jitted_outputs = decode_jitted(**prepared_inputs_dict).to_tuple()
395
+
396
+ with self.subTest("JIT Disabled"):
397
+ with jax.disable_jit():
398
+ outputs = decode_jitted(**prepared_inputs_dict).to_tuple()
399
+
400
+ self.assertEqual(len(outputs), len(jitted_outputs))
401
+ for jitted_output, output in zip(jitted_outputs, outputs):
402
+ self.assertEqual(jitted_output.shape, output.shape)
403
+
404
+ @slow
405
+ def test_model_from_pretrained(self):
406
+ for model_class_name in self.all_model_classes:
407
+ model = model_class_name.from_pretrained("facebook/blenderbot_small-90M")
408
+ # FlaxBlenderbotForSequenceClassification expects eos token in input_ids
409
+ input_ids = np.ones((1, 1)) * model.config.eos_token_id
410
+ outputs = model(input_ids)
411
+ self.assertIsNotNone(outputs)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blenderbot_small/test_modeling_tf_blenderbot_small.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+
17
+ from __future__ import annotations
18
+
19
+ import unittest
20
+
21
+ from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available
22
+ from transformers.testing_utils import require_tf, require_tokenizers, slow
23
+ from transformers.utils import cached_property
24
+
25
+ from ...test_configuration_common import ConfigTester
26
+ from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
27
+ from ...test_pipeline_mixin import PipelineTesterMixin
28
+
29
+
30
+ if is_tf_available():
31
+ import tensorflow as tf
32
+
33
+ from transformers import TFAutoModelForSeq2SeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel
34
+
35
+
36
+ @require_tf
37
+ class TFBlenderbotSmallModelTester:
38
+ config_cls = BlenderbotSmallConfig
39
+ config_updates = {}
40
+ hidden_act = "gelu"
41
+
42
+ def __init__(
43
+ self,
44
+ parent,
45
+ batch_size=13,
46
+ seq_length=7,
47
+ is_training=True,
48
+ use_labels=False,
49
+ vocab_size=99,
50
+ hidden_size=32,
51
+ num_hidden_layers=2,
52
+ num_attention_heads=4,
53
+ intermediate_size=37,
54
+ hidden_dropout_prob=0.1,
55
+ attention_probs_dropout_prob=0.1,
56
+ max_position_embeddings=50,
57
+ eos_token_id=2,
58
+ pad_token_id=1,
59
+ bos_token_id=0,
60
+ ):
61
+ self.parent = parent
62
+ self.batch_size = batch_size
63
+ self.seq_length = seq_length
64
+ self.is_training = is_training
65
+ self.use_labels = use_labels
66
+ self.vocab_size = vocab_size
67
+ self.hidden_size = hidden_size
68
+ self.num_hidden_layers = num_hidden_layers
69
+ self.num_attention_heads = num_attention_heads
70
+ self.intermediate_size = intermediate_size
71
+
72
+ self.hidden_dropout_prob = hidden_dropout_prob
73
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
74
+ self.max_position_embeddings = max_position_embeddings
75
+ self.eos_token_id = eos_token_id
76
+ self.pad_token_id = pad_token_id
77
+ self.bos_token_id = bos_token_id
78
+
79
+ def prepare_config_and_inputs_for_common(self):
80
+ input_ids = ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size)
81
+ eos_tensor = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size), 1)
82
+ input_ids = tf.concat([input_ids, eos_tensor], axis=1)
83
+
84
+ decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
85
+
86
+ config = self.config_cls(
87
+ vocab_size=self.vocab_size,
88
+ d_model=self.hidden_size,
89
+ encoder_layers=self.num_hidden_layers,
90
+ decoder_layers=self.num_hidden_layers,
91
+ encoder_attention_heads=self.num_attention_heads,
92
+ decoder_attention_heads=self.num_attention_heads,
93
+ encoder_ffn_dim=self.intermediate_size,
94
+ decoder_ffn_dim=self.intermediate_size,
95
+ dropout=self.hidden_dropout_prob,
96
+ attention_dropout=self.attention_probs_dropout_prob,
97
+ max_position_embeddings=self.max_position_embeddings,
98
+ eos_token_ids=[2],
99
+ bos_token_id=self.bos_token_id,
100
+ pad_token_id=self.pad_token_id,
101
+ decoder_start_token_id=self.pad_token_id,
102
+ **self.config_updates,
103
+ )
104
+ inputs_dict = prepare_blenderbot_small_inputs_dict(config, input_ids, decoder_input_ids)
105
+ return config, inputs_dict
106
+
107
+ def check_decoder_model_past_large_inputs(self, config, inputs_dict):
108
+ model = TFBlenderbotSmallModel(config=config).get_decoder()
109
+ input_ids = inputs_dict["input_ids"]
110
+
111
+ input_ids = input_ids[:1, :]
112
+ attention_mask = inputs_dict["attention_mask"][:1, :]
113
+ head_mask = inputs_dict["head_mask"]
114
+ self.batch_size = 1
115
+
116
+ # first forward pass
117
+ outputs = model(input_ids, attention_mask=attention_mask, head_mask=head_mask, use_cache=True)
118
+
119
+ output, past_key_values = outputs.to_tuple()
120
+
121
+ # create hypothetical next token and extent to next_input_ids
122
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
123
+ next_attn_mask = tf.cast(ids_tensor((self.batch_size, 3), 2), tf.int8)
124
+
125
+ # append to next input_ids and
126
+ next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
127
+ next_attention_mask = tf.concat([attention_mask, next_attn_mask], axis=-1)
128
+
129
+ output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)[0]
130
+ output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[0]
131
+
132
+ self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1])
133
+
134
+ # select random slice
135
+ random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1]))
136
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx]
137
+ output_from_past_slice = output_from_past[:, :, random_slice_idx]
138
+
139
+ # test that outputs are equal for slice
140
+ tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3)
141
+
142
+
143
+ def prepare_blenderbot_small_inputs_dict(
144
+ config,
145
+ input_ids,
146
+ decoder_input_ids,
147
+ attention_mask=None,
148
+ decoder_attention_mask=None,
149
+ head_mask=None,
150
+ decoder_head_mask=None,
151
+ cross_attn_head_mask=None,
152
+ ):
153
+ if attention_mask is None:
154
+ attention_mask = tf.cast(tf.math.not_equal(input_ids, config.pad_token_id), tf.int8)
155
+ if decoder_attention_mask is None:
156
+ decoder_attention_mask = tf.concat(
157
+ [
158
+ tf.ones(decoder_input_ids[:, :1].shape, dtype=tf.int8),
159
+ tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:], config.pad_token_id), tf.int8),
160
+ ],
161
+ axis=-1,
162
+ )
163
+ if head_mask is None:
164
+ head_mask = tf.ones((config.encoder_layers, config.encoder_attention_heads))
165
+ if decoder_head_mask is None:
166
+ decoder_head_mask = tf.ones((config.decoder_layers, config.decoder_attention_heads))
167
+ if cross_attn_head_mask is None:
168
+ cross_attn_head_mask = tf.ones((config.decoder_layers, config.decoder_attention_heads))
169
+ return {
170
+ "input_ids": input_ids,
171
+ "decoder_input_ids": decoder_input_ids,
172
+ "attention_mask": attention_mask,
173
+ "decoder_attention_mask": decoder_attention_mask,
174
+ "head_mask": head_mask,
175
+ "decoder_head_mask": decoder_head_mask,
176
+ "cross_attn_head_mask": cross_attn_head_mask,
177
+ }
178
+
179
+
180
+ @require_tf
181
+ class TFBlenderbotSmallModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
182
+ all_model_classes = (
183
+ (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else ()
184
+ )
185
+ all_generative_model_classes = (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else ()
186
+ pipeline_model_mapping = (
187
+ {
188
+ "feature-extraction": TFBlenderbotSmallModel,
189
+ "summarization": TFBlenderbotSmallForConditionalGeneration,
190
+ "text2text-generation": TFBlenderbotSmallForConditionalGeneration,
191
+ "translation": TFBlenderbotSmallForConditionalGeneration,
192
+ }
193
+ if is_tf_available()
194
+ else {}
195
+ )
196
+ is_encoder_decoder = True
197
+ test_pruning = False
198
+ test_onnx = False
199
+
200
+ def is_pipeline_test_to_skip(
201
+ self,
202
+ pipeline_test_case_name,
203
+ config_class,
204
+ model_architecture,
205
+ tokenizer_name,
206
+ image_processor_name,
207
+ feature_extractor_name,
208
+ processor_name,
209
+ ):
210
+ return pipeline_test_case_name == "TextGenerationPipelineTests"
211
+
212
+ def setUp(self):
213
+ self.model_tester = TFBlenderbotSmallModelTester(self)
214
+ self.config_tester = ConfigTester(self, config_class=BlenderbotSmallConfig)
215
+
216
+ def test_config(self):
217
+ self.config_tester.run_common_tests()
218
+
219
+ def test_decoder_model_past_large_inputs(self):
220
+ config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common()
221
+ self.model_tester.check_decoder_model_past_large_inputs(*config_and_inputs)
222
+
223
+
224
+ @require_tokenizers
225
+ @require_tf
226
+ class TFBlenderbot90MIntegrationTests(unittest.TestCase):
227
+ src_text = [
228
+ "Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like "
229
+ " i'm going to throw up.\nand why is that?"
230
+ ]
231
+ model_name = "facebook/blenderbot_small-90M"
232
+
233
+ @cached_property
234
+ def tokenizer(self):
235
+ # use "old" tokenizer here because of bug when downloading new tokenizer
236
+ return BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M")
237
+
238
+ @cached_property
239
+ def model(self):
240
+ model = TFAutoModelForSeq2SeqLM.from_pretrained(self.model_name)
241
+ return model
242
+
243
+ @slow
244
+ def test_90_generation_from_long_input(self):
245
+ model_inputs = self.tokenizer(self.src_text, return_tensors="tf")
246
+ generated_ids = self.model.generate(
247
+ model_inputs.input_ids,
248
+ attention_mask=model_inputs.attention_mask,
249
+ num_beams=2,
250
+ use_cache=True,
251
+ )
252
+ generated_words = self.tokenizer.batch_decode(generated_ids.numpy(), skip_special_tokens=True)[0]
253
+ assert generated_words in (
254
+ "i don't know. i just feel like i'm going to throw up. it's not fun.",
255
+ "i'm not sure. i just feel like i've been feeling like i have to be in a certain place",
256
+ "i'm not sure. i just feel like i've been in a bad situation.",
257
+ )
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blenderbot_small/test_tokenization_blenderbot_small.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # coding=utf-8
3
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """Tests for the Blenderbot small tokenizer."""
17
+
18
+ import json
19
+ import os
20
+ import unittest
21
+
22
+ from transformers.models.blenderbot_small.tokenization_blenderbot_small import (
23
+ VOCAB_FILES_NAMES,
24
+ BlenderbotSmallTokenizer,
25
+ )
26
+
27
+ from ...test_tokenization_common import TokenizerTesterMixin
28
+
29
+
30
+ class BlenderbotSmallTokenizerTest(TokenizerTesterMixin, unittest.TestCase):
31
+ from_pretrained_id = "facebook/blenderbot_small-90M"
32
+ tokenizer_class = BlenderbotSmallTokenizer
33
+ test_rust_tokenizer = False
34
+
35
+ def setUp(self):
36
+ super().setUp()
37
+
38
+ vocab = ["__start__", "adapt", "act", "ap@@", "te", "__end__", "__unk__"]
39
+ vocab_tokens = dict(zip(vocab, range(len(vocab))))
40
+
41
+ merges = ["#version: 0.2", "a p", "t e</w>", "ap t</w>", "a d", "ad apt</w>", "a c", "ac t</w>", ""]
42
+ self.special_tokens_map = {"unk_token": "__unk__", "bos_token": "__start__", "eos_token": "__end__"}
43
+
44
+ self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"])
45
+ self.merges_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["merges_file"])
46
+ with open(self.vocab_file, "w", encoding="utf-8") as fp:
47
+ fp.write(json.dumps(vocab_tokens) + "\n")
48
+ with open(self.merges_file, "w", encoding="utf-8") as fp:
49
+ fp.write("\n".join(merges))
50
+
51
+ def get_tokenizer(self, **kwargs):
52
+ kwargs.update(self.special_tokens_map)
53
+ return BlenderbotSmallTokenizer.from_pretrained(self.tmpdirname, **kwargs)
54
+
55
+ def get_input_output_texts(self, tokenizer):
56
+ input_text = "adapt act apte"
57
+ output_text = "adapt act apte"
58
+ return input_text, output_text
59
+
60
+ def test_full_blenderbot_small_tokenizer(self):
61
+ tokenizer = BlenderbotSmallTokenizer(self.vocab_file, self.merges_file, **self.special_tokens_map)
62
+ text = "adapt act apte"
63
+ bpe_tokens = ["adapt", "act", "ap@@", "te"]
64
+ tokens = tokenizer.tokenize(text)
65
+ self.assertListEqual(tokens, bpe_tokens)
66
+
67
+ input_tokens = [tokenizer.bos_token] + tokens + [tokenizer.eos_token]
68
+
69
+ input_bpe_tokens = [0, 1, 2, 3, 4, 5]
70
+ self.assertListEqual(tokenizer.convert_tokens_to_ids(input_tokens), input_bpe_tokens)
71
+
72
+ def test_special_tokens_small_tok(self):
73
+ tok = BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M")
74
+ assert tok("sam").input_ids == [1384]
75
+ src_text = "I am a small frog."
76
+ encoded = tok([src_text], padding=False, truncation=False)["input_ids"]
77
+ decoded = tok.batch_decode(encoded, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
78
+ assert src_text != decoded # I wish it did!
79
+ assert decoded == "i am a small frog ."
80
+
81
+ def test_empty_word_small_tok(self):
82
+ tok = BlenderbotSmallTokenizer.from_pretrained("facebook/blenderbot-90M")
83
+ src_text = "I am a small frog ."
84
+ src_text_dot = "."
85
+ encoded = tok(src_text)["input_ids"]
86
+ encoded_dot = tok(src_text_dot)["input_ids"]
87
+
88
+ assert encoded[-1] == encoded_dot[0]
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blip/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blip/test_image_processing_blip.py ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 HuggingFace Inc.
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
+
17
+ import unittest
18
+
19
+ from transformers.testing_utils import require_torch, require_vision
20
+ from transformers.utils import is_vision_available
21
+
22
+ from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs
23
+
24
+
25
+ if is_vision_available():
26
+ from transformers import BlipImageProcessor
27
+
28
+
29
+ class BlipImageProcessingTester(unittest.TestCase):
30
+ def __init__(
31
+ self,
32
+ parent,
33
+ batch_size=7,
34
+ num_channels=3,
35
+ image_size=18,
36
+ min_resolution=30,
37
+ max_resolution=400,
38
+ do_resize=True,
39
+ size=None,
40
+ do_normalize=True,
41
+ do_pad=False,
42
+ image_mean=[0.48145466, 0.4578275, 0.40821073],
43
+ image_std=[0.26862954, 0.26130258, 0.27577711],
44
+ do_convert_rgb=True,
45
+ ):
46
+ super().__init__()
47
+ size = size if size is not None else {"height": 20, "width": 20}
48
+ self.parent = parent
49
+ self.batch_size = batch_size
50
+ self.num_channels = num_channels
51
+ self.image_size = image_size
52
+ self.min_resolution = min_resolution
53
+ self.max_resolution = max_resolution
54
+ self.do_resize = do_resize
55
+ self.size = size
56
+ self.do_normalize = do_normalize
57
+ self.image_mean = image_mean
58
+ self.image_std = image_std
59
+ self.do_pad = do_pad
60
+ self.do_convert_rgb = do_convert_rgb
61
+
62
+ def prepare_image_processor_dict(self):
63
+ return {
64
+ "do_resize": self.do_resize,
65
+ "size": self.size,
66
+ "do_normalize": self.do_normalize,
67
+ "image_mean": self.image_mean,
68
+ "image_std": self.image_std,
69
+ "do_convert_rgb": self.do_convert_rgb,
70
+ "do_pad": self.do_pad,
71
+ }
72
+
73
+ def expected_output_image_shape(self, images):
74
+ return self.num_channels, self.size["height"], self.size["width"]
75
+
76
+ def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
77
+ return prepare_image_inputs(
78
+ batch_size=self.batch_size,
79
+ num_channels=self.num_channels,
80
+ min_resolution=self.min_resolution,
81
+ max_resolution=self.max_resolution,
82
+ equal_resolution=equal_resolution,
83
+ numpify=numpify,
84
+ torchify=torchify,
85
+ )
86
+
87
+
88
+ @require_torch
89
+ @require_vision
90
+ class BlipImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
91
+ image_processing_class = BlipImageProcessor if is_vision_available() else None
92
+
93
+ def setUp(self):
94
+ super().setUp()
95
+ self.image_processor_tester = BlipImageProcessingTester(self)
96
+
97
+ @property
98
+ def image_processor_dict(self):
99
+ return self.image_processor_tester.prepare_image_processor_dict()
100
+
101
+ def test_image_processor_properties(self):
102
+ image_processor = self.image_processing_class(**self.image_processor_dict)
103
+ self.assertTrue(hasattr(image_processor, "do_resize"))
104
+ self.assertTrue(hasattr(image_processor, "size"))
105
+ self.assertTrue(hasattr(image_processor, "do_normalize"))
106
+ self.assertTrue(hasattr(image_processor, "image_mean"))
107
+ self.assertTrue(hasattr(image_processor, "image_std"))
108
+ self.assertTrue(hasattr(image_processor, "do_convert_rgb"))
109
+
110
+
111
+ @require_torch
112
+ @require_vision
113
+ class BlipImageProcessingTestFourChannels(ImageProcessingTestMixin, unittest.TestCase):
114
+ image_processing_class = BlipImageProcessor if is_vision_available() else None
115
+
116
+ def setUp(self):
117
+ super().setUp()
118
+ self.image_processor_tester = BlipImageProcessingTester(self, num_channels=4)
119
+ self.expected_encoded_image_num_channels = 3
120
+
121
+ @property
122
+ def image_processor_dict(self):
123
+ return self.image_processor_tester.prepare_image_processor_dict()
124
+
125
+ def test_image_processor_properties(self):
126
+ image_processor = self.image_processing_class(**self.image_processor_dict)
127
+ self.assertTrue(hasattr(image_processor, "do_resize"))
128
+ self.assertTrue(hasattr(image_processor, "size"))
129
+ self.assertTrue(hasattr(image_processor, "do_normalize"))
130
+ self.assertTrue(hasattr(image_processor, "image_mean"))
131
+ self.assertTrue(hasattr(image_processor, "image_std"))
132
+ self.assertTrue(hasattr(image_processor, "do_convert_rgb"))
133
+
134
+ @unittest.skip(reason="BlipImageProcessor does not support 4 channels yet") # FIXME Amy
135
+ def test_call_numpy(self):
136
+ return super().test_call_numpy()
137
+
138
+ @unittest.skip(reason="BlipImageProcessor does not support 4 channels yet") # FIXME Amy
139
+ def test_call_pytorch(self):
140
+ return super().test_call_torch()
141
+
142
+ @unittest.skip(reason="BLIP doesn't treat 4 channel PIL and numpy consistently yet") # FIXME Amy
143
+ def test_call_pil(self):
144
+ pass
145
+
146
+ @unittest.skip(reason="BLIP doesn't treat 4 channel PIL and numpy consistently yet") # FIXME Amy
147
+ def test_call_numpy_4_channels(self):
148
+ pass
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blip/test_modeling_blip.py ADDED
@@ -0,0 +1,1435 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Testing suite for the PyTorch Blip model."""
16
+
17
+ import inspect
18
+ import os
19
+ import tempfile
20
+ import unittest
21
+
22
+ import numpy as np
23
+ import requests
24
+
25
+ from transformers import BlipConfig, BlipTextConfig, BlipVisionConfig
26
+ from transformers.testing_utils import (
27
+ require_torch,
28
+ require_torch_accelerator,
29
+ require_torch_fp16,
30
+ require_vision,
31
+ slow,
32
+ torch_device,
33
+ )
34
+ from transformers.utils import is_torch_available, is_vision_available
35
+
36
+ from ...test_configuration_common import ConfigTester
37
+ from ...test_modeling_common import (
38
+ ModelTesterMixin,
39
+ _config_zero_init,
40
+ floats_tensor,
41
+ ids_tensor,
42
+ random_attention_mask,
43
+ )
44
+ from ...test_pipeline_mixin import PipelineTesterMixin
45
+
46
+
47
+ if is_torch_available():
48
+ import torch
49
+ from torch import nn
50
+
51
+ from transformers import (
52
+ BlipForConditionalGeneration,
53
+ BlipForImageTextRetrieval,
54
+ BlipForQuestionAnswering,
55
+ BlipModel,
56
+ BlipTextModel,
57
+ BlipVisionModel,
58
+ )
59
+
60
+
61
+ if is_vision_available():
62
+ from PIL import Image
63
+
64
+ from transformers import BlipProcessor
65
+
66
+
67
+ class BlipVisionModelTester:
68
+ def __init__(
69
+ self,
70
+ parent,
71
+ batch_size=12,
72
+ image_size=30,
73
+ patch_size=2,
74
+ num_channels=3,
75
+ is_training=True,
76
+ hidden_size=32,
77
+ projection_dim=32,
78
+ num_hidden_layers=2,
79
+ num_attention_heads=4,
80
+ intermediate_size=37,
81
+ dropout=0.1,
82
+ attention_dropout=0.1,
83
+ initializer_range=1e-10,
84
+ scope=None,
85
+ ):
86
+ self.parent = parent
87
+ self.batch_size = batch_size
88
+ self.image_size = image_size
89
+ self.patch_size = patch_size
90
+ self.num_channels = num_channels
91
+ self.is_training = is_training
92
+ self.hidden_size = hidden_size
93
+ self.projection_dim = projection_dim
94
+ self.num_hidden_layers = num_hidden_layers
95
+ self.num_attention_heads = num_attention_heads
96
+ self.intermediate_size = intermediate_size
97
+ self.dropout = dropout
98
+ self.attention_dropout = attention_dropout
99
+ self.initializer_range = initializer_range
100
+ self.scope = scope
101
+
102
+ # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
103
+ num_patches = (image_size // patch_size) ** 2
104
+ self.seq_length = num_patches + 1
105
+
106
+ def prepare_config_and_inputs(self):
107
+ pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
108
+ config = self.get_config()
109
+
110
+ return config, pixel_values
111
+
112
+ def get_config(self):
113
+ return BlipVisionConfig(
114
+ image_size=self.image_size,
115
+ patch_size=self.patch_size,
116
+ num_channels=self.num_channels,
117
+ hidden_size=self.hidden_size,
118
+ projection_dim=self.projection_dim,
119
+ num_hidden_layers=self.num_hidden_layers,
120
+ num_attention_heads=self.num_attention_heads,
121
+ intermediate_size=self.intermediate_size,
122
+ dropout=self.dropout,
123
+ attention_dropout=self.attention_dropout,
124
+ initializer_range=self.initializer_range,
125
+ )
126
+
127
+ def create_and_check_model(self, config, pixel_values):
128
+ model = BlipVisionModel(config=config)
129
+ model.to(torch_device)
130
+ model.eval()
131
+ with torch.no_grad():
132
+ result = model(pixel_values)
133
+ # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
134
+ image_size = (self.image_size, self.image_size)
135
+ patch_size = (self.patch_size, self.patch_size)
136
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
137
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, num_patches + 1, self.hidden_size))
138
+ self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
139
+
140
+ def prepare_config_and_inputs_for_common(self):
141
+ config_and_inputs = self.prepare_config_and_inputs()
142
+ config, pixel_values = config_and_inputs
143
+ inputs_dict = {"pixel_values": pixel_values}
144
+ return config, inputs_dict
145
+
146
+
147
+ @require_torch
148
+ class BlipVisionModelTest(ModelTesterMixin, unittest.TestCase):
149
+ """
150
+ Here we also overwrite some of the tests of test_modeling_common.py, as Blip does not use input_ids, inputs_embeds,
151
+ attention_mask and seq_length.
152
+ """
153
+
154
+ all_model_classes = (BlipVisionModel,) if is_torch_available() else ()
155
+ fx_compatible = False
156
+ test_pruning = False
157
+ test_resize_embeddings = False
158
+ test_head_masking = False
159
+
160
+ def setUp(self):
161
+ self.model_tester = BlipVisionModelTester(self)
162
+ self.config_tester = ConfigTester(self, config_class=BlipVisionConfig, has_text_modality=False, hidden_size=37)
163
+
164
+ def test_config(self):
165
+ self.config_tester.run_common_tests()
166
+
167
+ @unittest.skip(reason="Blip does not use inputs_embeds")
168
+ def test_inputs_embeds(self):
169
+ pass
170
+
171
+ def test_model_get_set_embeddings(self):
172
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
173
+
174
+ for model_class in self.all_model_classes:
175
+ model = model_class(config)
176
+ self.assertIsInstance(model.get_input_embeddings(), (nn.Module))
177
+ x = model.get_output_embeddings()
178
+ self.assertTrue(x is None or isinstance(x, nn.Linear))
179
+
180
+ def test_forward_signature(self):
181
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
182
+
183
+ for model_class in self.all_model_classes:
184
+ model = model_class(config)
185
+ signature = inspect.signature(model.forward)
186
+ # signature.parameters is an OrderedDict => so arg_names order is deterministic
187
+ arg_names = [*signature.parameters.keys()]
188
+
189
+ expected_arg_names = ["pixel_values"]
190
+ self.assertListEqual(arg_names[:1], expected_arg_names)
191
+
192
+ def test_model(self):
193
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
194
+ self.model_tester.create_and_check_model(*config_and_inputs)
195
+
196
+ @unittest.skip
197
+ def test_training(self):
198
+ pass
199
+
200
+ @unittest.skip
201
+ def test_training_gradient_checkpointing(self):
202
+ pass
203
+
204
+ @unittest.skip(
205
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
206
+ )
207
+ def test_training_gradient_checkpointing_use_reentrant(self):
208
+ pass
209
+
210
+ @unittest.skip(
211
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
212
+ )
213
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
214
+ pass
215
+
216
+ @unittest.skip(reason="BlipVisionModel has no base class and is not available in MODEL_MAPPING")
217
+ def test_save_load_fast_init_from_base(self):
218
+ pass
219
+
220
+ @unittest.skip(reason="BlipVisionModel has no base class and is not available in MODEL_MAPPING")
221
+ def test_save_load_fast_init_to_base(self):
222
+ pass
223
+
224
+ @slow
225
+ def test_model_from_pretrained(self):
226
+ model_name = "Salesforce/blip-vqa-base"
227
+ model = BlipVisionModel.from_pretrained(model_name)
228
+ self.assertIsNotNone(model)
229
+
230
+
231
+ class BlipTextModelTester:
232
+ def __init__(
233
+ self,
234
+ parent,
235
+ batch_size=12,
236
+ seq_length=7,
237
+ is_training=True,
238
+ use_input_mask=True,
239
+ use_labels=True,
240
+ vocab_size=99,
241
+ hidden_size=32,
242
+ projection_dim=32,
243
+ num_hidden_layers=2,
244
+ num_attention_heads=4,
245
+ intermediate_size=37,
246
+ dropout=0.1,
247
+ attention_dropout=0.1,
248
+ max_position_embeddings=512,
249
+ initializer_range=0.02,
250
+ bos_token_id=0,
251
+ scope=None,
252
+ ):
253
+ self.parent = parent
254
+ self.batch_size = batch_size
255
+ self.seq_length = seq_length
256
+ self.is_training = is_training
257
+ self.use_input_mask = use_input_mask
258
+ self.use_labels = use_labels
259
+ self.vocab_size = vocab_size
260
+ self.hidden_size = hidden_size
261
+ self.projection_dim = projection_dim
262
+ self.num_hidden_layers = num_hidden_layers
263
+ self.num_attention_heads = num_attention_heads
264
+ self.intermediate_size = intermediate_size
265
+ self.dropout = dropout
266
+ self.attention_dropout = attention_dropout
267
+ self.max_position_embeddings = max_position_embeddings
268
+ self.initializer_range = initializer_range
269
+ self.scope = scope
270
+ self.bos_token_id = bos_token_id
271
+
272
+ def prepare_config_and_inputs(self):
273
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
274
+
275
+ input_mask = None
276
+ if self.use_input_mask:
277
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
278
+
279
+ if input_mask is not None:
280
+ batch_size, seq_length = input_mask.shape
281
+ rnd_start_indices = np.random.randint(1, seq_length - 1, size=(batch_size,))
282
+ for batch_idx, start_index in enumerate(rnd_start_indices):
283
+ input_mask[batch_idx, :start_index] = 1
284
+ input_mask[batch_idx, start_index:] = 0
285
+
286
+ config = self.get_config()
287
+
288
+ return config, input_ids, input_mask
289
+
290
+ def get_config(self):
291
+ return BlipTextConfig(
292
+ vocab_size=self.vocab_size,
293
+ hidden_size=self.hidden_size,
294
+ projection_dim=self.projection_dim,
295
+ num_hidden_layers=self.num_hidden_layers,
296
+ num_attention_heads=self.num_attention_heads,
297
+ intermediate_size=self.intermediate_size,
298
+ dropout=self.dropout,
299
+ attention_dropout=self.attention_dropout,
300
+ max_position_embeddings=self.max_position_embeddings,
301
+ initializer_range=self.initializer_range,
302
+ bos_token_id=self.bos_token_id,
303
+ )
304
+
305
+ def create_and_check_model(self, config, input_ids, input_mask):
306
+ model = BlipTextModel(config=config)
307
+ model.to(torch_device)
308
+ model.eval()
309
+ with torch.no_grad():
310
+ result = model(input_ids, attention_mask=input_mask)
311
+ result = model(input_ids)
312
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
313
+ self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
314
+
315
+ def prepare_config_and_inputs_for_common(self):
316
+ config_and_inputs = self.prepare_config_and_inputs()
317
+ config, input_ids, input_mask = config_and_inputs
318
+ inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
319
+ return config, inputs_dict
320
+
321
+
322
+ @require_torch
323
+ class BlipTextModelTest(ModelTesterMixin, unittest.TestCase):
324
+ all_model_classes = (BlipTextModel,) if is_torch_available() else ()
325
+ fx_compatible = False
326
+ test_pruning = False
327
+ test_head_masking = False
328
+
329
+ def setUp(self):
330
+ self.model_tester = BlipTextModelTester(self)
331
+ self.config_tester = ConfigTester(self, config_class=BlipTextConfig, hidden_size=37)
332
+
333
+ def test_config(self):
334
+ self.config_tester.run_common_tests()
335
+
336
+ def test_model(self):
337
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
338
+ self.model_tester.create_and_check_model(*config_and_inputs)
339
+
340
+ @unittest.skip
341
+ def test_training(self):
342
+ pass
343
+
344
+ @unittest.skip
345
+ def test_training_gradient_checkpointing(self):
346
+ pass
347
+
348
+ @unittest.skip(
349
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
350
+ )
351
+ def test_training_gradient_checkpointing_use_reentrant(self):
352
+ pass
353
+
354
+ @unittest.skip(
355
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
356
+ )
357
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
358
+ pass
359
+
360
+ @unittest.skip(reason="Blip does not use inputs_embeds")
361
+ def test_inputs_embeds(self):
362
+ pass
363
+
364
+ @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING")
365
+ def test_save_load_fast_init_from_base(self):
366
+ pass
367
+
368
+ @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING")
369
+ def test_save_load_fast_init_to_base(self):
370
+ pass
371
+
372
+ @slow
373
+ def test_model_from_pretrained(self):
374
+ model_name = "Salesforce/blip-vqa-base"
375
+ model = BlipTextModel.from_pretrained(model_name)
376
+ self.assertIsNotNone(model)
377
+
378
+ def test_pt_tf_model_equivalence(self):
379
+ super().test_pt_tf_model_equivalence(allow_missing_keys=True)
380
+
381
+
382
+ class BlipModelTester:
383
+ def __init__(self, parent, text_kwargs=None, vision_kwargs=None, is_training=True):
384
+ if text_kwargs is None:
385
+ text_kwargs = {}
386
+ if vision_kwargs is None:
387
+ vision_kwargs = {}
388
+
389
+ self.parent = parent
390
+ self.text_model_tester = BlipTextModelTester(parent, **text_kwargs)
391
+ self.vision_model_tester = BlipVisionModelTester(parent, **vision_kwargs)
392
+ self.batch_size = self.text_model_tester.batch_size # need bs for batching_equivalence test
393
+ self.is_training = is_training
394
+
395
+ def prepare_config_and_inputs(self):
396
+ text_config, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs()
397
+ vision_config, pixel_values = self.vision_model_tester.prepare_config_and_inputs()
398
+
399
+ config = self.get_config()
400
+
401
+ return config, input_ids, attention_mask, pixel_values
402
+
403
+ def get_config(self):
404
+ return BlipConfig.from_text_vision_configs(
405
+ self.text_model_tester.get_config(), self.vision_model_tester.get_config(), projection_dim=64
406
+ )
407
+
408
+ def create_and_check_model(self, config, input_ids, attention_mask, pixel_values):
409
+ model = BlipModel(config).to(torch_device).eval()
410
+ with torch.no_grad():
411
+ result = model(input_ids, pixel_values, attention_mask)
412
+ self.parent.assertEqual(
413
+ result.logits_per_image.shape, (self.vision_model_tester.batch_size, self.text_model_tester.batch_size)
414
+ )
415
+ self.parent.assertEqual(
416
+ result.logits_per_text.shape, (self.text_model_tester.batch_size, self.vision_model_tester.batch_size)
417
+ )
418
+
419
+ def prepare_config_and_inputs_for_common(self):
420
+ config_and_inputs = self.prepare_config_and_inputs()
421
+ config, input_ids, attention_mask, pixel_values = config_and_inputs
422
+ inputs_dict = {
423
+ "input_ids": input_ids,
424
+ "attention_mask": attention_mask,
425
+ "pixel_values": pixel_values,
426
+ "return_loss": True,
427
+ }
428
+ return config, inputs_dict
429
+
430
+
431
+ @require_torch
432
+ class BlipModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
433
+ all_model_classes = (BlipModel,) if is_torch_available() else ()
434
+ pipeline_model_mapping = (
435
+ {
436
+ "feature-extraction": BlipModel,
437
+ "image-to-text": BlipForConditionalGeneration,
438
+ "visual-question-answering": BlipForQuestionAnswering,
439
+ "image-text-to-text": BlipForConditionalGeneration,
440
+ }
441
+ if is_torch_available()
442
+ else {}
443
+ )
444
+ fx_compatible = False
445
+ test_head_masking = False
446
+ test_pruning = False
447
+ test_resize_embeddings = True
448
+ test_attention_outputs = False
449
+
450
+ def setUp(self):
451
+ self.model_tester = BlipModelTester(self)
452
+ common_properties = ["logit_scale_init_value", "image_text_hidden_size", "projection_dim", "label_smoothing"]
453
+ self.config_tester = ConfigTester(
454
+ self, config_class=BlipConfig, has_text_modality=False, common_properties=common_properties
455
+ )
456
+
457
+ def test_model(self):
458
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
459
+ self.model_tester.create_and_check_model(*config_and_inputs)
460
+
461
+ def test_config(self):
462
+ self.config_tester.run_common_tests()
463
+
464
+ @unittest.skip(reason="Hidden_states is tested in individual model tests")
465
+ def test_hidden_states_output(self):
466
+ pass
467
+
468
+ @unittest.skip(reason="Inputs_embeds is tested in individual model tests")
469
+ def test_inputs_embeds(self):
470
+ pass
471
+
472
+ @unittest.skip(reason="Retain_grad is tested in individual model tests")
473
+ def test_retain_grad_hidden_states_attentions(self):
474
+ pass
475
+
476
+ @unittest.skip(reason="BlipModel does not have input/output embeddings")
477
+ def test_model_get_set_embeddings(self):
478
+ pass
479
+
480
+ # override as the `logit_scale` parameter initilization is different for Blip
481
+ def test_initialization(self):
482
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
483
+
484
+ configs_no_init = _config_zero_init(config)
485
+ for model_class in self.all_model_classes:
486
+ model = model_class(config=configs_no_init)
487
+ for name, param in model.named_parameters():
488
+ if param.requires_grad:
489
+ # check if `logit_scale` is initilized as per the original implementation
490
+ if name == "logit_scale":
491
+ self.assertAlmostEqual(
492
+ param.data.item(),
493
+ np.log(1 / 0.07),
494
+ delta=1e-3,
495
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
496
+ )
497
+ else:
498
+ self.assertIn(
499
+ ((param.data.mean() * 1e9).round() / 1e9).item(),
500
+ [0.0, 1.0],
501
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
502
+ )
503
+
504
+ def _create_and_check_torchscript(self, config, inputs_dict):
505
+ if not self.test_torchscript:
506
+ self.skipTest(reason="test_torchscript is set to False")
507
+
508
+ configs_no_init = _config_zero_init(config) # To be sure we have no Nan
509
+ configs_no_init.torchscript = True
510
+ configs_no_init.return_dict = False
511
+ for model_class in self.all_model_classes:
512
+ model = model_class(config=configs_no_init)
513
+ model.to(torch_device)
514
+ model.eval()
515
+
516
+ try:
517
+ input_ids = inputs_dict["input_ids"]
518
+ pixel_values = inputs_dict["pixel_values"] # Blip needs pixel_values
519
+ traced_model = torch.jit.trace(model, (input_ids, pixel_values))
520
+ except RuntimeError:
521
+ self.fail("Couldn't trace module.")
522
+
523
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
524
+ pt_file_name = os.path.join(tmp_dir_name, "traced_model.pt")
525
+
526
+ try:
527
+ torch.jit.save(traced_model, pt_file_name)
528
+ except Exception:
529
+ self.fail("Couldn't save module.")
530
+
531
+ try:
532
+ loaded_model = torch.jit.load(pt_file_name)
533
+ except Exception:
534
+ self.fail("Couldn't load module.")
535
+
536
+ model.to(torch_device)
537
+ model.eval()
538
+
539
+ loaded_model.to(torch_device)
540
+ loaded_model.eval()
541
+
542
+ model_state_dict = model.state_dict()
543
+ loaded_model_state_dict = loaded_model.state_dict()
544
+
545
+ non_persistent_buffers = {}
546
+ for key in loaded_model_state_dict.keys():
547
+ if key not in model_state_dict.keys():
548
+ non_persistent_buffers[key] = loaded_model_state_dict[key]
549
+
550
+ loaded_model_state_dict = {
551
+ key: value for key, value in loaded_model_state_dict.items() if key not in non_persistent_buffers
552
+ }
553
+
554
+ self.assertEqual(set(model_state_dict.keys()), set(loaded_model_state_dict.keys()))
555
+
556
+ model_buffers = list(model.buffers())
557
+ for non_persistent_buffer in non_persistent_buffers.values():
558
+ found_buffer = False
559
+ for i, model_buffer in enumerate(model_buffers):
560
+ if torch.equal(non_persistent_buffer, model_buffer):
561
+ found_buffer = True
562
+ break
563
+
564
+ self.assertTrue(found_buffer)
565
+ model_buffers.pop(i)
566
+
567
+ models_equal = True
568
+ for layer_name, p1 in model_state_dict.items():
569
+ p2 = loaded_model_state_dict[layer_name]
570
+ if p1.data.ne(p2.data).sum() > 0:
571
+ models_equal = False
572
+
573
+ self.assertTrue(models_equal)
574
+
575
+ def test_load_vision_text_config(self):
576
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
577
+
578
+ # Save BlipConfig and check if we can load BlipVisionConfig from it
579
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
580
+ config.save_pretrained(tmp_dir_name)
581
+ vision_config = BlipVisionConfig.from_pretrained(tmp_dir_name)
582
+ self.assertDictEqual(config.vision_config.to_dict(), vision_config.to_dict())
583
+
584
+ # Save BlipConfig and check if we can load BlipTextConfig from it
585
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
586
+ config.save_pretrained(tmp_dir_name)
587
+ text_config = BlipTextConfig.from_pretrained(tmp_dir_name)
588
+ self.assertDictEqual(config.text_config.to_dict(), text_config.to_dict())
589
+
590
+ @slow
591
+ def test_model_from_pretrained(self):
592
+ model_name = "Salesforce/blip-vqa-base"
593
+ model = BlipModel.from_pretrained(model_name)
594
+ self.assertIsNotNone(model)
595
+
596
+ def test_get_image_features(self):
597
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
598
+
599
+ keys_to_pop = ["input_ids", "attention_mask", "return_loss"]
600
+
601
+ for key in keys_to_pop:
602
+ inputs_dict.pop(key)
603
+
604
+ model = BlipModel(config).to(torch_device)
605
+ model.eval()
606
+ image_features = model.get_image_features(**inputs_dict)
607
+ self.assertEqual(
608
+ image_features.shape,
609
+ (
610
+ self.model_tester.batch_size,
611
+ model.projection_dim,
612
+ ),
613
+ )
614
+
615
+ def test_get_text_features(self):
616
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
617
+
618
+ keys_to_pop = ["pixel_values", "return_loss"]
619
+
620
+ for key in keys_to_pop:
621
+ inputs_dict.pop(key)
622
+
623
+ model = BlipModel(config).to(torch_device)
624
+ model.eval()
625
+ text_features = model.get_text_features(**inputs_dict)
626
+ self.assertEqual(
627
+ text_features.shape,
628
+ (
629
+ self.model_tester.batch_size,
630
+ model.projection_dim,
631
+ ),
632
+ )
633
+
634
+ def test_get_multimodal_features(self):
635
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
636
+
637
+ keys_to_pop = ["return_loss"]
638
+
639
+ for key in keys_to_pop:
640
+ inputs_dict.pop(key)
641
+
642
+ model = BlipModel(config).to(torch_device)
643
+ model.eval()
644
+ multimodal_features = model.get_multimodal_features(**inputs_dict)
645
+ self.assertEqual(
646
+ multimodal_features.shape,
647
+ (
648
+ self.model_tester.batch_size,
649
+ model.projection_dim,
650
+ ),
651
+ )
652
+
653
+ def test_pt_tf_model_equivalence(self):
654
+ super().test_pt_tf_model_equivalence(allow_missing_keys=True)
655
+
656
+
657
+ class BlipTextRetrievalModelTester:
658
+ def __init__(self, parent, text_kwargs=None, vision_kwargs=None, is_training=True):
659
+ if text_kwargs is None:
660
+ text_kwargs = {}
661
+ if vision_kwargs is None:
662
+ vision_kwargs = {}
663
+
664
+ self.parent = parent
665
+ self.text_model_tester = BlipTextModelTester(parent, **text_kwargs)
666
+ self.vision_model_tester = BlipVisionModelTester(parent, **vision_kwargs)
667
+ self.batch_size = self.text_model_tester.batch_size # need bs for batching_equivalence test
668
+ self.is_training = is_training
669
+
670
+ def prepare_config_and_inputs(self):
671
+ text_config, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs()
672
+ vision_config, pixel_values = self.vision_model_tester.prepare_config_and_inputs()
673
+
674
+ config = self.get_config()
675
+
676
+ return config, input_ids, attention_mask, pixel_values
677
+
678
+ def get_config(self):
679
+ return BlipConfig.from_text_vision_configs(
680
+ self.text_model_tester.get_config(), self.vision_model_tester.get_config(), projection_dim=64
681
+ )
682
+
683
+ def create_and_check_model(self, config, input_ids, attention_mask, pixel_values):
684
+ model = BlipModel(config).to(torch_device).eval()
685
+ with torch.no_grad():
686
+ result = model(input_ids, pixel_values, attention_mask)
687
+ self.parent.assertEqual(
688
+ result.logits_per_image.shape, (self.vision_model_tester.batch_size, self.text_model_tester.batch_size)
689
+ )
690
+ self.parent.assertEqual(
691
+ result.logits_per_text.shape, (self.text_model_tester.batch_size, self.vision_model_tester.batch_size)
692
+ )
693
+
694
+ def prepare_config_and_inputs_for_common(self):
695
+ config_and_inputs = self.prepare_config_and_inputs()
696
+ config, input_ids, attention_mask, pixel_values = config_and_inputs
697
+ inputs_dict = {
698
+ "input_ids": input_ids,
699
+ "attention_mask": attention_mask,
700
+ "pixel_values": pixel_values,
701
+ }
702
+ return config, inputs_dict
703
+
704
+
705
+ class BlipTextImageModelsModelTester:
706
+ def __init__(self, parent, text_kwargs=None, vision_kwargs=None, is_training=True):
707
+ if text_kwargs is None:
708
+ text_kwargs = {}
709
+ if vision_kwargs is None:
710
+ vision_kwargs = {}
711
+
712
+ self.parent = parent
713
+ self.text_model_tester = BlipTextModelTester(parent, **text_kwargs)
714
+ self.vision_model_tester = BlipVisionModelTester(parent, **vision_kwargs)
715
+ self.batch_size = self.text_model_tester.batch_size # need bs for batching_equivalence test
716
+ self.seq_length = self.text_model_tester.seq_length # need seq_length for pt-tf equivalence test
717
+ self.is_training = is_training
718
+
719
+ def prepare_config_and_inputs(self):
720
+ text_config, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs()
721
+ vision_config, pixel_values = self.vision_model_tester.prepare_config_and_inputs()
722
+
723
+ config = self.get_config()
724
+
725
+ return config, input_ids, attention_mask, pixel_values
726
+
727
+ def get_config(self):
728
+ return BlipConfig.from_text_vision_configs(
729
+ self.text_model_tester.get_config(), self.vision_model_tester.get_config(), projection_dim=64
730
+ )
731
+
732
+ def create_and_check_model(self, config, input_ids, attention_mask, pixel_values):
733
+ model = BlipModel(config).to(torch_device).eval()
734
+ with torch.no_grad():
735
+ result = model(input_ids, pixel_values, attention_mask)
736
+ self.parent.assertEqual(
737
+ result.logits_per_image.shape, (self.vision_model_tester.batch_size, self.text_model_tester.batch_size)
738
+ )
739
+ self.parent.assertEqual(
740
+ result.logits_per_text.shape, (self.text_model_tester.batch_size, self.vision_model_tester.batch_size)
741
+ )
742
+
743
+ def prepare_config_and_inputs_for_common(self):
744
+ config_and_inputs = self.prepare_config_and_inputs()
745
+ config, input_ids, attention_mask, pixel_values = config_and_inputs
746
+ inputs_dict = {
747
+ "input_ids": input_ids,
748
+ "attention_mask": attention_mask,
749
+ "pixel_values": pixel_values,
750
+ }
751
+ return config, inputs_dict
752
+
753
+
754
+ class BlipVQAModelTester:
755
+ def __init__(self, parent, text_kwargs=None, vision_kwargs=None, is_training=True):
756
+ if text_kwargs is None:
757
+ text_kwargs = {}
758
+ if vision_kwargs is None:
759
+ vision_kwargs = {}
760
+
761
+ self.parent = parent
762
+ self.text_model_tester = BlipTextModelTester(parent, **text_kwargs)
763
+ self.vision_model_tester = BlipVisionModelTester(parent, **vision_kwargs)
764
+ self.batch_size = self.text_model_tester.batch_size # need bs for batching_equivalence test
765
+ self.is_training = is_training
766
+
767
+ def prepare_config_and_inputs(self):
768
+ text_config, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs()
769
+ vision_config, pixel_values = self.vision_model_tester.prepare_config_and_inputs()
770
+
771
+ config = self.get_config()
772
+
773
+ return config, input_ids, attention_mask, pixel_values
774
+
775
+ def get_config(self):
776
+ return BlipConfig.from_text_vision_configs(
777
+ self.text_model_tester.get_config(), self.vision_model_tester.get_config(), projection_dim=64
778
+ )
779
+
780
+ def create_and_check_model(self, config, input_ids, attention_mask, pixel_values):
781
+ model = BlipModel(config).to(torch_device).eval()
782
+ with torch.no_grad():
783
+ result = model(input_ids, pixel_values, attention_mask)
784
+ self.parent.assertEqual(
785
+ result.logits_per_image.shape, (self.vision_model_tester.batch_size, self.text_model_tester.batch_size)
786
+ )
787
+ self.parent.assertEqual(
788
+ result.logits_per_text.shape, (self.text_model_tester.batch_size, self.vision_model_tester.batch_size)
789
+ )
790
+
791
+ def prepare_config_and_inputs_for_common(self):
792
+ config_and_inputs = self.prepare_config_and_inputs()
793
+ config, input_ids, attention_mask, pixel_values = config_and_inputs
794
+ inputs_dict = {
795
+ "input_ids": input_ids,
796
+ "decoder_input_ids": input_ids,
797
+ "attention_mask": attention_mask,
798
+ "pixel_values": pixel_values,
799
+ "labels": input_ids,
800
+ }
801
+ return config, inputs_dict
802
+
803
+
804
+ @require_torch
805
+ @require_vision
806
+ class BlipVQAModelTest(ModelTesterMixin, unittest.TestCase):
807
+ all_model_classes = (BlipForQuestionAnswering,) if is_torch_available() else ()
808
+ fx_compatible = False
809
+ test_head_masking = False
810
+ test_pruning = False
811
+ test_resize_embeddings = True
812
+ test_attention_outputs = False
813
+ test_torchscript = False
814
+
815
+ def setUp(self):
816
+ self.model_tester = BlipVQAModelTester(self)
817
+
818
+ def _prepare_inputs_for_vqa(self):
819
+ _, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
820
+ inputs_dict["decoder_input_ids"] = inputs_dict["input_ids"]
821
+ inputs_dict.pop("return_loss")
822
+ return inputs_dict
823
+
824
+ def test_class_name_consistency(self):
825
+ """
826
+ Tests that all VQA models have a class name that ends with "ForQuestionAnswering"
827
+ """
828
+ for model_class in self.all_model_classes:
829
+ model = model_class(self.model_tester.get_config())
830
+ self.assertTrue(
831
+ model.__class__.__name__.endswith("ForQuestionAnswering"),
832
+ f"Class name should end with 'ForVisualQuestionAnswering' got {model.__class__.__name__}",
833
+ )
834
+
835
+ def test_training(self):
836
+ """
837
+ Tests that all VQA models can be trained on a single batch
838
+ """
839
+ for model_class in self.all_model_classes:
840
+ model = model_class(self.model_tester.get_config()).to(torch_device)
841
+ model.train()
842
+ loss = model(**self.model_tester.prepare_config_and_inputs_for_common()[1]).loss
843
+ loss.backward()
844
+
845
+ # verify the gradients are not None
846
+ for name, param in model.named_parameters():
847
+ self.assertIsNotNone(param.grad, f"Gradients should not be None - got {param.grad} for {name}")
848
+
849
+ def test_forward_signature(self):
850
+ """
851
+ Test if the forward function has the expected arguments.
852
+ """
853
+ for model_class in self.all_model_classes:
854
+ model = model_class(self.model_tester.get_config())
855
+ signature = inspect.signature(model.forward)
856
+ # signature.parameters is an OrderedDict => so args are the first n entries
857
+ args = list(signature.parameters.keys())
858
+ expected_args = [
859
+ "input_ids",
860
+ "attention_mask",
861
+ "labels",
862
+ "decoder_input_ids",
863
+ "decoder_attention_mask",
864
+ ]
865
+ for arg in expected_args:
866
+ self.assertTrue(
867
+ arg in args,
868
+ f"Argument {arg} of forward function signature should include {arg}. Found {args}.",
869
+ )
870
+
871
+ @unittest.skip(reason="Hidden_states is tested in individual model tests")
872
+ def test_hidden_states_output(self):
873
+ pass
874
+
875
+ @unittest.skip(reason="Inputs_embeds is tested in individual model tests")
876
+ def test_inputs_embeds(self):
877
+ pass
878
+
879
+ @unittest.skip(reason="BlipModel does not have input/output embeddings")
880
+ def test_model_get_set_embeddings(self):
881
+ pass
882
+
883
+
884
+ @require_torch
885
+ class BlipTextRetrievalModelTest(ModelTesterMixin, unittest.TestCase):
886
+ all_model_classes = (BlipForImageTextRetrieval,) if is_torch_available() else ()
887
+ fx_compatible = False
888
+ test_head_masking = False
889
+ test_pruning = False
890
+ test_resize_embeddings = True
891
+ test_attention_outputs = False
892
+ test_torchscript = False
893
+
894
+ def setUp(self):
895
+ self.model_tester = BlipTextRetrievalModelTester(self)
896
+
897
+ def test_model(self):
898
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
899
+ self.model_tester.create_and_check_model(*config_and_inputs)
900
+
901
+ @unittest.skip(reason="Hidden_states is tested in individual model tests")
902
+ def test_hidden_states_output(self):
903
+ pass
904
+
905
+ @unittest.skip(reason="Inputs_embeds is tested in individual model tests")
906
+ def test_inputs_embeds(self):
907
+ pass
908
+
909
+ @unittest.skip(reason="Retain_grad is tested in individual model tests")
910
+ def test_retain_grad_hidden_states_attentions(self):
911
+ pass
912
+
913
+ @unittest.skip(reason="BlipModel does not have input/output embeddings")
914
+ def test_model_get_set_embeddings(self):
915
+ pass
916
+
917
+ def test_forward_signature(self):
918
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
919
+
920
+ for model_class in self.all_model_classes:
921
+ model = model_class(config)
922
+ signature = inspect.signature(model.forward)
923
+ # signature.parameters is an OrderedDict => so arg_names order is deterministic
924
+ arg_names = [*signature.parameters.keys()]
925
+
926
+ if model.config.is_encoder_decoder:
927
+ expected_arg_names = [
928
+ "input_ids",
929
+ "attention_mask",
930
+ "decoder_input_ids",
931
+ "decoder_attention_mask",
932
+ ]
933
+ expected_arg_names.extend(
934
+ ["head_mask", "decoder_head_mask", "cross_attn_head_mask", "encoder_outputs"]
935
+ if "head_mask" and "decoder_head_mask" and "cross_attn_head_mask" in arg_names
936
+ else ["encoder_outputs"]
937
+ )
938
+ self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names)
939
+ else:
940
+ expected_arg_names = ["input_ids"] if model_class != BlipForConditionalGeneration else ["pixel_values"]
941
+ self.assertListEqual(arg_names[:1], expected_arg_names)
942
+
943
+ def test_training(self):
944
+ if not self.model_tester.is_training:
945
+ self.skipTest(reason="ModelTester is not setup for training")
946
+
947
+ for model_class in self.all_model_classes[:-1]:
948
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
949
+ config.return_dict = True
950
+
951
+ model = model_class(config)
952
+ model.to(torch_device)
953
+ model.train()
954
+ inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
955
+
956
+ # hardcode labels to be the same as input_ids
957
+ inputs["labels"] = inputs["input_ids"]
958
+
959
+ loss = model(**inputs).loss
960
+ loss.backward()
961
+
962
+ def test_training_gradient_checkpointing(self):
963
+ if not self.model_tester.is_training:
964
+ self.skipTest(reason="ModelTester is not setup for training")
965
+
966
+ for model_class in self.all_model_classes[:-1]:
967
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
968
+ config.use_cache = False
969
+ config.return_dict = True
970
+
971
+ model = model_class(config)
972
+ model.to(torch_device)
973
+ model.gradient_checkpointing_enable()
974
+ model.train()
975
+ inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
976
+
977
+ # hardcode labels to be the same as input_ids
978
+ inputs["labels"] = inputs["input_ids"]
979
+
980
+ loss = model(**inputs).loss
981
+ loss.backward()
982
+
983
+ @unittest.skip(
984
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
985
+ )
986
+ def test_training_gradient_checkpointing_use_reentrant(self):
987
+ pass
988
+
989
+ @unittest.skip(
990
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
991
+ )
992
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
993
+ pass
994
+
995
+ # override as the `logit_scale` parameter initilization is different for Blip
996
+ def test_initialization(self):
997
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
998
+
999
+ configs_no_init = _config_zero_init(config)
1000
+ for model_class in self.all_model_classes:
1001
+ model = model_class(config=configs_no_init)
1002
+ for name, param in model.named_parameters():
1003
+ if param.requires_grad:
1004
+ # check if `logit_scale` is initilized as per the original implementation
1005
+ if name == "logit_scale":
1006
+ self.assertAlmostEqual(
1007
+ param.data.item(),
1008
+ np.log(1 / 0.07),
1009
+ delta=1e-3,
1010
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
1011
+ )
1012
+ else:
1013
+ self.assertIn(
1014
+ ((param.data.mean() * 1e9).round() / 1e9).item(),
1015
+ [0.0, 1.0],
1016
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
1017
+ )
1018
+
1019
+ def _create_and_check_torchscript(self, config, inputs_dict):
1020
+ if not self.test_torchscript:
1021
+ self.skipTest(reason="test_torchscript is set to False")
1022
+
1023
+ configs_no_init = _config_zero_init(config) # To be sure we have no Nan
1024
+ configs_no_init.torchscript = True
1025
+ configs_no_init.return_dict = False
1026
+ for model_class in self.all_model_classes:
1027
+ model = model_class(config=configs_no_init)
1028
+ model.to(torch_device)
1029
+ model.eval()
1030
+
1031
+ try:
1032
+ input_ids = inputs_dict["input_ids"]
1033
+ pixel_values = inputs_dict["pixel_values"] # Blip needs pixel_values
1034
+ traced_model = torch.jit.trace(model, (input_ids, pixel_values))
1035
+ except RuntimeError:
1036
+ self.fail("Couldn't trace module.")
1037
+
1038
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
1039
+ pt_file_name = os.path.join(tmp_dir_name, "traced_model.pt")
1040
+
1041
+ try:
1042
+ torch.jit.save(traced_model, pt_file_name)
1043
+ except Exception:
1044
+ self.fail("Couldn't save module.")
1045
+
1046
+ try:
1047
+ loaded_model = torch.jit.load(pt_file_name)
1048
+ except Exception:
1049
+ self.fail("Couldn't load module.")
1050
+
1051
+ model.to(torch_device)
1052
+ model.eval()
1053
+
1054
+ loaded_model.to(torch_device)
1055
+ loaded_model.eval()
1056
+
1057
+ model_state_dict = model.state_dict()
1058
+ loaded_model_state_dict = loaded_model.state_dict()
1059
+
1060
+ non_persistent_buffers = {}
1061
+ for key in loaded_model_state_dict.keys():
1062
+ if key not in model_state_dict.keys():
1063
+ non_persistent_buffers[key] = loaded_model_state_dict[key]
1064
+
1065
+ loaded_model_state_dict = {
1066
+ key: value for key, value in loaded_model_state_dict.items() if key not in non_persistent_buffers
1067
+ }
1068
+
1069
+ self.assertEqual(set(model_state_dict.keys()), set(loaded_model_state_dict.keys()))
1070
+
1071
+ model_buffers = list(model.buffers())
1072
+ for non_persistent_buffer in non_persistent_buffers.values():
1073
+ found_buffer = False
1074
+ for i, model_buffer in enumerate(model_buffers):
1075
+ if torch.equal(non_persistent_buffer, model_buffer):
1076
+ found_buffer = True
1077
+ break
1078
+
1079
+ self.assertTrue(found_buffer)
1080
+ model_buffers.pop(i)
1081
+
1082
+ models_equal = True
1083
+ for layer_name, p1 in model_state_dict.items():
1084
+ p2 = loaded_model_state_dict[layer_name]
1085
+ if p1.data.ne(p2.data).sum() > 0:
1086
+ models_equal = False
1087
+
1088
+ self.assertTrue(models_equal)
1089
+
1090
+ def test_load_vision_text_config(self):
1091
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
1092
+
1093
+ # Save BlipConfig and check if we can load BlipVisionConfig from it
1094
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
1095
+ config.save_pretrained(tmp_dir_name)
1096
+ vision_config = BlipVisionConfig.from_pretrained(tmp_dir_name)
1097
+ self.assertDictEqual(config.vision_config.to_dict(), vision_config.to_dict())
1098
+
1099
+ # Save BlipConfig and check if we can load BlipTextConfig from it
1100
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
1101
+ config.save_pretrained(tmp_dir_name)
1102
+ text_config = BlipTextConfig.from_pretrained(tmp_dir_name)
1103
+ self.assertDictEqual(config.text_config.to_dict(), text_config.to_dict())
1104
+
1105
+ @slow
1106
+ def test_model_from_pretrained(self):
1107
+ model_name = "Salesforce/blip-vqa-base"
1108
+ model = BlipModel.from_pretrained(model_name)
1109
+ self.assertIsNotNone(model)
1110
+
1111
+
1112
+ @require_torch
1113
+ class BlipTextImageModelTest(ModelTesterMixin, unittest.TestCase):
1114
+ all_model_classes = (BlipForConditionalGeneration,) if is_torch_available() else ()
1115
+ fx_compatible = False
1116
+ test_head_masking = False
1117
+ test_pruning = False
1118
+ test_resize_embeddings = True
1119
+ test_attention_outputs = False
1120
+ test_torchscript = False
1121
+
1122
+ def setUp(self):
1123
+ self.model_tester = BlipTextImageModelsModelTester(self)
1124
+
1125
+ def test_model(self):
1126
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
1127
+ self.model_tester.create_and_check_model(*config_and_inputs)
1128
+
1129
+ @unittest.skip(reason="Hidden_states is tested in individual model tests")
1130
+ def test_hidden_states_output(self):
1131
+ pass
1132
+
1133
+ @unittest.skip(reason="Inputs_embeds is tested in individual model tests")
1134
+ def test_inputs_embeds(self):
1135
+ pass
1136
+
1137
+ @unittest.skip(reason="Retain_grad is tested in individual model tests")
1138
+ def test_retain_grad_hidden_states_attentions(self):
1139
+ pass
1140
+
1141
+ @unittest.skip(reason="BlipModel does not have input/output embeddings")
1142
+ def test_model_get_set_embeddings(self):
1143
+ pass
1144
+
1145
+ def test_forward_signature(self):
1146
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
1147
+
1148
+ for model_class in self.all_model_classes:
1149
+ model = model_class(config)
1150
+ signature = inspect.signature(model.forward)
1151
+ # signature.parameters is an OrderedDict => so arg_names order is deterministic
1152
+ arg_names = [*signature.parameters.keys()]
1153
+
1154
+ if model.config.is_encoder_decoder:
1155
+ expected_arg_names = [
1156
+ "input_ids",
1157
+ "attention_mask",
1158
+ "decoder_input_ids",
1159
+ "decoder_attention_mask",
1160
+ ]
1161
+ expected_arg_names.extend(
1162
+ ["head_mask", "decoder_head_mask", "cross_attn_head_mask", "encoder_outputs"]
1163
+ if "head_mask" and "decoder_head_mask" and "cross_attn_head_mask" in arg_names
1164
+ else ["encoder_outputs"]
1165
+ )
1166
+ self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names)
1167
+ else:
1168
+ expected_arg_names = ["input_ids"] if model_class != BlipForConditionalGeneration else ["pixel_values"]
1169
+ self.assertListEqual(arg_names[:1], expected_arg_names)
1170
+
1171
+ def test_training(self):
1172
+ if not self.model_tester.is_training:
1173
+ self.skipTest(reason="ModelTester is not setup for training")
1174
+
1175
+ for model_class in self.all_model_classes[:-1]:
1176
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
1177
+ config.return_dict = True
1178
+
1179
+ model = model_class(config)
1180
+ model.to(torch_device)
1181
+ model.train()
1182
+ inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
1183
+
1184
+ # hardcode labels to be the same as input_ids
1185
+ inputs["labels"] = inputs["input_ids"]
1186
+
1187
+ loss = model(**inputs).loss
1188
+ loss.backward()
1189
+
1190
+ def test_training_gradient_checkpointing(self):
1191
+ if not self.model_tester.is_training:
1192
+ self.skipTest(reason="ModelTester is not setup for training")
1193
+
1194
+ for model_class in self.all_model_classes[:-1]:
1195
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
1196
+ config.use_cache = False
1197
+ config.return_dict = True
1198
+
1199
+ model = model_class(config)
1200
+ model.to(torch_device)
1201
+ model.gradient_checkpointing_enable()
1202
+ model.train()
1203
+ inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
1204
+
1205
+ # hardcode labels to be the same as input_ids
1206
+ inputs["labels"] = inputs["input_ids"]
1207
+
1208
+ loss = model(**inputs).loss
1209
+ loss.backward()
1210
+
1211
+ # override as the `logit_scale` parameter initilization is different for Blip
1212
+ def test_initialization(self):
1213
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
1214
+
1215
+ configs_no_init = _config_zero_init(config)
1216
+ for model_class in self.all_model_classes:
1217
+ model = model_class(config=configs_no_init)
1218
+ for name, param in model.named_parameters():
1219
+ if param.requires_grad:
1220
+ # check if `logit_scale` is initilized as per the original implementation
1221
+ if name == "logit_scale":
1222
+ self.assertAlmostEqual(
1223
+ param.data.item(),
1224
+ np.log(1 / 0.07),
1225
+ delta=1e-3,
1226
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
1227
+ )
1228
+ else:
1229
+ self.assertIn(
1230
+ ((param.data.mean() * 1e9).round() / 1e9).item(),
1231
+ [0.0, 1.0],
1232
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
1233
+ )
1234
+
1235
+ def _create_and_check_torchscript(self, config, inputs_dict):
1236
+ if not self.test_torchscript:
1237
+ self.skipTest(reason="test_torchscript is set to False")
1238
+
1239
+ configs_no_init = _config_zero_init(config) # To be sure we have no Nan
1240
+ configs_no_init.torchscript = True
1241
+ configs_no_init.return_dict = False
1242
+ for model_class in self.all_model_classes:
1243
+ model = model_class(config=configs_no_init)
1244
+ model.to(torch_device)
1245
+ model.eval()
1246
+
1247
+ try:
1248
+ input_ids = inputs_dict["input_ids"]
1249
+ pixel_values = inputs_dict["pixel_values"] # Blip needs pixel_values
1250
+ traced_model = torch.jit.trace(model, (input_ids, pixel_values))
1251
+ except RuntimeError:
1252
+ self.fail("Couldn't trace module.")
1253
+
1254
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
1255
+ pt_file_name = os.path.join(tmp_dir_name, "traced_model.pt")
1256
+
1257
+ try:
1258
+ torch.jit.save(traced_model, pt_file_name)
1259
+ except Exception:
1260
+ self.fail("Couldn't save module.")
1261
+
1262
+ try:
1263
+ loaded_model = torch.jit.load(pt_file_name)
1264
+ except Exception:
1265
+ self.fail("Couldn't load module.")
1266
+
1267
+ model.to(torch_device)
1268
+ model.eval()
1269
+
1270
+ loaded_model.to(torch_device)
1271
+ loaded_model.eval()
1272
+
1273
+ model_state_dict = model.state_dict()
1274
+ loaded_model_state_dict = loaded_model.state_dict()
1275
+
1276
+ non_persistent_buffers = {}
1277
+ for key in loaded_model_state_dict.keys():
1278
+ if key not in model_state_dict.keys():
1279
+ non_persistent_buffers[key] = loaded_model_state_dict[key]
1280
+
1281
+ loaded_model_state_dict = {
1282
+ key: value for key, value in loaded_model_state_dict.items() if key not in non_persistent_buffers
1283
+ }
1284
+
1285
+ self.assertEqual(set(model_state_dict.keys()), set(loaded_model_state_dict.keys()))
1286
+
1287
+ model_buffers = list(model.buffers())
1288
+ for non_persistent_buffer in non_persistent_buffers.values():
1289
+ found_buffer = False
1290
+ for i, model_buffer in enumerate(model_buffers):
1291
+ if torch.equal(non_persistent_buffer, model_buffer):
1292
+ found_buffer = True
1293
+ break
1294
+
1295
+ self.assertTrue(found_buffer)
1296
+ model_buffers.pop(i)
1297
+
1298
+ models_equal = True
1299
+ for layer_name, p1 in model_state_dict.items():
1300
+ p2 = loaded_model_state_dict[layer_name]
1301
+ if p1.data.ne(p2.data).sum() > 0:
1302
+ models_equal = False
1303
+
1304
+ self.assertTrue(models_equal)
1305
+
1306
+ def test_load_vision_text_config(self):
1307
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
1308
+
1309
+ # Save BlipConfig and check if we can load BlipVisionConfig from it
1310
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
1311
+ config.save_pretrained(tmp_dir_name)
1312
+ vision_config = BlipVisionConfig.from_pretrained(tmp_dir_name)
1313
+ self.assertDictEqual(config.vision_config.to_dict(), vision_config.to_dict())
1314
+
1315
+ # Save BlipConfig and check if we can load BlipTextConfig from it
1316
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
1317
+ config.save_pretrained(tmp_dir_name)
1318
+ text_config = BlipTextConfig.from_pretrained(tmp_dir_name)
1319
+ self.assertDictEqual(config.text_config.to_dict(), text_config.to_dict())
1320
+
1321
+ @slow
1322
+ def test_model_from_pretrained(self):
1323
+ model_name = "Salesforce/blip-vqa-base"
1324
+ model = BlipModel.from_pretrained(model_name)
1325
+ self.assertIsNotNone(model)
1326
+
1327
+
1328
+ # We will verify our results on an image of cute cats
1329
+ def prepare_img():
1330
+ url = "https://huggingface.co/hf-internal-testing/blip-test-image/resolve/main/demo.jpg"
1331
+ im = Image.open(requests.get(url, stream=True).raw)
1332
+ return im
1333
+
1334
+
1335
+ @require_vision
1336
+ @require_torch
1337
+ @slow
1338
+ class BlipModelIntegrationTest(unittest.TestCase):
1339
+ def test_inference_image_captioning(self):
1340
+ model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to(torch_device)
1341
+ processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
1342
+ image = prepare_img()
1343
+
1344
+ # image only
1345
+ inputs = processor(images=image, return_tensors="pt").to(torch_device)
1346
+
1347
+ predictions = model.generate(**inputs)
1348
+
1349
+ # Test output
1350
+ self.assertEqual(predictions[0].tolist(), [30522, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102])
1351
+
1352
+ # image and context
1353
+ context = ["a picture of"]
1354
+ inputs = processor(images=image, text=context, return_tensors="pt").to(torch_device)
1355
+
1356
+ predictions = model.generate(**inputs)
1357
+
1358
+ # Test output
1359
+ self.assertEqual(
1360
+ predictions[0].tolist(),
1361
+ [30522, 1037, 3861, 1997, 1037, 2450, 1998, 2014, 3899, 2006, 1996, 3509, 102],
1362
+ )
1363
+
1364
+ @require_torch_accelerator
1365
+ @require_torch_fp16
1366
+ def test_inference_image_captioning_fp16(self):
1367
+ model = BlipForConditionalGeneration.from_pretrained(
1368
+ "Salesforce/blip-image-captioning-base", torch_dtype=torch.float16
1369
+ ).to(torch_device)
1370
+ processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
1371
+ image = prepare_img()
1372
+
1373
+ # image only
1374
+ inputs = processor(images=image, return_tensors="pt").to(torch_device, torch.float16)
1375
+
1376
+ predictions = model.generate(**inputs)
1377
+
1378
+ # Test output
1379
+ self.assertEqual(predictions[0].tolist(), [30522, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102])
1380
+
1381
+ # image and context
1382
+ context = ["a picture of"]
1383
+ inputs = processor(images=image, text=context, return_tensors="pt").to(torch_device, torch.float16)
1384
+
1385
+ predictions = model.generate(**inputs)
1386
+
1387
+ # Test output
1388
+ self.assertEqual(
1389
+ predictions[0].tolist(),
1390
+ [30522, 1037, 3861, 1997, 1037, 2450, 1998, 2014, 3899, 2006, 1996, 3509, 102],
1391
+ )
1392
+
1393
+ def test_inference_interpolate_pos_encoding(self):
1394
+ model = BlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base").to(torch_device)
1395
+ processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
1396
+ processor.image_processor.size = {"height": 500, "width": 500}
1397
+
1398
+ image = prepare_img()
1399
+ inputs = processor(images=image, return_tensors="pt").to(torch_device)
1400
+
1401
+ predictions = model.generate(**inputs, interpolate_pos_encoding=True)
1402
+ generated_text = processor.batch_decode(predictions, skip_special_tokens=True)[0].strip()
1403
+
1404
+ self.assertEqual(predictions[0].tolist(), [30522, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 1037, 3899, 102])
1405
+ self.assertEqual(generated_text, "a woman sitting on the beach with a dog")
1406
+
1407
+ def test_inference_vqa(self):
1408
+ model = BlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base").to(torch_device)
1409
+ processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-base")
1410
+
1411
+ image = prepare_img()
1412
+ text = "how many dogs are in the picture?"
1413
+
1414
+ inputs = processor(image, text=text, return_tensors="pt").to(torch_device)
1415
+ out = model.generate(**inputs)
1416
+
1417
+ # Test output
1418
+ self.assertEqual(out[0].tolist(), [30522, 1015, 102])
1419
+
1420
+ def test_inference_itm(self):
1421
+ model = BlipForImageTextRetrieval.from_pretrained("Salesforce/blip-itm-base-coco").to(torch_device)
1422
+ processor = BlipProcessor.from_pretrained("Salesforce/blip-itm-base-coco")
1423
+
1424
+ image = prepare_img()
1425
+ text = "A woman and her dog sitting in a beach"
1426
+
1427
+ inputs = processor(image, text, return_tensors="pt").to(torch_device)
1428
+
1429
+ out_itm = model(**inputs)
1430
+ out = model(**inputs, use_itm_head=False)
1431
+
1432
+ expected_scores = torch.Tensor([[0.0029, 0.9971]])
1433
+
1434
+ self.assertTrue(torch.allclose(torch.nn.Softmax()(out_itm[0].cpu()), expected_scores, rtol=1e-3, atol=1e-3))
1435
+ self.assertTrue(torch.allclose(out[0].cpu(), torch.Tensor([[0.5162]]), rtol=1e-3, atol=1e-3))
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blip/test_modeling_blip_text.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """Testing suite for the PyTorch Blip model."""
16
+
17
+ import unittest
18
+
19
+ import numpy as np
20
+
21
+ from transformers import BlipTextConfig
22
+ from transformers.testing_utils import require_torch, slow, torch_device
23
+ from transformers.utils import is_torch_available
24
+
25
+ from ...test_configuration_common import ConfigTester
26
+ from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
27
+
28
+
29
+ if is_torch_available():
30
+ import torch
31
+
32
+ from transformers import BlipTextModel
33
+
34
+
35
+ class BlipTextModelTester:
36
+ def __init__(
37
+ self,
38
+ parent,
39
+ batch_size=12,
40
+ seq_length=7,
41
+ is_training=True,
42
+ use_input_mask=True,
43
+ use_labels=True,
44
+ vocab_size=99,
45
+ hidden_size=32,
46
+ projection_dim=32,
47
+ num_hidden_layers=2,
48
+ num_attention_heads=4,
49
+ intermediate_size=37,
50
+ dropout=0.1,
51
+ attention_dropout=0.1,
52
+ max_position_embeddings=512,
53
+ initializer_range=0.02,
54
+ bos_token_id=0,
55
+ scope=None,
56
+ ):
57
+ self.parent = parent
58
+ self.batch_size = batch_size
59
+ self.seq_length = seq_length
60
+ self.is_training = is_training
61
+ self.use_input_mask = use_input_mask
62
+ self.use_labels = use_labels
63
+ self.vocab_size = vocab_size
64
+ self.hidden_size = hidden_size
65
+ self.projection_dim = projection_dim
66
+ self.num_hidden_layers = num_hidden_layers
67
+ self.num_attention_heads = num_attention_heads
68
+ self.intermediate_size = intermediate_size
69
+ self.dropout = dropout
70
+ self.attention_dropout = attention_dropout
71
+ self.max_position_embeddings = max_position_embeddings
72
+ self.initializer_range = initializer_range
73
+ self.scope = scope
74
+ self.bos_token_id = bos_token_id
75
+
76
+ def prepare_config_and_inputs(self):
77
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
78
+
79
+ input_mask = None
80
+ if self.use_input_mask:
81
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
82
+
83
+ if input_mask is not None:
84
+ batch_size, seq_length = input_mask.shape
85
+ rnd_start_indices = np.random.randint(1, seq_length - 1, size=(batch_size,))
86
+ for batch_idx, start_index in enumerate(rnd_start_indices):
87
+ input_mask[batch_idx, :start_index] = 1
88
+ input_mask[batch_idx, start_index:] = 0
89
+
90
+ config = self.get_config()
91
+
92
+ return config, input_ids, input_mask
93
+
94
+ def get_config(self):
95
+ return BlipTextConfig(
96
+ vocab_size=self.vocab_size,
97
+ hidden_size=self.hidden_size,
98
+ projection_dim=self.projection_dim,
99
+ num_hidden_layers=self.num_hidden_layers,
100
+ num_attention_heads=self.num_attention_heads,
101
+ intermediate_size=self.intermediate_size,
102
+ dropout=self.dropout,
103
+ attention_dropout=self.attention_dropout,
104
+ max_position_embeddings=self.max_position_embeddings,
105
+ initializer_range=self.initializer_range,
106
+ bos_token_id=self.bos_token_id,
107
+ )
108
+
109
+ def create_and_check_model(self, config, input_ids, input_mask):
110
+ model = BlipTextModel(config=config)
111
+ model.to(torch_device)
112
+ model.eval()
113
+ with torch.no_grad():
114
+ result = model(input_ids, attention_mask=input_mask)
115
+ result = model(input_ids)
116
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
117
+ self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
118
+
119
+ def prepare_config_and_inputs_for_common(self):
120
+ config_and_inputs = self.prepare_config_and_inputs()
121
+ config, input_ids, input_mask = config_and_inputs
122
+ inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
123
+ return config, inputs_dict
124
+
125
+
126
+ @require_torch
127
+ class BlipTextModelTest(ModelTesterMixin, unittest.TestCase):
128
+ all_model_classes = (BlipTextModel,) if is_torch_available() else ()
129
+ fx_compatible = False
130
+ test_pruning = False
131
+ test_head_masking = False
132
+
133
+ def setUp(self):
134
+ self.model_tester = BlipTextModelTester(self)
135
+ self.config_tester = ConfigTester(self, config_class=BlipTextConfig, hidden_size=37)
136
+
137
+ def test_config(self):
138
+ self.config_tester.run_common_tests()
139
+
140
+ def test_model(self):
141
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
142
+ self.model_tester.create_and_check_model(*config_and_inputs)
143
+
144
+ @unittest.skip
145
+ def test_training(self):
146
+ pass
147
+
148
+ @unittest.skip
149
+ def test_training_gradient_checkpointing(self):
150
+ pass
151
+
152
+ @unittest.skip(
153
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
154
+ )
155
+ def test_training_gradient_checkpointing_use_reentrant(self):
156
+ pass
157
+
158
+ @unittest.skip(
159
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
160
+ )
161
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
162
+ pass
163
+
164
+ @unittest.skip(reason="Blip does not use inputs_embeds")
165
+ def test_inputs_embeds(self):
166
+ pass
167
+
168
+ @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING")
169
+ def test_save_load_fast_init_from_base(self):
170
+ pass
171
+
172
+ @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING")
173
+ def test_save_load_fast_init_to_base(self):
174
+ pass
175
+
176
+ @slow
177
+ def test_model_from_pretrained(self):
178
+ model_name = "Salesforce/blip-vqa-base"
179
+ model = BlipTextModel.from_pretrained(model_name)
180
+ self.assertIsNotNone(model)
181
+
182
+ def test_pt_tf_model_equivalence(self):
183
+ super().test_pt_tf_model_equivalence(allow_missing_keys=True)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blip/test_modeling_tf_blip.py ADDED
@@ -0,0 +1,901 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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
+ """Testing suite for the TensorFlow Blip model."""
16
+
17
+ from __future__ import annotations
18
+
19
+ import inspect
20
+ import tempfile
21
+ import unittest
22
+
23
+ import numpy as np
24
+ import requests
25
+
26
+ from transformers import BlipConfig, BlipTextConfig, BlipVisionConfig
27
+ from transformers.testing_utils import require_tf, require_vision, slow
28
+ from transformers.utils import is_tf_available, is_vision_available
29
+
30
+ from ...test_configuration_common import ConfigTester
31
+ from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
32
+ from ...test_pipeline_mixin import PipelineTesterMixin
33
+
34
+
35
+ if is_tf_available():
36
+ import tensorflow as tf
37
+
38
+ from transformers import (
39
+ TFBlipForConditionalGeneration,
40
+ TFBlipForImageTextRetrieval,
41
+ TFBlipForQuestionAnswering,
42
+ TFBlipModel,
43
+ TFBlipTextModel,
44
+ TFBlipVisionModel,
45
+ )
46
+ from transformers.modeling_tf_utils import keras
47
+
48
+
49
+ if is_vision_available():
50
+ from PIL import Image
51
+
52
+ from transformers import BlipProcessor
53
+
54
+
55
+ class TFBlipVisionModelTester:
56
+ def __init__(
57
+ self,
58
+ parent,
59
+ batch_size=12,
60
+ image_size=30,
61
+ patch_size=2,
62
+ num_channels=3,
63
+ is_training=True,
64
+ hidden_size=32,
65
+ projection_dim=32,
66
+ num_hidden_layers=2,
67
+ num_attention_heads=4,
68
+ intermediate_size=37,
69
+ dropout=0.1,
70
+ attention_dropout=0.1,
71
+ initializer_range=1e-10,
72
+ scope=None,
73
+ ):
74
+ self.parent = parent
75
+ self.batch_size = batch_size
76
+ self.image_size = image_size
77
+ self.patch_size = patch_size
78
+ self.num_channels = num_channels
79
+ self.is_training = is_training
80
+ self.hidden_size = hidden_size
81
+ self.projection_dim = projection_dim
82
+ self.num_hidden_layers = num_hidden_layers
83
+ self.num_attention_heads = num_attention_heads
84
+ self.intermediate_size = intermediate_size
85
+ self.dropout = dropout
86
+ self.attention_dropout = attention_dropout
87
+ self.initializer_range = initializer_range
88
+ self.scope = scope
89
+
90
+ # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
91
+ num_patches = (image_size // patch_size) ** 2
92
+ self.seq_length = num_patches + 1
93
+
94
+ def prepare_config_and_inputs(self):
95
+ pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
96
+ config = self.get_config()
97
+
98
+ return config, pixel_values
99
+
100
+ def get_config(self):
101
+ return BlipVisionConfig(
102
+ image_size=self.image_size,
103
+ patch_size=self.patch_size,
104
+ num_channels=self.num_channels,
105
+ hidden_size=self.hidden_size,
106
+ projection_dim=self.projection_dim,
107
+ num_hidden_layers=self.num_hidden_layers,
108
+ num_attention_heads=self.num_attention_heads,
109
+ intermediate_size=self.intermediate_size,
110
+ dropout=self.dropout,
111
+ attention_dropout=self.attention_dropout,
112
+ initializer_range=self.initializer_range,
113
+ )
114
+
115
+ def create_and_check_model(self, config, pixel_values):
116
+ model = TFBlipVisionModel(config=config)
117
+ result = model(pixel_values)
118
+ # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
119
+ image_size = (self.image_size, self.image_size)
120
+ patch_size = (self.patch_size, self.patch_size)
121
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
122
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, num_patches + 1, self.hidden_size))
123
+ self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
124
+
125
+ def prepare_config_and_inputs_for_common(self):
126
+ config_and_inputs = self.prepare_config_and_inputs()
127
+ config, pixel_values = config_and_inputs
128
+ inputs_dict = {"pixel_values": pixel_values}
129
+ return config, inputs_dict
130
+
131
+
132
+ @require_tf
133
+ class TFBlipVisionModelTest(TFModelTesterMixin, unittest.TestCase):
134
+ """
135
+ Here we also overwrite some of the tests of test_modeling_common.py, as Blip does not use input_ids, inputs_embeds,
136
+ attention_mask and seq_length.
137
+ """
138
+
139
+ all_model_classes = (TFBlipVisionModel,) if is_tf_available() else ()
140
+ fx_compatible = False
141
+ test_pruning = False
142
+ test_resize_embeddings = False
143
+ test_head_masking = False
144
+ test_onnx = False
145
+
146
+ def setUp(self):
147
+ self.model_tester = TFBlipVisionModelTester(self)
148
+ self.config_tester = ConfigTester(self, config_class=BlipVisionConfig, has_text_modality=False, hidden_size=37)
149
+
150
+ def test_config(self):
151
+ self.config_tester.run_common_tests()
152
+
153
+ @unittest.skip(reason="Blip does not use inputs_embeds")
154
+ def test_inputs_embeds(self):
155
+ pass
156
+
157
+ def test_forward_signature(self):
158
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
159
+
160
+ for model_class in self.all_model_classes:
161
+ model = model_class(config)
162
+ signature = inspect.signature(model.call)
163
+ # signature.parameters is an OrderedDict => so arg_names order is deterministic
164
+ arg_names = [*signature.parameters.keys()]
165
+
166
+ expected_arg_names = ["pixel_values"]
167
+ self.assertListEqual(arg_names[:1], expected_arg_names)
168
+
169
+ def test_model_common_attributes(self):
170
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
171
+
172
+ for model_class in self.all_model_classes:
173
+ model = model_class(config)
174
+ self.assertIsInstance(model.get_input_embeddings(), (keras.layers.Layer))
175
+ x = model.get_output_embeddings()
176
+ self.assertTrue(x is None or isinstance(x, keras.layers.Layer))
177
+
178
+ def test_model(self):
179
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
180
+ self.model_tester.create_and_check_model(*config_and_inputs)
181
+
182
+ @unittest.skip(reason="BlipVisionModel has no base class and is not available in MODEL_MAPPING")
183
+ def test_save_load_fast_init_from_base(self):
184
+ pass
185
+
186
+ @unittest.skip(reason="BlipVisionModel has no base class and is not available in MODEL_MAPPING")
187
+ def test_save_load_fast_init_to_base(self):
188
+ pass
189
+
190
+ @slow
191
+ def test_model_from_pretrained(self):
192
+ model_name = "Salesforce/blip-vqa-base"
193
+ model = TFBlipVisionModel.from_pretrained(model_name)
194
+ self.assertIsNotNone(model)
195
+
196
+
197
+ class TFBlipTextModelTester:
198
+ def __init__(
199
+ self,
200
+ parent,
201
+ batch_size=12,
202
+ seq_length=7,
203
+ is_training=True,
204
+ use_input_mask=True,
205
+ use_labels=True,
206
+ vocab_size=99,
207
+ hidden_size=32,
208
+ projection_dim=32,
209
+ num_hidden_layers=2,
210
+ num_attention_heads=4,
211
+ intermediate_size=37,
212
+ dropout=0.1,
213
+ attention_dropout=0.1,
214
+ max_position_embeddings=512,
215
+ initializer_range=0.02,
216
+ bos_token_id=0,
217
+ scope=None,
218
+ ):
219
+ self.parent = parent
220
+ self.batch_size = batch_size
221
+ self.seq_length = seq_length
222
+ self.is_training = is_training
223
+ self.use_input_mask = use_input_mask
224
+ self.use_labels = use_labels
225
+ self.vocab_size = vocab_size
226
+ self.hidden_size = hidden_size
227
+ self.projection_dim = projection_dim
228
+ self.num_hidden_layers = num_hidden_layers
229
+ self.num_attention_heads = num_attention_heads
230
+ self.intermediate_size = intermediate_size
231
+ self.dropout = dropout
232
+ self.attention_dropout = attention_dropout
233
+ self.max_position_embeddings = max_position_embeddings
234
+ self.initializer_range = initializer_range
235
+ self.scope = scope
236
+ self.bos_token_id = bos_token_id
237
+
238
+ def prepare_config_and_inputs(self):
239
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
240
+
241
+ input_mask = None
242
+ if self.use_input_mask:
243
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
244
+
245
+ if input_mask is not None:
246
+ input_mask = input_mask.numpy()
247
+ batch_size, seq_length = input_mask.shape
248
+ rnd_start_indices = np.random.randint(1, seq_length - 1, size=(batch_size,))
249
+ for batch_idx, start_index in enumerate(rnd_start_indices):
250
+ input_mask[batch_idx, :start_index] = 1
251
+ input_mask[batch_idx, start_index:] = 0
252
+ input_mask = tf.convert_to_tensor(input_mask)
253
+
254
+ config = self.get_config()
255
+
256
+ return config, input_ids, input_mask
257
+
258
+ def get_config(self):
259
+ return BlipTextConfig(
260
+ vocab_size=self.vocab_size,
261
+ hidden_size=self.hidden_size,
262
+ projection_dim=self.projection_dim,
263
+ num_hidden_layers=self.num_hidden_layers,
264
+ num_attention_heads=self.num_attention_heads,
265
+ intermediate_size=self.intermediate_size,
266
+ dropout=self.dropout,
267
+ attention_dropout=self.attention_dropout,
268
+ max_position_embeddings=self.max_position_embeddings,
269
+ initializer_range=self.initializer_range,
270
+ bos_token_id=self.bos_token_id,
271
+ )
272
+
273
+ def create_and_check_model(self, config, input_ids, input_mask):
274
+ model = TFBlipTextModel(config=config)
275
+ result = model(input_ids, attention_mask=input_mask, training=False)
276
+ result = model(input_ids, training=False)
277
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
278
+ self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
279
+
280
+ def prepare_config_and_inputs_for_common(self):
281
+ config_and_inputs = self.prepare_config_and_inputs()
282
+ config, input_ids, input_mask = config_and_inputs
283
+ inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
284
+ return config, inputs_dict
285
+
286
+
287
+ @require_tf
288
+ class TFBlipTextModelTest(TFModelTesterMixin, unittest.TestCase):
289
+ all_model_classes = (TFBlipTextModel,) if is_tf_available() else ()
290
+ fx_compatible = False
291
+ test_pruning = False
292
+ test_head_masking = False
293
+ test_onnx = False
294
+
295
+ def setUp(self):
296
+ self.model_tester = TFBlipTextModelTester(self)
297
+ self.config_tester = ConfigTester(self, config_class=BlipTextConfig, hidden_size=37)
298
+
299
+ def test_config(self):
300
+ self.config_tester.run_common_tests()
301
+
302
+ def test_model(self):
303
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
304
+ self.model_tester.create_and_check_model(*config_and_inputs)
305
+
306
+ @unittest.skip(reason="Blip does not use inputs_embeds")
307
+ def test_inputs_embeds(self):
308
+ pass
309
+
310
+ @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING")
311
+ def test_save_load_fast_init_from_base(self):
312
+ pass
313
+
314
+ @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING")
315
+ def test_save_load_fast_init_to_base(self):
316
+ pass
317
+
318
+ @slow
319
+ def test_model_from_pretrained(self):
320
+ model_name = "Salesforce/blip-vqa-base"
321
+ model = TFBlipTextModel.from_pretrained(model_name)
322
+ self.assertIsNotNone(model)
323
+
324
+ def test_pt_tf_model_equivalence(self, allow_missing_keys=True):
325
+ super().test_pt_tf_model_equivalence(allow_missing_keys=allow_missing_keys)
326
+
327
+
328
+ class TFBlipModelTester:
329
+ def __init__(self, parent, text_kwargs=None, vision_kwargs=None, is_training=True):
330
+ if text_kwargs is None:
331
+ text_kwargs = {}
332
+ if vision_kwargs is None:
333
+ vision_kwargs = {}
334
+
335
+ self.parent = parent
336
+ self.text_model_tester = TFBlipTextModelTester(parent, **text_kwargs)
337
+ self.vision_model_tester = TFBlipVisionModelTester(parent, **vision_kwargs)
338
+ self.is_training = is_training
339
+
340
+ def prepare_config_and_inputs(self):
341
+ text_config, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs()
342
+ vision_config, pixel_values = self.vision_model_tester.prepare_config_and_inputs()
343
+
344
+ config = self.get_config()
345
+
346
+ return config, input_ids, attention_mask, pixel_values
347
+
348
+ def get_config(self):
349
+ return BlipConfig.from_text_vision_configs(
350
+ self.text_model_tester.get_config(), self.vision_model_tester.get_config(), projection_dim=64
351
+ )
352
+
353
+ def create_and_check_model(self, config, input_ids, attention_mask, pixel_values):
354
+ model = TFBlipModel(config)
355
+ result = model(input_ids, pixel_values, attention_mask, training=False)
356
+ self.parent.assertEqual(
357
+ result.logits_per_image.shape, (self.vision_model_tester.batch_size, self.text_model_tester.batch_size)
358
+ )
359
+ self.parent.assertEqual(
360
+ result.logits_per_text.shape, (self.text_model_tester.batch_size, self.vision_model_tester.batch_size)
361
+ )
362
+
363
+ def prepare_config_and_inputs_for_common(self):
364
+ config_and_inputs = self.prepare_config_and_inputs()
365
+ config, input_ids, attention_mask, pixel_values = config_and_inputs
366
+ inputs_dict = {
367
+ "input_ids": input_ids,
368
+ "attention_mask": attention_mask,
369
+ "pixel_values": pixel_values,
370
+ "return_loss": True,
371
+ }
372
+ return config, inputs_dict
373
+
374
+
375
+ @require_tf
376
+ class TFBlipModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
377
+ all_model_classes = (TFBlipModel,) if is_tf_available() else ()
378
+ pipeline_model_mapping = (
379
+ {"feature-extraction": TFBlipModel, "image-to-text": TFBlipForConditionalGeneration}
380
+ if is_tf_available()
381
+ else {}
382
+ )
383
+ test_head_masking = False
384
+ test_pruning = False
385
+ test_resize_embeddings = False
386
+ test_attention_outputs = False
387
+ test_onnx = False
388
+
389
+ def setUp(self):
390
+ self.model_tester = TFBlipModelTester(self)
391
+
392
+ def test_model(self):
393
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
394
+ self.model_tester.create_and_check_model(*config_and_inputs)
395
+
396
+ @unittest.skip(reason="Hidden_states is tested in individual model tests")
397
+ def test_hidden_states_output(self):
398
+ pass
399
+
400
+ @unittest.skip(reason="Inputs_embeds is tested in individual model tests")
401
+ def test_inputs_embeds(self):
402
+ pass
403
+
404
+ @unittest.skip(reason="Retain_grad is tested in individual model tests")
405
+ def test_retain_grad_hidden_states_attentions(self):
406
+ pass
407
+
408
+ @unittest.skip(reason="BlipModel does not have input/output embeddings")
409
+ def test_model_common_attributes(self):
410
+ pass
411
+
412
+ def test_load_vision_text_config(self):
413
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
414
+
415
+ # Save BlipConfig and check if we can load BlipVisionConfig from it
416
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
417
+ config.save_pretrained(tmp_dir_name)
418
+ vision_config = BlipVisionConfig.from_pretrained(tmp_dir_name)
419
+ self.assertDictEqual(config.vision_config.to_dict(), vision_config.to_dict())
420
+
421
+ # Save BlipConfig and check if we can load BlipTextConfig from it
422
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
423
+ config.save_pretrained(tmp_dir_name)
424
+ text_config = BlipTextConfig.from_pretrained(tmp_dir_name)
425
+ self.assertDictEqual(config.text_config.to_dict(), text_config.to_dict())
426
+
427
+ @slow
428
+ def test_model_from_pretrained(self):
429
+ model_name = "Salesforce/blip-vqa-base"
430
+ model = TFBlipModel.from_pretrained(model_name)
431
+ self.assertIsNotNone(model)
432
+
433
+ def test_pt_tf_model_equivalence(self, allow_missing_keys=True):
434
+ super().test_pt_tf_model_equivalence(allow_missing_keys=allow_missing_keys)
435
+
436
+ @unittest.skip("Matt: Re-enable this test when we have a proper export function for TF models.")
437
+ def test_saved_model_creation(self):
438
+ # This fails because the if return_loss: conditional can return None or a Tensor and TF hates that.
439
+ # We could fix that by setting the bool to a constant when exporting, but that requires a dedicated export
440
+ # function that we don't have yet.
441
+ pass
442
+
443
+
444
+ class BlipTextRetrievalModelTester:
445
+ def __init__(self, parent, text_kwargs=None, vision_kwargs=None, is_training=True):
446
+ if text_kwargs is None:
447
+ text_kwargs = {}
448
+ if vision_kwargs is None:
449
+ vision_kwargs = {}
450
+
451
+ self.parent = parent
452
+ self.text_model_tester = TFBlipTextModelTester(parent, **text_kwargs)
453
+ self.vision_model_tester = TFBlipVisionModelTester(parent, **vision_kwargs)
454
+ self.is_training = is_training
455
+
456
+ def prepare_config_and_inputs(self):
457
+ text_config, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs()
458
+ vision_config, pixel_values = self.vision_model_tester.prepare_config_and_inputs()
459
+
460
+ config = self.get_config()
461
+
462
+ return config, input_ids, attention_mask, pixel_values
463
+
464
+ def get_config(self):
465
+ return BlipConfig.from_text_vision_configs(
466
+ self.text_model_tester.get_config(), self.vision_model_tester.get_config(), projection_dim=64
467
+ )
468
+
469
+ def create_and_check_model(self, config, input_ids, attention_mask, pixel_values):
470
+ model = TFBlipModel(config)
471
+ result = model(input_ids, pixel_values, attention_mask, training=False)
472
+ self.parent.assertEqual(
473
+ result.logits_per_image.shape, (self.vision_model_tester.batch_size, self.text_model_tester.batch_size)
474
+ )
475
+ self.parent.assertEqual(
476
+ result.logits_per_text.shape, (self.text_model_tester.batch_size, self.vision_model_tester.batch_size)
477
+ )
478
+
479
+ def prepare_config_and_inputs_for_common(self):
480
+ config_and_inputs = self.prepare_config_and_inputs()
481
+ config, input_ids, attention_mask, pixel_values = config_and_inputs
482
+ inputs_dict = {
483
+ "input_ids": input_ids,
484
+ "attention_mask": attention_mask,
485
+ "pixel_values": pixel_values,
486
+ }
487
+ return config, inputs_dict
488
+
489
+
490
+ class BlipTextImageModelsModelTester:
491
+ def __init__(self, parent, text_kwargs=None, vision_kwargs=None, is_training=True):
492
+ if text_kwargs is None:
493
+ text_kwargs = {}
494
+ if vision_kwargs is None:
495
+ vision_kwargs = {}
496
+
497
+ self.parent = parent
498
+ self.text_model_tester = TFBlipTextModelTester(parent, **text_kwargs)
499
+ self.vision_model_tester = TFBlipVisionModelTester(parent, **vision_kwargs)
500
+ self.is_training = is_training
501
+
502
+ def prepare_config_and_inputs(self):
503
+ text_config, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs()
504
+ vision_config, pixel_values = self.vision_model_tester.prepare_config_and_inputs()
505
+
506
+ config = self.get_config()
507
+
508
+ return config, input_ids, attention_mask, pixel_values
509
+
510
+ def get_config(self):
511
+ return BlipConfig.from_text_vision_configs(
512
+ self.text_model_tester.get_config(), self.vision_model_tester.get_config(), projection_dim=64
513
+ )
514
+
515
+ def create_and_check_model(self, config, input_ids, attention_mask, pixel_values):
516
+ model = TFBlipModel(config)
517
+ result = model(input_ids, pixel_values, attention_mask, training=False)
518
+ self.parent.assertEqual(
519
+ result.logits_per_image.shape, (self.vision_model_tester.batch_size, self.text_model_tester.batch_size)
520
+ )
521
+ self.parent.assertEqual(
522
+ result.logits_per_text.shape, (self.text_model_tester.batch_size, self.vision_model_tester.batch_size)
523
+ )
524
+
525
+ def prepare_config_and_inputs_for_common(self):
526
+ config_and_inputs = self.prepare_config_and_inputs()
527
+ config, input_ids, attention_mask, pixel_values = config_and_inputs
528
+ inputs_dict = {
529
+ "input_ids": input_ids,
530
+ "labels": input_ids,
531
+ "attention_mask": attention_mask,
532
+ "pixel_values": pixel_values,
533
+ }
534
+ return config, inputs_dict
535
+
536
+
537
+ class BlipVQAModelsModelTester:
538
+ def __init__(self, parent, text_kwargs=None, vision_kwargs=None, is_training=True):
539
+ if text_kwargs is None:
540
+ text_kwargs = {}
541
+ if vision_kwargs is None:
542
+ vision_kwargs = {}
543
+
544
+ self.parent = parent
545
+ self.text_model_tester = TFBlipTextModelTester(parent, **text_kwargs)
546
+ self.vision_model_tester = TFBlipVisionModelTester(parent, **vision_kwargs)
547
+ self.is_training = is_training
548
+
549
+ def prepare_config_and_inputs(self):
550
+ text_config, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs()
551
+ vision_config, pixel_values = self.vision_model_tester.prepare_config_and_inputs()
552
+
553
+ config = self.get_config()
554
+
555
+ return config, input_ids, attention_mask, pixel_values
556
+
557
+ def get_config(self):
558
+ return BlipConfig.from_text_vision_configs(
559
+ self.text_model_tester.get_config(), self.vision_model_tester.get_config(), projection_dim=64
560
+ )
561
+
562
+ def create_and_check_model(self, config, input_ids, attention_mask, pixel_values):
563
+ model = TFBlipModel(config)
564
+ result = model(input_ids, pixel_values, attention_mask, training=False)
565
+ self.parent.assertEqual(
566
+ result.logits_per_image.shape, (self.vision_model_tester.batch_size, self.text_model_tester.batch_size)
567
+ )
568
+ self.parent.assertEqual(
569
+ result.logits_per_text.shape, (self.text_model_tester.batch_size, self.vision_model_tester.batch_size)
570
+ )
571
+
572
+ def prepare_config_and_inputs_for_common(self):
573
+ config_and_inputs = self.prepare_config_and_inputs()
574
+ config, input_ids, attention_mask, pixel_values = config_and_inputs
575
+ inputs_dict = {
576
+ "input_ids": input_ids,
577
+ "decoder_input_ids": input_ids,
578
+ "labels": input_ids,
579
+ "attention_mask": attention_mask,
580
+ "pixel_values": pixel_values,
581
+ }
582
+ return config, inputs_dict
583
+
584
+
585
+ @require_tf
586
+ @require_vision
587
+ class TFBlipVQAModelTest(TFModelTesterMixin, unittest.TestCase):
588
+ all_model_classes = (TFBlipForQuestionAnswering,) if is_tf_available() else ()
589
+ test_head_masking = False
590
+ test_pruning = False
591
+ test_resize_embeddings = False
592
+ test_attention_outputs = False
593
+ test_onnx = False
594
+
595
+ def setUp(self):
596
+ self.model_tester = BlipVQAModelsModelTester(self)
597
+
598
+ def _prepare_inputs_for_vqa(self):
599
+ _, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
600
+ inputs_dict["labels"] = inputs_dict["input_ids"]
601
+ inputs_dict["decoder_input_ids"] = inputs_dict["input_ids"]
602
+ inputs_dict.pop("return_loss")
603
+ return inputs_dict
604
+
605
+ def test_class_name_consistency(self):
606
+ """
607
+ Tests that all VQA models have a class name that ends with "ForQuestionAnswering"
608
+ """
609
+ for model_class in self.all_model_classes:
610
+ model = model_class(self.model_tester.get_config())
611
+ self.assertTrue(
612
+ model.__class__.__name__.endswith("ForQuestionAnswering"),
613
+ f"Class name should end with 'ForVisualQuestionAnswering' got {model.__class__.__name__}",
614
+ )
615
+
616
+ def test_training(self):
617
+ """
618
+ Tests that all VQA models can be trained on a single batch
619
+ """
620
+ for model_class in self.all_model_classes:
621
+ model = model_class(self.model_tester.get_config())
622
+ loss = model(**self.model_tester.prepare_config_and_inputs_for_common()[1], training=True).loss
623
+
624
+ self.assertIsNotNone(loss, "Loss should not be None")
625
+
626
+ @unittest.skip(reason="Hidden_states is tested in individual model tests")
627
+ def test_hidden_states_output(self):
628
+ pass
629
+
630
+ @unittest.skip(reason="Inputs_embeds is tested in individual model tests")
631
+ def test_inputs_embeds(self):
632
+ pass
633
+
634
+ @unittest.skip(reason="Retain_grad is tested in individual model tests")
635
+ def test_retain_grad_hidden_states_attentions(self):
636
+ pass
637
+
638
+ @unittest.skip(reason="BlipModel does not have input/output embeddings")
639
+ def test_model_common_attributes(self):
640
+ pass
641
+
642
+ @unittest.skip(reason="Tested in individual model tests")
643
+ def test_compile_tf_model(self):
644
+ pass
645
+
646
+ @unittest.skip("Model doesn't have a clean loss output.")
647
+ def test_keras_fit(self):
648
+ pass
649
+
650
+
651
+ @require_tf
652
+ class TFBlipTextRetrievalModelTest(TFModelTesterMixin, unittest.TestCase):
653
+ all_model_classes = (TFBlipForImageTextRetrieval,) if is_tf_available() else ()
654
+ test_head_masking = False
655
+ test_pruning = False
656
+ test_resize_embeddings = False
657
+ test_attention_outputs = False
658
+ test_onnx = False
659
+
660
+ def setUp(self):
661
+ self.model_tester = BlipTextRetrievalModelTester(self)
662
+
663
+ def test_model(self):
664
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
665
+ self.model_tester.create_and_check_model(*config_and_inputs)
666
+
667
+ @unittest.skip(reason="Hidden_states is tested in individual model tests")
668
+ def test_hidden_states_output(self):
669
+ pass
670
+
671
+ @unittest.skip(reason="Inputs_embeds is tested in individual model tests")
672
+ def test_inputs_embeds(self):
673
+ pass
674
+
675
+ @unittest.skip(reason="Retain_grad is tested in individual model tests")
676
+ def test_retain_grad_hidden_states_attentions(self):
677
+ pass
678
+
679
+ @unittest.skip(reason="BlipModel does not have input/output embeddings")
680
+ def test_model_common_attributes(self):
681
+ pass
682
+
683
+ def test_training(self):
684
+ if not self.model_tester.is_training:
685
+ return
686
+
687
+ for model_class in self.all_model_classes[:-1]:
688
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
689
+ config.return_dict = True
690
+
691
+ model = model_class(config)
692
+ inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
693
+
694
+ # hardcode labels to be the same as input_ids
695
+ inputs["labels"] = inputs["input_ids"]
696
+
697
+ loss = model(**inputs, training=True).loss
698
+ self.assertTrue(loss is not None)
699
+
700
+ def test_load_vision_text_config(self):
701
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
702
+
703
+ # Save BlipConfig and check if we can load BlipVisionConfig from it
704
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
705
+ config.save_pretrained(tmp_dir_name)
706
+ vision_config = BlipVisionConfig.from_pretrained(tmp_dir_name)
707
+ self.assertDictEqual(config.vision_config.to_dict(), vision_config.to_dict())
708
+
709
+ # Save BlipConfig and check if we can load BlipTextConfig from it
710
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
711
+ config.save_pretrained(tmp_dir_name)
712
+ text_config = BlipTextConfig.from_pretrained(tmp_dir_name)
713
+ self.assertDictEqual(config.text_config.to_dict(), text_config.to_dict())
714
+
715
+ @slow
716
+ def test_model_from_pretrained(self):
717
+ model_name = "Salesforce/blip-vqa-base"
718
+ model = TFBlipModel.from_pretrained(model_name)
719
+ self.assertIsNotNone(model)
720
+
721
+ @unittest.skip(reason="Tested in individual model tests")
722
+ def test_compile_tf_model(self):
723
+ pass
724
+
725
+ @unittest.skip("Model doesn't have a clean loss output.")
726
+ def test_keras_fit(self):
727
+ pass
728
+
729
+
730
+ @require_tf
731
+ class TFBlipTextImageModelTest(TFModelTesterMixin, unittest.TestCase):
732
+ all_model_classes = (TFBlipForConditionalGeneration,) if is_tf_available() else ()
733
+ test_head_masking = False
734
+ test_pruning = False
735
+ test_resize_embeddings = False
736
+ test_attention_outputs = False
737
+ test_onnx = False
738
+
739
+ def setUp(self):
740
+ self.model_tester = BlipTextImageModelsModelTester(self)
741
+
742
+ def test_model(self):
743
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
744
+ self.model_tester.create_and_check_model(*config_and_inputs)
745
+
746
+ @unittest.skip(reason="Hidden_states is tested in individual model tests")
747
+ def test_hidden_states_output(self):
748
+ pass
749
+
750
+ @unittest.skip(reason="Inputs_embeds is tested in individual model tests")
751
+ def test_inputs_embeds(self):
752
+ pass
753
+
754
+ def test_forward_signature(self):
755
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
756
+
757
+ for model_class in self.all_model_classes:
758
+ model = model_class(config)
759
+ signature = inspect.signature(model.call)
760
+ # signature.parameters is an OrderedDict => so arg_names order is deterministic
761
+ arg_names = [*signature.parameters.keys()]
762
+
763
+ if model.config.is_encoder_decoder:
764
+ expected_arg_names = [
765
+ "input_ids",
766
+ "attention_mask",
767
+ "decoder_input_ids",
768
+ "decoder_attention_mask",
769
+ ]
770
+ expected_arg_names.extend(
771
+ ["head_mask", "decoder_head_mask", "cross_attn_head_mask", "encoder_outputs"]
772
+ if "head_mask" and "decoder_head_mask" and "cross_attn_head_mask" in arg_names
773
+ else ["encoder_outputs"]
774
+ )
775
+ self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names)
776
+ else:
777
+ expected_arg_names = (
778
+ ["input_ids"] if model_class != TFBlipForConditionalGeneration else ["pixel_values"]
779
+ )
780
+ self.assertListEqual(arg_names[:1], expected_arg_names)
781
+
782
+ @unittest.skip(reason="Tested in individual model tests")
783
+ def test_compile_tf_model(self):
784
+ pass
785
+
786
+ @unittest.skip("Has some odd input names!")
787
+ def test_keras_fit(self):
788
+ pass
789
+
790
+ @unittest.skip(reason="Retain_grad is tested in individual model tests")
791
+ def test_retain_grad_hidden_states_attentions(self):
792
+ pass
793
+
794
+ @unittest.skip(reason="BlipModel does not have input/output embeddings")
795
+ def test_model_common_attributes(self):
796
+ pass
797
+
798
+ def test_training(self):
799
+ if not self.model_tester.is_training:
800
+ return
801
+
802
+ for model_class in self.all_model_classes[:-1]:
803
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
804
+ config.return_dict = True
805
+
806
+ model = model_class(config)
807
+ inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
808
+
809
+ # hardcode labels to be the same as input_ids
810
+ inputs["labels"] = inputs["input_ids"]
811
+
812
+ loss = model(**inputs, training=True).loss
813
+ self.assertIsNotNone(loss)
814
+
815
+ def test_load_vision_text_config(self):
816
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
817
+
818
+ # Save BlipConfig and check if we can load BlipVisionConfig from it
819
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
820
+ config.save_pretrained(tmp_dir_name)
821
+ vision_config = BlipVisionConfig.from_pretrained(tmp_dir_name)
822
+ self.assertDictEqual(config.vision_config.to_dict(), vision_config.to_dict())
823
+
824
+ # Save BlipConfig and check if we can load BlipTextConfig from it
825
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
826
+ config.save_pretrained(tmp_dir_name)
827
+ text_config = BlipTextConfig.from_pretrained(tmp_dir_name)
828
+ self.assertDictEqual(config.text_config.to_dict(), text_config.to_dict())
829
+
830
+ @slow
831
+ def test_model_from_pretrained(self):
832
+ model_name = "Salesforce/blip-vqa-base"
833
+ model = TFBlipModel.from_pretrained(model_name)
834
+ self.assertIsNotNone(model)
835
+
836
+
837
+ # We will verify our results on an image of cute cats
838
+ def prepare_img():
839
+ url = "https://huggingface.co/hf-internal-testing/blip-test-image/resolve/main/demo.jpg"
840
+ im = Image.open(requests.get(url, stream=True).raw)
841
+ return im
842
+
843
+
844
+ @require_vision
845
+ @require_tf
846
+ @slow
847
+ class TFBlipModelIntegrationTest(unittest.TestCase):
848
+ def test_inference_image_captioning(self):
849
+ model = TFBlipForConditionalGeneration.from_pretrained("Salesforce/blip-image-captioning-base")
850
+ processor = BlipProcessor.from_pretrained("Salesforce/blip-image-captioning-base")
851
+ image = prepare_img()
852
+
853
+ # image only
854
+ inputs = processor(images=image, return_tensors="tf")
855
+
856
+ predictions = model.generate(**inputs)
857
+
858
+ # Test output
859
+ self.assertEqual(
860
+ predictions[0].numpy().tolist(), [30522, 1037, 2450, 3564, 2006, 1996, 3509, 2007, 2014, 3899, 102]
861
+ )
862
+
863
+ # image and context
864
+ context = ["a picture of"]
865
+ inputs = processor(images=image, text=context, return_tensors="tf")
866
+
867
+ predictions = model.generate(**inputs)
868
+
869
+ # Test output
870
+ self.assertEqual(
871
+ predictions[0].numpy().tolist(),
872
+ [30522, 1037, 3861, 1997, 1037, 2450, 1998, 2014, 3899, 2006, 1996, 3509, 102],
873
+ )
874
+
875
+ def test_inference_vqa(self):
876
+ model = TFBlipForQuestionAnswering.from_pretrained("Salesforce/blip-vqa-base")
877
+ processor = BlipProcessor.from_pretrained("Salesforce/blip-vqa-base")
878
+
879
+ image = prepare_img()
880
+ text = "how many dogs are in the picture?"
881
+ inputs = processor(image, text=text, return_tensors="tf")
882
+ out = model.generate(**inputs)
883
+
884
+ # Test output
885
+ self.assertEqual(out[0].numpy().tolist(), [30522, 1015, 102])
886
+
887
+ def test_inference_itm(self):
888
+ model = TFBlipForImageTextRetrieval.from_pretrained("Salesforce/blip-itm-base-coco")
889
+ processor = BlipProcessor.from_pretrained("Salesforce/blip-itm-base-coco")
890
+
891
+ image = prepare_img()
892
+ text = "A woman and her dog sitting in a beach"
893
+
894
+ inputs = processor(image, text, return_tensors="tf")
895
+
896
+ out_itm = model(**inputs)
897
+ out = model(**inputs, use_itm_head=False, training=False)
898
+
899
+ expected_scores = tf.convert_to_tensor([[0.0029, 0.9971]])
900
+ self.assertTrue(np.allclose(tf.nn.softmax(out_itm[0]).numpy(), expected_scores, rtol=1e-3, atol=1e-3))
901
+ self.assertTrue(np.allclose(out[0], tf.convert_to_tensor([[0.5162]]), rtol=1e-3, atol=1e-3))
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blip/test_modeling_tf_blip_text.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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
+ """Testing suite for the TensorFlow Blip model."""
16
+
17
+ from __future__ import annotations
18
+
19
+ import unittest
20
+
21
+ import numpy as np
22
+
23
+ from transformers import BlipTextConfig
24
+ from transformers.testing_utils import require_tf, slow
25
+ from transformers.utils import is_tf_available
26
+
27
+ from ...test_configuration_common import ConfigTester
28
+ from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
29
+
30
+
31
+ if is_tf_available():
32
+ import tensorflow as tf
33
+
34
+ from transformers import TFBlipTextModel
35
+
36
+
37
+ class BlipTextModelTester:
38
+ def __init__(
39
+ self,
40
+ parent,
41
+ batch_size=12,
42
+ seq_length=7,
43
+ is_training=True,
44
+ use_input_mask=True,
45
+ use_labels=True,
46
+ vocab_size=99,
47
+ hidden_size=32,
48
+ projection_dim=32,
49
+ num_hidden_layers=2,
50
+ num_attention_heads=4,
51
+ intermediate_size=37,
52
+ dropout=0.1,
53
+ attention_dropout=0.1,
54
+ max_position_embeddings=512,
55
+ initializer_range=0.02,
56
+ bos_token_id=0,
57
+ scope=None,
58
+ ):
59
+ self.parent = parent
60
+ self.batch_size = batch_size
61
+ self.seq_length = seq_length
62
+ self.is_training = is_training
63
+ self.use_input_mask = use_input_mask
64
+ self.use_labels = use_labels
65
+ self.vocab_size = vocab_size
66
+ self.hidden_size = hidden_size
67
+ self.projection_dim = projection_dim
68
+ self.num_hidden_layers = num_hidden_layers
69
+ self.num_attention_heads = num_attention_heads
70
+ self.intermediate_size = intermediate_size
71
+ self.dropout = dropout
72
+ self.attention_dropout = attention_dropout
73
+ self.max_position_embeddings = max_position_embeddings
74
+ self.initializer_range = initializer_range
75
+ self.scope = scope
76
+ self.bos_token_id = bos_token_id
77
+
78
+ def prepare_config_and_inputs(self):
79
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
80
+
81
+ input_mask = None
82
+ if self.use_input_mask:
83
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
84
+
85
+ if input_mask is not None:
86
+ input_mask = input_mask.numpy()
87
+ batch_size, seq_length = input_mask.shape
88
+ rnd_start_indices = np.random.randint(1, seq_length - 1, size=(batch_size,))
89
+ for batch_idx, start_index in enumerate(rnd_start_indices):
90
+ input_mask[batch_idx, :start_index] = 1
91
+ input_mask[batch_idx, start_index:] = 0
92
+
93
+ config = self.get_config()
94
+
95
+ return config, input_ids, tf.convert_to_tensor(input_mask)
96
+
97
+ def get_config(self):
98
+ return BlipTextConfig(
99
+ vocab_size=self.vocab_size,
100
+ hidden_size=self.hidden_size,
101
+ projection_dim=self.projection_dim,
102
+ num_hidden_layers=self.num_hidden_layers,
103
+ num_attention_heads=self.num_attention_heads,
104
+ intermediate_size=self.intermediate_size,
105
+ dropout=self.dropout,
106
+ attention_dropout=self.attention_dropout,
107
+ max_position_embeddings=self.max_position_embeddings,
108
+ initializer_range=self.initializer_range,
109
+ bos_token_id=self.bos_token_id,
110
+ )
111
+
112
+ def create_and_check_model(self, config, input_ids, input_mask):
113
+ model = TFBlipTextModel(config=config)
114
+ result = model(input_ids, attention_mask=input_mask, training=False)
115
+ result = model(input_ids, training=False)
116
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
117
+ self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
118
+
119
+ def prepare_config_and_inputs_for_common(self):
120
+ config_and_inputs = self.prepare_config_and_inputs()
121
+ config, input_ids, input_mask = config_and_inputs
122
+ inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
123
+ return config, inputs_dict
124
+
125
+
126
+ @require_tf
127
+ class BlipTextModelTest(TFModelTesterMixin, unittest.TestCase):
128
+ all_model_classes = (TFBlipTextModel,) if is_tf_available() else ()
129
+ test_onnx = False
130
+ test_pruning = False
131
+ test_head_masking = False
132
+
133
+ def setUp(self):
134
+ self.model_tester = BlipTextModelTester(self)
135
+ self.config_tester = ConfigTester(self, config_class=BlipTextConfig, hidden_size=37)
136
+
137
+ def test_config(self):
138
+ self.config_tester.run_common_tests()
139
+
140
+ def test_model(self):
141
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
142
+ self.model_tester.create_and_check_model(*config_and_inputs)
143
+
144
+ def test_training(self):
145
+ pass
146
+
147
+ def test_training_gradient_checkpointing(self):
148
+ pass
149
+
150
+ @unittest.skip(
151
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
152
+ )
153
+ def test_training_gradient_checkpointing_use_reentrant(self):
154
+ pass
155
+
156
+ @unittest.skip(
157
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
158
+ )
159
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
160
+ pass
161
+
162
+ @unittest.skip(reason="Blip does not use inputs_embeds")
163
+ def test_inputs_embeds(self):
164
+ pass
165
+
166
+ @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING")
167
+ def test_save_load_fast_init_from_base(self):
168
+ pass
169
+
170
+ @unittest.skip(reason="BlipTextModel has no base class and is not available in MODEL_MAPPING")
171
+ def test_save_load_fast_init_to_base(self):
172
+ pass
173
+
174
+ @slow
175
+ def test_model_from_pretrained(self):
176
+ model_name = "Salesforce/blip-vqa-base"
177
+ model = TFBlipTextModel.from_pretrained(model_name)
178
+ self.assertIsNotNone(model)
179
+
180
+ def test_pt_tf_model_equivalence(self, allow_missing_keys=True):
181
+ super().test_pt_tf_model_equivalence(allow_missing_keys=allow_missing_keys)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blip/test_processor_blip.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import shutil
15
+ import tempfile
16
+ import unittest
17
+
18
+ import pytest
19
+
20
+ from transformers.testing_utils import require_torch, require_vision
21
+ from transformers.utils import is_vision_available
22
+
23
+ from ...test_processing_common import ProcessorTesterMixin
24
+
25
+
26
+ if is_vision_available():
27
+ from transformers import AutoProcessor, BertTokenizer, BlipImageProcessor, BlipProcessor, PreTrainedTokenizerFast
28
+
29
+
30
+ @require_vision
31
+ class BlipProcessorTest(ProcessorTesterMixin, unittest.TestCase):
32
+ processor_class = BlipProcessor
33
+
34
+ def setUp(self):
35
+ self.tmpdirname = tempfile.mkdtemp()
36
+
37
+ image_processor = BlipImageProcessor()
38
+ tokenizer = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-BertModel")
39
+
40
+ processor = BlipProcessor(image_processor, tokenizer)
41
+
42
+ processor.save_pretrained(self.tmpdirname)
43
+
44
+ def get_tokenizer(self, **kwargs):
45
+ return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).tokenizer
46
+
47
+ def get_image_processor(self, **kwargs):
48
+ return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).image_processor
49
+
50
+ def tearDown(self):
51
+ shutil.rmtree(self.tmpdirname)
52
+
53
+ def test_save_load_pretrained_additional_features(self):
54
+ processor = BlipProcessor(tokenizer=self.get_tokenizer(), image_processor=self.get_image_processor())
55
+ processor.save_pretrained(self.tmpdirname)
56
+
57
+ tokenizer_add_kwargs = self.get_tokenizer(bos_token="(BOS)", eos_token="(EOS)")
58
+ image_processor_add_kwargs = self.get_image_processor(do_normalize=False, padding_value=1.0)
59
+
60
+ processor = BlipProcessor.from_pretrained(
61
+ self.tmpdirname, bos_token="(BOS)", eos_token="(EOS)", do_normalize=False, padding_value=1.0
62
+ )
63
+
64
+ self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab())
65
+ self.assertIsInstance(processor.tokenizer, PreTrainedTokenizerFast)
66
+
67
+ self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string())
68
+ self.assertIsInstance(processor.image_processor, BlipImageProcessor)
69
+
70
+ def test_image_processor(self):
71
+ image_processor = self.get_image_processor()
72
+ tokenizer = self.get_tokenizer()
73
+
74
+ processor = BlipProcessor(tokenizer=tokenizer, image_processor=image_processor)
75
+
76
+ image_input = self.prepare_image_inputs()
77
+
78
+ input_feat_extract = image_processor(image_input, return_tensors="np")
79
+ input_processor = processor(images=image_input, return_tensors="np")
80
+
81
+ for key in input_feat_extract.keys():
82
+ self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2)
83
+
84
+ def test_tokenizer(self):
85
+ image_processor = self.get_image_processor()
86
+ tokenizer = self.get_tokenizer()
87
+
88
+ processor = BlipProcessor(tokenizer=tokenizer, image_processor=image_processor)
89
+
90
+ input_str = "lower newer"
91
+
92
+ encoded_processor = processor(text=input_str)
93
+
94
+ encoded_tok = tokenizer(input_str, return_token_type_ids=False)
95
+
96
+ for key in encoded_tok.keys():
97
+ self.assertListEqual(encoded_tok[key], encoded_processor[key])
98
+
99
+ def test_processor(self):
100
+ image_processor = self.get_image_processor()
101
+ tokenizer = self.get_tokenizer()
102
+
103
+ processor = BlipProcessor(tokenizer=tokenizer, image_processor=image_processor)
104
+
105
+ input_str = "lower newer"
106
+ image_input = self.prepare_image_inputs()
107
+
108
+ inputs = processor(text=input_str, images=image_input)
109
+
110
+ self.assertListEqual(list(inputs.keys()), ["pixel_values", "input_ids", "attention_mask"])
111
+
112
+ # test if it raises when no input is passed
113
+ with pytest.raises(ValueError):
114
+ processor()
115
+
116
+ def test_tokenizer_decode(self):
117
+ image_processor = self.get_image_processor()
118
+ tokenizer = self.get_tokenizer()
119
+
120
+ processor = BlipProcessor(tokenizer=tokenizer, image_processor=image_processor)
121
+
122
+ predicted_ids = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
123
+
124
+ decoded_processor = processor.batch_decode(predicted_ids)
125
+ decoded_tok = tokenizer.batch_decode(predicted_ids)
126
+
127
+ self.assertListEqual(decoded_tok, decoded_processor)
128
+
129
+ def test_model_input_names(self):
130
+ image_processor = self.get_image_processor()
131
+ tokenizer = self.get_tokenizer()
132
+
133
+ processor = BlipProcessor(tokenizer=tokenizer, image_processor=image_processor)
134
+
135
+ input_str = "lower newer"
136
+ image_input = self.prepare_image_inputs()
137
+
138
+ inputs = processor(text=input_str, images=image_input)
139
+
140
+ # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask']
141
+ self.assertListEqual(list(inputs.keys()), ["pixel_values", "input_ids", "attention_mask"])
142
+
143
+ @require_torch
144
+ @require_vision
145
+ def test_unstructured_kwargs_batched(self):
146
+ if "image_processor" not in self.processor_class.attributes:
147
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
148
+ image_processor = self.get_component("image_processor")
149
+ tokenizer = self.get_component("tokenizer")
150
+
151
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
152
+ self.skip_processor_without_typed_kwargs(processor)
153
+
154
+ input_str = ["lower newer", "upper older longer string"]
155
+ image_input = self.prepare_image_inputs(batch_size=2)
156
+ inputs = processor(
157
+ text=input_str,
158
+ images=image_input,
159
+ return_tensors="pt",
160
+ crop_size={"height": 214, "width": 214},
161
+ size={"height": 214, "width": 214},
162
+ padding="longest",
163
+ max_length=76,
164
+ )
165
+ self.assertEqual(inputs["pixel_values"].shape[2], 214)
166
+
167
+ self.assertEqual(len(inputs["input_ids"][0]), 24)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blip_2/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blip_2/test_modeling_blip_2.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/blip_2/test_processor_blip_2.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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
+ import shutil
15
+ import tempfile
16
+ import unittest
17
+
18
+ import pytest
19
+
20
+ from transformers.testing_utils import require_vision
21
+ from transformers.utils import is_vision_available
22
+
23
+ from ...test_processing_common import ProcessorTesterMixin
24
+
25
+
26
+ if is_vision_available():
27
+ from transformers import AutoProcessor, Blip2Processor, BlipImageProcessor, GPT2Tokenizer, PreTrainedTokenizerFast
28
+
29
+
30
+ @require_vision
31
+ class Blip2ProcessorTest(ProcessorTesterMixin, unittest.TestCase):
32
+ processor_class = Blip2Processor
33
+
34
+ def setUp(self):
35
+ self.tmpdirname = tempfile.mkdtemp()
36
+
37
+ image_processor = BlipImageProcessor()
38
+ tokenizer = GPT2Tokenizer.from_pretrained("hf-internal-testing/tiny-random-GPT2Model")
39
+
40
+ processor = Blip2Processor(image_processor, tokenizer)
41
+
42
+ processor.save_pretrained(self.tmpdirname)
43
+
44
+ def get_tokenizer(self, **kwargs):
45
+ return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).tokenizer
46
+
47
+ def get_image_processor(self, **kwargs):
48
+ return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).image_processor
49
+
50
+ def tearDown(self):
51
+ shutil.rmtree(self.tmpdirname)
52
+
53
+ def test_save_load_pretrained_additional_features(self):
54
+ processor = Blip2Processor(tokenizer=self.get_tokenizer(), image_processor=self.get_image_processor())
55
+ processor.save_pretrained(self.tmpdirname)
56
+
57
+ tokenizer_add_kwargs = self.get_tokenizer(bos_token="(BOS)", eos_token="(EOS)")
58
+ image_processor_add_kwargs = self.get_image_processor(do_normalize=False, padding_value=1.0)
59
+
60
+ processor = Blip2Processor.from_pretrained(
61
+ self.tmpdirname, bos_token="(BOS)", eos_token="(EOS)", do_normalize=False, padding_value=1.0
62
+ )
63
+
64
+ self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab())
65
+ self.assertIsInstance(processor.tokenizer, PreTrainedTokenizerFast)
66
+
67
+ self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string())
68
+ self.assertIsInstance(processor.image_processor, BlipImageProcessor)
69
+
70
+ def test_image_processor(self):
71
+ image_processor = self.get_image_processor()
72
+ tokenizer = self.get_tokenizer()
73
+
74
+ processor = Blip2Processor(tokenizer=tokenizer, image_processor=image_processor)
75
+
76
+ image_input = self.prepare_image_inputs()
77
+
78
+ input_feat_extract = image_processor(image_input, return_tensors="np")
79
+ input_processor = processor(images=image_input, return_tensors="np")
80
+
81
+ for key in input_feat_extract.keys():
82
+ self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2)
83
+
84
+ def test_tokenizer(self):
85
+ image_processor = self.get_image_processor()
86
+ tokenizer = self.get_tokenizer()
87
+
88
+ processor = Blip2Processor(tokenizer=tokenizer, image_processor=image_processor)
89
+
90
+ input_str = "lower newer"
91
+
92
+ encoded_processor = processor(text=input_str)
93
+
94
+ encoded_tok = tokenizer(input_str, return_token_type_ids=False)
95
+
96
+ for key in encoded_tok.keys():
97
+ self.assertListEqual(encoded_tok[key], encoded_processor[key][0])
98
+
99
+ def test_processor(self):
100
+ image_processor = self.get_image_processor()
101
+ tokenizer = self.get_tokenizer()
102
+
103
+ processor = Blip2Processor(tokenizer=tokenizer, image_processor=image_processor)
104
+
105
+ input_str = "lower newer"
106
+ image_input = self.prepare_image_inputs()
107
+
108
+ inputs = processor(text=input_str, images=image_input)
109
+
110
+ self.assertCountEqual(list(inputs.keys()), ["input_ids", "pixel_values", "attention_mask"])
111
+
112
+ # test if it raises when no input is passed
113
+ with pytest.raises(ValueError):
114
+ processor()
115
+
116
+ def test_tokenizer_decode(self):
117
+ image_processor = self.get_image_processor()
118
+ tokenizer = self.get_tokenizer()
119
+
120
+ processor = Blip2Processor(tokenizer=tokenizer, image_processor=image_processor)
121
+
122
+ predicted_ids = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
123
+
124
+ decoded_processor = processor.batch_decode(predicted_ids)
125
+ decoded_tok = tokenizer.batch_decode(predicted_ids)
126
+
127
+ self.assertListEqual(decoded_tok, decoded_processor)
128
+
129
+ def test_model_input_names(self):
130
+ image_processor = self.get_image_processor()
131
+ tokenizer = self.get_tokenizer()
132
+
133
+ processor = Blip2Processor(tokenizer=tokenizer, image_processor=image_processor)
134
+
135
+ input_str = "lower newer"
136
+ image_input = self.prepare_image_inputs()
137
+
138
+ inputs = processor(text=input_str, images=image_input)
139
+
140
+ # For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask']
141
+ self.assertCountEqual(list(inputs.keys()), ["input_ids", "pixel_values", "attention_mask"])
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bloom/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bloom/test_modeling_bloom.py ADDED
@@ -0,0 +1,825 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 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
+ #
16
+
17
+ import math
18
+ import unittest
19
+
20
+ from transformers import BloomConfig, is_torch_available
21
+ from transformers.testing_utils import require_torch, require_torch_accelerator, slow, torch_device
22
+
23
+ from ...generation.test_utils import GenerationTesterMixin
24
+ from ...test_configuration_common import ConfigTester
25
+ from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
26
+ from ...test_pipeline_mixin import PipelineTesterMixin
27
+
28
+
29
+ if is_torch_available():
30
+ import torch
31
+
32
+ from transformers import (
33
+ BloomForCausalLM,
34
+ BloomForQuestionAnswering,
35
+ BloomForSequenceClassification,
36
+ BloomForTokenClassification,
37
+ BloomModel,
38
+ BloomTokenizerFast,
39
+ )
40
+
41
+
42
+ @require_torch
43
+ class BloomModelTester:
44
+ def __init__(
45
+ self,
46
+ parent,
47
+ batch_size=14,
48
+ seq_length=7,
49
+ is_training=True,
50
+ use_token_type_ids=False,
51
+ use_input_mask=True,
52
+ use_labels=True,
53
+ use_mc_token_ids=True,
54
+ vocab_size=99,
55
+ hidden_size=32,
56
+ num_hidden_layers=2,
57
+ num_attention_heads=4,
58
+ intermediate_size=37,
59
+ hidden_act="gelu",
60
+ hidden_dropout_prob=0.1,
61
+ attention_dropout_prob=0.1,
62
+ max_position_embeddings=512,
63
+ type_vocab_size=16,
64
+ type_sequence_label_size=2,
65
+ initializer_range=0.02,
66
+ num_labels=3,
67
+ num_choices=4,
68
+ scope=None,
69
+ ):
70
+ self.parent = parent
71
+ self.batch_size = batch_size
72
+ self.seq_length = seq_length
73
+ self.is_training = is_training
74
+ self.use_token_type_ids = use_token_type_ids
75
+ self.use_input_mask = use_input_mask
76
+ self.use_labels = use_labels
77
+ self.use_mc_token_ids = use_mc_token_ids
78
+ self.vocab_size = vocab_size
79
+ self.hidden_size = hidden_size
80
+ self.num_hidden_layers = num_hidden_layers
81
+ self.num_attention_heads = num_attention_heads
82
+ self.intermediate_size = intermediate_size
83
+ self.hidden_act = hidden_act
84
+ self.hidden_dropout_prob = hidden_dropout_prob
85
+ self.attention_dropout_prob = attention_dropout_prob
86
+ self.max_position_embeddings = max_position_embeddings
87
+ self.type_vocab_size = type_vocab_size
88
+ self.type_sequence_label_size = type_sequence_label_size
89
+ self.initializer_range = initializer_range
90
+ self.num_labels = num_labels
91
+ self.num_choices = num_choices
92
+ self.scope = None
93
+ self.bos_token_id = vocab_size - 1
94
+ self.eos_token_id = vocab_size - 1
95
+ self.pad_token_id = vocab_size - 1
96
+
97
+ def get_large_model_config(self):
98
+ return BloomConfig.from_pretrained("bigscience/bloom")
99
+
100
+ def prepare_config_and_inputs(self, gradient_checkpointing=False):
101
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
102
+
103
+ input_mask = None
104
+ if self.use_input_mask:
105
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
106
+
107
+ sequence_labels = None
108
+ if self.use_labels:
109
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
110
+
111
+ config = self.get_config(gradient_checkpointing=gradient_checkpointing)
112
+
113
+ return (config, input_ids, input_mask, sequence_labels)
114
+
115
+ def get_config(self, gradient_checkpointing=False, slow_but_exact=True):
116
+ return BloomConfig(
117
+ vocab_size=self.vocab_size,
118
+ seq_length=self.seq_length,
119
+ hidden_size=self.hidden_size,
120
+ n_layer=self.num_hidden_layers,
121
+ n_head=self.num_attention_heads,
122
+ hidden_dropout=self.hidden_dropout_prob,
123
+ attention_dropout=self.attention_dropout_prob,
124
+ n_positions=self.max_position_embeddings,
125
+ type_vocab_size=self.type_vocab_size,
126
+ initializer_range=self.initializer_range,
127
+ use_cache=True,
128
+ bos_token_id=self.bos_token_id,
129
+ eos_token_id=self.eos_token_id,
130
+ pad_token_id=self.pad_token_id,
131
+ num_labels=self.num_labels,
132
+ gradient_checkpointing=gradient_checkpointing,
133
+ slow_but_exact=slow_but_exact,
134
+ dtype="float32",
135
+ )
136
+
137
+ def create_and_check_bloom_model(self, config, input_ids, input_mask, *args):
138
+ model = BloomModel(config=config)
139
+ model.to(torch_device)
140
+ model.eval()
141
+
142
+ result = model(input_ids)
143
+
144
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
145
+ self.parent.assertEqual(len(result.past_key_values), config.n_layer)
146
+
147
+ def create_and_check_bloom_model_past(self, config, input_ids, input_mask, *args):
148
+ model = BloomModel(config=config)
149
+
150
+ model.to(torch_device)
151
+ model.eval()
152
+
153
+ # first forward pass
154
+ outputs = model(input_ids, attention_mask=torch.ones_like(input_ids), use_cache=True)
155
+ outputs_use_cache_conf = model(input_ids, attention_mask=torch.ones_like(input_ids))
156
+ outputs_no_past = model(input_ids, use_cache=False, attention_mask=torch.ones_like(input_ids))
157
+
158
+ self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))
159
+ self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)
160
+
161
+ past = outputs["past_key_values"]
162
+
163
+ # create hypothetical next token and extent to next_input_ids
164
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
165
+
166
+ # append to next input_ids and token_type_ids
167
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
168
+
169
+ output_from_no_past = model(next_input_ids)["last_hidden_state"]
170
+ output_from_past = model(next_tokens, past_key_values=past)["last_hidden_state"]
171
+
172
+ # select random slice
173
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
174
+ output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach()
175
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
176
+
177
+ # test that outputs are equal for slice
178
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
179
+
180
+ def create_and_check_bloom_model_attention_mask_past(self, config, input_ids, input_mask, *args):
181
+ model = BloomModel(config=config)
182
+ model.to(torch_device)
183
+ model.eval()
184
+
185
+ # create attention mask
186
+ attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
187
+ half_seq_length = self.seq_length // 2
188
+ attn_mask[:, half_seq_length:] = 0
189
+
190
+ # first forward pass
191
+ output, past = model(input_ids, attention_mask=attn_mask).to_tuple()
192
+
193
+ # create hypothetical next token and extent to next_input_ids
194
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
195
+
196
+ # change a random masked slice from input_ids
197
+ random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1
198
+ random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1)
199
+ input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens
200
+
201
+ # append to next input_ids and attn_mask
202
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
203
+ attn_mask = torch.cat(
204
+ [attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)],
205
+ dim=1,
206
+ )
207
+
208
+ # get two different outputs
209
+ output_from_no_past = model(next_input_ids, attention_mask=attn_mask)["last_hidden_state"]
210
+ output_from_past = model(next_tokens, past_key_values=past, attention_mask=attn_mask)["last_hidden_state"]
211
+
212
+ # select random slice
213
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
214
+ output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach()
215
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
216
+
217
+ # test that outputs are equal for slice
218
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
219
+
220
+ def create_and_check_bloom_model_past_large_inputs(self, config, input_ids, input_mask, *args):
221
+ model = BloomModel(config=config)
222
+ model.to(torch_device)
223
+ model.eval()
224
+
225
+ # first forward pass
226
+ outputs = model(input_ids, attention_mask=input_mask, use_cache=True)
227
+
228
+ output, past = outputs.to_tuple()
229
+
230
+ # create hypothetical next token and extent to next_input_ids
231
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
232
+ next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
233
+
234
+ # append to next input_ids and token_type_ids
235
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
236
+ next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
237
+
238
+ output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"]
239
+ output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past)[
240
+ "last_hidden_state"
241
+ ]
242
+ self.parent.assertTrue(output_from_past.shape[1] == next_tokens.shape[1])
243
+
244
+ # select random slice
245
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
246
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
247
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
248
+
249
+ # test that outputs are equal for slice
250
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
251
+
252
+ def create_and_check_lm_head_model(self, config, input_ids, input_mask, *args):
253
+ model = BloomForCausalLM(config)
254
+ model.to(torch_device)
255
+ model.eval()
256
+
257
+ result = model(input_ids, labels=input_ids)
258
+ self.parent.assertEqual(result.loss.shape, ())
259
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
260
+
261
+ def create_and_check_sequence_classification_model(self, config, input_ids, input_mask, *args):
262
+ config.num_labels = self.num_labels
263
+ model = BloomForSequenceClassification(config)
264
+ model.to(torch_device)
265
+ model.eval()
266
+
267
+ result = model(input_ids, attention_mask=input_mask)
268
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
269
+
270
+ def create_and_check_token_classification_model(self, config, input_ids, input_mask, *args):
271
+ model = BloomForTokenClassification(config)
272
+ model.to(torch_device)
273
+ model.eval()
274
+
275
+ result = model(input_ids, attention_mask=input_mask)
276
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
277
+
278
+ def create_and_check_question_answering_model(self, config, input_ids, input_mask, *args):
279
+ model = BloomForQuestionAnswering(config)
280
+ model.to(torch_device)
281
+ model.eval()
282
+
283
+ result = model(input_ids, attention_mask=input_mask)
284
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
285
+
286
+ def create_and_check_forward_and_backwards(
287
+ self, config, input_ids, input_mask, *args, gradient_checkpointing=False
288
+ ):
289
+ model = BloomForCausalLM(config)
290
+ model.to(torch_device)
291
+ if gradient_checkpointing:
292
+ model.gradient_checkpointing_enable()
293
+
294
+ result = model(input_ids, labels=input_ids)
295
+ self.parent.assertEqual(result.loss.shape, ())
296
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
297
+ result.loss.backward()
298
+
299
+ def create_and_check_bloom_weight_initialization(self, config, *args):
300
+ model = BloomModel(config)
301
+ model_std = model.config.initializer_range / math.sqrt(2 * model.config.n_layer)
302
+ for key in model.state_dict().keys():
303
+ if "c_proj" in key and "weight" in key:
304
+ self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key]) - model_std), 0.001)
305
+ self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key]) - 0.0), 0.01)
306
+
307
+ def prepare_config_and_inputs_for_common(self):
308
+ config_and_inputs = self.prepare_config_and_inputs()
309
+
310
+ config, input_ids, input_mask, sequence_labels = config_and_inputs
311
+
312
+ inputs_dict = {"input_ids": input_ids}
313
+
314
+ return config, inputs_dict
315
+
316
+
317
+ @require_torch
318
+ class BloomModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
319
+ all_model_classes = (
320
+ (
321
+ BloomModel,
322
+ BloomForCausalLM,
323
+ BloomForSequenceClassification,
324
+ BloomForTokenClassification,
325
+ BloomForQuestionAnswering,
326
+ )
327
+ if is_torch_available()
328
+ else ()
329
+ )
330
+
331
+ all_generative_model_classes = (BloomForCausalLM,) if is_torch_available() else ()
332
+ pipeline_model_mapping = (
333
+ {
334
+ "feature-extraction": BloomModel,
335
+ "question-answering": BloomForQuestionAnswering,
336
+ "text-classification": BloomForSequenceClassification,
337
+ "text-generation": BloomForCausalLM,
338
+ "token-classification": BloomForTokenClassification,
339
+ "zero-shot": BloomForSequenceClassification,
340
+ }
341
+ if is_torch_available()
342
+ else {}
343
+ )
344
+ fx_compatible = True
345
+ test_missing_keys = False
346
+ test_pruning = False
347
+ test_torchscript = True # torch.autograd functions seems not to be supported
348
+
349
+ def setUp(self):
350
+ self.model_tester = BloomModelTester(self)
351
+ self.config_tester = ConfigTester(self, config_class=BloomConfig, n_embd=37)
352
+
353
+ def test_config(self):
354
+ self.config_tester.run_common_tests()
355
+
356
+ def test_bloom_model(self):
357
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
358
+ self.model_tester.create_and_check_bloom_model(*config_and_inputs)
359
+
360
+ def test_bloom_model_past(self):
361
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
362
+ self.model_tester.create_and_check_bloom_model_past(*config_and_inputs)
363
+
364
+ def test_bloom_model_att_mask_past(self):
365
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
366
+ self.model_tester.create_and_check_bloom_model_attention_mask_past(*config_and_inputs)
367
+
368
+ def test_bloom_model_past_large_inputs(self):
369
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
370
+ self.model_tester.create_and_check_bloom_model_past_large_inputs(*config_and_inputs)
371
+
372
+ def test_bloom_lm_head_model(self):
373
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
374
+ self.model_tester.create_and_check_lm_head_model(*config_and_inputs)
375
+
376
+ def test_bloom_sequence_classification_model(self):
377
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
378
+ self.model_tester.create_and_check_sequence_classification_model(*config_and_inputs)
379
+
380
+ def test_bloom_token_classification_model(self):
381
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
382
+ self.model_tester.create_and_check_token_classification_model(*config_and_inputs)
383
+
384
+ def test_bloom_gradient_checkpointing(self):
385
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
386
+ self.model_tester.create_and_check_forward_and_backwards(*config_and_inputs, gradient_checkpointing=True)
387
+
388
+ def test_bloom_weight_initialization(self):
389
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
390
+ self.model_tester.create_and_check_bloom_weight_initialization(*config_and_inputs)
391
+
392
+ @slow
393
+ def test_model_from_pretrained(self):
394
+ model_name = "bigscience/bigscience-small-testing"
395
+ model = BloomModel.from_pretrained(model_name)
396
+ self.assertIsNotNone(model)
397
+
398
+ @slow
399
+ @require_torch_accelerator
400
+ def test_simple_generation(self):
401
+ # This test is a bit flaky. For some GPU architectures, pytorch sets by default allow_fp16_reduced_precision_reduction = True and some operations
402
+ # do not give the same results under this configuration, especially torch.baddmm and torch.bmm. https://pytorch.org/docs/stable/notes/numerical_accuracy.html#fp16-on-mi200
403
+ # As we leave the default value (True) for allow_fp16_reduced_precision_reduction , the tests failed when running in half-precision with smaller models (560m)
404
+ # Please see: https://pytorch.org/docs/stable/notes/cuda.html#reduced-precision-reduction-in-fp16-gemms
405
+ # This discrepancy is observed only when using small models and seems to be stable for larger models.
406
+ # Our conclusion is that these operations are flaky for small inputs but seems to be stable for larger inputs (for the functions `baddmm` and `bmm`), and therefore for larger models.
407
+
408
+ # Here is a summary of an ablation study of our observations
409
+ # EXPECTED_OUTPUT = "I enjoy walking with my cute dog, and I love to watch the kids play. I am a very active person, and I am a very good listener. I am a very good person, and I am a very good person. I am a"
410
+ # 560m + allow_fp16_reduced_precision_reduction = False + torch.bmm ==> PASS
411
+ # 560m + allow_fp16_reduced_precision_reduction = False + torch.baddm ==> PASS
412
+ # 560m + allow_fp16_reduced_precision_reduction = True + torch.baddm ==> PASS
413
+ # 560m + allow_fp16_reduced_precision_reduction = True + torch.bmm ==> FAIL
414
+
415
+ # EXPECTED_OUTPUT = "I enjoy walking with my cute dog, but I also enjoy hiking, biking, and swimming. I love to cook and bake. I love to cook and bake. I love to cook and bake. I love to cook and bake. I love"
416
+ # >=1b1 + allow_fp16_reduced_precision_reduction = True + torch.baddm ==> PASS (for use_cache=True and use_cache=False)
417
+ # >=1b1 + allow_fp16_reduced_precision_reduction = True + torch.bmm ==> PASS
418
+ # >=1b1 + allow_fp16_reduced_precision_reduction = False + torch.bmm ==> PASS
419
+
420
+ path_560m = "bigscience/bloom-560m"
421
+ model = BloomForCausalLM.from_pretrained(path_560m, use_cache=True, revision="gs555750").to(torch_device)
422
+ model = model.eval()
423
+ tokenizer = BloomTokenizerFast.from_pretrained(path_560m)
424
+
425
+ input_sentence = "I enjoy walking with my cute dog"
426
+ # This output has been obtained using fp32 model on the huggingface DGX workstation - NVIDIA A100 GPU
427
+ EXPECTED_OUTPUT = (
428
+ "I enjoy walking with my cute dog, and I love to watch the kids play with the kids. I am a very "
429
+ "active person, and I enjoy working out, and I am a very active person. I am a very active person, and I"
430
+ )
431
+
432
+ input_ids = tokenizer.encode(input_sentence, return_tensors="pt")
433
+ greedy_output = model.generate(input_ids.to(torch_device), max_length=50)
434
+
435
+ self.assertEqual(tokenizer.decode(greedy_output[0], skip_special_tokens=True), EXPECTED_OUTPUT)
436
+
437
+ @slow
438
+ @require_torch_accelerator
439
+ def test_batch_generation(self):
440
+ path_560m = "bigscience/bloom-560m"
441
+ model = BloomForCausalLM.from_pretrained(path_560m, use_cache=True, revision="gs555750").to(torch_device)
442
+ model = model.eval()
443
+ tokenizer = BloomTokenizerFast.from_pretrained(path_560m, padding_side="left")
444
+
445
+ input_sentence = ["I enjoy walking with my cute dog", "I enjoy walking with my cute dog"]
446
+
447
+ inputs = tokenizer.batch_encode_plus(input_sentence, return_tensors="pt", padding=True)
448
+ input_ids = inputs["input_ids"].to(torch_device)
449
+ attention_mask = inputs["attention_mask"]
450
+ greedy_output = model.generate(input_ids, attention_mask=attention_mask, max_length=50, do_sample=False)
451
+
452
+ self.assertEqual(
453
+ tokenizer.decode(greedy_output[0], skip_special_tokens=True),
454
+ tokenizer.decode(greedy_output[1], skip_special_tokens=True),
455
+ )
456
+
457
+ @slow
458
+ @require_torch_accelerator
459
+ def test_batch_generation_padd(self):
460
+ path_560m = "bigscience/bloom-560m"
461
+ model = BloomForCausalLM.from_pretrained(path_560m, use_cache=True, revision="gs555750").to(torch_device)
462
+ model = model.eval()
463
+ tokenizer = BloomTokenizerFast.from_pretrained(path_560m, padding_side="left")
464
+
465
+ input_sentence = ["I enjoy walking with my cute dog", "Hello my name is"]
466
+ input_sentence_without_pad = "Hello my name is"
467
+
468
+ input_ids = tokenizer.batch_encode_plus(input_sentence, return_tensors="pt", padding=True)
469
+ input_ids_without_pad = tokenizer.encode(input_sentence_without_pad, return_tensors="pt")
470
+
471
+ input_ids, attention_mask = input_ids["input_ids"].to(torch_device), input_ids["attention_mask"]
472
+ greedy_output = model.generate(input_ids, attention_mask=attention_mask, max_length=50, do_sample=False)
473
+ greedy_output_without_pad = model.generate(
474
+ input_ids_without_pad.to(torch_device), max_length=50, do_sample=False
475
+ )
476
+
477
+ # test token values
478
+ self.assertEqual(greedy_output[-1, 3:].tolist(), greedy_output_without_pad[0, :-3].tolist())
479
+
480
+ # test reconstructions
481
+ self.assertEqual(
482
+ tokenizer.decode(greedy_output[-1, 3:], skip_special_tokens=True),
483
+ tokenizer.decode(greedy_output_without_pad[0, :-3], skip_special_tokens=True),
484
+ )
485
+
486
+ @slow
487
+ @require_torch_accelerator
488
+ def test_batch_generated_text(self):
489
+ path_560m = "bigscience/bloom-560m"
490
+
491
+ model = BloomForCausalLM.from_pretrained(path_560m, use_cache=True, revision="gs555750").to(torch_device)
492
+ model = model.eval()
493
+ tokenizer = BloomTokenizerFast.from_pretrained(path_560m, padding_side="left")
494
+
495
+ input_sentences = [
496
+ "Hello what is",
497
+ "Running a quick test with the",
498
+ ]
499
+ inputs = tokenizer(input_sentences, return_tensors="pt", padding=True, truncation=True)
500
+ generated_ids = model.generate(
501
+ inputs["input_ids"].to(torch_device), attention_mask=inputs["attention_mask"], max_length=20
502
+ )
503
+ generated_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
504
+
505
+ # these generations match those of the PyTorch model
506
+ EXPECTED_GENERATIONS = [
507
+ "Hello what is the best way to get the data from the server? I have tried",
508
+ "Running a quick test with the following command:\nsudo apt-get install python3\nsudo apt-get install python2",
509
+ ]
510
+
511
+ self.assertListEqual(generated_text, EXPECTED_GENERATIONS)
512
+
513
+ @unittest.skip("Bloom needs a 2D attention for alibi")
514
+ def test_custom_4d_attention_mask(self):
515
+ pass
516
+
517
+
518
+ @require_torch
519
+ class BloomEmbeddingTest(unittest.TestCase):
520
+ """
521
+ The goal here is to compare the embeddings generated by the model trained
522
+ using Megatron-LM with the one from the transformers library, with a small GPT2-like model
523
+ to ensure that the conversion from Megatron-LM to transformers has been done successfully.
524
+ The script compares the logits of the embedding layer and the transformer layers.
525
+
526
+ WARNING: It is expected that these logits will not have exactly the same statistics when running
527
+ the code on CPU or GPU. For more info, please visit:
528
+ - https://github.com/pytorch/pytorch/issues/76052#issuecomment-1103193548
529
+ - https://discuss.pytorch.org/t/reproducibility-issue-between-intel-and-amd-cpus/144779/9
530
+
531
+
532
+ You need to install tokenizers following this readme:
533
+ - https://huggingface.co/bigscience-catalogue-data-dev/byte-level-bpe-tokenizer-no-norm-250k-whitespace-and-eos-regex-alpha-v3-dedup-lines-articles
534
+
535
+ Tokenizer used during training:
536
+ - https://huggingface.co/bigscience-catalogue-data-dev/byte-level-bpe-tokenizer-no-norm-250k-whitespace-and-eos-regex-alpha-v3-dedup-lines-articles
537
+
538
+ # TODO change the script (or just add skip) when building the env with tokenizers 0.12.0
539
+ """
540
+
541
+ def setUp(self):
542
+ super().setUp()
543
+ self.path_bigscience_model = "bigscience/bigscience-small-testing"
544
+
545
+ @require_torch
546
+ def test_embeddings(self):
547
+ # The config in this checkpoint has `bfloat16` as `torch_dtype` -> model in `bfloat16`
548
+ model = BloomForCausalLM.from_pretrained(self.path_bigscience_model, torch_dtype="auto")
549
+ model.eval()
550
+
551
+ EMBEDDINGS_DS_BEFORE_LN_BF_16_MEAN = {
552
+ 3478: 0.0002307891845703125,
553
+ 368: -0.000568389892578125,
554
+ 109586: -0.0003910064697265625,
555
+ 35433: -0.000194549560546875,
556
+ 2: 0.0004138946533203125,
557
+ 77: 0.000659942626953125,
558
+ 132619: -0.00031280517578125,
559
+ 2175: 0.000457763671875,
560
+ 23714: 0.000263214111328125,
561
+ 73173: -0.000286102294921875,
562
+ 144252: 0.00052642822265625,
563
+ }
564
+ EMBEDDINGS_DS_BEFORE_LN_BF_16_MIN = {
565
+ 3478: -0.00921630859375,
566
+ 368: -0.010009765625,
567
+ 109586: -0.01031494140625,
568
+ 35433: -0.01177978515625,
569
+ 2: -0.0074462890625,
570
+ 77: -0.00848388671875,
571
+ 132619: -0.009521484375,
572
+ 2175: -0.0074462890625,
573
+ 23714: -0.0145263671875,
574
+ 73173: -0.007415771484375,
575
+ 144252: -0.01007080078125,
576
+ }
577
+ EMBEDDINGS_DS_BEFORE_LN_BF_16_MAX = {
578
+ 3478: 0.0128173828125,
579
+ 368: 0.01214599609375,
580
+ 109586: 0.0111083984375,
581
+ 35433: 0.01019287109375,
582
+ 2: 0.0157470703125,
583
+ 77: 0.0174560546875,
584
+ 132619: 0.0078125,
585
+ 2175: 0.0113525390625,
586
+ 23714: 0.0146484375,
587
+ 73173: 0.01116943359375,
588
+ 144252: 0.01141357421875,
589
+ }
590
+ EMBEDDINGS_DS_BEFORE_LN_BF_16_SUM = {"value": 0.08203125}
591
+
592
+ EMBEDDINGS_DS_BEFORE_LN_F_16_MEAN = {
593
+ 132619: -0.00031256675720214844,
594
+ 3478: 0.00023090839385986328,
595
+ 368: -0.0005702972412109375,
596
+ 109586: -0.00039124488830566406,
597
+ 35433: -0.000194549560546875,
598
+ 2: 0.0004146099090576172,
599
+ 2175: 0.0004572868347167969,
600
+ 23714: 0.00026416778564453125,
601
+ 73173: -0.0002865791320800781,
602
+ 144252: 0.0005254745483398438,
603
+ 77: 0.0006618499755859375,
604
+ }
605
+ EMBEDDINGS_DS_BEFORE_LN_F_16_MIN = {
606
+ 3478: -0.00921630859375,
607
+ 368: -0.010009765625,
608
+ 109586: -0.01031494140625,
609
+ 35433: -0.01177978515625,
610
+ 2: -0.0074462890625,
611
+ 77: -0.00848388671875,
612
+ 132619: -0.009521484375,
613
+ 2175: -0.0074462890625,
614
+ 23714: -0.0145263671875,
615
+ 73173: -0.007415771484375,
616
+ 144252: -0.01007080078125,
617
+ }
618
+ EMBEDDINGS_DS_BEFORE_LN_F_16_MAX = {
619
+ 3478: 0.0128173828125,
620
+ 368: 0.01214599609375,
621
+ 109586: 0.0111083984375,
622
+ 35433: 0.01019287109375,
623
+ 2: 0.0157470703125,
624
+ 77: 0.0174560546875,
625
+ 132619: 0.0078125,
626
+ 2175: 0.0113525390625,
627
+ 23714: 0.0146484375,
628
+ 73173: 0.01116943359375,
629
+ 144252: 0.01141357421875,
630
+ }
631
+ EMBEDDINGS_DS_BEFORE_LN_F_16_SUM = {"value": 0.0821533203125}
632
+
633
+ EMBEDDINGS_DS_BEFORE_LN_F_32_MEAN = {
634
+ 132619: -0.00031267106533050537,
635
+ 3478: 0.00023087859153747559,
636
+ 368: -0.0005701072514057159,
637
+ 109586: -0.0003911703824996948,
638
+ 35433: -0.0001944899559020996,
639
+ 2: 0.0004146844148635864,
640
+ 2175: 0.00045740045607089996,
641
+ 23714: 0.0002641640603542328,
642
+ 73173: -0.0002864748239517212,
643
+ 144252: 0.0005256589502096176,
644
+ 77: 0.0006617321632802486,
645
+ }
646
+ EMBEDDINGS_DS_BEFORE_LN_F_32_MIN = {
647
+ 3478: -0.00921630859375,
648
+ 368: -0.010009765625,
649
+ 109586: -0.01031494140625,
650
+ 35433: -0.01177978515625,
651
+ 2: -0.0074462890625,
652
+ 77: -0.00848388671875,
653
+ 132619: -0.009521484375,
654
+ 2175: -0.0074462890625,
655
+ 23714: -0.0145263671875,
656
+ 73173: -0.007415771484375,
657
+ 144252: -0.01007080078125,
658
+ }
659
+ EMBEDDINGS_DS_BEFORE_LN_F_32_MAX = {
660
+ 3478: 0.0128173828125,
661
+ 368: 0.01214599609375,
662
+ 109586: 0.0111083984375,
663
+ 35433: 0.01019287109375,
664
+ 2: 0.0157470703125,
665
+ 77: 0.0174560546875,
666
+ 132619: 0.0078125,
667
+ 2175: 0.0113525390625,
668
+ 23714: 0.0146484375,
669
+ 73173: 0.01116943359375,
670
+ 144252: 0.01141357421875,
671
+ }
672
+ EMBEDDINGS_DS_BEFORE_LN_F_32_SUM = {"value": 0.08217757940292358}
673
+
674
+ TEST_EMBEDDINGS = {
675
+ "torch.bfloat16": {
676
+ "mean": EMBEDDINGS_DS_BEFORE_LN_BF_16_MEAN,
677
+ "max": EMBEDDINGS_DS_BEFORE_LN_BF_16_MAX,
678
+ "min": EMBEDDINGS_DS_BEFORE_LN_BF_16_MIN,
679
+ "sum": EMBEDDINGS_DS_BEFORE_LN_BF_16_SUM,
680
+ },
681
+ "torch.float32": {
682
+ "mean": EMBEDDINGS_DS_BEFORE_LN_F_32_MEAN,
683
+ "max": EMBEDDINGS_DS_BEFORE_LN_F_32_MAX,
684
+ "min": EMBEDDINGS_DS_BEFORE_LN_F_32_MIN,
685
+ "sum": EMBEDDINGS_DS_BEFORE_LN_F_32_SUM,
686
+ },
687
+ "torch.float": {
688
+ "mean": EMBEDDINGS_DS_BEFORE_LN_F_32_MEAN,
689
+ "max": EMBEDDINGS_DS_BEFORE_LN_F_32_MAX,
690
+ "min": EMBEDDINGS_DS_BEFORE_LN_F_32_MIN,
691
+ "sum": EMBEDDINGS_DS_BEFORE_LN_F_32_SUM,
692
+ },
693
+ "torch.float16": {
694
+ "mean": EMBEDDINGS_DS_BEFORE_LN_F_16_MEAN,
695
+ "max": EMBEDDINGS_DS_BEFORE_LN_F_16_MAX,
696
+ "min": EMBEDDINGS_DS_BEFORE_LN_F_16_MIN,
697
+ "sum": EMBEDDINGS_DS_BEFORE_LN_F_16_SUM,
698
+ },
699
+ }
700
+
701
+ EXAMPLE_IDS = [3478, 368, 109586, 35433, 2, 77, 132619, 3478, 368, 109586, 35433, 2, 2175, 23714, 73173, 144252, 2, 77, 132619, 3478] # fmt: skip
702
+
703
+ EMBEDDINGS_DS_AFTER_LN_MEAN = {
704
+ 3478: -6.580352783203125e-05,
705
+ 368: 0.0001316070556640625,
706
+ 109586: -0.00030517578125,
707
+ 35433: 4.00543212890625e-05,
708
+ 2: -7.2479248046875e-05,
709
+ 77: -8.96453857421875e-05,
710
+ 132619: 0.0001583099365234375,
711
+ 2175: 2.1219253540039062e-05,
712
+ 23714: -0.000247955322265625,
713
+ 73173: -0.00021839141845703125,
714
+ 144252: -0.0001430511474609375,
715
+ }
716
+ EMBEDDINGS_DS_AFTER_LN_MIN = {
717
+ 3478: -1.6953125,
718
+ 368: -1.6875,
719
+ 109586: -1.6875,
720
+ 35433: -2.125,
721
+ 2: -1.390625,
722
+ 77: -1.5390625,
723
+ 132619: -1.875,
724
+ 2175: -1.4609375,
725
+ 23714: -2.296875,
726
+ 73173: -1.3515625,
727
+ 144252: -1.78125,
728
+ }
729
+ EMBEDDINGS_DS_AFTER_LN_MAX = {
730
+ 3478: 2.265625,
731
+ 368: 2.28125,
732
+ 109586: 1.953125,
733
+ 35433: 1.90625,
734
+ 2: 2.703125,
735
+ 77: 2.828125,
736
+ 132619: 1.65625,
737
+ 2175: 2.015625,
738
+ 23714: 2.234375,
739
+ 73173: 2.171875,
740
+ 144252: 1.828125,
741
+ }
742
+
743
+ EMBEDDINGS_DS_AFTER_LN = {
744
+ "mean": EMBEDDINGS_DS_AFTER_LN_MEAN,
745
+ "min": EMBEDDINGS_DS_AFTER_LN_MIN,
746
+ "max": EMBEDDINGS_DS_AFTER_LN_MAX,
747
+ }
748
+
749
+ tensor_ids = torch.LongTensor([EXAMPLE_IDS])
750
+ with torch.no_grad():
751
+ embeddings = model.transformer.word_embeddings(tensor_ids)
752
+ embeddings_ln = model.transformer.word_embeddings_layernorm(embeddings) #
753
+ # first check the embeddings before LN
754
+ output_dict = {"min": {}, "max": {}, "mean": {}, "sum": {"value": embeddings.sum().item()}}
755
+ for i, idx in enumerate(EXAMPLE_IDS):
756
+ output_dict["min"][idx] = embeddings.min(dim=-1).values[0][i].item()
757
+ output_dict["max"][idx] = embeddings.max(dim=-1).values[0][i].item()
758
+ output_dict["mean"][idx] = embeddings.mean(dim=-1)[0][i].item()
759
+
760
+ for key in TEST_EMBEDDINGS[str(model.dtype)].keys():
761
+ self.assertDictEqual(TEST_EMBEDDINGS[str(model.dtype)][key], output_dict[key])
762
+
763
+ output_dict_norm = {"min": {}, "max": {}, "mean": {}}
764
+ for i, idx in enumerate(EXAMPLE_IDS):
765
+ output_dict_norm["min"][idx] = embeddings_ln.min(dim=-1).values[0][i].item()
766
+ output_dict_norm["max"][idx] = embeddings_ln.max(dim=-1).values[0][i].item()
767
+ output_dict_norm["mean"][idx] = embeddings_ln.mean(dim=-1)[0][i].item()
768
+
769
+ # This test does not pass when places = 2
770
+ for i, key in enumerate(output_dict_norm.keys()):
771
+ for j, idx in enumerate(output_dict[key].keys()):
772
+ self.assertAlmostEqual(EMBEDDINGS_DS_AFTER_LN[key][idx], output_dict_norm[key][idx], places=1)
773
+
774
+ @require_torch
775
+ def test_hidden_states_transformers(self):
776
+ cuda_available = torch.cuda.is_available()
777
+ model = BloomModel.from_pretrained(self.path_bigscience_model, use_cache=False, torch_dtype="auto").to(
778
+ torch_device
779
+ )
780
+ model.eval()
781
+
782
+ EXAMPLE_IDS = [3478, 368, 109586, 35433, 2, 77, 132619, 3478, 368, 109586, 35433, 2, 2175, 23714, 73173, 144252, 2, 77, 132619, 3478] # fmt: skip
783
+
784
+ MEAN_VALUE_LAST_LM = -4.3392181396484375e-05
785
+ MIN_MAX_DICT = {"min": -2.0625, "max": 2.75}
786
+ tensor_ids = torch.LongTensor([EXAMPLE_IDS])
787
+
788
+ with torch.no_grad():
789
+ logits = model(tensor_ids.to(torch_device))
790
+ output_dict = {
791
+ "min": logits.last_hidden_state.min(dim=-1).values[0][0].item(),
792
+ "max": logits.last_hidden_state.max(dim=-1).values[0][0].item(),
793
+ }
794
+
795
+ if cuda_available:
796
+ self.assertAlmostEqual(MEAN_VALUE_LAST_LM, logits.last_hidden_state.mean().item(), places=4)
797
+ else:
798
+ self.assertAlmostEqual(MEAN_VALUE_LAST_LM, logits.last_hidden_state.mean().item(), places=3)
799
+
800
+ self.assertDictEqual(MIN_MAX_DICT, output_dict)
801
+
802
+ @require_torch
803
+ def test_logits(self):
804
+ cuda_available = torch.cuda.is_available()
805
+ model = BloomForCausalLM.from_pretrained(self.path_bigscience_model, use_cache=False, torch_dtype="auto").to(
806
+ torch_device
807
+ ) # load in bf16
808
+ model.eval()
809
+
810
+ EXAMPLE_IDS = [3478, 368, 109586, 35433, 2, 77, 132619, 3478, 368, 109586, 35433, 2, 2175, 23714, 73173, 144252, 2, 77, 132619, 3478] # fmt: skip
811
+
812
+ MEAN_LOGITS_GPU_1 = -1.823902130126953e-05
813
+ MEAN_LOGITS_GPU_2 = 1.9431114196777344e-05
814
+
815
+ tensor_ids = torch.LongTensor([EXAMPLE_IDS]).to(torch_device)
816
+ with torch.no_grad():
817
+ output = model(tensor_ids).logits
818
+
819
+ output_gpu_1, output_gpu_2 = output.split(125440, dim=-1)
820
+ if cuda_available:
821
+ self.assertAlmostEqual(output_gpu_1.mean().item(), MEAN_LOGITS_GPU_1, places=6)
822
+ self.assertAlmostEqual(output_gpu_2.mean().item(), MEAN_LOGITS_GPU_2, places=6)
823
+ else:
824
+ self.assertAlmostEqual(output_gpu_1.mean().item(), MEAN_LOGITS_GPU_1, places=6) # 1e-06 precision!!
825
+ self.assertAlmostEqual(output_gpu_2.mean().item(), MEAN_LOGITS_GPU_2, places=6)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bloom/test_modeling_flax_bloom.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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
+ import unittest
15
+
16
+ import numpy as np
17
+
18
+ from transformers import BloomConfig, BloomTokenizerFast, is_flax_available
19
+ from transformers.testing_utils import require_flax, slow
20
+
21
+ from ...generation.test_flax_utils import FlaxGenerationTesterMixin
22
+ from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor
23
+
24
+
25
+ if is_flax_available():
26
+ import os
27
+
28
+ # The slow tests are often failing with OOM error on GPU
29
+ # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
30
+ # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
31
+ os.environ["XLA_PYTHON_CLIENT_ALLOCATOR"] = "platform"
32
+
33
+ import jax.numpy as jnp
34
+
35
+ from transformers import FlaxBloomForCausalLM, FlaxBloomModel
36
+
37
+
38
+ def prepare_bloom_inputs_dict(config, input_ids, attention_mask=None):
39
+ if attention_mask is None:
40
+ attention_mask = np.where(input_ids != config.pad_token_id, 1, 0)
41
+ return {"input_ids": input_ids, "attention_mask": attention_mask}
42
+
43
+
44
+ @require_flax
45
+ class FlaxBloomModelTester:
46
+ def __init__(
47
+ self,
48
+ parent,
49
+ batch_size=13,
50
+ seq_length=7,
51
+ is_training=True,
52
+ use_labels=False,
53
+ vocab_size=99,
54
+ hidden_size=16,
55
+ n_layer=2,
56
+ n_head=4,
57
+ hidden_act="gelu",
58
+ hidden_dropout=0.1,
59
+ attention_probs_dropout_prob=0.1,
60
+ eos_token_id=2,
61
+ pad_token_id=1,
62
+ bos_token_id=0,
63
+ initializer_range=0.02,
64
+ apply_residual_connection_post_layernorm=False,
65
+ ):
66
+ self.parent = parent
67
+ self.batch_size = batch_size
68
+ self.seq_length = seq_length
69
+ self.is_training = is_training
70
+ self.use_labels = use_labels
71
+ self.vocab_size = vocab_size
72
+ self.hidden_size = hidden_size
73
+ self.num_hidden_layers = n_layer
74
+ self.num_attention_heads = n_head
75
+ self.hidden_act = hidden_act
76
+ self.hidden_dropout = hidden_dropout
77
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
78
+ self.eos_token_id = eos_token_id
79
+ self.pad_token_id = pad_token_id
80
+ self.bos_token_id = bos_token_id
81
+ self.initializer_range = initializer_range
82
+ self.is_encoder_decoder = False
83
+ self.apply_residual_connection_post_layernorm = apply_residual_connection_post_layernorm
84
+
85
+ def prepare_config_and_inputs(self):
86
+ input_ids = np.clip(ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size), 3, self.vocab_size)
87
+ input_ids = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1), dtype=np.int64)), -1)
88
+
89
+ config = BloomConfig(
90
+ vocab_size=self.vocab_size,
91
+ hidden_size=self.hidden_size,
92
+ n_layer=self.num_hidden_layers,
93
+ n_head=self.num_attention_heads,
94
+ hidden_dropout=self.hidden_dropout,
95
+ attention_dropout=self.attention_probs_dropout_prob,
96
+ eos_token_id=self.eos_token_id,
97
+ bos_token_id=self.bos_token_id,
98
+ pad_token_id=self.pad_token_id,
99
+ is_encoder_decoder=False,
100
+ use_cache=False,
101
+ )
102
+ inputs_dict = prepare_bloom_inputs_dict(config, input_ids)
103
+ return config, inputs_dict
104
+
105
+ def prepare_config_and_inputs_for_common(self):
106
+ config, inputs_dict = self.prepare_config_and_inputs()
107
+ return config, inputs_dict
108
+
109
+ def check_use_cache_forward(self, model_class_name, config, inputs_dict):
110
+ max_length = 20
111
+ model = model_class_name(config)
112
+
113
+ input_ids = inputs_dict["input_ids"]
114
+ attention_mask = jnp.ones((input_ids.shape[0], max_length), dtype="i4")
115
+
116
+ past_key_values = model.init_cache(input_ids.shape[0], max_length)
117
+
118
+ outputs_cache = model(
119
+ input_ids[:, :-1],
120
+ attention_mask=attention_mask,
121
+ past_key_values=past_key_values,
122
+ )
123
+
124
+ outputs_cache_next = model(
125
+ input_ids[:, -1:],
126
+ attention_mask=attention_mask,
127
+ past_key_values=outputs_cache.past_key_values,
128
+ )
129
+
130
+ outputs = model(input_ids)
131
+
132
+ diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
133
+ self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}")
134
+
135
+ def check_use_cache_forward_with_attn_mask(self, model_class_name, config, inputs_dict):
136
+ max_length = 20
137
+ model = model_class_name(config)
138
+
139
+ input_ids, attention_mask = (
140
+ inputs_dict["input_ids"],
141
+ inputs_dict["attention_mask"],
142
+ )
143
+
144
+ attention_mask_cache = jnp.concatenate(
145
+ [
146
+ attention_mask,
147
+ jnp.zeros((attention_mask.shape[0], max_length - attention_mask.shape[1])),
148
+ ],
149
+ axis=-1,
150
+ )
151
+
152
+ past_key_values = model.init_cache(input_ids.shape[0], max_length)
153
+
154
+ outputs_cache = model(
155
+ input_ids[:, :-1],
156
+ attention_mask=attention_mask_cache,
157
+ past_key_values=past_key_values,
158
+ )
159
+ outputs_cache_next = model(
160
+ input_ids[:, -1:],
161
+ past_key_values=outputs_cache.past_key_values,
162
+ attention_mask=attention_mask_cache,
163
+ )
164
+
165
+ outputs = model(input_ids, attention_mask=attention_mask)
166
+
167
+ diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
168
+ self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}")
169
+
170
+
171
+ @require_flax
172
+ class FlaxBloomModelTest(FlaxModelTesterMixin, unittest.TestCase, FlaxGenerationTesterMixin):
173
+ all_model_classes = (FlaxBloomModel, FlaxBloomForCausalLM) if is_flax_available() else ()
174
+ all_generative_model_classes = () if is_flax_available() else ()
175
+
176
+ def setUp(self):
177
+ self.model_tester = FlaxBloomModelTester(self)
178
+
179
+ def test_use_cache_forward(self):
180
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
181
+ for model_class in self.all_model_classes:
182
+ self.model_tester.check_use_cache_forward(model_class, config, inputs_dict)
183
+
184
+ def test_use_cache_forward_with_attn_mask(self):
185
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
186
+ for model_class in self.all_model_classes:
187
+ self.model_tester.check_use_cache_forward_with_attn_mask(model_class, config, inputs_dict)
188
+
189
+ @slow
190
+ def test_model_from_pretrained(self):
191
+ for model_class_name in self.all_model_classes:
192
+ model = model_class_name.from_pretrained("bigscience/bloom-560m")
193
+ input_ids = np.ones((1, 1)) * model.config.eos_token_id
194
+ outputs = model(input_ids)
195
+ self.assertIsNotNone(outputs)
196
+
197
+
198
+ @slow
199
+ @require_flax
200
+ class FlaxBloomGenerationTest(unittest.TestCase):
201
+ all_model_classes = (FlaxBloomForCausalLM,) if is_flax_available() else ()
202
+ all_generative_model_classes = () if is_flax_available() else ()
203
+
204
+ def setUp(self):
205
+ self.model_id = "bigscience/bloom-560m"
206
+ self.tokenizer = BloomTokenizerFast.from_pretrained(self.model_id, padding_side="left")
207
+ self.model_tester = FlaxBloomModelTester(self)
208
+ self.model = FlaxBloomForCausalLM.from_pretrained(self.model_id, from_pt=True, revision="gs555750")
209
+
210
+ def test_model_batched_gen(self):
211
+ # tests if the model outputs the same generation for the same batched input
212
+ input_sentences = [
213
+ "Hello there is this string is definitely longer I believe that",
214
+ "Hello there is this string is definitely longer I believe that",
215
+ ]
216
+ inputs = self.tokenizer(input_sentences, return_tensors="np", padding=True, truncation=True)
217
+ sequences_fx = self.model.generate(**inputs, max_length=20).sequences
218
+ self.assertEqual(sequences_fx[0].tolist(), sequences_fx[1].tolist())
219
+
220
+ def test_model_batched_padding_left(self):
221
+ # tests if the model outputs the same generation for an input that is part of a batch
222
+ # and a single input
223
+ input_sentences_batch = [
224
+ "Hello there is this string is definitely longer I believe that",
225
+ "Hi I want to order",
226
+ ]
227
+ inputs = self.tokenizer(input_sentences_batch, return_tensors="np", padding=True, truncation=True)
228
+ sequences_fx_batch = self.model.generate(**inputs, max_length=20).sequences
229
+
230
+ input_sentence_simple = "Hi I want to order"
231
+ inputs_simple = self.tokenizer(input_sentence_simple, return_tensors="np")
232
+ sequences_fx_simple = self.model.generate(**inputs_simple, max_length=20).sequences
233
+
234
+ self.assertEqual(sequences_fx_batch[1][6:].tolist(), sequences_fx_simple[0][:-6].tolist())
235
+
236
+ def test_batch_generated_text(self):
237
+ input_sentences = [
238
+ "Hello what is",
239
+ "Running a quick test with the",
240
+ ]
241
+ inputs = self.tokenizer(input_sentences, return_tensors="np", padding=True, truncation=True)
242
+ generated_ids = self.model.generate(**inputs, max_length=20).sequences
243
+ generated_text = self.tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
244
+
245
+ # these generations match those of the PyTorch model, ensuring correctness
246
+ EXPECTED_GENERATIONS = [
247
+ "Hello what is the best way to get the data from the server? I have tried",
248
+ "Running a quick test with the following command:\nsudo apt-get install python3\nsudo apt-get install python2",
249
+ ]
250
+
251
+ self.assertListEqual(generated_text, EXPECTED_GENERATIONS)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bloom/test_tokenization_bloom.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 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
+
16
+ import unittest
17
+
18
+ from datasets import load_dataset
19
+
20
+ from transformers import BloomTokenizerFast
21
+ from transformers.testing_utils import require_jinja, require_tokenizers
22
+
23
+ from ...test_tokenization_common import TokenizerTesterMixin
24
+
25
+
26
+ @require_tokenizers
27
+ class BloomTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
28
+ from_pretrained_id = "bigscience/tokenizer"
29
+ slow_tokenizer_class = None
30
+ rust_tokenizer_class = BloomTokenizerFast
31
+ tokenizer_class = BloomTokenizerFast
32
+ test_rust_tokenizer = True
33
+ test_slow_tokenizer = False
34
+ from_pretrained_vocab_key = "tokenizer_file"
35
+ special_tokens_map = {"bos_token": "<s>", "eos_token": "</s>", "unk_token": "<unk>", "pad_token": "<pad>"}
36
+
37
+ def setUp(self):
38
+ super().setUp()
39
+ tokenizer = BloomTokenizerFast.from_pretrained("bigscience/tokenizer")
40
+ tokenizer.save_pretrained(self.tmpdirname)
41
+
42
+ def get_rust_tokenizer(self, **kwargs):
43
+ kwargs.update(self.special_tokens_map)
44
+ return BloomTokenizerFast.from_pretrained(self.tmpdirname, **kwargs)
45
+
46
+ @unittest.skip(reason="This needs a slow tokenizer. Bloom does not have one!")
47
+ def test_encode_decode_with_spaces(self):
48
+ return
49
+
50
+ def test_encodings_from_sample_data(self):
51
+ """
52
+ Assert that the created tokens are the same than the hard-coded ones
53
+ """
54
+ tokenizer = self.get_rust_tokenizer()
55
+
56
+ INPUT_SENTENCES = ["The quick brown fox</s>", "jumps over the lazy dog</s>"]
57
+ TARGET_TOKENS = [[2175, 23714, 73173, 144252, 2], [77, 132619, 3478, 368, 109586, 35433, 2]]
58
+
59
+ computed_tokens = tokenizer.batch_encode_plus(INPUT_SENTENCES)["input_ids"]
60
+ self.assertListEqual(TARGET_TOKENS, computed_tokens)
61
+
62
+ decoded_tokens = tokenizer.batch_decode(computed_tokens)
63
+ self.assertListEqual(decoded_tokens, INPUT_SENTENCES)
64
+
65
+ def test_padding(self, max_length=6):
66
+ for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
67
+ with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
68
+ tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
69
+ # tokenizer_r.pad_token = None # Hotfixing padding = None
70
+ # Simple input
71
+ s = "This is a simple input"
72
+ s2 = ["This is a simple input 1", "This is a simple input 2"]
73
+ p = ("This is a simple input", "This is a pair")
74
+ p2 = [
75
+ ("This is a simple input 1", "This is a simple input 2"),
76
+ ("This is a simple pair 1", "This is a simple pair 2"),
77
+ ]
78
+
79
+ # Simple input tests
80
+ try:
81
+ tokenizer_r.encode(s, max_length=max_length)
82
+ tokenizer_r.encode_plus(s, max_length=max_length)
83
+
84
+ tokenizer_r.batch_encode_plus(s2, max_length=max_length)
85
+ tokenizer_r.encode(p, max_length=max_length)
86
+ tokenizer_r.batch_encode_plus(p2, max_length=max_length)
87
+ except ValueError:
88
+ self.fail("Bloom Tokenizer should be able to deal with padding")
89
+
90
+ tokenizer_r.pad_token = None # Hotfixing padding = None
91
+ self.assertRaises(ValueError, tokenizer_r.encode, s, max_length=max_length, padding="max_length")
92
+
93
+ # Simple input
94
+ self.assertRaises(ValueError, tokenizer_r.encode_plus, s, max_length=max_length, padding="max_length")
95
+
96
+ # Simple input
97
+ self.assertRaises(
98
+ ValueError,
99
+ tokenizer_r.batch_encode_plus,
100
+ s2,
101
+ max_length=max_length,
102
+ padding="max_length",
103
+ )
104
+
105
+ # Pair input
106
+ self.assertRaises(ValueError, tokenizer_r.encode, p, max_length=max_length, padding="max_length")
107
+
108
+ # Pair input
109
+ self.assertRaises(ValueError, tokenizer_r.encode_plus, p, max_length=max_length, padding="max_length")
110
+
111
+ # Pair input
112
+ self.assertRaises(
113
+ ValueError,
114
+ tokenizer_r.batch_encode_plus,
115
+ p2,
116
+ max_length=max_length,
117
+ padding="max_length",
118
+ )
119
+
120
+ def test_encodings_from_xnli_dataset(self):
121
+ """
122
+ Tests the tokenizer downloaded from here:
123
+ - https://huggingface.co/bigscience/tokenizer/
124
+ """
125
+ tokenizer = self.get_rust_tokenizer()
126
+ ds = load_dataset("facebook/xnli", "all_languages", split="test", streaming=True)
127
+
128
+ sample_data = next(iter(ds))["premise"] # pick up one data
129
+ input_text = list(sample_data.values())
130
+
131
+ output_tokens = list(map(tokenizer.encode, input_text))
132
+ predicted_text = [tokenizer.decode(x, clean_up_tokenization_spaces=False) for x in output_tokens]
133
+ self.assertListEqual(predicted_text, input_text)
134
+
135
+ @require_jinja
136
+ def test_tokenization_for_chat(self):
137
+ tokenizer = self.get_rust_tokenizer()
138
+ tokenizer.chat_template = "{% for message in messages %}" "{{ message.content }}{{ eos_token }}" "{% endfor %}"
139
+ test_chats = [
140
+ [{"role": "system", "content": "You are a helpful chatbot."}, {"role": "user", "content": "Hello!"}],
141
+ [
142
+ {"role": "system", "content": "You are a helpful chatbot."},
143
+ {"role": "user", "content": "Hello!"},
144
+ {"role": "assistant", "content": "Nice to meet you."},
145
+ ],
146
+ [{"role": "assistant", "content": "Nice to meet you."}, {"role": "user", "content": "Hello!"}],
147
+ ]
148
+ tokenized_chats = [tokenizer.apply_chat_template(test_chat) for test_chat in test_chats]
149
+ expected_tokens = [
150
+ [5448, 1306, 267, 66799, 44799, 37143, 17, 2, 59414, 4, 2],
151
+ [5448, 1306, 267, 66799, 44799, 37143, 17, 2, 59414, 4, 2, 229126, 427, 11890, 1152, 17, 2],
152
+ [229126, 427, 11890, 1152, 17, 2, 59414, 4, 2],
153
+ ]
154
+ for tokenized_chat, expected_tokens in zip(tokenized_chats, expected_tokens):
155
+ self.assertListEqual(tokenized_chat, expected_tokens)
156
+
157
+ def test_add_prefix_space_fast(self):
158
+ tokenizer_w_prefix = self.get_rust_tokenizer(add_prefix_space=True)
159
+ tokenizer_wo_prefix = self.get_rust_tokenizer(add_prefix_space=False)
160
+ tokens_w_prefix = tokenizer_w_prefix.tokenize("Hey")
161
+ tokens_wo_prefix = tokenizer_wo_prefix.tokenize("Hey")
162
+ self.assertNotEqual(tokens_w_prefix, tokens_wo_prefix)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bridgetower/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bridgetower/test_image_processing_bridgetower.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The Intel Labs Team Authors, The Microsoft Research Team Authors and 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
+
16
+
17
+ import unittest
18
+ from typing import Dict, List, Optional, Union
19
+
20
+ import numpy as np
21
+
22
+ from transformers.testing_utils import require_torch, require_vision
23
+ from transformers.utils import is_vision_available
24
+
25
+ from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs
26
+
27
+
28
+ if is_vision_available():
29
+ from PIL import Image
30
+
31
+ from transformers import BridgeTowerImageProcessor
32
+
33
+
34
+ class BridgeTowerImageProcessingTester(unittest.TestCase):
35
+ def __init__(
36
+ self,
37
+ parent,
38
+ do_resize: bool = True,
39
+ size: Dict[str, int] = None,
40
+ size_divisor: int = 32,
41
+ do_rescale: bool = True,
42
+ rescale_factor: Union[int, float] = 1 / 255,
43
+ do_normalize: bool = True,
44
+ do_center_crop: bool = True,
45
+ image_mean: Optional[Union[float, List[float]]] = [0.48145466, 0.4578275, 0.40821073],
46
+ image_std: Optional[Union[float, List[float]]] = [0.26862954, 0.26130258, 0.27577711],
47
+ do_pad: bool = True,
48
+ batch_size=7,
49
+ min_resolution=30,
50
+ max_resolution=400,
51
+ num_channels=3,
52
+ ):
53
+ super().__init__()
54
+ self.parent = parent
55
+ self.do_resize = do_resize
56
+ self.size = size if size is not None else {"shortest_edge": 288}
57
+ self.size_divisor = size_divisor
58
+ self.do_rescale = do_rescale
59
+ self.rescale_factor = rescale_factor
60
+ self.do_normalize = do_normalize
61
+ self.do_center_crop = do_center_crop
62
+ self.image_mean = image_mean
63
+ self.image_std = image_std
64
+ self.do_pad = do_pad
65
+ self.batch_size = batch_size
66
+ self.num_channels = num_channels
67
+ self.min_resolution = min_resolution
68
+ self.max_resolution = max_resolution
69
+
70
+ def prepare_image_processor_dict(self):
71
+ return {
72
+ "image_mean": self.image_mean,
73
+ "image_std": self.image_std,
74
+ "do_normalize": self.do_normalize,
75
+ "do_resize": self.do_resize,
76
+ "size": self.size,
77
+ "size_divisor": self.size_divisor,
78
+ }
79
+
80
+ def get_expected_values(self, image_inputs, batched=False):
81
+ """
82
+ This function computes the expected height and width when providing images to BridgeTowerImageProcessor,
83
+ assuming do_resize is set to True with a scalar size and size_divisor.
84
+ """
85
+ if not batched:
86
+ size = self.size["shortest_edge"]
87
+ image = image_inputs[0]
88
+ if isinstance(image, Image.Image):
89
+ w, h = image.size
90
+ elif isinstance(image, np.ndarray):
91
+ h, w = image.shape[0], image.shape[1]
92
+ else:
93
+ h, w = image.shape[1], image.shape[2]
94
+ scale = size / min(w, h)
95
+ if h < w:
96
+ newh, neww = size, scale * w
97
+ else:
98
+ newh, neww = scale * h, size
99
+
100
+ max_size = int((1333 / 800) * size)
101
+ if max(newh, neww) > max_size:
102
+ scale = max_size / max(newh, neww)
103
+ newh = newh * scale
104
+ neww = neww * scale
105
+
106
+ newh, neww = int(newh + 0.5), int(neww + 0.5)
107
+ expected_height, expected_width = (
108
+ newh // self.size_divisor * self.size_divisor,
109
+ neww // self.size_divisor * self.size_divisor,
110
+ )
111
+
112
+ else:
113
+ expected_values = []
114
+ for image in image_inputs:
115
+ expected_height, expected_width = self.get_expected_values([image])
116
+ expected_values.append((expected_height, expected_width))
117
+ expected_height = max(expected_values, key=lambda item: item[0])[0]
118
+ expected_width = max(expected_values, key=lambda item: item[1])[1]
119
+
120
+ return expected_height, expected_width
121
+
122
+ def expected_output_image_shape(self, images):
123
+ height, width = self.get_expected_values(images, batched=True)
124
+ return self.num_channels, height, width
125
+
126
+ def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
127
+ return prepare_image_inputs(
128
+ batch_size=self.batch_size,
129
+ num_channels=self.num_channels,
130
+ min_resolution=self.min_resolution,
131
+ max_resolution=self.max_resolution,
132
+ equal_resolution=equal_resolution,
133
+ numpify=numpify,
134
+ torchify=torchify,
135
+ )
136
+
137
+
138
+ @require_torch
139
+ @require_vision
140
+ class BridgeTowerImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
141
+ image_processing_class = BridgeTowerImageProcessor if is_vision_available() else None
142
+
143
+ def setUp(self):
144
+ super().setUp()
145
+ self.image_processor_tester = BridgeTowerImageProcessingTester(self)
146
+
147
+ @property
148
+ def image_processor_dict(self):
149
+ return self.image_processor_tester.prepare_image_processor_dict()
150
+
151
+ def test_image_processor_properties(self):
152
+ image_processing = self.image_processing_class(**self.image_processor_dict)
153
+ self.assertTrue(hasattr(image_processing, "image_mean"))
154
+ self.assertTrue(hasattr(image_processing, "image_std"))
155
+ self.assertTrue(hasattr(image_processing, "do_normalize"))
156
+ self.assertTrue(hasattr(image_processing, "do_resize"))
157
+ self.assertTrue(hasattr(image_processing, "size"))
158
+ self.assertTrue(hasattr(image_processing, "size_divisor"))
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bridgetower/test_modeling_bridgetower.py ADDED
@@ -0,0 +1,692 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The Intel Labs Team Authors, The Microsoft Research Team Authors and 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
+ """Testing suite for the PyTorch BridgeTower model."""
16
+
17
+ import tempfile
18
+ import unittest
19
+
20
+ import numpy as np
21
+
22
+ from transformers import (
23
+ BridgeTowerConfig,
24
+ BridgeTowerTextConfig,
25
+ BridgeTowerVisionConfig,
26
+ is_torch_available,
27
+ is_vision_available,
28
+ )
29
+ from transformers.testing_utils import require_torch, require_vision, slow, torch_device
30
+ from transformers.utils import cached_property
31
+
32
+ from ...test_configuration_common import ConfigTester
33
+ from ...test_modeling_common import (
34
+ ModelTesterMixin,
35
+ _config_zero_init,
36
+ floats_tensor,
37
+ ids_tensor,
38
+ random_attention_mask,
39
+ )
40
+ from ...test_pipeline_mixin import PipelineTesterMixin
41
+
42
+
43
+ if is_torch_available():
44
+ import torch
45
+
46
+ from transformers import (
47
+ BridgeTowerForContrastiveLearning,
48
+ BridgeTowerForImageAndTextRetrieval,
49
+ BridgeTowerForMaskedLM,
50
+ BridgeTowerModel,
51
+ )
52
+
53
+ if is_vision_available():
54
+ from PIL import Image
55
+
56
+ from transformers import BridgeTowerProcessor
57
+
58
+
59
+ class BridgeTowerTextModelTester:
60
+ def __init__(
61
+ self,
62
+ parent,
63
+ hidden_act="gelu",
64
+ hidden_size=64,
65
+ initializer_factor=1,
66
+ layer_norm_eps=1e-05,
67
+ num_attention_heads=4,
68
+ num_hidden_layers=2,
69
+ intermediate_size=128,
70
+ tie_word_embeddings=False,
71
+ output_hidden_states=False,
72
+ ):
73
+ self.parent = parent
74
+ self.hidden_act = hidden_act
75
+ self.hidden_size = hidden_size
76
+ self.initializer_factor = initializer_factor
77
+ self.layer_norm_eps = layer_norm_eps
78
+ self.num_attention_heads = num_attention_heads
79
+ self.num_hidden_layers = num_hidden_layers
80
+ self.intermediate_size = intermediate_size
81
+ self.tie_word_embeddings = tie_word_embeddings
82
+ self.vocab_size = 99
83
+ self.seq_length = 4
84
+ self.batch_size = 1
85
+ self.is_training = False
86
+ self.output_hidden_states = output_hidden_states
87
+
88
+ def prepare_config_and_inputs(self):
89
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
90
+ attention_mask = random_attention_mask([self.batch_size, self.seq_length])
91
+
92
+ config = self.get_config()
93
+
94
+ return config, input_ids, attention_mask
95
+
96
+ def get_config(self):
97
+ return BridgeTowerTextConfig(
98
+ hidden_act=self.hidden_act,
99
+ hidden_size=self.hidden_size,
100
+ initializer_factor=self.initializer_factor,
101
+ layer_norm_eps=self.layer_norm_eps,
102
+ num_attention_heads=self.num_attention_heads,
103
+ num_hidden_layers=self.num_hidden_layers,
104
+ intermediate_size=self.intermediate_size,
105
+ tie_word_embeddings=self.tie_word_embeddings,
106
+ output_hidden_states=self.output_hidden_states,
107
+ vocab_size=self.vocab_size,
108
+ )
109
+
110
+
111
+ class BridgeTowerImageModelTester:
112
+ def __init__(
113
+ self,
114
+ parent,
115
+ hidden_size=64,
116
+ initializer_factor=1,
117
+ layer_norm_eps=1e-05,
118
+ num_hidden_layers=2,
119
+ init_layernorm_from_vision_encoder=False,
120
+ output_hidden_states=False,
121
+ image_size=64,
122
+ ):
123
+ self.parent = parent
124
+ self.hidden_size = hidden_size
125
+ self.initializer_factor = initializer_factor
126
+ self.layer_norm_eps = layer_norm_eps
127
+ self.num_hidden_layers = num_hidden_layers
128
+ self.init_layernorm_from_vision_encoder = init_layernorm_from_vision_encoder
129
+ self.num_channels = 3
130
+ self.num_image_features = 17
131
+ self.batch_size = 1
132
+ self.image_size = image_size
133
+ self.is_training = False
134
+ self.output_hidden_states = output_hidden_states
135
+
136
+ def prepare_config_and_inputs(self):
137
+ pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
138
+ pixel_mask = random_attention_mask([self.batch_size, self.image_size, self.image_size])
139
+ config = self.get_config()
140
+
141
+ return config, pixel_values, pixel_mask
142
+
143
+ def get_config(self):
144
+ return BridgeTowerVisionConfig(
145
+ hidden_size=self.hidden_size,
146
+ initializer_factor=self.initializer_factor,
147
+ layer_norm_eps=self.layer_norm_eps,
148
+ num_hidden_layers=self.num_hidden_layers,
149
+ init_layernorm_from_vision_encoder=self.init_layernorm_from_vision_encoder,
150
+ num_channels=self.num_channels,
151
+ num_image_features=self.num_image_features,
152
+ batch_size=self.batch_size,
153
+ image_size=self.image_size,
154
+ is_training=self.is_training,
155
+ output_hidden_states=self.output_hidden_states,
156
+ )
157
+
158
+
159
+ class BridgeTowerModelTester:
160
+ def __init__(
161
+ self,
162
+ parent,
163
+ text_kwargs=None,
164
+ vision_kwargs=None,
165
+ share_cross_modal_transformer_layers=True,
166
+ share_link_tower_layers=False,
167
+ link_tower_type="add",
168
+ init_layernorm_from_vision_encoder=False,
169
+ contrastive_hidden_size=512,
170
+ logit_scale_init_value=2.6592,
171
+ hidden_size=64,
172
+ num_hidden_layers=2,
173
+ num_attention_heads=4,
174
+ intermediate_size=128,
175
+ ):
176
+ if text_kwargs is None:
177
+ text_kwargs = {}
178
+ if vision_kwargs is None:
179
+ vision_kwargs = {}
180
+
181
+ self.parent = parent
182
+ self.text_model_tester = BridgeTowerTextModelTester(parent, **text_kwargs)
183
+ self.vision_model_tester = BridgeTowerImageModelTester(parent, **vision_kwargs)
184
+
185
+ self.share_cross_modal_transformer_layers = share_cross_modal_transformer_layers
186
+ self.share_link_tower_layers = share_link_tower_layers
187
+ self.link_tower_type = link_tower_type
188
+ self.init_layernorm_from_vision_encoder = init_layernorm_from_vision_encoder
189
+ self.contrastive_hidden_size = contrastive_hidden_size
190
+ self.logit_scale_init_value = logit_scale_init_value
191
+
192
+ self.batch_size = 1
193
+ self.expected_num_hidden_layers = 8
194
+ self.is_training = False
195
+
196
+ self.hidden_size = hidden_size
197
+ self.num_hidden_layers = num_hidden_layers
198
+ self.num_attention_heads = num_attention_heads
199
+ self.intermediate_size = intermediate_size
200
+
201
+ def prepare_config_and_inputs(self):
202
+ text_config, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs()
203
+ vision_config, pixel_values, pixel_mask = self.vision_model_tester.prepare_config_and_inputs()
204
+
205
+ config = self.get_config()
206
+
207
+ return (config, input_ids, attention_mask, pixel_values, pixel_mask)
208
+
209
+ def get_config(self):
210
+ return BridgeTowerConfig.from_text_vision_configs(
211
+ text_config=self.text_model_tester.get_config(),
212
+ vision_config=self.vision_model_tester.get_config(),
213
+ share_cross_modal_transformer_layers=self.share_cross_modal_transformer_layers,
214
+ share_link_tower_layers=self.share_link_tower_layers,
215
+ link_tower_type=self.link_tower_type,
216
+ init_layernorm_from_vision_encoder=self.init_layernorm_from_vision_encoder,
217
+ contrastive_hidden_size=self.contrastive_hidden_size,
218
+ logit_scale_init_value=self.logit_scale_init_value,
219
+ hidden_size=self.hidden_size,
220
+ num_hidden_layers=self.num_hidden_layers,
221
+ num_attention_heads=self.num_attention_heads,
222
+ intermediate_size=self.intermediate_size,
223
+ )
224
+
225
+ def create_and_check_model(
226
+ self,
227
+ config,
228
+ input_ids,
229
+ attention_mask,
230
+ pixel_values,
231
+ pixel_mask,
232
+ ):
233
+ model = BridgeTowerModel(config=config)
234
+ model.to(torch_device)
235
+ model.eval()
236
+ result = model(input_ids, attention_mask=attention_mask, pixel_values=pixel_values, pixel_mask=pixel_mask)
237
+ result = model(input_ids, attention_mask=attention_mask, pixel_values=pixel_values)
238
+ self.parent.assertEqual(
239
+ result["text_features"].shape,
240
+ (self.batch_size, self.text_model_tester.seq_length, self.text_model_tester.hidden_size),
241
+ )
242
+ self.parent.assertEqual(
243
+ result["image_features"].shape,
244
+ (self.batch_size, self.vision_model_tester.num_image_features, self.vision_model_tester.hidden_size),
245
+ )
246
+ self.parent.assertEqual(
247
+ result["pooler_output"].shape,
248
+ (self.batch_size, self.text_model_tester.hidden_size + self.vision_model_tester.hidden_size),
249
+ )
250
+
251
+ def create_and_check_for_image_and_text_retrieval(
252
+ self,
253
+ config,
254
+ input_ids,
255
+ attention_mask,
256
+ pixel_values,
257
+ pixel_mask,
258
+ ):
259
+ bridgetower_itm_output_last_dimension = 2
260
+
261
+ model = BridgeTowerForImageAndTextRetrieval(config)
262
+ model.to(torch_device)
263
+ model.eval()
264
+ result = model(input_ids, attention_mask=attention_mask, pixel_values=pixel_values, pixel_mask=pixel_mask)
265
+ result = model(input_ids, attention_mask=attention_mask, pixel_values=pixel_values)
266
+
267
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, bridgetower_itm_output_last_dimension))
268
+
269
+ def create_and_check_for_masked_language_modeling(
270
+ self,
271
+ config,
272
+ input_ids,
273
+ attention_mask,
274
+ pixel_values,
275
+ pixel_mask,
276
+ ):
277
+ model = BridgeTowerForMaskedLM(config)
278
+ model.to(torch_device)
279
+ model.eval()
280
+ result = model(input_ids, attention_mask=attention_mask, pixel_values=pixel_values, pixel_mask=pixel_mask)
281
+ result = model(input_ids, attention_mask=attention_mask, pixel_values=pixel_values)
282
+
283
+ self.parent.assertEqual(
284
+ result.logits.shape,
285
+ (self.batch_size, self.text_model_tester.seq_length, self.text_model_tester.vocab_size),
286
+ )
287
+
288
+ def prepare_config_and_inputs_for_common(self):
289
+ config_and_inputs = self.prepare_config_and_inputs()
290
+ (config, input_ids, attention_mask, pixel_values, pixel_mask) = config_and_inputs
291
+ inputs_dict = {
292
+ "input_ids": input_ids,
293
+ "attention_mask": attention_mask,
294
+ "pixel_values": pixel_values,
295
+ "pixel_mask": pixel_mask,
296
+ }
297
+ return config, inputs_dict
298
+
299
+
300
+ @require_torch
301
+ class BridgeTowerModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
302
+ all_model_classes = (
303
+ (
304
+ BridgeTowerModel,
305
+ BridgeTowerForImageAndTextRetrieval,
306
+ BridgeTowerForMaskedLM,
307
+ BridgeTowerForContrastiveLearning,
308
+ )
309
+ if is_torch_available()
310
+ else ()
311
+ )
312
+ pipeline_model_mapping = {"feature-extraction": BridgeTowerModel} if is_torch_available() else {}
313
+
314
+ is_training = False
315
+ test_headmasking = False
316
+ test_pruning = False
317
+ test_torchscript = False
318
+ test_resize_embeddings = False
319
+ has_attentions = False
320
+
321
+ @unittest.skip(reason="Does not work on the tiny model as we keep hitting edge cases.")
322
+ def test_cpu_offload(self):
323
+ pass
324
+
325
+ @unittest.skip(reason="Does not work on the tiny model as we keep hitting edge cases.")
326
+ def test_disk_offload(self):
327
+ pass
328
+
329
+ @unittest.skip(reason="Does not work on the tiny model as we keep hitting edge cases.")
330
+ def test_model_parallelism(self):
331
+ pass
332
+
333
+ # function to extract meaningful tensor from output per different model_class
334
+ def extract_output(self, outputs, model_class):
335
+ return outputs["pooler_output"] if model_class == "BridgeTowerModel" else outputs["logits"]
336
+
337
+ def setUp(self):
338
+ self.model_tester = BridgeTowerModelTester(self)
339
+ self.config_tester = ConfigTester(self, config_class=BridgeTowerConfig, hidden_size=37, vocab_size=99)
340
+
341
+ def test_config(self):
342
+ self.config_tester.run_common_tests()
343
+
344
+ def test_model(self):
345
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
346
+ self.model_tester.create_and_check_model(*config_and_inputs)
347
+
348
+ def test_for_image_and_text_retrieval(self):
349
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
350
+ self.model_tester.create_and_check_for_image_and_text_retrieval(*config_and_inputs)
351
+
352
+ def test_for_masked_language_modeling(self):
353
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
354
+ self.model_tester.create_and_check_for_masked_language_modeling(*config_and_inputs)
355
+
356
+ @slow
357
+ def test_model_from_pretrained(self):
358
+ model_name = "BridgeTower/bridgetower-base"
359
+ model = BridgeTowerModel.from_pretrained(model_name)
360
+ self.assertIsNotNone(model)
361
+
362
+ @slow
363
+ def test_save_load_fast_init_from_base(self):
364
+ # Override as it is a slow test on this model
365
+ super().test_save_load_fast_init_from_base()
366
+
367
+ # Override as extracting meaningful tensor from output is different for BridgeTower
368
+ def test_save_load(self):
369
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
370
+ for model_class in self.all_model_classes:
371
+ model = model_class(config)
372
+ model.to(torch_device)
373
+ model.eval()
374
+ with torch.no_grad():
375
+ outputs = model(**input_dict)
376
+
377
+ out_2 = self.extract_output(outputs, model_class.__name__)
378
+ out_2 = out_2.cpu().numpy()
379
+ out_2[np.isnan(out_2)] = 0
380
+
381
+ with tempfile.TemporaryDirectory() as tmpdirname:
382
+ model.save_pretrained(tmpdirname)
383
+ model = model_class.from_pretrained(tmpdirname)
384
+ model.to(torch_device)
385
+ with torch.no_grad():
386
+ after_outputs = model(**input_dict)
387
+
388
+ # Make sure we don't have nans
389
+ out_1 = self.extract_output(after_outputs, model_class.__name__)
390
+ out_1 = out_1.cpu().numpy()
391
+ out_1[np.isnan(out_1)] = 0
392
+ max_diff = np.amax(np.abs(out_1 - out_2))
393
+ self.assertLessEqual(max_diff, 1e-5)
394
+
395
+ # Override this as `hidden states output` is different for BridgeTower
396
+ def test_hidden_states_output(self):
397
+ def check_hidden_states_output(inputs_dict, config, model_class):
398
+ model = model_class(config)
399
+ model.to(torch_device)
400
+ model.eval()
401
+
402
+ with torch.no_grad():
403
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
404
+
405
+ hidden_states_text, hidden_states_vision, hidden_states_cross = (
406
+ outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
407
+ )
408
+
409
+ expected_num_layers = self.model_tester.expected_num_hidden_layers
410
+ self.assertEqual(
411
+ sum((len(hidden_states_text), len(hidden_states_vision), len(hidden_states_cross))),
412
+ expected_num_layers,
413
+ )
414
+
415
+ seq_length = self.model_tester.text_model_tester.seq_length
416
+ num_image_features = self.model_tester.vision_model_tester.num_image_features
417
+
418
+ self.assertListEqual(
419
+ list(hidden_states_text[0].shape[-2:]),
420
+ [seq_length, self.model_tester.text_model_tester.hidden_size],
421
+ )
422
+ self.assertListEqual(
423
+ list(hidden_states_vision[0].shape),
424
+ [num_image_features, 1, self.model_tester.vision_model_tester.hidden_size],
425
+ )
426
+ self.assertListEqual(
427
+ list(hidden_states_cross[0][0].shape[-2:]),
428
+ [seq_length, self.model_tester.text_model_tester.hidden_size],
429
+ )
430
+ self.assertListEqual(
431
+ list(hidden_states_cross[0][1].shape[-2:]),
432
+ [num_image_features, self.model_tester.vision_model_tester.hidden_size],
433
+ )
434
+
435
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
436
+
437
+ for model_class in self.all_model_classes:
438
+ inputs_dict["output_hidden_states"] = True
439
+ check_hidden_states_output(inputs_dict, config, model_class)
440
+
441
+ # check that output_hidden_states also work using config
442
+ del inputs_dict["output_hidden_states"]
443
+ config.output_hidden_states = True
444
+ check_hidden_states_output(inputs_dict, config, model_class)
445
+
446
+ # Override as `hidden states output` is different for BridgeTower
447
+ def test_retain_grad_hidden_states_attentions(self):
448
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
449
+ config.output_hidden_states = True
450
+ config.output_attentions = self.has_attentions
451
+
452
+ # no need to test all models as different heads yield the same functionality
453
+ model_class = self.all_model_classes[0]
454
+ model = model_class(config)
455
+ model.to(torch_device)
456
+
457
+ inputs = self._prepare_for_class(inputs_dict, model_class)
458
+
459
+ outputs = model(**inputs)
460
+
461
+ output = outputs[0]
462
+
463
+ # Encoder-/Decoder-only models
464
+ hidden_states = outputs.hidden_states[0][0]
465
+ hidden_states.retain_grad()
466
+
467
+ if self.has_attentions:
468
+ attentions = outputs.attentions[0][0]
469
+ attentions.retain_grad()
470
+
471
+ output.flatten()[0].backward(retain_graph=True)
472
+
473
+ self.assertIsNotNone(hidden_states.grad)
474
+
475
+ if self.has_attentions:
476
+ self.assertIsNotNone(attentions.grad)
477
+
478
+ # override as the `logit_scale` parameter initilization is different for BRIDGE TOWER
479
+ def test_initialization(self):
480
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
481
+
482
+ configs_no_init = _config_zero_init(config)
483
+ for model_class in self.all_model_classes:
484
+ model = model_class(config=configs_no_init)
485
+ for name, param in model.named_parameters():
486
+ if param.requires_grad:
487
+ if name == "logit_scale":
488
+ self.assertAlmostEqual(
489
+ param.data.item(),
490
+ config.logit_scale_init_value,
491
+ delta=1e-3,
492
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
493
+ )
494
+ else:
495
+ self.assertIn(
496
+ ((param.data.mean() * 1e9).round() / 1e9).item(),
497
+ [0.0, 1.0],
498
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
499
+ )
500
+
501
+ @unittest.skip(reason="""Bridge Tower does not have input/output embeddings. So this test is not applicable.""")
502
+ def test_model_get_set_embeddings(self):
503
+ pass
504
+
505
+ @unittest.skip(reason="""Bridge Tower does not have input/output embeddings. Thus this test is not applicable.""")
506
+ def test_inputs_embeds(self):
507
+ pass
508
+
509
+ @unittest.skip(reason="Bridge Tower does not use inputs_embeds")
510
+ def test_inputs_embeds_matches_input_ids(self):
511
+ pass
512
+
513
+
514
+ # We will verify our results on an image of cute cats
515
+ def prepare_img():
516
+ image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
517
+ return image
518
+
519
+
520
+ @require_torch
521
+ @require_vision
522
+ class BridgeTowerModelIntegrationTest(unittest.TestCase):
523
+ @cached_property
524
+ def default_processor(self):
525
+ return (
526
+ BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-base-itm-mlm")
527
+ if is_vision_available()
528
+ else None
529
+ )
530
+
531
+ @slow
532
+ def test_image_and_text_retrieval(self):
533
+ model = BridgeTowerForImageAndTextRetrieval.from_pretrained("BridgeTower/bridgetower-base-itm-mlm").to(
534
+ torch_device
535
+ )
536
+ model.eval()
537
+ processor = self.default_processor
538
+ image = prepare_img()
539
+ text = "a bunch of cats laying on a tower."
540
+ inputs = processor(image, text, return_tensors="pt").to(torch_device)
541
+
542
+ # forward pass
543
+ with torch.no_grad():
544
+ outputs = model(**inputs)
545
+
546
+ # verify the logits
547
+ expected_shape = torch.Size([1, 2])
548
+ self.assertEqual(outputs.logits.shape, expected_shape)
549
+ self.assertTrue(outputs.logits[0, 1].item() > outputs.logits[0, 0].item())
550
+
551
+ # verify loss
552
+ inputs["labels"] = torch.ones(1, dtype=torch.long, device=torch_device)
553
+ inputs = inputs.to(torch_device)
554
+ with torch.no_grad():
555
+ outputs = model(**inputs)
556
+ self.assertAlmostEqual(outputs.loss.item(), 0.5108, places=4)
557
+
558
+ @slow
559
+ def test_masked_language_modeling(self):
560
+ model = BridgeTowerForMaskedLM.from_pretrained("BridgeTower/bridgetower-base-itm-mlm").to(torch_device)
561
+ model.eval()
562
+ processor = self.default_processor
563
+ image = prepare_img()
564
+ text = "a bunch of <mask> laying on a tower."
565
+ inputs = processor(image, text, return_tensors="pt").to(torch_device)
566
+
567
+ # forward pass
568
+ with torch.no_grad():
569
+ outputs = model(**inputs)
570
+
571
+ # verify the logits
572
+ expected_shape = torch.Size([1, 11, 50265])
573
+ self.assertEqual(outputs.logits.shape, expected_shape)
574
+
575
+ # verify predicted word
576
+ predicted_id = outputs.logits.argmax(dim=-1).squeeze(0).tolist()[4]
577
+ self.assertTrue(processor.decode([predicted_id]) == " cats")
578
+
579
+ # verify loss
580
+ inputs["labels"] = inputs["input_ids"].clone()
581
+ inputs = inputs.to(torch_device)
582
+ with torch.no_grad():
583
+ outputs = model(**inputs)
584
+ self.assertAlmostEqual(outputs.loss.item(), 5.7373, places=4)
585
+
586
+ @slow
587
+ def test_constrastive_learning(self):
588
+ model = BridgeTowerForContrastiveLearning.from_pretrained("BridgeTower/bridgetower-large-itm-mlm-itc").to(
589
+ torch_device
590
+ )
591
+ model.eval()
592
+ processor = BridgeTowerProcessor.from_pretrained("BridgeTower/bridgetower-large-itm-mlm-itc")
593
+ image = prepare_img()
594
+ text = "a bunch of cats laying on a tower."
595
+ inputs = processor(image, text, padding=True, return_tensors="pt").to(torch_device)
596
+ with torch.no_grad():
597
+ outputs = model(**inputs, output_hidden_states=True, return_loss=True)
598
+
599
+ # verify the logits
600
+ expected_shape = torch.Size([1, 3, 512])
601
+ self.assertEqual(outputs.logits.shape, expected_shape)
602
+
603
+
604
+ @slow
605
+ @require_torch
606
+ class BridgeTowerModelTrainingTest(unittest.TestCase):
607
+ all_training_supported_model_classes = (
608
+ (BridgeTowerForImageAndTextRetrieval, BridgeTowerForMaskedLM, BridgeTowerForContrastiveLearning)
609
+ if is_torch_available()
610
+ else ()
611
+ )
612
+
613
+ def setUp(self):
614
+ self.model_tester = BridgeTowerModelTester(self)
615
+ self.config_tester = ConfigTester(self, config_class=BridgeTowerConfig, hidden_size=37, vocab_size=99)
616
+
617
+ def _prepare_inputs_for_training(self, model_class):
618
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
619
+ if model_class == BridgeTowerForMaskedLM:
620
+ inputs_dict["labels"] = inputs_dict["input_ids"]
621
+ elif model_class == BridgeTowerForImageAndTextRetrieval:
622
+ inputs_dict["labels"] = ids_tensor([1], 2)
623
+ elif model_class == BridgeTowerForContrastiveLearning:
624
+ inputs_dict["return_loss"] = True
625
+ return config, inputs_dict
626
+
627
+ def _get_non_used_layer_names(self, model_class):
628
+ non_used_layer_names = ["text_model.pooler"]
629
+ if model_class == BridgeTowerForMaskedLM:
630
+ non_used_layer_names = non_used_layer_names + [
631
+ # This number `1` actually depends on the number of layers in `cross_modal_image_layers` (by minus 1)
632
+ "cross_modal_image_layers.1",
633
+ "cross_modal_image_pooler",
634
+ "cross_modal_text_pooler",
635
+ ]
636
+ return non_used_layer_names
637
+
638
+ def _is_layer_used(self, model_class, layer_name):
639
+ non_used_layer_names = self._get_non_used_layer_names(model_class)
640
+ for non_used_layer_name in non_used_layer_names:
641
+ if non_used_layer_name in layer_name:
642
+ return False
643
+ return True
644
+
645
+ def test_training(self):
646
+ for model_class in self.all_training_supported_model_classes:
647
+ config, inputs_dict = self._prepare_inputs_for_training(model_class)
648
+ model = model_class(config)
649
+ model.to(torch_device)
650
+ model.train()
651
+
652
+ loss = model(**inputs_dict).loss
653
+ loss.backward()
654
+
655
+ # verify the gradients of used layers' weight are not None
656
+ for name, param in model.named_parameters():
657
+ if self._is_layer_used(model_class, name):
658
+ self.assertIsNotNone(param.grad, f"Gradients should not be None - got {param.grad} for {name}")
659
+
660
+ @slow
661
+ def test_inference_interpolate_pos_encoding(self):
662
+ # ViT models have an `interpolate_pos_encoding` argument in their forward method,
663
+ # allowing to interpolate the pre-trained position embeddings in order to use
664
+ # the model on higher resolutions. The DINO model by Facebook AI leverages this
665
+ # to visualize self-attention on higher resolution images.
666
+ model_name = "BridgeTower/bridgetower-base"
667
+ model = BridgeTowerModel.from_pretrained(model_name).to(torch_device)
668
+
669
+ image_processor = BridgeTowerProcessor.from_pretrained(model_name, size={"shortest_edge": 180})
670
+
671
+ image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
672
+ inputs = image_processor(text="what's in the image", images=image, return_tensors="pt").to(torch_device)
673
+
674
+ # interpolate_pos_encodiung false should return value error
675
+ with self.assertRaises(ValueError, msg="doesn't match model"):
676
+ with torch.no_grad():
677
+ model(**inputs, interpolate_pos_encoding=False)
678
+
679
+ # forward pass
680
+ with torch.no_grad():
681
+ outputs = model(**inputs, interpolate_pos_encoding=True)
682
+
683
+ # verify the logits
684
+ expected_shape = torch.Size((1, 122, 768))
685
+
686
+ self.assertEqual(outputs.image_features.shape, expected_shape)
687
+
688
+ expected_slice = torch.tensor(
689
+ [[-0.6518, 0.4978, -0.4544], [-2.6672, -0.0843, -0.4210], [-2.4510, -0.1002, -0.3458]]
690
+ ).to(torch_device)
691
+
692
+ self.assertTrue(torch.allclose(outputs.image_features[0, :3, :3], expected_slice, atol=1e-4))
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bridgetower/test_processor_bridgetower.py ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 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
+ import shutil
15
+ import tempfile
16
+ import unittest
17
+
18
+ from transformers.testing_utils import require_torch, require_vision
19
+ from transformers.utils import is_vision_available
20
+
21
+ from ...test_processing_common import ProcessorTesterMixin
22
+
23
+
24
+ if is_vision_available():
25
+ from transformers import (
26
+ AutoProcessor,
27
+ BridgeTowerImageProcessor,
28
+ BridgeTowerProcessor,
29
+ RobertaTokenizerFast,
30
+ )
31
+
32
+
33
+ @require_vision
34
+ class BridgeTowerProcessorTest(ProcessorTesterMixin, unittest.TestCase):
35
+ processor_class = BridgeTowerProcessor
36
+
37
+ def setUp(self):
38
+ self.tmpdirname = tempfile.mkdtemp()
39
+
40
+ image_processor = BridgeTowerImageProcessor()
41
+ tokenizer = RobertaTokenizerFast.from_pretrained("BridgeTower/bridgetower-large-itm-mlm-itc")
42
+
43
+ processor = BridgeTowerProcessor(image_processor, tokenizer)
44
+
45
+ processor.save_pretrained(self.tmpdirname)
46
+
47
+ def get_tokenizer(self, **kwargs):
48
+ return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).tokenizer
49
+
50
+ def get_image_processor(self, **kwargs):
51
+ return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).image_processor
52
+
53
+ def tearDown(self):
54
+ shutil.rmtree(self.tmpdirname)
55
+
56
+ # Some kwargs tests are overriden from common tests to handle shortest_edge
57
+ # and size_divisor behaviour
58
+
59
+ @require_torch
60
+ @require_vision
61
+ def test_image_processor_defaults_preserved_by_image_kwargs(self):
62
+ if "image_processor" not in self.processor_class.attributes:
63
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
64
+ image_processor = self.get_component(
65
+ "image_processor",
66
+ crop_size={"shortest_edge": 234, "longest_edge": 234},
67
+ )
68
+ tokenizer = self.get_component("tokenizer", max_length=117, padding="max_length")
69
+
70
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
71
+ self.skip_processor_without_typed_kwargs(processor)
72
+
73
+ input_str = "lower newer"
74
+ image_input = self.prepare_image_inputs()
75
+
76
+ inputs = processor(text=input_str, images=image_input)
77
+ self.assertEqual(len(inputs["pixel_values"][0][0]), 234)
78
+
79
+ @require_torch
80
+ @require_vision
81
+ def test_structured_kwargs_nested_from_dict(self):
82
+ if "image_processor" not in self.processor_class.attributes:
83
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
84
+
85
+ image_processor = self.get_component("image_processor")
86
+ tokenizer = self.get_component("tokenizer")
87
+
88
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
89
+ self.skip_processor_without_typed_kwargs(processor)
90
+ input_str = "lower newer"
91
+ image_input = self.prepare_image_inputs()
92
+
93
+ # Define the kwargs for each modality
94
+ all_kwargs = {
95
+ "common_kwargs": {"return_tensors": "pt"},
96
+ "images_kwargs": {
97
+ "crop_size": {"shortest_edge": 214},
98
+ },
99
+ "text_kwargs": {"padding": "max_length", "max_length": 76},
100
+ }
101
+
102
+ inputs = processor(text=input_str, images=image_input, **all_kwargs)
103
+ self.assertEqual(inputs["pixel_values"].shape[2], 214)
104
+
105
+ self.assertEqual(len(inputs["input_ids"][0]), 76)
106
+
107
+ @require_torch
108
+ @require_vision
109
+ def test_kwargs_overrides_default_image_processor_kwargs(self):
110
+ if "image_processor" not in self.processor_class.attributes:
111
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
112
+ image_processor = self.get_component("image_processor", crop_size={"shortest_edge": 234})
113
+ tokenizer = self.get_component("tokenizer", max_length=117)
114
+ if not tokenizer.pad_token:
115
+ tokenizer.pad_token = "[TEST_PAD]"
116
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
117
+ self.skip_processor_without_typed_kwargs(processor)
118
+
119
+ input_str = "lower newer"
120
+ image_input = self.prepare_image_inputs()
121
+ inputs = processor(text=input_str, images=image_input, crop_size={"shortest_edge": 224})
122
+ self.assertEqual(len(inputs["pixel_values"][0][0]), 224)
123
+
124
+ @require_torch
125
+ @require_vision
126
+ def test_unstructured_kwargs_batched(self):
127
+ if "image_processor" not in self.processor_class.attributes:
128
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
129
+ image_processor = self.get_component("image_processor")
130
+ tokenizer = self.get_component("tokenizer")
131
+ if not tokenizer.pad_token:
132
+ tokenizer.pad_token = "[TEST_PAD]"
133
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
134
+ self.skip_processor_without_typed_kwargs(processor)
135
+
136
+ input_str = ["lower newer", "upper older longer string"]
137
+ image_input = self.prepare_image_inputs(batch_size=2)
138
+ inputs = processor(
139
+ text=input_str,
140
+ images=image_input,
141
+ return_tensors="pt",
142
+ crop_size={"shortest_edge": 214},
143
+ padding="longest",
144
+ max_length=76,
145
+ )
146
+ self.assertEqual(inputs["pixel_values"].shape[2], 214)
147
+
148
+ self.assertEqual(len(inputs["input_ids"][0]), 6)
149
+
150
+ @require_torch
151
+ @require_vision
152
+ def test_unstructured_kwargs(self):
153
+ if "image_processor" not in self.processor_class.attributes:
154
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
155
+ image_processor = self.get_component("image_processor")
156
+ tokenizer = self.get_component("tokenizer")
157
+ if not tokenizer.pad_token:
158
+ tokenizer.pad_token = "[TEST_PAD]"
159
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
160
+ self.skip_processor_without_typed_kwargs(processor)
161
+
162
+ input_str = "lower newer"
163
+ image_input = self.prepare_image_inputs()
164
+ inputs = processor(
165
+ text=input_str,
166
+ images=image_input,
167
+ return_tensors="pt",
168
+ crop_size={"shortest_edge": 214},
169
+ padding="max_length",
170
+ max_length=76,
171
+ )
172
+
173
+ self.assertEqual(inputs["pixel_values"].shape[2], 214)
174
+ self.assertEqual(len(inputs["input_ids"][0]), 76)
175
+
176
+ @require_torch
177
+ @require_vision
178
+ def test_structured_kwargs_nested(self):
179
+ if "image_processor" not in self.processor_class.attributes:
180
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
181
+ image_processor = self.get_component("image_processor")
182
+ tokenizer = self.get_component("tokenizer")
183
+ if not tokenizer.pad_token:
184
+ tokenizer.pad_token = "[TEST_PAD]"
185
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
186
+ self.skip_processor_without_typed_kwargs(processor)
187
+
188
+ input_str = "lower newer"
189
+ image_input = self.prepare_image_inputs()
190
+
191
+ # Define the kwargs for each modality
192
+ all_kwargs = {
193
+ "common_kwargs": {"return_tensors": "pt"},
194
+ "images_kwargs": {"crop_size": {"shortest_edge": 214}},
195
+ "text_kwargs": {"padding": "max_length", "max_length": 76},
196
+ }
197
+
198
+ inputs = processor(text=input_str, images=image_input, **all_kwargs)
199
+ self.skip_processor_without_typed_kwargs(processor)
200
+
201
+ self.assertEqual(inputs["pixel_values"].shape[2], 214)
202
+
203
+ self.assertEqual(len(inputs["input_ids"][0]), 76)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bros/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/bros/test_modeling_bros.py ADDED
@@ -0,0 +1,455 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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
+ """Testing suite for the PyTorch Bros model."""
16
+
17
+ import copy
18
+ import unittest
19
+
20
+ from transformers.testing_utils import require_torch, require_torch_multi_gpu, slow, torch_device
21
+ from transformers.utils import is_torch_available
22
+
23
+ from ...test_configuration_common import ConfigTester
24
+ from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
25
+ from ...test_pipeline_mixin import PipelineTesterMixin
26
+
27
+
28
+ if is_torch_available():
29
+ import torch
30
+
31
+ from transformers import (
32
+ BrosConfig,
33
+ BrosForTokenClassification,
34
+ BrosModel,
35
+ BrosSpadeEEForTokenClassification,
36
+ BrosSpadeELForTokenClassification,
37
+ )
38
+
39
+
40
+ class BrosModelTester:
41
+ def __init__(
42
+ self,
43
+ parent,
44
+ batch_size=13,
45
+ seq_length=7,
46
+ is_training=True,
47
+ use_input_mask=True,
48
+ use_token_type_ids=True,
49
+ use_bbox_first_token_mask=True,
50
+ use_labels=True,
51
+ vocab_size=99,
52
+ hidden_size=64,
53
+ num_hidden_layers=5,
54
+ num_attention_heads=4,
55
+ intermediate_size=37,
56
+ hidden_act="gelu",
57
+ hidden_dropout_prob=0.1,
58
+ attention_probs_dropout_prob=0.1,
59
+ max_position_embeddings=512,
60
+ type_vocab_size=16,
61
+ type_sequence_label_size=2,
62
+ initializer_range=0.02,
63
+ num_labels=3,
64
+ num_choices=4,
65
+ scope=None,
66
+ ):
67
+ self.parent = parent
68
+ self.batch_size = batch_size
69
+ self.seq_length = seq_length
70
+ self.is_training = is_training
71
+ self.use_input_mask = use_input_mask
72
+ self.use_bbox_first_token_mask = use_bbox_first_token_mask
73
+ self.use_token_type_ids = use_token_type_ids
74
+ self.use_labels = use_labels
75
+ self.vocab_size = vocab_size
76
+ self.hidden_size = hidden_size
77
+ self.num_hidden_layers = num_hidden_layers
78
+ self.num_attention_heads = num_attention_heads
79
+ self.intermediate_size = intermediate_size
80
+ self.hidden_act = hidden_act
81
+ self.hidden_dropout_prob = hidden_dropout_prob
82
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
83
+ self.max_position_embeddings = max_position_embeddings
84
+ self.type_vocab_size = type_vocab_size
85
+ self.type_sequence_label_size = type_sequence_label_size
86
+ self.initializer_range = initializer_range
87
+ self.num_labels = num_labels
88
+
89
+ def prepare_config_and_inputs(self):
90
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
91
+
92
+ bbox = ids_tensor([self.batch_size, self.seq_length, 8], 1)
93
+ # Ensure that bbox is legal
94
+ for i in range(bbox.shape[0]):
95
+ for j in range(bbox.shape[1]):
96
+ if bbox[i, j, 3] < bbox[i, j, 1]:
97
+ t = bbox[i, j, 3]
98
+ bbox[i, j, 3] = bbox[i, j, 1]
99
+ bbox[i, j, 1] = t
100
+ if bbox[i, j, 2] < bbox[i, j, 0]:
101
+ t = bbox[i, j, 2]
102
+ bbox[i, j, 2] = bbox[i, j, 0]
103
+ bbox[i, j, 0] = t
104
+
105
+ input_mask = None
106
+ if self.use_input_mask:
107
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
108
+
109
+ bbox_first_token_mask = None
110
+ if self.use_bbox_first_token_mask:
111
+ bbox_first_token_mask = torch.ones([self.batch_size, self.seq_length], dtype=torch.bool).to(torch_device)
112
+
113
+ token_type_ids = None
114
+ if self.use_token_type_ids:
115
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
116
+
117
+ token_labels = None
118
+ if self.use_labels:
119
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
120
+ initial_token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
121
+ subsequent_token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
122
+
123
+ config = self.get_config()
124
+
125
+ return (
126
+ config,
127
+ input_ids,
128
+ bbox,
129
+ token_type_ids,
130
+ input_mask,
131
+ bbox_first_token_mask,
132
+ token_labels,
133
+ initial_token_labels,
134
+ subsequent_token_labels,
135
+ )
136
+
137
+ def get_config(self):
138
+ return BrosConfig(
139
+ vocab_size=self.vocab_size,
140
+ hidden_size=self.hidden_size,
141
+ num_hidden_layers=self.num_hidden_layers,
142
+ num_attention_heads=self.num_attention_heads,
143
+ intermediate_size=self.intermediate_size,
144
+ hidden_act=self.hidden_act,
145
+ hidden_dropout_prob=self.hidden_dropout_prob,
146
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
147
+ max_position_embeddings=self.max_position_embeddings,
148
+ type_vocab_size=self.type_vocab_size,
149
+ is_decoder=False,
150
+ initializer_range=self.initializer_range,
151
+ )
152
+
153
+ def create_and_check_model(
154
+ self,
155
+ config,
156
+ input_ids,
157
+ bbox,
158
+ token_type_ids,
159
+ input_mask,
160
+ bbox_first_token_mask,
161
+ token_labels,
162
+ initial_token_labels,
163
+ subsequent_token_labels,
164
+ ):
165
+ model = BrosModel(config=config)
166
+ model.to(torch_device)
167
+ model.eval()
168
+ result = model(input_ids, bbox=bbox, attention_mask=input_mask, token_type_ids=token_type_ids)
169
+ result = model(input_ids, bbox=bbox, token_type_ids=token_type_ids)
170
+ result = model(input_ids, bbox=bbox)
171
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
172
+
173
+ def create_and_check_for_token_classification(
174
+ self,
175
+ config,
176
+ input_ids,
177
+ bbox,
178
+ token_type_ids,
179
+ input_mask,
180
+ bbox_first_token_mask,
181
+ token_labels,
182
+ initial_token_labels,
183
+ subsequent_token_labels,
184
+ ):
185
+ config.num_labels = self.num_labels
186
+ model = BrosForTokenClassification(config=config)
187
+ model.to(torch_device)
188
+ model.eval()
189
+ result = model(
190
+ input_ids, bbox=bbox, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels
191
+ )
192
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
193
+
194
+ def create_and_check_for_spade_ee_token_classification(
195
+ self,
196
+ config,
197
+ input_ids,
198
+ bbox,
199
+ token_type_ids,
200
+ input_mask,
201
+ bbox_first_token_mask,
202
+ token_labels,
203
+ initial_token_labels,
204
+ subsequent_token_labels,
205
+ ):
206
+ config.num_labels = self.num_labels
207
+ model = BrosSpadeEEForTokenClassification(config=config)
208
+ model.to(torch_device)
209
+ model.eval()
210
+ result = model(
211
+ input_ids,
212
+ bbox=bbox,
213
+ attention_mask=input_mask,
214
+ bbox_first_token_mask=bbox_first_token_mask,
215
+ token_type_ids=token_type_ids,
216
+ initial_token_labels=token_labels,
217
+ subsequent_token_labels=token_labels,
218
+ )
219
+ self.parent.assertEqual(result.initial_token_logits.shape, (self.batch_size, self.seq_length, self.num_labels))
220
+ self.parent.assertEqual(
221
+ result.subsequent_token_logits.shape, (self.batch_size, self.seq_length, self.seq_length + 1)
222
+ )
223
+
224
+ def create_and_check_for_spade_el_token_classification(
225
+ self,
226
+ config,
227
+ input_ids,
228
+ bbox,
229
+ token_type_ids,
230
+ input_mask,
231
+ bbox_first_token_mask,
232
+ token_labels,
233
+ initial_token_labels,
234
+ subsequent_token_labels,
235
+ ):
236
+ config.num_labels = self.num_labels
237
+ model = BrosSpadeELForTokenClassification(config=config)
238
+ model.to(torch_device)
239
+ model.eval()
240
+ result = model(
241
+ input_ids,
242
+ bbox=bbox,
243
+ attention_mask=input_mask,
244
+ bbox_first_token_mask=bbox_first_token_mask,
245
+ token_type_ids=token_type_ids,
246
+ labels=token_labels,
247
+ )
248
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.seq_length + 1))
249
+
250
+ def prepare_config_and_inputs_for_common(self):
251
+ config_and_inputs = self.prepare_config_and_inputs()
252
+ (
253
+ config,
254
+ input_ids,
255
+ bbox,
256
+ token_type_ids,
257
+ input_mask,
258
+ bbox_first_token_mask,
259
+ token_labels,
260
+ initial_token_labels,
261
+ subsequent_token_labels,
262
+ ) = config_and_inputs
263
+ inputs_dict = {
264
+ "input_ids": input_ids,
265
+ "bbox": bbox,
266
+ "token_type_ids": token_type_ids,
267
+ "attention_mask": input_mask,
268
+ }
269
+ return config, inputs_dict
270
+
271
+
272
+ @require_torch
273
+ class BrosModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
274
+ test_pruning = False
275
+ test_torchscript = False
276
+ test_mismatched_shapes = False
277
+
278
+ all_model_classes = (
279
+ (
280
+ BrosForTokenClassification,
281
+ BrosSpadeEEForTokenClassification,
282
+ BrosSpadeELForTokenClassification,
283
+ BrosModel,
284
+ )
285
+ if is_torch_available()
286
+ else ()
287
+ )
288
+ all_generative_model_classes = () if is_torch_available() else ()
289
+ pipeline_model_mapping = (
290
+ {"feature-extraction": BrosModel, "token-classification": BrosForTokenClassification}
291
+ if is_torch_available()
292
+ else {}
293
+ )
294
+
295
+ # BROS requires `bbox` in the inputs which doesn't fit into the above 2 pipelines' input formats.
296
+ # see https://github.com/huggingface/transformers/pull/26294
297
+ def is_pipeline_test_to_skip(
298
+ self,
299
+ pipeline_test_case_name,
300
+ config_class,
301
+ model_architecture,
302
+ tokenizer_name,
303
+ image_processor_name,
304
+ feature_extractor_name,
305
+ processor_name,
306
+ ):
307
+ return True
308
+
309
+ def setUp(self):
310
+ self.model_tester = BrosModelTester(self)
311
+ self.config_tester = ConfigTester(self, config_class=BrosConfig, hidden_size=37)
312
+
313
+ def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
314
+ inputs_dict = copy.deepcopy(inputs_dict)
315
+
316
+ if return_labels:
317
+ if model_class.__name__ in ["BrosForTokenClassification", "BrosSpadeELForTokenClassification"]:
318
+ inputs_dict["labels"] = torch.zeros(
319
+ (self.model_tester.batch_size, self.model_tester.seq_length),
320
+ dtype=torch.long,
321
+ device=torch_device,
322
+ )
323
+ inputs_dict["bbox_first_token_mask"] = torch.ones(
324
+ [self.model_tester.batch_size, self.model_tester.seq_length],
325
+ dtype=torch.bool,
326
+ device=torch_device,
327
+ )
328
+ elif model_class.__name__ in ["BrosSpadeEEForTokenClassification"]:
329
+ inputs_dict["initial_token_labels"] = torch.zeros(
330
+ (self.model_tester.batch_size, self.model_tester.seq_length),
331
+ dtype=torch.long,
332
+ device=torch_device,
333
+ )
334
+ inputs_dict["subsequent_token_labels"] = torch.zeros(
335
+ (self.model_tester.batch_size, self.model_tester.seq_length),
336
+ dtype=torch.long,
337
+ device=torch_device,
338
+ )
339
+ inputs_dict["bbox_first_token_mask"] = torch.ones(
340
+ [self.model_tester.batch_size, self.model_tester.seq_length],
341
+ dtype=torch.bool,
342
+ device=torch_device,
343
+ )
344
+
345
+ return inputs_dict
346
+
347
+ def test_config(self):
348
+ self.config_tester.run_common_tests()
349
+
350
+ def test_model(self):
351
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
352
+ self.model_tester.create_and_check_model(*config_and_inputs)
353
+
354
+ @require_torch_multi_gpu
355
+ def test_multi_gpu_data_parallel_forward(self):
356
+ super().test_multi_gpu_data_parallel_forward()
357
+
358
+ def test_model_various_embeddings(self):
359
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
360
+ for type in ["absolute", "relative_key", "relative_key_query"]:
361
+ config_and_inputs[0].position_embedding_type = type
362
+ self.model_tester.create_and_check_model(*config_and_inputs)
363
+
364
+ def test_for_token_classification(self):
365
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
366
+ self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
367
+
368
+ def test_for_spade_ee_token_classification(self):
369
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
370
+ self.model_tester.create_and_check_for_spade_ee_token_classification(*config_and_inputs)
371
+
372
+ def test_for_spade_el_token_classification(self):
373
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
374
+ self.model_tester.create_and_check_for_spade_el_token_classification(*config_and_inputs)
375
+
376
+ @slow
377
+ def test_model_from_pretrained(self):
378
+ model_name = "jinho8345/bros-base-uncased"
379
+ model = BrosModel.from_pretrained(model_name)
380
+ self.assertIsNotNone(model)
381
+
382
+
383
+ def prepare_bros_batch_inputs():
384
+ attention_mask = torch.tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]])
385
+
386
+ bbox = torch.tensor(
387
+ [
388
+ [
389
+ [0.0000, 0.0000, 0.0000, 0.0000],
390
+ [0.5223, 0.5590, 0.5787, 0.5720],
391
+ [0.5853, 0.5590, 0.6864, 0.5720],
392
+ [0.5853, 0.5590, 0.6864, 0.5720],
393
+ [0.1234, 0.5700, 0.2192, 0.5840],
394
+ [0.2231, 0.5680, 0.2782, 0.5780],
395
+ [0.2874, 0.5670, 0.3333, 0.5780],
396
+ [0.3425, 0.5640, 0.4344, 0.5750],
397
+ [0.0866, 0.7770, 0.1181, 0.7870],
398
+ [0.1168, 0.7770, 0.1522, 0.7850],
399
+ [0.1535, 0.7750, 0.1864, 0.7850],
400
+ [0.1890, 0.7750, 0.2572, 0.7850],
401
+ [1.0000, 1.0000, 1.0000, 1.0000],
402
+ ],
403
+ [
404
+ [0.0000, 0.0000, 0.0000, 0.0000],
405
+ [0.4396, 0.6720, 0.4659, 0.6850],
406
+ [0.4698, 0.6720, 0.4843, 0.6850],
407
+ [0.1575, 0.6870, 0.2021, 0.6980],
408
+ [0.2047, 0.6870, 0.2730, 0.7000],
409
+ [0.1299, 0.7010, 0.1430, 0.7140],
410
+ [0.1299, 0.7010, 0.1430, 0.7140],
411
+ [0.1562, 0.7010, 0.2441, 0.7120],
412
+ [0.1562, 0.7010, 0.2441, 0.7120],
413
+ [0.2454, 0.7010, 0.3150, 0.7120],
414
+ [0.3176, 0.7010, 0.3320, 0.7110],
415
+ [0.3333, 0.7000, 0.4029, 0.7140],
416
+ [1.0000, 1.0000, 1.0000, 1.0000],
417
+ ],
418
+ ]
419
+ )
420
+ input_ids = torch.tensor(
421
+ [
422
+ [101, 1055, 8910, 1012, 5719, 3296, 5366, 3378, 2146, 2846, 10807, 13494, 102],
423
+ [101, 2112, 1997, 3671, 6364, 1019, 1012, 5057, 1011, 4646, 2030, 2974, 102],
424
+ ]
425
+ )
426
+
427
+ return input_ids, bbox, attention_mask
428
+
429
+
430
+ @require_torch
431
+ class BrosModelIntegrationTest(unittest.TestCase):
432
+ @slow
433
+ def test_inference_no_head(self):
434
+ model = BrosModel.from_pretrained("jinho8345/bros-base-uncased").to(torch_device)
435
+
436
+ input_ids, bbox, attention_mask = prepare_bros_batch_inputs()
437
+
438
+ with torch.no_grad():
439
+ outputs = model(
440
+ input_ids.to(torch_device),
441
+ bbox.to(torch_device),
442
+ attention_mask=attention_mask.to(torch_device),
443
+ return_dict=True,
444
+ )
445
+
446
+ # verify the logits
447
+ expected_shape = torch.Size((2, 13, 768))
448
+ self.assertEqual(outputs.last_hidden_state.shape, expected_shape)
449
+
450
+ expected_slice = torch.tensor(
451
+ [[-0.3074, 0.1363, 0.3143], [0.0925, -0.1155, 0.1050], [0.0221, 0.0003, 0.1285]]
452
+ ).to(torch_device)
453
+ torch.set_printoptions(sci_mode=False)
454
+
455
+ self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3], expected_slice, atol=1e-4))
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/byt5/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/byt5/test_tokenization_byt5.py ADDED
@@ -0,0 +1,362 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 Google 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
+
16
+ import json
17
+ import os
18
+ import re
19
+ import shutil
20
+ import tempfile
21
+ import unittest
22
+ from typing import Tuple
23
+
24
+ from transformers import AddedToken, BatchEncoding, ByT5Tokenizer
25
+ from transformers.utils import cached_property, is_tf_available, is_torch_available
26
+
27
+ from ...test_tokenization_common import TokenizerTesterMixin
28
+
29
+
30
+ if is_torch_available():
31
+ FRAMEWORK = "pt"
32
+ elif is_tf_available():
33
+ FRAMEWORK = "tf"
34
+ else:
35
+ FRAMEWORK = "jax"
36
+
37
+
38
+ class ByT5TokenizationTest(TokenizerTesterMixin, unittest.TestCase):
39
+ tokenizer_class = ByT5Tokenizer
40
+ test_rust_tokenizer = False
41
+
42
+ def setUp(self):
43
+ super().setUp()
44
+ tokenizer = ByT5Tokenizer()
45
+ tokenizer.save_pretrained(self.tmpdirname)
46
+
47
+ @cached_property
48
+ def t5_base_tokenizer(self):
49
+ return ByT5Tokenizer.from_pretrained("google/byt5-small")
50
+
51
+ def get_tokenizer(self, **kwargs) -> ByT5Tokenizer:
52
+ return self.tokenizer_class.from_pretrained(self.tmpdirname, **kwargs)
53
+
54
+ def get_clean_sequence(self, tokenizer, with_prefix_space=False, max_length=20, min_length=5) -> Tuple[str, list]:
55
+ # XXX The default common tokenizer tests assume that every ID is decodable on its own.
56
+ # This assumption is invalid for ByT5 because single bytes might not be
57
+ # valid utf-8 (byte 128 for instance).
58
+ # Here we're overriding the smallest possible method to provide
59
+ # a clean sequence without making the same assumption.
60
+
61
+ toks = []
62
+ for i in range(len(tokenizer)):
63
+ try:
64
+ tok = tokenizer.decode([i], clean_up_tokenization_spaces=False)
65
+ except UnicodeDecodeError:
66
+ pass
67
+ toks.append((i, tok))
68
+
69
+ toks = list(filter(lambda t: re.match(r"^[ a-zA-Z]+$", t[1]), toks))
70
+ toks = list(filter(lambda t: [t[0]] == tokenizer.encode(t[1], add_special_tokens=False), toks))
71
+ if max_length is not None and len(toks) > max_length:
72
+ toks = toks[:max_length]
73
+ if min_length is not None and len(toks) < min_length and len(toks) > 0:
74
+ while len(toks) < min_length:
75
+ toks = toks + toks
76
+ # toks_str = [t[1] for t in toks]
77
+ toks_ids = [t[0] for t in toks]
78
+
79
+ # Ensure consistency
80
+ output_txt = tokenizer.decode(toks_ids, clean_up_tokenization_spaces=False)
81
+ if " " not in output_txt and len(toks_ids) > 1:
82
+ output_txt = (
83
+ tokenizer.decode([toks_ids[0]], clean_up_tokenization_spaces=False)
84
+ + " "
85
+ + tokenizer.decode(toks_ids[1:], clean_up_tokenization_spaces=False)
86
+ )
87
+ if with_prefix_space:
88
+ output_txt = " " + output_txt
89
+ output_ids = tokenizer.encode(output_txt, add_special_tokens=False)
90
+ return output_txt, output_ids
91
+
92
+ def test_eos_treatment(self):
93
+ tokenizer = self.t5_base_tokenizer
94
+ batch_with_eos_added = tokenizer(["hi</s>", "I went to the gym</s>", "</s>"])
95
+ batch_without_eos_added = tokenizer(["hi", "I went to the gym", ""])
96
+ self.assertListEqual(batch_with_eos_added["input_ids"], batch_without_eos_added["input_ids"])
97
+
98
+ def test_multibytes_char(self):
99
+ tokenizer = self.t5_base_tokenizer
100
+ src_text = "Unicode €."
101
+ encoded = tokenizer(src_text)
102
+ encoded_ids = [88, 113, 108, 102, 114, 103, 104, 35, 229, 133, 175, 49, 1]
103
+ self.assertEqual(encoded["input_ids"], encoded_ids)
104
+
105
+ # decoding
106
+ decoded = tokenizer.decode(encoded_ids)
107
+ self.assertEqual(decoded, "Unicode €.</s>")
108
+
109
+ encoded = tokenizer("e è é ê ë")
110
+ encoded_ids = [104, 35, 198, 171, 35, 198, 172, 35, 198, 173, 35, 198, 174, 1]
111
+ self.assertEqual(encoded["input_ids"], encoded_ids)
112
+ # decoding
113
+ decoded = tokenizer.decode(encoded_ids)
114
+ self.assertEqual(decoded, "e è é ê ë</s>")
115
+
116
+ # encode/decode, but with `encode` instead of `__call__`
117
+ self.assertEqual(tokenizer.decode(tokenizer.encode("e è é ê ë")), "e è é ê ë</s>")
118
+
119
+ def test_prepare_batch_integration(self):
120
+ tokenizer = self.t5_base_tokenizer
121
+ src_text = ["A long paragraph for summarization.", "Another paragraph for summarization."]
122
+ expected_src_tokens = [68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 1, 0] # fmt: skip
123
+ batch = tokenizer(src_text, padding=True, return_tensors=FRAMEWORK)
124
+ self.assertIsInstance(batch, BatchEncoding)
125
+
126
+ if FRAMEWORK != "jax":
127
+ result = list(batch.input_ids.numpy()[0])
128
+ else:
129
+ result = list(batch.input_ids.tolist()[0])
130
+
131
+ self.assertListEqual(expected_src_tokens, result)
132
+
133
+ self.assertEqual((2, 37), batch.input_ids.shape)
134
+ self.assertEqual((2, 37), batch.attention_mask.shape)
135
+
136
+ def test_empty_target_text(self):
137
+ tokenizer = self.t5_base_tokenizer
138
+ src_text = ["A long paragraph for summarization.", "Another paragraph for summarization."]
139
+ batch = tokenizer(src_text, padding=True, return_tensors=FRAMEWORK)
140
+ # check if input_ids are returned and no decoder_input_ids
141
+ self.assertIn("input_ids", batch)
142
+ self.assertIn("attention_mask", batch)
143
+ self.assertNotIn("decoder_input_ids", batch)
144
+ self.assertNotIn("decoder_attention_mask", batch)
145
+
146
+ def test_max_length_integration(self):
147
+ tokenizer = self.t5_base_tokenizer
148
+ tgt_text = [
149
+ "Summary of the text.",
150
+ "Another summary.",
151
+ ]
152
+ targets = tokenizer(
153
+ text_target=tgt_text, max_length=32, padding="max_length", truncation=True, return_tensors=FRAMEWORK
154
+ )
155
+ self.assertEqual(32, targets["input_ids"].shape[1])
156
+
157
+ def test_eos_in_input(self):
158
+ tokenizer = self.t5_base_tokenizer
159
+ src_text = ["A long paragraph for summarization. </s>"]
160
+ tgt_text = ["Summary of the text. </s>"]
161
+ expected_src_tokens = [68, 35, 111, 114, 113, 106, 35, 115, 100, 117, 100, 106, 117, 100, 115, 107, 35, 105, 114, 117, 35, 118, 120, 112, 112, 100, 117, 108, 125, 100, 119, 108, 114, 113, 49, 35, 1] # fmt: skip
162
+ expected_tgt_tokens = [86, 120, 112, 112, 100, 117, 124, 35, 114, 105, 35, 119, 107, 104, 35, 119, 104, 123, 119, 49, 35, 1] # fmt: skip
163
+
164
+ batch = tokenizer(src_text, text_target=tgt_text)
165
+
166
+ self.assertEqual(expected_src_tokens, batch["input_ids"][0])
167
+ self.assertEqual(expected_tgt_tokens, batch["labels"][0])
168
+
169
+ # cannot use default save_and_load_tokenizer test method because tokenizer has no vocab
170
+ def test_save_and_load_tokenizer(self):
171
+ # safety check on max_len default value so we are sure the test works
172
+ tokenizers = self.get_tokenizers()
173
+ for tokenizer in tokenizers:
174
+ with self.subTest(f"{tokenizer.__class__.__name__}"):
175
+ self.assertNotEqual(tokenizer.model_max_length, 42)
176
+
177
+ # Now let's start the test
178
+ tokenizers = self.get_tokenizers()
179
+ for tokenizer in tokenizers:
180
+ with self.subTest(f"{tokenizer.__class__.__name__}"):
181
+ # Isolate this from the other tests because we save additional tokens/etc
182
+ tmpdirname = tempfile.mkdtemp()
183
+
184
+ sample_text = " He is very happy, UNwant\u00e9d,running"
185
+ before_tokens = tokenizer.encode(sample_text, add_special_tokens=False)
186
+ tokenizer.save_pretrained(tmpdirname)
187
+
188
+ after_tokenizer = tokenizer.__class__.from_pretrained(tmpdirname)
189
+ after_tokens = after_tokenizer.encode(sample_text, add_special_tokens=False)
190
+ self.assertListEqual(before_tokens, after_tokens)
191
+
192
+ shutil.rmtree(tmpdirname)
193
+
194
+ tokenizers = self.get_tokenizers(model_max_length=42)
195
+ for tokenizer in tokenizers:
196
+ with self.subTest(f"{tokenizer.__class__.__name__}"):
197
+ # Isolate this from the other tests because we save additional tokens/etc
198
+ tmpdirname = tempfile.mkdtemp()
199
+
200
+ sample_text = " He is very happy, UNwant\u00e9d,running"
201
+ tokenizer.add_tokens(["bim", "bambam"])
202
+ additional_special_tokens = tokenizer.additional_special_tokens
203
+ additional_special_tokens.append("new_additional_special_token")
204
+ tokenizer.add_special_tokens(
205
+ {"additional_special_tokens": additional_special_tokens}, replace_additional_special_tokens=False
206
+ )
207
+ before_tokens = tokenizer.encode(sample_text, add_special_tokens=False)
208
+ tokenizer.save_pretrained(tmpdirname)
209
+
210
+ after_tokenizer = tokenizer.__class__.from_pretrained(tmpdirname)
211
+ after_tokens = after_tokenizer.encode(sample_text, add_special_tokens=False)
212
+ self.assertListEqual(before_tokens, after_tokens)
213
+ self.assertIn("new_additional_special_token", after_tokenizer.additional_special_tokens)
214
+ self.assertEqual(after_tokenizer.model_max_length, 42)
215
+
216
+ tokenizer = tokenizer.__class__.from_pretrained(tmpdirname, model_max_length=43)
217
+ self.assertEqual(tokenizer.model_max_length, 43)
218
+
219
+ shutil.rmtree(tmpdirname)
220
+
221
+ # There is a conflict between the default value of extra_ids and adding a new special token through additional_special_tokens
222
+ # We need to add the extra_ids in the list of the arg additional_special_tokens
223
+ def test_special_tokens_initialization_with_non_empty_additional_special_tokens(self):
224
+ tokenizer_list = []
225
+ if self.test_slow_tokenizer:
226
+ tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()))
227
+
228
+ if self.test_rust_tokenizer:
229
+ tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()))
230
+
231
+ for tokenizer_class, tokenizer_utils in tokenizer_list:
232
+ with tempfile.TemporaryDirectory() as tmp_dir:
233
+ tokenizer_utils.save_pretrained(tmp_dir)
234
+
235
+ with open(os.path.join(tmp_dir, "special_tokens_map.json"), encoding="utf-8") as json_file:
236
+ special_tokens_map = json.load(json_file)
237
+
238
+ with open(os.path.join(tmp_dir, "tokenizer_config.json"), encoding="utf-8") as json_file:
239
+ tokenizer_config = json.load(json_file)
240
+
241
+ added_tokens_extra_ids = [f"<extra_id_{i}>" for i in range(125)]
242
+
243
+ special_tokens_map["additional_special_tokens"] = added_tokens_extra_ids + [
244
+ "an_additional_special_token"
245
+ ]
246
+ tokenizer_config["additional_special_tokens"] = added_tokens_extra_ids + [
247
+ "an_additional_special_token"
248
+ ]
249
+
250
+ with open(os.path.join(tmp_dir, "special_tokens_map.json"), "w", encoding="utf-8") as outfile:
251
+ json.dump(special_tokens_map, outfile)
252
+ with open(os.path.join(tmp_dir, "tokenizer_config.json"), "w", encoding="utf-8") as outfile:
253
+ json.dump(tokenizer_config, outfile)
254
+
255
+ # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes
256
+ # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and
257
+ # "special_tokens_map.json" files
258
+ tokenizer_without_change_in_init = tokenizer_class.from_pretrained(
259
+ tmp_dir,
260
+ )
261
+ self.assertIn(
262
+ "an_additional_special_token", tokenizer_without_change_in_init.additional_special_tokens
263
+ )
264
+ # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab
265
+ self.assertEqual(
266
+ ["an_additional_special_token"],
267
+ tokenizer_without_change_in_init.convert_ids_to_tokens(
268
+ tokenizer_without_change_in_init.convert_tokens_to_ids(["an_additional_special_token"])
269
+ ),
270
+ )
271
+
272
+ # Now we test that we can change the value of additional_special_tokens in the from_pretrained
273
+ new_added_tokens = added_tokens_extra_ids + [AddedToken("a_new_additional_special_token", lstrip=True)]
274
+ tokenizer = tokenizer_class.from_pretrained(
275
+ tmp_dir,
276
+ additional_special_tokens=new_added_tokens,
277
+ )
278
+
279
+ self.assertIn("a_new_additional_special_token", tokenizer.additional_special_tokens)
280
+ self.assertEqual(
281
+ ["a_new_additional_special_token"],
282
+ tokenizer.convert_ids_to_tokens(
283
+ tokenizer.convert_tokens_to_ids(["a_new_additional_special_token"])
284
+ ),
285
+ )
286
+
287
+ def test_decode_single_bytes(self):
288
+ tokenizer_list = []
289
+ if self.test_slow_tokenizer:
290
+ tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()))
291
+
292
+ if self.test_rust_tokenizer:
293
+ tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()))
294
+
295
+ for tokenizer_class, tokenizer_utils in tokenizer_list:
296
+ with tempfile.TemporaryDirectory() as tmp_dir:
297
+ tokenizer_utils.save_pretrained(tmp_dir)
298
+
299
+ tokenizer = tokenizer_class.from_pretrained(tmp_dir)
300
+
301
+ self.assertTrue(tokenizer.decode([255]) == "")
302
+
303
+ @unittest.skip(reason="ByT5Tokenizer does not have a vocabulary")
304
+ def test_get_vocab(self):
305
+ pass
306
+
307
+ @unittest.skip(reason="inputs cannot be pretokenized as ids depend on whole input string")
308
+ def test_pretokenized_inputs(self):
309
+ pass
310
+
311
+ @unittest.skip(reason="ByT5Tokenizer does not have a vocabulary")
312
+ def test_conversion_reversible(self):
313
+ pass
314
+
315
+ def test_convert_tokens_to_string_format(self):
316
+ # The default common tokenizer tests uses invalid tokens for ByT5 that can only accept one-character strings
317
+ # and special added tokens as tokens
318
+ tokenizers = self.get_tokenizers(fast=True, do_lower_case=True)
319
+ for tokenizer in tokenizers:
320
+ with self.subTest(f"{tokenizer.__class__.__name__}"):
321
+ tokens = ["t", "h", "i", "s", " ", "i", "s", " ", "a", " ", "t", "e", "x", "t", "</s>"]
322
+ string = tokenizer.convert_tokens_to_string(tokens)
323
+
324
+ self.assertIsInstance(string, str)
325
+
326
+ # We need a different implementation of the test of the same name defined in TokenizerTesterMixin because this tokenizer
327
+ # doesn't have a vocab
328
+ def test_tokenizers_common_ids_setters(self):
329
+ tokenizers = self.get_tokenizers()
330
+ for tokenizer in tokenizers:
331
+ with self.subTest(f"{tokenizer.__class__.__name__}"):
332
+ attributes_list = [
333
+ "bos_token",
334
+ "eos_token",
335
+ "unk_token",
336
+ "sep_token",
337
+ "pad_token",
338
+ "cls_token",
339
+ "mask_token",
340
+ ]
341
+
342
+ token_id_to_test_setters = 0
343
+ token_to_test_setters = tokenizer.convert_ids_to_tokens(
344
+ token_id_to_test_setters, skip_special_tokens=False
345
+ )
346
+
347
+ for attr in attributes_list:
348
+ setattr(tokenizer, attr + "_id", None)
349
+ self.assertEqual(getattr(tokenizer, attr), None)
350
+ self.assertEqual(getattr(tokenizer, attr + "_id"), None)
351
+
352
+ setattr(tokenizer, attr + "_id", token_id_to_test_setters)
353
+ self.assertEqual(getattr(tokenizer, attr), token_to_test_setters)
354
+ self.assertEqual(getattr(tokenizer, attr + "_id"), token_id_to_test_setters)
355
+
356
+ setattr(tokenizer, "additional_special_tokens_ids", [])
357
+ self.assertListEqual(getattr(tokenizer, "additional_special_tokens"), [])
358
+ self.assertListEqual(getattr(tokenizer, "additional_special_tokens_ids"), [])
359
+
360
+ setattr(tokenizer, "additional_special_tokens_ids", [token_id_to_test_setters])
361
+ self.assertListEqual(getattr(tokenizer, "additional_special_tokens"), [token_to_test_setters])
362
+ self.assertListEqual(getattr(tokenizer, "additional_special_tokens_ids"), [token_id_to_test_setters])
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/camembert/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/camembert/test_modeling_camembert.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 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
+
16
+ import unittest
17
+
18
+ from transformers import is_torch_available
19
+ from transformers.testing_utils import (
20
+ require_sentencepiece,
21
+ require_tokenizers,
22
+ require_torch,
23
+ require_torch_sdpa,
24
+ slow,
25
+ torch_device,
26
+ )
27
+
28
+
29
+ if is_torch_available():
30
+ import torch
31
+
32
+ from transformers import CamembertModel
33
+
34
+
35
+ @require_torch
36
+ @require_sentencepiece
37
+ @require_tokenizers
38
+ class CamembertModelIntegrationTest(unittest.TestCase):
39
+ @slow
40
+ def test_output_embeds_base_model(self):
41
+ model = CamembertModel.from_pretrained("almanach/camembert-base", attn_implementation="eager")
42
+ model.to(torch_device)
43
+
44
+ input_ids = torch.tensor(
45
+ [[5, 121, 11, 660, 16, 730, 25543, 110, 83, 6]],
46
+ device=torch_device,
47
+ dtype=torch.long,
48
+ ) # J'aime le camembert !
49
+ with torch.no_grad():
50
+ output = model(input_ids)["last_hidden_state"]
51
+ expected_shape = torch.Size((1, 10, 768))
52
+ self.assertEqual(output.shape, expected_shape)
53
+ # compare the actual values for a slice.
54
+ expected_slice = torch.tensor(
55
+ [[[-0.0254, 0.0235, 0.1027], [0.0606, -0.1811, -0.0418], [-0.1561, -0.1127, 0.2687]]],
56
+ device=torch_device,
57
+ dtype=torch.float,
58
+ )
59
+ # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0')
60
+ # camembert.eval()
61
+ # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach()
62
+
63
+ self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4))
64
+
65
+ @slow
66
+ @require_torch_sdpa
67
+ def test_output_embeds_base_model_sdpa(self):
68
+ input_ids = torch.tensor(
69
+ [[5, 121, 11, 660, 16, 730, 25543, 110, 83, 6]],
70
+ device=torch_device,
71
+ dtype=torch.long,
72
+ ) # J'aime le camembert !
73
+
74
+ expected_slice = torch.tensor(
75
+ [[[-0.0254, 0.0235, 0.1027], [0.0606, -0.1811, -0.0418], [-0.1561, -0.1127, 0.2687]]],
76
+ device=torch_device,
77
+ dtype=torch.float,
78
+ )
79
+
80
+ model = CamembertModel.from_pretrained("almanach/camembert-base", attn_implementation="sdpa").to(torch_device)
81
+ with torch.no_grad():
82
+ output = model(input_ids)["last_hidden_state"].detach()
83
+
84
+ self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-4))
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/camembert/test_modeling_tf_camembert.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 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
+
16
+ from __future__ import annotations
17
+
18
+ import unittest
19
+
20
+ from transformers import is_tf_available
21
+ from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
22
+
23
+
24
+ if is_tf_available():
25
+ import numpy as np
26
+ import tensorflow as tf
27
+
28
+ from transformers import TFCamembertModel
29
+
30
+
31
+ @require_tf
32
+ @require_sentencepiece
33
+ @require_tokenizers
34
+ class TFCamembertModelIntegrationTest(unittest.TestCase):
35
+ @slow
36
+ def test_output_embeds_base_model(self):
37
+ model = TFCamembertModel.from_pretrained("jplu/tf-camembert-base")
38
+
39
+ input_ids = tf.convert_to_tensor(
40
+ [[5, 121, 11, 660, 16, 730, 25543, 110, 83, 6]],
41
+ dtype=tf.int32,
42
+ ) # J'aime le camembert !"
43
+
44
+ output = model(input_ids)["last_hidden_state"]
45
+ expected_shape = tf.TensorShape((1, 10, 768))
46
+ self.assertEqual(output.shape, expected_shape)
47
+ # compare the actual values for a slice.
48
+ expected_slice = tf.convert_to_tensor(
49
+ [[[-0.0254, 0.0235, 0.1027], [0.0606, -0.1811, -0.0418], [-0.1561, -0.1127, 0.2687]]],
50
+ dtype=tf.float32,
51
+ )
52
+ # camembert = torch.hub.load('pytorch/fairseq', 'camembert.v0')
53
+ # camembert.eval()
54
+ # expected_slice = roberta.model.forward(input_ids)[0][:, :3, :3].detach()
55
+
56
+ self.assertTrue(np.allclose(output[:, :3, :3].numpy(), expected_slice.numpy(), atol=1e-4))
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/camembert/test_tokenization_camembert.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 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
+ import tempfile
17
+ import unittest
18
+
19
+ from transformers import AddedToken, CamembertTokenizer, CamembertTokenizerFast
20
+ from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow
21
+ from transformers.utils import is_torch_available
22
+
23
+ from ...test_tokenization_common import TokenizerTesterMixin
24
+
25
+
26
+ SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model")
27
+ SAMPLE_BPE_VOCAB = get_tests_dir("fixtures/test_sentencepiece_bpe.model")
28
+
29
+ FRAMEWORK = "pt" if is_torch_available() else "tf"
30
+
31
+
32
+ @require_sentencepiece
33
+ @require_tokenizers
34
+ class CamembertTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
35
+ from_pretrained_id = "almanach/camembert-base"
36
+ tokenizer_class = CamembertTokenizer
37
+ rust_tokenizer_class = CamembertTokenizerFast
38
+ test_rust_tokenizer = True
39
+ test_sentencepiece = True
40
+
41
+ def setUp(self):
42
+ super().setUp()
43
+
44
+ # We have a SentencePiece fixture for testing
45
+ tokenizer = CamembertTokenizer(SAMPLE_VOCAB)
46
+ tokenizer.save_pretrained(self.tmpdirname)
47
+
48
+ @unittest.skip(
49
+ "Token maps are not equal because someone set the probability of ('<unk>NOTUSED', -100), so it's never encoded for fast"
50
+ )
51
+ def test_special_tokens_map_equal(self):
52
+ return
53
+
54
+ def test_convert_token_and_id(self):
55
+ """Test ``_convert_token_to_id`` and ``_convert_id_to_token``."""
56
+ token = "<pad>"
57
+ token_id = 1 # 1 is the offset id, but in the spm vocab it's 3
58
+
59
+ self.assertEqual(self.get_tokenizer().convert_tokens_to_ids(token), token_id)
60
+ self.assertEqual(self.get_tokenizer().convert_ids_to_tokens(token_id), token)
61
+
62
+ def test_get_vocab(self):
63
+ vocab_keys = list(self.get_tokenizer().get_vocab().keys())
64
+
65
+ self.assertEqual(vocab_keys[0], "<s>NOTUSED")
66
+ self.assertEqual(vocab_keys[1], "<pad>")
67
+ self.assertEqual(vocab_keys[-1], "<mask>")
68
+ self.assertEqual(len(vocab_keys), 1_005)
69
+
70
+ def test_vocab_size(self):
71
+ self.assertEqual(self.get_tokenizer().vocab_size, 1_000)
72
+
73
+ def test_rust_and_python_bpe_tokenizers(self):
74
+ tokenizer = CamembertTokenizer(SAMPLE_BPE_VOCAB)
75
+ tokenizer.save_pretrained(self.tmpdirname)
76
+ rust_tokenizer = CamembertTokenizerFast.from_pretrained(self.tmpdirname)
77
+
78
+ sequence = "I was born in 92000, and this is falsé."
79
+
80
+ ids = tokenizer.encode(sequence)
81
+ rust_ids = rust_tokenizer.encode(sequence)
82
+ self.assertListEqual(ids, rust_ids)
83
+
84
+ ids = tokenizer.encode(sequence, add_special_tokens=False)
85
+ rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False)
86
+ self.assertListEqual(ids, rust_ids)
87
+
88
+ # <unk> tokens are not the same for `rust` than for `slow`.
89
+ # Because spm gives back raw token instead of `unk` in EncodeAsPieces
90
+ # tokens = tokenizer.tokenize(sequence)
91
+ tokens = tokenizer.convert_ids_to_tokens(ids)
92
+ rust_tokens = rust_tokenizer.tokenize(sequence)
93
+ self.assertListEqual(tokens, rust_tokens)
94
+
95
+ def test_rust_and_python_full_tokenizers(self):
96
+ if not self.test_rust_tokenizer:
97
+ self.skipTest(reason="test_rust_tokenizer is set to False")
98
+
99
+ tokenizer = self.get_tokenizer()
100
+ rust_tokenizer = self.get_rust_tokenizer()
101
+
102
+ sequence = "I was born in 92000, and this is falsé."
103
+
104
+ tokens = tokenizer.tokenize(sequence)
105
+ rust_tokens = rust_tokenizer.tokenize(sequence)
106
+ self.assertListEqual(tokens, rust_tokens)
107
+
108
+ ids = tokenizer.encode(sequence, add_special_tokens=False)
109
+ rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False)
110
+ self.assertListEqual(ids, rust_ids)
111
+
112
+ rust_tokenizer = self.get_rust_tokenizer()
113
+ ids = tokenizer.encode(sequence)
114
+ rust_ids = rust_tokenizer.encode(sequence)
115
+ self.assertListEqual(ids, rust_ids)
116
+
117
+ @slow
118
+ def test_tokenizer_integration(self):
119
+ expected_encoding = {'input_ids': [[5, 54, 7196, 297, 30, 23, 776, 18, 11, 3215, 3705, 8252, 22, 3164, 1181, 2116, 29, 16, 813, 25, 791, 3314, 20, 3446, 38, 27575, 120, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [5, 468, 17, 11, 9088, 20, 1517, 8, 22804, 18818, 10, 38, 629, 607, 607, 142, 19, 7196, 867, 56, 10326, 24, 2267, 20, 416, 5072, 15612, 233, 734, 7, 2399, 27, 16, 3015, 1649, 7, 24, 20, 4338, 2399, 27, 13, 3400, 14, 13, 6189, 8, 930, 9, 6]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # fmt: skip
120
+
121
+ # camembert is a french model. So we also use french texts.
122
+ sequences = [
123
+ "Le transformeur est un modèle d'apprentissage profond introduit en 2017, "
124
+ "utilisé principalement dans le domaine du traitement automatique des langues (TAL).",
125
+ "À l'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus "
126
+ "pour gérer des données séquentielles, telles que le langage naturel, pour des tâches "
127
+ "telles que la traduction et la synthèse de texte.",
128
+ ]
129
+
130
+ self.tokenizer_integration_test_util(
131
+ expected_encoding=expected_encoding,
132
+ model_name="almanach/camembert-base",
133
+ revision="3a0641d9a1aeb7e848a74299e7e4c4bca216b4cf",
134
+ sequences=sequences,
135
+ )
136
+
137
+ # Overwritten because we have to use from slow (online pretrained is wrong, the tokenizer.json has a whole)
138
+ def test_added_tokens_serialization(self):
139
+ self.maxDiff = None
140
+
141
+ # Utility to test the added vocab
142
+ def _test_added_vocab_and_eos(expected, tokenizer_class, expected_eos, temp_dir):
143
+ tokenizer = tokenizer_class.from_pretrained(temp_dir)
144
+ self.assertTrue(str(expected_eos) not in tokenizer.additional_special_tokens)
145
+ self.assertIn(new_eos, tokenizer.added_tokens_decoder.values())
146
+ self.assertEqual(tokenizer.added_tokens_decoder[tokenizer.eos_token_id], new_eos)
147
+ self.assertTrue(all(item in tokenizer.added_tokens_decoder.items() for item in expected.items()))
148
+ return tokenizer
149
+
150
+ new_eos = AddedToken("[NEW_EOS]", rstrip=False, lstrip=True, normalized=False)
151
+ for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
152
+ with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
153
+ # Load a slow tokenizer from the hub, init with the new token for fast to also include it
154
+ tokenizer = self.tokenizer_class.from_pretrained(pretrained_name, eos_token=new_eos)
155
+ EXPECTED_ADDED_TOKENS_DECODER = tokenizer.added_tokens_decoder
156
+ with self.subTest("Hub -> Slow: Test loading a slow tokenizer from the hub)"):
157
+ self.assertEqual(tokenizer._special_tokens_map["eos_token"], new_eos)
158
+ self.assertIn(new_eos, list(tokenizer.added_tokens_decoder.values()))
159
+
160
+ with tempfile.TemporaryDirectory() as tmp_dir_2:
161
+ tokenizer.save_pretrained(tmp_dir_2)
162
+ with self.subTest(
163
+ "Hub -> Slow -> Slow: Test saving this slow tokenizer and reloading it in the fast class"
164
+ ):
165
+ _test_added_vocab_and_eos(
166
+ EXPECTED_ADDED_TOKENS_DECODER, self.tokenizer_class, new_eos, tmp_dir_2
167
+ )
168
+
169
+ if self.rust_tokenizer_class is not None:
170
+ with self.subTest(
171
+ "Hub -> Slow -> Fast: Test saving this slow tokenizer and reloading it in the fast class"
172
+ ):
173
+ tokenizer_fast = _test_added_vocab_and_eos(
174
+ EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_2
175
+ )
176
+ with tempfile.TemporaryDirectory() as tmp_dir_3:
177
+ tokenizer_fast.save_pretrained(tmp_dir_3)
178
+ with self.subTest(
179
+ "Hub -> Slow -> Fast -> Fast: Test saving this fast tokenizer and reloading it in the fast class"
180
+ ):
181
+ _test_added_vocab_and_eos(
182
+ EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_3
183
+ )
184
+
185
+ with self.subTest(
186
+ "Hub -> Slow -> Fast -> Slow: Test saving this slow tokenizer and reloading it in the slow class"
187
+ ):
188
+ _test_added_vocab_and_eos(
189
+ EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_3
190
+ )
191
+
192
+ with self.subTest("Hub -> Fast: Test loading a fast tokenizer from the hub)"):
193
+ if self.rust_tokenizer_class is not None:
194
+ tokenizer_fast = self.rust_tokenizer_class.from_pretrained(
195
+ pretrained_name, eos_token=new_eos, from_slow=True
196
+ )
197
+ self.assertEqual(tokenizer_fast._special_tokens_map["eos_token"], new_eos)
198
+ self.assertIn(new_eos, list(tokenizer_fast.added_tokens_decoder.values()))
199
+ # We can't test the following because for BC we kept the default rstrip lstrip in slow not fast. Will comment once normalization is alright
200
+ with self.subTest("Hub -> Fast == Hub -> Slow: make sure slow and fast tokenizer match"):
201
+ with self.subTest("Hub -> Fast == Hub -> Slow: make sure slow and fast tokenizer match"):
202
+ self.assertTrue(
203
+ all(
204
+ item in tokenizer.added_tokens_decoder.items()
205
+ for item in EXPECTED_ADDED_TOKENS_DECODER.items()
206
+ )
207
+ )
208
+
209
+ EXPECTED_ADDED_TOKENS_DECODER = tokenizer_fast.added_tokens_decoder
210
+ with tempfile.TemporaryDirectory() as tmp_dir_4:
211
+ tokenizer_fast.save_pretrained(tmp_dir_4)
212
+ with self.subTest("Hub -> Fast -> Fast: saving Fast1 locally and loading"):
213
+ _test_added_vocab_and_eos(
214
+ EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_4
215
+ )
216
+
217
+ with self.subTest("Hub -> Fast -> Slow: saving Fast1 locally and loading"):
218
+ _test_added_vocab_and_eos(
219
+ EXPECTED_ADDED_TOKENS_DECODER, self.tokenizer_class, new_eos, tmp_dir_4
220
+ )
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/canine/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/canine/test_modeling_canine.py ADDED
@@ -0,0 +1,573 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Testing suite for the PyTorch CANINE model."""
16
+
17
+ import unittest
18
+ from typing import List, Tuple
19
+
20
+ from transformers import CanineConfig, is_torch_available
21
+ from transformers.testing_utils import require_torch, slow, torch_device
22
+
23
+ from ...test_configuration_common import ConfigTester
24
+ from ...test_modeling_common import ModelTesterMixin, _config_zero_init, global_rng, ids_tensor, random_attention_mask
25
+ from ...test_pipeline_mixin import PipelineTesterMixin
26
+
27
+
28
+ if is_torch_available():
29
+ import torch
30
+
31
+ from transformers import (
32
+ CanineForMultipleChoice,
33
+ CanineForQuestionAnswering,
34
+ CanineForSequenceClassification,
35
+ CanineForTokenClassification,
36
+ CanineModel,
37
+ )
38
+
39
+
40
+ class CanineModelTester:
41
+ def __init__(
42
+ self,
43
+ parent,
44
+ batch_size=13,
45
+ seq_length=7,
46
+ is_training=True,
47
+ use_input_mask=True,
48
+ use_token_type_ids=True,
49
+ use_labels=True,
50
+ # let's use a vocab size that's way bigger than BERT's one
51
+ # NOTE: this is not a model parameter, just an input
52
+ vocab_size=100000,
53
+ hidden_size=32,
54
+ num_hidden_layers=2,
55
+ num_attention_heads=4,
56
+ intermediate_size=37,
57
+ hidden_act="gelu",
58
+ hidden_dropout_prob=0.1,
59
+ attention_probs_dropout_prob=0.1,
60
+ max_position_embeddings=512,
61
+ type_vocab_size=16,
62
+ type_sequence_label_size=2,
63
+ initializer_range=0.02,
64
+ num_labels=3,
65
+ num_choices=4,
66
+ num_hash_buckets=16,
67
+ scope=None,
68
+ ):
69
+ self.parent = parent
70
+ self.batch_size = batch_size
71
+ self.seq_length = seq_length
72
+ self.is_training = is_training
73
+ self.use_input_mask = use_input_mask
74
+ self.use_token_type_ids = use_token_type_ids
75
+ self.use_labels = use_labels
76
+ self.vocab_size = vocab_size
77
+ self.hidden_size = hidden_size
78
+ self.num_hidden_layers = num_hidden_layers
79
+ self.num_attention_heads = num_attention_heads
80
+ self.intermediate_size = intermediate_size
81
+ self.hidden_act = hidden_act
82
+ self.hidden_dropout_prob = hidden_dropout_prob
83
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
84
+ self.max_position_embeddings = max_position_embeddings
85
+ self.type_vocab_size = type_vocab_size
86
+ self.type_sequence_label_size = type_sequence_label_size
87
+ self.initializer_range = initializer_range
88
+ self.num_labels = num_labels
89
+ self.num_choices = num_choices
90
+ self.num_hash_buckets = num_hash_buckets
91
+ self.scope = scope
92
+
93
+ def prepare_config_and_inputs(self):
94
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
95
+
96
+ input_mask = None
97
+ if self.use_input_mask:
98
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
99
+
100
+ token_type_ids = None
101
+ if self.use_token_type_ids:
102
+ token_type_ids = ids_tensor(input_ids.shape, self.type_vocab_size)
103
+
104
+ sequence_labels = None
105
+ token_labels = None
106
+ choice_labels = None
107
+ if self.use_labels:
108
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
109
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
110
+ choice_labels = ids_tensor([self.batch_size], self.num_choices)
111
+
112
+ config = self.get_config()
113
+
114
+ return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
115
+
116
+ def get_config(self):
117
+ return CanineConfig(
118
+ hidden_size=self.hidden_size,
119
+ num_hidden_layers=self.num_hidden_layers,
120
+ num_attention_heads=self.num_attention_heads,
121
+ intermediate_size=self.intermediate_size,
122
+ hidden_act=self.hidden_act,
123
+ hidden_dropout_prob=self.hidden_dropout_prob,
124
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
125
+ max_position_embeddings=self.max_position_embeddings,
126
+ type_vocab_size=self.type_vocab_size,
127
+ is_decoder=False,
128
+ initializer_range=self.initializer_range,
129
+ num_hash_buckets=self.num_hash_buckets,
130
+ )
131
+
132
+ def create_and_check_model(
133
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
134
+ ):
135
+ model = CanineModel(config=config)
136
+ model.to(torch_device)
137
+ model.eval()
138
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
139
+ result = model(input_ids, token_type_ids=token_type_ids)
140
+ result = model(input_ids)
141
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
142
+
143
+ def create_and_check_for_question_answering(
144
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
145
+ ):
146
+ model = CanineForQuestionAnswering(config=config)
147
+ model.to(torch_device)
148
+ model.eval()
149
+ result = model(
150
+ input_ids,
151
+ attention_mask=input_mask,
152
+ token_type_ids=token_type_ids,
153
+ start_positions=sequence_labels,
154
+ end_positions=sequence_labels,
155
+ )
156
+ self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
157
+ self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
158
+
159
+ def create_and_check_for_sequence_classification(
160
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
161
+ ):
162
+ config.num_labels = self.num_labels
163
+ model = CanineForSequenceClassification(config)
164
+ model.to(torch_device)
165
+ model.eval()
166
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels)
167
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
168
+
169
+ def create_and_check_for_token_classification(
170
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
171
+ ):
172
+ config.num_labels = self.num_labels
173
+ model = CanineForTokenClassification(config=config)
174
+ model.to(torch_device)
175
+ model.eval()
176
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
177
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
178
+
179
+ def create_and_check_for_multiple_choice(
180
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
181
+ ):
182
+ config.num_choices = self.num_choices
183
+ model = CanineForMultipleChoice(config=config)
184
+ model.to(torch_device)
185
+ model.eval()
186
+ multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
187
+ multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
188
+ multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
189
+ result = model(
190
+ multiple_choice_inputs_ids,
191
+ attention_mask=multiple_choice_input_mask,
192
+ token_type_ids=multiple_choice_token_type_ids,
193
+ labels=choice_labels,
194
+ )
195
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
196
+
197
+ def prepare_config_and_inputs_for_common(self):
198
+ config_and_inputs = self.prepare_config_and_inputs()
199
+ (
200
+ config,
201
+ input_ids,
202
+ token_type_ids,
203
+ input_mask,
204
+ sequence_labels,
205
+ token_labels,
206
+ choice_labels,
207
+ ) = config_and_inputs
208
+ inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
209
+ return config, inputs_dict
210
+
211
+
212
+ @require_torch
213
+ class CanineModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
214
+ all_model_classes = (
215
+ (
216
+ CanineModel,
217
+ CanineForMultipleChoice,
218
+ CanineForQuestionAnswering,
219
+ CanineForSequenceClassification,
220
+ CanineForTokenClassification,
221
+ )
222
+ if is_torch_available()
223
+ else ()
224
+ )
225
+ pipeline_model_mapping = (
226
+ {
227
+ "feature-extraction": CanineModel,
228
+ "question-answering": CanineForQuestionAnswering,
229
+ "text-classification": CanineForSequenceClassification,
230
+ "token-classification": CanineForTokenClassification,
231
+ "zero-shot": CanineForSequenceClassification,
232
+ }
233
+ if is_torch_available()
234
+ else {}
235
+ )
236
+
237
+ test_mismatched_shapes = False
238
+ test_resize_embeddings = False
239
+ test_pruning = False
240
+
241
+ def setUp(self):
242
+ self.model_tester = CanineModelTester(self)
243
+ # we set has_text_modality to False as the config has no vocab_size attribute
244
+ self.config_tester = ConfigTester(self, config_class=CanineConfig, has_text_modality=False, hidden_size=37)
245
+
246
+ def test_config(self):
247
+ self.config_tester.run_common_tests()
248
+
249
+ def test_model(self):
250
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
251
+ self.model_tester.create_and_check_model(*config_and_inputs)
252
+
253
+ def test_for_multiple_choice(self):
254
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
255
+ self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
256
+
257
+ def test_for_question_answering(self):
258
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
259
+ self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
260
+
261
+ def test_for_sequence_classification(self):
262
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
263
+ self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs)
264
+
265
+ def test_for_token_classification(self):
266
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
267
+ self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
268
+
269
+ def test_hidden_states_output(self):
270
+ def check_hidden_states_output(inputs_dict, config, model_class):
271
+ model = model_class(config)
272
+ model.to(torch_device)
273
+ model.eval()
274
+
275
+ with torch.no_grad():
276
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
277
+
278
+ hidden_states = outputs.hidden_states
279
+ # expected_num_layers equals num_hidden_layers of the deep encoder + 1, + 2 for the first shallow encoder, + 2
280
+ # for the final shallow encoder
281
+ expected_num_layers = self.model_tester.num_hidden_layers + 1 + 2 + 2
282
+ self.assertEqual(len(hidden_states), expected_num_layers)
283
+
284
+ seq_length = self.model_tester.seq_length
285
+ for i in range(expected_num_layers):
286
+ if (i < 2) or ((expected_num_layers - i) < 3):
287
+ # the expected length of the hidden_states of the first and final shallow encoders
288
+ # is equal to the seq_length
289
+ self.assertListEqual(
290
+ list(hidden_states[i].shape[-2:]),
291
+ [seq_length, self.model_tester.hidden_size],
292
+ )
293
+ else:
294
+ # the expected length of the hidden_states of the deep encoder need to be updated
295
+ # for CANINE since the seq length is downsampled
296
+ self.assertListEqual(
297
+ list(hidden_states[i].shape[-2:]),
298
+ [seq_length // config.downsampling_rate, self.model_tester.hidden_size],
299
+ )
300
+
301
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
302
+
303
+ for model_class in self.all_model_classes:
304
+ inputs_dict["output_hidden_states"] = True
305
+ check_hidden_states_output(inputs_dict, config, model_class)
306
+
307
+ # check that output_hidden_states also work using config
308
+ del inputs_dict["output_hidden_states"]
309
+ config.output_hidden_states = True
310
+
311
+ check_hidden_states_output(inputs_dict, config, model_class)
312
+
313
+ def test_attention_outputs(self):
314
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
315
+ config.return_dict = True
316
+
317
+ seq_len = getattr(self.model_tester, "seq_length", None)
318
+
319
+ for model_class in self.all_model_classes:
320
+ inputs_dict["output_attentions"] = True
321
+ inputs_dict["output_hidden_states"] = False
322
+ config.return_dict = True
323
+ model = model_class(config)
324
+ model.to(torch_device)
325
+ model.eval()
326
+ with torch.no_grad():
327
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
328
+ attentions = outputs.attentions
329
+ # we add + 2 due to the 2 shallow encoders
330
+ self.assertEqual(len(attentions), self.model_tester.num_hidden_layers + 2)
331
+
332
+ # check that output_attentions also work using config
333
+ del inputs_dict["output_attentions"]
334
+ config.output_attentions = True
335
+ model = model_class(config)
336
+ model.to(torch_device)
337
+ model.eval()
338
+ with torch.no_grad():
339
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
340
+ attentions = outputs.attentions
341
+ # we add + 2 due to the 2 shallow encoders
342
+ self.assertEqual(len(attentions), self.model_tester.num_hidden_layers + 2)
343
+
344
+ self.assertListEqual(
345
+ list(attentions[0].shape[-3:]),
346
+ [self.model_tester.num_attention_heads, seq_len, seq_len],
347
+ )
348
+ out_len = len(outputs)
349
+
350
+ # Check attention is always last and order is fine
351
+ inputs_dict["output_attentions"] = True
352
+ inputs_dict["output_hidden_states"] = True
353
+ model = model_class(config)
354
+ model.to(torch_device)
355
+ model.eval()
356
+ with torch.no_grad():
357
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
358
+
359
+ if hasattr(self.model_tester, "num_hidden_states_types"):
360
+ added_hidden_states = self.model_tester.num_hidden_states_types
361
+ else:
362
+ added_hidden_states = 1
363
+ self.assertEqual(out_len + added_hidden_states, len(outputs))
364
+
365
+ self_attentions = outputs.attentions
366
+
367
+ self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers + 2)
368
+ self.assertListEqual(
369
+ list(self_attentions[0].shape[-3:]),
370
+ [self.model_tester.num_attention_heads, seq_len, seq_len],
371
+ )
372
+
373
+ def test_model_outputs_equivalence(self):
374
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
375
+
376
+ def set_nan_tensor_to_zero(t):
377
+ t[t != t] = 0
378
+ return t
379
+
380
+ def check_equivalence(model, tuple_inputs, dict_inputs, additional_kwargs={}):
381
+ with torch.no_grad():
382
+ tuple_output = model(**tuple_inputs, return_dict=False, **additional_kwargs)
383
+ dict_output = model(**dict_inputs, return_dict=True, **additional_kwargs).to_tuple()
384
+
385
+ def recursive_check(tuple_object, dict_object):
386
+ if isinstance(tuple_object, (List, Tuple)):
387
+ for tuple_iterable_value, dict_iterable_value in zip(tuple_object, dict_object):
388
+ recursive_check(tuple_iterable_value, dict_iterable_value)
389
+ elif tuple_object is None:
390
+ return
391
+ else:
392
+ self.assertTrue(
393
+ torch.allclose(
394
+ set_nan_tensor_to_zero(tuple_object), set_nan_tensor_to_zero(dict_object), atol=1e-5
395
+ ),
396
+ msg=(
397
+ "Tuple and dict output are not equal. Difference:"
398
+ f" {torch.max(torch.abs(tuple_object - dict_object))}. Tuple has `nan`:"
399
+ f" {torch.isnan(tuple_object).any()} and `inf`: {torch.isinf(tuple_object)}. Dict has"
400
+ f" `nan`: {torch.isnan(dict_object).any()} and `inf`: {torch.isinf(dict_object)}."
401
+ ),
402
+ )
403
+
404
+ recursive_check(tuple_output, dict_output)
405
+
406
+ for model_class in self.all_model_classes:
407
+ print(model_class)
408
+ model = model_class(config)
409
+ model.to(torch_device)
410
+ model.eval()
411
+
412
+ tuple_inputs = self._prepare_for_class(inputs_dict, model_class)
413
+ dict_inputs = self._prepare_for_class(inputs_dict, model_class)
414
+ check_equivalence(model, tuple_inputs, dict_inputs)
415
+
416
+ tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
417
+ dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
418
+ check_equivalence(model, tuple_inputs, dict_inputs)
419
+
420
+ tuple_inputs = self._prepare_for_class(inputs_dict, model_class)
421
+ dict_inputs = self._prepare_for_class(inputs_dict, model_class)
422
+ check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True})
423
+
424
+ tuple_inputs = self._prepare_for_class(inputs_dict, model_class)
425
+ dict_inputs = self._prepare_for_class(inputs_dict, model_class)
426
+ check_equivalence(model, tuple_inputs, dict_inputs, {"output_attentions": True})
427
+
428
+ tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
429
+ dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
430
+ check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True})
431
+
432
+ tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
433
+ dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
434
+ check_equivalence(model, tuple_inputs, dict_inputs, {"output_attentions": True})
435
+
436
+ tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
437
+ dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
438
+ check_equivalence(
439
+ model, tuple_inputs, dict_inputs, {"output_hidden_states": True, "output_attentions": True}
440
+ )
441
+
442
+ def test_headmasking(self):
443
+ if not self.test_head_masking:
444
+ self.skipTest(reason="test_head_masking is set to False")
445
+
446
+ global_rng.seed(42)
447
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
448
+ global_rng.seed()
449
+
450
+ inputs_dict["output_attentions"] = True
451
+ config.output_hidden_states = True
452
+ configs_no_init = _config_zero_init(config) # To be sure we have no Nan
453
+ for model_class in self.all_model_classes:
454
+ model = model_class(config=configs_no_init)
455
+ model.to(torch_device)
456
+ model.eval()
457
+
458
+ # Prepare head_mask
459
+ # Set require_grad after having prepared the tensor to avoid error (leaf variable has been moved into the graph interior)
460
+ head_mask = torch.ones(
461
+ self.model_tester.num_hidden_layers,
462
+ self.model_tester.num_attention_heads,
463
+ device=torch_device,
464
+ )
465
+ head_mask[0, 0] = 0
466
+ head_mask[-1, :-1] = 0
467
+ head_mask.requires_grad_(requires_grad=True)
468
+ inputs = self._prepare_for_class(inputs_dict, model_class).copy()
469
+ inputs["head_mask"] = head_mask
470
+
471
+ outputs = model(**inputs, return_dict=True)
472
+
473
+ # Test that we can get a gradient back for importance score computation
474
+ output = sum(t.sum() for t in outputs[0])
475
+ output = output.sum()
476
+ output.backward()
477
+ multihead_outputs = head_mask.grad
478
+
479
+ self.assertIsNotNone(multihead_outputs)
480
+ self.assertEqual(len(multihead_outputs), self.model_tester.num_hidden_layers)
481
+
482
+ def check_attentions_validity(attentions):
483
+ # Remove Nan
484
+ for t in attentions:
485
+ self.assertLess(
486
+ torch.sum(torch.isnan(t)), t.numel() / 4
487
+ ) # Check we don't have more than 25% nans (arbitrary)
488
+ attentions = [
489
+ t.masked_fill(torch.isnan(t), 0.0) for t in attentions
490
+ ] # remove them (the test is less complete)
491
+
492
+ self.assertAlmostEqual(attentions[1][..., 0, :, :].flatten().sum().item(), 0.0)
493
+ self.assertNotEqual(attentions[1][..., -1, :, :].flatten().sum().item(), 0.0)
494
+ self.assertAlmostEqual(attentions[-2][..., -2, :, :].flatten().sum().item(), 0.0)
495
+ self.assertNotEqual(attentions[-2][..., -1, :, :].flatten().sum().item(), 0.0)
496
+
497
+ check_attentions_validity(outputs.attentions)
498
+
499
+ @unittest.skip(reason="CANINE does not have a get_input_embeddings() method.")
500
+ def test_inputs_embeds(self):
501
+ # ViT does not use inputs_embeds
502
+ pass
503
+
504
+ @unittest.skip(reason="Canine Tower does not use inputs_embeds")
505
+ def test_inputs_embeds_matches_input_ids(self):
506
+ pass
507
+
508
+ @unittest.skip(reason="CANINE does not have a get_input_embeddings() method.")
509
+ def test_model_get_set_embeddings(self):
510
+ pass
511
+
512
+ @unittest.skip(
513
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
514
+ )
515
+ def test_training_gradient_checkpointing(self):
516
+ pass
517
+
518
+ @unittest.skip(
519
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
520
+ )
521
+ def test_training_gradient_checkpointing_use_reentrant(self):
522
+ pass
523
+
524
+ @unittest.skip(
525
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
526
+ )
527
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
528
+ pass
529
+
530
+ @slow
531
+ def test_model_from_pretrained(self):
532
+ model_name = "google/canine-s"
533
+ model = CanineModel.from_pretrained(model_name)
534
+ self.assertIsNotNone(model)
535
+
536
+
537
+ @require_torch
538
+ class CanineModelIntegrationTest(unittest.TestCase):
539
+ @slow
540
+ def test_inference_no_head(self):
541
+ model = CanineModel.from_pretrained("google/canine-s")
542
+ # this one corresponds to the first example of the TydiQA dev set (in Swahili)
543
+ # fmt: off
544
+ input_ids = [57344, 57349, 85, 107, 117, 98, 119, 97, 32, 119, 97, 32, 82, 105, 106, 105, 108, 105, 32, 75, 97, 110, 116, 111, 114, 105, 32, 110, 105, 32, 107, 105, 97, 115, 105, 32, 103, 97, 110, 105, 63, 57345, 57350, 32, 82, 105, 106, 105, 108, 105, 32, 75, 97, 110, 116, 111, 114, 105, 32, 44, 32, 82, 105, 106, 105, 108, 105, 32, 75, 97, 110, 116, 97, 114, 117, 115, 105, 32, 97, 117, 32, 105, 110, 103, 46, 32, 65, 108, 112, 104, 97, 32, 67, 101, 110, 116, 97, 117, 114, 105, 32, 40, 112, 105, 97, 58, 32, 84, 111, 108, 105, 109, 97, 110, 32, 97, 117, 32, 82, 105, 103, 105, 108, 32, 75, 101, 110, 116, 97, 117, 114, 117, 115, 41, 32, 110, 105, 32, 110, 121, 111, 116, 97, 32, 105, 110, 97, 121, 111, 110, 103, 39, 97, 97, 32, 115, 97, 110, 97, 32, 107, 97, 116, 105, 107, 97, 32, 97, 110, 103, 97, 32, 121, 97, 32, 107, 117, 115, 105, 110, 105, 32, 107, 119, 101, 110, 121, 101, 32, 107, 117, 110, 100, 105, 110, 121, 111, 116, 97, 32, 121, 97, 32, 75, 97, 110, 116, 97, 114, 117, 115, 105, 32, 40, 112, 105, 97, 58, 32, 105, 110, 103, 46, 32, 67, 101, 110, 116, 97, 117, 114, 117, 115, 41, 46, 32, 78, 105, 32, 110, 121, 111, 116, 97, 32, 121, 97, 32, 107, 117, 110, 103, 97, 97, 32, 115, 97, 110, 97, 32, 121, 97, 32, 110, 110, 101, 32, 97, 110, 103, 97, 110, 105, 32, 108, 97, 107, 105, 110, 105, 32, 104, 97, 105, 111, 110, 101, 107, 97, 110, 105, 32, 107, 119, 101, 110, 121, 101, 32, 110, 117, 115, 117, 100, 117, 110, 105, 97, 32, 121, 97, 32, 107, 97, 115, 107, 97, 122, 105, 110, 105, 46, 32, 57351, 32, 65, 108, 112, 104, 97, 32, 67, 101, 110, 116, 97, 117, 114, 105, 32, 110, 105, 32, 110, 121, 111, 116, 97, 32, 121, 97, 32, 112, 101, 107, 101, 101, 32, 107, 119, 97, 32, 115, 97, 98, 97, 98, 117, 32, 110, 105, 32, 110, 121, 111, 116, 97, 32, 121, 101, 116, 117, 32, 106, 105, 114, 97, 110, 105, 32, 107, 97, 116, 105, 107, 97, 32, 97, 110, 103, 97, 32, 105, 110, 97, 32, 117, 109, 98, 97, 108, 105, 32, 119, 97, 32, 109, 105, 97, 107, 97, 32, 121, 97, 32, 110, 117, 114, 117, 32, 52, 46, 50, 46, 32, 73, 110, 97, 111, 110, 101, 107, 97, 110, 97, 32, 97, 110, 103, 97, 110, 105, 32, 107, 97, 114, 105, 98, 117, 32, 110, 97, 32, 107, 117, 110, 100, 105, 110, 121, 111, 116, 97, 32, 121, 97, 32, 83, 97, 108, 105, 98, 117, 32, 40, 67, 114, 117, 120, 41, 46, 32, 57352, 32, 82, 105, 106, 105, 108, 105, 32, 75, 97, 110, 116, 97, 114, 117, 115, 105, 32, 40, 65, 108, 112, 104, 97, 32, 67, 101, 110, 116, 97, 117, 114, 105, 41, 32, 105, 110, 97, 111, 110, 101, 107, 97, 110, 97, 32, 107, 97, 109, 97, 32, 110, 121, 111, 116, 97, 32, 109, 111, 106, 97, 32, 108, 97, 107, 105, 110, 105, 32, 107, 119, 97, 32, 100, 97, 114, 117, 98, 105, 110, 105, 32, 107, 117, 98, 119, 97, 32, 105, 110, 97, 111, 110, 101, 107, 97, 110, 97, 32, 107, 117, 119, 97, 32, 109, 102, 117, 109, 111, 32, 119, 97, 32, 110, 121, 111, 116, 97, 32, 116, 97, 116, 117, 32, 122, 105, 110, 97, 122, 111, 107, 97, 97, 32, 107, 97, 114, 105, 98, 117, 32, 110, 97, 32, 107, 117, 115, 104, 105, 107, 97, 109, 97, 110, 97, 32, 107, 97, 116, 105, 32, 121, 97, 111, 46, 32, 78, 121, 111, 116, 97, 32, 109, 97, 112, 97, 99, 104, 97, 32, 122, 97, 32, 65, 108, 112, 104, 97, 32, 67, 101, 110, 116, 97, 117, 114, 105, 32, 65, 32, 110, 97, 32, 65, 108, 112, 104, 97, 32, 67, 101, 110, 116, 97, 117, 114, 105, 32, 66, 32, 122, 105, 107, 111, 32, 109, 105, 97, 107, 97, 32, 121, 97, 32, 110, 117, 114, 117, 32, 52, 46, 51, 54, 32, 107, 117, 116, 111, 107, 97, 32, 107, 119, 101, 116, 117, 32, 110, 97, 32, 110, 121, 111, 116, 97, 32, 121, 97, 32, 116, 97, 116, 117, 32, 65, 108, 112, 104, 97, 32, 67, 101, 110, 116, 97, 117, 114, 105, 32, 67, 32, 97, 117, 32, 80, 114, 111, 120, 105, 109, 97, 32, 67, 101, 110, 116, 97, 117, 114, 105, 32, 105, 110, 97, 32, 117, 109, 98, 97, 108, 105, 32, 119, 97, 32, 109, 105, 97, 107, 97, 32, 121, 97, 32, 110, 117, 114, 117, 32, 52, 46, 50, 50, 46, 32, 57353, 32, 80, 114, 111, 120, 105, 109, 97, 32, 67, 101, 110, 116, 97, 117, 114, 105, 32, 40, 121, 97, 97, 110, 105, 32, 110, 121, 111, 116, 97, 32, 121, 97, 32, 75, 97, 110, 116, 97, 114, 117, 115, 105, 32, 105, 108, 105, 121, 111, 32, 107, 97, 114, 105, 98, 117, 32, 122, 97, 105, 100, 105, 32, 110, 97, 115, 105, 41, 32, 105, 109, 101, 103, 117, 110, 100, 117, 108, 105, 119, 97, 32, 107, 117, 119, 97, 32, 110, 97, 32, 115, 97, 121, 97, 114, 105, 32, 109, 111, 106, 97, 46, 32, 86, 105, 112, 105, 109, 111, 32, 118, 105, 110, 97, 118, 121, 111, 112, 97, 116, 105, 107, 97, 110, 97, 32, 104, 97, 100, 105, 32, 115, 97, 115, 97, 32, 122, 105, 110, 97, 111, 110, 121, 101, 115, 104, 97, 32, 117, 119, 101, 122, 101, 107, 97, 110, 111, 32, 109, 107, 117, 98, 119, 97, 32, 121, 97, 32, 107, 119, 97, 109, 98, 97, 32, 115, 97, 121, 97, 114, 105, 32, 104, 105, 105, 32, 110, 105, 32, 121, 97, 32, 109, 119, 97, 109, 98, 97, 32, 40, 107, 97, 109, 97, 32, 100, 117, 110, 105, 97, 32, 121, 101, 116, 117, 44, 32, 77, 105, 114, 105, 104, 105, 32, 97, 117, 32, 90, 117, 104, 117, 114, 97, 41, 32, 110, 97, 32, 105, 110, 97, 119, 101, 122, 97, 32, 107, 117, 119, 97, 32, 110, 97, 32, 97, 110, 103, 97, 104, 101, 119, 97, 44, 32, 116, 101, 110, 97, 32, 107, 97, 116, 105, 107, 97, 32, 117, 112, 101, 111, 32, 119, 97, 32, 106, 111, 116, 111, 32, 117, 110, 97, 111, 114, 117, 104, 117, 115, 117, 32, 107, 117, 119, 101, 112, 111, 32, 107, 119, 97, 32, 117, 104, 97, 105, 46, 32, 91, 49, 93, 57345, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
545
+ attention_mask = [1 if x != 0 else 0 for x in input_ids]
546
+ token_type_ids = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
547
+ # fmt: on
548
+ input_ids = torch.tensor([input_ids])
549
+ attention_mask = torch.tensor([attention_mask])
550
+ token_type_ids = torch.tensor([token_type_ids])
551
+ outputs = model(input_ids, attention_mask, token_type_ids)
552
+
553
+ # verify sequence output
554
+ expected_shape = torch.Size((1, 2048, 768))
555
+ self.assertEqual(outputs.last_hidden_state.shape, expected_shape)
556
+
557
+ expected_slice = torch.tensor(
558
+ [
559
+ [-0.161433131, 0.395568609, 0.0407391489],
560
+ [-0.108025983, 0.362060368, -0.544592619],
561
+ [-0.141537309, 0.180541009, 0.076907],
562
+ ]
563
+ )
564
+
565
+ self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3], expected_slice, atol=1e-2))
566
+
567
+ # verify pooled output
568
+ expected_shape = torch.Size((1, 768))
569
+ self.assertEqual(outputs.pooler_output.shape, expected_shape)
570
+
571
+ expected_slice = torch.tensor([-0.884311497, -0.529064834, 0.723164916])
572
+
573
+ self.assertTrue(torch.allclose(outputs.pooler_output[0, :3], expected_slice, atol=1e-2))
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/canine/test_tokenization_canine.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 Google AI 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
+
16
+ import json
17
+ import os
18
+ import shutil
19
+ import tempfile
20
+ import unittest
21
+
22
+ from transformers import BatchEncoding, CanineTokenizer
23
+ from transformers.testing_utils import require_tokenizers, require_torch
24
+ from transformers.tokenization_utils import AddedToken
25
+ from transformers.utils import cached_property
26
+
27
+ from ...test_tokenization_common import TokenizerTesterMixin
28
+
29
+
30
+ class CanineTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
31
+ from_pretrained_id = "nielsr/canine-s"
32
+ tokenizer_class = CanineTokenizer
33
+ test_rust_tokenizer = False
34
+
35
+ def setUp(self):
36
+ super().setUp()
37
+ tokenizer = CanineTokenizer()
38
+ tokenizer.save_pretrained(self.tmpdirname)
39
+
40
+ @cached_property
41
+ def canine_tokenizer(self):
42
+ return CanineTokenizer.from_pretrained("google/canine-s")
43
+
44
+ def get_tokenizer(self, **kwargs) -> CanineTokenizer:
45
+ tokenizer = self.tokenizer_class.from_pretrained(self.tmpdirname, **kwargs)
46
+ tokenizer._unicode_vocab_size = 1024
47
+ return tokenizer
48
+
49
+ @require_torch
50
+ def test_prepare_batch_integration(self):
51
+ tokenizer = self.canine_tokenizer
52
+ src_text = ["Life is like a box of chocolates.", "You never know what you're gonna get."]
53
+ expected_src_tokens = [57344, 76, 105, 102, 101, 32, 105, 115, 32, 108, 105, 107, 101, 32, 97, 32, 98, 111, 120, 32, 111, 102, 32, 99, 104, 111, 99, 111, 108, 97, 116, 101, 115, 46, 57345, 0, 0, 0, 0] # fmt: skip
54
+ batch = tokenizer(src_text, padding=True, return_tensors="pt")
55
+ self.assertIsInstance(batch, BatchEncoding)
56
+
57
+ result = list(batch.input_ids.numpy()[0])
58
+
59
+ self.assertListEqual(expected_src_tokens, result)
60
+
61
+ self.assertEqual((2, 39), batch.input_ids.shape)
62
+ self.assertEqual((2, 39), batch.attention_mask.shape)
63
+
64
+ @require_torch
65
+ def test_encoding_keys(self):
66
+ tokenizer = self.canine_tokenizer
67
+ src_text = ["Once there was a man.", "He wrote a test in HuggingFace Tranformers."]
68
+ batch = tokenizer(src_text, padding=True, return_tensors="pt")
69
+ # check if input_ids, attention_mask and token_type_ids are returned
70
+ self.assertIn("input_ids", batch)
71
+ self.assertIn("attention_mask", batch)
72
+ self.assertIn("token_type_ids", batch)
73
+
74
+ @require_torch
75
+ def test_max_length_integration(self):
76
+ tokenizer = self.canine_tokenizer
77
+ tgt_text = [
78
+ "What's the weater?",
79
+ "It's about 25 degrees.",
80
+ ]
81
+ targets = tokenizer(
82
+ text_target=tgt_text, max_length=32, padding="max_length", truncation=True, return_tensors="pt"
83
+ )
84
+ self.assertEqual(32, targets["input_ids"].shape[1])
85
+
86
+ # cannot use default save_and_load_tokenizer test method because tokenizer has no vocab
87
+ def test_save_and_load_tokenizer(self):
88
+ # safety check on max_len default value so we are sure the test works
89
+ tokenizers = self.get_tokenizers()
90
+ for tokenizer in tokenizers:
91
+ with self.subTest(f"{tokenizer.__class__.__name__}"):
92
+ self.assertNotEqual(tokenizer.model_max_length, 42)
93
+
94
+ # Now let's start the test
95
+ tokenizers = self.get_tokenizers()
96
+ for tokenizer in tokenizers:
97
+ with self.subTest(f"{tokenizer.__class__.__name__}"):
98
+ # Isolate this from the other tests because we save additional tokens/etc
99
+ tmpdirname = tempfile.mkdtemp()
100
+
101
+ sample_text = " He is very happy, UNwant\u00e9d,running"
102
+ before_tokens = tokenizer.encode(sample_text, add_special_tokens=False)
103
+ tokenizer.save_pretrained(tmpdirname)
104
+
105
+ after_tokenizer = tokenizer.__class__.from_pretrained(tmpdirname)
106
+ after_tokens = after_tokenizer.encode(sample_text, add_special_tokens=False)
107
+ self.assertListEqual(before_tokens, after_tokens)
108
+
109
+ shutil.rmtree(tmpdirname)
110
+
111
+ tokenizers = self.get_tokenizers(model_max_length=42)
112
+ for tokenizer in tokenizers:
113
+ with self.subTest(f"{tokenizer.__class__.__name__}"):
114
+ # Isolate this from the other tests because we save additional tokens/etc
115
+ tmpdirname = tempfile.mkdtemp()
116
+
117
+ sample_text = " He is very happy, UNwant\u00e9d,running"
118
+
119
+ additional_special_tokens = tokenizer.additional_special_tokens
120
+
121
+ # We can add a new special token for Canine as follows:
122
+ new_additional_special_token = chr(0xE007)
123
+ additional_special_tokens.append(new_additional_special_token)
124
+ tokenizer.add_special_tokens(
125
+ {"additional_special_tokens": additional_special_tokens}, replace_additional_special_tokens=False
126
+ )
127
+ before_tokens = tokenizer.encode(sample_text, add_special_tokens=False)
128
+ tokenizer.save_pretrained(tmpdirname)
129
+
130
+ after_tokenizer = tokenizer.__class__.from_pretrained(tmpdirname)
131
+ after_tokens = after_tokenizer.encode(sample_text, add_special_tokens=False)
132
+ self.assertListEqual(before_tokens, after_tokens)
133
+ self.assertIn(new_additional_special_token, after_tokenizer.additional_special_tokens)
134
+ self.assertEqual(after_tokenizer.model_max_length, 42)
135
+
136
+ tokenizer = tokenizer.__class__.from_pretrained(tmpdirname, model_max_length=43)
137
+ self.assertEqual(tokenizer.model_max_length, 43)
138
+
139
+ shutil.rmtree(tmpdirname)
140
+
141
+ def test_add_special_tokens(self):
142
+ tokenizers = self.get_tokenizers(do_lower_case=False)
143
+ for tokenizer in tokenizers:
144
+ with self.subTest(f"{tokenizer.__class__.__name__}"):
145
+ input_text, ids = self.get_clean_sequence(tokenizer)
146
+
147
+ # a special token for Canine can be defined as follows:
148
+ SPECIAL_TOKEN = 0xE005
149
+ special_token = chr(SPECIAL_TOKEN)
150
+
151
+ tokenizer.add_special_tokens({"cls_token": special_token})
152
+ encoded_special_token = tokenizer.encode(special_token, add_special_tokens=False)
153
+ self.assertEqual(len(encoded_special_token), 1)
154
+
155
+ text = tokenizer.decode(ids + encoded_special_token, clean_up_tokenization_spaces=False)
156
+ encoded = tokenizer.encode(text, add_special_tokens=False)
157
+
158
+ input_encoded = tokenizer.encode(input_text, add_special_tokens=False)
159
+ special_token_id = tokenizer.encode(special_token, add_special_tokens=False)
160
+ self.assertEqual(encoded, input_encoded + special_token_id)
161
+
162
+ decoded = tokenizer.decode(encoded, skip_special_tokens=True)
163
+ self.assertTrue(special_token not in decoded)
164
+
165
+ def test_tokenize_special_tokens(self):
166
+ tokenizers = self.get_tokenizers(do_lower_case=True)
167
+ for tokenizer in tokenizers:
168
+ with self.subTest(f"{tokenizer.__class__.__name__}"):
169
+ SPECIAL_TOKEN_1 = chr(0xE005)
170
+ SPECIAL_TOKEN_2 = chr(0xE006)
171
+ tokenizer.add_tokens([SPECIAL_TOKEN_1], special_tokens=True)
172
+ tokenizer.add_special_tokens({"additional_special_tokens": [SPECIAL_TOKEN_2]})
173
+
174
+ token_1 = tokenizer.tokenize(SPECIAL_TOKEN_1)
175
+ token_2 = tokenizer.tokenize(SPECIAL_TOKEN_2)
176
+
177
+ self.assertEqual(len(token_1), 1)
178
+ self.assertEqual(len(token_2), 1)
179
+ self.assertEqual(token_1[0], SPECIAL_TOKEN_1)
180
+ self.assertEqual(token_2[0], SPECIAL_TOKEN_2)
181
+
182
+ @require_tokenizers
183
+ def test_added_token_serializable(self):
184
+ tokenizers = self.get_tokenizers(do_lower_case=False)
185
+ for tokenizer in tokenizers:
186
+ with self.subTest(f"{tokenizer.__class__.__name__}"):
187
+ # a special token for Canine can be defined as follows:
188
+ NEW_TOKEN = 0xE006
189
+ new_token = chr(NEW_TOKEN)
190
+
191
+ new_token = AddedToken(new_token, lstrip=True)
192
+ tokenizer.add_special_tokens({"additional_special_tokens": [new_token]})
193
+
194
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
195
+ tokenizer.save_pretrained(tmp_dir_name)
196
+ tokenizer.from_pretrained(tmp_dir_name)
197
+
198
+ def test_special_tokens_initialization_with_non_empty_additional_special_tokens(self):
199
+ tokenizer_list = []
200
+ if self.test_slow_tokenizer:
201
+ tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()))
202
+
203
+ if self.test_rust_tokenizer:
204
+ tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()))
205
+
206
+ for tokenizer_class, tokenizer_utils in tokenizer_list:
207
+ with tempfile.TemporaryDirectory() as tmp_dir:
208
+ tokenizer_utils.save_pretrained(tmp_dir)
209
+
210
+ with open(os.path.join(tmp_dir, "special_tokens_map.json"), encoding="utf-8") as json_file:
211
+ special_tokens_map = json.load(json_file)
212
+
213
+ with open(os.path.join(tmp_dir, "tokenizer_config.json"), encoding="utf-8") as json_file:
214
+ tokenizer_config = json.load(json_file)
215
+
216
+ # a special token for Canine can be defined as follows:
217
+ NEW_TOKEN = 0xE006
218
+ new_token_1 = chr(NEW_TOKEN)
219
+
220
+ special_tokens_map["additional_special_tokens"] = [new_token_1]
221
+ tokenizer_config["additional_special_tokens"] = [new_token_1]
222
+
223
+ with open(os.path.join(tmp_dir, "special_tokens_map.json"), "w", encoding="utf-8") as outfile:
224
+ json.dump(special_tokens_map, outfile)
225
+ with open(os.path.join(tmp_dir, "tokenizer_config.json"), "w", encoding="utf-8") as outfile:
226
+ json.dump(tokenizer_config, outfile)
227
+
228
+ # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes
229
+ # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and
230
+ # "special_tokens_map.json" files
231
+ tokenizer_without_change_in_init = tokenizer_class.from_pretrained(tmp_dir, extra_ids=0)
232
+ self.assertIn(new_token_1, tokenizer_without_change_in_init.additional_special_tokens)
233
+ # self.assertIn("an_additional_special_token",tokenizer_without_change_in_init.get_vocab()) # ByT5Tokenization no vocab
234
+ self.assertEqual(
235
+ [new_token_1],
236
+ tokenizer_without_change_in_init.convert_ids_to_tokens(
237
+ tokenizer_without_change_in_init.convert_tokens_to_ids([new_token_1])
238
+ ),
239
+ )
240
+
241
+ NEW_TOKEN = 0xE007
242
+ new_token_2 = chr(NEW_TOKEN)
243
+ # Now we test that we can change the value of additional_special_tokens in the from_pretrained
244
+ new_added_tokens = [AddedToken(new_token_2, lstrip=True)]
245
+ tokenizer = tokenizer_class.from_pretrained(
246
+ tmp_dir, additional_special_tokens=new_added_tokens, extra_ids=0
247
+ )
248
+
249
+ self.assertIn(new_token_2, tokenizer.additional_special_tokens)
250
+ # self.assertIn(new_token_2,tokenizer.get_vocab()) # ByT5Tokenization no vocab
251
+ self.assertEqual(
252
+ [new_token_2], tokenizer.convert_ids_to_tokens(tokenizer.convert_tokens_to_ids([new_token_2]))
253
+ )
254
+
255
+ @require_tokenizers
256
+ def test_encode_decode_with_spaces(self):
257
+ tokenizers = self.get_tokenizers(do_lower_case=False)
258
+ for tokenizer in tokenizers:
259
+ with self.subTest(f"{tokenizer.__class__.__name__}"):
260
+ input = "hello world"
261
+ if self.space_between_special_tokens:
262
+ output = "[CLS] hello world [SEP]"
263
+ else:
264
+ output = input
265
+ encoded = tokenizer.encode(input, add_special_tokens=False)
266
+ decoded = tokenizer.decode(encoded, spaces_between_special_tokens=self.space_between_special_tokens)
267
+ self.assertIn(decoded, [output, output.lower()])
268
+
269
+ # cannot use default `test_tokenizers_common_ids_setters` method because tokenizer has no vocab
270
+ def test_tokenizers_common_ids_setters(self):
271
+ tokenizers = self.get_tokenizers()
272
+ for tokenizer in tokenizers:
273
+ with self.subTest(f"{tokenizer.__class__.__name__}"):
274
+ attributes_list = [
275
+ "bos_token",
276
+ "eos_token",
277
+ "unk_token",
278
+ "sep_token",
279
+ "pad_token",
280
+ "cls_token",
281
+ "mask_token",
282
+ ]
283
+
284
+ token_to_test_setters = "a"
285
+ token_id_to_test_setters = ord(token_to_test_setters)
286
+
287
+ for attr in attributes_list:
288
+ setattr(tokenizer, attr + "_id", None)
289
+ self.assertEqual(getattr(tokenizer, attr), None)
290
+ self.assertEqual(getattr(tokenizer, attr + "_id"), None)
291
+
292
+ setattr(tokenizer, attr + "_id", token_id_to_test_setters)
293
+ self.assertEqual(getattr(tokenizer, attr), token_to_test_setters)
294
+ self.assertEqual(getattr(tokenizer, attr + "_id"), token_id_to_test_setters)
295
+
296
+ setattr(tokenizer, "additional_special_tokens_ids", [])
297
+ self.assertListEqual(getattr(tokenizer, "additional_special_tokens"), [])
298
+ self.assertListEqual(getattr(tokenizer, "additional_special_tokens_ids"), [])
299
+
300
+ additional_special_token_id = 0xE006
301
+ additional_special_token = chr(additional_special_token_id)
302
+ setattr(tokenizer, "additional_special_tokens_ids", [additional_special_token_id])
303
+ self.assertListEqual(getattr(tokenizer, "additional_special_tokens"), [additional_special_token])
304
+ self.assertListEqual(getattr(tokenizer, "additional_special_tokens_ids"), [additional_special_token_id])
305
+
306
+ @unittest.skip(reason="tokenizer has a fixed vocab_size (namely all possible unicode code points)")
307
+ def test_add_tokens_tokenizer(self):
308
+ pass
309
+
310
+ # CanineTokenizer does not support do_lower_case = True, as each character has its own Unicode code point
311
+ # ("b" and "B" for example have different Unicode code points)
312
+ @unittest.skip(reason="CanineTokenizer does not support do_lower_case = True")
313
+ def test_added_tokens_do_lower_case(self):
314
+ pass
315
+
316
+ @unittest.skip(reason="CanineModel does not support the get_input_embeddings nor the get_vocab method")
317
+ def test_np_encode_plus_sent_to_model(self):
318
+ pass
319
+
320
+ @unittest.skip(reason="CanineModel does not support the get_input_embeddings nor the get_vocab method")
321
+ def test_torch_encode_plus_sent_to_model(self):
322
+ pass
323
+
324
+ @unittest.skip(reason="CanineTokenizer does not have vocabulary")
325
+ def test_get_vocab(self):
326
+ pass
327
+
328
+ @unittest.skip(reason="inputs cannot be pretokenized since ids depend on whole input string")
329
+ def test_pretokenized_inputs(self):
330
+ pass
331
+
332
+ @unittest.skip(reason="CanineTokenizer does not have vocabulary")
333
+ def test_conversion_reversible(self):
334
+ pass
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/chameleon/__init__.py ADDED
File without changes