AdithyaSK HF Staff commited on
Commit
aeb0791
·
verified ·
1 Parent(s): a759c9c

Stage Harbor release files 27501-28000

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-441eeab80047/tests/source/tests/models/funnel/test_modeling_funnel.py +525 -0
  2. tasks/tasksmith-441eeab80047/tests/source/tests/models/funnel/test_modeling_tf_funnel.py +415 -0
  3. tasks/tasksmith-441eeab80047/tests/source/tests/models/funnel/test_tokenization_funnel.py +83 -0
  4. tasks/tasksmith-441eeab80047/tests/source/tests/models/fuyu/__init__.py +0 -0
  5. tasks/tasksmith-441eeab80047/tests/source/tests/models/fuyu/test_image_processing_fuyu.py +63 -0
  6. tasks/tasksmith-441eeab80047/tests/source/tests/models/fuyu/test_modeling_fuyu.py +421 -0
  7. tasks/tasksmith-441eeab80047/tests/source/tests/models/fuyu/test_processor_fuyu.py +403 -0
  8. tasks/tasksmith-441eeab80047/tests/source/tests/models/gemma/__init__.py +0 -0
  9. tasks/tasksmith-441eeab80047/tests/source/tests/models/gemma/test_modeling_flax_gemma.py +264 -0
  10. tasks/tasksmith-441eeab80047/tests/source/tests/models/gemma/test_modeling_gemma.py +875 -0
  11. tasks/tasksmith-441eeab80047/tests/source/tests/models/gemma/test_tokenization_gemma.py +544 -0
  12. tasks/tasksmith-441eeab80047/tests/source/tests/models/gemma2/__init__.py +0 -0
  13. tasks/tasksmith-441eeab80047/tests/source/tests/models/gemma2/test_modeling_gemma2.py +394 -0
  14. tasks/tasksmith-441eeab80047/tests/source/tests/models/gemma3/__init__.py +0 -0
  15. tasks/tasksmith-441eeab80047/tests/source/tests/models/gemma3/test_image_processing_gemma3.py +229 -0
  16. tasks/tasksmith-441eeab80047/tests/source/tests/models/gemma3/test_modeling_gemma3.py +520 -0
  17. tasks/tasksmith-441eeab80047/tests/source/tests/models/gemma3/test_processing_gemma3.py +136 -0
  18. tasks/tasksmith-441eeab80047/tests/source/tests/models/git/__init__.py +0 -0
  19. tasks/tasksmith-441eeab80047/tests/source/tests/models/git/test_modeling_git.py +630 -0
  20. tasks/tasksmith-441eeab80047/tests/source/tests/models/git/test_processor_git.py +143 -0
  21. tasks/tasksmith-441eeab80047/tests/source/tests/models/glm/__init__.py +0 -0
  22. tasks/tasksmith-441eeab80047/tests/source/tests/models/glm/test_modeling_glm.py +541 -0
  23. tasks/tasksmith-441eeab80047/tests/source/tests/models/glpn/__init__.py +0 -0
  24. tasks/tasksmith-441eeab80047/tests/source/tests/models/glpn/test_image_processing_glpn.py +164 -0
  25. tasks/tasksmith-441eeab80047/tests/source/tests/models/glpn/test_modeling_glpn.py +346 -0
  26. tasks/tasksmith-441eeab80047/tests/source/tests/models/got_ocr2/__init__.py +0 -0
  27. tasks/tasksmith-441eeab80047/tests/source/tests/models/got_ocr2/test_image_processing_got_ocr2.py +178 -0
  28. tasks/tasksmith-441eeab80047/tests/source/tests/models/got_ocr2/test_modeling_got_ocr2.py +379 -0
  29. tasks/tasksmith-441eeab80047/tests/source/tests/models/got_ocr2/test_processor_got_ocr2.py +77 -0
  30. tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt2/__init__.py +0 -0
  31. tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt2/test_modeling_flax_gpt2.py +254 -0
  32. tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt2/test_modeling_gpt2.py +898 -0
  33. tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt2/test_modeling_tf_gpt2.py +733 -0
  34. tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt2/test_tokenization_gpt2.py +355 -0
  35. tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt2/test_tokenization_gpt2_tf.py +131 -0
  36. tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_bigcode/__init__.py +0 -0
  37. tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_bigcode/test_modeling_gpt_bigcode.py +595 -0
  38. tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_neo/__init__.py +0 -0
  39. tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_neo/test_modeling_flax_gpt_neo.py +223 -0
  40. tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_neo/test_modeling_gpt_neo.py +574 -0
  41. tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_neox/__init__.py +0 -0
  42. tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_neox/test_modeling_gpt_neox.py +483 -0
  43. tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_neox_japanese/__init__.py +0 -0
  44. tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_neox_japanese/test_modeling_gpt_neox_japanese.py +269 -0
  45. tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_neox_japanese/test_tokenization_gpt_neox_japanese.py +138 -0
  46. tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_sw3/__init__.py +0 -0
  47. tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_sw3/test_tokenization_gpt_sw3.py +162 -0
  48. tasks/tasksmith-441eeab80047/tests/source/tests/models/gptj/__init__.py +0 -0
  49. tasks/tasksmith-441eeab80047/tests/source/tests/models/gptj/test_modeling_flax_gptj.py +220 -0
  50. tasks/tasksmith-441eeab80047/tests/source/tests/models/gptj/test_modeling_gptj.py +580 -0
tasks/tasksmith-441eeab80047/tests/source/tests/models/funnel/test_modeling_funnel.py ADDED
@@ -0,0 +1,525 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 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
+
17
+ import unittest
18
+
19
+ from transformers import FunnelConfig, FunnelTokenizer, is_torch_available
20
+ from transformers.models.auto import get_values
21
+ from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device
22
+
23
+ from ...test_configuration_common import ConfigTester
24
+ from ...test_modeling_common import ModelTesterMixin, ids_tensor
25
+ from ...test_pipeline_mixin import PipelineTesterMixin
26
+
27
+
28
+ if is_torch_available():
29
+ import torch
30
+
31
+ from transformers import (
32
+ MODEL_FOR_PRETRAINING_MAPPING,
33
+ FunnelBaseModel,
34
+ FunnelForMaskedLM,
35
+ FunnelForMultipleChoice,
36
+ FunnelForPreTraining,
37
+ FunnelForQuestionAnswering,
38
+ FunnelForSequenceClassification,
39
+ FunnelForTokenClassification,
40
+ FunnelModel,
41
+ )
42
+
43
+
44
+ class FunnelModelTester:
45
+ """You can also import this e.g, from .test_modeling_funnel import FunnelModelTester"""
46
+
47
+ def __init__(
48
+ self,
49
+ parent,
50
+ batch_size=13,
51
+ seq_length=7,
52
+ is_training=True,
53
+ use_input_mask=True,
54
+ use_token_type_ids=True,
55
+ use_labels=True,
56
+ vocab_size=99,
57
+ block_sizes=[1, 1, 2],
58
+ num_decoder_layers=1,
59
+ d_model=32,
60
+ n_head=4,
61
+ d_head=8,
62
+ d_inner=37,
63
+ hidden_act="gelu_new",
64
+ hidden_dropout=0.1,
65
+ attention_dropout=0.1,
66
+ activation_dropout=0.0,
67
+ max_position_embeddings=512,
68
+ type_vocab_size=3,
69
+ initializer_std=0.02, # Set to a smaller value, so we can keep the small error threshold (1e-5) in the test
70
+ num_labels=3,
71
+ num_choices=4,
72
+ scope=None,
73
+ base=False,
74
+ ):
75
+ self.parent = parent
76
+ self.batch_size = batch_size
77
+ self.seq_length = seq_length
78
+ self.is_training = is_training
79
+ self.use_input_mask = use_input_mask
80
+ self.use_token_type_ids = use_token_type_ids
81
+ self.use_labels = use_labels
82
+ self.vocab_size = vocab_size
83
+ self.block_sizes = block_sizes
84
+ self.num_decoder_layers = num_decoder_layers
85
+ self.d_model = d_model
86
+ self.n_head = n_head
87
+ self.d_head = d_head
88
+ self.d_inner = d_inner
89
+ self.hidden_act = hidden_act
90
+ self.hidden_dropout = hidden_dropout
91
+ self.attention_dropout = attention_dropout
92
+ self.activation_dropout = activation_dropout
93
+ self.max_position_embeddings = max_position_embeddings
94
+ self.type_vocab_size = type_vocab_size
95
+ self.type_sequence_label_size = 2
96
+ self.num_labels = num_labels
97
+ self.num_choices = num_choices
98
+ self.scope = scope
99
+ self.initializer_std = initializer_std
100
+
101
+ # Used in the tests to check the size of the first attention layer
102
+ self.num_attention_heads = n_head
103
+ # Used in the tests to check the size of the first hidden state
104
+ self.hidden_size = self.d_model
105
+ # Used in the tests to check the number of output hidden states/attentions
106
+ self.num_hidden_layers = sum(self.block_sizes) + (0 if base else self.num_decoder_layers)
107
+ # FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with
108
+ # the last hidden state of the first block (which is the first hidden state of the decoder).
109
+ if not base:
110
+ self.expected_num_hidden_layers = self.num_hidden_layers + 2
111
+
112
+ def prepare_config_and_inputs(self):
113
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
114
+
115
+ input_mask = None
116
+ if self.use_input_mask:
117
+ input_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
118
+
119
+ token_type_ids = None
120
+ if self.use_token_type_ids:
121
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
122
+
123
+ sequence_labels = None
124
+ token_labels = None
125
+ choice_labels = None
126
+ if self.use_labels:
127
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
128
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
129
+ choice_labels = ids_tensor([self.batch_size], self.num_choices)
130
+ fake_token_labels = ids_tensor([self.batch_size, self.seq_length], 1)
131
+
132
+ config = self.get_config()
133
+
134
+ return (
135
+ config,
136
+ input_ids,
137
+ token_type_ids,
138
+ input_mask,
139
+ sequence_labels,
140
+ token_labels,
141
+ choice_labels,
142
+ fake_token_labels,
143
+ )
144
+
145
+ def get_config(self):
146
+ return FunnelConfig(
147
+ vocab_size=self.vocab_size,
148
+ block_sizes=self.block_sizes,
149
+ num_decoder_layers=self.num_decoder_layers,
150
+ d_model=self.d_model,
151
+ n_head=self.n_head,
152
+ d_head=self.d_head,
153
+ d_inner=self.d_inner,
154
+ hidden_act=self.hidden_act,
155
+ hidden_dropout=self.hidden_dropout,
156
+ attention_dropout=self.attention_dropout,
157
+ activation_dropout=self.activation_dropout,
158
+ max_position_embeddings=self.max_position_embeddings,
159
+ type_vocab_size=self.type_vocab_size,
160
+ initializer_std=self.initializer_std,
161
+ )
162
+
163
+ def create_and_check_model(
164
+ self,
165
+ config,
166
+ input_ids,
167
+ token_type_ids,
168
+ input_mask,
169
+ sequence_labels,
170
+ token_labels,
171
+ choice_labels,
172
+ fake_token_labels,
173
+ ):
174
+ model = FunnelModel(config=config)
175
+ model.to(torch_device)
176
+ model.eval()
177
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
178
+ result = model(input_ids, token_type_ids=token_type_ids)
179
+ result = model(input_ids)
180
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.d_model))
181
+
182
+ model.config.truncate_seq = False
183
+ result = model(input_ids)
184
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.d_model))
185
+
186
+ model.config.separate_cls = False
187
+ result = model(input_ids)
188
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.d_model))
189
+
190
+ def create_and_check_base_model(
191
+ self,
192
+ config,
193
+ input_ids,
194
+ token_type_ids,
195
+ input_mask,
196
+ sequence_labels,
197
+ token_labels,
198
+ choice_labels,
199
+ fake_token_labels,
200
+ ):
201
+ model = FunnelBaseModel(config=config)
202
+ model.to(torch_device)
203
+ model.eval()
204
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
205
+ result = model(input_ids, token_type_ids=token_type_ids)
206
+ result = model(input_ids)
207
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, 2, self.d_model))
208
+
209
+ model.config.truncate_seq = False
210
+ result = model(input_ids)
211
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, 3, self.d_model))
212
+
213
+ model.config.separate_cls = False
214
+ result = model(input_ids)
215
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, 2, self.d_model))
216
+
217
+ def create_and_check_for_pretraining(
218
+ self,
219
+ config,
220
+ input_ids,
221
+ token_type_ids,
222
+ input_mask,
223
+ sequence_labels,
224
+ token_labels,
225
+ choice_labels,
226
+ fake_token_labels,
227
+ ):
228
+ config.num_labels = self.num_labels
229
+ model = FunnelForPreTraining(config=config)
230
+ model.to(torch_device)
231
+ model.eval()
232
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=fake_token_labels)
233
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length))
234
+
235
+ def create_and_check_for_masked_lm(
236
+ self,
237
+ config,
238
+ input_ids,
239
+ token_type_ids,
240
+ input_mask,
241
+ sequence_labels,
242
+ token_labels,
243
+ choice_labels,
244
+ fake_token_labels,
245
+ ):
246
+ model = FunnelForMaskedLM(config=config)
247
+ model.to(torch_device)
248
+ model.eval()
249
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
250
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
251
+
252
+ def create_and_check_for_sequence_classification(
253
+ self,
254
+ config,
255
+ input_ids,
256
+ token_type_ids,
257
+ input_mask,
258
+ sequence_labels,
259
+ token_labels,
260
+ choice_labels,
261
+ fake_token_labels,
262
+ ):
263
+ config.num_labels = self.num_labels
264
+ model = FunnelForSequenceClassification(config)
265
+ model.to(torch_device)
266
+ model.eval()
267
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels)
268
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
269
+
270
+ def create_and_check_for_multiple_choice(
271
+ self,
272
+ config,
273
+ input_ids,
274
+ token_type_ids,
275
+ input_mask,
276
+ sequence_labels,
277
+ token_labels,
278
+ choice_labels,
279
+ fake_token_labels,
280
+ ):
281
+ config.num_choices = self.num_choices
282
+ model = FunnelForMultipleChoice(config=config)
283
+ model.to(torch_device)
284
+ model.eval()
285
+ multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
286
+ multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
287
+ multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
288
+ result = model(
289
+ multiple_choice_inputs_ids,
290
+ attention_mask=multiple_choice_input_mask,
291
+ token_type_ids=multiple_choice_token_type_ids,
292
+ labels=choice_labels,
293
+ )
294
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
295
+
296
+ def create_and_check_for_token_classification(
297
+ self,
298
+ config,
299
+ input_ids,
300
+ token_type_ids,
301
+ input_mask,
302
+ sequence_labels,
303
+ token_labels,
304
+ choice_labels,
305
+ fake_token_labels,
306
+ ):
307
+ config.num_labels = self.num_labels
308
+ model = FunnelForTokenClassification(config=config)
309
+ model.to(torch_device)
310
+ model.eval()
311
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
312
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
313
+
314
+ def create_and_check_for_question_answering(
315
+ self,
316
+ config,
317
+ input_ids,
318
+ token_type_ids,
319
+ input_mask,
320
+ sequence_labels,
321
+ token_labels,
322
+ choice_labels,
323
+ fake_token_labels,
324
+ ):
325
+ model = FunnelForQuestionAnswering(config=config)
326
+ model.to(torch_device)
327
+ model.eval()
328
+ result = model(
329
+ input_ids,
330
+ attention_mask=input_mask,
331
+ token_type_ids=token_type_ids,
332
+ start_positions=sequence_labels,
333
+ end_positions=sequence_labels,
334
+ )
335
+ self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
336
+ self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
337
+
338
+ def prepare_config_and_inputs_for_common(self):
339
+ config_and_inputs = self.prepare_config_and_inputs()
340
+ (
341
+ config,
342
+ input_ids,
343
+ token_type_ids,
344
+ input_mask,
345
+ sequence_labels,
346
+ token_labels,
347
+ choice_labels,
348
+ fake_token_labels,
349
+ ) = config_and_inputs
350
+ inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
351
+ return config, inputs_dict
352
+
353
+
354
+ @require_torch
355
+ class FunnelModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
356
+ test_head_masking = False
357
+ test_pruning = False
358
+ all_model_classes = (
359
+ (
360
+ FunnelModel,
361
+ FunnelForMaskedLM,
362
+ FunnelForPreTraining,
363
+ FunnelForQuestionAnswering,
364
+ FunnelForTokenClassification,
365
+ )
366
+ if is_torch_available()
367
+ else ()
368
+ )
369
+ pipeline_model_mapping = (
370
+ {
371
+ "feature-extraction": (FunnelBaseModel, FunnelModel),
372
+ "fill-mask": FunnelForMaskedLM,
373
+ "question-answering": FunnelForQuestionAnswering,
374
+ "text-classification": FunnelForSequenceClassification,
375
+ "token-classification": FunnelForTokenClassification,
376
+ "zero-shot": FunnelForSequenceClassification,
377
+ }
378
+ if is_torch_available()
379
+ else {}
380
+ )
381
+
382
+ # special case for ForPreTraining model
383
+ def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
384
+ inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
385
+
386
+ if return_labels:
387
+ if model_class in get_values(MODEL_FOR_PRETRAINING_MAPPING):
388
+ inputs_dict["labels"] = torch.zeros(
389
+ (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device
390
+ )
391
+ return inputs_dict
392
+
393
+ def setUp(self):
394
+ self.model_tester = FunnelModelTester(self)
395
+ self.config_tester = ConfigTester(self, config_class=FunnelConfig)
396
+
397
+ def test_config(self):
398
+ self.config_tester.run_common_tests()
399
+
400
+ def test_model(self):
401
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
402
+ self.model_tester.create_and_check_model(*config_and_inputs)
403
+
404
+ def test_for_pretraining(self):
405
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
406
+ self.model_tester.create_and_check_for_pretraining(*config_and_inputs)
407
+
408
+ def test_for_masked_lm(self):
409
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
410
+ self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
411
+
412
+ def test_for_token_classification(self):
413
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
414
+ self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
415
+
416
+ def test_for_question_answering(self):
417
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
418
+ self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
419
+
420
+ # overwrite from test_modeling_common
421
+ def _mock_init_weights(self, module):
422
+ if hasattr(module, "weight") and module.weight is not None:
423
+ module.weight.data.fill_(3)
424
+ if hasattr(module, "bias") and module.bias is not None:
425
+ module.bias.data.fill_(3)
426
+
427
+ for param in ["r_w_bias", "r_r_bias", "r_kernel", "r_s_bias", "seg_embed"]:
428
+ if hasattr(module, param) and getattr(module, param) is not None:
429
+ weight = getattr(module, param)
430
+ weight.data.fill_(3)
431
+
432
+
433
+ @require_torch
434
+ class FunnelBaseModelTest(ModelTesterMixin, unittest.TestCase):
435
+ test_head_masking = False
436
+ test_pruning = False
437
+ all_model_classes = (
438
+ (FunnelBaseModel, FunnelForMultipleChoice, FunnelForSequenceClassification) if is_torch_available() else ()
439
+ )
440
+
441
+ def setUp(self):
442
+ self.model_tester = FunnelModelTester(self, base=True)
443
+ self.config_tester = ConfigTester(self, config_class=FunnelConfig)
444
+
445
+ def test_config(self):
446
+ self.config_tester.run_common_tests()
447
+
448
+ def test_base_model(self):
449
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
450
+ self.model_tester.create_and_check_base_model(*config_and_inputs)
451
+
452
+ def test_for_sequence_classification(self):
453
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
454
+ self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs)
455
+
456
+ def test_for_multiple_choice(self):
457
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
458
+ self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
459
+
460
+ # overwrite from test_modeling_common
461
+ def test_training(self):
462
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
463
+ config.return_dict = True
464
+
465
+ for model_class in self.all_model_classes:
466
+ if model_class.__name__ == "FunnelBaseModel":
467
+ continue
468
+ model = model_class(config)
469
+ model.to(torch_device)
470
+ model.train()
471
+ inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
472
+ loss = model(**inputs).loss
473
+ loss.backward()
474
+
475
+ # overwrite from test_modeling_common
476
+ def _mock_init_weights(self, module):
477
+ if hasattr(module, "weight") and module.weight is not None:
478
+ module.weight.data.fill_(3)
479
+ if hasattr(module, "bias") and module.bias is not None:
480
+ module.bias.data.fill_(3)
481
+
482
+ for param in ["r_w_bias", "r_r_bias", "r_kernel", "r_s_bias", "seg_embed"]:
483
+ if hasattr(module, param) and getattr(module, param) is not None:
484
+ weight = getattr(module, param)
485
+ weight.data.fill_(3)
486
+
487
+
488
+ @require_torch
489
+ @require_sentencepiece
490
+ @require_tokenizers
491
+ class FunnelModelIntegrationTest(unittest.TestCase):
492
+ def test_inference_tiny_model(self):
493
+ batch_size = 13
494
+ sequence_length = 7
495
+ input_ids = torch.arange(0, batch_size * sequence_length).long().reshape(batch_size, sequence_length)
496
+ lengths = [0, 1, 2, 3, 4, 5, 6, 4, 1, 3, 5, 0, 1]
497
+ token_type_ids = torch.tensor([[2] + [0] * a + [1] * (sequence_length - a - 1) for a in lengths])
498
+
499
+ model = FunnelModel.from_pretrained("sgugger/funnel-random-tiny")
500
+ output = model(input_ids, token_type_ids=token_type_ids)[0].abs()
501
+
502
+ expected_output_sum = torch.tensor(2344.8352)
503
+ expected_output_mean = torch.tensor(0.8052)
504
+ torch.testing.assert_close(output.sum(), expected_output_sum, rtol=1e-4, atol=1e-4)
505
+ torch.testing.assert_close(output.mean(), expected_output_mean, rtol=1e-4, atol=1e-4)
506
+
507
+ attention_mask = torch.tensor([[1] * 7, [1] * 4 + [0] * 3] * 6 + [[0, 1, 1, 0, 0, 1, 1]])
508
+ output = model(input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids)[0].abs()
509
+
510
+ expected_output_sum = torch.tensor(2343.8425)
511
+ expected_output_mean = torch.tensor(0.8049)
512
+ torch.testing.assert_close(output.sum(), expected_output_sum, rtol=1e-4, atol=1e-4)
513
+ torch.testing.assert_close(output.mean(), expected_output_mean, rtol=1e-4, atol=1e-4)
514
+
515
+ @slow
516
+ def test_inference_model(self):
517
+ tokenizer = FunnelTokenizer.from_pretrained("huggingface/funnel-small")
518
+ model = FunnelModel.from_pretrained("huggingface/funnel-small")
519
+ inputs = tokenizer("Hello! I am the Funnel Transformer model.", return_tensors="pt")
520
+ output = model(**inputs)[0]
521
+
522
+ expected_output_sum = torch.tensor(235.7246)
523
+ expected_output_mean = torch.tensor(0.0256)
524
+ torch.testing.assert_close(output.sum(), expected_output_sum, rtol=1e-4, atol=1e-4)
525
+ torch.testing.assert_close(output.mean(), expected_output_mean, rtol=1e-4, atol=1e-4)
tasks/tasksmith-441eeab80047/tests/source/tests/models/funnel/test_modeling_tf_funnel.py ADDED
@@ -0,0 +1,415 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 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
+
17
+ from __future__ import annotations
18
+
19
+ import unittest
20
+
21
+ from transformers import FunnelConfig, is_tf_available
22
+ from transformers.testing_utils import require_tf
23
+
24
+ from ...test_configuration_common import ConfigTester
25
+ from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
26
+ from ...test_pipeline_mixin import PipelineTesterMixin
27
+
28
+
29
+ if is_tf_available():
30
+ import tensorflow as tf
31
+
32
+ from transformers import (
33
+ TFFunnelBaseModel,
34
+ TFFunnelForMaskedLM,
35
+ TFFunnelForMultipleChoice,
36
+ TFFunnelForPreTraining,
37
+ TFFunnelForQuestionAnswering,
38
+ TFFunnelForSequenceClassification,
39
+ TFFunnelForTokenClassification,
40
+ TFFunnelModel,
41
+ )
42
+
43
+
44
+ class TFFunnelModelTester:
45
+ """You can also import this e.g, from .test_modeling_funnel import FunnelModelTester"""
46
+
47
+ def __init__(
48
+ self,
49
+ parent,
50
+ batch_size=13,
51
+ seq_length=7,
52
+ is_training=True,
53
+ use_input_mask=True,
54
+ use_token_type_ids=True,
55
+ use_labels=True,
56
+ vocab_size=99,
57
+ block_sizes=[1, 1, 2],
58
+ num_decoder_layers=1,
59
+ d_model=32,
60
+ n_head=4,
61
+ d_head=8,
62
+ d_inner=37,
63
+ hidden_act="gelu_new",
64
+ hidden_dropout=0.1,
65
+ attention_dropout=0.1,
66
+ activation_dropout=0.0,
67
+ max_position_embeddings=512,
68
+ type_vocab_size=3,
69
+ initializer_std=0.02, # Set to a smaller value, so we can keep the small error threshold (1e-5) in the test
70
+ num_labels=3,
71
+ num_choices=4,
72
+ scope=None,
73
+ base=False,
74
+ ):
75
+ self.parent = parent
76
+ self.batch_size = batch_size
77
+ self.seq_length = seq_length
78
+ self.is_training = is_training
79
+ self.use_input_mask = use_input_mask
80
+ self.use_token_type_ids = use_token_type_ids
81
+ self.use_labels = use_labels
82
+ self.vocab_size = vocab_size
83
+ self.block_sizes = block_sizes
84
+ self.num_decoder_layers = num_decoder_layers
85
+ self.d_model = d_model
86
+ self.n_head = n_head
87
+ self.d_head = d_head
88
+ self.d_inner = d_inner
89
+ self.hidden_act = hidden_act
90
+ self.hidden_dropout = hidden_dropout
91
+ self.attention_dropout = attention_dropout
92
+ self.activation_dropout = activation_dropout
93
+ self.max_position_embeddings = max_position_embeddings
94
+ self.type_vocab_size = type_vocab_size
95
+ self.type_sequence_label_size = 2
96
+ self.num_labels = num_labels
97
+ self.num_choices = num_choices
98
+ self.scope = scope
99
+ self.initializer_std = initializer_std
100
+
101
+ # Used in the tests to check the size of the first attention layer
102
+ self.num_attention_heads = n_head
103
+ # Used in the tests to check the size of the first hidden state
104
+ self.hidden_size = self.d_model
105
+ # Used in the tests to check the number of output hidden states/attentions
106
+ self.num_hidden_layers = sum(self.block_sizes) + (0 if base else self.num_decoder_layers)
107
+ # FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with
108
+ # the last hidden state of the first block (which is the first hidden state of the decoder).
109
+ if not base:
110
+ self.expected_num_hidden_layers = self.num_hidden_layers + 2
111
+
112
+ def prepare_config_and_inputs(self):
113
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
114
+
115
+ input_mask = None
116
+ if self.use_input_mask:
117
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
118
+
119
+ token_type_ids = None
120
+ if self.use_token_type_ids:
121
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
122
+
123
+ sequence_labels = None
124
+ token_labels = None
125
+ choice_labels = None
126
+ if self.use_labels:
127
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
128
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
129
+ choice_labels = ids_tensor([self.batch_size], self.num_choices)
130
+
131
+ config = FunnelConfig(
132
+ vocab_size=self.vocab_size,
133
+ block_sizes=self.block_sizes,
134
+ num_decoder_layers=self.num_decoder_layers,
135
+ d_model=self.d_model,
136
+ n_head=self.n_head,
137
+ d_head=self.d_head,
138
+ d_inner=self.d_inner,
139
+ hidden_act=self.hidden_act,
140
+ hidden_dropout=self.hidden_dropout,
141
+ attention_dropout=self.attention_dropout,
142
+ activation_dropout=self.activation_dropout,
143
+ max_position_embeddings=self.max_position_embeddings,
144
+ type_vocab_size=self.type_vocab_size,
145
+ initializer_std=self.initializer_std,
146
+ )
147
+
148
+ return (
149
+ config,
150
+ input_ids,
151
+ token_type_ids,
152
+ input_mask,
153
+ sequence_labels,
154
+ token_labels,
155
+ choice_labels,
156
+ )
157
+
158
+ def create_and_check_model(
159
+ self,
160
+ config,
161
+ input_ids,
162
+ token_type_ids,
163
+ input_mask,
164
+ sequence_labels,
165
+ token_labels,
166
+ choice_labels,
167
+ ):
168
+ model = TFFunnelModel(config=config)
169
+ inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
170
+ result = model(inputs)
171
+
172
+ inputs = [input_ids, input_mask]
173
+ result = model(inputs)
174
+
175
+ result = model(input_ids)
176
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.d_model))
177
+
178
+ config.truncate_seq = False
179
+ model = TFFunnelModel(config=config)
180
+ result = model(input_ids)
181
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.d_model))
182
+
183
+ config.separate_cls = False
184
+ model = TFFunnelModel(config=config)
185
+ result = model(input_ids)
186
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.d_model))
187
+
188
+ def create_and_check_base_model(
189
+ self,
190
+ config,
191
+ input_ids,
192
+ token_type_ids,
193
+ input_mask,
194
+ sequence_labels,
195
+ token_labels,
196
+ choice_labels,
197
+ ):
198
+ model = TFFunnelBaseModel(config=config)
199
+ inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
200
+ result = model(inputs)
201
+
202
+ inputs = [input_ids, input_mask]
203
+ result = model(inputs)
204
+
205
+ result = model(input_ids)
206
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, 2, self.d_model))
207
+
208
+ config.truncate_seq = False
209
+ model = TFFunnelBaseModel(config=config)
210
+ result = model(input_ids)
211
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, 3, self.d_model))
212
+
213
+ config.separate_cls = False
214
+ model = TFFunnelBaseModel(config=config)
215
+ result = model(input_ids)
216
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, 2, self.d_model))
217
+
218
+ def create_and_check_for_pretraining(
219
+ self,
220
+ config,
221
+ input_ids,
222
+ token_type_ids,
223
+ input_mask,
224
+ sequence_labels,
225
+ token_labels,
226
+ choice_labels,
227
+ ):
228
+ model = TFFunnelForPreTraining(config=config)
229
+ inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
230
+ result = model(inputs)
231
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length))
232
+
233
+ def create_and_check_for_masked_lm(
234
+ self,
235
+ config,
236
+ input_ids,
237
+ token_type_ids,
238
+ input_mask,
239
+ sequence_labels,
240
+ token_labels,
241
+ choice_labels,
242
+ ):
243
+ model = TFFunnelForMaskedLM(config=config)
244
+ inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
245
+ result = model(inputs)
246
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
247
+
248
+ def create_and_check_for_sequence_classification(
249
+ self,
250
+ config,
251
+ input_ids,
252
+ token_type_ids,
253
+ input_mask,
254
+ sequence_labels,
255
+ token_labels,
256
+ choice_labels,
257
+ ):
258
+ config.num_labels = self.num_labels
259
+ model = TFFunnelForSequenceClassification(config=config)
260
+ inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
261
+ result = model(inputs)
262
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
263
+
264
+ def create_and_check_for_multiple_choice(
265
+ self,
266
+ config,
267
+ input_ids,
268
+ token_type_ids,
269
+ input_mask,
270
+ sequence_labels,
271
+ token_labels,
272
+ choice_labels,
273
+ ):
274
+ config.num_choices = self.num_choices
275
+ model = TFFunnelForMultipleChoice(config=config)
276
+ multiple_choice_inputs_ids = tf.tile(tf.expand_dims(input_ids, 1), (1, self.num_choices, 1))
277
+ multiple_choice_input_mask = tf.tile(tf.expand_dims(input_mask, 1), (1, self.num_choices, 1))
278
+ multiple_choice_token_type_ids = tf.tile(tf.expand_dims(token_type_ids, 1), (1, self.num_choices, 1))
279
+ inputs = {
280
+ "input_ids": multiple_choice_inputs_ids,
281
+ "attention_mask": multiple_choice_input_mask,
282
+ "token_type_ids": multiple_choice_token_type_ids,
283
+ }
284
+ result = model(inputs)
285
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
286
+
287
+ def create_and_check_for_token_classification(
288
+ self,
289
+ config,
290
+ input_ids,
291
+ token_type_ids,
292
+ input_mask,
293
+ sequence_labels,
294
+ token_labels,
295
+ choice_labels,
296
+ ):
297
+ config.num_labels = self.num_labels
298
+ model = TFFunnelForTokenClassification(config=config)
299
+ inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
300
+ result = model(inputs)
301
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
302
+
303
+ def create_and_check_for_question_answering(
304
+ self,
305
+ config,
306
+ input_ids,
307
+ token_type_ids,
308
+ input_mask,
309
+ sequence_labels,
310
+ token_labels,
311
+ choice_labels,
312
+ ):
313
+ model = TFFunnelForQuestionAnswering(config=config)
314
+ inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
315
+ result = model(inputs)
316
+ self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
317
+ self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
318
+
319
+ def prepare_config_and_inputs_for_common(self):
320
+ config_and_inputs = self.prepare_config_and_inputs()
321
+ (
322
+ config,
323
+ input_ids,
324
+ token_type_ids,
325
+ input_mask,
326
+ sequence_labels,
327
+ token_labels,
328
+ choice_labels,
329
+ ) = config_and_inputs
330
+ inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
331
+ return config, inputs_dict
332
+
333
+
334
+ @require_tf
335
+ class TFFunnelModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
336
+ all_model_classes = (
337
+ (
338
+ TFFunnelModel,
339
+ TFFunnelForMaskedLM,
340
+ TFFunnelForPreTraining,
341
+ TFFunnelForQuestionAnswering,
342
+ TFFunnelForTokenClassification,
343
+ )
344
+ if is_tf_available()
345
+ else ()
346
+ )
347
+ pipeline_model_mapping = (
348
+ {
349
+ "feature-extraction": (TFFunnelBaseModel, TFFunnelModel),
350
+ "fill-mask": TFFunnelForMaskedLM,
351
+ "question-answering": TFFunnelForQuestionAnswering,
352
+ "text-classification": TFFunnelForSequenceClassification,
353
+ "token-classification": TFFunnelForTokenClassification,
354
+ "zero-shot": TFFunnelForSequenceClassification,
355
+ }
356
+ if is_tf_available()
357
+ else {}
358
+ )
359
+ test_head_masking = False
360
+ test_onnx = False
361
+
362
+ def setUp(self):
363
+ self.model_tester = TFFunnelModelTester(self)
364
+ self.config_tester = ConfigTester(self, config_class=FunnelConfig)
365
+
366
+ def test_config(self):
367
+ self.config_tester.run_common_tests()
368
+
369
+ def test_model(self):
370
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
371
+ self.model_tester.create_and_check_model(*config_and_inputs)
372
+
373
+ def test_for_pretraining(self):
374
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
375
+ self.model_tester.create_and_check_for_pretraining(*config_and_inputs)
376
+
377
+ def test_for_masked_lm(self):
378
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
379
+ self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
380
+
381
+ def test_for_token_classification(self):
382
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
383
+ self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
384
+
385
+ def test_for_question_answering(self):
386
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
387
+ self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
388
+
389
+
390
+ @require_tf
391
+ class TFFunnelBaseModelTest(TFModelTesterMixin, unittest.TestCase):
392
+ all_model_classes = (
393
+ (TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else ()
394
+ )
395
+ test_head_masking = False
396
+ test_onnx = False
397
+
398
+ def setUp(self):
399
+ self.model_tester = TFFunnelModelTester(self, base=True)
400
+ self.config_tester = ConfigTester(self, config_class=FunnelConfig)
401
+
402
+ def test_config(self):
403
+ self.config_tester.run_common_tests()
404
+
405
+ def test_base_model(self):
406
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
407
+ self.model_tester.create_and_check_base_model(*config_and_inputs)
408
+
409
+ def test_for_sequence_classification(self):
410
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
411
+ self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs)
412
+
413
+ def test_for_multiple_choice(self):
414
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
415
+ self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
tasks/tasksmith-441eeab80047/tests/source/tests/models/funnel/test_tokenization_funnel.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 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
+
17
+ import os
18
+ import unittest
19
+
20
+ from transformers import FunnelTokenizer, FunnelTokenizerFast
21
+ from transformers.models.funnel.tokenization_funnel import VOCAB_FILES_NAMES
22
+ from transformers.testing_utils import require_tokenizers
23
+
24
+ from ...test_tokenization_common import TokenizerTesterMixin
25
+
26
+
27
+ @require_tokenizers
28
+ class FunnelTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
29
+ from_pretrained_id = "funnel-transformer/small"
30
+ tokenizer_class = FunnelTokenizer
31
+ rust_tokenizer_class = FunnelTokenizerFast
32
+ test_rust_tokenizer = True
33
+ space_between_special_tokens = True
34
+
35
+ def setUp(self):
36
+ super().setUp()
37
+
38
+ vocab_tokens = [
39
+ "<unk>",
40
+ "<cls>",
41
+ "<sep>",
42
+ "want",
43
+ "##want",
44
+ "##ed",
45
+ "wa",
46
+ "un",
47
+ "runn",
48
+ "##ing",
49
+ ",",
50
+ "low",
51
+ "lowest",
52
+ ]
53
+ self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"])
54
+ with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer:
55
+ vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))
56
+
57
+ def get_tokenizer(self, **kwargs):
58
+ return FunnelTokenizer.from_pretrained(self.tmpdirname, **kwargs)
59
+
60
+ def get_rust_tokenizer(self, **kwargs):
61
+ return FunnelTokenizerFast.from_pretrained(self.tmpdirname, **kwargs)
62
+
63
+ def get_input_output_texts(self, tokenizer):
64
+ input_text = "UNwant\u00e9d,running"
65
+ output_text = "unwanted, running"
66
+ return input_text, output_text
67
+
68
+ def test_full_tokenizer(self):
69
+ tokenizer = self.tokenizer_class(self.vocab_file)
70
+
71
+ tokens = tokenizer.tokenize("UNwant\u00e9d,running")
72
+ self.assertListEqual(tokens, ["un", "##want", "##ed", ",", "runn", "##ing"])
73
+ self.assertListEqual(tokenizer.convert_tokens_to_ids(tokens), [7, 4, 5, 10, 8, 9])
74
+
75
+ def test_token_type_ids(self):
76
+ tokenizers = self.get_tokenizers(do_lower_case=False)
77
+ for tokenizer in tokenizers:
78
+ inputs = tokenizer("UNwant\u00e9d,running")
79
+ sentence_len = len(inputs["input_ids"]) - 1
80
+ self.assertListEqual(inputs["token_type_ids"], [2] + [0] * sentence_len)
81
+
82
+ inputs = tokenizer("UNwant\u00e9d,running", "UNwant\u00e9d,running")
83
+ self.assertListEqual(inputs["token_type_ids"], [2] + [0] * sentence_len + [1] * sentence_len)
tasks/tasksmith-441eeab80047/tests/source/tests/models/fuyu/__init__.py ADDED
File without changes
tasks/tasksmith-441eeab80047/tests/source/tests/models/fuyu/test_image_processing_fuyu.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+
3
+ import numpy as np
4
+
5
+ from transformers import is_torch_available, is_vision_available
6
+ from transformers.testing_utils import (
7
+ require_torch,
8
+ require_torchvision,
9
+ require_vision,
10
+ )
11
+
12
+
13
+ if is_torch_available() and is_vision_available():
14
+ import torch
15
+
16
+ from transformers import FuyuImageProcessor
17
+
18
+ if is_vision_available():
19
+ from PIL import Image
20
+
21
+
22
+ @require_torch
23
+ @require_vision
24
+ @require_torchvision
25
+ class TestFuyuImageProcessor(unittest.TestCase):
26
+ def setUp(self):
27
+ self.size = {"height": 160, "width": 320}
28
+ self.processor = FuyuImageProcessor(size=self.size, padding_value=1.0)
29
+ self.batch_size = 3
30
+ self.channels = 3
31
+ self.height = 300
32
+ self.width = 300
33
+
34
+ self.image_input = torch.rand(self.batch_size, self.channels, self.height, self.width)
35
+
36
+ self.image_patch_dim_h = 30
37
+ self.image_patch_dim_w = 30
38
+ self.sample_image = np.zeros((450, 210, 3), dtype=np.uint8)
39
+ self.sample_image_pil = Image.fromarray(self.sample_image)
40
+
41
+ def test_patches(self):
42
+ expected_num_patches = self.processor.get_num_patches(image_height=self.height, image_width=self.width)
43
+
44
+ patches_final = self.processor.patchify_image(image=self.image_input)
45
+ assert (
46
+ patches_final.shape[1] == expected_num_patches
47
+ ), f"Expected {expected_num_patches} patches, got {patches_final.shape[1]}."
48
+
49
+ def test_scale_to_target_aspect_ratio(self):
50
+ # (h:450, w:210) fitting (160, 320) -> (160, 210*160/450)
51
+ scaled_image = self.processor.resize(self.sample_image, size=self.size)
52
+ self.assertEqual(scaled_image.shape[0], 160)
53
+ self.assertEqual(scaled_image.shape[1], 74)
54
+
55
+ def test_apply_transformation_numpy(self):
56
+ transformed_image = self.processor.preprocess(self.sample_image).images[0][0]
57
+ self.assertEqual(transformed_image.shape[1], 160)
58
+ self.assertEqual(transformed_image.shape[2], 320)
59
+
60
+ def test_apply_transformation_pil(self):
61
+ transformed_image = self.processor.preprocess(self.sample_image_pil).images[0][0]
62
+ self.assertEqual(transformed_image.shape[1], 160)
63
+ self.assertEqual(transformed_image.shape[2], 320)
tasks/tasksmith-441eeab80047/tests/source/tests/models/fuyu/test_modeling_fuyu.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Fuyu model."""
16
+
17
+ import io
18
+ import unittest
19
+
20
+ import pytest
21
+ import requests
22
+ from parameterized import parameterized
23
+
24
+ from transformers import FuyuConfig, is_torch_available, is_vision_available
25
+ from transformers.testing_utils import require_torch, require_torch_accelerator, slow, torch_device
26
+ from transformers.utils import cached_property
27
+
28
+ from ...generation.test_utils import GenerationTesterMixin
29
+ from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
30
+ from ...test_pipeline_mixin import PipelineTesterMixin
31
+
32
+
33
+ if is_vision_available():
34
+ from PIL import Image
35
+
36
+
37
+ if is_torch_available() and is_vision_available():
38
+ from transformers import FuyuProcessor
39
+
40
+
41
+ if is_torch_available():
42
+ import torch
43
+
44
+ from transformers import FuyuForCausalLM
45
+
46
+
47
+ class FuyuModelTester:
48
+ def __init__(
49
+ self,
50
+ parent,
51
+ batch_size=13,
52
+ seq_length=7,
53
+ image_size=30,
54
+ patch_size=15,
55
+ num_channels=3,
56
+ is_training=True,
57
+ use_input_mask=True,
58
+ use_labels=True,
59
+ vocab_size=99,
60
+ hidden_size=32,
61
+ num_hidden_layers=2,
62
+ num_attention_heads=4,
63
+ intermediate_size=37,
64
+ hidden_act="gelu",
65
+ hidden_dropout_prob=0.1,
66
+ attention_probs_dropout_prob=0.1,
67
+ max_position_embeddings=512,
68
+ type_vocab_size=16,
69
+ type_sequence_label_size=2,
70
+ initializer_range=0.02,
71
+ num_labels=3,
72
+ num_choices=4,
73
+ pad_token_id=0,
74
+ scope=None,
75
+ ):
76
+ self.parent = parent
77
+ self.batch_size = batch_size
78
+ self.seq_length = seq_length
79
+ self.image_size = image_size
80
+ self.patch_size = patch_size
81
+ self.num_channels = num_channels
82
+ self.is_training = is_training
83
+ self.use_input_mask = use_input_mask
84
+ self.use_labels = use_labels
85
+ self.vocab_size = vocab_size
86
+ self.hidden_size = hidden_size
87
+ self.num_hidden_layers = num_hidden_layers
88
+ self.num_attention_heads = num_attention_heads
89
+ self.intermediate_size = intermediate_size
90
+ self.hidden_act = hidden_act
91
+ self.hidden_dropout_prob = hidden_dropout_prob
92
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
93
+ self.max_position_embeddings = max_position_embeddings
94
+ self.type_vocab_size = type_vocab_size
95
+ self.type_sequence_label_size = type_sequence_label_size
96
+ self.initializer_range = initializer_range
97
+ self.num_labels = num_labels
98
+ self.num_choices = num_choices
99
+ self.pad_token_id = pad_token_id
100
+ self.scope = scope
101
+
102
+ def prepare_config_and_inputs(self):
103
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
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
+ sequence_labels = None
110
+ token_labels = None
111
+ if self.use_labels:
112
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
113
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
114
+
115
+ config = self.get_config()
116
+
117
+ return config, input_ids, input_mask, sequence_labels, token_labels
118
+
119
+ def get_config(self):
120
+ return FuyuConfig(
121
+ vocab_size=self.vocab_size,
122
+ hidden_size=self.hidden_size,
123
+ num_hidden_layers=self.num_hidden_layers,
124
+ num_attention_heads=self.num_attention_heads,
125
+ intermediate_size=self.intermediate_size,
126
+ hidden_act=self.hidden_act,
127
+ hidden_dropout_prob=self.hidden_dropout_prob,
128
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
129
+ max_position_embeddings=self.max_position_embeddings,
130
+ type_vocab_size=self.type_vocab_size,
131
+ is_decoder=False,
132
+ initializer_range=self.initializer_range,
133
+ pad_token_id=self.pad_token_id,
134
+ )
135
+
136
+ def create_and_check_model(
137
+ self,
138
+ config,
139
+ input_ids,
140
+ input_mask,
141
+ sequence_labels,
142
+ token_labels,
143
+ ):
144
+ model = FuyuForCausalLM(config=config)
145
+ model.to(torch_device)
146
+ model.eval()
147
+ result = model(input_ids, attention_mask=input_mask)
148
+ result = model(input_ids)
149
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
150
+
151
+ def create_and_check_model_as_decoder(
152
+ self,
153
+ config,
154
+ input_ids,
155
+ input_mask,
156
+ sequence_labels,
157
+ token_labels,
158
+ encoder_hidden_states,
159
+ encoder_attention_mask,
160
+ ):
161
+ config.add_cross_attention = True
162
+ model = FuyuForCausalLM(config)
163
+ model.to(torch_device)
164
+ model.eval()
165
+ result = model(
166
+ input_ids,
167
+ attention_mask=input_mask,
168
+ encoder_hidden_states=encoder_hidden_states,
169
+ encoder_attention_mask=encoder_attention_mask,
170
+ )
171
+ result = model(
172
+ input_ids,
173
+ attention_mask=input_mask,
174
+ encoder_hidden_states=encoder_hidden_states,
175
+ )
176
+ result = model(input_ids, attention_mask=input_mask)
177
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
178
+
179
+ def create_and_check_for_causal_lm(
180
+ self,
181
+ config,
182
+ input_ids,
183
+ input_mask,
184
+ sequence_labels,
185
+ token_labels,
186
+ encoder_hidden_states,
187
+ encoder_attention_mask,
188
+ ):
189
+ model = FuyuForCausalLM(config=config)
190
+ model.to(torch_device)
191
+ model.eval()
192
+ result = model(input_ids, attention_mask=input_mask, labels=token_labels)
193
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
194
+
195
+ def create_and_check_decoder_model_past_large_inputs(
196
+ self,
197
+ config,
198
+ input_ids,
199
+ input_mask,
200
+ sequence_labels,
201
+ token_labels,
202
+ encoder_hidden_states,
203
+ encoder_attention_mask,
204
+ ):
205
+ config.is_decoder = True
206
+ config.add_cross_attention = True
207
+ model = FuyuForCausalLM(config=config)
208
+ model.to(torch_device)
209
+ model.eval()
210
+
211
+ # first forward pass
212
+ outputs = model(
213
+ input_ids,
214
+ attention_mask=input_mask,
215
+ encoder_hidden_states=encoder_hidden_states,
216
+ encoder_attention_mask=encoder_attention_mask,
217
+ use_cache=True,
218
+ )
219
+ past_key_values = outputs.past_key_values
220
+
221
+ # create hypothetical multiple next token and extent to next_input_ids
222
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
223
+ next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
224
+
225
+ # append to next input_ids and
226
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
227
+ next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
228
+
229
+ output_from_no_past = model(
230
+ next_input_ids,
231
+ attention_mask=next_attention_mask,
232
+ encoder_hidden_states=encoder_hidden_states,
233
+ encoder_attention_mask=encoder_attention_mask,
234
+ output_hidden_states=True,
235
+ )["hidden_states"][0]
236
+ output_from_past = model(
237
+ next_tokens,
238
+ attention_mask=next_attention_mask,
239
+ encoder_hidden_states=encoder_hidden_states,
240
+ encoder_attention_mask=encoder_attention_mask,
241
+ past_key_values=past_key_values,
242
+ output_hidden_states=True,
243
+ )["hidden_states"][0]
244
+
245
+ # select random slice
246
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
247
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
248
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
249
+
250
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
251
+
252
+ # test that outputs are equal for slice
253
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
254
+
255
+ def prepare_config_and_inputs_for_common(self):
256
+ config_and_inputs = self.prepare_config_and_inputs()
257
+ (
258
+ config,
259
+ input_ids,
260
+ input_mask,
261
+ sequence_labels,
262
+ token_labels,
263
+ ) = config_and_inputs
264
+ inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
265
+ return config, inputs_dict
266
+
267
+
268
+ @require_torch
269
+ class FuyuModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
270
+ all_model_classes = (FuyuForCausalLM,) if is_torch_available() else ()
271
+ pipeline_model_mapping = (
272
+ {"text-generation": FuyuForCausalLM, "image-text-to-text": FuyuForCausalLM} if is_torch_available() else {}
273
+ )
274
+
275
+ test_head_masking = False
276
+ test_pruning = False
277
+ test_cpu_offload = False
278
+ test_disk_offload = False
279
+ test_model_parallel = False
280
+
281
+ def setUp(self):
282
+ self.model_tester = FuyuModelTester(self)
283
+
284
+ @unittest.skip(
285
+ reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
286
+ )
287
+ def test_training_gradient_checkpointing(self):
288
+ pass
289
+
290
+ @unittest.skip(
291
+ reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
292
+ )
293
+ def test_training_gradient_checkpointing_use_reentrant(self):
294
+ pass
295
+
296
+ @unittest.skip(
297
+ reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
298
+ )
299
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
300
+ pass
301
+
302
+ @pytest.mark.generate
303
+ @parameterized.expand([("random",), ("same",)])
304
+ @unittest.skip("Fuyu doesn't support assisted generation due to the need to crop/extend image patches indices")
305
+ def test_assisted_decoding_matches_greedy_search(self):
306
+ pass
307
+
308
+ @unittest.skip("Fuyu doesn't support assisted generation due to the need to crop/extend image patches indices")
309
+ def test_assisted_decoding_sample(self):
310
+ pass
311
+
312
+ # TODO: Fix me (once this model gets more usage)
313
+ @unittest.skip(reason="Does not work on the tiny model.")
314
+ def test_disk_offload_bin(self):
315
+ super().test_disk_offload()
316
+
317
+ # TODO: Fix me (once this model gets more usage)
318
+ @unittest.skip(reason="Does not work on the tiny model.")
319
+ def test_disk_offload_safetensors(self):
320
+ super().test_disk_offload()
321
+
322
+ # TODO: Fix me (once this model gets more usage)
323
+ @unittest.skip(reason="Does not work on the tiny model.")
324
+ def test_model_parallelism(self):
325
+ super().test_model_parallelism()
326
+
327
+ @unittest.skip(reason="Fuyu `prepare_inputs_for_generation` function doesn't have cache position.")
328
+ def test_generate_continue_from_inputs_embeds():
329
+ pass
330
+
331
+
332
+ @slow
333
+ @require_torch_accelerator
334
+ class FuyuModelIntegrationTest(unittest.TestCase):
335
+ @cached_property
336
+ def default_processor(self):
337
+ return FuyuProcessor.from_pretrained("adept/fuyu-8b")
338
+
339
+ @cached_property
340
+ def default_model(self):
341
+ return FuyuForCausalLM.from_pretrained("adept/fuyu-8b")
342
+
343
+ def test_greedy_generation(self):
344
+ processor = self.default_processor
345
+ model = self.default_model
346
+
347
+ url = "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/bus.png"
348
+ image = Image.open(io.BytesIO(requests.get(url).content))
349
+
350
+ text_prompt_coco_captioning = "Generate a coco-style caption.\n"
351
+
352
+ inputs = processor(images=image, text=text_prompt_coco_captioning, return_tensors="pt")
353
+ generated_ids = model.generate(**inputs, max_new_tokens=10)
354
+
355
+ # take the last 8 tokens (in order to skip special \n\x04 characters) and decode them
356
+ generated_text = processor.batch_decode(generated_ids[:, -8:], skip_special_tokens=True)[0]
357
+ self.assertEqual(generated_text, "A blue bus parked on the side of a road.")
358
+
359
+
360
+ """
361
+ @slow
362
+ @require_torch_accelerator
363
+ def test_model_8b_chat_greedy_generation_bus_color(self):
364
+ EXPECTED_TEXT_COMPLETION = "The bus is blue.\n|ENDOFTEXT|"
365
+ text_prompt_bus_color = "What color is the bus?\n"
366
+ model_inputs_bus_color = self.processor(text=text_prompt_bus_color, images=self.bus_image_pil)
367
+
368
+ generated_tokens = self.model.generate(**model_inputs_bus_color, max_new_tokens=10)
369
+ text = self.processor.tokenizer.batch_decode(generated_tokens)
370
+ end_sequence = text[0].split("\x04")[1]
371
+ clean_sequence = (
372
+ end_sequence[: end_sequence.find("|ENDOFTEXT|") + len("|ENDOFTEXT|")]
373
+ if "|ENDOFTEXT|" in end_sequence
374
+ else end_sequence
375
+ )
376
+ self.assertEqual(EXPECTED_TEXT_COMPLETION, clean_sequence)
377
+
378
+ @slow
379
+ @require_torch_accelerator
380
+ def test_model_8b_chat_greedy_generation_chart_vqa(self):
381
+ EXPECTED_TEXT_TOKENS = ["The","life expectancy","at","birth","of male","s in","","20","18","is","","80",".","7",".","\n","|ENDOFTEXT|",] # fmt: skip
382
+ expected_text_completion = " ".join(EXPECTED_TEXT_TOKENS) # TODO make sure the end string matches
383
+
384
+ text_prompt_chart_vqa = "What is the highest life expectancy at birth of male?\n"
385
+
386
+ chart_image_url = (
387
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/chart.png"
388
+ )
389
+ chart_image_pil = Image.open(io.BytesIO(requests.get(chart_image_url).content))
390
+
391
+ model_inputs_chart_vqa = self.processor(text=text_prompt_chart_vqa, images=chart_image_pil)
392
+ generated_tokens = self.model.generate(**model_inputs_chart_vqa, max_new_tokens=10)
393
+ text = self.processor.tokenizer.batch_decode(generated_tokens)
394
+ end_sequence = text[0].split("\x04")[1]
395
+ clean_sequence = (
396
+ end_sequence[: end_sequence.find("|ENDOFTEXT|") + len("|ENDOFTEXT|")]
397
+ if "|ENDOFTEXT|" in end_sequence
398
+ else end_sequence
399
+ )
400
+ self.assertEqual(expected_text_completion, clean_sequence)
401
+
402
+ @slow
403
+ @require_torch_accelerator
404
+ def test_model_8b_chat_greedy_generation_bounding_box(self):
405
+ EXPECTED_TEXT_COMPLETION = "\x00194213202244\x01|ENDOFTEXT|"
406
+ text_prompt_bbox = "When presented with a box, perform OCR to extract text contained within it. If provided with text, generate the corresponding bounding box.\\nWilliams" # noqa: E231
407
+
408
+ bbox_image_url = "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/bbox_sample_image.png"
409
+ bbox_image_pil = Image.open(io.BytesIO(requests.get(bbox_image_url).content))
410
+
411
+ model_inputs_bbox = self.processor(text=text_prompt_bbox, images=bbox_image_pil)
412
+ generated_tokens = self.model.generate(**model_inputs_bbox, max_new_tokens=10)
413
+ text = self.processor.tokenizer.batch_decode(generated_tokens)
414
+ end_sequence = text[0].split("\x04")[1]
415
+ clean_sequence = (
416
+ end_sequence[: end_sequence.find("|ENDOFTEXT|") + len("|ENDOFTEXT|")]
417
+ if "|ENDOFTEXT|" in end_sequence
418
+ else end_sequence
419
+ )
420
+ self.assertEqual(EXPECTED_TEXT_COMPLETION, clean_sequence)
421
+ """
tasks/tasksmith-441eeab80047/tests/source/tests/models/fuyu/test_processor_fuyu.py ADDED
@@ -0,0 +1,403 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ import tempfile
3
+ import unittest
4
+
5
+ import requests
6
+
7
+ from transformers import (
8
+ AutoProcessor,
9
+ AutoTokenizer,
10
+ FuyuImageProcessor,
11
+ FuyuProcessor,
12
+ is_torch_available,
13
+ is_vision_available,
14
+ )
15
+ from transformers.testing_utils import require_torch, require_vision
16
+
17
+ from ...test_processing_common import ProcessorTesterMixin
18
+
19
+
20
+ if is_vision_available():
21
+ from PIL import Image
22
+
23
+
24
+ if is_torch_available():
25
+ import torch
26
+
27
+ from transformers.models.fuyu.processing_fuyu import construct_full_unpacked_stream, full_unpacked_stream_to_tensor
28
+
29
+
30
+ @require_torch
31
+ @require_vision
32
+ class FuyuProcessingTest(ProcessorTesterMixin, unittest.TestCase):
33
+ processor_class = FuyuProcessor
34
+
35
+ def setUp(self):
36
+ self.tmpdirname = tempfile.mkdtemp()
37
+
38
+ image_processor = FuyuImageProcessor()
39
+ tokenizer = AutoTokenizer.from_pretrained("adept/fuyu-8b")
40
+
41
+ processor = FuyuProcessor(image_processor=image_processor, tokenizer=tokenizer)
42
+ processor.save_pretrained(self.tmpdirname)
43
+
44
+ self.text_prompt = "Generate a coco-style caption.\\n"
45
+ bus_image_url = "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/bus.png"
46
+ self.bus_image_pil = Image.open(io.BytesIO(requests.get(bus_image_url).content))
47
+
48
+ def get_processor(self):
49
+ image_processor = FuyuImageProcessor()
50
+ tokenizer = AutoTokenizer.from_pretrained("adept/fuyu-8b")
51
+ processor = FuyuProcessor(image_processor, tokenizer, **self.prepare_processor_dict())
52
+
53
+ return processor
54
+
55
+ def get_tokenizer(self, **kwargs):
56
+ return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).tokenizer
57
+
58
+ def get_image_processor(self, **kwargs):
59
+ return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).image_processor
60
+
61
+ def test_fuyu_processing(self):
62
+ """
63
+ Test to ensure that the standard processing on a gold example matches adept's code.
64
+ """
65
+ # fmt: off
66
+ EXPECTED_IMAGE_PATCH_INPUTS = torch.Tensor([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, -1, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, -1, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, -1, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, -1, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, -1, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, -1, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, -1, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, -1, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, -1, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, -1, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, -1, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, -1, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, -1, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,]]).to(torch.int64)
67
+ EXPECTED_PADDED_UNPACKED_TOKEN_INPUTS = torch.Tensor([[71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 1, 128340, 71374, 71389, 120412, 71377, 71835, 71374, 73615, 71375, 71399, 71435, 71122,]]).to(torch.int64)
68
+
69
+ one_image_bus_model_inputs = self.get_processor()(text=self.text_prompt, images=self.bus_image_pil)
70
+
71
+ # fmt: on
72
+ torch.testing.assert_close(one_image_bus_model_inputs["image_patches_indices"], EXPECTED_IMAGE_PATCH_INPUTS)
73
+ torch.testing.assert_close(one_image_bus_model_inputs["input_ids"], EXPECTED_PADDED_UNPACKED_TOKEN_INPUTS)
74
+
75
+ def test_fuyu_processing_no_image(self):
76
+ """
77
+ Test to check processor works with just text input
78
+ """
79
+ processor_outputs = self.get_processor()(text=self.text_prompt)
80
+ tokenizer_outputs = self.get_tokenizer()(self.text_prompt)
81
+ self.assertEqual(processor_outputs["input_ids"], tokenizer_outputs["input_ids"])
82
+
83
+ def test_fuyu_processing_no_text(self):
84
+ """
85
+ Test to check processor works with just image input
86
+ """
87
+ # fmt: off
88
+ EXPECTED_IMAGE_PATCH_INPUTS = torch.Tensor([
89
+ [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
90
+ 14, 15, 16, 17, 18, 19, 20, 21, -1, 22, 23, 24, 25, 26,
91
+ 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
92
+ 41, 42, 43, -1, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
93
+ 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, -1, 66,
94
+ 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
95
+ 81, 82, 83, 84, 85, 86, 87, -1, 88, 89, 90, 91, 92, 93,
96
+ 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107,
97
+ 108, 109, -1, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120,
98
+ 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, -1, 132, 133,
99
+ 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147,
100
+ 148, 149, 150, 151, 152, 153, -1, 154, 155, 156, 157, 158, 159, 160,
101
+ 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174,
102
+ 175, -1, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187,
103
+ 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, -1, 198, 199, 200,
104
+ 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214,
105
+ 215, 216, 217, 218, 219, -1, 220, 221, 222, 223, 224, 225, 226, 227,
106
+ 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241,
107
+ -1, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
108
+ 255, 256, 257, 258, 259, 260, 261, 262, 263, -1, 264, 265, 266, 267,
109
+ 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281,
110
+ 282, 283, 284, 285, -1, 286, 287, 288, 289, 290, 291, 292, 293, 294,
111
+ 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, -1,
112
+ -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]
113
+ ]).to(torch.int64)
114
+ # fmt: on
115
+
116
+ processor_outputs = self.get_processor()(images=self.bus_image_pil)
117
+ self.assertTrue((processor_outputs["image_patches_indices"] == EXPECTED_IMAGE_PATCH_INPUTS).all())
118
+
119
+ def test_fuyu_processing_multiple_image_sample(self):
120
+ """
121
+ Test to check processor works with multiple image inputs for a single text input
122
+ """
123
+ # fmt: off
124
+ SINGLE_IMAGE_PATCH_INPUTS = torch.Tensor([[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, -1, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, -1, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, -1, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, -1, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, -1, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, -1, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, -1, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, -1, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, -1, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, -1, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, -1, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, -1, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, -1, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,]]).to(torch.int64)
125
+ SINGLE_PADDED_UNPACKED_TOKEN_INPUTS = torch.Tensor([[71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71011, 71019, 1, 128340, 71374, 71389, 120412, 71377, 71835, 71374, 73615, 71375, 71399, 71435, 71122,]]).to(torch.int64)
126
+
127
+ SINGLE_RESIZED_IMAGE_PATCH_INPUTS = torch.Tensor([[ 0, 1, 2, -1, 3, 4, 5, -1, 6, 7, 8, -1, 9, 10, 11, -1, 12, 13, 14, -1, 15, 16, 17, -1, 18, 19, 20, -1, 21, 22, 23, -1, 24, 25, 26, -1, 27, 28, 29, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1]])
128
+ SINGLE_RESIZED_PADDED_UNPACKED_TOKEN_INPUTS = torch.Tensor([[ 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71019, 71011, 71011, 71011, 71019, 1, 128340, 71374, 71389, 120412, 71377, 71835, 71374, 73615, 71375, 71399, 71435, 71122]])
129
+ # fmt: on
130
+
131
+ # Batch of two images - equally sized
132
+ images = [self.bus_image_pil, self.bus_image_pil]
133
+ processor_outputs = self.get_processor()(text=[self.text_prompt, self.text_prompt], images=images)
134
+
135
+ self.assertTrue(
136
+ (
137
+ processor_outputs["image_patches_indices"]
138
+ == torch.cat([SINGLE_IMAGE_PATCH_INPUTS, SINGLE_IMAGE_PATCH_INPUTS], dim=0)
139
+ ).all()
140
+ )
141
+ self.assertTrue(
142
+ (
143
+ processor_outputs["input_ids"]
144
+ == torch.cat([SINGLE_PADDED_UNPACKED_TOKEN_INPUTS, SINGLE_PADDED_UNPACKED_TOKEN_INPUTS], dim=0)
145
+ ).all()
146
+ )
147
+
148
+ # Processes single images with different sizes as expected
149
+ images = [self.bus_image_pil]
150
+ processor_outputs = self.get_processor()(text=self.text_prompt, images=images)
151
+ self.assertTrue((processor_outputs["image_patches_indices"] == SINGLE_IMAGE_PATCH_INPUTS).all())
152
+ self.assertTrue((processor_outputs["input_ids"] == SINGLE_PADDED_UNPACKED_TOKEN_INPUTS).all())
153
+
154
+ images = [self.bus_image_pil.resize((64, 300))]
155
+ processor_outputs = self.get_processor()(text=self.text_prompt, images=images)
156
+ self.assertTrue((processor_outputs["image_patches_indices"] == SINGLE_RESIZED_IMAGE_PATCH_INPUTS).all())
157
+ self.assertTrue((processor_outputs["input_ids"] == SINGLE_RESIZED_PADDED_UNPACKED_TOKEN_INPUTS).all())
158
+
159
+ # Batch of two images - different sizes. Left-pads the smaller image inputs
160
+ images = [self.bus_image_pil, self.bus_image_pil.resize((64, 300))]
161
+ processor_outputs = self.get_processor()(text=[self.text_prompt, self.text_prompt], images=images)
162
+
163
+ padding_len_patch = SINGLE_IMAGE_PATCH_INPUTS.shape[1] - SINGLE_RESIZED_IMAGE_PATCH_INPUTS.shape[1]
164
+ padded_single_resized_image_patch = torch.cat(
165
+ [torch.ones([1, padding_len_patch]) * -1, SINGLE_RESIZED_IMAGE_PATCH_INPUTS], dim=1
166
+ )
167
+ expected_image_patch_inputs = torch.cat([SINGLE_IMAGE_PATCH_INPUTS, padded_single_resized_image_patch], dim=0)
168
+
169
+ padding_len_token = (
170
+ SINGLE_PADDED_UNPACKED_TOKEN_INPUTS.shape[1] - SINGLE_RESIZED_PADDED_UNPACKED_TOKEN_INPUTS.shape[1]
171
+ )
172
+ padded_single_resized_padded_unpacked_token_inputs = torch.cat(
173
+ [torch.zeros([1, padding_len_token]), SINGLE_RESIZED_PADDED_UNPACKED_TOKEN_INPUTS], dim=1
174
+ )
175
+ expected_padded_unpacked_token_inputs = torch.cat(
176
+ [SINGLE_PADDED_UNPACKED_TOKEN_INPUTS, padded_single_resized_padded_unpacked_token_inputs], dim=0
177
+ )
178
+
179
+ self.assertTrue((processor_outputs["image_patches_indices"] == expected_image_patch_inputs).all())
180
+ self.assertTrue((processor_outputs["input_ids"] == expected_padded_unpacked_token_inputs).all())
181
+
182
+ # Rewrite as Fuyu supports tokenizer kwargs only when image is None.
183
+ @require_vision
184
+ @require_torch
185
+ def test_kwargs_overrides_default_tokenizer_kwargs(self):
186
+ if "image_processor" not in self.processor_class.attributes:
187
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
188
+ image_processor = self.get_component("image_processor")
189
+ tokenizer = self.get_component("tokenizer", max_length=117)
190
+
191
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
192
+ self.skip_processor_without_typed_kwargs(processor)
193
+ input_str = self.prepare_text_inputs()
194
+ # Fuyu uses tokenizer kwargs only when image is None.
195
+ image_input = None
196
+
197
+ inputs = processor(
198
+ text=input_str, images=image_input, return_tensors="pt", max_length=112, padding="max_length"
199
+ )
200
+ self.assertEqual(len(inputs["input_ids"][0]), 112)
201
+
202
+ @unittest.skip("Fuyu processor does not support image_processor kwargs")
203
+ def test_image_processor_defaults_preserved_by_image_kwargs(self):
204
+ pass
205
+
206
+ @unittest.skip("Fuyu processor does not support image_processor kwargs")
207
+ def test_kwargs_overrides_default_image_processor_kwargs(self):
208
+ pass
209
+
210
+ # Rewrite as Fuyu supports tokenizer kwargs only when image is None.
211
+ @require_vision
212
+ @require_torch
213
+ def test_tokenizer_defaults_preserved_by_kwargs(self):
214
+ if "image_processor" not in self.processor_class.attributes:
215
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
216
+ image_processor = self.get_component("image_processor")
217
+ tokenizer = self.get_component("tokenizer", max_length=117, padding="max_length")
218
+
219
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
220
+ self.skip_processor_without_typed_kwargs(processor)
221
+ input_str = self.prepare_text_inputs()
222
+ # Fuyu uses tokenizer kwargs only when image is None.
223
+ image_input = None
224
+
225
+ inputs = processor(text=input_str, images=image_input, return_tensors="pt")
226
+ self.assertEqual(len(inputs["input_ids"][0]), 117)
227
+
228
+ # Rewrite as Fuyu image processor does not return pixel values
229
+ @require_torch
230
+ @require_vision
231
+ def test_structured_kwargs_nested(self):
232
+ if "image_processor" not in self.processor_class.attributes:
233
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
234
+ image_processor = self.get_component("image_processor")
235
+ tokenizer = self.get_component("tokenizer")
236
+
237
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
238
+ self.skip_processor_without_typed_kwargs(processor)
239
+
240
+ input_str = self.prepare_text_inputs()
241
+ # Fuyu uses tokenizer kwargs only when image is None.
242
+ image_input = None
243
+
244
+ # Define the kwargs for each modality
245
+ all_kwargs = {
246
+ "common_kwargs": {"return_tensors": "pt"},
247
+ "text_kwargs": {"padding": "max_length", "max_length": 76},
248
+ }
249
+
250
+ inputs = processor(text=input_str, images=image_input, **all_kwargs)
251
+ self.skip_processor_without_typed_kwargs(processor)
252
+
253
+ self.assertEqual(len(inputs["input_ids"][0]), 76)
254
+
255
+ # Rewrite as Fuyu image processor does not return pixel values
256
+ @require_torch
257
+ @require_vision
258
+ def test_structured_kwargs_nested_from_dict(self):
259
+ if "image_processor" not in self.processor_class.attributes:
260
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
261
+
262
+ image_processor = self.get_component("image_processor")
263
+ tokenizer = self.get_component("tokenizer")
264
+
265
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
266
+ self.skip_processor_without_typed_kwargs(processor)
267
+ input_str = self.prepare_text_inputs()
268
+ # Fuyu uses tokenizer kwargs only when image is None.
269
+ image_input = None
270
+
271
+ # Define the kwargs for each modality
272
+ all_kwargs = {
273
+ "common_kwargs": {"return_tensors": "pt"},
274
+ "text_kwargs": {"padding": "max_length", "max_length": 76},
275
+ }
276
+
277
+ inputs = processor(text=input_str, images=image_input, **all_kwargs)
278
+
279
+ self.assertEqual(len(inputs["input_ids"][0]), 76)
280
+
281
+ # Rewrite as Fuyu supports tokenizer kwargs only when image is None.
282
+ @require_torch
283
+ @require_vision
284
+ def test_unstructured_kwargs(self):
285
+ if "image_processor" not in self.processor_class.attributes:
286
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
287
+ image_processor = self.get_component("image_processor")
288
+ tokenizer = self.get_component("tokenizer")
289
+
290
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
291
+ self.skip_processor_without_typed_kwargs(processor)
292
+
293
+ input_str = self.prepare_text_inputs()
294
+ # Fuyu uses tokenizer kwargs only when image is None.
295
+ image_input = None
296
+ inputs = processor(
297
+ text=input_str,
298
+ images=image_input,
299
+ return_tensors="pt",
300
+ padding="max_length",
301
+ max_length=76,
302
+ )
303
+
304
+ self.assertEqual(len(inputs["input_ids"][0]), 76)
305
+
306
+ # Rewrite as Fuyu supports tokenizer kwargs only when image is None.
307
+ @require_torch
308
+ @require_vision
309
+ def test_unstructured_kwargs_batched(self):
310
+ if "image_processor" not in self.processor_class.attributes:
311
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
312
+ image_processor = self.get_component("image_processor")
313
+ tokenizer = self.get_component("tokenizer")
314
+
315
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
316
+ self.skip_processor_without_typed_kwargs(processor)
317
+
318
+ input_str = self.prepare_text_inputs(batch_size=2)
319
+ # Fuyu uses tokenizer kwargs only when image is None.
320
+ image_input = None
321
+ inputs = processor(
322
+ text=input_str,
323
+ images=image_input,
324
+ return_tensors="pt",
325
+ padding="longest",
326
+ max_length=76,
327
+ )
328
+
329
+ self.assertEqual(len(inputs["input_ids"][0]), 6)
330
+
331
+
332
+ @require_torch
333
+ class TestImageTextProcessingUtils(unittest.TestCase):
334
+ def setUp(self):
335
+ self.batch_size = 2
336
+ self.new_seq_len = 8
337
+ self.num_sub_sequences = 1
338
+
339
+ self.all_bi_tokens_to_place = [4, 6]
340
+ self.full_unpacked_stream = [torch.tensor([1, 2, 3, 4]), torch.tensor([5, 6, 7, 8, 9, 10])]
341
+ self.fill_value = 0
342
+
343
+ self.num_real_text_tokens = [[3, 2], [2, 4]]
344
+ # Here the input stream is padded to avoid inconsistencies (current model release matches)
345
+ self.input_stream = torch.tensor([[[1, 2, 3], [4, 5, 0]], [[6, 7, 0], [8, 9, 10]]])
346
+ self.image_tokens = [
347
+ [torch.tensor([1, 2]), torch.tensor([3])],
348
+ [torch.tensor([4, 5, 6]), torch.tensor([7, 8])],
349
+ ]
350
+
351
+ def test_full_unpacked_stream_to_tensor(self):
352
+ result = full_unpacked_stream_to_tensor(
353
+ self.all_bi_tokens_to_place,
354
+ self.full_unpacked_stream,
355
+ self.fill_value,
356
+ self.batch_size,
357
+ self.new_seq_len,
358
+ offset=0,
359
+ )
360
+ EXPECTED_TENSOR = torch.tensor([[1, 2, 3, 4, 0, 0, 0, 0], [5, 6, 7, 8, 9, 10, 0, 0]])
361
+ self.assertTrue(torch.equal(result, EXPECTED_TENSOR))
362
+
363
+ def test_construct_full_unpacked_stream(self):
364
+ result = construct_full_unpacked_stream(
365
+ self.num_real_text_tokens, self.input_stream, self.image_tokens, self.batch_size, self.num_sub_sequences
366
+ )
367
+ EXPECTED_UNPACKED_STREAM = [torch.tensor([1, 2, 1, 2, 3]), torch.tensor([4, 5, 6, 6, 7])]
368
+ for i in range(len(result)):
369
+ self.assertTrue(torch.equal(result[i], EXPECTED_UNPACKED_STREAM[i]))
370
+
371
+
372
+ @require_torch
373
+ class TestProcessImagesForModelInput(unittest.TestCase):
374
+ def setUp(self):
375
+ """
376
+ Adding a mix of present and absent images.
377
+ """
378
+
379
+ self.image_input = torch.randn([1, 1, 3, 64, 64])
380
+ self.image_present = torch.tensor([[1]])
381
+ self.image_unpadded_h = torch.tensor([[45]]) # Adjusted for subsequence of 1
382
+ self.image_unpadded_w = torch.tensor([[50]]) # Adjusted for subsequence of 1
383
+ self.image_patch_dim_h = 16
384
+ self.image_patch_dim_w = 16
385
+ self.image_placeholder_id = 999
386
+ self.image_newline_id = 888
387
+ self.variable_sized = True
388
+ self.image_processor = FuyuImageProcessor(
389
+ patch_size={"height": self.image_patch_dim_h, "width": self.image_patch_dim_w}
390
+ )
391
+
392
+ def test_process_images_for_model_input_fixed_sized(self):
393
+ self.variable_sized = False
394
+ result = self.image_processor.preprocess_with_tokenizer_info(
395
+ image_input=self.image_input,
396
+ image_present=self.image_present,
397
+ image_unpadded_h=self.image_unpadded_h,
398
+ image_unpadded_w=self.image_unpadded_w,
399
+ image_placeholder_id=self.image_placeholder_id,
400
+ image_newline_id=self.image_newline_id,
401
+ variable_sized=self.variable_sized,
402
+ )
403
+ self.assertEqual(result["images"][0][0].shape, torch.Size([3, 64, 64]))
tasks/tasksmith-441eeab80047/tests/source/tests/models/gemma/__init__.py ADDED
File without changes
tasks/tasksmith-441eeab80047/tests/source/tests/models/gemma/test_modeling_flax_gemma.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import unittest
15
+
16
+ import numpy as np
17
+
18
+ from transformers import AutoTokenizer, GemmaConfig, is_flax_available
19
+ from transformers.testing_utils import require_flax, require_read_token, slow
20
+
21
+ from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor
22
+
23
+
24
+ if is_flax_available():
25
+ import jax
26
+ import jax.numpy as jnp
27
+
28
+ from transformers.models.gemma.modeling_flax_gemma import (
29
+ FlaxGemmaForCausalLM,
30
+ FlaxGemmaModel,
31
+ )
32
+
33
+
34
+ class FlaxGemmaModelTester:
35
+ def __init__(
36
+ self,
37
+ parent,
38
+ batch_size=2,
39
+ seq_length=7,
40
+ is_training=True,
41
+ use_input_mask=True,
42
+ use_token_type_ids=False,
43
+ use_labels=True,
44
+ vocab_size=99,
45
+ hidden_size=32,
46
+ num_hidden_layers=2,
47
+ num_attention_heads=4,
48
+ num_key_value_heads=2,
49
+ intermediate_size=37,
50
+ hidden_act="gelu",
51
+ hidden_dropout_prob=0.1,
52
+ attention_probs_dropout_prob=0.1,
53
+ max_position_embeddings=512,
54
+ initializer_range=0.02,
55
+ ):
56
+ self.parent = parent
57
+ self.batch_size = batch_size
58
+ self.seq_length = seq_length
59
+ self.is_training = is_training
60
+ self.use_input_mask = use_input_mask
61
+ self.use_token_type_ids = use_token_type_ids
62
+ self.use_labels = use_labels
63
+ self.vocab_size = vocab_size
64
+ self.hidden_size = hidden_size
65
+ self.num_hidden_layers = num_hidden_layers
66
+ self.num_attention_heads = num_attention_heads
67
+ self.num_key_value_heads = num_key_value_heads
68
+ self.intermediate_size = intermediate_size
69
+ self.hidden_act = hidden_act
70
+ self.hidden_dropout_prob = hidden_dropout_prob
71
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
72
+ self.max_position_embeddings = max_position_embeddings
73
+ self.initializer_range = initializer_range
74
+ self.scope = None
75
+ self.bos_token_id = vocab_size - 1
76
+ self.eos_token_id = vocab_size - 1
77
+ self.pad_token_id = vocab_size - 1
78
+
79
+ def prepare_config_and_inputs(self):
80
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
81
+
82
+ input_mask = None
83
+ if self.use_input_mask:
84
+ input_mask = np.tril(np.ones((self.batch_size, self.seq_length)))
85
+
86
+ config = GemmaConfig(
87
+ vocab_size=self.vocab_size,
88
+ hidden_size=self.hidden_size,
89
+ num_hidden_layers=self.num_hidden_layers,
90
+ num_attention_heads=self.num_attention_heads,
91
+ num_key_value_heads=self.num_key_value_heads,
92
+ head_dim=self.hidden_size // self.num_attention_heads,
93
+ intermediate_size=self.intermediate_size,
94
+ hidden_act=self.hidden_act,
95
+ hidden_dropout_prob=self.hidden_dropout_prob,
96
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
97
+ max_position_embeddings=self.max_position_embeddings,
98
+ use_cache=True,
99
+ is_decoder=False,
100
+ initializer_range=self.initializer_range,
101
+ )
102
+
103
+ return config, input_ids, input_mask
104
+
105
+ def prepare_config_and_inputs_for_common(self):
106
+ config_and_inputs = self.prepare_config_and_inputs()
107
+ config, input_ids, attention_mask = config_and_inputs
108
+ inputs_dict = {"input_ids": input_ids, "attention_mask": attention_mask}
109
+ return config, inputs_dict
110
+
111
+ def check_use_cache_forward(self, model_class_name, config, input_ids, attention_mask):
112
+ max_decoder_length = 20
113
+ model = model_class_name(config)
114
+
115
+ past_key_values = model.init_cache(input_ids.shape[0], max_decoder_length)
116
+ attention_mask = jnp.ones((input_ids.shape[0], max_decoder_length), dtype="i4")
117
+
118
+ position_ids = jnp.broadcast_to(
119
+ jnp.arange(input_ids.shape[-1] - 1)[None, :], (input_ids.shape[0], input_ids.shape[-1] - 1)
120
+ )
121
+ outputs_cache = model(
122
+ input_ids[:, :-1],
123
+ attention_mask=attention_mask,
124
+ past_key_values=past_key_values,
125
+ position_ids=position_ids,
126
+ )
127
+
128
+ position_ids = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]], dtype="i4")
129
+ outputs_cache_next = model(
130
+ input_ids[:, -1:],
131
+ attention_mask=attention_mask,
132
+ past_key_values=outputs_cache.past_key_values,
133
+ position_ids=position_ids,
134
+ )
135
+
136
+ outputs = model(input_ids)
137
+
138
+ diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
139
+ self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}")
140
+
141
+ def check_use_cache_forward_with_attn_mask(self, model_class_name, config, input_ids, attention_mask):
142
+ max_decoder_length = 20
143
+ model = model_class_name(config)
144
+
145
+ attention_mask_cache = jnp.concatenate(
146
+ [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]))],
147
+ axis=-1,
148
+ )
149
+
150
+ past_key_values = model.init_cache(input_ids.shape[0], max_decoder_length)
151
+ position_ids = jnp.broadcast_to(
152
+ jnp.arange(input_ids.shape[-1] - 1)[None, :], (input_ids.shape[0], input_ids.shape[-1] - 1)
153
+ )
154
+
155
+ outputs_cache = model(
156
+ input_ids[:, :-1],
157
+ attention_mask=attention_mask_cache,
158
+ past_key_values=past_key_values,
159
+ position_ids=position_ids,
160
+ )
161
+ position_ids = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]], dtype="i4")
162
+ outputs_cache_next = model(
163
+ input_ids[:, -1:],
164
+ past_key_values=outputs_cache.past_key_values,
165
+ attention_mask=attention_mask_cache,
166
+ position_ids=position_ids,
167
+ )
168
+
169
+ outputs = model(input_ids, attention_mask=attention_mask)
170
+
171
+ diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
172
+ self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}")
173
+
174
+
175
+ @require_flax
176
+ class FlaxGemmaModelTest(FlaxModelTesterMixin, unittest.TestCase):
177
+ all_model_classes = (FlaxGemmaModel, FlaxGemmaForCausalLM) if is_flax_available() else ()
178
+
179
+ def setUp(self):
180
+ self.model_tester = FlaxGemmaModelTester(self)
181
+
182
+ def test_use_cache_forward(self):
183
+ for model_class_name in self.all_model_classes:
184
+ config, input_ids, attention_mask = self.model_tester.prepare_config_and_inputs()
185
+ self.model_tester.check_use_cache_forward(model_class_name, config, input_ids, attention_mask)
186
+
187
+ def test_use_cache_forward_with_attn_mask(self):
188
+ for model_class_name in self.all_model_classes:
189
+ config, input_ids, attention_mask = self.model_tester.prepare_config_and_inputs()
190
+ self.model_tester.check_use_cache_forward_with_attn_mask(
191
+ model_class_name, config, input_ids, attention_mask
192
+ )
193
+
194
+ @slow
195
+ def test_model_from_pretrained(self):
196
+ for model_class_name in self.all_model_classes:
197
+ model = model_class_name.from_pretrained("google/gemma-2b", from_pt=True)
198
+ outputs = model(np.ones((1, 1)))
199
+ self.assertIsNotNone(outputs)
200
+
201
+
202
+ @slow
203
+ @require_flax
204
+ @require_read_token
205
+ class FlaxGemmaIntegrationTest(unittest.TestCase):
206
+ input_text = ["The capital of France is", "To play the perfect cover drive"]
207
+ model_id = "google/gemma-2b"
208
+ revision = "flax"
209
+
210
+ def setUp(self):
211
+ self.model, self.params = FlaxGemmaForCausalLM.from_pretrained(
212
+ self.model_id, revision=self.revision, _do_init=False
213
+ )
214
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model_id)
215
+ self.tokenizer.padding_side = "left"
216
+
217
+ def test_logits(self):
218
+ inputs = self.tokenizer(self.input_text, return_tensors="np", padding=True)
219
+ # fmt: off
220
+ EXPECTED_MEAN = [
221
+ [-16.427, -21.386, -35.491, -36.258, -31.401, -36.370, -37.598],
222
+ [-21.386, -32.150, -33.155, -34.344, -34.706, -34.678, -38.495],
223
+ ]
224
+ EXPECTED_SLICE = [-33.462, -16.481, -30.837, -32.195, -33.113]
225
+ # fmt: on
226
+
227
+ logits = self.model(**inputs, params=self.params).logits
228
+
229
+ diff_mean = jnp.abs(logits.mean(-1) - np.array(EXPECTED_MEAN)).max()
230
+ diff_slice = jnp.abs(logits[0, -1, 475:480] - np.array(EXPECTED_SLICE)).max()
231
+
232
+ self.assertAlmostEqual(diff_mean, 0, places=3)
233
+ self.assertAlmostEqual(diff_slice, 0, places=3)
234
+
235
+ def test_generation(self):
236
+ EXPECTED_TEXTS = [
237
+ "The capital of France is a city of contrasts. It is a city of history, of art, of culture, of fashion",
238
+ "To play the perfect cover drive, you need to have a good technique and a good mindset.\n\nThe cover drive is a shot",
239
+ ]
240
+ inputs = self.tokenizer(self.input_text, return_tensors="np", padding=True)
241
+
242
+ output = self.model.generate(**inputs, params=self.params, max_new_tokens=20, do_sample=False)
243
+ output_text = self.tokenizer.batch_decode(output.sequences, skip_special_tokens=True)
244
+
245
+ self.assertEqual(output_text, EXPECTED_TEXTS)
246
+
247
+ def test_jit_generation(self):
248
+ EXPECTED_TEXTS = [
249
+ "The capital of France is a city of contrasts. It is a city of history, culture, and art, but it is",
250
+ "To play the perfect cover drive, you need to have a good technique and a good mindset.\n\nThe cover drive is a shot",
251
+ ]
252
+ inputs = self.tokenizer(self.input_text, return_tensors="np", padding=True)
253
+
254
+ def generate(input_ids, attention_mask):
255
+ outputs = self.model.generate(
256
+ input_ids, attention_mask=attention_mask, params=self.params, max_new_tokens=20, do_sample=False
257
+ )
258
+ return outputs
259
+
260
+ jit_generate = jax.jit(generate)
261
+ output_sequences = jit_generate(**inputs).sequences
262
+ output_text = self.tokenizer.batch_decode(output_sequences, skip_special_tokens=True)
263
+
264
+ self.assertEqual(output_text, EXPECTED_TEXTS)
tasks/tasksmith-441eeab80047/tests/source/tests/models/gemma/test_modeling_gemma.py ADDED
@@ -0,0 +1,875 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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 Gemma model."""
16
+
17
+ import tempfile
18
+ import unittest
19
+
20
+ import pytest
21
+ from packaging import version
22
+
23
+ from transformers import AutoModelForCausalLM, AutoTokenizer, GemmaConfig, is_torch_available
24
+ from transformers.generation.configuration_utils import GenerationConfig
25
+ from transformers.testing_utils import (
26
+ is_flaky,
27
+ require_bitsandbytes,
28
+ require_flash_attn,
29
+ require_read_token,
30
+ require_torch,
31
+ require_torch_accelerator,
32
+ require_torch_gpu,
33
+ require_torch_sdpa,
34
+ slow,
35
+ torch_device,
36
+ )
37
+
38
+ from ...generation.test_utils import GenerationTesterMixin
39
+ from ...test_configuration_common import ConfigTester
40
+ from ...test_modeling_common import ModelTesterMixin, ids_tensor
41
+ from ...test_pipeline_mixin import PipelineTesterMixin
42
+
43
+
44
+ if is_torch_available():
45
+ import torch
46
+
47
+ from transformers import (
48
+ GemmaForCausalLM,
49
+ GemmaForSequenceClassification,
50
+ GemmaForTokenClassification,
51
+ GemmaModel,
52
+ )
53
+
54
+
55
+ @require_torch
56
+ class GemmaModelTester:
57
+ config_class = GemmaConfig
58
+ if is_torch_available():
59
+ model_class = GemmaModel
60
+ for_causal_lm_class = GemmaForCausalLM
61
+ for_sequence_class = GemmaForSequenceClassification
62
+ for_token_class = GemmaForTokenClassification
63
+
64
+ def __init__(
65
+ self,
66
+ parent,
67
+ batch_size=13,
68
+ seq_length=7,
69
+ is_training=True,
70
+ use_input_mask=True,
71
+ use_token_type_ids=False,
72
+ use_labels=True,
73
+ vocab_size=99,
74
+ hidden_size=32,
75
+ num_hidden_layers=2,
76
+ num_attention_heads=4,
77
+ num_key_value_heads=2,
78
+ intermediate_size=37,
79
+ hidden_act="gelu",
80
+ hidden_dropout_prob=0.1,
81
+ attention_probs_dropout_prob=0.1,
82
+ max_position_embeddings=512,
83
+ type_vocab_size=16,
84
+ type_sequence_label_size=2,
85
+ initializer_range=0.02,
86
+ num_labels=3,
87
+ num_choices=4,
88
+ pad_token_id=0,
89
+ scope=None,
90
+ ):
91
+ self.parent = parent
92
+ self.batch_size = batch_size
93
+ self.seq_length = seq_length
94
+ self.is_training = is_training
95
+ self.use_input_mask = use_input_mask
96
+ self.use_token_type_ids = use_token_type_ids
97
+ self.use_labels = use_labels
98
+ self.vocab_size = vocab_size
99
+ self.hidden_size = hidden_size
100
+ self.num_hidden_layers = num_hidden_layers
101
+ self.num_attention_heads = num_attention_heads
102
+ self.num_key_value_heads = num_key_value_heads
103
+ self.intermediate_size = intermediate_size
104
+ self.hidden_act = hidden_act
105
+ self.hidden_dropout_prob = hidden_dropout_prob
106
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
107
+ self.max_position_embeddings = max_position_embeddings
108
+ self.type_vocab_size = type_vocab_size
109
+ self.type_sequence_label_size = type_sequence_label_size
110
+ self.initializer_range = initializer_range
111
+ self.num_labels = num_labels
112
+ self.num_choices = num_choices
113
+ self.pad_token_id = pad_token_id
114
+ self.scope = scope
115
+ self.head_dim = self.hidden_size // self.num_attention_heads
116
+
117
+ # Copied from tests.models.mistral.test_modeling_mistral.MistralModelTester.prepare_config_and_inputs
118
+ def prepare_config_and_inputs(self):
119
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
120
+
121
+ input_mask = None
122
+ if self.use_input_mask:
123
+ input_mask = torch.tril(torch.ones_like(input_ids).to(torch_device))
124
+
125
+ token_type_ids = None
126
+ if self.use_token_type_ids:
127
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
128
+
129
+ sequence_labels = None
130
+ token_labels = None
131
+ choice_labels = None
132
+ if self.use_labels:
133
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
134
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
135
+ choice_labels = ids_tensor([self.batch_size], self.num_choices)
136
+
137
+ config = self.get_config()
138
+
139
+ return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
140
+
141
+ def get_config(self):
142
+ return self.config_class(
143
+ vocab_size=self.vocab_size,
144
+ hidden_size=self.hidden_size,
145
+ num_hidden_layers=self.num_hidden_layers,
146
+ num_attention_heads=self.num_attention_heads,
147
+ num_key_value_heads=self.num_key_value_heads,
148
+ intermediate_size=self.intermediate_size,
149
+ hidden_act=self.hidden_act,
150
+ hidden_dropout_prob=self.hidden_dropout_prob,
151
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
152
+ max_position_embeddings=self.max_position_embeddings,
153
+ type_vocab_size=self.type_vocab_size,
154
+ is_decoder=False,
155
+ initializer_range=self.initializer_range,
156
+ pad_token_id=self.pad_token_id,
157
+ head_dim=self.head_dim,
158
+ )
159
+
160
+ def create_and_check_model(
161
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
162
+ ):
163
+ model = self.model_class(config=config)
164
+ model.to(torch_device)
165
+ model.eval()
166
+ result = model(input_ids, attention_mask=input_mask)
167
+ result = model(input_ids)
168
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
169
+
170
+ def create_and_check_model_as_decoder(
171
+ self,
172
+ config,
173
+ input_ids,
174
+ token_type_ids,
175
+ input_mask,
176
+ sequence_labels,
177
+ token_labels,
178
+ choice_labels,
179
+ encoder_hidden_states,
180
+ encoder_attention_mask,
181
+ ):
182
+ config.add_cross_attention = True
183
+ model = self.model_class(config)
184
+ model.to(torch_device)
185
+ model.eval()
186
+ result = model(
187
+ input_ids,
188
+ attention_mask=input_mask,
189
+ encoder_hidden_states=encoder_hidden_states,
190
+ encoder_attention_mask=encoder_attention_mask,
191
+ )
192
+ result = model(
193
+ input_ids,
194
+ attention_mask=input_mask,
195
+ encoder_hidden_states=encoder_hidden_states,
196
+ )
197
+ result = model(input_ids, attention_mask=input_mask)
198
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
199
+
200
+ def create_and_check_for_causal_lm(
201
+ self,
202
+ config,
203
+ input_ids,
204
+ token_type_ids,
205
+ input_mask,
206
+ sequence_labels,
207
+ token_labels,
208
+ choice_labels,
209
+ encoder_hidden_states,
210
+ encoder_attention_mask,
211
+ ):
212
+ model = self.for_causal_lm_class(config=config)
213
+ model.to(torch_device)
214
+ model.eval()
215
+ result = model(input_ids, attention_mask=input_mask, labels=token_labels)
216
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
217
+
218
+ def create_and_check_decoder_model_past_large_inputs(
219
+ self,
220
+ config,
221
+ input_ids,
222
+ token_type_ids,
223
+ input_mask,
224
+ sequence_labels,
225
+ token_labels,
226
+ choice_labels,
227
+ encoder_hidden_states,
228
+ encoder_attention_mask,
229
+ ):
230
+ config.is_decoder = True
231
+ config.add_cross_attention = True
232
+ model = self.for_causal_lm_class(config=config)
233
+ model.to(torch_device)
234
+ model.eval()
235
+
236
+ # first forward pass
237
+ outputs = model(
238
+ input_ids,
239
+ attention_mask=input_mask,
240
+ encoder_hidden_states=encoder_hidden_states,
241
+ encoder_attention_mask=encoder_attention_mask,
242
+ use_cache=True,
243
+ )
244
+ past_key_values = outputs.past_key_values
245
+
246
+ # create hypothetical multiple next token and extent to next_input_ids
247
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
248
+ next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
249
+
250
+ # append to next input_ids and
251
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
252
+ next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
253
+
254
+ output_from_no_past = model(
255
+ next_input_ids,
256
+ attention_mask=next_attention_mask,
257
+ encoder_hidden_states=encoder_hidden_states,
258
+ encoder_attention_mask=encoder_attention_mask,
259
+ output_hidden_states=True,
260
+ )["hidden_states"][0]
261
+ output_from_past = model(
262
+ next_tokens,
263
+ attention_mask=next_attention_mask,
264
+ encoder_hidden_states=encoder_hidden_states,
265
+ encoder_attention_mask=encoder_attention_mask,
266
+ past_key_values=past_key_values,
267
+ output_hidden_states=True,
268
+ )["hidden_states"][0]
269
+
270
+ # select random slice
271
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
272
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
273
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
274
+
275
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
276
+
277
+ # test that outputs are equal for slice
278
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
279
+
280
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTester.prepare_config_and_inputs_for_common with Llama->Gemma
281
+ def prepare_config_and_inputs_for_common(self):
282
+ config_and_inputs = self.prepare_config_and_inputs()
283
+ (
284
+ config,
285
+ input_ids,
286
+ token_type_ids,
287
+ input_mask,
288
+ sequence_labels,
289
+ token_labels,
290
+ choice_labels,
291
+ ) = config_and_inputs
292
+ inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
293
+ return config, inputs_dict
294
+
295
+
296
+ @require_torch
297
+ class GemmaModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
298
+ all_model_classes = (
299
+ (GemmaModel, GemmaForCausalLM, GemmaForSequenceClassification, GemmaForTokenClassification)
300
+ if is_torch_available()
301
+ else ()
302
+ )
303
+ pipeline_model_mapping = (
304
+ {
305
+ "feature-extraction": GemmaModel,
306
+ "text-classification": GemmaForSequenceClassification,
307
+ "token-classification": GemmaForTokenClassification,
308
+ "text-generation": GemmaForCausalLM,
309
+ "zero-shot": GemmaForSequenceClassification,
310
+ }
311
+ if is_torch_available()
312
+ else {}
313
+ )
314
+ test_headmasking = False
315
+ test_pruning = False
316
+
317
+ # Need to remove 0.9 in `test_cpu_offload`
318
+ # This is because we are hitting edge cases with the causal_mask buffer
319
+ model_split_percents = [0.5, 0.6]
320
+
321
+ # used in `test_torch_compile_for_training`
322
+ _torch_compile_train_cls = GemmaForCausalLM if is_torch_available() else None
323
+
324
+ # TODO (ydshieh): Check this. See https://app.circleci.com/pipelines/github/huggingface/transformers/79245/workflows/9490ef58-79c2-410d-8f51-e3495156cf9c/jobs/1012146
325
+ def is_pipeline_test_to_skip(
326
+ self,
327
+ pipeline_test_case_name,
328
+ config_class,
329
+ model_architecture,
330
+ tokenizer_name,
331
+ image_processor_name,
332
+ feature_extractor_name,
333
+ processor_name,
334
+ ):
335
+ return True
336
+
337
+ def setUp(self):
338
+ self.model_tester = GemmaModelTester(self)
339
+ self.config_tester = ConfigTester(self, config_class=GemmaConfig, hidden_size=37)
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_model_various_embeddings(self):
349
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
350
+ for type in ["absolute", "relative_key", "relative_key_query"]:
351
+ config_and_inputs[0].position_embedding_type = type
352
+ self.model_tester.create_and_check_model(*config_and_inputs)
353
+
354
+ def test_Gemma_sequence_classification_model(self):
355
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
356
+ config.num_labels = 3
357
+ input_ids = input_dict["input_ids"]
358
+ attention_mask = input_ids.ne(1).to(torch_device)
359
+ sequence_labels = ids_tensor([self.model_tester.batch_size], self.model_tester.type_sequence_label_size)
360
+ model = self.model_tester.for_sequence_class(config)
361
+ model.to(torch_device)
362
+ model.eval()
363
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
364
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
365
+
366
+ def test_Gemma_sequence_classification_model_for_single_label(self):
367
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
368
+ config.num_labels = 3
369
+ config.problem_type = "single_label_classification"
370
+ input_ids = input_dict["input_ids"]
371
+ attention_mask = input_ids.ne(1).to(torch_device)
372
+ sequence_labels = ids_tensor([self.model_tester.batch_size], self.model_tester.type_sequence_label_size)
373
+ model = self.model_tester.for_sequence_class(config)
374
+ model.to(torch_device)
375
+ model.eval()
376
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
377
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
378
+
379
+ def test_Gemma_sequence_classification_model_for_multi_label(self):
380
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
381
+ config.num_labels = 3
382
+ config.problem_type = "multi_label_classification"
383
+ input_ids = input_dict["input_ids"]
384
+ attention_mask = input_ids.ne(1).to(torch_device)
385
+ sequence_labels = ids_tensor(
386
+ [self.model_tester.batch_size, config.num_labels], self.model_tester.type_sequence_label_size
387
+ ).to(torch.float)
388
+ model = self.model_tester.for_sequence_class(config)
389
+ model.to(torch_device)
390
+ model.eval()
391
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
392
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
393
+
394
+ def test_Gemma_token_classification_model(self):
395
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
396
+ config.num_labels = 3
397
+ input_ids = input_dict["input_ids"]
398
+ attention_mask = input_ids.ne(1).to(torch_device)
399
+ token_labels = ids_tensor([self.model_tester.batch_size, self.model_tester.seq_length], config.num_labels)
400
+ model = self.model_tester.for_token_class(config=config)
401
+ model.to(torch_device)
402
+ model.eval()
403
+ result = model(input_ids, attention_mask=attention_mask, labels=token_labels)
404
+ self.assertEqual(
405
+ result.logits.shape,
406
+ (self.model_tester.batch_size, self.model_tester.seq_length, self.model_tester.num_labels),
407
+ )
408
+
409
+ @unittest.skip(reason="Gemma buffers include complex numbers, which breaks this test")
410
+ def test_save_load_fast_init_from_base(self):
411
+ pass
412
+
413
+ @unittest.skip(reason="Gemma uses GQA on all models so the KV cache is a non standard format")
414
+ def test_past_key_values_format(self):
415
+ pass
416
+
417
+ @require_flash_attn
418
+ @require_torch_gpu
419
+ @pytest.mark.flash_attn_test
420
+ @slow
421
+ def test_flash_attn_2_inference_equivalence_right_padding(self):
422
+ self.skipTest(reason="Gemma flash attention does not support right padding")
423
+
424
+ @require_torch_sdpa
425
+ @require_torch_accelerator
426
+ @slow
427
+ def test_sdpa_equivalence(self):
428
+ for model_class in self.all_model_classes:
429
+ if not model_class._supports_sdpa:
430
+ self.skipTest(reason="Model does not support SDPA")
431
+
432
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
433
+ model = model_class(config)
434
+
435
+ with tempfile.TemporaryDirectory() as tmpdirname:
436
+ model.save_pretrained(tmpdirname)
437
+ model_sdpa = model_class.from_pretrained(
438
+ tmpdirname, torch_dtype=torch.float16, attn_implementation="sdpa"
439
+ )
440
+ model_sdpa.to(torch_device)
441
+
442
+ model = model_class.from_pretrained(tmpdirname, torch_dtype=torch.float16, attn_implementation="eager")
443
+ model.to(torch_device)
444
+
445
+ dummy_input = inputs_dict[model_class.main_input_name]
446
+ dummy_input = dummy_input.to(torch_device)
447
+ outputs = model(dummy_input, output_hidden_states=True)
448
+ outputs_sdpa = model_sdpa(dummy_input, output_hidden_states=True)
449
+
450
+ logits = outputs.hidden_states[-1]
451
+ logits_sdpa = outputs_sdpa.hidden_states[-1]
452
+
453
+ # gemma sdpa needs a high tolerance
454
+ assert torch.allclose(logits_sdpa, logits, atol=3e-3)
455
+
456
+ @require_flash_attn
457
+ @require_torch_gpu
458
+ @pytest.mark.flash_attn_test
459
+ @is_flaky()
460
+ @slow
461
+ def test_flash_attn_2_equivalence(self):
462
+ for model_class in self.all_model_classes:
463
+ if not model_class._supports_flash_attn_2:
464
+ self.skipTest(reason="Model does not support Flash Attention 2")
465
+
466
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
467
+ model = model_class(config)
468
+
469
+ with tempfile.TemporaryDirectory() as tmpdirname:
470
+ model.save_pretrained(tmpdirname)
471
+ model_fa = model_class.from_pretrained(
472
+ tmpdirname, torch_dtype=torch.float16, attn_implementation="flash_attention_2"
473
+ )
474
+ model_fa.to(torch_device)
475
+
476
+ model = model_class.from_pretrained(tmpdirname, torch_dtype=torch.float16, attn_implementation="eager")
477
+ model.to(torch_device)
478
+
479
+ dummy_input = inputs_dict[model_class.main_input_name]
480
+ dummy_input = dummy_input.to(torch_device)
481
+ outputs = model(dummy_input, output_hidden_states=True)
482
+ outputs_fa = model_fa(dummy_input, output_hidden_states=True)
483
+
484
+ logits = outputs.hidden_states[-1]
485
+ logits_fa = outputs_fa.hidden_states[-1]
486
+
487
+ # gemma flash attention 2 needs a high tolerance
488
+ assert torch.allclose(logits_fa, logits, atol=3e-3)
489
+
490
+
491
+ @slow
492
+ @require_torch_accelerator
493
+ class GemmaIntegrationTest(unittest.TestCase):
494
+ input_text = ["Hello I am doing", "Hi today"]
495
+ # This variable is used to determine which CUDA device are we using for our runners (A10 or T4)
496
+ # Depending on the hardware we get different logits / generations
497
+ cuda_compute_capability_major_version = None
498
+
499
+ @classmethod
500
+ def setUpClass(cls):
501
+ if is_torch_available() and torch.cuda.is_available():
502
+ # 8 is for A100 / A10 and 7 for T4
503
+ cls.cuda_compute_capability_major_version = torch.cuda.get_device_capability()[0]
504
+
505
+ @require_read_token
506
+ def test_model_2b_fp16(self):
507
+ model_id = "google/gemma-2b"
508
+ EXPECTED_TEXTS = [
509
+ "Hello I am doing a project on the 1990s and I need to know what the most popular music",
510
+ "Hi today I am going to share with you a very easy and simple recipe of <strong><em>Kaju Kat",
511
+ ]
512
+
513
+ model = AutoModelForCausalLM.from_pretrained(model_id, low_cpu_mem_usage=True, torch_dtype=torch.float16).to(
514
+ torch_device
515
+ )
516
+
517
+ model.generation_config.cache_implementation = "static"
518
+
519
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
520
+ inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device)
521
+
522
+ output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
523
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=True)
524
+
525
+ self.assertEqual(output_text, EXPECTED_TEXTS)
526
+
527
+ @require_read_token
528
+ def test_model_2b_bf16(self):
529
+ model_id = "google/gemma-2b"
530
+
531
+ EXPECTED_TEXTS = [
532
+ "Hello I am doing a project on the 1990s and I need to know what the most popular music",
533
+ "Hi today I am going to share with you a very easy and simple recipe of <strong><em>Khichdi",
534
+ ]
535
+
536
+ model = AutoModelForCausalLM.from_pretrained(model_id, low_cpu_mem_usage=True, torch_dtype=torch.bfloat16).to(
537
+ torch_device
538
+ )
539
+
540
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
541
+ inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device)
542
+
543
+ output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
544
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=True)
545
+
546
+ self.assertEqual(output_text, EXPECTED_TEXTS)
547
+
548
+ @require_read_token
549
+ def test_model_2b_eager(self):
550
+ model_id = "google/gemma-2b"
551
+
552
+ EXPECTED_TEXTS = [
553
+ "Hello I am doing a project on the 1990s and I need to know what the most popular music",
554
+ "Hi today I am going to share with you a very easy and simple recipe of <strong><em>Khichdi",
555
+ ]
556
+
557
+ model = AutoModelForCausalLM.from_pretrained(
558
+ model_id, low_cpu_mem_usage=True, torch_dtype=torch.bfloat16, attn_implementation="eager"
559
+ )
560
+ model.to(torch_device)
561
+
562
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
563
+ inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device)
564
+
565
+ output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
566
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=True)
567
+
568
+ self.assertEqual(output_text, EXPECTED_TEXTS)
569
+
570
+ @require_torch_sdpa
571
+ @require_read_token
572
+ def test_model_2b_sdpa(self):
573
+ model_id = "google/gemma-2b"
574
+
575
+ EXPECTED_TEXTS = [
576
+ "Hello I am doing a project on the 1990s and I need to know what the most popular music",
577
+ "Hi today I am going to share with you a very easy and simple recipe of <strong><em>Khichdi",
578
+ ]
579
+
580
+ model = AutoModelForCausalLM.from_pretrained(
581
+ model_id, low_cpu_mem_usage=True, torch_dtype=torch.bfloat16, attn_implementation="sdpa"
582
+ )
583
+ model.to(torch_device)
584
+
585
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
586
+ inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device)
587
+
588
+ output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
589
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=True)
590
+
591
+ self.assertEqual(output_text, EXPECTED_TEXTS)
592
+
593
+ @require_flash_attn
594
+ @require_read_token
595
+ @pytest.mark.flash_attn_test
596
+ def test_model_2b_flash_attn(self):
597
+ model_id = "google/gemma-2b"
598
+ EXPECTED_TEXTS = [
599
+ "Hello I am doing a project on the 1990s and I need to know what the most popular music",
600
+ "Hi today I am going to share with you a very easy and simple recipe of <strong><em>Kaju Kat",
601
+ ]
602
+
603
+ model = AutoModelForCausalLM.from_pretrained(
604
+ model_id, low_cpu_mem_usage=True, torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2"
605
+ )
606
+ model.to(torch_device)
607
+
608
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
609
+ inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device)
610
+
611
+ output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
612
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=True)
613
+
614
+ self.assertEqual(output_text, EXPECTED_TEXTS)
615
+
616
+ @require_bitsandbytes
617
+ @require_read_token
618
+ def test_model_2b_4bit(self):
619
+ model_id = "google/gemma-2b"
620
+ EXPECTED_TEXTS = [
621
+ "Hello I am doing a project and I need to make a 3d model of a house. I have been using",
622
+ "Hi today I'd like to share with you my experience with the new wattpad wattpad wattpad wattpad wattpad wattpad wattpad",
623
+ ]
624
+
625
+ model = AutoModelForCausalLM.from_pretrained(model_id, low_cpu_mem_usage=True, load_in_4bit=True)
626
+
627
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
628
+ inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device)
629
+
630
+ output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
631
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=True)
632
+
633
+ self.assertEqual(output_text, EXPECTED_TEXTS)
634
+
635
+ @unittest.skip(reason="The test will not fit our CI runners")
636
+ @require_read_token
637
+ def test_model_7b_fp32(self):
638
+ model_id = "google/gemma-7b"
639
+ EXPECTED_TEXTS = [
640
+ "Hello my name is ***** ***** I will be assisting you today. I am sorry to hear about your issue. I will",
641
+ "Hi,\n\nI have a problem with my 2005 1.6 16",
642
+ ]
643
+
644
+ model = AutoModelForCausalLM.from_pretrained(model_id, low_cpu_mem_usage=True).to(torch_device)
645
+
646
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
647
+ inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device)
648
+
649
+ output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
650
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=True)
651
+
652
+ self.assertEqual(output_text, EXPECTED_TEXTS)
653
+
654
+ @require_read_token
655
+ def test_model_7b_fp16(self):
656
+ if self.cuda_compute_capability_major_version == 7:
657
+ self.skipTest("This test is failing (`torch.compile` fails) on Nvidia T4 GPU (OOM).")
658
+
659
+ model_id = "google/gemma-7b"
660
+ EXPECTED_TEXTS = [
661
+ """Hello I am doing a project on a 1999 4.0L 4x4. I""",
662
+ "Hi today I am going to show you how to make a simple and easy to make a DIY 3D",
663
+ ]
664
+
665
+ model = AutoModelForCausalLM.from_pretrained(model_id, low_cpu_mem_usage=True, torch_dtype=torch.float16).to(
666
+ torch_device
667
+ )
668
+
669
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
670
+ inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device)
671
+
672
+ output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
673
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=True)
674
+
675
+ self.assertEqual(output_text, EXPECTED_TEXTS)
676
+
677
+ @require_read_token
678
+ def test_model_7b_bf16(self):
679
+ if self.cuda_compute_capability_major_version == 7:
680
+ self.skipTest("This test is failing (`torch.compile` fails) on Nvidia T4 GPU (OOM).")
681
+
682
+ model_id = "google/gemma-7b"
683
+
684
+ # Key 9 for MI300, Key 8 for A100/A10, and Key 7 for T4.
685
+ #
686
+ # Note: Key 9 is currently set for MI300, but may need potential future adjustments for H100s,
687
+ # considering differences in hardware processing and potential deviations in generated text.
688
+ EXPECTED_TEXTS = {
689
+ 7: [
690
+ """Hello I am doing a project on a 1991 240sx and I am trying to find""",
691
+ "Hi today I am going to show you how to make a very simple and easy to make a very simple and",
692
+ ],
693
+ 8: [
694
+ "Hello I am doing a project for my school and I am trying to make a program that will read a .txt file",
695
+ "Hi today I am going to show you how to make a very simple and easy to make a very simple and",
696
+ ],
697
+ 9: [
698
+ "Hello I am doing a project for my school and I am trying to get a servo to move a certain amount of degrees",
699
+ "Hi today I am going to show you how to make a very simple and easy to make DIY light up sign",
700
+ ],
701
+ }
702
+
703
+ model = AutoModelForCausalLM.from_pretrained(model_id, low_cpu_mem_usage=True, torch_dtype=torch.bfloat16).to(
704
+ torch_device
705
+ )
706
+
707
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
708
+ inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device)
709
+
710
+ output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
711
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=True)
712
+ self.assertEqual(output_text, EXPECTED_TEXTS[self.cuda_compute_capability_major_version])
713
+
714
+ @require_read_token
715
+ def test_model_7b_fp16_static_cache(self):
716
+ if self.cuda_compute_capability_major_version == 7:
717
+ self.skipTest("This test is failing (`torch.compile` fails) on Nvidia T4 GPU (OOM).")
718
+
719
+ model_id = "google/gemma-7b"
720
+ EXPECTED_TEXTS = [
721
+ """Hello I am doing a project on a 1999 4.0L 4x4. I""",
722
+ "Hi today I am going to show you how to make a simple and easy to make a DIY 3D",
723
+ ]
724
+
725
+ model = AutoModelForCausalLM.from_pretrained(model_id, low_cpu_mem_usage=True, torch_dtype=torch.float16).to(
726
+ torch_device
727
+ )
728
+
729
+ model.generation_config.cache_implementation = "static"
730
+
731
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
732
+ inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device)
733
+ output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
734
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=True)
735
+ self.assertEqual(output_text, EXPECTED_TEXTS)
736
+
737
+ @require_bitsandbytes
738
+ @require_read_token
739
+ def test_model_7b_4bit(self):
740
+ model_id = "google/gemma-7b"
741
+ EXPECTED_TEXTS = [
742
+ "Hello I am doing a project for my school and I am trying to make a program that will take a number and then",
743
+ "Hi today I am going to talk about the best way to get rid of acne. miniaturing is a very",
744
+ ]
745
+
746
+ model = AutoModelForCausalLM.from_pretrained(model_id, low_cpu_mem_usage=True, load_in_4bit=True)
747
+
748
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
749
+ inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device)
750
+
751
+ output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
752
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=True)
753
+ self.assertEqual(output_text, EXPECTED_TEXTS)
754
+
755
+ @slow
756
+ @require_torch_gpu
757
+ @require_read_token
758
+ def test_compile_static_cache(self):
759
+ # `torch==2.2` will throw an error on this test (as in other compilation tests), but torch==2.1.2 and torch>2.2
760
+ # work as intended. See https://github.com/pytorch/pytorch/issues/121943
761
+ if version.parse(torch.__version__) < version.parse("2.3.0"):
762
+ self.skipTest(reason="This test requires torch >= 2.3 to run.")
763
+
764
+ NUM_TOKENS_TO_GENERATE = 40
765
+ EXPECTED_TEXT_COMPLETION = [
766
+ "Hello I am doing a project on the 1990s and I need to know what the most popular music was in the 1990s. I have looked on the internet and I have found",
767
+ "Hi today\nI have a problem with my 2007 1.9 tdi 105bhp.\nI have a problem with the engine management light on.\nI have checked the",
768
+ ]
769
+
770
+ prompts = ["Hello I am doing", "Hi today"]
771
+ tokenizer = AutoTokenizer.from_pretrained("google/gemma-2b", pad_token="</s>", padding_side="right")
772
+ model = GemmaForCausalLM.from_pretrained("google/gemma-2b", device_map=torch_device, torch_dtype=torch.float16)
773
+ inputs = tokenizer(prompts, return_tensors="pt", padding=True).to(model.device)
774
+
775
+ # Dynamic Cache
776
+ generated_ids = model.generate(**inputs, max_new_tokens=NUM_TOKENS_TO_GENERATE, do_sample=False)
777
+ dynamic_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
778
+ self.assertEqual(EXPECTED_TEXT_COMPLETION, dynamic_text) # Both GPU architectures have the same output
779
+
780
+ # Static Cache
781
+ generated_ids = model.generate(
782
+ **inputs, max_new_tokens=NUM_TOKENS_TO_GENERATE, do_sample=False, cache_implementation="static"
783
+ )
784
+ static_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
785
+ self.assertEqual(EXPECTED_TEXT_COMPLETION, static_text)
786
+
787
+ # Static Cache + compile
788
+ model.forward = torch.compile(model.forward, mode="reduce-overhead", fullgraph=True)
789
+ generated_ids = model.generate(
790
+ **inputs, max_new_tokens=NUM_TOKENS_TO_GENERATE, do_sample=False, cache_implementation="static"
791
+ )
792
+ static_compiled_text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
793
+ self.assertEqual(EXPECTED_TEXT_COMPLETION, static_compiled_text)
794
+
795
+ @slow
796
+ @require_read_token
797
+ def test_export_static_cache(self):
798
+ if version.parse(torch.__version__) < version.parse("2.3.0"):
799
+ self.skipTest(reason="This test requires torch >= 2.3 to run.")
800
+
801
+ from transformers.integrations.executorch import (
802
+ TorchExportableModuleWithStaticCache,
803
+ convert_and_export_with_cache,
804
+ )
805
+
806
+ tokenizer = AutoTokenizer.from_pretrained("google/gemma-2b", pad_token="</s>", padding_side="right")
807
+ EXPECTED_TEXT_COMPLETION = [
808
+ "Hello I am doing a project on the 1990s and I need to know what the most popular music was in the 1990s. I have looked on the internet and I have found",
809
+ ]
810
+ max_generation_length = tokenizer(EXPECTED_TEXT_COMPLETION, return_tensors="pt", padding=True)[
811
+ "input_ids"
812
+ ].shape[-1]
813
+
814
+ # Load model
815
+ device = "cpu"
816
+ dtype = torch.bfloat16
817
+ cache_implementation = "static"
818
+ attn_implementation = "sdpa"
819
+ batch_size = 1
820
+ model = GemmaForCausalLM.from_pretrained(
821
+ "google/gemma-2b",
822
+ device_map=device,
823
+ torch_dtype=dtype,
824
+ attn_implementation=attn_implementation,
825
+ generation_config=GenerationConfig(
826
+ use_cache=True,
827
+ cache_implementation=cache_implementation,
828
+ max_length=max_generation_length,
829
+ cache_config={
830
+ "batch_size": batch_size,
831
+ "max_cache_len": max_generation_length,
832
+ },
833
+ ),
834
+ )
835
+
836
+ prompts = ["Hello I am doing"]
837
+ prompt_tokens = tokenizer(prompts, return_tensors="pt", padding=True).to(model.device)
838
+ prompt_token_ids = prompt_tokens["input_ids"]
839
+ max_new_tokens = max_generation_length - prompt_token_ids.shape[-1]
840
+
841
+ # Static Cache + eager
842
+ eager_generated_ids = model.generate(
843
+ **prompt_tokens, max_new_tokens=max_new_tokens, do_sample=False, cache_implementation=cache_implementation
844
+ )
845
+ eager_generated_text = tokenizer.batch_decode(eager_generated_ids, skip_special_tokens=True)
846
+ self.assertEqual(EXPECTED_TEXT_COMPLETION, eager_generated_text)
847
+
848
+ # Static Cache + export
849
+ exported_program = convert_and_export_with_cache(model)
850
+ ep_generated_ids = TorchExportableModuleWithStaticCache.generate(
851
+ exported_program=exported_program, prompt_token_ids=prompt_token_ids, max_new_tokens=max_new_tokens
852
+ )
853
+ ep_generated_text = tokenizer.batch_decode(ep_generated_ids, skip_special_tokens=True)
854
+ self.assertEqual(EXPECTED_TEXT_COMPLETION, ep_generated_text)
855
+
856
+ def test_model_2b_bf16_dola(self):
857
+ model_id = "google/gemma-2b"
858
+ # ground truth text generated with dola_layers="low", repetition_penalty=1.2
859
+ EXPECTED_TEXTS = [
860
+ "Hello I am doing an experiment and need to get the mass of a block. The problem is, it has no scale",
861
+ "Hi today we have the review for a <strong>2016/2017</strong> season of",
862
+ ]
863
+
864
+ model = AutoModelForCausalLM.from_pretrained(model_id, low_cpu_mem_usage=True, torch_dtype=torch.bfloat16).to(
865
+ torch_device
866
+ )
867
+
868
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
869
+ inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device)
870
+
871
+ output = model.generate(
872
+ **inputs, max_new_tokens=20, do_sample=False, dola_layers="low", repetition_penalty=1.2
873
+ )
874
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=True)
875
+ self.assertEqual(output_text, EXPECTED_TEXTS)
tasks/tasksmith-441eeab80047/tests/source/tests/models/gemma/test_tokenization_gemma.py ADDED
@@ -0,0 +1,544 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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 os
17
+ import tempfile
18
+ import unittest
19
+
20
+ from datasets import load_dataset
21
+
22
+ from transformers import (
23
+ AddedToken,
24
+ GemmaTokenizer,
25
+ GemmaTokenizerFast,
26
+ )
27
+ from transformers.convert_slow_tokenizer import convert_slow_tokenizer
28
+ from transformers.testing_utils import (
29
+ get_tests_dir,
30
+ nested_simplify,
31
+ require_jinja,
32
+ require_read_token,
33
+ require_sentencepiece,
34
+ require_tokenizers,
35
+ require_torch,
36
+ slow,
37
+ )
38
+
39
+ from ...test_tokenization_common import TokenizerTesterMixin
40
+
41
+
42
+ SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model")
43
+
44
+
45
+ @require_sentencepiece
46
+ @require_tokenizers
47
+ class GemmaTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
48
+ from_pretrained_id = "google/gemma-7b"
49
+ tokenizer_class = GemmaTokenizer
50
+ rust_tokenizer_class = GemmaTokenizerFast
51
+
52
+ test_rust_tokenizer = False
53
+ test_sentencepiece = True
54
+ from_pretrained_kwargs = {}
55
+
56
+ def setUp(self):
57
+ super().setUp()
58
+ # We have a SentencePiece fixture for testing
59
+ tokenizer = GemmaTokenizer(SAMPLE_VOCAB, keep_accents=True)
60
+ tokenizer.pad_token = tokenizer.eos_token
61
+ tokenizer.save_pretrained(self.tmpdirname)
62
+
63
+ @require_torch
64
+ def test_batch_tokenization(self):
65
+ if not self.test_seq2seq:
66
+ self.skipTest(reason="test_seq2seq is set to False")
67
+
68
+ tokenizers = self.get_tokenizers()
69
+ for tokenizer in tokenizers:
70
+ with self.subTest(f"{tokenizer.__class__.__name__}"):
71
+ # Longer text that will definitely require truncation.
72
+ text = [
73
+ " UN Chief Says There Is No Military Solution in Syria",
74
+ " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for"
75
+ " Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons"
76
+ " will only worsen the violence and misery for millions of people.",
77
+ ]
78
+ try:
79
+ batch = tokenizer(
80
+ text=text,
81
+ max_length=3,
82
+ max_target_length=10,
83
+ return_tensors="pt",
84
+ )
85
+ except NotImplementedError:
86
+ self.skipTest(reason="Encountered NotImplementedError when calling tokenizer")
87
+ self.assertEqual(batch.input_ids.shape[1], 3)
88
+ # max_target_length will default to max_length if not specified
89
+ batch = tokenizer(text, max_length=3, return_tensors="pt")
90
+ self.assertEqual(batch.input_ids.shape[1], 3)
91
+
92
+ batch_encoder_only = tokenizer(text=text, max_length=3, max_target_length=10, return_tensors="pt")
93
+ self.assertEqual(batch_encoder_only.input_ids.shape[1], 3)
94
+ self.assertEqual(batch_encoder_only.attention_mask.shape[1], 3)
95
+ self.assertNotIn("decoder_input_ids", batch_encoder_only)
96
+
97
+ @unittest.skip(reason="Unfortunately way too slow to build a BPE with SentencePiece.")
98
+ def test_save_slow_from_fast_and_reload_fast(self):
99
+ pass
100
+
101
+ def test_special_tokens_initialization(self):
102
+ for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
103
+ with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
104
+ added_tokens = [AddedToken("<special>", lstrip=True)]
105
+
106
+ tokenizer_r = self.rust_tokenizer_class.from_pretrained(
107
+ pretrained_name, additional_special_tokens=added_tokens, **kwargs
108
+ )
109
+ r_output = tokenizer_r.encode("Hey this is a <special> token")
110
+
111
+ special_token_id = tokenizer_r.encode("<special>", add_special_tokens=False)[0]
112
+
113
+ self.assertTrue(special_token_id in r_output)
114
+
115
+ if self.test_slow_tokenizer:
116
+ tokenizer_cr = self.rust_tokenizer_class.from_pretrained(
117
+ pretrained_name,
118
+ additional_special_tokens=added_tokens,
119
+ **kwargs, # , from_slow=True <- unfortunately too slow to convert
120
+ )
121
+ tokenizer_p = self.tokenizer_class.from_pretrained(
122
+ pretrained_name, additional_special_tokens=added_tokens, **kwargs
123
+ )
124
+
125
+ p_output = tokenizer_p.encode("Hey this is a <special> token")
126
+
127
+ cr_output = tokenizer_cr.encode("Hey this is a <special> token")
128
+
129
+ self.assertEqual(p_output, r_output)
130
+ self.assertEqual(cr_output, r_output)
131
+ self.assertTrue(special_token_id in p_output)
132
+ self.assertTrue(special_token_id in cr_output)
133
+
134
+ @slow
135
+ @require_read_token
136
+ def test_tokenizer_integration(self):
137
+ expected_encoding = {'input_ids': [[2, 158434, 591, 84193, 3836, 685, 6599, 31223, 235290, 140247, 578, 6599, 31223, 235290, 145139, 235290, 3491, 235275, 6572, 3311, 235290, 38197, 109959, 591, 25894, 235269, 162174, 235290, 235284, 235269, 1791, 6362, 12481, 235269, 1576, 18622, 235269, 2900, 1136, 86684, 235269, 29092, 4632, 16994, 604, 13146, 14944, 40371, 591, 19700, 235327, 235275, 578, 13146, 14944, 25511, 591, 235300, 12474, 235275, 675, 1163, 235248, 235304, 235284, 235340, 229903, 5377, 575, 235248, 235274, 235276, 235276, 235340, 17044, 578, 5271, 1061, 118345, 1865, 125247, 235269, 8745, 111226, 578, 176888, 235265], [2, 25894, 603, 6869, 577, 953, 235290, 8297, 5271, 209099, 41642, 774, 748, 78253, 2793, 731, 51506, 34346, 611, 2145, 2731, 578, 1833, 4807, 575, 832, 16630, 235265], [2, 651, 4320, 8426, 25341, 36271, 1163, 573, 27894, 5929, 235265]], '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]]} # fmt: skip
138
+ self.tokenizer_integration_test_util(
139
+ expected_encoding=expected_encoding,
140
+ model_name="google/gemma-2b",
141
+ padding=False,
142
+ )
143
+
144
+ @unittest.skip(reason="worker 'gw4' crashed on CI, passing locally.")
145
+ def test_pickle_subword_regularization_tokenizer(self):
146
+ pass
147
+
148
+ @unittest.skip(reason="worker 'gw4' crashed on CI, passing locally.")
149
+ def test_subword_regularization_tokenizer(self):
150
+ pass
151
+
152
+ @unittest.skip(reason="Skipping")
153
+ def test_torch_encode_plus_sent_to_model(self):
154
+ pass
155
+
156
+
157
+ @require_torch
158
+ @require_sentencepiece
159
+ @require_tokenizers
160
+ class GemmaIntegrationTest(unittest.TestCase):
161
+ @classmethod
162
+ def setUpClass(cls):
163
+ checkpoint_name = "hf-internal-testing/dummy-gemma"
164
+ cls.tokenizer: GemmaTokenizer = GemmaTokenizer.from_pretrained(
165
+ checkpoint_name, eos_token="<s>"
166
+ ) # add this token
167
+ cls.rust_tokenizer = GemmaTokenizerFast.from_pretrained(
168
+ checkpoint_name, eos_token="<s>", from_slow=True
169
+ ) # add this token
170
+ return cls
171
+
172
+ @require_torch
173
+ def integration_tests(self):
174
+ inputs = self.tokenizer(
175
+ ["The following string should be properly encoded: Hello.", "But ird and ปี ird ด"],
176
+ return_tensors="pt",
177
+ )
178
+
179
+ self.assertEqual(
180
+ nested_simplify(inputs),
181
+ {
182
+ "input_ids": [
183
+ [2, 450, 1494, 1347, 881, 367, 6284, 18511, 29901, 15043, 29889],
184
+ [2, 1205, 29871, 1823, 322, 29871, 31010, 30691, 1678, 1823, 1678, 30718],
185
+ ],
186
+ "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]],
187
+ },
188
+ )
189
+
190
+ def test_user_added_tokens(self):
191
+ # Ensure that user added tokens are not split in the fast tokenizer
192
+ slow_tokenizer = self.tokenizer
193
+ fast_tokenizer = self.rust_tokenizer
194
+
195
+ user_added_token = "<mask>"
196
+
197
+ slow_tokens = slow_tokenizer.convert_ids_to_tokens(slow_tokenizer.encode(user_added_token))
198
+ fast_tokens = slow_tokenizer.convert_ids_to_tokens(fast_tokenizer.encode(user_added_token))
199
+
200
+ self.assertTrue(user_added_token in fast_tokens)
201
+ self.assertEqual(slow_tokens, fast_tokens)
202
+
203
+ def test_fast_special_tokens(self):
204
+ slow_tokenizer = self.tokenizer
205
+ fast_tokenizer = self.rust_tokenizer
206
+ slow = slow_tokenizer.encode("A sample test", add_special_tokens=True)
207
+ assert slow == [2, 235280, 6453, 2121]
208
+
209
+ fast_tokenizer.add_eos_token = False
210
+ fast = fast_tokenizer.encode("A sample test", add_special_tokens=True)
211
+ assert fast == [2, 235280, 6453, 2121]
212
+
213
+ fast_tokenizer.add_eos_token = True
214
+ fast = fast_tokenizer.encode("A sample test", add_special_tokens=True)
215
+ assert fast == [2, 235280, 6453, 2121, 204]
216
+
217
+ slow_tokenizer.add_eos_token = True
218
+ slow = slow_tokenizer.encode("A sample test", add_special_tokens=True)
219
+ assert slow == [2, 235280, 6453, 2121, 204]
220
+
221
+ self.tokenizer.add_eos_token = False
222
+ self.rust_tokenizer.add_eos_token = False
223
+
224
+ def test_fast_merge_priority(self):
225
+ slow_tokenizer = self.tokenizer
226
+ fast_tokenizer = self.rust_tokenizer
227
+ text = " "
228
+ target = [168, 153]
229
+ slow = slow_tokenizer.encode(text, add_special_tokens=False)
230
+ assert slow == target
231
+
232
+ fast = fast_tokenizer.encode(text, add_special_tokens=False)
233
+ assert fast == target
234
+
235
+ @unittest.skip(reason="Not super important and always failing. Let's skip it")
236
+ @slow
237
+ def test_conversion(self):
238
+ # This is excruciatingly slow since it has to recreate the entire merge
239
+ # list from the original vocabulary in spm
240
+ self.rust_tokenizer.save_pretrained("./out")
241
+ with tempfile.TemporaryDirectory() as dirname:
242
+ self.rust_tokenizer.save_pretrained(dirname)
243
+
244
+ with open(os.path.join(dirname, "tokenizer.json"), "r") as f:
245
+ old_serialized = f.read()
246
+
247
+ new_tokenizer = convert_slow_tokenizer(self.tokenizer)
248
+ with tempfile.NamedTemporaryFile() as f:
249
+ new_tokenizer.save(f.name)
250
+ # Re-opening since `f` is in bytes.
251
+ new_serialized = open(f.name, "r").read()
252
+ with open("out_tokenizer.json", "w") as g:
253
+ g.write(new_serialized)
254
+
255
+ self.assertEqual(old_serialized, new_serialized)
256
+
257
+ def test_simple_encode_decode(self):
258
+ pyth_tokenizer = self.tokenizer
259
+ rust_tokenizer = self.rust_tokenizer
260
+
261
+ self.tokenizer.add_eos_token = False
262
+ self.rust_tokenizer.add_eos_token = False
263
+
264
+ self.assertEqual(pyth_tokenizer.encode("This is a test"), [2, 1596, 603, 476, 2121])
265
+ self.assertEqual(rust_tokenizer.encode("This is a test"), [2, 1596, 603, 476, 2121])
266
+ self.assertEqual(pyth_tokenizer.decode([2, 1596, 603, 476, 2121], skip_special_tokens=True), "This is a test")
267
+ self.assertEqual(rust_tokenizer.decode([2, 1596, 603, 476, 2121], skip_special_tokens=True), "This is a test")
268
+
269
+ # bytefallback showcase
270
+ self.assertEqual(pyth_tokenizer.encode("生活的真谛是"), [2, 122182, 235710, 245467, 235427] ) # fmt: skip
271
+ self.assertEqual(rust_tokenizer.encode("生活的真谛是"), [2, 122182, 235710, 245467, 235427] ) # fmt: skip
272
+ self.assertEqual(
273
+ pyth_tokenizer.decode([2, 122182, 235710, 245467, 235427], skip_special_tokens=True),
274
+ "生活的真谛是",
275
+ )
276
+ self.assertEqual(
277
+ rust_tokenizer.decode([2, 122182, 235710, 245467, 235427], skip_special_tokens=True),
278
+ "生活的真谛是",
279
+ )
280
+
281
+ # Inner spaces showcase
282
+ self.assertEqual(pyth_tokenizer.encode("Hi Hello"), [2, 2151, 139, 4521])
283
+ self.assertEqual(rust_tokenizer.encode("Hi Hello"), [2, 2151, 139, 4521])
284
+ self.assertEqual(pyth_tokenizer.decode([2, 2151, 139, 4521], skip_special_tokens=True), "Hi Hello")
285
+ self.assertEqual(rust_tokenizer.decode([2, 2151, 139, 4521], skip_special_tokens=True), "Hi Hello")
286
+
287
+ self.assertEqual(pyth_tokenizer.encode("Hi Hello"), [2, 2151, 140, 4521])
288
+ self.assertEqual(rust_tokenizer.encode("Hi Hello"), [2, 2151, 140, 4521])
289
+ self.assertEqual(pyth_tokenizer.decode([2, 2151, 140, 4521], skip_special_tokens=True), "Hi Hello")
290
+ self.assertEqual(rust_tokenizer.decode([2, 2151, 140, 4521], skip_special_tokens=True), "Hi Hello")
291
+
292
+ self.assertEqual(pyth_tokenizer.encode(""), [2])
293
+ self.assertEqual(rust_tokenizer.encode(""), [2])
294
+
295
+ self.assertEqual(pyth_tokenizer.encode(" "), [2, 235248])
296
+ self.assertEqual(rust_tokenizer.encode(" "), [2, 235248])
297
+
298
+ self.assertEqual(pyth_tokenizer.encode(" "), [2, 139])
299
+ self.assertEqual(rust_tokenizer.encode(" "), [2, 139])
300
+
301
+ self.assertEqual(pyth_tokenizer.encode(" Hello"), [2, 25957])
302
+ self.assertEqual(rust_tokenizer.encode(" Hello"), [2, 25957])
303
+
304
+ def test_no_differences_decode(self):
305
+ self.tokenizer.add_eos_token = False
306
+ self.rust_tokenizer.add_eos_token = False
307
+ pyth_tokenizer = self.tokenizer
308
+ rust_tokenizer = self.rust_tokenizer
309
+
310
+ self.assertEqual(pyth_tokenizer.decode([869]), "og")
311
+ self.assertEqual(rust_tokenizer.decode([869]), "og")
312
+
313
+ self.assertEqual(pyth_tokenizer.decode([30112, 869]), " expenditureog")
314
+ self.assertEqual(rust_tokenizer.decode([30112, 869]), " expenditureog")
315
+
316
+ def test_no_differences_special_tokens(self):
317
+ pyth_tokenizer = self.tokenizer
318
+ rust_tokenizer = self.rust_tokenizer
319
+ self.assertEqual(pyth_tokenizer.encode(""), [2])
320
+ self.assertEqual(rust_tokenizer.encode(""), [2])
321
+
322
+ self.assertEqual(pyth_tokenizer.encode("<s>"), [2, 204])
323
+ self.assertEqual(rust_tokenizer.encode("<s>"), [2, 204])
324
+
325
+ @unittest.skipIf(
326
+ os.getenv("RUN_TOKENIZER_INTEGRATION", "0") == "0",
327
+ "RUN_TOKENIZER_INTEGRATION=1 to run tokenizer integration tests",
328
+ )
329
+ def test_integration_test_xnli(self):
330
+ import tqdm
331
+
332
+ pyth_tokenizer = self.tokenizer
333
+ rust_tokenizer = self.rust_tokenizer
334
+
335
+ dataset = load_dataset("google/code_x_glue_ct_code_to_text", "go")
336
+ for item in tqdm.tqdm(dataset["validation"]):
337
+ string = item["code"]
338
+ encoded1 = pyth_tokenizer.encode(string)
339
+ encoded2 = rust_tokenizer.encode(string)
340
+
341
+ self.assertEqual(
342
+ encoded1,
343
+ encoded2,
344
+ msg="Hint: the following tokenization diff were obtained for slow vs fast:\n "
345
+ f"elements in slow: {set(pyth_tokenizer.tokenize(string))-set(rust_tokenizer.tokenize(string))} \nvs\n "
346
+ f"elements in fast: {set(rust_tokenizer.tokenize(string))-set(pyth_tokenizer.tokenize(string))} \n\n{string}",
347
+ )
348
+
349
+ decoded1 = pyth_tokenizer.decode(encoded1, skip_special_tokens=True)
350
+ decoded2 = rust_tokenizer.decode(encoded1, skip_special_tokens=True)
351
+
352
+ self.assertEqual(decoded1, decoded2)
353
+
354
+ dataset = load_dataset("facebook/xnli", "all_languages")
355
+
356
+ for item in tqdm.tqdm(dataset["train"]):
357
+ for string in item["premise"].values():
358
+ encoded1 = pyth_tokenizer.encode(string)
359
+ encoded2 = rust_tokenizer.encode(string)
360
+
361
+ self.assertEqual(encoded1, encoded2, msg=f"failed on {string}")
362
+
363
+ decoded1 = pyth_tokenizer.decode(encoded1, skip_special_tokens=True)
364
+ decoded2 = rust_tokenizer.decode(encoded2, skip_special_tokens=True)
365
+
366
+ self.assertEqual(decoded1, decoded2)
367
+
368
+ def test_special_token_special_word(self):
369
+ # the word inform should be split as ['in', 'form']
370
+ tokenizer = GemmaTokenizer.from_pretrained("hf-internal-testing/dummy-gemma")
371
+ tokenizer.add_tokens([AddedToken("<REPR_END>", rstrip=True, lstrip=True)], special_tokens=False)
372
+ out1 = tokenizer.decode(
373
+ tokenizer.encode("<REPR_END>inform", add_special_tokens=False), spaces_between_special_tokens=False
374
+ )
375
+ self.assertEqual(out1, "<REPR_END>inform")
376
+ out2 = tokenizer.decode(
377
+ tokenizer.encode("<REPR_END>inform", add_special_tokens=False), spaces_between_special_tokens=True
378
+ )
379
+ # decoding strips the added prefix space.
380
+ self.assertEqual(out2, "<REPR_END> inform")
381
+ input_ids = tokenizer.encode("<REPR_END>inform", add_special_tokens=False)
382
+ self.assertEqual(input_ids, [256000, 43910])
383
+
384
+ out2 = tokenizer.decode(
385
+ tokenizer.encode(" <REPR_END> inform", add_special_tokens=False), spaces_between_special_tokens=False
386
+ )
387
+ # TODO @ArthurZ currently we strip left and right, so this will not keep the spaces
388
+ self.assertEqual(out2, "<REPR_END>inform")
389
+
390
+ ### Let's make sure decoding does not add extra spaces here and there
391
+ # TODO @ArthurZ this should be affected by the lstrip/rstrip/single word /normalize refactoring
392
+ # Since currently we always strip left and right of the token, results are as such
393
+ input_ids = tokenizer.encode("<s> Hello<s>how", add_special_tokens=False)
394
+ self.assertEqual(input_ids, [204, 25957, 204, 1139])
395
+ tokens = tokenizer.tokenize("<s> Hello<s>how", add_special_tokens=False)
396
+ self.assertEqual(tokens, ["<s>", "▁Hello", "<s>", "how"])
397
+ decoded_tokens = tokenizer.decode(input_ids)
398
+ self.assertEqual(decoded_tokens, "<s> Hello<s>how")
399
+
400
+ # Let's make sure that if there are any spaces, we don't remove them!
401
+ input_ids = tokenizer.encode(" <s> Hello<s> how", add_special_tokens=False)
402
+ self.assertEqual(input_ids, [235248, 204, 25957, 204, 1368])
403
+ tokens = tokenizer.tokenize(" <s> Hello<s> how", add_special_tokens=False)
404
+ self.assertEqual(tokens, ["▁", "<s>", "▁Hello", "<s>", "▁how"])
405
+ decoded_tokens = tokenizer.decode(input_ids)
406
+ self.assertEqual(decoded_tokens, " <s> Hello<s> how")
407
+
408
+ def test_some_edge_cases(self):
409
+ tokenizer = GemmaTokenizer.from_pretrained("hf-internal-testing/dummy-gemma")
410
+
411
+ sp_tokens = tokenizer.sp_model.encode("<s>>", out_type=str)
412
+ self.assertEqual(sp_tokens, ["<s>", ">"])
413
+ tokens = tokenizer.tokenize("<s>>")
414
+ self.assertEqual(sp_tokens, tokens)
415
+ self.assertEqual(tokens, ["<s>", ">"])
416
+
417
+ tokens = tokenizer.tokenize("")
418
+ self.assertEqual(tokens, [])
419
+ self.assertEqual(tokens, tokenizer.sp_model.encode("", out_type=str))
420
+
421
+ tokens = tokenizer.tokenize(" ")
422
+ self.assertEqual(tokens, ["▁"])
423
+ # a dummy prefix space is not added by the sp_model as it was de-activated
424
+ self.assertEqual(tokens, tokenizer.sp_model.encode(" ", out_type=str))
425
+
426
+ tokens = tokenizer.tokenize("▁")
427
+ self.assertEqual(tokens, ["▁"])
428
+ # a dummy prefix space is not added by the sp_model as it was de-activated
429
+ self.assertEqual(tokens, tokenizer.sp_model.encode("▁", out_type=str))
430
+
431
+ tokens = tokenizer.tokenize(" ▁")
432
+ self.assertEqual(tokens, ["▁▁"])
433
+ # a dummy prefix space is not added by the sp_model as it was de-activated
434
+ self.assertEqual(tokens, tokenizer.sp_model.encode("▁▁", out_type=str))
435
+
436
+ @require_jinja
437
+ def test_tokenization_for_chat(self):
438
+ tokenizer = GemmaTokenizer.from_pretrained("hf-internal-testing/dummy-gemma")
439
+
440
+ test_chats = [
441
+ [{"role": "user", "content": "Hello!"}],
442
+ [
443
+ {"role": "user", "content": "Hello!"},
444
+ {"role": "assistant", "content": "Nice to meet you."},
445
+ ],
446
+ [{"role": "user", "content": "Hello!"}],
447
+ ]
448
+ # Matt: The third test case tests the default system message, but if this is ever changed in the
449
+ # class/repo code then that test will fail, and the case will need to be updated.
450
+ tokenized_chats = [tokenizer.apply_chat_template(test_chat) for test_chat in test_chats]
451
+ expected_tokens = [[235322, 235371, 571, 235298, 2997, 73786, 1645, 108, 4521, 149907, 235371, 571, 235298, 615, 73786, 108], [235322, 235371, 571, 235298, 2997, 73786, 1645, 108, 4521, 149907, 235371, 571, 235298, 615, 73786, 108, 235322, 235371, 571, 235298, 2997, 73786, 105776, 108, 7731, 577, 4664, 692, 35606, 235371, 571, 235298, 615, 73786, 108], [235322, 235371, 571, 235298, 2997, 73786, 1645, 108, 4521, 149907, 235371, 571, 235298, 615, 73786, 108]] # fmt: skip
452
+ for tokenized_chat, expected_tokens in zip(tokenized_chats, expected_tokens):
453
+ self.assertListEqual(tokenized_chat, expected_tokens)
454
+
455
+ def test_save_fast_load_slow(self):
456
+ # Ensure that we can save a fast tokenizer and load it as a slow tokenizer
457
+ slow_tokenizer = self.tokenizer
458
+ text = "a "
459
+ target_encoded = [2, 235250, 139]
460
+ slow = slow_tokenizer.encode(text, add_special_tokens=True)
461
+ assert slow == target_encoded
462
+
463
+ slow_decoded = slow_tokenizer.decode(slow, skip_special_tokens=True)
464
+ assert slow_decoded == text
465
+
466
+ with tempfile.TemporaryDirectory() as dirname:
467
+ # Save fast tokenizer
468
+ self.rust_tokenizer.save_pretrained(dirname)
469
+
470
+ # Load slow tokenizer with fast files present in the directory
471
+ slow_tokenizer_from_fast = GemmaTokenizer.from_pretrained(dirname)
472
+
473
+ slow_from_fast = slow_tokenizer_from_fast.encode(text, add_special_tokens=True)
474
+ assert slow_from_fast == target_encoded
475
+
476
+ slow_from_fast_decoded = slow_tokenizer_from_fast.decode(slow, skip_special_tokens=True)
477
+ assert slow_from_fast_decoded == text
478
+
479
+
480
+ @require_sentencepiece
481
+ @require_tokenizers
482
+ class CommonSpmIntegrationTests(unittest.TestCase):
483
+ """
484
+ A class that regroups important test to make sure that we properly handle the special tokens.
485
+ """
486
+
487
+ def test_edge_case_tabulation(self):
488
+ fast_tokenizer = GemmaTokenizerFast.from_pretrained("hf-internal-testing/dummy-gemma")
489
+ slow_tokenizer = GemmaTokenizer.from_pretrained("hf-internal-testing/dummy-gemma")
490
+ input_text = "Hey<eos>. \t\t \n\nyou é @#😈 🤗! , 1234 15 5,61"
491
+ EXPECTED_IDS = [ 2, 6750, 1, 235265, 235248, 255969, 235248, 109, 4747, 139, 235335, 139, 216311, 241316, 139, 239880, 235341, 144, 235269, 235248, 235274, 235284, 235304, 235310, 235248, 235274, 235308, 235248, 235308, 235269, 235318, 235274] # fmt: skip
492
+ EXPECTED_TOKENS = [ "Hey", "<eos>", ".", "▁", "\t\t", "▁", "\n\n", "you", "▁▁", "é", "▁▁", "@#", "😈", "▁▁", "🤗", "!", "▁▁▁▁▁▁▁", ",", "▁", "1", "2", "3", "4", "▁", "1", "5", "▁", "5", ",", "6", "1"] # fmt: skip
493
+
494
+ tokens = fast_tokenizer.tokenize(input_text)
495
+ with self.subTest("test fast edge case fast"):
496
+ self.assertEqual(tokens, EXPECTED_TOKENS)
497
+
498
+ tokens = slow_tokenizer.tokenize(input_text)
499
+ with self.subTest("test fast edge case fast"):
500
+ self.assertEqual(tokens, EXPECTED_TOKENS)
501
+
502
+ input_ids = fast_tokenizer.encode(input_text)
503
+ with self.subTest("test fast edge case fast"):
504
+ self.assertEqual(input_ids, EXPECTED_IDS)
505
+
506
+ input_ids = slow_tokenizer.encode(input_text)
507
+ with self.subTest("test fast edge case fast"):
508
+ self.assertEqual(input_ids, EXPECTED_IDS)
509
+
510
+ text = fast_tokenizer.decode(EXPECTED_IDS)
511
+ with self.subTest("test fast edge case fast"):
512
+ self.assertEqual(text, "<bos>Hey<eos>. \t\t \n\nyou é @#😈 🤗! , 1234 15 5,61")
513
+
514
+ text = slow_tokenizer.decode(EXPECTED_IDS)
515
+ with self.subTest("test fast edge case fast"):
516
+ self.assertEqual(text, "<bos>Hey<eos>. \t\t \n\nyou é @#😈 🤗! , 1234 15 5,61")
517
+
518
+ input_text = "\t\t\t\t \n\n61"
519
+ EXPECTED_IDS = [2, 255971, 235248, 109, 235318, 235274]
520
+ EXPECTED_TOKENS = ["\t\t\t\t", "▁", "\n\n", "6", "1"]
521
+
522
+ tokens = fast_tokenizer.tokenize(input_text)
523
+ with self.subTest("test fast edge case fast"):
524
+ self.assertEqual(tokens, EXPECTED_TOKENS)
525
+
526
+ tokens = slow_tokenizer.tokenize(input_text)
527
+ with self.subTest("test fast edge case fast"):
528
+ self.assertEqual(tokens, EXPECTED_TOKENS)
529
+
530
+ input_ids = fast_tokenizer.encode(input_text)
531
+ with self.subTest("test fast edge case fast"):
532
+ self.assertEqual(input_ids, EXPECTED_IDS)
533
+
534
+ input_ids = slow_tokenizer.encode(input_text)
535
+ with self.subTest("test fast edge case fast"):
536
+ self.assertEqual(input_ids, EXPECTED_IDS)
537
+
538
+ text = fast_tokenizer.decode(EXPECTED_IDS)
539
+ with self.subTest("test fast edge case fast"):
540
+ self.assertEqual(text, "<bos>\t\t\t\t \n\n61")
541
+
542
+ text = slow_tokenizer.decode(EXPECTED_IDS)
543
+ with self.subTest("test fast edge case fast"):
544
+ self.assertEqual(text, "<bos>\t\t\t\t \n\n61")
tasks/tasksmith-441eeab80047/tests/source/tests/models/gemma2/__init__.py ADDED
File without changes
tasks/tasksmith-441eeab80047/tests/source/tests/models/gemma2/test_modeling_gemma2.py ADDED
@@ -0,0 +1,394 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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 Gemma2 model."""
16
+
17
+ import unittest
18
+
19
+ from packaging import version
20
+ from parameterized import parameterized
21
+ from pytest import mark
22
+
23
+ from transformers import AutoModelForCausalLM, AutoTokenizer, Gemma2Config, is_torch_available, pipeline
24
+ from transformers.generation.configuration_utils import GenerationConfig
25
+ from transformers.testing_utils import (
26
+ require_flash_attn,
27
+ require_read_token,
28
+ require_torch,
29
+ require_torch_gpu,
30
+ slow,
31
+ tooslow,
32
+ torch_device,
33
+ )
34
+
35
+ from ...models.gemma.test_modeling_gemma import GemmaModelTest, GemmaModelTester
36
+ from ...test_configuration_common import ConfigTester
37
+
38
+
39
+ if is_torch_available():
40
+ import torch
41
+
42
+ from transformers import (
43
+ Gemma2ForCausalLM,
44
+ Gemma2ForSequenceClassification,
45
+ Gemma2ForTokenClassification,
46
+ Gemma2Model,
47
+ )
48
+
49
+
50
+ class Gemma2ModelTester(GemmaModelTester):
51
+ if is_torch_available():
52
+ config_class = Gemma2Config
53
+ model_class = Gemma2Model
54
+ for_causal_lm_class = Gemma2ForCausalLM
55
+ for_sequence_class = Gemma2ForSequenceClassification
56
+ for_token_class = Gemma2ForTokenClassification
57
+
58
+
59
+ @require_torch
60
+ class Gemma2ModelTest(GemmaModelTest, unittest.TestCase):
61
+ all_model_classes = (
62
+ (Gemma2Model, Gemma2ForCausalLM, Gemma2ForSequenceClassification, Gemma2ForTokenClassification)
63
+ if is_torch_available()
64
+ else ()
65
+ )
66
+ pipeline_model_mapping = (
67
+ {
68
+ "feature-extraction": Gemma2Model,
69
+ "text-classification": Gemma2ForSequenceClassification,
70
+ "token-classification": Gemma2ForTokenClassification,
71
+ "text-generation": Gemma2ForCausalLM,
72
+ "zero-shot": Gemma2ForSequenceClassification,
73
+ }
74
+ if is_torch_available()
75
+ else {}
76
+ )
77
+ test_headmasking = False
78
+ test_pruning = False
79
+ _is_stateful = True
80
+ model_split_percents = [0.5, 0.6]
81
+
82
+ def setUp(self):
83
+ self.model_tester = Gemma2ModelTester(self)
84
+ self.config_tester = ConfigTester(self, config_class=Gemma2Config, hidden_size=37)
85
+
86
+ @unittest.skip("Failing because of unique cache (HybridCache)")
87
+ def test_model_outputs_equivalence(self, **kwargs):
88
+ pass
89
+
90
+ @unittest.skip("Gemma2's forcefully disables sdpa due to softcapping")
91
+ def test_sdpa_can_dispatch_non_composite_models(self):
92
+ pass
93
+
94
+ @parameterized.expand([("float16",), ("bfloat16",), ("float32",)])
95
+ @unittest.skip("Gemma2's eager attn/sdpa attn outputs are expected to be different")
96
+ def test_eager_matches_sdpa_inference(self):
97
+ pass
98
+
99
+ @unittest.skip("Gemma2's eager attn/sdpa attn outputs are expected to be different")
100
+ def test_eager_matches_sdpa_generate(self):
101
+ pass
102
+
103
+ @parameterized.expand([("random",), ("same",)])
104
+ @unittest.skip("Gemma2 has HybridCache which is not compatible with assisted decoding")
105
+ def test_assisted_decoding_matches_greedy_search(self, assistant_type):
106
+ pass
107
+
108
+ @unittest.skip("Gemma2 has HybridCache which is not compatible with assisted decoding")
109
+ def test_prompt_lookup_decoding_matches_greedy_search(self, assistant_type):
110
+ pass
111
+
112
+ @unittest.skip("Gemma2 has HybridCache which is not compatible with assisted decoding")
113
+ def test_assisted_decoding_sample(self):
114
+ pass
115
+
116
+ @unittest.skip("Gemma2 has HybridCache which is not compatible with dola decoding")
117
+ def test_dola_decoding_sample(self):
118
+ pass
119
+
120
+ @unittest.skip("Gemma2 has HybridCache and doesn't support continue from past kv")
121
+ def test_generate_continue_from_past_key_values(self):
122
+ pass
123
+
124
+ @unittest.skip("Gemma2 has HybridCache and doesn't support low_memory generation")
125
+ def test_beam_search_low_memory(self):
126
+ pass
127
+
128
+ @unittest.skip("Gemma2 has HybridCache and doesn't support contrastive generation")
129
+ def test_contrastive_generate(self):
130
+ pass
131
+
132
+ @unittest.skip("Gemma2 has HybridCache and doesn't support contrastive generation")
133
+ def test_contrastive_generate_dict_outputs_use_cache(self):
134
+ pass
135
+
136
+ @unittest.skip("Gemma2 has HybridCache and doesn't support contrastive generation")
137
+ def test_contrastive_generate_low_memory(self):
138
+ pass
139
+
140
+ @unittest.skip("Gemma2 has HybridCache and doesn't support StaticCache. Though it could, it shouldn't support.")
141
+ def test_generate_with_static_cache(self):
142
+ pass
143
+
144
+ @unittest.skip("Gemma2 has HybridCache and doesn't support StaticCache. Though it could, it shouldn't support.")
145
+ def test_generate_from_inputs_embeds_with_static_cache(self):
146
+ pass
147
+
148
+ @unittest.skip("Gemma2 has HybridCache and doesn't support StaticCache. Though it could, it shouldn't support.")
149
+ def test_generate_continue_from_inputs_embeds(self):
150
+ pass
151
+
152
+ @unittest.skip("Gemma2's eager attn/sdpa attn outputs are expected to be different")
153
+ def test_sdpa_equivalence(self):
154
+ pass
155
+
156
+ @unittest.skip(
157
+ reason="HybridCache can't be gathered because it is not iterable. Adding a simple iter and dumping `distributed_iterator`"
158
+ " as in Dynamic Cache doesnt work. NOTE: @gante all cache objects would need better compatibility with multi gpu setting"
159
+ )
160
+ def test_multi_gpu_data_parallel_forward(self):
161
+ pass
162
+
163
+
164
+ @slow
165
+ @require_torch_gpu
166
+ class Gemma2IntegrationTest(unittest.TestCase):
167
+ input_text = ["Hello I am doing", "Hi today"]
168
+ # This variable is used to determine which CUDA device are we using for our runners (A10 or T4)
169
+ # Depending on the hardware we get different logits / generations
170
+ cuda_compute_capability_major_version = None
171
+
172
+ @classmethod
173
+ def setUpClass(cls):
174
+ if is_torch_available() and torch.cuda.is_available():
175
+ # 8 is for A100 / A10 and 7 for T4
176
+ cls.cuda_compute_capability_major_version = torch.cuda.get_device_capability()[0]
177
+
178
+ @tooslow
179
+ @require_read_token
180
+ def test_model_9b_bf16(self):
181
+ model_id = "google/gemma-2-9b"
182
+ EXPECTED_TEXTS = [
183
+ "<bos>Hello I am doing a project on the 1918 flu pandemic and I am trying to find out how many",
184
+ "<pad><pad><bos>Hi today I'm going to be talking about the history of the United States. The United States of America",
185
+ ]
186
+
187
+ model = AutoModelForCausalLM.from_pretrained(
188
+ model_id, low_cpu_mem_usage=True, torch_dtype=torch.bfloat16, attn_implementation="eager"
189
+ ).to(torch_device)
190
+
191
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
192
+ inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device)
193
+
194
+ output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
195
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=False)
196
+
197
+ self.assertEqual(output_text, EXPECTED_TEXTS)
198
+
199
+ @tooslow
200
+ @require_read_token
201
+ def test_model_9b_fp16(self):
202
+ model_id = "google/gemma-2-9b"
203
+ EXPECTED_TEXTS = [
204
+ "<bos>Hello I am doing a project on the 1918 flu pandemic and I am trying to find out how many",
205
+ "<pad><pad><bos>Hi today I'm going to be talking about the history of the United States. The United States of America",
206
+ ]
207
+
208
+ model = AutoModelForCausalLM.from_pretrained(
209
+ model_id, low_cpu_mem_usage=True, torch_dtype=torch.float16, attn_implementation="eager"
210
+ ).to(torch_device)
211
+
212
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
213
+ inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device)
214
+
215
+ output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
216
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=False)
217
+
218
+ self.assertEqual(output_text, EXPECTED_TEXTS)
219
+
220
+ @require_read_token
221
+ @tooslow
222
+ def test_model_9b_pipeline_bf16(self):
223
+ # See https://github.com/huggingface/transformers/pull/31747 -- pipeline was broken for Gemma2 before this PR
224
+ model_id = "google/gemma-2-9b"
225
+ # EXPECTED_TEXTS should match the same non-pipeline test, minus the special tokens
226
+ EXPECTED_TEXTS = [
227
+ "Hello I am doing a project on the 1918 flu pandemic and I am trying to find out how many",
228
+ "Hi today I'm going to be talking about the history of the United States. The United States of America",
229
+ ]
230
+
231
+ model = AutoModelForCausalLM.from_pretrained(
232
+ model_id, low_cpu_mem_usage=True, torch_dtype=torch.bfloat16, attn_implementation="flex_attention"
233
+ ).to(torch_device)
234
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
235
+ pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)
236
+
237
+ output = pipe(self.input_text, max_new_tokens=20, do_sample=False, padding=True)
238
+
239
+ self.assertEqual(output[0][0]["generated_text"], EXPECTED_TEXTS[0])
240
+ self.assertEqual(output[1][0]["generated_text"], EXPECTED_TEXTS[1])
241
+
242
+ @require_read_token
243
+ def test_model_2b_pipeline_bf16_flex_attention(self):
244
+ # See https://github.com/huggingface/transformers/pull/31747 -- pipeline was broken for Gemma2 before this PR
245
+ model_id = "google/gemma-2-2b"
246
+ # EXPECTED_TEXTS should match the same non-pipeline test, minus the special tokens
247
+ EXPECTED_TEXTS = [
248
+ "Hello I am doing a project on the 1960s and I am trying to find out what the average",
249
+ "Hi today I'm going to be talking about the 10 best anime of all time.\n\n1",
250
+ ]
251
+
252
+ model = AutoModelForCausalLM.from_pretrained(
253
+ model_id, low_cpu_mem_usage=True, torch_dtype=torch.bfloat16, attn_implementation="flex_attention"
254
+ ).to(torch_device)
255
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
256
+ pipe = pipeline("text-generation", model=model, tokenizer=tokenizer)
257
+
258
+ output = pipe(self.input_text, max_new_tokens=20, do_sample=False, padding=True)
259
+
260
+ self.assertEqual(output[0][0]["generated_text"], EXPECTED_TEXTS[0])
261
+ self.assertEqual(output[1][0]["generated_text"], EXPECTED_TEXTS[1])
262
+
263
+ @require_read_token
264
+ @require_flash_attn
265
+ @require_torch_gpu
266
+ @mark.flash_attn_test
267
+ @slow
268
+ @tooslow
269
+ def test_model_9b_flash_attn(self):
270
+ # See https://github.com/huggingface/transformers/issues/31953 --- flash attn was generating garbage for gemma2, especially in long context
271
+ model_id = "google/gemma-2-9b"
272
+ EXPECTED_TEXTS = [
273
+ '<bos>Hello I am doing a project on the 1918 flu pandemic and I am trying to find out how many people died in the United States. I have found a few sites that say 500,000 but I am not sure if that is correct. I have also found a site that says 675,000 but I am not sure if that is correct either. I am trying to find out how many people died in the United States. I have found a few',
274
+ "<pad><pad><bos>Hi today I'm going to be talking about the history of the United States. The United States of America is a country in North America. It is the third largest country in the world by total area and the third most populous country with over 320 million people. The United States is a federal republic consisting of 50 states and a federal district. The 48 contiguous states and the district of Columbia are in central North America between Canada and Mexico. The state of Alaska is in the"
275
+ ] # fmt: skip
276
+
277
+ model = AutoModelForCausalLM.from_pretrained(
278
+ model_id, attn_implementation="flash_attention_2", torch_dtype="float16"
279
+ ).to(torch_device)
280
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
281
+ inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device)
282
+
283
+ output = model.generate(**inputs, max_new_tokens=100, do_sample=False)
284
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=False)
285
+
286
+ self.assertEqual(output_text, EXPECTED_TEXTS)
287
+
288
+ @slow
289
+ @require_read_token
290
+ def test_export_static_cache(self):
291
+ if version.parse(torch.__version__) < version.parse("2.5.0"):
292
+ self.skipTest(reason="This test requires torch >= 2.5 to run.")
293
+
294
+ from transformers.integrations.executorch import (
295
+ TorchExportableModuleWithStaticCache,
296
+ convert_and_export_with_cache,
297
+ )
298
+
299
+ tokenizer = AutoTokenizer.from_pretrained("google/gemma-2-2b", pad_token="</s>", padding_side="right")
300
+ EXPECTED_TEXT_COMPLETION = [
301
+ "Hello I am doing a project for my school and I need to know how to make a program that will take a number",
302
+ ]
303
+ max_generation_length = tokenizer(EXPECTED_TEXT_COMPLETION, return_tensors="pt", padding=True)[
304
+ "input_ids"
305
+ ].shape[-1]
306
+
307
+ # Load model
308
+ device = "cpu"
309
+ dtype = torch.bfloat16
310
+ cache_implementation = "static"
311
+ attn_implementation = "sdpa"
312
+ batch_size = 1
313
+ model = AutoModelForCausalLM.from_pretrained(
314
+ "google/gemma-2-2b",
315
+ device_map=device,
316
+ torch_dtype=dtype,
317
+ attn_implementation=attn_implementation,
318
+ generation_config=GenerationConfig(
319
+ use_cache=True,
320
+ cache_implementation=cache_implementation,
321
+ max_length=max_generation_length,
322
+ cache_config={
323
+ "batch_size": batch_size,
324
+ "max_cache_len": max_generation_length,
325
+ },
326
+ ),
327
+ )
328
+
329
+ prompts = ["Hello I am doing"]
330
+ prompt_tokens = tokenizer(prompts, return_tensors="pt", padding=True).to(model.device)
331
+ prompt_token_ids = prompt_tokens["input_ids"]
332
+ max_new_tokens = max_generation_length - prompt_token_ids.shape[-1]
333
+
334
+ # Static Cache + export
335
+ exported_program = convert_and_export_with_cache(model)
336
+ ep_generated_ids = TorchExportableModuleWithStaticCache.generate(
337
+ exported_program=exported_program, prompt_token_ids=prompt_token_ids, max_new_tokens=max_new_tokens
338
+ )
339
+ ep_generated_text = tokenizer.batch_decode(ep_generated_ids, skip_special_tokens=True)
340
+ self.assertEqual(EXPECTED_TEXT_COMPLETION, ep_generated_text)
341
+
342
+ @require_read_token
343
+ @tooslow
344
+ def test_model_9b_bf16_flex_attention(self):
345
+ model_id = "google/gemma-2-9b"
346
+ EXPECTED_TEXTS = [
347
+ "<bos>Hello I am doing a project on the 1918 flu pandemic and I am trying to find out how many",
348
+ "<pad><pad><bos>Hi today I'm going to be talking about the history of the United States. The United States of America",
349
+ ]
350
+
351
+ model = AutoModelForCausalLM.from_pretrained(
352
+ model_id, low_cpu_mem_usage=True, torch_dtype=torch.bfloat16, attn_implementation="flex_attention"
353
+ ).to(torch_device)
354
+ assert model.config._attn_implementation == "flex_attention"
355
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
356
+ inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device)
357
+
358
+ output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
359
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=False)
360
+
361
+ self.assertEqual(output_text, EXPECTED_TEXTS)
362
+
363
+ @parameterized.expand([("flash_attention_2",), ("sdpa",), ("flex_attention",), ("eager",)])
364
+ @require_read_token
365
+ def test_generation_beyond_sliding_window(self, attn_implementation: str):
366
+ """Test that we can correctly generate beyond the sliding window. This is non trivial as
367
+ we need to correctly slice the attention mask in all cases (because we use a HybridCache).
368
+ Outputs for every attention functions should be coherent and identical.
369
+ """
370
+ model_id = "google/gemma-2-2b"
371
+ EXPECTED_COMPLETIONS = [
372
+ " the people, the food, the culture, the history, the music, the art, the architecture",
373
+ ", green, yellow, orange, purple, pink, brown, black, white, gray, silver",
374
+ ]
375
+
376
+ input_text = [
377
+ "This is a nice place. " * 800 + "I really enjoy the scenery,", # This is larger than 4096 tokens
378
+ "A list of colors: red, blue", # This will almost all be padding tokens
379
+ ]
380
+ tokenizer = AutoTokenizer.from_pretrained(model_id, padding="left")
381
+ inputs = tokenizer(input_text, padding=True, return_tensors="pt").to(torch_device)
382
+
383
+ model = AutoModelForCausalLM.from_pretrained(
384
+ model_id, attn_implementation=attn_implementation, torch_dtype=torch.float16
385
+ ).to(torch_device)
386
+
387
+ # Make sure prefill is larger than sliding window
388
+ input_size = inputs.input_ids.shape[-1]
389
+ self.assertTrue(input_size > model.config.sliding_window)
390
+
391
+ out = model.generate(**inputs, max_new_tokens=20)[:, input_size:]
392
+ output_text = tokenizer.batch_decode(out)
393
+
394
+ self.assertEqual(output_text, EXPECTED_COMPLETIONS)
tasks/tasksmith-441eeab80047/tests/source/tests/models/gemma3/__init__.py ADDED
File without changes
tasks/tasksmith-441eeab80047/tests/source/tests/models/gemma3/test_image_processing_gemma3.py ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 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
+ import unittest
17
+
18
+ import numpy as np
19
+
20
+ from transformers.image_utils import IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD
21
+ from transformers.testing_utils import require_torch, require_vision
22
+ from transformers.utils import is_torch_available, is_torchvision_available, is_vision_available
23
+
24
+ from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs
25
+
26
+
27
+ if is_torch_available():
28
+ import torch
29
+
30
+ if is_vision_available():
31
+ from PIL import Image
32
+
33
+ from transformers import Gemma3ImageProcessor
34
+
35
+ if is_torchvision_available():
36
+ from transformers import Gemma3ImageProcessorFast
37
+
38
+
39
+ class Gemma3ImageProcessingTester:
40
+ def __init__(
41
+ self,
42
+ parent,
43
+ batch_size=7,
44
+ num_channels=3,
45
+ image_size=18,
46
+ min_resolution=30,
47
+ max_resolution=400,
48
+ do_resize=True,
49
+ size=None,
50
+ do_normalize=True,
51
+ image_mean=IMAGENET_STANDARD_MEAN,
52
+ image_std=IMAGENET_STANDARD_STD,
53
+ do_convert_rgb=True,
54
+ do_pan_and_scan=True,
55
+ pan_and_scan_min_crop_size=10,
56
+ pan_and_scan_max_num_crops=2,
57
+ pan_and_scan_min_ratio_to_activate=1.2,
58
+ ):
59
+ super().__init__()
60
+ size = size if size is not None else {"height": 18, "width": 18}
61
+ self.parent = parent
62
+ self.batch_size = batch_size
63
+ self.num_channels = num_channels
64
+ self.image_size = image_size
65
+ self.min_resolution = min_resolution
66
+ self.max_resolution = max_resolution
67
+ self.do_resize = do_resize
68
+ self.size = size
69
+ self.do_normalize = do_normalize
70
+ self.image_mean = image_mean
71
+ self.image_std = image_std
72
+ self.do_convert_rgb = do_convert_rgb
73
+ self.do_pan_and_scan = do_pan_and_scan
74
+ self.pan_and_scan_min_crop_size = pan_and_scan_min_crop_size
75
+ self.pan_and_scan_max_num_crops = pan_and_scan_max_num_crops
76
+ self.pan_and_scan_min_ratio_to_activate = pan_and_scan_min_ratio_to_activate
77
+
78
+ def prepare_image_processor_dict(self):
79
+ return {
80
+ "do_resize": self.do_resize,
81
+ "size": self.size,
82
+ "do_normalize": self.do_normalize,
83
+ "image_mean": self.image_mean,
84
+ "image_std": self.image_std,
85
+ "do_convert_rgb": self.do_convert_rgb,
86
+ "do_pan_and_scan": self.do_pan_and_scan,
87
+ "pan_and_scan_min_crop_size": self.pan_and_scan_min_crop_size,
88
+ "pan_and_scan_max_num_crops": self.pan_and_scan_max_num_crops,
89
+ "pan_and_scan_min_ratio_to_activate": self.pan_and_scan_min_ratio_to_activate,
90
+ }
91
+
92
+ def expected_output_image_shape(self, images):
93
+ return self.num_channels, self.size["height"], self.size["width"]
94
+
95
+ # Copied from tests.models.clip.test_image_processing_clip.CLIPImageProcessingTester.prepare_image_inputs
96
+ def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
97
+ return prepare_image_inputs(
98
+ batch_size=self.batch_size,
99
+ num_channels=self.num_channels,
100
+ min_resolution=self.min_resolution,
101
+ max_resolution=self.max_resolution,
102
+ equal_resolution=equal_resolution,
103
+ numpify=numpify,
104
+ torchify=torchify,
105
+ )
106
+
107
+
108
+ @require_torch
109
+ @require_vision
110
+ class Gemma3ImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
111
+ image_processing_class = Gemma3ImageProcessor if is_vision_available() else None
112
+ fast_image_processing_class = Gemma3ImageProcessorFast if is_torchvision_available() else None
113
+
114
+ # Copied from tests.models.clip.test_image_processing_clip.CLIPImageProcessingTest.setUp with CLIP->Gemma3
115
+ def setUp(self):
116
+ super().setUp()
117
+ self.image_processor_tester = Gemma3ImageProcessingTester(self)
118
+
119
+ @property
120
+ # Copied from tests.models.clip.test_image_processing_clip.CLIPImageProcessingTest.image_processor_dict
121
+ def image_processor_dict(self):
122
+ return self.image_processor_tester.prepare_image_processor_dict()
123
+
124
+ def test_image_processor_properties(self):
125
+ for image_processing_class in self.image_processor_list:
126
+ image_processing = image_processing_class(**self.image_processor_dict)
127
+ self.assertTrue(hasattr(image_processing, "do_resize"))
128
+ self.assertTrue(hasattr(image_processing, "size"))
129
+ self.assertTrue(hasattr(image_processing, "do_normalize"))
130
+ self.assertTrue(hasattr(image_processing, "image_mean"))
131
+ self.assertTrue(hasattr(image_processing, "image_std"))
132
+ self.assertTrue(hasattr(image_processing, "do_convert_rgb"))
133
+ self.assertTrue(hasattr(image_processing, "do_pan_and_scan"))
134
+ self.assertTrue(hasattr(image_processing, "pan_and_scan_min_crop_size"))
135
+ self.assertTrue(hasattr(image_processing, "pan_and_scan_max_num_crops"))
136
+ self.assertTrue(hasattr(image_processing, "pan_and_scan_min_ratio_to_activate"))
137
+
138
+ def test_image_processor_from_dict_with_kwargs(self):
139
+ for image_processing_class in self.image_processor_list:
140
+ image_processor = image_processing_class.from_dict(self.image_processor_dict)
141
+ self.assertEqual(image_processor.size, {"height": 18, "width": 18})
142
+
143
+ image_processor = image_processing_class.from_dict(self.image_processor_dict, size=84)
144
+ self.assertEqual(image_processor.size, {"height": 84, "width": 84})
145
+
146
+ def test_pan_and_scan(self):
147
+ """
148
+ Enables Pan and Scan path by choosing the correct input image resolution. If you are changing
149
+ image processor attributes for PaS, please update this test.
150
+ """
151
+ for image_processing_class in self.image_processor_list:
152
+ # Initialize image_processing
153
+ image_processing = image_processing_class(**self.image_processor_dict)
154
+ # create random numpy tensors
155
+ """This function prepares a list of PIL images"""
156
+ image_inputs = [np.random.randint(255, size=(3, 300, 600), dtype=np.uint8)] * 3
157
+ image_inputs = [Image.fromarray(np.moveaxis(x, 0, -1)) for x in image_inputs]
158
+
159
+ # Test not batched input, 3 images because we have base image + 2 crops
160
+ encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
161
+ expected_output_image_shape = (3, 3, 18, 18)
162
+ self.assertEqual(tuple(encoded_images.shape), expected_output_image_shape)
163
+
164
+ # Test batched, 9 images because we have base image + 2 crops per each item
165
+ encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values
166
+ expected_output_image_shape = (9, 3, 18, 18)
167
+ self.assertEqual(tuple(encoded_images.shape), expected_output_image_shape)
168
+
169
+ def test_call_pil(self):
170
+ for image_processing_class in self.image_processor_list:
171
+ # Initialize image_processing
172
+ image_processing = image_processing_class(**self.image_processor_dict)
173
+ # create random PIL images
174
+ image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=True)
175
+ for image in image_inputs:
176
+ self.assertIsInstance(image, Image.Image)
177
+
178
+ # Test not batched input
179
+ encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
180
+ expected_output_image_shape = (1, 3, 18, 18)
181
+ self.assertEqual(tuple(encoded_images.shape), expected_output_image_shape)
182
+
183
+ # Test batched
184
+ encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values
185
+ expected_output_image_shape = (7, 3, 18, 18)
186
+ self.assertEqual(tuple(encoded_images.shape), expected_output_image_shape)
187
+
188
+ def test_call_numpy(self):
189
+ for image_processing_class in self.image_processor_list:
190
+ # Initialize image_processing
191
+ image_processing = image_processing_class(**self.image_processor_dict)
192
+ # create random numpy tensors
193
+ image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=True, numpify=True)
194
+ for image in image_inputs:
195
+ self.assertIsInstance(image, np.ndarray)
196
+
197
+ # Test not batched input
198
+ encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
199
+ expected_output_image_shape = (1, 3, 18, 18)
200
+ self.assertEqual(tuple(encoded_images.shape), expected_output_image_shape)
201
+
202
+ # Test batched
203
+ encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values
204
+ expected_output_image_shape = (7, 3, 18, 18)
205
+ self.assertEqual(tuple(encoded_images.shape), expected_output_image_shape)
206
+
207
+ def test_call_pytorch(self):
208
+ for image_processing_class in self.image_processor_list:
209
+ # Initialize image_processing
210
+ image_processing = image_processing_class(**self.image_processor_dict)
211
+ # create random PyTorch tensors
212
+ image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=True, torchify=True)
213
+
214
+ for image in image_inputs:
215
+ self.assertIsInstance(image, torch.Tensor)
216
+
217
+ # Test not batched input
218
+ encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
219
+ expected_output_image_shape = (1, 3, 18, 18)
220
+ self.assertEqual(tuple(encoded_images.shape), expected_output_image_shape)
221
+
222
+ # Test batched
223
+ encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values
224
+ expected_output_image_shape = (7, 3, 18, 18)
225
+ self.assertEqual(tuple(encoded_images.shape), expected_output_image_shape)
226
+
227
+ @unittest.skip("Gemma3 doesn't work with 4 channels due to pan and scan method")
228
+ def test_call_numpy_4_channels(self):
229
+ pass
tasks/tasksmith-441eeab80047/tests/source/tests/models/gemma3/test_modeling_gemma3.py ADDED
@@ -0,0 +1,520 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 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 Gemma3 model."""
16
+
17
+ import unittest
18
+
19
+ from parameterized import parameterized
20
+
21
+ from transformers import (
22
+ AutoModelForCausalLM,
23
+ AutoTokenizer,
24
+ Gemma3Config,
25
+ Gemma3TextConfig,
26
+ is_torch_available,
27
+ )
28
+ from transformers.testing_utils import (
29
+ cleanup,
30
+ require_torch,
31
+ require_torch_gpu,
32
+ slow,
33
+ torch_device,
34
+ )
35
+
36
+ from ...generation.test_utils import GenerationTesterMixin
37
+ from ...models.gemma.test_modeling_gemma import GemmaModelTester
38
+ from ...test_configuration_common import ConfigTester
39
+ from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
40
+
41
+
42
+ if is_torch_available():
43
+ import torch
44
+
45
+ from transformers import (
46
+ Gemma3ForCausalLM,
47
+ Gemma3ForConditionalGeneration,
48
+ Gemma3Processor,
49
+ Gemma3TextModel,
50
+ )
51
+
52
+
53
+ class Gemma3ModelTester(GemmaModelTester):
54
+ if is_torch_available():
55
+ config_class = Gemma3TextConfig
56
+ model_class = Gemma3TextModel
57
+ for_causal_lm_class = Gemma3ForCausalLM
58
+
59
+
60
+ @require_torch
61
+ class Gemma3ModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
62
+ all_model_classes = (Gemma3TextModel, Gemma3ForCausalLM) if is_torch_available() else ()
63
+ all_generative_model_classes = (Gemma3ForCausalLM,) if is_torch_available() else ()
64
+ test_headmasking = False
65
+ test_pruning = False
66
+ _is_stateful = True
67
+ model_split_percents = [0.5, 0.6]
68
+
69
+ def setUp(self):
70
+ self.model_tester = Gemma3ModelTester(self)
71
+ self.config_tester = ConfigTester(self, config_class=Gemma3Config, hidden_size=37)
72
+
73
+ @unittest.skip("Failing because of unique cache (HybridCache)")
74
+ def test_model_outputs_equivalence(self, **kwargs):
75
+ pass
76
+
77
+ @parameterized.expand([("random",), ("same",)])
78
+ @unittest.skip("Gemma3 has HybridCache which is not compatible with assisted decoding")
79
+ def test_assisted_decoding_matches_greedy_search(self, assistant_type):
80
+ pass
81
+
82
+ @unittest.skip("Gemma3 has HybridCache which is not compatible with assisted decoding")
83
+ def test_prompt_lookup_decoding_matches_greedy_search(self, assistant_type):
84
+ pass
85
+
86
+ @unittest.skip("Gemma3 has HybridCache which is not compatible with assisted decoding")
87
+ def test_assisted_decoding_sample(self):
88
+ pass
89
+
90
+ @unittest.skip("Gemma3 has HybridCache which is not compatible with dola decoding")
91
+ def test_dola_decoding_sample(self):
92
+ pass
93
+
94
+ @unittest.skip("Gemma3 has HybridCache and doesn't support continue from past kv")
95
+ def test_generate_continue_from_past_key_values(self):
96
+ pass
97
+
98
+ @unittest.skip("Gemma3 has HybridCache and doesn't support low_memory generation")
99
+ def test_beam_search_low_memory(self):
100
+ pass
101
+
102
+ @unittest.skip("Gemma3 has HybridCache and doesn't support contrastive generation")
103
+ def test_contrastive_generate(self):
104
+ pass
105
+
106
+ @unittest.skip("Gemma3 has HybridCache and doesn't support contrastive generation")
107
+ def test_contrastive_generate_dict_outputs_use_cache(self):
108
+ pass
109
+
110
+ @unittest.skip("Gemma3 has HybridCache and doesn't support contrastive generation")
111
+ def test_contrastive_generate_low_memory(self):
112
+ pass
113
+
114
+ @unittest.skip("Gemma3 has HybridCache and doesn't support StaticCache. Though it could, it shouldn't support.")
115
+ def test_generate_with_static_cache(self):
116
+ pass
117
+
118
+ @unittest.skip("Gemma3 has HybridCache and doesn't support StaticCache. Though it could, it shouldn't support.")
119
+ def test_generate_from_inputs_embeds_with_static_cache(self):
120
+ pass
121
+
122
+ @unittest.skip("Gemma3 has HybridCache and doesn't support StaticCache. Though it could, it shouldn't support.")
123
+ def test_generate_continue_from_inputs_embeds(self):
124
+ pass
125
+
126
+ @unittest.skip("Gemma3 has HybridCache which auto-compiles. Compile and FA2 don't work together.")
127
+ def test_eager_matches_fa2_generate(self):
128
+ pass
129
+
130
+ @unittest.skip(
131
+ reason="HybridCache can't be gathered because it is not iterable. Adding a simple iter and dumping `distributed_iterator`"
132
+ " as in Dynamic Cache doesnt work. NOTE: @gante all cache objects would need better compatibility with multi gpu setting"
133
+ )
134
+ def test_multi_gpu_data_parallel_forward(self):
135
+ pass
136
+
137
+
138
+ class Gemma3Vision2TextModelTester:
139
+ def __init__(
140
+ self,
141
+ parent,
142
+ mm_tokens_per_image=2,
143
+ image_token_index=1,
144
+ boi_token_index=2,
145
+ eoi_token_index=3,
146
+ seq_length=25,
147
+ is_training=True,
148
+ vision_config={
149
+ "use_labels": True,
150
+ "image_size": 20,
151
+ "patch_size": 5,
152
+ "num_channels": 3,
153
+ "is_training": True,
154
+ "hidden_size": 32,
155
+ "num_key_value_heads": 1,
156
+ "num_hidden_layers": 2,
157
+ "num_attention_heads": 4,
158
+ "intermediate_size": 37,
159
+ "dropout": 0.1,
160
+ "attention_dropout": 0.1,
161
+ "initializer_range": 0.02,
162
+ },
163
+ use_cache=False,
164
+ ):
165
+ self.parent = parent
166
+ # `image_token_index` is set to 0 to pass "resize_embeddings" test, do not modify
167
+ self.mm_tokens_per_image = mm_tokens_per_image
168
+ self.image_token_index = image_token_index
169
+ self.boi_token_index = boi_token_index
170
+ self.eoi_token_index = eoi_token_index
171
+ self.llm_tester = Gemma3ModelTester(self.parent)
172
+ self.text_config = self.llm_tester.get_config()
173
+ self.vision_config = vision_config
174
+ self.seq_length = seq_length
175
+ self.pad_token_id = self.text_config.pad_token_id
176
+
177
+ self.num_hidden_layers = self.text_config.num_hidden_layers
178
+ self.vocab_size = self.text_config.vocab_size
179
+ self.hidden_size = self.text_config.hidden_size
180
+ self.num_attention_heads = self.text_config.num_attention_heads
181
+ self.is_training = is_training
182
+
183
+ self.batch_size = 3
184
+ self.num_channels = vision_config["num_channels"]
185
+ self.image_size = vision_config["image_size"]
186
+ self.encoder_seq_length = seq_length
187
+ self.use_cache = use_cache
188
+
189
+ def get_config(self):
190
+ return Gemma3Config(
191
+ text_config=self.text_config,
192
+ vision_config=self.vision_config,
193
+ image_token_index=self.image_token_index,
194
+ boi_token_index=self.boi_token_index,
195
+ eoi_token_index=self.eoi_token_index,
196
+ mm_tokens_per_image=self.mm_tokens_per_image,
197
+ )
198
+
199
+ def prepare_config_and_inputs(self):
200
+ pixel_values = floats_tensor(
201
+ [
202
+ self.batch_size,
203
+ self.vision_config["num_channels"],
204
+ self.vision_config["image_size"],
205
+ self.vision_config["image_size"],
206
+ ]
207
+ )
208
+ config = self.get_config()
209
+
210
+ return config, pixel_values
211
+
212
+ def prepare_config_and_inputs_for_common(self):
213
+ config_and_inputs = self.prepare_config_and_inputs()
214
+ config, pixel_values = config_and_inputs
215
+ input_ids = ids_tensor([self.batch_size, self.seq_length], config.text_config.vocab_size - 1) + 1
216
+ attention_mask = input_ids.ne(self.pad_token_id).to(torch_device)
217
+
218
+ # set the 3 first tokens to be image, and ensure that no other tokens are image tokens
219
+ # do not change this unless you modified image size or patch size
220
+ input_ids[input_ids == config.image_token_index] = self.pad_token_id
221
+ input_ids[:, :1] = config.image_token_index
222
+
223
+ token_type_ids = torch.zeros_like(input_ids)
224
+ token_type_ids[input_ids == config.image_token_index] = 1
225
+
226
+ inputs_dict = {
227
+ "pixel_values": pixel_values,
228
+ "input_ids": input_ids,
229
+ "attention_mask": attention_mask,
230
+ "token_type_ids": token_type_ids,
231
+ }
232
+ return config, inputs_dict
233
+
234
+
235
+ @require_torch
236
+ class Gemma3Vision2TextModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
237
+ all_model_classes = (Gemma3ForConditionalGeneration,) if is_torch_available() else ()
238
+ all_generative_model_classes = (Gemma3ForConditionalGeneration,) if is_torch_available() else ()
239
+ test_headmasking = False
240
+ test_pruning = False
241
+ test_missing_keys = False
242
+ _is_stateful = True
243
+ model_split_percents = [0.5, 0.6]
244
+
245
+ # MP works but offload doesn't work when the SigLIP MultiheadAttention is offloaded
246
+ # TODO: One potential solution would be to add to set preload_module_classes = ["SiglipMultiheadAttentionPoolingHead"]
247
+ # in the dispatch_model function
248
+ test_cpu_offload = False
249
+ test_disk_offload_safetensors = False
250
+ test_disk_offload_bin = False
251
+
252
+ def setUp(self):
253
+ self.model_tester = Gemma3Vision2TextModelTester(self)
254
+ self.config_tester = ConfigTester(self, config_class=Gemma3Config, hidden_size=37)
255
+
256
+ @unittest.skip(reason="SiglipVisionModel (vision backbone) does not support standalone training")
257
+ def test_training_gradient_checkpointing(self):
258
+ pass
259
+
260
+ @unittest.skip(reason="SiglipVisionModel (vision backbone) does not support standalone training")
261
+ def test_training_gradient_checkpointing_use_reentrant(self):
262
+ pass
263
+
264
+ @unittest.skip(reason="SiglipVisionModel (vision backbone) does not support standalone training")
265
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
266
+ pass
267
+
268
+ @unittest.skip(
269
+ reason="HybridCache can't be gathered because it is not iterable. Adding a simple iter and dumping `distributed_iterator`"
270
+ " as in Dynamic Cache doesnt work. NOTE: @gante all cache objects would need better compatibility with multi gpu setting"
271
+ )
272
+ def test_multi_gpu_data_parallel_forward(self):
273
+ pass
274
+
275
+ @unittest.skip("Failing because of unique cache (HybridCache)")
276
+ def test_model_outputs_equivalence(self, **kwargs):
277
+ pass
278
+
279
+ @parameterized.expand([("random",), ("same",)])
280
+ @unittest.skip("Gemma3 has HybridCache which is not compatible with assisted decoding")
281
+ def test_assisted_decoding_matches_greedy_search(self, assistant_type):
282
+ pass
283
+
284
+ @unittest.skip("Gemma3 has HybridCache which is not compatible with assisted decoding")
285
+ def test_prompt_lookup_decoding_matches_greedy_search(self, assistant_type):
286
+ pass
287
+
288
+ @unittest.skip("Gemma3 has HybridCache which is not compatible with assisted decoding")
289
+ def test_assisted_decoding_sample(self):
290
+ pass
291
+
292
+ @unittest.skip("Gemma3 has HybridCache which is not compatible with dola decoding")
293
+ def test_dola_decoding_sample(self):
294
+ pass
295
+
296
+ @unittest.skip("Gemma3 has HybridCache and doesn't support continue from past kv")
297
+ def test_generate_continue_from_past_key_values(self):
298
+ pass
299
+
300
+ @unittest.skip("Gemma3 has HybridCache and doesn't support low_memory generation")
301
+ def test_beam_search_low_memory(self):
302
+ pass
303
+
304
+ @unittest.skip("Gemma3 has HybridCache and doesn't support contrastive generation")
305
+ def test_contrastive_generate(self):
306
+ pass
307
+
308
+ @unittest.skip("Gemma3 has HybridCache and doesn't support contrastive generation")
309
+ def test_contrastive_generate_dict_outputs_use_cache(self):
310
+ pass
311
+
312
+ @unittest.skip("Gemma3 has HybridCache and doesn't support contrastive generation")
313
+ def test_contrastive_generate_low_memory(self):
314
+ pass
315
+
316
+ @unittest.skip("Gemma3 has HybridCache and doesn't support StaticCache. Though it could, it shouldn't support.")
317
+ def test_generate_with_static_cache(self):
318
+ pass
319
+
320
+ @unittest.skip("Gemma3 has HybridCache and doesn't support StaticCache. Though it could, it shouldn't support.")
321
+ def test_generate_from_inputs_embeds_with_static_cache(self):
322
+ pass
323
+
324
+ @unittest.skip(
325
+ reason="Siglip (vision backbone) uses the same initialization scheme as the Flax original implementation"
326
+ )
327
+ def test_initialization(self):
328
+ pass
329
+
330
+ @unittest.skip(
331
+ reason="Siglip has no FLEX attention, and we don't have a proper way to set/test attn in VLMs. TODO @raushan"
332
+ )
333
+ def test_flex_attention_with_grads(self):
334
+ pass
335
+
336
+
337
+ @slow
338
+ @require_torch_gpu
339
+ # @require_read_token
340
+ class Gemma3IntegrationTest(unittest.TestCase):
341
+ def setUp(self):
342
+ self.processor = Gemma3Processor.from_pretrained("gg-hf-g/gemma-3-4b-it", padding_side="left")
343
+
344
+ url = "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/cow_beach_1.png"
345
+ self.messages = [
346
+ {"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant."}]},
347
+ {
348
+ "role": "user",
349
+ "content": [
350
+ {"type": "image", "url": url},
351
+ {"type": "text", "text": "What is shown in this image?"},
352
+ ],
353
+ },
354
+ ]
355
+
356
+ def tearDown(self):
357
+ cleanup(torch_device, gc_collect=True)
358
+
359
+ def test_model_4b_bf16(self):
360
+ model_id = "gg-hf-g/gemma-3-4b-it"
361
+
362
+ model = Gemma3ForConditionalGeneration.from_pretrained(
363
+ model_id, low_cpu_mem_usage=True, torch_dtype=torch.bfloat16
364
+ ).to(torch_device)
365
+
366
+ inputs = self.processor.apply_chat_template(
367
+ self.messages,
368
+ tokenize=True,
369
+ return_dict=True,
370
+ return_tensors="pt",
371
+ add_generation_prompt=True,
372
+ ).to(torch_device)
373
+
374
+ output = model.generate(**inputs, max_new_tokens=30, do_sample=False)
375
+ output_text = self.processor.batch_decode(output, skip_special_tokens=True)
376
+
377
+ EXPECTED_TEXTS = ['user\nYou are a helpful assistant.\n\n\n\n\n\nWhat is shown in this image?\nmodel\nCertainly! \n\nThe image shows a brown cow standing on a sandy beach with clear blue water and a blue sky in the background. It looks like'] # fmt: skip
378
+ self.assertEqual(output_text, EXPECTED_TEXTS)
379
+
380
+ def test_model_4b_batch(self):
381
+ model_id = "gg-hf-g/gemma-3-4b-it"
382
+
383
+ model = Gemma3ForConditionalGeneration.from_pretrained(
384
+ model_id, low_cpu_mem_usage=True, torch_dtype=torch.bfloat16
385
+ ).to(torch_device)
386
+
387
+ messages_2 = [
388
+ {"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant."}]},
389
+ {
390
+ "role": "user",
391
+ "content": [
392
+ {
393
+ "type": "image",
394
+ "url": "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/cow_beach_1.png",
395
+ },
396
+ {"type": "image", "url": "https://www.ilankelman.org/stopsigns/australia.jpg"},
397
+ {"type": "text", "text": "Are these images identical?"},
398
+ ],
399
+ },
400
+ ]
401
+
402
+ inputs = self.processor.apply_chat_template(
403
+ [self.messages, messages_2],
404
+ tokenize=True,
405
+ return_dict=True,
406
+ return_tensors="pt",
407
+ padding=True,
408
+ add_generation_prompt=True,
409
+ ).to(torch_device)
410
+
411
+ output = model.generate(**inputs, max_new_tokens=30, do_sample=False)
412
+ output_text = self.processor.batch_decode(output, skip_special_tokens=True)
413
+
414
+ EXPECTED_TEXTS = [
415
+ 'user\nYou are a helpful assistant.\n\n\n\n\n\nWhat is shown in this image?\nmodel\nCertainly! \n\nThe image shows a brown cow standing on a sandy beach with clear turquoise water and a blue sky in the background. It looks like',
416
+ "user\nYou are a helpful assistant.\n\n\n\n\n\n\n\n\n\nAre these images identical?\nmodel\nNo, these images are not identical. \n\nHere's a breakdown of the differences:\n\n* **Image 1:** Shows a cow"
417
+ ] # fmt: skip
418
+ self.assertEqual(output_text, EXPECTED_TEXTS)
419
+
420
+ def test_model_4b_multiimage(self):
421
+ model_id = "gg-hf-g/gemma-3-4b-it"
422
+
423
+ model = Gemma3ForConditionalGeneration.from_pretrained(
424
+ model_id, low_cpu_mem_usage=True, torch_dtype=torch.bfloat16
425
+ ).to(torch_device)
426
+
427
+ messages = [
428
+ {"role": "system", "content": [{"type": "text", "text": "You are a helpful assistant."}]},
429
+ {
430
+ "role": "user",
431
+ "content": [
432
+ {"type": "image", "url": "https://www.ilankelman.org/stopsigns/australia.jpg"},
433
+ {"type": "text", "text": "What do you see here?"},
434
+ ],
435
+ },
436
+ ]
437
+
438
+ inputs = self.processor.apply_chat_template(
439
+ messages,
440
+ tokenize=True,
441
+ return_dict=True,
442
+ return_tensors="pt",
443
+ padding=True,
444
+ add_generation_prompt=True,
445
+ ).to(torch_device)
446
+
447
+ output = model.generate(**inputs, max_new_tokens=30, do_sample=False)
448
+ output_text = self.processor.batch_decode(output, skip_special_tokens=True)
449
+
450
+ EXPECTED_TEXTS = ["user\nYou are a helpful assistant.\n\n\n\n\n\nWhat do you see here?\nmodel\nOkay, let's break down what I see in this image:\n\n**Overall Scene:**\n\nIt looks like a street scene in a vibrant,"] # fmt: skip
451
+ self.assertEqual(output_text, EXPECTED_TEXTS)
452
+
453
+ def test_model_1b_text_only(self):
454
+ model_id = "gg-hf-g/gemma-3-1b-it"
455
+
456
+ model = Gemma3ForCausalLM.from_pretrained(model_id, low_cpu_mem_usage=True, torch_dtype=torch.bfloat16).to(
457
+ torch_device
458
+ )
459
+ tokenizer = AutoTokenizer.from_pretrained(model_id, padding_side="left")
460
+ inputs = tokenizer("Write a poem about Machine Learning.", return_tensors="pt").to(torch_device)
461
+
462
+ output = model.generate(**inputs, max_new_tokens=30, do_sample=False)
463
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=True)
464
+
465
+ EXPECTED_TEXTS = ['Write a poem about Machine Learning.\n\n---\n\nThe data flows, a river deep,\nWith patterns hidden, secrets sleep.\nA neural net, a watchful eye,\nLearning'] # fmt: skip
466
+ self.assertEqual(output_text, EXPECTED_TEXTS)
467
+
468
+ # TODO: raushan FA2 generates gibberish for no reason, check later
469
+ # @require_flash_attn
470
+ # @require_torch_gpu
471
+ # @mark.flash_attn_test
472
+ # def test_model_4b_flash_attn(self):
473
+ # model_id = "gg-hf-g/gemma-3-4b-it"
474
+ #
475
+ # model = Gemma3ForConditionalGeneration.from_pretrained(
476
+ # model_id, torch_dtype=torch.bfloat16, attn_implementation="flash_attention_2"
477
+ # ).to(torch_device)
478
+ #
479
+ # inputs = self.processor.apply_chat_template(
480
+ # self.messages,
481
+ # tokenize=True,
482
+ # return_dict=True,
483
+ # return_tensors="pt",
484
+ # add_generation_prompt=True,
485
+ # ).to(torch_device)
486
+ #
487
+ # output = model.generate(**inputs, max_new_tokens=30, do_sample=False)
488
+ # output_text = self.processor.batch_decode(output, skip_special_tokens=True)
489
+ #
490
+ # EXPECTED_TEXTS = ['user\nYou are a helpful assistant.\n\n\n\n\n\nWhat is shown in this image?\nmodel\nPlease look out that you are what Grammy and Vi- ||.xfairesr--ith alerts themselves are||ِّ\n\n**General Note:**'] # fmt: skip
491
+ # self.assertEqual(output_text, EXPECTED_TEXTS)
492
+
493
+ @parameterized.expand([("flash_attention_2",), ("sdpa",), ("eager",)])
494
+ def test_generation_beyond_sliding_window(self, attn_implementation: str):
495
+ """Test that we can correctly generate beyond the sliding window. This is non trivial as
496
+ we need to correctly slice the attention mask in all cases (because we use a HybridCache).
497
+ Outputs for every attention functions should be coherent and identical.
498
+ """
499
+ model_id = "gg-hf-g/gemma-3-1b-it"
500
+
501
+ input_text = [
502
+ "This is a nice place. " * 800 + "I really enjoy the scenery,", # This is larger than 4096 tokens
503
+ "A list of colors: red, blue", # This will almost all be padding tokens
504
+ ]
505
+ tokenizer = AutoTokenizer.from_pretrained(model_id, padding="left")
506
+ inputs = tokenizer(input_text, padding=True, return_tensors="pt").to(torch_device)
507
+
508
+ model = AutoModelForCausalLM.from_pretrained(
509
+ model_id, attn_implementation=attn_implementation, torch_dtype=torch.float16
510
+ ).to(torch_device)
511
+
512
+ # Make sure prefill is larger than sliding window
513
+ input_size = inputs.input_ids.shape[-1]
514
+ self.assertTrue(input_size > model.config.sliding_window)
515
+
516
+ out = model.generate(**inputs, max_new_tokens=20)[:, input_size:]
517
+ output_text = tokenizer.batch_decode(out)
518
+
519
+ EXPECTED_COMPLETIONS = [" and I'm going to take a walk.\n\nI really enjoy the scenery, and I'", ", green, yellow, orange, purple, brown, black, white, gray.\n\nI'"] # fmt: skip
520
+ self.assertEqual(output_text, EXPECTED_COMPLETIONS)
tasks/tasksmith-441eeab80047/tests/source/tests/models/gemma3/test_processing_gemma3.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 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 shutil
16
+ import tempfile
17
+ import unittest
18
+ from typing import Optional
19
+
20
+ from transformers import Gemma3Processor, GemmaTokenizer
21
+ from transformers.testing_utils import get_tests_dir, require_vision
22
+ from transformers.utils import is_vision_available
23
+
24
+ from ...test_processing_common import ProcessorTesterMixin
25
+
26
+
27
+ if is_vision_available():
28
+ from transformers import Gemma3ImageProcessor
29
+
30
+ SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model")
31
+
32
+
33
+ @require_vision
34
+ class Gemma3ProcessorTest(ProcessorTesterMixin, unittest.TestCase):
35
+ processor_class = Gemma3Processor
36
+
37
+ def setUp(self):
38
+ self.tmpdirname = tempfile.mkdtemp()
39
+ gemma3_image_processor_kwargs = {
40
+ "do_pan_and_scan": True,
41
+ "pan_and_scan_min_crop_size": 256,
42
+ "pan_and_scan_max_num_crops": 4,
43
+ "pan_and_scan_min_ratio_to_activate": 1.2,
44
+ }
45
+ image_processor = Gemma3ImageProcessor.from_pretrained(
46
+ "google/siglip-so400m-patch14-384", **gemma3_image_processor_kwargs
47
+ )
48
+
49
+ extra_special_tokens = {
50
+ "image_token": "<image_soft_token>",
51
+ "boi_token": "<start_of_image>",
52
+ "eoi_token": "<end_of_image>",
53
+ }
54
+ tokenizer = GemmaTokenizer(SAMPLE_VOCAB, keep_accents=True, extra_special_tokens=extra_special_tokens)
55
+ processor_kwargs = self.prepare_processor_dict()
56
+ processor = Gemma3Processor(image_processor=image_processor, tokenizer=tokenizer, **processor_kwargs)
57
+ processor.save_pretrained(self.tmpdirname)
58
+
59
+ def tearDown(self):
60
+ shutil.rmtree(self.tmpdirname)
61
+
62
+ # TODO: raushan or arthur: add the real chat template
63
+ def prepare_processor_dict(self):
64
+ return {
65
+ "chat_template": "{{ bos_token }}\n{%- if messages[0]['role'] == 'system' -%}\n {%- set first_user_prefix = messages[0]['content'][0]['text'] + '\n\n' -%}\n {%- set loop_messages = messages[1:] -%}\n{%- else -%}\n {%- set first_user_prefix = \"\" -%}\n {%- set loop_messages = messages -%}\n{%- endif -%}\n{%- for message in loop_messages -%}\n {%- if (message['role'] == 'user') != (loop.index0 % 2 == 0) -%}\n {{ raise_exception(\"Conversation roles must alternate user/assistant/user/assistant/...\") }}\n {%- endif -%}\n {%- if (message['role'] == 'assistant') -%}\n {%- set role = \"model\" -%}\n {%- else -%}\n {%- set role = message['role'] -%}\n {%- endif -%}\n {{ '<start_of_turn>' + role + '\n' + (first_user_prefix if loop.first else \"\") }}\n {%- if message['content'] is string -%}\n {{ message['content'] | trim }}\n {%- elif message['content'] is iterable -%}\n {%- for item in message['content'] -%}\n {%- if item['type'] == 'image' -%}\n {{ '<start_of_image>' }}\n {%- elif item['type'] == 'text' -%}\n {{ item['text'] | trim }}\n {%- endif -%}\n {%- endfor -%}\n {%- else -%}\n {{ raise_exception(\"Invalid content type\") }}\n {%- endif -%}\n {{ '<end_of_turn>\n' }}\n{%- endfor -%}\n{%- if add_generation_prompt -%}\n {{'<start_of_turn>model\n'}}\n{%- endif -%}\n", "image_seq_length": 3,
66
+ } # fmt: skip
67
+
68
+ # Override as VLMs need image tokens in prompts
69
+ def prepare_text_inputs(self, batch_size: Optional[int] = None):
70
+ if batch_size is None:
71
+ return "lower newer <start_of_image>"
72
+
73
+ if batch_size < 1:
74
+ raise ValueError("batch_size must be greater than 0")
75
+
76
+ if batch_size == 1:
77
+ return ["lower newer <start_of_image>"]
78
+ return ["lower newer <start_of_image>", "<start_of_image> upper older longer string"] + [
79
+ "<start_of_image> lower newer"
80
+ ] * (batch_size - 2)
81
+
82
+ # Override as Gemma3 needs images to be an explicitly nested batch
83
+ def prepare_image_inputs(self, batch_size: Optional[int] = None):
84
+ """This function prepares a list of PIL images for testing"""
85
+ images = super().prepare_image_inputs(batch_size)
86
+ if isinstance(images, (list, tuple)):
87
+ images = [[image] for image in images]
88
+ return images
89
+
90
+ def test_text_with_image_tokens(self):
91
+ image_processor = self.get_component("image_processor")
92
+ tokenizer = self.get_component("tokenizer")
93
+
94
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
95
+ text_multi_images = f"{processor.boi_token}{processor.boi_token}Dummy text!"
96
+ text_single_image = f"{processor.boi_token}Dummy text!"
97
+ text_no_image = "Dummy text!"
98
+
99
+ image = self.prepare_image_inputs()
100
+
101
+ # If text has no image tokens, iamge should be `None`
102
+ with self.assertRaises(ValueError):
103
+ _ = processor(text=text_no_image, images=image, return_tensors="np")
104
+
105
+ # We can't be sure what is users intention: if user wants one image per text OR two images for first text and no image for second text
106
+ with self.assertRaises(ValueError):
107
+ _ = processor(text=[text_single_image, text_single_image], images=[image, image], return_tensors="np")
108
+
109
+ # The users is expected to be explicit about which image belong to which text by nesting the images list
110
+ out_multiimages = processor(text=text_multi_images, images=[image, image], return_tensors="np")
111
+ out_batch_oneimage = processor(
112
+ text=[text_single_image, text_single_image], images=[[image], [image]], return_tensors="np"
113
+ )
114
+ self.assertListEqual(
115
+ out_batch_oneimage[self.images_input_name].tolist(), out_multiimages[self.images_input_name].tolist()
116
+ )
117
+
118
+ def test_pan_and_scan(self):
119
+ processor_components = self.prepare_components()
120
+ processor_kwargs = self.prepare_processor_dict()
121
+ processor = self.processor_class(**processor_components, **processor_kwargs)
122
+
123
+ input_str = self.prepare_text_inputs()
124
+ image_input = self.prepare_image_inputs()
125
+ inputs = processor(
126
+ text=input_str,
127
+ images=image_input,
128
+ return_tensors="np",
129
+ do_pan_and_scan=True,
130
+ image_seq_length=2,
131
+ pan_and_scan_min_crop_size=10,
132
+ )
133
+
134
+ # base image + 4 crops
135
+ self.assertEqual(len(inputs[self.images_input_name]), 5)
136
+ self.assertEqual(len(inputs[self.text_input_name][0]), 67)
tasks/tasksmith-441eeab80047/tests/source/tests/models/git/__init__.py ADDED
File without changes
tasks/tasksmith-441eeab80047/tests/source/tests/models/git/test_modeling_git.py ADDED
@@ -0,0 +1,630 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 inspect
17
+ import unittest
18
+
19
+ from huggingface_hub import hf_hub_download
20
+
21
+ from transformers import GitConfig, GitProcessor, GitVisionConfig, is_torch_available, is_vision_available
22
+ from transformers.models.auto import get_values
23
+ from transformers.testing_utils import require_torch, require_vision, slow, torch_device
24
+
25
+ from ...generation.test_utils import GenerationTesterMixin
26
+ from ...test_configuration_common import ConfigTester
27
+ from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
28
+ from ...test_pipeline_mixin import PipelineTesterMixin
29
+
30
+
31
+ if is_torch_available():
32
+ import torch
33
+ from torch import nn
34
+
35
+ from transformers import MODEL_FOR_CAUSAL_LM_MAPPING, GitForCausalLM, GitModel, GitVisionModel
36
+
37
+
38
+ if is_vision_available():
39
+ from PIL import Image
40
+
41
+
42
+ class GitVisionModelTester:
43
+ def __init__(
44
+ self,
45
+ parent,
46
+ batch_size=12,
47
+ image_size=32,
48
+ patch_size=16,
49
+ num_channels=3,
50
+ is_training=True,
51
+ hidden_size=32,
52
+ projection_dim=32,
53
+ num_hidden_layers=2,
54
+ num_attention_heads=4,
55
+ intermediate_size=37,
56
+ dropout=0.1,
57
+ attention_dropout=0.1,
58
+ initializer_range=0.02,
59
+ scope=None,
60
+ ):
61
+ self.parent = parent
62
+ self.batch_size = batch_size
63
+ self.image_size = image_size
64
+ self.patch_size = patch_size
65
+ self.num_channels = num_channels
66
+ self.is_training = is_training
67
+ self.hidden_size = hidden_size
68
+ self.projection_dim = projection_dim
69
+ self.num_hidden_layers = num_hidden_layers
70
+ self.num_attention_heads = num_attention_heads
71
+ self.intermediate_size = intermediate_size
72
+ self.dropout = dropout
73
+ self.attention_dropout = attention_dropout
74
+ self.initializer_range = initializer_range
75
+ self.scope = scope
76
+
77
+ # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
78
+ num_patches = (image_size // patch_size) ** 2
79
+ self.seq_length = num_patches + 1
80
+
81
+ def prepare_config_and_inputs(self):
82
+ pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
83
+ config = self.get_config()
84
+
85
+ return config, pixel_values
86
+
87
+ def get_config(self):
88
+ return GitVisionConfig(
89
+ image_size=self.image_size,
90
+ patch_size=self.patch_size,
91
+ num_channels=self.num_channels,
92
+ hidden_size=self.hidden_size,
93
+ projection_dim=self.projection_dim,
94
+ num_hidden_layers=self.num_hidden_layers,
95
+ num_attention_heads=self.num_attention_heads,
96
+ intermediate_size=self.intermediate_size,
97
+ dropout=self.dropout,
98
+ attention_dropout=self.attention_dropout,
99
+ initializer_range=self.initializer_range,
100
+ )
101
+
102
+ def create_and_check_model(self, config, pixel_values):
103
+ model = GitVisionModel(config=config)
104
+ model.to(torch_device)
105
+ model.eval()
106
+ with torch.no_grad():
107
+ result = model(pixel_values)
108
+ # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
109
+ image_size = (self.image_size, self.image_size)
110
+ patch_size = (self.patch_size, self.patch_size)
111
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
112
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, num_patches + 1, self.hidden_size))
113
+
114
+ def prepare_config_and_inputs_for_common(self):
115
+ config_and_inputs = self.prepare_config_and_inputs()
116
+ config, pixel_values = config_and_inputs
117
+ inputs_dict = {"pixel_values": pixel_values}
118
+ return config, inputs_dict
119
+
120
+
121
+ @require_torch
122
+ class GitVisionModelTest(ModelTesterMixin, unittest.TestCase):
123
+ """
124
+ Here we also overwrite some of the tests of test_modeling_common.py, as GIT does not use input_ids, inputs_embeds,
125
+ attention_mask and seq_length.
126
+ """
127
+
128
+ all_model_classes = (GitVisionModel,) if is_torch_available() else ()
129
+ fx_compatible = True
130
+ test_pruning = False
131
+ test_resize_embeddings = False
132
+ test_head_masking = False
133
+
134
+ def setUp(self):
135
+ self.model_tester = GitVisionModelTester(self)
136
+ self.config_tester = ConfigTester(self, config_class=GitVisionConfig, has_text_modality=False, hidden_size=37)
137
+
138
+ def test_config(self):
139
+ self.config_tester.run_common_tests()
140
+
141
+ @unittest.skip(reason="GIT does not use inputs_embeds")
142
+ def test_inputs_embeds(self):
143
+ pass
144
+
145
+ def test_model_get_set_embeddings(self):
146
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
147
+
148
+ for model_class in self.all_model_classes:
149
+ model = model_class(config)
150
+ self.assertIsInstance(model.get_input_embeddings(), (nn.Module))
151
+ x = model.get_output_embeddings()
152
+ self.assertTrue(x is None or isinstance(x, nn.Linear))
153
+
154
+ def test_forward_signature(self):
155
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
156
+
157
+ for model_class in self.all_model_classes:
158
+ model = model_class(config)
159
+ signature = inspect.signature(model.forward)
160
+ # signature.parameters is an OrderedDict => so arg_names order is deterministic
161
+ arg_names = [*signature.parameters.keys()]
162
+
163
+ expected_arg_names = ["pixel_values"]
164
+ self.assertListEqual(arg_names[:1], expected_arg_names)
165
+
166
+ def test_model(self):
167
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
168
+ self.model_tester.create_and_check_model(*config_and_inputs)
169
+
170
+ @unittest.skip
171
+ def test_training(self):
172
+ pass
173
+
174
+ @unittest.skip
175
+ def test_training_gradient_checkpointing(self):
176
+ pass
177
+
178
+ @unittest.skip(
179
+ reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
180
+ )
181
+ def test_training_gradient_checkpointing_use_reentrant(self):
182
+ pass
183
+
184
+ @unittest.skip(
185
+ reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
186
+ )
187
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
188
+ pass
189
+
190
+ @unittest.skip(reason="GitVisionModel has no base class and is not available in MODEL_MAPPING")
191
+ def test_save_load_fast_init_from_base(self):
192
+ pass
193
+
194
+ @unittest.skip(reason="GitVisionModel has no base class and is not available in MODEL_MAPPING")
195
+ def test_save_load_fast_init_to_base(self):
196
+ pass
197
+
198
+ @slow
199
+ def test_model_from_pretrained(self):
200
+ model_name = "microsoft/git-base"
201
+ model = GitVisionModel.from_pretrained(model_name)
202
+ self.assertIsNotNone(model)
203
+
204
+
205
+ class GitModelTester:
206
+ def __init__(
207
+ self,
208
+ parent,
209
+ num_channels=3,
210
+ image_size=32,
211
+ patch_size=16,
212
+ batch_size=13,
213
+ text_seq_length=7,
214
+ is_training=True,
215
+ use_input_mask=True,
216
+ use_labels=True,
217
+ vocab_size=99,
218
+ hidden_size=32,
219
+ num_hidden_layers=2,
220
+ num_attention_heads=4,
221
+ intermediate_size=37,
222
+ hidden_act="gelu",
223
+ hidden_dropout_prob=0.1,
224
+ attention_probs_dropout_prob=0.1,
225
+ max_position_embeddings=512,
226
+ type_vocab_size=16,
227
+ initializer_range=0.02,
228
+ num_labels=3,
229
+ scope=None,
230
+ ):
231
+ self.parent = parent
232
+ self.num_channels = num_channels
233
+ self.image_size = image_size
234
+ self.patch_size = patch_size
235
+ self.batch_size = batch_size
236
+ self.text_seq_length = text_seq_length
237
+ self.is_training = is_training
238
+ self.use_input_mask = use_input_mask
239
+ self.use_labels = use_labels
240
+ self.vocab_size = vocab_size
241
+ self.hidden_size = hidden_size
242
+ self.num_hidden_layers = num_hidden_layers
243
+ self.num_attention_heads = num_attention_heads
244
+ self.intermediate_size = intermediate_size
245
+ self.hidden_act = hidden_act
246
+ self.hidden_dropout_prob = hidden_dropout_prob
247
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
248
+ self.max_position_embeddings = max_position_embeddings
249
+ self.type_vocab_size = type_vocab_size
250
+ self.initializer_range = initializer_range
251
+ self.num_labels = num_labels
252
+ self.scope = scope
253
+
254
+ # make sure the BOS, EOS and PAD tokens are within the vocab
255
+ self.bos_token_id = vocab_size - 1
256
+ self.eos_token_id = vocab_size - 1
257
+ self.pad_token_id = vocab_size - 1
258
+
259
+ # for GIT, the sequence length is the sum of the text and patch tokens, + 1 due to the CLS token
260
+ self.seq_length = self.text_seq_length + int((self.image_size / self.patch_size) ** 2) + 1
261
+
262
+ def prepare_config_and_inputs(self):
263
+ input_ids = ids_tensor([self.batch_size, self.text_seq_length], self.vocab_size)
264
+
265
+ input_mask = None
266
+ if self.use_input_mask:
267
+ input_mask = random_attention_mask([self.batch_size, self.text_seq_length])
268
+
269
+ pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
270
+
271
+ config = self.get_config()
272
+
273
+ return config, input_ids, input_mask, pixel_values
274
+
275
+ def get_config(self):
276
+ """
277
+ Returns a tiny configuration by default.
278
+ """
279
+ return GitConfig(
280
+ vision_config={
281
+ "num_channels": self.num_channels,
282
+ "image_size": self.image_size,
283
+ "patch_size": self.patch_size,
284
+ "hidden_size": self.hidden_size,
285
+ "projection_dim": 32,
286
+ "num_hidden_layers": self.num_hidden_layers,
287
+ "num_attention_heads": self.num_attention_heads,
288
+ },
289
+ vocab_size=self.vocab_size,
290
+ hidden_size=self.hidden_size,
291
+ num_hidden_layers=self.num_hidden_layers,
292
+ num_attention_heads=self.num_attention_heads,
293
+ intermediate_size=self.intermediate_size,
294
+ hidden_act=self.hidden_act,
295
+ hidden_dropout_prob=self.hidden_dropout_prob,
296
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
297
+ max_position_embeddings=self.max_position_embeddings,
298
+ initializer_range=self.initializer_range,
299
+ bos_token_id=self.bos_token_id,
300
+ eos_token_id=self.eos_token_id,
301
+ pad_token_id=self.pad_token_id,
302
+ )
303
+
304
+ def create_and_check_model(self, config, input_ids, input_mask, pixel_values):
305
+ model = GitModel(config=config)
306
+ model.to(torch_device)
307
+ model.eval()
308
+
309
+ # inference with pixel values
310
+ result = model(input_ids, attention_mask=input_mask, pixel_values=pixel_values)
311
+
312
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
313
+
314
+ # inference without pixel values
315
+ result = model(input_ids, attention_mask=input_mask)
316
+ result = model(input_ids)
317
+
318
+ self.parent.assertEqual(
319
+ result.last_hidden_state.shape, (self.batch_size, self.text_seq_length, self.hidden_size)
320
+ )
321
+
322
+ def create_and_check_for_causal_lm(self, config, input_ids, input_mask, pixel_values):
323
+ model = GitForCausalLM(config=config)
324
+ model.to(torch_device)
325
+ model.eval()
326
+
327
+ # inference with pixel values
328
+ result = model(input_ids, attention_mask=input_mask, pixel_values=pixel_values)
329
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
330
+
331
+ # inference without pixel values
332
+ result = model(input_ids, attention_mask=input_mask)
333
+ result = model(input_ids)
334
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.text_seq_length, self.vocab_size))
335
+
336
+ # training
337
+ result = model(input_ids, attention_mask=input_mask, pixel_values=pixel_values, labels=input_ids)
338
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
339
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
340
+ self.parent.assertEqual(result.loss.shape, ())
341
+ self.parent.assertTrue(result.loss.item() > 0)
342
+
343
+ def _test_beam_search_generate(self, config, input_ids, input_mask, pixel_values):
344
+ model = GitForCausalLM(config=config)
345
+ model.to(torch_device)
346
+ model.eval()
347
+
348
+ # generate
349
+ generated_ids = model.generate(
350
+ input_ids,
351
+ attention_mask=input_mask,
352
+ pixel_values=pixel_values,
353
+ do_sample=False,
354
+ max_length=20,
355
+ num_beams=2,
356
+ num_return_sequences=2,
357
+ )
358
+
359
+ self.parent.assertEqual(generated_ids.shape, (self.batch_size * 2, 20))
360
+
361
+ def _test_batched_generate_captioning(self, config, input_ids, input_mask, pixel_values):
362
+ model = GitForCausalLM(config=config)
363
+ model.to(torch_device)
364
+ model.eval()
365
+
366
+ # generate
367
+ generated_ids = model.generate(
368
+ input_ids=None, # captioning -> no input_ids
369
+ attention_mask=None,
370
+ pixel_values=pixel_values,
371
+ do_sample=False,
372
+ min_length=20,
373
+ max_length=20,
374
+ num_beams=2,
375
+ num_return_sequences=2,
376
+ )
377
+
378
+ self.parent.assertEqual(generated_ids.shape, (self.batch_size * 2, 20))
379
+
380
+ def prepare_config_and_inputs_for_common(self):
381
+ config_and_inputs = self.prepare_config_and_inputs()
382
+
383
+ (
384
+ config,
385
+ input_ids,
386
+ input_mask,
387
+ pixel_values,
388
+ ) = config_and_inputs
389
+
390
+ inputs_dict = {
391
+ "input_ids": input_ids,
392
+ "attention_mask": input_mask,
393
+ "pixel_values": pixel_values,
394
+ }
395
+
396
+ return config, inputs_dict
397
+
398
+
399
+ @require_torch
400
+ class GitModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
401
+ all_model_classes = (GitModel, GitForCausalLM) if is_torch_available() else ()
402
+ pipeline_model_mapping = (
403
+ {
404
+ "feature-extraction": GitModel,
405
+ "image-to-text": GitForCausalLM,
406
+ "text-generation": GitForCausalLM,
407
+ "image-text-to-text": GitForCausalLM,
408
+ }
409
+ if is_torch_available()
410
+ else {}
411
+ )
412
+ fx_compatible = False
413
+ test_torchscript = False
414
+
415
+ # special case for GitForCausalLM model
416
+ def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
417
+ inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
418
+
419
+ if return_labels:
420
+ if model_class in get_values(MODEL_FOR_CAUSAL_LM_MAPPING):
421
+ inputs_dict["labels"] = torch.zeros(
422
+ (self.model_tester.batch_size, self.model_tester.text_seq_length),
423
+ dtype=torch.long,
424
+ device=torch_device,
425
+ )
426
+ return inputs_dict
427
+
428
+ def setUp(self):
429
+ self.model_tester = GitModelTester(self)
430
+ self.config_tester = ConfigTester(self, config_class=GitConfig, hidden_size=37)
431
+
432
+ def test_config(self):
433
+ self.config_tester.run_common_tests()
434
+
435
+ def test_model(self):
436
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
437
+ self.model_tester.create_and_check_model(*config_and_inputs)
438
+
439
+ def test_for_causal_lm(self):
440
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
441
+ self.model_tester.create_and_check_for_causal_lm(*config_and_inputs)
442
+
443
+ def test_beam_search_generate(self):
444
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
445
+ self.model_tester._test_beam_search_generate(*config_and_inputs)
446
+
447
+ def test_batched_generate_captioning(self):
448
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
449
+ self.model_tester._test_batched_generate_captioning(*config_and_inputs)
450
+
451
+ def test_model_various_embeddings(self):
452
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
453
+ for type in ["absolute", "relative_key", "relative_key_query"]:
454
+ config_and_inputs[0].position_embedding_type = type
455
+ self.model_tester.create_and_check_model(*config_and_inputs)
456
+
457
+ def _check_attentions_for_generate(
458
+ self, batch_size, attentions, prompt_length, output_length, config, decoder_past_key_values
459
+ ):
460
+ # GIT attention shape depends on image inputs, overwrite
461
+ image_length = int((config.vision_config.image_size / config.vision_config.patch_size) ** 2 + 1)
462
+ prompt_length += image_length
463
+ output_length += image_length
464
+ super()._check_attentions_for_generate(
465
+ batch_size, attentions, prompt_length, output_length, config, decoder_past_key_values
466
+ )
467
+
468
+ def _check_hidden_states_for_generate(
469
+ self, batch_size, hidden_states, prompt_length, output_length, config, use_cache=False
470
+ ):
471
+ # GIT attention shape depends on image inputs, overwrite
472
+ image_length = int((config.vision_config.image_size / config.vision_config.patch_size) ** 2 + 1)
473
+ prompt_length += image_length
474
+ output_length += image_length
475
+ super()._check_hidden_states_for_generate(
476
+ batch_size, hidden_states, prompt_length, output_length, config, use_cache=use_cache
477
+ )
478
+
479
+ @slow
480
+ def test_model_from_pretrained(self):
481
+ model_name = "microsoft/git-base"
482
+ model = GitModel.from_pretrained(model_name)
483
+ self.assertIsNotNone(model)
484
+
485
+ @unittest.skip(reason="GIT has pixel values as additional input")
486
+ def test_beam_search_generate_dict_outputs_use_cache(self):
487
+ pass
488
+
489
+ @unittest.skip(reason="GIT has pixel values as additional input")
490
+ def test_contrastive_generate(self):
491
+ pass
492
+
493
+ @unittest.skip(reason="GIT has pixel values as additional input")
494
+ def test_contrastive_generate_dict_outputs_use_cache(self):
495
+ pass
496
+
497
+ @unittest.skip(reason="GIT has pixel values as additional input")
498
+ def test_contrastive_generate_low_memory(self):
499
+ pass
500
+
501
+ @unittest.skip(reason="GIT has pixel values as additional input")
502
+ def test_greedy_generate_dict_outputs_use_cache(self):
503
+ pass
504
+
505
+ @unittest.skip(reason="GIT has pixel values as additional input")
506
+ def test_dola_decoding_sample(self):
507
+ pass
508
+
509
+
510
+ @require_torch
511
+ @require_vision
512
+ @slow
513
+ class GitModelIntegrationTest(unittest.TestCase):
514
+ def test_forward_pass(self):
515
+ processor = GitProcessor.from_pretrained("microsoft/git-base")
516
+ model = GitForCausalLM.from_pretrained("microsoft/git-base")
517
+
518
+ model.to(torch_device)
519
+
520
+ image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
521
+ inputs = processor(images=image, text="hello world", return_tensors="pt").to(torch_device)
522
+
523
+ with torch.no_grad():
524
+ outputs = model(**inputs)
525
+
526
+ expected_shape = torch.Size((1, 201, 30522))
527
+ self.assertEqual(outputs.logits.shape, expected_shape)
528
+ expected_slice = torch.tensor(
529
+ [[-0.9514, -0.9512, -0.9507], [-0.5454, -0.5453, -0.5453], [-0.8862, -0.8857, -0.8848]],
530
+ device=torch_device,
531
+ )
532
+ torch.testing.assert_close(outputs.logits[0, :3, :3], expected_slice, rtol=1e-4, atol=1e-4)
533
+
534
+ def test_inference_image_captioning(self):
535
+ processor = GitProcessor.from_pretrained("microsoft/git-base")
536
+ model = GitForCausalLM.from_pretrained("microsoft/git-base")
537
+ model.to(torch_device)
538
+
539
+ image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
540
+ inputs = processor(images=image, return_tensors="pt")
541
+ pixel_values = inputs.pixel_values.to(torch_device)
542
+
543
+ outputs = model.generate(
544
+ pixel_values=pixel_values, max_length=20, output_scores=True, return_dict_in_generate=True
545
+ )
546
+ generated_caption = processor.batch_decode(outputs.sequences, skip_special_tokens=True)[0]
547
+
548
+ expected_shape = torch.Size((1, 9))
549
+ self.assertEqual(outputs.sequences.shape, expected_shape)
550
+ self.assertEqual(generated_caption, "two cats laying on a pink blanket")
551
+ self.assertTrue(outputs.scores[-1].shape, expected_shape)
552
+ expected_slice = torch.tensor([-0.8805, -0.8803, -0.8799], device=torch_device)
553
+ torch.testing.assert_close(outputs.scores[-1][0, :3], expected_slice, rtol=1e-4, atol=1e-4)
554
+
555
+ def test_visual_question_answering(self):
556
+ processor = GitProcessor.from_pretrained("microsoft/git-base-textvqa")
557
+ model = GitForCausalLM.from_pretrained("microsoft/git-base-textvqa")
558
+ model.to(torch_device)
559
+
560
+ # prepare image
561
+ file_path = hf_hub_download(repo_id="nielsr/textvqa-sample", filename="bus.png", repo_type="dataset")
562
+ image = Image.open(file_path).convert("RGB")
563
+ inputs = processor(images=image, return_tensors="pt")
564
+ pixel_values = inputs.pixel_values.to(torch_device)
565
+
566
+ # prepare question
567
+ question = "what does the front of the bus say at the top?"
568
+ input_ids = processor(text=question, add_special_tokens=False).input_ids
569
+ input_ids = [processor.tokenizer.cls_token_id] + input_ids
570
+ input_ids = torch.tensor(input_ids).unsqueeze(0).to(torch_device)
571
+
572
+ generated_ids = model.generate(pixel_values=pixel_values, input_ids=input_ids, max_length=20)
573
+ generated_caption = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
574
+
575
+ expected_shape = torch.Size((1, 15))
576
+ self.assertEqual(generated_ids.shape, expected_shape)
577
+ self.assertEqual(generated_caption, "what does the front of the bus say at the top? special")
578
+
579
+ def test_batched_generation(self):
580
+ processor = GitProcessor.from_pretrained("microsoft/git-base-coco")
581
+ model = GitForCausalLM.from_pretrained("microsoft/git-base-coco")
582
+ model.to(torch_device)
583
+
584
+ # create batch of size 2
585
+ image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
586
+ inputs = processor(images=[image, image], return_tensors="pt")
587
+ pixel_values = inputs.pixel_values.to(torch_device)
588
+
589
+ # we have to prepare `input_ids` with the same batch size as `pixel_values`
590
+ start_token_id = model.config.bos_token_id
591
+ input_ids = torch.tensor([[start_token_id], [start_token_id]], device=torch_device)
592
+ generated_ids = model.generate(pixel_values=pixel_values, input_ids=input_ids, max_length=50)
593
+ generated_captions = processor.batch_decode(generated_ids, skip_special_tokens=True)
594
+
595
+ self.assertEqual(generated_captions, ["two cats sleeping on a pink blanket next to remotes."] * 2)
596
+
597
+ @slow
598
+ def test_inference_interpolate_pos_encoding(self):
599
+ # CLIP family models have an `interpolate_pos_encoding` argument in their forward method,
600
+ # allowing to interpolate the pre-trained position embeddings in order to use
601
+ # the model on higher resolutions. The DINO model by Facebook AI leverages this
602
+ # to visualize self-attention on higher resolution images.
603
+ model = GitModel.from_pretrained("microsoft/git-base").to(torch_device)
604
+
605
+ processor = GitProcessor.from_pretrained(
606
+ "microsoft/git-base", size={"height": 180, "width": 180}, crop_size={"height": 180, "width": 180}
607
+ )
608
+
609
+ image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
610
+ inputs = processor(text="what's in the image", images=image, return_tensors="pt").to(torch_device)
611
+
612
+ # interpolate_pos_encodiung false should return value error
613
+ with self.assertRaises(ValueError, msg="doesn't match model"):
614
+ with torch.no_grad():
615
+ model(**inputs, interpolate_pos_encoding=False)
616
+
617
+ # forward pass
618
+ with torch.no_grad():
619
+ outputs = model(**inputs, interpolate_pos_encoding=True)
620
+
621
+ # verify the logits
622
+ expected_shape = torch.Size((1, 130, 768))
623
+
624
+ self.assertEqual(outputs.last_hidden_state.shape, expected_shape)
625
+
626
+ expected_slice = torch.tensor(
627
+ [[-1.0296, 2.5960, 0.8703], [1.7027, 1.3302, -0.4543], [-1.4932, -0.1084, 0.0502]]
628
+ ).to(torch_device)
629
+
630
+ torch.testing.assert_close(outputs.last_hidden_state[0, :3, :3], expected_slice, rtol=1e-4, atol=1e-4)
tasks/tasksmith-441eeab80047/tests/source/tests/models/git/test_processor_git.py ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_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, CLIPImageProcessor, GitProcessor, PreTrainedTokenizerFast
28
+
29
+
30
+ @require_vision
31
+ class GitProcessorTest(ProcessorTesterMixin, unittest.TestCase):
32
+ processor_class = GitProcessor
33
+
34
+ def setUp(self):
35
+ self.tmpdirname = tempfile.mkdtemp()
36
+
37
+ image_processor = CLIPImageProcessor()
38
+ tokenizer = BertTokenizer.from_pretrained(
39
+ "hf-internal-testing/tiny-random-BertModel", model_input_names=["input_ids", "attention_mask"]
40
+ )
41
+
42
+ processor = GitProcessor(image_processor, tokenizer)
43
+
44
+ processor.save_pretrained(self.tmpdirname)
45
+
46
+ def get_tokenizer(self, **kwargs):
47
+ return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).tokenizer
48
+
49
+ def get_image_processor(self, **kwargs):
50
+ return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).image_processor
51
+
52
+ def tearDown(self):
53
+ shutil.rmtree(self.tmpdirname)
54
+
55
+ def test_save_load_pretrained_additional_features(self):
56
+ processor = GitProcessor(tokenizer=self.get_tokenizer(), image_processor=self.get_image_processor())
57
+ processor.save_pretrained(self.tmpdirname)
58
+
59
+ tokenizer_add_kwargs = self.get_tokenizer(bos_token="(BOS)", eos_token="(EOS)")
60
+ image_processor_add_kwargs = self.get_image_processor(do_normalize=False, padding_value=1.0)
61
+
62
+ processor = GitProcessor.from_pretrained(
63
+ self.tmpdirname, bos_token="(BOS)", eos_token="(EOS)", do_normalize=False, padding_value=1.0
64
+ )
65
+
66
+ self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab())
67
+ self.assertIsInstance(processor.tokenizer, PreTrainedTokenizerFast)
68
+
69
+ self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string())
70
+ self.assertIsInstance(processor.image_processor, CLIPImageProcessor)
71
+
72
+ def test_image_processor(self):
73
+ image_processor = self.get_image_processor()
74
+ tokenizer = self.get_tokenizer()
75
+
76
+ processor = GitProcessor(tokenizer=tokenizer, image_processor=image_processor)
77
+
78
+ image_input = self.prepare_image_inputs()
79
+
80
+ input_feat_extract = image_processor(image_input, return_tensors="np")
81
+ input_processor = processor(images=image_input, return_tensors="np")
82
+
83
+ for key in input_feat_extract.keys():
84
+ self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2)
85
+
86
+ def test_tokenizer(self):
87
+ image_processor = self.get_image_processor()
88
+ tokenizer = self.get_tokenizer()
89
+
90
+ processor = GitProcessor(tokenizer=tokenizer, image_processor=image_processor)
91
+
92
+ input_str = "lower newer"
93
+
94
+ encoded_processor = processor(text=input_str)
95
+
96
+ encoded_tok = tokenizer(input_str, return_token_type_ids=False)
97
+
98
+ for key in encoded_tok.keys():
99
+ self.assertListEqual(encoded_tok[key], encoded_processor[key])
100
+
101
+ def test_processor(self):
102
+ image_processor = self.get_image_processor()
103
+ tokenizer = self.get_tokenizer()
104
+
105
+ processor = GitProcessor(tokenizer=tokenizer, image_processor=image_processor)
106
+
107
+ input_str = "lower newer"
108
+ image_input = self.prepare_image_inputs()
109
+
110
+ inputs = processor(text=input_str, images=image_input)
111
+
112
+ self.assertListEqual(list(inputs.keys()), ["input_ids", "attention_mask", "pixel_values"])
113
+
114
+ # test if it raises when no input is passed
115
+ with pytest.raises(ValueError):
116
+ processor()
117
+
118
+ def test_tokenizer_decode(self):
119
+ image_processor = self.get_image_processor()
120
+ tokenizer = self.get_tokenizer()
121
+
122
+ processor = GitProcessor(tokenizer=tokenizer, image_processor=image_processor)
123
+
124
+ predicted_ids = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
125
+
126
+ decoded_processor = processor.batch_decode(predicted_ids)
127
+ decoded_tok = tokenizer.batch_decode(predicted_ids)
128
+
129
+ self.assertListEqual(decoded_tok, decoded_processor)
130
+
131
+ def test_model_input_names(self):
132
+ image_processor = self.get_image_processor()
133
+ tokenizer = self.get_tokenizer()
134
+
135
+ processor = GitProcessor(tokenizer=tokenizer, image_processor=image_processor)
136
+
137
+ input_str = "lower newer"
138
+ image_input = self.prepare_image_inputs()
139
+
140
+ inputs = processor(text=input_str, images=image_input)
141
+
142
+ # For now the processor supports only ['input_ids', 'attention_mask', 'pixel_values']
143
+ self.assertListEqual(list(inputs.keys()), ["input_ids", "attention_mask", "pixel_values"])
tasks/tasksmith-441eeab80047/tests/source/tests/models/glm/__init__.py ADDED
File without changes
tasks/tasksmith-441eeab80047/tests/source/tests/models/glm/test_modeling_glm.py ADDED
@@ -0,0 +1,541 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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 Glm model."""
16
+
17
+ import unittest
18
+
19
+ import pytest
20
+
21
+ from transformers import AutoModelForCausalLM, AutoTokenizer, GlmConfig, is_torch_available
22
+ from transformers.testing_utils import (
23
+ is_flaky,
24
+ require_flash_attn,
25
+ require_torch,
26
+ require_torch_large_gpu,
27
+ require_torch_sdpa,
28
+ slow,
29
+ torch_device,
30
+ )
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 (
42
+ GlmForCausalLM,
43
+ GlmForSequenceClassification,
44
+ GlmForTokenClassification,
45
+ GlmModel,
46
+ )
47
+
48
+
49
+ @require_torch
50
+ class GlmModelTester:
51
+ config_class = GlmConfig
52
+ if is_torch_available():
53
+ model_class = GlmModel
54
+ for_causal_lm_class = GlmForCausalLM
55
+ for_sequence_class = GlmForSequenceClassification
56
+ for_token_class = GlmForTokenClassification
57
+
58
+ def __init__(
59
+ self,
60
+ parent,
61
+ batch_size=13,
62
+ seq_length=7,
63
+ is_training=True,
64
+ use_input_mask=True,
65
+ use_token_type_ids=False,
66
+ use_labels=True,
67
+ vocab_size=99,
68
+ hidden_size=32,
69
+ num_hidden_layers=2,
70
+ num_attention_heads=4,
71
+ num_key_value_heads=2,
72
+ intermediate_size=37,
73
+ hidden_act="silu",
74
+ attention_dropout=0.1,
75
+ max_position_embeddings=512,
76
+ type_vocab_size=16,
77
+ type_sequence_label_size=2,
78
+ initializer_range=0.02,
79
+ num_labels=3,
80
+ num_choices=4,
81
+ pad_token_id=0,
82
+ scope=None,
83
+ ):
84
+ self.parent = parent
85
+ self.batch_size = batch_size
86
+ self.seq_length = seq_length
87
+ self.is_training = is_training
88
+ self.use_input_mask = use_input_mask
89
+ self.use_token_type_ids = use_token_type_ids
90
+ self.use_labels = use_labels
91
+ self.vocab_size = vocab_size
92
+ self.hidden_size = hidden_size
93
+ self.num_hidden_layers = num_hidden_layers
94
+ self.num_attention_heads = num_attention_heads
95
+ self.num_key_value_heads = num_key_value_heads
96
+ self.intermediate_size = intermediate_size
97
+ self.hidden_act = hidden_act
98
+ self.attention_dropout = attention_dropout
99
+ self.max_position_embeddings = max_position_embeddings
100
+ self.type_vocab_size = type_vocab_size
101
+ self.type_sequence_label_size = type_sequence_label_size
102
+ self.initializer_range = initializer_range
103
+ self.num_labels = num_labels
104
+ self.num_choices = num_choices
105
+ self.pad_token_id = pad_token_id
106
+ self.scope = scope
107
+ self.head_dim = self.hidden_size // self.num_attention_heads
108
+
109
+ # Copied from tests.models.mistral.test_modeling_mistral.MistralModelTester.prepare_config_and_inputs
110
+ def prepare_config_and_inputs(self):
111
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
112
+
113
+ input_mask = None
114
+ if self.use_input_mask:
115
+ input_mask = torch.tril(torch.ones_like(input_ids).to(torch_device))
116
+
117
+ token_type_ids = None
118
+ if self.use_token_type_ids:
119
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
120
+
121
+ sequence_labels = None
122
+ token_labels = None
123
+ choice_labels = None
124
+ if self.use_labels:
125
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
126
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
127
+ choice_labels = ids_tensor([self.batch_size], self.num_choices)
128
+
129
+ config = self.get_config()
130
+
131
+ return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
132
+
133
+ def get_config(self):
134
+ return self.config_class(
135
+ vocab_size=self.vocab_size,
136
+ hidden_size=self.hidden_size,
137
+ num_hidden_layers=self.num_hidden_layers,
138
+ num_attention_heads=self.num_attention_heads,
139
+ num_key_value_heads=self.num_key_value_heads,
140
+ intermediate_size=self.intermediate_size,
141
+ hidden_act=self.hidden_act,
142
+ attention_dropout=self.attention_dropout,
143
+ max_position_embeddings=self.max_position_embeddings,
144
+ initializer_range=self.initializer_range,
145
+ pad_token_id=self.pad_token_id,
146
+ head_dim=self.head_dim,
147
+ )
148
+
149
+ def create_and_check_model(
150
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
151
+ ):
152
+ model = self.model_class(config=config)
153
+ model.to(torch_device)
154
+ model.eval()
155
+ result = model(input_ids, attention_mask=input_mask)
156
+ result = model(input_ids)
157
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
158
+
159
+ def create_and_check_model_as_decoder(
160
+ self,
161
+ config,
162
+ input_ids,
163
+ token_type_ids,
164
+ input_mask,
165
+ sequence_labels,
166
+ token_labels,
167
+ choice_labels,
168
+ encoder_hidden_states,
169
+ encoder_attention_mask,
170
+ ):
171
+ model = self.model_class(config)
172
+ model.to(torch_device)
173
+ model.eval()
174
+ result = model(
175
+ input_ids,
176
+ attention_mask=input_mask,
177
+ encoder_hidden_states=encoder_hidden_states,
178
+ encoder_attention_mask=encoder_attention_mask,
179
+ )
180
+ result = model(
181
+ input_ids,
182
+ attention_mask=input_mask,
183
+ encoder_hidden_states=encoder_hidden_states,
184
+ )
185
+ result = model(input_ids, attention_mask=input_mask)
186
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
187
+
188
+ def create_and_check_for_causal_lm(
189
+ self,
190
+ config,
191
+ input_ids,
192
+ token_type_ids,
193
+ input_mask,
194
+ sequence_labels,
195
+ token_labels,
196
+ choice_labels,
197
+ encoder_hidden_states,
198
+ encoder_attention_mask,
199
+ ):
200
+ model = self.for_causal_lm_class(config=config)
201
+ model.to(torch_device)
202
+ model.eval()
203
+ result = model(input_ids, attention_mask=input_mask, labels=token_labels)
204
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
205
+
206
+ def create_and_check_decoder_model_past_large_inputs(
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
+ model = self.for_causal_lm_class(config=config)
219
+ model.to(torch_device)
220
+ model.eval()
221
+
222
+ # first forward pass
223
+ outputs = model(
224
+ input_ids,
225
+ attention_mask=input_mask,
226
+ encoder_hidden_states=encoder_hidden_states,
227
+ encoder_attention_mask=encoder_attention_mask,
228
+ use_cache=True,
229
+ )
230
+ past_key_values = outputs.past_key_values
231
+
232
+ # create hypothetical multiple next token and extent to next_input_ids
233
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
234
+ next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
235
+
236
+ # append to next input_ids and
237
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
238
+ next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
239
+
240
+ output_from_no_past = model(
241
+ next_input_ids,
242
+ attention_mask=next_attention_mask,
243
+ encoder_hidden_states=encoder_hidden_states,
244
+ encoder_attention_mask=encoder_attention_mask,
245
+ output_hidden_states=True,
246
+ )["hidden_states"][0]
247
+ output_from_past = model(
248
+ next_tokens,
249
+ attention_mask=next_attention_mask,
250
+ encoder_hidden_states=encoder_hidden_states,
251
+ encoder_attention_mask=encoder_attention_mask,
252
+ past_key_values=past_key_values,
253
+ output_hidden_states=True,
254
+ )["hidden_states"][0]
255
+
256
+ # select random slice
257
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
258
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
259
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
260
+
261
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
262
+
263
+ # test that outputs are equal for slice
264
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
265
+
266
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTester.prepare_config_and_inputs_for_common with Llama->Glm
267
+ def prepare_config_and_inputs_for_common(self):
268
+ config_and_inputs = self.prepare_config_and_inputs()
269
+ (
270
+ config,
271
+ input_ids,
272
+ token_type_ids,
273
+ input_mask,
274
+ sequence_labels,
275
+ token_labels,
276
+ choice_labels,
277
+ ) = config_and_inputs
278
+ inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
279
+ return config, inputs_dict
280
+
281
+
282
+ @require_torch
283
+ class GlmModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
284
+ all_model_classes = (
285
+ (GlmModel, GlmForCausalLM, GlmForSequenceClassification, GlmForTokenClassification)
286
+ if is_torch_available()
287
+ else ()
288
+ )
289
+ pipeline_model_mapping = (
290
+ {
291
+ "feature-extraction": GlmModel,
292
+ "text-classification": GlmForSequenceClassification,
293
+ "token-classification": GlmForTokenClassification,
294
+ "text-generation": GlmForCausalLM,
295
+ }
296
+ if is_torch_available()
297
+ else {}
298
+ )
299
+ test_headmasking = False
300
+ test_pruning = False
301
+
302
+ def setUp(self):
303
+ self.model_tester = GlmModelTester(self)
304
+ self.config_tester = ConfigTester(self, config_class=GlmConfig, hidden_size=37)
305
+
306
+ def test_config(self):
307
+ self.config_tester.run_common_tests()
308
+
309
+ def test_model(self):
310
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
311
+ self.model_tester.create_and_check_model(*config_and_inputs)
312
+
313
+ def test_model_various_embeddings(self):
314
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
315
+ for type in ["absolute", "relative_key", "relative_key_query"]:
316
+ config_and_inputs[0].position_embedding_type = type
317
+ self.model_tester.create_and_check_model(*config_and_inputs)
318
+
319
+ def test_Glm_sequence_classification_model(self):
320
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
321
+ print(config)
322
+ config.num_labels = 3
323
+ input_ids = input_dict["input_ids"]
324
+ attention_mask = input_ids.ne(1).to(torch_device)
325
+ sequence_labels = ids_tensor([self.model_tester.batch_size], self.model_tester.type_sequence_label_size)
326
+ model = self.model_tester.for_sequence_class(config)
327
+ model.to(torch_device)
328
+ model.eval()
329
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
330
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
331
+
332
+ def test_Glm_sequence_classification_model_for_single_label(self):
333
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
334
+ config.num_labels = 3
335
+ config.problem_type = "single_label_classification"
336
+ input_ids = input_dict["input_ids"]
337
+ attention_mask = input_ids.ne(1).to(torch_device)
338
+ sequence_labels = ids_tensor([self.model_tester.batch_size], self.model_tester.type_sequence_label_size)
339
+ model = self.model_tester.for_sequence_class(config)
340
+ model.to(torch_device)
341
+ model.eval()
342
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
343
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
344
+
345
+ def test_Glm_sequence_classification_model_for_multi_label(self):
346
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
347
+ config.num_labels = 3
348
+ config.problem_type = "multi_label_classification"
349
+ input_ids = input_dict["input_ids"]
350
+ attention_mask = input_ids.ne(1).to(torch_device)
351
+ sequence_labels = ids_tensor(
352
+ [self.model_tester.batch_size, config.num_labels], self.model_tester.type_sequence_label_size
353
+ ).to(torch.float)
354
+ model = self.model_tester.for_sequence_class(config)
355
+ model.to(torch_device)
356
+ model.eval()
357
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
358
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
359
+
360
+ def test_Glm_token_classification_model(self):
361
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
362
+ config.num_labels = 3
363
+ input_ids = input_dict["input_ids"]
364
+ attention_mask = input_ids.ne(1).to(torch_device)
365
+ token_labels = ids_tensor([self.model_tester.batch_size, self.model_tester.seq_length], config.num_labels)
366
+ model = self.model_tester.for_token_class(config=config)
367
+ model.to(torch_device)
368
+ model.eval()
369
+ result = model(input_ids, attention_mask=attention_mask, labels=token_labels)
370
+ self.assertEqual(
371
+ result.logits.shape,
372
+ (self.model_tester.batch_size, self.model_tester.seq_length, self.model_tester.num_labels),
373
+ )
374
+
375
+ @unittest.skip(reason="Glm uses GQA on all models so the KV cache is a non standard format")
376
+ def test_past_key_values_format(self):
377
+ pass
378
+
379
+ @is_flaky()
380
+ def test_custom_4d_attention_mask(self):
381
+ """Overwrite the common test to use atol=1e-3 instead of 1e-4. Can still rarely fail, thus flaky."""
382
+ for model_class in self.all_generative_model_classes:
383
+ if not model_class._supports_static_cache:
384
+ self.skipTest(f"{model_class.__name__} is not guaranteed to work with custom 4D attention masks")
385
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
386
+ if getattr(config, "sliding_window", 0) is not None and getattr(config, "sliding_window", 0) > 0:
387
+ self.skipTest(f"{model_class.__name__} with sliding window attention is not supported by this test")
388
+ model = model_class(config).to(device=torch_device, dtype=torch.float32)
389
+
390
+ (
391
+ input_ids,
392
+ position_ids,
393
+ input_ids_shared_prefix,
394
+ mask_shared_prefix,
395
+ position_ids_shared_prefix,
396
+ ) = self._get_custom_4d_mask_test_data()
397
+
398
+ logits = model.forward(input_ids, position_ids=position_ids).logits
399
+ # logits.shape == torch.Size([3, 4, ...])
400
+
401
+ logits_shared_prefix = model(
402
+ input_ids_shared_prefix,
403
+ attention_mask=mask_shared_prefix,
404
+ position_ids=position_ids_shared_prefix,
405
+ )[0]
406
+ # logits_shared_prefix.shape == torch.Size([1, 6, ...])
407
+
408
+ out_last_tokens = logits[:, -1, :] # last tokens in each batch line
409
+ out_shared_prefix_last_tokens = logits_shared_prefix[0, -3:, :] # last three tokens
410
+
411
+ # comparing softmax-normalized logits:
412
+ normalized_0 = torch.nn.functional.softmax(out_last_tokens)
413
+ normalized_1 = torch.nn.functional.softmax(out_shared_prefix_last_tokens)
414
+ print(torch.abs(normalized_0 - normalized_1).max())
415
+
416
+ torch.testing.assert_close(normalized_0, normalized_1, rtol=1e-3, atol=1e-3)
417
+
418
+
419
+ @slow
420
+ @require_torch_large_gpu
421
+ class GlmIntegrationTest(unittest.TestCase):
422
+ input_text = ["Hello I am doing", "Hi today"]
423
+ model_id = "THUDM/glm-4-9b"
424
+ revision = "refs/pr/15"
425
+ # This variable is used to determine which CUDA device are we using for our runners (A10 or T4)
426
+ # Depending on the hardware we get different logits / generations
427
+ cuda_compute_capability_major_version = None
428
+
429
+ @classmethod
430
+ def setUpClass(cls):
431
+ if is_torch_available() and torch.cuda.is_available():
432
+ # 8 is for A100 / A10 and 7 for T4
433
+ cls.cuda_compute_capability_major_version = torch.cuda.get_device_capability()[0]
434
+
435
+ def test_model_9b_fp16(self):
436
+ EXPECTED_TEXTS = [
437
+ "Hello I am doing a project on the history of the internetSolution:\n\nStep 1: Introduction\nThe history of the",
438
+ "Hi today I am going to show you how to make a simple and easy to make a DIY paper flower.",
439
+ ]
440
+
441
+ model = AutoModelForCausalLM.from_pretrained(
442
+ self.model_id, low_cpu_mem_usage=True, torch_dtype=torch.float16, revision=self.revision
443
+ ).to(torch_device)
444
+
445
+ tokenizer = AutoTokenizer.from_pretrained(self.model_id, revision=self.revision)
446
+ inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device)
447
+
448
+ output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
449
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=True)
450
+
451
+ self.assertEqual(output_text, EXPECTED_TEXTS)
452
+
453
+ def test_model_9b_bf16(self):
454
+ EXPECTED_TEXTS = [
455
+ "Hello I am doing a project on the history of the internetSolution:\n\nStep 1: Introduction\nThe history of the",
456
+ "Hi today I am going to show you how to make a simple and easy to make a DIY paper flower.",
457
+ ]
458
+
459
+ model = AutoModelForCausalLM.from_pretrained(
460
+ self.model_id, low_cpu_mem_usage=True, torch_dtype=torch.bfloat16, revision=self.revision
461
+ ).to(torch_device)
462
+
463
+ tokenizer = AutoTokenizer.from_pretrained(self.model_id, revision=self.revision)
464
+ inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device)
465
+
466
+ output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
467
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=True)
468
+
469
+ self.assertEqual(output_text, EXPECTED_TEXTS)
470
+
471
+ def test_model_9b_eager(self):
472
+ EXPECTED_TEXTS = [
473
+ "Hello I am doing a project on the history of the internetSolution:\n\nStep 1: Introduction\nThe history of the",
474
+ "Hi today I am going to show you how to make a simple and easy to make a DIY paper flower.",
475
+ ]
476
+
477
+ model = AutoModelForCausalLM.from_pretrained(
478
+ self.model_id,
479
+ low_cpu_mem_usage=True,
480
+ torch_dtype=torch.bfloat16,
481
+ attn_implementation="eager",
482
+ revision=self.revision,
483
+ )
484
+ model.to(torch_device)
485
+
486
+ tokenizer = AutoTokenizer.from_pretrained(self.model_id, revision=self.revision)
487
+ inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device)
488
+
489
+ output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
490
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=True)
491
+
492
+ self.assertEqual(output_text, EXPECTED_TEXTS)
493
+
494
+ @require_torch_sdpa
495
+ def test_model_9b_sdpa(self):
496
+ EXPECTED_TEXTS = [
497
+ "Hello I am doing a project on the history of the internetSolution:\n\nStep 1: Introduction\nThe history of the",
498
+ "Hi today I am going to show you how to make a simple and easy to make a DIY paper flower.",
499
+ ]
500
+
501
+ model = AutoModelForCausalLM.from_pretrained(
502
+ self.model_id,
503
+ low_cpu_mem_usage=True,
504
+ torch_dtype=torch.bfloat16,
505
+ attn_implementation="sdpa",
506
+ revision=self.revision,
507
+ )
508
+ model.to(torch_device)
509
+
510
+ tokenizer = AutoTokenizer.from_pretrained(self.model_id, revision=self.revision)
511
+ inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device)
512
+
513
+ output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
514
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=True)
515
+
516
+ self.assertEqual(output_text, EXPECTED_TEXTS)
517
+
518
+ @require_flash_attn
519
+ @pytest.mark.flash_attn_test
520
+ def test_model_9b_flash_attn(self):
521
+ EXPECTED_TEXTS = [
522
+ "Hello I am doing a project on the history of the internetSolution:\n\nStep 1: Introduction\nThe history of the",
523
+ "Hi today I am going to show you how to make a simple and easy to make a DIY paper flower.",
524
+ ]
525
+
526
+ model = AutoModelForCausalLM.from_pretrained(
527
+ self.model_id,
528
+ low_cpu_mem_usage=True,
529
+ torch_dtype=torch.bfloat16,
530
+ attn_implementation="flash_attention_2",
531
+ revision=self.revision,
532
+ )
533
+ model.to(torch_device)
534
+
535
+ tokenizer = AutoTokenizer.from_pretrained(self.model_id, revision=self.revision)
536
+ inputs = tokenizer(self.input_text, return_tensors="pt", padding=True).to(torch_device)
537
+
538
+ output = model.generate(**inputs, max_new_tokens=20, do_sample=False)
539
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=True)
540
+
541
+ self.assertEqual(output_text, EXPECTED_TEXTS)
tasks/tasksmith-441eeab80047/tests/source/tests/models/glpn/__init__.py ADDED
File without changes
tasks/tasksmith-441eeab80047/tests/source/tests/models/glpn/test_image_processing_glpn.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import numpy as np
20
+
21
+ from transformers.testing_utils import require_torch, require_vision
22
+ from transformers.utils import is_torch_available, is_vision_available
23
+
24
+ from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs
25
+
26
+
27
+ if is_torch_available():
28
+ import torch
29
+
30
+ if is_vision_available():
31
+ from PIL import Image
32
+
33
+ from transformers import GLPNImageProcessor
34
+
35
+
36
+ class GLPNImageProcessingTester:
37
+ def __init__(
38
+ self,
39
+ parent,
40
+ batch_size=7,
41
+ num_channels=3,
42
+ image_size=18,
43
+ min_resolution=30,
44
+ max_resolution=400,
45
+ do_resize=True,
46
+ size_divisor=32,
47
+ do_rescale=True,
48
+ ):
49
+ self.parent = parent
50
+ self.batch_size = batch_size
51
+ self.num_channels = num_channels
52
+ self.image_size = image_size
53
+ self.min_resolution = min_resolution
54
+ self.max_resolution = max_resolution
55
+ self.do_resize = do_resize
56
+ self.size_divisor = size_divisor
57
+ self.do_rescale = do_rescale
58
+
59
+ def prepare_image_processor_dict(self):
60
+ return {
61
+ "do_resize": self.do_resize,
62
+ "size_divisor": self.size_divisor,
63
+ "do_rescale": self.do_rescale,
64
+ }
65
+
66
+ def expected_output_image_shape(self, images):
67
+ if isinstance(images[0], Image.Image):
68
+ width, height = images[0].size
69
+ elif isinstance(images[0], np.ndarray):
70
+ height, width = images[0].shape[0], images[0].shape[1]
71
+ else:
72
+ height, width = images[0].shape[1], images[0].shape[2]
73
+
74
+ height = height // self.size_divisor * self.size_divisor
75
+ width = width // self.size_divisor * self.size_divisor
76
+
77
+ return self.num_channels, height, width
78
+
79
+ def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
80
+ return prepare_image_inputs(
81
+ batch_size=self.batch_size,
82
+ num_channels=self.num_channels,
83
+ min_resolution=self.min_resolution,
84
+ max_resolution=self.max_resolution,
85
+ size_divisor=self.size_divisor,
86
+ equal_resolution=equal_resolution,
87
+ numpify=numpify,
88
+ torchify=torchify,
89
+ )
90
+
91
+
92
+ @require_torch
93
+ @require_vision
94
+ class GLPNImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
95
+ image_processing_class = GLPNImageProcessor if is_vision_available() else None
96
+
97
+ def setUp(self):
98
+ super().setUp()
99
+ self.image_processor_tester = GLPNImageProcessingTester(self)
100
+
101
+ @property
102
+ def image_processor_dict(self):
103
+ return self.image_processor_tester.prepare_image_processor_dict()
104
+
105
+ def test_image_processor_properties(self):
106
+ image_processing = self.image_processing_class(**self.image_processor_dict)
107
+ self.assertTrue(hasattr(image_processing, "do_resize"))
108
+ self.assertTrue(hasattr(image_processing, "size_divisor"))
109
+ self.assertTrue(hasattr(image_processing, "resample"))
110
+ self.assertTrue(hasattr(image_processing, "do_rescale"))
111
+
112
+ def test_call_pil(self):
113
+ # Initialize image_processing
114
+ image_processing = self.image_processing_class(**self.image_processor_dict)
115
+ # create random PIL images
116
+ image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False)
117
+ for image in image_inputs:
118
+ self.assertIsInstance(image, Image.Image)
119
+
120
+ # Test not batched input (GLPNImageProcessor doesn't support batching)
121
+ encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
122
+ expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs)
123
+ self.assertTrue(tuple(encoded_images.shape) == (1, *expected_output_image_shape))
124
+
125
+ def test_call_numpy(self):
126
+ # Initialize image_processing
127
+ image_processing = self.image_processing_class(**self.image_processor_dict)
128
+ # create random numpy tensors
129
+ image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True)
130
+ for image in image_inputs:
131
+ self.assertIsInstance(image, np.ndarray)
132
+
133
+ # Test not batched input (GLPNImageProcessor doesn't support batching)
134
+ encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
135
+ expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs)
136
+ self.assertTrue(tuple(encoded_images.shape) == (1, *expected_output_image_shape))
137
+
138
+ def test_call_pytorch(self):
139
+ # Initialize image_processing
140
+ image_processing = self.image_processing_class(**self.image_processor_dict)
141
+ # create random PyTorch tensors
142
+ image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True)
143
+ for image in image_inputs:
144
+ self.assertIsInstance(image, torch.Tensor)
145
+
146
+ # Test not batched input (GLPNImageProcessor doesn't support batching)
147
+ encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
148
+ expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs)
149
+ self.assertTrue(tuple(encoded_images.shape) == (1, *expected_output_image_shape))
150
+
151
+ def test_call_numpy_4_channels(self):
152
+ # Initialize image_processing
153
+ image_processing = self.image_processing_class(**self.image_processor_dict)
154
+ # create random numpy tensors
155
+ self.image_processing_class.num_channels = 4
156
+ image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True)
157
+ for image in image_inputs:
158
+ self.assertIsInstance(image, np.ndarray)
159
+
160
+ # Test not batched input (GLPNImageProcessor doesn't support batching)
161
+ encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values
162
+ expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs)
163
+ self.assertTrue(tuple(encoded_images.shape) == (1, *expected_output_image_shape))
164
+ self.image_processing_class.num_channels = 3
tasks/tasksmith-441eeab80047/tests/source/tests/models/glpn/test_modeling_glpn.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 GLPN model."""
16
+
17
+ import unittest
18
+
19
+ from transformers import is_torch_available, is_vision_available
20
+ from transformers.testing_utils import require_torch, require_vision, slow, torch_device
21
+
22
+ from ...test_configuration_common import ConfigTester
23
+ from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
24
+ from ...test_pipeline_mixin import PipelineTesterMixin
25
+
26
+
27
+ if is_torch_available():
28
+ import torch
29
+
30
+ from transformers import GLPNConfig, GLPNForDepthEstimation, GLPNModel
31
+ from transformers.models.auto.modeling_auto import MODEL_MAPPING_NAMES
32
+
33
+
34
+ if is_vision_available():
35
+ from PIL import Image
36
+
37
+ from transformers import GLPNImageProcessor
38
+
39
+
40
+ class GLPNConfigTester(ConfigTester):
41
+ def create_and_test_config_common_properties(self):
42
+ config = self.config_class(**self.inputs_dict)
43
+ self.parent.assertTrue(hasattr(config, "hidden_sizes"))
44
+ self.parent.assertTrue(hasattr(config, "num_attention_heads"))
45
+ self.parent.assertTrue(hasattr(config, "num_encoder_blocks"))
46
+
47
+
48
+ class GLPNModelTester:
49
+ def __init__(
50
+ self,
51
+ parent,
52
+ batch_size=13,
53
+ image_size=64,
54
+ num_channels=3,
55
+ num_encoder_blocks=4,
56
+ depths=[2, 2, 2, 2],
57
+ sr_ratios=[8, 4, 2, 1],
58
+ hidden_sizes=[16, 32, 64, 128],
59
+ downsampling_rates=[1, 4, 8, 16],
60
+ num_attention_heads=[1, 2, 4, 8],
61
+ is_training=True,
62
+ use_labels=True,
63
+ hidden_act="gelu",
64
+ hidden_dropout_prob=0.1,
65
+ attention_probs_dropout_prob=0.1,
66
+ initializer_range=0.02,
67
+ decoder_hidden_size=16,
68
+ num_labels=3,
69
+ scope=None,
70
+ ):
71
+ self.parent = parent
72
+ self.batch_size = batch_size
73
+ self.image_size = image_size
74
+ self.num_channels = num_channels
75
+ self.num_encoder_blocks = num_encoder_blocks
76
+ self.sr_ratios = sr_ratios
77
+ self.depths = depths
78
+ self.hidden_sizes = hidden_sizes
79
+ self.downsampling_rates = downsampling_rates
80
+ self.num_attention_heads = num_attention_heads
81
+ self.is_training = is_training
82
+ self.use_labels = use_labels
83
+ self.hidden_act = hidden_act
84
+ self.hidden_dropout_prob = hidden_dropout_prob
85
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
86
+ self.initializer_range = initializer_range
87
+ self.decoder_hidden_size = decoder_hidden_size
88
+ self.num_labels = num_labels
89
+ self.scope = scope
90
+
91
+ def prepare_config_and_inputs(self):
92
+ pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
93
+
94
+ labels = None
95
+ if self.use_labels:
96
+ labels = ids_tensor([self.batch_size, self.image_size, self.image_size], self.num_labels)
97
+
98
+ config = self.get_config()
99
+ return config, pixel_values, labels
100
+
101
+ def get_config(self):
102
+ return GLPNConfig(
103
+ image_size=self.image_size,
104
+ num_channels=self.num_channels,
105
+ num_encoder_blocks=self.num_encoder_blocks,
106
+ depths=self.depths,
107
+ hidden_sizes=self.hidden_sizes,
108
+ num_attention_heads=self.num_attention_heads,
109
+ hidden_act=self.hidden_act,
110
+ hidden_dropout_prob=self.hidden_dropout_prob,
111
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
112
+ initializer_range=self.initializer_range,
113
+ decoder_hidden_size=self.decoder_hidden_size,
114
+ )
115
+
116
+ def create_and_check_model(self, config, pixel_values, labels):
117
+ model = GLPNModel(config=config)
118
+ model.to(torch_device)
119
+ model.eval()
120
+ result = model(pixel_values)
121
+ expected_height = expected_width = self.image_size // (self.downsampling_rates[-1] * 2)
122
+ self.parent.assertEqual(
123
+ result.last_hidden_state.shape, (self.batch_size, self.hidden_sizes[-1], expected_height, expected_width)
124
+ )
125
+
126
+ def create_and_check_for_depth_estimation(self, config, pixel_values, labels):
127
+ config.num_labels = self.num_labels
128
+ model = GLPNForDepthEstimation(config)
129
+ model.to(torch_device)
130
+ model.eval()
131
+ result = model(pixel_values)
132
+ self.parent.assertEqual(result.predicted_depth.shape, (self.batch_size, self.image_size, self.image_size))
133
+ result = model(pixel_values, labels=labels)
134
+ self.parent.assertEqual(result.predicted_depth.shape, (self.batch_size, self.image_size, self.image_size))
135
+
136
+ def prepare_config_and_inputs_for_common(self):
137
+ config_and_inputs = self.prepare_config_and_inputs()
138
+ config, pixel_values, labels = config_and_inputs
139
+ inputs_dict = {"pixel_values": pixel_values}
140
+ return config, inputs_dict
141
+
142
+
143
+ @require_torch
144
+ class GLPNModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
145
+ all_model_classes = (GLPNModel, GLPNForDepthEstimation) if is_torch_available() else ()
146
+ pipeline_model_mapping = (
147
+ {"depth-estimation": GLPNForDepthEstimation, "image-feature-extraction": GLPNModel}
148
+ if is_torch_available()
149
+ else {}
150
+ )
151
+
152
+ test_head_masking = False
153
+ test_pruning = False
154
+ test_resize_embeddings = False
155
+ test_torch_exportable = True
156
+
157
+ def setUp(self):
158
+ self.model_tester = GLPNModelTester(self)
159
+ self.config_tester = GLPNConfigTester(self, config_class=GLPNConfig)
160
+
161
+ def test_config(self):
162
+ self.config_tester.run_common_tests()
163
+
164
+ def test_model(self):
165
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
166
+ self.model_tester.create_and_check_model(*config_and_inputs)
167
+
168
+ def test_for_depth_estimation(self):
169
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
170
+ self.model_tester.create_and_check_for_depth_estimation(*config_and_inputs)
171
+
172
+ @unittest.skip(reason="GLPN does not use inputs_embeds")
173
+ def test_inputs_embeds(self):
174
+ pass
175
+
176
+ @unittest.skip(reason="GLPN does not have get_input_embeddings method and get_output_embeddings methods")
177
+ def test_model_get_set_embeddings(self):
178
+ pass
179
+
180
+ def test_attention_outputs(self):
181
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
182
+ config.return_dict = True
183
+
184
+ for model_class in self.all_model_classes:
185
+ inputs_dict["output_attentions"] = True
186
+ inputs_dict["output_hidden_states"] = False
187
+ config.return_dict = True
188
+ model = model_class(config)
189
+ model.to(torch_device)
190
+ model.eval()
191
+ with torch.no_grad():
192
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
193
+ attentions = outputs.attentions
194
+
195
+ expected_num_attentions = sum(self.model_tester.depths)
196
+ self.assertEqual(len(attentions), expected_num_attentions)
197
+
198
+ # check that output_attentions also work using config
199
+ del inputs_dict["output_attentions"]
200
+ config.output_attentions = True
201
+ model = model_class(config)
202
+ model.to(torch_device)
203
+ model.eval()
204
+ with torch.no_grad():
205
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
206
+ attentions = outputs.attentions
207
+
208
+ self.assertEqual(len(attentions), expected_num_attentions)
209
+
210
+ # verify the first attentions (first block, first layer)
211
+ expected_seq_len = (self.model_tester.image_size // 4) ** 2
212
+ expected_reduced_seq_len = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
213
+ self.assertListEqual(
214
+ list(attentions[0].shape[-3:]),
215
+ [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len],
216
+ )
217
+
218
+ # verify the last attentions (last block, last layer)
219
+ expected_seq_len = (self.model_tester.image_size // 32) ** 2
220
+ expected_reduced_seq_len = (self.model_tester.image_size // (32 * self.model_tester.sr_ratios[-1])) ** 2
221
+ self.assertListEqual(
222
+ list(attentions[-1].shape[-3:]),
223
+ [self.model_tester.num_attention_heads[-1], expected_seq_len, expected_reduced_seq_len],
224
+ )
225
+ out_len = len(outputs)
226
+
227
+ # Check attention is always last and order is fine
228
+ inputs_dict["output_attentions"] = True
229
+ inputs_dict["output_hidden_states"] = True
230
+ model = model_class(config)
231
+ model.to(torch_device)
232
+ model.eval()
233
+ with torch.no_grad():
234
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
235
+
236
+ self.assertEqual(out_len + 1, len(outputs))
237
+
238
+ self_attentions = outputs.attentions
239
+
240
+ self.assertEqual(len(self_attentions), expected_num_attentions)
241
+ # verify the first attentions (first block, first layer)
242
+ expected_seq_len = (self.model_tester.image_size // 4) ** 2
243
+ expected_reduced_seq_len = (self.model_tester.image_size // (4 * self.model_tester.sr_ratios[0])) ** 2
244
+ self.assertListEqual(
245
+ list(self_attentions[0].shape[-3:]),
246
+ [self.model_tester.num_attention_heads[0], expected_seq_len, expected_reduced_seq_len],
247
+ )
248
+
249
+ def test_hidden_states_output(self):
250
+ def check_hidden_states_output(inputs_dict, config, model_class):
251
+ model = model_class(config)
252
+ model.to(torch_device)
253
+ model.eval()
254
+
255
+ with torch.no_grad():
256
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
257
+
258
+ hidden_states = outputs.hidden_states
259
+
260
+ expected_num_layers = self.model_tester.num_encoder_blocks
261
+ self.assertEqual(len(hidden_states), expected_num_layers)
262
+
263
+ # verify the first hidden states (first block)
264
+ self.assertListEqual(
265
+ list(hidden_states[0].shape[-3:]),
266
+ [
267
+ self.model_tester.hidden_sizes[0],
268
+ self.model_tester.image_size // 4,
269
+ self.model_tester.image_size // 4,
270
+ ],
271
+ )
272
+
273
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
274
+
275
+ for model_class in self.all_model_classes:
276
+ inputs_dict["output_hidden_states"] = True
277
+ check_hidden_states_output(inputs_dict, config, model_class)
278
+
279
+ # check that output_hidden_states also work using config
280
+ del inputs_dict["output_hidden_states"]
281
+ config.output_hidden_states = True
282
+
283
+ check_hidden_states_output(inputs_dict, config, model_class)
284
+
285
+ def test_training(self):
286
+ if not self.model_tester.is_training:
287
+ self.skipTest(reason="model_tester.is_training is set to False")
288
+
289
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
290
+ config.return_dict = True
291
+
292
+ for model_class in self.all_model_classes:
293
+ if model_class.__name__ in MODEL_MAPPING_NAMES.values():
294
+ continue
295
+ # TODO: remove the following 3 lines once we have a MODEL_FOR_DEPTH_ESTIMATION_MAPPING
296
+ # this can then be incorporated into _prepare_for_class in test_modeling_common.py
297
+ if model_class.__name__ == "GLPNForDepthEstimation":
298
+ batch_size, num_channels, height, width = inputs_dict["pixel_values"].shape
299
+ inputs_dict["labels"] = torch.zeros(
300
+ [self.model_tester.batch_size, height, width], device=torch_device
301
+ ).long()
302
+ model = model_class(config)
303
+ model.to(torch_device)
304
+ model.train()
305
+ inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
306
+ loss = model(**inputs).loss
307
+ loss.backward()
308
+
309
+ @slow
310
+ def test_model_from_pretrained(self):
311
+ model_name = "vinvino02/glpn-kitti"
312
+ model = GLPNModel.from_pretrained(model_name)
313
+ self.assertIsNotNone(model)
314
+
315
+
316
+ # We will verify our results on an image of cute cats
317
+ def prepare_img():
318
+ image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
319
+ return image
320
+
321
+
322
+ @require_torch
323
+ @require_vision
324
+ @slow
325
+ class GLPNModelIntegrationTest(unittest.TestCase):
326
+ @slow
327
+ def test_inference_depth_estimation(self):
328
+ image_processor = GLPNImageProcessor.from_pretrained("vinvino02/glpn-kitti")
329
+ model = GLPNForDepthEstimation.from_pretrained("vinvino02/glpn-kitti").to(torch_device)
330
+
331
+ image = prepare_img()
332
+ inputs = image_processor(images=image, return_tensors="pt").to(torch_device)
333
+
334
+ # forward pass
335
+ with torch.no_grad():
336
+ outputs = model(**inputs)
337
+
338
+ # verify the predicted depth
339
+ expected_shape = torch.Size([1, 480, 640])
340
+ self.assertEqual(outputs.predicted_depth.shape, expected_shape)
341
+
342
+ expected_slice = torch.tensor(
343
+ [[3.4291, 2.7865, 2.5151], [3.2841, 2.7021, 2.3502], [3.1147, 2.4625, 2.2481]]
344
+ ).to(torch_device)
345
+
346
+ torch.testing.assert_close(outputs.predicted_depth[0, :3, :3], expected_slice, rtol=1e-4, atol=1e-4)
tasks/tasksmith-441eeab80047/tests/source/tests/models/got_ocr2/__init__.py ADDED
File without changes
tasks/tasksmith-441eeab80047/tests/source/tests/models/got_ocr2/test_image_processing_got_ocr2.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.image_utils import SizeDict
20
+ from transformers.testing_utils import require_torch, require_vision
21
+ from transformers.utils import is_torch_available, is_torchvision_available, is_vision_available
22
+
23
+ from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs
24
+
25
+
26
+ if is_torch_available():
27
+ import torch
28
+
29
+ if is_vision_available():
30
+ from transformers import GotOcr2ImageProcessor
31
+
32
+ if is_torchvision_available():
33
+ from transformers import GotOcr2ImageProcessorFast
34
+
35
+
36
+ class GotOcr2ImageProcessingTester(unittest.TestCase):
37
+ def __init__(
38
+ self,
39
+ parent,
40
+ batch_size=7,
41
+ num_channels=3,
42
+ image_size=18,
43
+ min_resolution=30,
44
+ max_resolution=400,
45
+ do_resize=True,
46
+ size=None,
47
+ do_normalize=True,
48
+ do_pad=False,
49
+ image_mean=[0.48145466, 0.4578275, 0.40821073],
50
+ image_std=[0.26862954, 0.26130258, 0.27577711],
51
+ do_convert_rgb=True,
52
+ ):
53
+ super().__init__()
54
+ size = size if size is not None else {"height": 20, "width": 20}
55
+ self.parent = parent
56
+ self.batch_size = batch_size
57
+ self.num_channels = num_channels
58
+ self.image_size = image_size
59
+ self.min_resolution = min_resolution
60
+ self.max_resolution = max_resolution
61
+ self.do_resize = do_resize
62
+ self.size = size
63
+ self.do_normalize = do_normalize
64
+ self.image_mean = image_mean
65
+ self.image_std = image_std
66
+ self.do_pad = do_pad
67
+ self.do_convert_rgb = do_convert_rgb
68
+
69
+ def prepare_image_processor_dict(self):
70
+ return {
71
+ "do_resize": self.do_resize,
72
+ "size": self.size,
73
+ "do_normalize": self.do_normalize,
74
+ "image_mean": self.image_mean,
75
+ "image_std": self.image_std,
76
+ "do_convert_rgb": self.do_convert_rgb,
77
+ "do_pad": self.do_pad,
78
+ }
79
+
80
+ def expected_output_image_shape(self, images):
81
+ return self.num_channels, self.size["height"], self.size["width"]
82
+
83
+ def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
84
+ return prepare_image_inputs(
85
+ batch_size=self.batch_size,
86
+ num_channels=self.num_channels,
87
+ min_resolution=self.min_resolution,
88
+ max_resolution=self.max_resolution,
89
+ equal_resolution=equal_resolution,
90
+ numpify=numpify,
91
+ torchify=torchify,
92
+ )
93
+
94
+
95
+ @require_torch
96
+ @require_vision
97
+ class GotOcr2ProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
98
+ image_processing_class = GotOcr2ImageProcessor if is_vision_available() else None
99
+ fast_image_processing_class = GotOcr2ImageProcessorFast if is_torchvision_available() else None
100
+
101
+ def setUp(self):
102
+ super().setUp()
103
+ self.image_processor_tester = GotOcr2ImageProcessingTester(self)
104
+
105
+ @property
106
+ def image_processor_dict(self):
107
+ return self.image_processor_tester.prepare_image_processor_dict()
108
+
109
+ def test_image_processor_properties(self):
110
+ for image_processing_class in self.image_processor_list:
111
+ image_processor = image_processing_class(**self.image_processor_dict)
112
+ self.assertTrue(hasattr(image_processor, "do_resize"))
113
+ self.assertTrue(hasattr(image_processor, "size"))
114
+ self.assertTrue(hasattr(image_processor, "do_normalize"))
115
+ self.assertTrue(hasattr(image_processor, "image_mean"))
116
+ self.assertTrue(hasattr(image_processor, "image_std"))
117
+ self.assertTrue(hasattr(image_processor, "do_convert_rgb"))
118
+
119
+ def test_slow_fast_equivalence_crop_to_patches(self):
120
+ dummy_image = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True)[0]
121
+
122
+ image_processor_slow = self.image_processing_class(**self.image_processor_dict, crop_to_patches=True)
123
+ image_processor_fast = self.fast_image_processing_class(**self.image_processor_dict, crop_to_patches=True)
124
+
125
+ encoding_slow = image_processor_slow(dummy_image, return_tensors="pt")
126
+ encoding_fast = image_processor_fast(dummy_image, return_tensors="pt")
127
+
128
+ torch.testing.assert_close(encoding_slow.num_patches, encoding_fast.num_patches)
129
+ self.assertTrue(torch.allclose(encoding_slow.pixel_values, encoding_fast.pixel_values, atol=1e-1))
130
+ self.assertLessEqual(
131
+ torch.mean(torch.abs(encoding_slow.pixel_values - encoding_fast.pixel_values)).item(), 1e-3
132
+ )
133
+
134
+ def test_slow_fast_equivalence_batched_crop_to_patches(self):
135
+ # Prepare image inputs so that we have two groups of images with equal resolution with a group of images with
136
+ # different resolutions in between
137
+ dummy_images = self.image_processor_tester.prepare_image_inputs(equal_resolution=True, torchify=True)
138
+ dummy_images += self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True)
139
+ dummy_images += self.image_processor_tester.prepare_image_inputs(equal_resolution=True, torchify=True)
140
+
141
+ image_processor_slow = self.image_processing_class(**self.image_processor_dict, crop_to_patches=True)
142
+ image_processor_fast = self.fast_image_processing_class(**self.image_processor_dict, crop_to_patches=True)
143
+
144
+ encoding_slow = image_processor_slow(dummy_images, return_tensors="pt")
145
+ encoding_fast = image_processor_fast(dummy_images, return_tensors="pt")
146
+
147
+ torch.testing.assert_close(encoding_slow.num_patches, encoding_fast.num_patches)
148
+ self.assertTrue(torch.allclose(encoding_slow.pixel_values, encoding_fast.pixel_values, atol=1e-1))
149
+ self.assertLessEqual(
150
+ torch.mean(torch.abs(encoding_slow.pixel_values - encoding_fast.pixel_values)).item(), 1e-3
151
+ )
152
+
153
+ def test_crop_to_patches(self):
154
+ # test slow image processor
155
+ image_processor = self.image_processor_list[0](**self.image_processor_dict)
156
+ image = self.image_processor_tester.prepare_image_inputs(equal_resolution=True, numpify=True)[0]
157
+ processed_images = image_processor.crop_image_to_patches(
158
+ image,
159
+ min_patches=1,
160
+ max_patches=6,
161
+ use_thumbnail=True,
162
+ patch_size={"height": 20, "width": 20},
163
+ )
164
+ self.assertEqual(len(processed_images), 5)
165
+ self.assertEqual(processed_images[0].shape[:2], (20, 20))
166
+
167
+ # test fast image processor (process batch)
168
+ image_processor = self.image_processor_list[1](**self.image_processor_dict)
169
+ image = self.image_processor_tester.prepare_image_inputs(equal_resolution=True, torchify=True)[0]
170
+ processed_images = image_processor.crop_image_to_patches(
171
+ image.unsqueeze(0),
172
+ min_patches=1,
173
+ max_patches=6,
174
+ use_thumbnail=True,
175
+ patch_size=SizeDict(height=20, width=20),
176
+ )
177
+ self.assertEqual(len(processed_images[0]), 5)
178
+ self.assertEqual(processed_images.shape[-2:], (20, 20))
tasks/tasksmith-441eeab80047/tests/source/tests/models/got_ocr2/test_modeling_got_ocr2.py ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 The Qwen team, Alibaba Group and The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Testing suite for the PyTorch GotOcr2 model."""
16
+
17
+ import unittest
18
+
19
+ from transformers import (
20
+ AutoProcessor,
21
+ GotOcr2Config,
22
+ is_torch_available,
23
+ is_vision_available,
24
+ )
25
+ from transformers.testing_utils import cleanup, require_torch, slow, torch_device
26
+
27
+ from ...generation.test_utils import GenerationTesterMixin
28
+ from ...test_configuration_common import ConfigTester
29
+ from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
30
+ from ...test_pipeline_mixin import PipelineTesterMixin
31
+
32
+
33
+ if is_torch_available():
34
+ import torch
35
+
36
+ from transformers import (
37
+ GotOcr2ForConditionalGeneration,
38
+ )
39
+
40
+
41
+ if is_vision_available():
42
+ from transformers.image_utils import load_image
43
+
44
+
45
+ class GotOcr2VisionText2TextModelTester:
46
+ def __init__(
47
+ self,
48
+ parent,
49
+ batch_size=3,
50
+ seq_length=7,
51
+ num_channels=3,
52
+ ignore_index=-100,
53
+ image_size=64,
54
+ bos_token_id=0,
55
+ eos_token_id=0,
56
+ pad_token_id=0,
57
+ image_token_index=1,
58
+ model_type="got_ocr2",
59
+ is_training=True,
60
+ text_config={
61
+ "model_type": "qwen2",
62
+ "vocab_size": 99,
63
+ "hidden_size": 128,
64
+ "intermediate_size": 37,
65
+ "num_hidden_layers": 4,
66
+ "num_attention_heads": 4,
67
+ "num_key_value_heads": 2,
68
+ "output_channels": 64,
69
+ "hidden_act": "silu",
70
+ "max_position_embeddings": 512,
71
+ "rope_theta": 10000,
72
+ "mlp_ratio": 4,
73
+ "tie_word_embeddings": True,
74
+ },
75
+ vision_config={
76
+ "num_hidden_layers": 2,
77
+ "output_channels": 64,
78
+ "hidden_act": "quick_gelu",
79
+ "hidden_size": 32,
80
+ "mlp_dim": 128,
81
+ "num_attention_heads": 4,
82
+ "patch_size": 2,
83
+ "image_size": 64,
84
+ },
85
+ ):
86
+ self.parent = parent
87
+ self.ignore_index = ignore_index
88
+ self.bos_token_id = bos_token_id
89
+ self.eos_token_id = eos_token_id
90
+ self.pad_token_id = pad_token_id
91
+ self.image_token_index = image_token_index
92
+ self.model_type = model_type
93
+ self.text_config = text_config
94
+ self.vision_config = vision_config
95
+ self.batch_size = batch_size
96
+ self.num_channels = num_channels
97
+ self.image_size = image_size
98
+ self.is_training = is_training
99
+ self.num_image_tokens = 64
100
+ self.seq_length = seq_length + self.num_image_tokens
101
+
102
+ self.num_hidden_layers = text_config["num_hidden_layers"]
103
+ self.vocab_size = text_config["vocab_size"]
104
+ self.hidden_size = text_config["hidden_size"]
105
+ self.num_attention_heads = text_config["num_attention_heads"]
106
+
107
+ def get_config(self):
108
+ return GotOcr2Config(
109
+ text_config=self.text_config,
110
+ vision_config=self.vision_config,
111
+ model_type=self.model_type,
112
+ bos_token_id=self.bos_token_id,
113
+ eos_token_id=self.eos_token_id,
114
+ pad_token_id=self.pad_token_id,
115
+ image_token_index=self.image_token_index,
116
+ )
117
+
118
+ def prepare_config_and_inputs(self):
119
+ config = self.get_config()
120
+ pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
121
+
122
+ return config, pixel_values
123
+
124
+ def prepare_config_and_inputs_for_common(self):
125
+ config_and_inputs = self.prepare_config_and_inputs()
126
+ config, pixel_values = config_and_inputs
127
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
128
+ attention_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
129
+
130
+ # input_ids[:, -1] = self.pad_token_id
131
+ input_ids[input_ids == self.image_token_index] = self.pad_token_id
132
+ input_ids[:, : self.num_image_tokens] = self.image_token_index
133
+
134
+ inputs_dict = {
135
+ "pixel_values": pixel_values,
136
+ "input_ids": input_ids,
137
+ "attention_mask": attention_mask,
138
+ }
139
+ return config, inputs_dict
140
+
141
+ def create_and_check_model_fp16_forward(self, config, input_ids, pixel_values, attention_mask):
142
+ model = GotOcr2ForConditionalGeneration(config=config)
143
+ model.to(torch_device)
144
+ model.half()
145
+ model.eval()
146
+ logits = model(
147
+ input_ids=input_ids,
148
+ attention_mask=attention_mask,
149
+ pixel_values=pixel_values.to(torch.bfloat16),
150
+ return_dict=True,
151
+ )["logits"]
152
+ self.parent.assertFalse(torch.isnan(logits).any().item())
153
+
154
+ def create_and_check_model_fp16_autocast_forward(self, config, input_ids, pixel_values, attention_mask):
155
+ config.torch_dtype = torch.float16
156
+ model = GotOcr2ForConditionalGeneration(config=config)
157
+ model.to(torch_device)
158
+ model.eval()
159
+ with torch.autocast(device_type="cuda", dtype=torch.float16):
160
+ logits = model(
161
+ input_ids=input_ids,
162
+ attention_mask=attention_mask,
163
+ pixel_values=pixel_values.to(torch.bfloat16),
164
+ return_dict=True,
165
+ )["logits"]
166
+ self.parent.assertFalse(torch.isnan(logits).any().item())
167
+
168
+
169
+ @require_torch
170
+ class GotOcr2ModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
171
+ all_model_classes = (GotOcr2ForConditionalGeneration,) if is_torch_available() else ()
172
+ pipeline_model_mapping = (
173
+ {
174
+ "image-to-text": GotOcr2ForConditionalGeneration,
175
+ "image-text-to-text": GotOcr2ForConditionalGeneration,
176
+ }
177
+ if is_torch_available()
178
+ else {}
179
+ )
180
+ test_headmasking = False
181
+ test_pruning = False
182
+
183
+ def setUp(self):
184
+ self.model_tester = GotOcr2VisionText2TextModelTester(self)
185
+ self.config_tester = ConfigTester(self, config_class=GotOcr2Config, has_text_modality=False)
186
+
187
+ def test_config(self):
188
+ self.config_tester.run_common_tests()
189
+
190
+ def test_initialization(self):
191
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
192
+
193
+ configs_no_init = _config_zero_init(config)
194
+ for model_class in self.all_model_classes:
195
+ model = model_class(config=configs_no_init)
196
+ for name, param in model.named_parameters():
197
+ if param.requires_grad:
198
+ self.assertIn(
199
+ ((param.data.mean() * 1e9).round() / 1e9).item(),
200
+ [0.0, 1.0],
201
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
202
+ )
203
+
204
+ # overwrite inputs_embeds tests because we need to delete "pixel values" for LVLMs
205
+ def test_inputs_embeds(self):
206
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
207
+
208
+ for model_class in self.all_model_classes:
209
+ model = model_class(config)
210
+ model.to(torch_device)
211
+ model.eval()
212
+
213
+ inputs = self._prepare_for_class(inputs_dict, model_class)
214
+
215
+ input_ids = inputs["input_ids"]
216
+ del inputs["input_ids"]
217
+ del inputs["pixel_values"]
218
+
219
+ wte = model.get_input_embeddings()
220
+ inputs["inputs_embeds"] = wte(input_ids)
221
+
222
+ with torch.no_grad():
223
+ model(**inputs)
224
+
225
+ # overwrite inputs_embeds tests because we need to delete "pixel values" for LVLMs
226
+ # while some other models require pixel_values to be present
227
+ def test_inputs_embeds_matches_input_ids(self):
228
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
229
+
230
+ for model_class in self.all_model_classes:
231
+ model = model_class(config)
232
+ model.to(torch_device)
233
+ model.eval()
234
+
235
+ inputs = self._prepare_for_class(inputs_dict, model_class)
236
+ input_ids = inputs["input_ids"]
237
+ del inputs["input_ids"]
238
+ del inputs["pixel_values"]
239
+
240
+ inputs_embeds = model.get_input_embeddings()(input_ids)
241
+
242
+ with torch.no_grad():
243
+ out_ids = model(input_ids=input_ids, **inputs)[0]
244
+ out_embeds = model(inputs_embeds=inputs_embeds, **inputs)[0]
245
+ torch.testing.assert_close(out_embeds, out_ids)
246
+
247
+ @unittest.skip(
248
+ reason="VLMs can't generate from inputs embeds and pixels. This can be tested as part of bacbone LM, no need to run the test for VLMs"
249
+ )
250
+ def test_generate_from_inputs_embeds_with_static_cache(self):
251
+ pass
252
+
253
+ @unittest.skip(
254
+ reason="GotOcr2's language backbone is Qwen2 which uses GQA so the KV cache is a non standard format"
255
+ )
256
+ def test_past_key_values_format(self):
257
+ pass
258
+
259
+ @unittest.skip("FlashAttention only support fp16 and bf16 data type")
260
+ def test_flash_attn_2_fp32_ln(self):
261
+ pass
262
+
263
+
264
+ @require_torch
265
+ class GotOcr2IntegrationTest(unittest.TestCase):
266
+ def setUp(self):
267
+ self.processor = AutoProcessor.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf")
268
+
269
+ def tearDown(self):
270
+ cleanup(torch_device, gc_collect=True)
271
+
272
+ @slow
273
+ def test_small_model_integration_test_got_ocr_stop_strings(self):
274
+ model_id = "stepfun-ai/GOT-OCR-2.0-hf"
275
+ model = GotOcr2ForConditionalGeneration.from_pretrained(model_id, device_map=torch_device)
276
+ image = load_image(
277
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures_ocr/resolve/main/iam_picture.jpeg"
278
+ )
279
+
280
+ inputs = self.processor(image, return_tensors="pt").to(torch_device)
281
+ generate_ids = model.generate(
282
+ **inputs,
283
+ do_sample=False,
284
+ num_beams=1,
285
+ tokenizer=self.processor.tokenizer,
286
+ stop_strings="<|im_end|>",
287
+ max_new_tokens=4096,
288
+ )
289
+ decoded_output = self.processor.decode(
290
+ generate_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True
291
+ )
292
+ expected_output = "industre"
293
+ self.assertEqual(decoded_output, expected_output)
294
+
295
+ @slow
296
+ def test_small_model_integration_test_got_ocr_format(self):
297
+ model_id = "stepfun-ai/GOT-OCR-2.0-hf"
298
+ model = GotOcr2ForConditionalGeneration.from_pretrained(model_id, device_map=torch_device)
299
+ image = load_image(
300
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/image_ocr.jpg"
301
+ )
302
+
303
+ inputs = self.processor(image, return_tensors="pt", format=True).to(torch_device)
304
+ generate_ids = model.generate(**inputs, do_sample=False, num_beams=1, max_new_tokens=4)
305
+ decoded_output = self.processor.decode(
306
+ generate_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True
307
+ )
308
+ expected_output = "\\title{\nR"
309
+ self.assertEqual(decoded_output, expected_output)
310
+
311
+ @slow
312
+ def test_small_model_integration_test_got_ocr_fine_grained(self):
313
+ model_id = "stepfun-ai/GOT-OCR-2.0-hf"
314
+ model = GotOcr2ForConditionalGeneration.from_pretrained(model_id, device_map=torch_device)
315
+ image = load_image(
316
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/multi_box.png"
317
+ )
318
+
319
+ inputs = self.processor(image, return_tensors="pt", color="green").to(torch_device)
320
+ generate_ids = model.generate(**inputs, do_sample=False, num_beams=1, max_new_tokens=4)
321
+ decoded_output = self.processor.decode(
322
+ generate_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True
323
+ )
324
+ expected_output = "You should keep in"
325
+ self.assertEqual(decoded_output, expected_output)
326
+
327
+ @slow
328
+ def test_small_model_integration_test_got_ocr_crop_to_patches(self):
329
+ model_id = "stepfun-ai/GOT-OCR-2.0-hf"
330
+ model = GotOcr2ForConditionalGeneration.from_pretrained(model_id, device_map=torch_device)
331
+ image = load_image(
332
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/one_column.png"
333
+ )
334
+
335
+ inputs = self.processor(image, return_tensors="pt", crop_to_patches=True).to(torch_device)
336
+ generate_ids = model.generate(**inputs, do_sample=False, num_beams=1, max_new_tokens=4)
337
+ decoded_output = self.processor.decode(
338
+ generate_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True
339
+ )
340
+ expected_output = "on developing architectural improvements"
341
+ self.assertEqual(decoded_output, expected_output)
342
+
343
+ @slow
344
+ def test_small_model_integration_test_got_ocr_multi_pages(self):
345
+ model_id = "stepfun-ai/GOT-OCR-2.0-hf"
346
+ model = GotOcr2ForConditionalGeneration.from_pretrained(model_id, device_map=torch_device)
347
+ image1 = load_image(
348
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/one_column.png"
349
+ )
350
+ image2 = load_image(
351
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/multi_box.png"
352
+ )
353
+
354
+ inputs = self.processor([image1, image2], return_tensors="pt", multi_page=True).to(torch_device)
355
+ generate_ids = model.generate(**inputs, do_sample=False, num_beams=1, max_new_tokens=4)
356
+ decoded_output = self.processor.decode(
357
+ generate_ids[0, inputs["input_ids"].shape[1] :], skip_special_tokens=True
358
+ )
359
+ expected_output = "on developing architectural improvements"
360
+ self.assertEqual(decoded_output, expected_output)
361
+
362
+ @slow
363
+ def test_small_model_integration_test_got_ocr_batched(self):
364
+ model_id = "stepfun-ai/GOT-OCR-2.0-hf"
365
+ model = GotOcr2ForConditionalGeneration.from_pretrained(model_id, device_map=torch_device)
366
+ image1 = load_image(
367
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/multi_box.png"
368
+ )
369
+ image2 = load_image(
370
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures_got_ocr/resolve/main/image_ocr.jpg"
371
+ )
372
+
373
+ inputs = self.processor([image1, image2], return_tensors="pt").to(torch_device)
374
+ generate_ids = model.generate(**inputs, do_sample=False, num_beams=1, max_new_tokens=4)
375
+ decoded_output = self.processor.batch_decode(
376
+ generate_ids[:, inputs["input_ids"].shape[1] :], skip_special_tokens=True
377
+ )
378
+ expected_output = ["Reducing the number", "R&D QUALITY"]
379
+ self.assertEqual(decoded_output, expected_output)
tasks/tasksmith-441eeab80047/tests/source/tests/models/got_ocr2/test_processor_got_ocr2.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import shutil
16
+ import tempfile
17
+ import unittest
18
+
19
+ from transformers import AutoProcessor, GotOcr2Processor, PreTrainedTokenizerFast
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 GotOcr2ImageProcessor
28
+
29
+
30
+ @require_vision
31
+ class GotOcr2ProcessorTest(ProcessorTesterMixin, unittest.TestCase):
32
+ processor_class = GotOcr2Processor
33
+
34
+ def setUp(self):
35
+ self.tmpdirname = tempfile.mkdtemp()
36
+
37
+ image_processor = GotOcr2ImageProcessor()
38
+ tokenizer = PreTrainedTokenizerFast.from_pretrained("stepfun-ai/GOT-OCR-2.0-hf")
39
+ processor_kwargs = self.prepare_processor_dict()
40
+ processor = GotOcr2Processor(image_processor, tokenizer, **processor_kwargs)
41
+ processor.save_pretrained(self.tmpdirname)
42
+
43
+ def get_tokenizer(self, **kwargs):
44
+ return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).tokenizer
45
+
46
+ def get_image_processor(self, **kwargs):
47
+ return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).image_processor
48
+
49
+ def tearDown(self):
50
+ shutil.rmtree(self.tmpdirname)
51
+
52
+ def test_ocr_queries(self):
53
+ processor = self.get_processor()
54
+ image_input = self.prepare_image_inputs()
55
+ inputs = processor(image_input, return_tensors="pt")
56
+ self.assertEqual(inputs["input_ids"].shape, (1, 286))
57
+ self.assertEqual(inputs["pixel_values"].shape, (1, 3, 384, 384))
58
+
59
+ inputs = processor(image_input, return_tensors="pt", format=True)
60
+ self.assertEqual(inputs["input_ids"].shape, (1, 288))
61
+ self.assertEqual(inputs["pixel_values"].shape, (1, 3, 384, 384))
62
+
63
+ inputs = processor(image_input, return_tensors="pt", color="red")
64
+ self.assertEqual(inputs["input_ids"].shape, (1, 290))
65
+ self.assertEqual(inputs["pixel_values"].shape, (1, 3, 384, 384))
66
+
67
+ inputs = processor(image_input, return_tensors="pt", box=[0, 0, 100, 100])
68
+ self.assertEqual(inputs["input_ids"].shape, (1, 303))
69
+ self.assertEqual(inputs["pixel_values"].shape, (1, 3, 384, 384))
70
+
71
+ inputs = processor([image_input, image_input], return_tensors="pt", multi_page=True, format=True)
72
+ self.assertEqual(inputs["input_ids"].shape, (1, 547))
73
+ self.assertEqual(inputs["pixel_values"].shape, (2, 3, 384, 384))
74
+
75
+ inputs = processor(image_input, return_tensors="pt", crop_to_patches=True, max_patches=6)
76
+ self.assertEqual(inputs["input_ids"].shape, (1, 1826))
77
+ self.assertEqual(inputs["pixel_values"].shape, (7, 3, 384, 384))
tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt2/__init__.py ADDED
File without changes
tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt2/test_modeling_flax_gpt2.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
16
+ import unittest
17
+
18
+ import numpy as np
19
+
20
+ from transformers import GPT2Config, GPT2Tokenizer, is_flax_available
21
+ from transformers.testing_utils import require_flax, slow
22
+
23
+ from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
24
+
25
+
26
+ if is_flax_available():
27
+ import jax
28
+ import jax.numpy as jnp
29
+
30
+ from transformers.models.gpt2.modeling_flax_gpt2 import FlaxGPT2LMHeadModel, FlaxGPT2Model
31
+
32
+
33
+ class FlaxGPT2ModelTester:
34
+ def __init__(
35
+ self,
36
+ parent,
37
+ batch_size=14,
38
+ seq_length=7,
39
+ is_training=True,
40
+ use_input_mask=True,
41
+ use_token_type_ids=False,
42
+ use_labels=True,
43
+ vocab_size=99,
44
+ hidden_size=32,
45
+ num_hidden_layers=2,
46
+ num_attention_heads=4,
47
+ intermediate_size=37,
48
+ hidden_act="gelu",
49
+ hidden_dropout_prob=0.1,
50
+ attention_probs_dropout_prob=0.1,
51
+ max_position_embeddings=512,
52
+ initializer_range=0.02,
53
+ ):
54
+ self.parent = parent
55
+ self.batch_size = batch_size
56
+ self.seq_length = seq_length
57
+ self.is_training = is_training
58
+ self.use_input_mask = use_input_mask
59
+ self.use_token_type_ids = use_token_type_ids
60
+ self.use_labels = use_labels
61
+ self.vocab_size = vocab_size
62
+ self.hidden_size = hidden_size
63
+ self.num_hidden_layers = num_hidden_layers
64
+ self.num_attention_heads = num_attention_heads
65
+ self.intermediate_size = intermediate_size
66
+ self.hidden_act = hidden_act
67
+ self.hidden_dropout_prob = hidden_dropout_prob
68
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
69
+ self.max_position_embeddings = max_position_embeddings
70
+ self.initializer_range = initializer_range
71
+ self.scope = None
72
+ self.bos_token_id = vocab_size - 1
73
+ self.eos_token_id = vocab_size - 1
74
+ self.pad_token_id = vocab_size - 1
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
+ config = GPT2Config(
84
+ vocab_size=self.vocab_size,
85
+ n_embd=self.hidden_size,
86
+ n_layer=self.num_hidden_layers,
87
+ n_head=self.num_attention_heads,
88
+ n_positions=self.max_position_embeddings,
89
+ use_cache=False,
90
+ bos_token_id=self.bos_token_id,
91
+ eos_token_id=self.eos_token_id,
92
+ pad_token_id=self.pad_token_id,
93
+ )
94
+
95
+ return (config, input_ids, input_mask)
96
+
97
+ def prepare_config_and_inputs_for_common(self):
98
+ config_and_inputs = self.prepare_config_and_inputs()
99
+ config, input_ids, attention_mask = config_and_inputs
100
+ inputs_dict = {"input_ids": input_ids, "attention_mask": attention_mask}
101
+ return config, inputs_dict
102
+
103
+ def prepare_config_and_inputs_for_decoder(self):
104
+ config, input_ids, attention_mask = self.prepare_config_and_inputs()
105
+
106
+ encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
107
+ encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
108
+
109
+ return (
110
+ config,
111
+ input_ids,
112
+ attention_mask,
113
+ encoder_hidden_states,
114
+ encoder_attention_mask,
115
+ )
116
+
117
+ def check_use_cache_forward(self, model_class_name, config, input_ids, attention_mask):
118
+ max_decoder_length = 20
119
+ model = model_class_name(config)
120
+
121
+ past_key_values = model.init_cache(input_ids.shape[0], max_decoder_length)
122
+ attention_mask = jnp.ones((input_ids.shape[0], max_decoder_length), dtype="i4")
123
+
124
+ position_ids = jnp.broadcast_to(
125
+ jnp.arange(input_ids.shape[-1] - 1)[None, :], (input_ids.shape[0], input_ids.shape[-1] - 1)
126
+ )
127
+ outputs_cache = model(
128
+ input_ids[:, :-1],
129
+ attention_mask=attention_mask,
130
+ past_key_values=past_key_values,
131
+ position_ids=position_ids,
132
+ )
133
+
134
+ position_ids = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]], dtype="i4")
135
+ outputs_cache_next = model(
136
+ input_ids[:, -1:],
137
+ attention_mask=attention_mask,
138
+ past_key_values=outputs_cache.past_key_values,
139
+ position_ids=position_ids,
140
+ )
141
+
142
+ outputs = model(input_ids)
143
+
144
+ diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
145
+ self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}")
146
+
147
+ def check_use_cache_forward_with_attn_mask(self, model_class_name, config, input_ids, attention_mask):
148
+ max_decoder_length = 20
149
+ model = model_class_name(config)
150
+
151
+ attention_mask_cache = jnp.concatenate(
152
+ [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]))],
153
+ axis=-1,
154
+ )
155
+
156
+ past_key_values = model.init_cache(input_ids.shape[0], max_decoder_length)
157
+ position_ids = jnp.broadcast_to(
158
+ jnp.arange(input_ids.shape[-1] - 1)[None, :], (input_ids.shape[0], input_ids.shape[-1] - 1)
159
+ )
160
+
161
+ outputs_cache = model(
162
+ input_ids[:, :-1],
163
+ attention_mask=attention_mask_cache,
164
+ past_key_values=past_key_values,
165
+ position_ids=position_ids,
166
+ )
167
+ position_ids = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]], dtype="i4")
168
+ outputs_cache_next = model(
169
+ input_ids[:, -1:],
170
+ past_key_values=outputs_cache.past_key_values,
171
+ attention_mask=attention_mask_cache,
172
+ position_ids=position_ids,
173
+ )
174
+
175
+ outputs = model(input_ids, attention_mask=attention_mask)
176
+
177
+ diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
178
+ self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}")
179
+
180
+ def check_bool_attention_mask_in_generation(self, model_class_name, config, input_ids, attention_mask):
181
+ model = model_class_name(config)
182
+
183
+ output_int_att_mask = model.generate(
184
+ input_ids=input_ids,
185
+ attention_mask=attention_mask,
186
+ max_new_tokens=3,
187
+ )
188
+
189
+ output_bool_att_mask = model.generate(
190
+ input_ids=input_ids,
191
+ attention_mask=attention_mask.astype(bool),
192
+ max_new_tokens=3,
193
+ )
194
+
195
+ self.parent.assertTrue(
196
+ (output_bool_att_mask.sequences == output_int_att_mask.sequences).all(),
197
+ "Generated response differ between boolean and integer attention mask",
198
+ )
199
+
200
+
201
+ @require_flax
202
+ class FlaxGPT2ModelTest(FlaxModelTesterMixin, unittest.TestCase):
203
+ all_model_classes = (FlaxGPT2Model, FlaxGPT2LMHeadModel) if is_flax_available() else ()
204
+
205
+ def setUp(self):
206
+ self.model_tester = FlaxGPT2ModelTester(self)
207
+
208
+ def test_use_cache_forward(self):
209
+ for model_class_name in self.all_model_classes:
210
+ config, input_ids, attention_mask = self.model_tester.prepare_config_and_inputs()
211
+ self.model_tester.check_use_cache_forward(model_class_name, config, input_ids, attention_mask)
212
+
213
+ def test_use_cache_forward_with_attn_mask(self):
214
+ for model_class_name in self.all_model_classes:
215
+ config, input_ids, attention_mask = self.model_tester.prepare_config_and_inputs()
216
+ self.model_tester.check_use_cache_forward_with_attn_mask(
217
+ model_class_name, config, input_ids, attention_mask
218
+ )
219
+
220
+ def test_bool_attention_mask_in_generation(self):
221
+ for model_class_name in self.all_generative_model_classes:
222
+ config, input_ids, attention_mask = self.model_tester.prepare_config_and_inputs()
223
+ self.model_tester.check_bool_attention_mask_in_generation(
224
+ model_class_name, config, input_ids, attention_mask
225
+ )
226
+
227
+ @slow
228
+ def test_batch_generation(self):
229
+ tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2", pad_token="</s>", padding_side="left")
230
+ inputs = tokenizer(["Hello this is a long string", "Hey"], return_tensors="np", padding=True, truncation=True)
231
+
232
+ model = FlaxGPT2LMHeadModel.from_pretrained("openai-community/gpt2")
233
+ model.do_sample = False
234
+ model.config.pad_token_id = model.config.eos_token_id
235
+
236
+ jit_generate = jax.jit(model.generate)
237
+
238
+ output_sequences = jit_generate(inputs["input_ids"], attention_mask=inputs["attention_mask"]).sequences
239
+
240
+ output_string = tokenizer.batch_decode(output_sequences, skip_special_tokens=True)
241
+
242
+ expected_string = [
243
+ "Hello this is a long string of words. I'm going to start with the first one.\n",
244
+ "Hey, I'm not sure if I'm going to be able to do",
245
+ ]
246
+
247
+ self.assertListEqual(output_string, expected_string)
248
+
249
+ @slow
250
+ def test_model_from_pretrained(self):
251
+ for model_class_name in self.all_model_classes:
252
+ model = model_class_name.from_pretrained("openai-community/gpt2", from_pt=True)
253
+ outputs = model(np.ones((1, 1)))
254
+ self.assertIsNotNone(outputs)
tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt2/test_modeling_gpt2.py ADDED
@@ -0,0 +1,898 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
17
+ import math
18
+ import unittest
19
+
20
+ import pytest
21
+
22
+ from transformers import GPT2Config, is_torch_available
23
+ from transformers.testing_utils import (
24
+ cleanup,
25
+ require_flash_attn,
26
+ require_torch,
27
+ require_torch_gpu,
28
+ slow,
29
+ torch_device,
30
+ )
31
+
32
+ from ...generation.test_utils import GenerationTesterMixin
33
+ from ...test_configuration_common import ConfigTester
34
+ from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
35
+ from ...test_pipeline_mixin import PipelineTesterMixin
36
+
37
+
38
+ if is_torch_available():
39
+ import torch
40
+
41
+ from transformers import (
42
+ GPT2DoubleHeadsModel,
43
+ GPT2ForQuestionAnswering,
44
+ GPT2ForSequenceClassification,
45
+ GPT2ForTokenClassification,
46
+ GPT2LMHeadModel,
47
+ GPT2Model,
48
+ GPT2Tokenizer,
49
+ )
50
+
51
+
52
+ class GPT2ModelTester:
53
+ def __init__(
54
+ self,
55
+ parent,
56
+ batch_size=14,
57
+ seq_length=7,
58
+ is_training=True,
59
+ use_token_type_ids=True,
60
+ use_input_mask=True,
61
+ use_labels=True,
62
+ use_mc_token_ids=True,
63
+ vocab_size=99,
64
+ hidden_size=32,
65
+ num_hidden_layers=2,
66
+ num_attention_heads=4,
67
+ intermediate_size=37,
68
+ hidden_act="gelu",
69
+ hidden_dropout_prob=0.1,
70
+ attention_probs_dropout_prob=0.1,
71
+ max_position_embeddings=512,
72
+ type_vocab_size=16,
73
+ type_sequence_label_size=2,
74
+ initializer_range=0.02,
75
+ num_labels=3,
76
+ num_choices=4,
77
+ scope=None,
78
+ ):
79
+ self.parent = parent
80
+ self.batch_size = batch_size
81
+ self.seq_length = seq_length
82
+ self.is_training = is_training
83
+ self.use_token_type_ids = use_token_type_ids
84
+ self.use_input_mask = use_input_mask
85
+ self.use_labels = use_labels
86
+ self.use_mc_token_ids = use_mc_token_ids
87
+ self.vocab_size = vocab_size
88
+ self.hidden_size = hidden_size
89
+ self.num_hidden_layers = num_hidden_layers
90
+ self.num_attention_heads = num_attention_heads
91
+ self.intermediate_size = intermediate_size
92
+ self.hidden_act = hidden_act
93
+ self.hidden_dropout_prob = hidden_dropout_prob
94
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
95
+ self.max_position_embeddings = max_position_embeddings
96
+ self.type_vocab_size = type_vocab_size
97
+ self.type_sequence_label_size = type_sequence_label_size
98
+ self.initializer_range = initializer_range
99
+ self.num_labels = num_labels
100
+ self.num_choices = num_choices
101
+ self.scope = None
102
+ self.bos_token_id = vocab_size - 1
103
+ self.eos_token_id = vocab_size - 1
104
+ self.pad_token_id = vocab_size - 1
105
+
106
+ def get_large_model_config(self):
107
+ return GPT2Config.from_pretrained("openai-community/gpt2")
108
+
109
+ def prepare_config_and_inputs(
110
+ self, gradient_checkpointing=False, scale_attn_by_inverse_layer_idx=False, reorder_and_upcast_attn=False
111
+ ):
112
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
113
+
114
+ input_mask = None
115
+ if self.use_input_mask:
116
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
117
+
118
+ token_type_ids = None
119
+ if self.use_token_type_ids:
120
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
121
+
122
+ mc_token_ids = None
123
+ if self.use_mc_token_ids:
124
+ mc_token_ids = ids_tensor([self.batch_size, self.num_choices], self.seq_length)
125
+
126
+ sequence_labels = None
127
+ token_labels = None
128
+ choice_labels = None
129
+ if self.use_labels:
130
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
131
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
132
+ choice_labels = ids_tensor([self.batch_size], self.num_choices)
133
+
134
+ config = self.get_config(
135
+ gradient_checkpointing=gradient_checkpointing,
136
+ scale_attn_by_inverse_layer_idx=scale_attn_by_inverse_layer_idx,
137
+ reorder_and_upcast_attn=reorder_and_upcast_attn,
138
+ )
139
+
140
+ head_mask = ids_tensor([self.num_hidden_layers, self.num_attention_heads], 2)
141
+
142
+ return (
143
+ config,
144
+ input_ids,
145
+ input_mask,
146
+ head_mask,
147
+ token_type_ids,
148
+ mc_token_ids,
149
+ sequence_labels,
150
+ token_labels,
151
+ choice_labels,
152
+ )
153
+
154
+ def get_config(
155
+ self, gradient_checkpointing=False, scale_attn_by_inverse_layer_idx=False, reorder_and_upcast_attn=False
156
+ ):
157
+ return GPT2Config(
158
+ vocab_size=self.vocab_size,
159
+ n_embd=self.hidden_size,
160
+ n_layer=self.num_hidden_layers,
161
+ n_head=self.num_attention_heads,
162
+ n_inner=self.intermediate_size,
163
+ activation_function=self.hidden_act,
164
+ resid_pdrop=self.hidden_dropout_prob,
165
+ attn_pdrop=self.attention_probs_dropout_prob,
166
+ n_positions=self.max_position_embeddings,
167
+ type_vocab_size=self.type_vocab_size,
168
+ initializer_range=self.initializer_range,
169
+ use_cache=True,
170
+ bos_token_id=self.bos_token_id,
171
+ eos_token_id=self.eos_token_id,
172
+ pad_token_id=self.pad_token_id,
173
+ gradient_checkpointing=gradient_checkpointing,
174
+ scale_attn_by_inverse_layer_idx=scale_attn_by_inverse_layer_idx,
175
+ reorder_and_upcast_attn=reorder_and_upcast_attn,
176
+ )
177
+
178
+ def get_pipeline_config(self):
179
+ config = self.get_config()
180
+ config.vocab_size = 300
181
+ return config
182
+
183
+ def prepare_config_and_inputs_for_decoder(self):
184
+ (
185
+ config,
186
+ input_ids,
187
+ input_mask,
188
+ head_mask,
189
+ token_type_ids,
190
+ mc_token_ids,
191
+ sequence_labels,
192
+ token_labels,
193
+ choice_labels,
194
+ ) = self.prepare_config_and_inputs()
195
+
196
+ encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
197
+ encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
198
+
199
+ return (
200
+ config,
201
+ input_ids,
202
+ input_mask,
203
+ head_mask,
204
+ token_type_ids,
205
+ sequence_labels,
206
+ token_labels,
207
+ choice_labels,
208
+ encoder_hidden_states,
209
+ encoder_attention_mask,
210
+ )
211
+
212
+ def create_and_check_gpt2_model(self, config, input_ids, input_mask, head_mask, token_type_ids, *args):
213
+ model = GPT2Model(config=config)
214
+ model.to(torch_device)
215
+ model.eval()
216
+
217
+ result = model(input_ids, token_type_ids=token_type_ids, head_mask=head_mask)
218
+ result = model(input_ids, token_type_ids=token_type_ids)
219
+ result = model(input_ids)
220
+
221
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
222
+ self.parent.assertEqual(len(result.past_key_values), config.n_layer)
223
+
224
+ def create_and_check_gpt2_model_past(self, config, input_ids, input_mask, head_mask, token_type_ids, *args):
225
+ model = GPT2Model(config=config)
226
+ model.to(torch_device)
227
+ model.eval()
228
+
229
+ # first forward pass
230
+ outputs = model(input_ids, token_type_ids=token_type_ids, use_cache=True)
231
+ outputs_use_cache_conf = model(input_ids, token_type_ids=token_type_ids)
232
+ outputs_no_past = model(input_ids, token_type_ids=token_type_ids, use_cache=False)
233
+
234
+ self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))
235
+ self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)
236
+
237
+ output, past = outputs.to_tuple()
238
+
239
+ # create hypothetical next token and extent to next_input_ids
240
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
241
+ next_token_types = ids_tensor([self.batch_size, 1], self.type_vocab_size)
242
+
243
+ # append to next input_ids and token_type_ids
244
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
245
+ next_token_type_ids = torch.cat([token_type_ids, next_token_types], dim=-1)
246
+
247
+ output_from_no_past = model(next_input_ids, token_type_ids=next_token_type_ids)["last_hidden_state"]
248
+ output_from_past = model(next_tokens, token_type_ids=next_token_types, past_key_values=past)[
249
+ "last_hidden_state"
250
+ ]
251
+
252
+ # select random slice
253
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
254
+ output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach()
255
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
256
+
257
+ # test that outputs are equal for slice
258
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
259
+
260
+ def create_and_check_gpt2_model_attention_mask_past(
261
+ self, config, input_ids, input_mask, head_mask, token_type_ids, *args
262
+ ):
263
+ model = GPT2Model(config=config)
264
+ model.to(torch_device)
265
+ model.eval()
266
+
267
+ # create attention mask
268
+ attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
269
+ half_seq_length = self.seq_length // 2
270
+ attn_mask[:, half_seq_length:] = 0
271
+
272
+ # first forward pass
273
+ output, past = model(input_ids, attention_mask=attn_mask).to_tuple()
274
+
275
+ # create hypothetical next token and extent to next_input_ids
276
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
277
+
278
+ # change a random masked slice from input_ids
279
+ random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1
280
+ random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1)
281
+ input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens
282
+
283
+ # append to next input_ids and attn_mask
284
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
285
+ attn_mask = torch.cat(
286
+ [attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)],
287
+ dim=1,
288
+ )
289
+
290
+ # get two different outputs
291
+ output_from_no_past = model(next_input_ids, attention_mask=attn_mask)["last_hidden_state"]
292
+ output_from_past = model(next_tokens, past_key_values=past, attention_mask=attn_mask)["last_hidden_state"]
293
+
294
+ # select random slice
295
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
296
+ output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach()
297
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
298
+
299
+ # test that outputs are equal for slice
300
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
301
+
302
+ def create_and_check_gpt2_model_past_large_inputs(
303
+ self, config, input_ids, input_mask, head_mask, token_type_ids, *args
304
+ ):
305
+ model = GPT2Model(config=config)
306
+ model.to(torch_device)
307
+ model.eval()
308
+
309
+ # first forward pass
310
+ outputs = model(input_ids, token_type_ids=token_type_ids, attention_mask=input_mask, use_cache=True)
311
+
312
+ output, past = outputs.to_tuple()
313
+
314
+ # create hypothetical next token and extent to next_input_ids
315
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
316
+ next_token_types = ids_tensor([self.batch_size, 3], self.type_vocab_size)
317
+ next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
318
+
319
+ # append to next input_ids and token_type_ids
320
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
321
+ next_token_type_ids = torch.cat([token_type_ids, next_token_types], dim=-1)
322
+ next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
323
+
324
+ output_from_no_past = model(
325
+ next_input_ids, token_type_ids=next_token_type_ids, attention_mask=next_attention_mask
326
+ )["last_hidden_state"]
327
+ output_from_past = model(
328
+ next_tokens, token_type_ids=next_token_types, attention_mask=next_attention_mask, past_key_values=past
329
+ )["last_hidden_state"]
330
+ self.parent.assertTrue(output_from_past.shape[1] == next_tokens.shape[1])
331
+
332
+ # select random slice
333
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
334
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
335
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
336
+
337
+ # test that outputs are equal for slice
338
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
339
+
340
+ def create_and_check_lm_head_model(self, config, input_ids, input_mask, head_mask, token_type_ids, *args):
341
+ model = GPT2LMHeadModel(config)
342
+ model.to(torch_device)
343
+ model.eval()
344
+
345
+ result = model(input_ids, token_type_ids=token_type_ids, labels=input_ids)
346
+ self.parent.assertEqual(result.loss.shape, ())
347
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
348
+
349
+ def create_and_check_forward_and_backwards(
350
+ self, config, input_ids, input_mask, head_mask, token_type_ids, *args, gradient_checkpointing=False
351
+ ):
352
+ model = GPT2LMHeadModel(config)
353
+ model.to(torch_device)
354
+ if gradient_checkpointing:
355
+ model.gradient_checkpointing_enable()
356
+
357
+ result = model(input_ids, token_type_ids=token_type_ids, labels=input_ids)
358
+ self.parent.assertEqual(result.loss.shape, ())
359
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
360
+ result.loss.backward()
361
+
362
+ def create_and_check_double_lm_head_model(
363
+ self, config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, *args
364
+ ):
365
+ model = GPT2DoubleHeadsModel(config)
366
+ model.to(torch_device)
367
+ model.eval()
368
+
369
+ multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
370
+ multiple_choice_input_mask = input_mask.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
+
373
+ inputs = {
374
+ "input_ids": multiple_choice_inputs_ids,
375
+ "mc_token_ids": mc_token_ids,
376
+ "attention_mask": multiple_choice_input_mask,
377
+ "token_type_ids": multiple_choice_token_type_ids,
378
+ "labels": multiple_choice_inputs_ids,
379
+ }
380
+
381
+ result = model(**inputs)
382
+ self.parent.assertEqual(result.loss.shape, ())
383
+ self.parent.assertEqual(
384
+ result.logits.shape, (self.batch_size, self.num_choices, self.seq_length, self.vocab_size)
385
+ )
386
+ self.parent.assertEqual(result.mc_logits.shape, (self.batch_size, self.num_choices))
387
+
388
+ def create_and_check_gpt2_for_question_answering(
389
+ self, config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, *args
390
+ ):
391
+ config.num_labels = self.num_labels
392
+ model = GPT2ForQuestionAnswering(config)
393
+ model.to(torch_device)
394
+ model.eval()
395
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
396
+ self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
397
+ self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
398
+
399
+ def create_and_check_gpt2_for_sequence_classification(
400
+ self, config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, *args
401
+ ):
402
+ config.num_labels = self.num_labels
403
+ model = GPT2ForSequenceClassification(config)
404
+ model.to(torch_device)
405
+ model.eval()
406
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels)
407
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
408
+
409
+ def create_and_check_gpt2_for_token_classification(
410
+ self, config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, *args
411
+ ):
412
+ config.num_labels = self.num_labels
413
+ model = GPT2ForTokenClassification(config)
414
+ model.to(torch_device)
415
+ model.eval()
416
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
417
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
418
+
419
+ def create_and_check_gpt2_weight_initialization(self, config, *args):
420
+ model = GPT2Model(config)
421
+ model_std = model.config.initializer_range / math.sqrt(2 * model.config.n_layer)
422
+ for key in model.state_dict().keys():
423
+ if "c_proj" in key and "weight" in key:
424
+ self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key]) - model_std), 0.001)
425
+ self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key]) - 0.0), 0.01)
426
+
427
+ def create_and_check_cached_forward_with_and_without_attention_mask(self, config, input_ids, *args):
428
+ # Relevant issue: https://github.com/huggingface/transformers/issues/31943
429
+ model = GPT2Model(config)
430
+ model.to(torch_device)
431
+ model.eval()
432
+
433
+ # We want this for SDPA, eager works with a `None` attention mask
434
+ assert (
435
+ model.config._attn_implementation == "sdpa"
436
+ ), "This test assumes the model to have the SDPA implementation for its attention calculations."
437
+
438
+ # Prepare cache and non_cache input, needs a full attention mask
439
+ cached_len = input_ids.shape[-1] // 2
440
+ input_mask = torch.ones(size=input_ids.size()).to(torch_device)
441
+ cache_inputs = {"input_ids": input_ids[:, :cached_len], "attention_mask": input_mask[:, :cached_len]}
442
+ non_cache_inputs = {"input_ids": input_ids[:, cached_len:], "attention_mask": input_mask}
443
+
444
+ # Cached forward once with the attention mask provided and the other time without it (which should assume full attention)
445
+ cache_outputs = model(**cache_inputs)
446
+ full_outputs_with_attention_mask = model(
447
+ **non_cache_inputs, past_key_values=cache_outputs.past_key_values
448
+ ).last_hidden_state
449
+ full_outputs_without_attention_mask = model(
450
+ non_cache_inputs["input_ids"], past_key_values=cache_outputs.past_key_values
451
+ ).last_hidden_state
452
+
453
+ self.parent.assertTrue(
454
+ torch.allclose(full_outputs_with_attention_mask, full_outputs_without_attention_mask, atol=1e-5)
455
+ )
456
+
457
+ def prepare_config_and_inputs_for_common(self):
458
+ config_and_inputs = self.prepare_config_and_inputs()
459
+
460
+ (
461
+ config,
462
+ input_ids,
463
+ input_mask,
464
+ head_mask,
465
+ token_type_ids,
466
+ mc_token_ids,
467
+ sequence_labels,
468
+ token_labels,
469
+ choice_labels,
470
+ ) = config_and_inputs
471
+
472
+ inputs_dict = {
473
+ "input_ids": input_ids,
474
+ "token_type_ids": token_type_ids,
475
+ "head_mask": head_mask,
476
+ }
477
+
478
+ return config, inputs_dict
479
+
480
+
481
+ @require_torch
482
+ class GPT2ModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
483
+ all_model_classes = (
484
+ (
485
+ GPT2Model,
486
+ GPT2LMHeadModel,
487
+ GPT2DoubleHeadsModel,
488
+ GPT2ForQuestionAnswering,
489
+ GPT2ForSequenceClassification,
490
+ GPT2ForTokenClassification,
491
+ )
492
+ if is_torch_available()
493
+ else ()
494
+ )
495
+ pipeline_model_mapping = (
496
+ {
497
+ "feature-extraction": GPT2Model,
498
+ "question-answering": GPT2ForQuestionAnswering,
499
+ "text-classification": GPT2ForSequenceClassification,
500
+ "text-generation": GPT2LMHeadModel,
501
+ "token-classification": GPT2ForTokenClassification,
502
+ "zero-shot": GPT2ForSequenceClassification,
503
+ }
504
+ if is_torch_available()
505
+ else {}
506
+ )
507
+ all_parallelizable_model_classes = (GPT2LMHeadModel, GPT2DoubleHeadsModel) if is_torch_available() else ()
508
+ fx_compatible = False # Broken by attention refactor cc @Cyrilvallez
509
+ test_missing_keys = False
510
+ test_model_parallel = True
511
+
512
+ # special case for DoubleHeads model
513
+ def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
514
+ inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
515
+
516
+ if return_labels:
517
+ if model_class.__name__ == "GPT2DoubleHeadsModel":
518
+ inputs_dict["labels"] = torch.zeros(
519
+ (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length),
520
+ dtype=torch.long,
521
+ device=torch_device,
522
+ )
523
+ inputs_dict["input_ids"] = inputs_dict["labels"]
524
+ inputs_dict["token_type_ids"] = inputs_dict["labels"]
525
+ inputs_dict["mc_token_ids"] = torch.zeros(
526
+ (self.model_tester.batch_size, self.model_tester.num_choices),
527
+ dtype=torch.long,
528
+ device=torch_device,
529
+ )
530
+ inputs_dict["mc_labels"] = torch.zeros(
531
+ self.model_tester.batch_size, dtype=torch.long, device=torch_device
532
+ )
533
+ return inputs_dict
534
+
535
+ def setUp(self):
536
+ self.model_tester = GPT2ModelTester(self)
537
+ self.config_tester = ConfigTester(self, config_class=GPT2Config, n_embd=37)
538
+
539
+ def tearDown(self):
540
+ super().tearDown()
541
+ # clean-up as much as possible GPU memory occupied by PyTorch
542
+ cleanup(torch_device)
543
+
544
+ def test_config(self):
545
+ self.config_tester.run_common_tests()
546
+
547
+ def test_gpt2_model(self):
548
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
549
+ self.model_tester.create_and_check_gpt2_model(*config_and_inputs)
550
+
551
+ def test_gpt2_model_past(self):
552
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
553
+ self.model_tester.create_and_check_gpt2_model_past(*config_and_inputs)
554
+
555
+ def test_gpt2_model_att_mask_past(self):
556
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
557
+ self.model_tester.create_and_check_gpt2_model_attention_mask_past(*config_and_inputs)
558
+
559
+ def test_gpt2_model_past_large_inputs(self):
560
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
561
+ self.model_tester.create_and_check_gpt2_model_past_large_inputs(*config_and_inputs)
562
+
563
+ def test_gpt2_lm_head_model(self):
564
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
565
+ self.model_tester.create_and_check_lm_head_model(*config_and_inputs)
566
+
567
+ def test_gpt2_double_lm_head_model(self):
568
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
569
+ self.model_tester.create_and_check_double_lm_head_model(*config_and_inputs)
570
+
571
+ def test_gpt2_question_answering_model(self):
572
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
573
+ self.model_tester.create_and_check_gpt2_for_question_answering(*config_and_inputs)
574
+
575
+ def test_gpt2_sequence_classification_model(self):
576
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
577
+ self.model_tester.create_and_check_gpt2_for_sequence_classification(*config_and_inputs)
578
+
579
+ def test_gpt2_token_classification_model(self):
580
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
581
+ self.model_tester.create_and_check_gpt2_for_token_classification(*config_and_inputs)
582
+
583
+ def test_gpt2_gradient_checkpointing(self):
584
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
585
+ self.model_tester.create_and_check_forward_and_backwards(*config_and_inputs, gradient_checkpointing=True)
586
+
587
+ def test_gpt2_scale_attn_by_inverse_layer_idx(self):
588
+ config_and_inputs = self.model_tester.prepare_config_and_inputs(scale_attn_by_inverse_layer_idx=True)
589
+ self.model_tester.create_and_check_forward_and_backwards(*config_and_inputs)
590
+
591
+ def test_gpt2_reorder_and_upcast_attn(self):
592
+ config_and_inputs = self.model_tester.prepare_config_and_inputs(reorder_and_upcast_attn=True)
593
+ self.model_tester.create_and_check_forward_and_backwards(*config_and_inputs)
594
+
595
+ def test_gpt2_weight_initialization(self):
596
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
597
+ self.model_tester.create_and_check_gpt2_weight_initialization(*config_and_inputs)
598
+
599
+ def test_cached_forward_with_and_without_attention_mask(self):
600
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
601
+ self.model_tester.create_and_check_cached_forward_with_and_without_attention_mask(*config_and_inputs)
602
+
603
+ @unittest.skip(
604
+ reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
605
+ )
606
+ def test_training_gradient_checkpointing(self):
607
+ pass
608
+
609
+ @unittest.skip(
610
+ reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
611
+ )
612
+ def test_training_gradient_checkpointing_use_reentrant(self):
613
+ pass
614
+
615
+ @unittest.skip(
616
+ reason="This architecture seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
617
+ )
618
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
619
+ pass
620
+
621
+ @slow
622
+ def test_batch_generation(self):
623
+ model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2")
624
+ model.to(torch_device)
625
+ tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
626
+
627
+ tokenizer.padding_side = "left"
628
+
629
+ # Define PAD Token = EOS Token = 50256
630
+ tokenizer.pad_token = tokenizer.eos_token
631
+ model.config.pad_token_id = model.config.eos_token_id
632
+
633
+ # use different length sentences to test batching
634
+ sentences = [
635
+ "Hello, my dog is a little",
636
+ "Today, I",
637
+ ]
638
+
639
+ inputs = tokenizer(sentences, return_tensors="pt", padding=True)
640
+ input_ids = inputs["input_ids"].to(torch_device)
641
+ token_type_ids = torch.cat(
642
+ [
643
+ input_ids.new_full((input_ids.shape[0], input_ids.shape[1] - 1), 0),
644
+ input_ids.new_full((input_ids.shape[0], 1), 500),
645
+ ],
646
+ dim=-1,
647
+ )
648
+
649
+ outputs = model.generate(
650
+ input_ids=input_ids,
651
+ attention_mask=inputs["attention_mask"].to(torch_device),
652
+ max_length=20,
653
+ )
654
+
655
+ outputs_tt = model.generate(
656
+ input_ids=input_ids,
657
+ attention_mask=inputs["attention_mask"].to(torch_device),
658
+ token_type_ids=token_type_ids,
659
+ max_length=20,
660
+ )
661
+
662
+ inputs_non_padded = tokenizer(sentences[0], return_tensors="pt").input_ids.to(torch_device)
663
+ output_non_padded = model.generate(input_ids=inputs_non_padded, max_length=20)
664
+
665
+ num_paddings = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item()
666
+ inputs_padded = tokenizer(sentences[1], return_tensors="pt").input_ids.to(torch_device)
667
+ output_padded = model.generate(input_ids=inputs_padded, max_length=model.config.max_length - num_paddings)
668
+
669
+ batch_out_sentence = tokenizer.batch_decode(outputs, skip_special_tokens=True)
670
+ batch_out_sentence_tt = tokenizer.batch_decode(outputs_tt, skip_special_tokens=True)
671
+ non_padded_sentence = tokenizer.decode(output_non_padded[0], skip_special_tokens=True)
672
+ padded_sentence = tokenizer.decode(output_padded[0], skip_special_tokens=True)
673
+
674
+ expected_output_sentence = [
675
+ "Hello, my dog is a little bit of a mess. I'm not sure if he's going",
676
+ "Today, I'm going to be doing a lot of research on this. I",
677
+ ]
678
+ self.assertListEqual(expected_output_sentence, batch_out_sentence)
679
+ self.assertTrue(batch_out_sentence_tt != batch_out_sentence) # token_type_ids should change output
680
+ self.assertListEqual(expected_output_sentence, [non_padded_sentence, padded_sentence])
681
+
682
+ @slow
683
+ def test_batch_generation_2heads(self):
684
+ model = GPT2DoubleHeadsModel.from_pretrained("openai-community/gpt2")
685
+ model.to(torch_device)
686
+ tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
687
+
688
+ tokenizer.padding_side = "left"
689
+
690
+ # This tokenizer has no pad token, so we have to set it in some way
691
+ # Define PAD Token = EOS Token = 50256
692
+ tokenizer.pad_token = tokenizer.eos_token
693
+ model.config.pad_token_id = model.config.eos_token_id
694
+
695
+ # use different length sentences to test batching
696
+ sentences = [
697
+ "Hello, my dog is a little",
698
+ "Today, I",
699
+ ]
700
+
701
+ inputs = tokenizer(sentences, return_tensors="pt", padding=True)
702
+ input_ids = inputs["input_ids"].to(torch_device)
703
+ token_type_ids = torch.cat(
704
+ [
705
+ input_ids.new_full((input_ids.shape[0], input_ids.shape[1] - 1), 0),
706
+ input_ids.new_full((input_ids.shape[0], 1), 500),
707
+ ],
708
+ dim=-1,
709
+ )
710
+
711
+ outputs = model.generate(
712
+ input_ids=input_ids,
713
+ attention_mask=inputs["attention_mask"].to(torch_device),
714
+ max_length=20,
715
+ )
716
+
717
+ outputs_tt = model.generate(
718
+ input_ids=input_ids,
719
+ attention_mask=inputs["attention_mask"].to(torch_device),
720
+ token_type_ids=token_type_ids,
721
+ max_length=20,
722
+ )
723
+
724
+ inputs_non_padded = tokenizer(sentences[0], return_tensors="pt").input_ids.to(torch_device)
725
+ output_non_padded = model.generate(input_ids=inputs_non_padded, max_length=20)
726
+
727
+ num_paddings = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item()
728
+ inputs_padded = tokenizer(sentences[1], return_tensors="pt").input_ids.to(torch_device)
729
+ output_padded = model.generate(input_ids=inputs_padded, max_length=model.config.max_length - num_paddings)
730
+
731
+ batch_out_sentence = tokenizer.batch_decode(outputs, skip_special_tokens=True)
732
+ batch_out_sentence_tt = tokenizer.batch_decode(outputs_tt, skip_special_tokens=True)
733
+ non_padded_sentence = tokenizer.decode(output_non_padded[0], skip_special_tokens=True)
734
+ padded_sentence = tokenizer.decode(output_padded[0], skip_special_tokens=True)
735
+
736
+ expected_output_sentence = [
737
+ "Hello, my dog is a little bit of a mess. I'm not sure if he's going",
738
+ "Today, I'm going to be doing a lot of research on this. I",
739
+ ]
740
+ self.assertListEqual(expected_output_sentence, batch_out_sentence)
741
+ self.assertTrue(batch_out_sentence_tt != batch_out_sentence) # token_type_ids should change output
742
+ self.assertListEqual(expected_output_sentence, [non_padded_sentence, padded_sentence])
743
+
744
+ @slow
745
+ def test_model_from_pretrained(self):
746
+ model_name = "openai-community/gpt2"
747
+ model = GPT2Model.from_pretrained(model_name)
748
+ self.assertIsNotNone(model)
749
+
750
+
751
+ @require_torch
752
+ class GPT2ModelLanguageGenerationTest(unittest.TestCase):
753
+ def tearDown(self):
754
+ super().tearDown()
755
+ # clean-up as much as possible GPU memory occupied by PyTorch
756
+ cleanup(torch_device, gc_collect=True)
757
+
758
+ def _test_lm_generate_gpt2_helper(
759
+ self,
760
+ gradient_checkpointing=False,
761
+ reorder_and_upcast_attn=False,
762
+ scale_attn_by_inverse_layer_idx=False,
763
+ verify_outputs=True,
764
+ ):
765
+ model = GPT2LMHeadModel.from_pretrained(
766
+ "openai-community/gpt2",
767
+ reorder_and_upcast_attn=reorder_and_upcast_attn,
768
+ scale_attn_by_inverse_layer_idx=scale_attn_by_inverse_layer_idx,
769
+ )
770
+ if gradient_checkpointing:
771
+ model.gradient_checkpointing_enable()
772
+ else:
773
+ model.gradient_checkpointing_disable()
774
+ model.to(torch_device)
775
+
776
+ # The dog
777
+ input_ids = torch.tensor([[464, 3290]], dtype=torch.long, device=torch_device)
778
+
779
+ # The dog was found in a field near the intersection of West and West Streets.\n\nThe dog
780
+ expected_output_ids = [464, 3290, 373, 1043, 287, 257, 2214, 1474, 262, 16246, 286, 2688, 290, 2688, 27262, 13, 198, 198, 464, 3290,] # fmt: skip
781
+ output_ids = model.generate(input_ids, do_sample=False, max_length=20)
782
+ if verify_outputs:
783
+ self.assertListEqual(output_ids[0].tolist(), expected_output_ids)
784
+
785
+ @slow
786
+ def test_lm_generate_gpt2(self):
787
+ self._test_lm_generate_gpt2_helper()
788
+
789
+ @slow
790
+ def test_lm_generate_gpt2_with_gradient_checkpointing(self):
791
+ self._test_lm_generate_gpt2_helper(gradient_checkpointing=True)
792
+
793
+ @slow
794
+ def test_lm_generate_gpt2_with_reorder_and_upcast_attn(self):
795
+ self._test_lm_generate_gpt2_helper(reorder_and_upcast_attn=True)
796
+
797
+ @slow
798
+ def test_lm_generate_gpt2_with_scale_attn_by_inverse_layer_idx(self):
799
+ self._test_lm_generate_gpt2_helper(scale_attn_by_inverse_layer_idx=True, verify_outputs=False)
800
+
801
+ @slow
802
+ def test_gpt2_sample(self):
803
+ tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
804
+ model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2")
805
+ model.to(torch_device)
806
+
807
+ torch.manual_seed(0)
808
+ tokenized = tokenizer("Today is a nice day and", return_tensors="pt", return_token_type_ids=True)
809
+ input_ids = tokenized.input_ids.to(torch_device)
810
+ output_ids = model.generate(input_ids, do_sample=True, max_length=20)
811
+ output_str = tokenizer.decode(output_ids[0], skip_special_tokens=True)
812
+
813
+ token_type_ids = tokenized.token_type_ids.to(torch_device)
814
+ output_seq = model.generate(input_ids=input_ids, do_sample=True, num_return_sequences=5, max_length=20)
815
+ output_seq_tt = model.generate(
816
+ input_ids=input_ids, token_type_ids=token_type_ids, do_sample=True, num_return_sequences=5, max_length=20
817
+ )
818
+ output_seq_strs = tokenizer.batch_decode(output_seq, skip_special_tokens=True)
819
+ output_seq_tt_strs = tokenizer.batch_decode(output_seq_tt, skip_special_tokens=True)
820
+
821
+ EXPECTED_OUTPUT_STR = (
822
+ "Today is a nice day and if you don't know anything about the state of play during your holiday"
823
+ )
824
+ self.assertEqual(output_str, EXPECTED_OUTPUT_STR)
825
+ self.assertTrue(
826
+ all(output_seq_strs[idx] != output_seq_tt_strs[idx] for idx in range(len(output_seq_tt_strs)))
827
+ ) # token_type_ids should change output
828
+
829
+ @slow
830
+ def test_contrastive_search_gpt2(self):
831
+ article = (
832
+ "DeepMind Technologies is a British artificial intelligence subsidiary of Alphabet Inc. and research "
833
+ "laboratory founded in 2010. DeepMind was acquired by Google in 2014. The company is based"
834
+ )
835
+
836
+ gpt2_tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2-large")
837
+ gpt2_model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2-large").to(torch_device)
838
+ input_ids = gpt2_tokenizer(article, return_tensors="pt").input_ids.to(torch_device)
839
+
840
+ outputs = gpt2_model.generate(input_ids, penalty_alpha=0.6, top_k=4, max_length=256)
841
+
842
+ generated_text = gpt2_tokenizer.batch_decode(outputs, skip_special_tokens=True)
843
+
844
+ self.assertListEqual(
845
+ generated_text,
846
+ [
847
+ "DeepMind Technologies is a British artificial intelligence subsidiary of Alphabet Inc. and research "
848
+ "laboratory founded in 2010. DeepMind was acquired by Google in 2014. The company is based in London, "
849
+ "United Kingdom\n\nGoogle has a lot of data on its users and uses it to improve its products, such as "
850
+ "Google Now, which helps users find the information they're looking for on the web. But the company "
851
+ "is not the only one to collect data on its users. Facebook, for example, has its own facial "
852
+ "recognition technology, as well as a database of millions of photos that it uses to personalize its "
853
+ "News Feed.\n\nFacebook's use of data is a hot topic in the tech industry, with privacy advocates "
854
+ "concerned about the company's ability to keep users' information private. In a blog post last "
855
+ 'year, Facebook CEO Mark Zuckerberg said his company would "do our best to be transparent about our '
856
+ 'data use and how we use it."\n\n"We have made it clear that we do not sell or share your data with '
857
+ 'third parties," Zuckerberg wrote. "If you have questions or concerns, please reach out to us at '
858
+ 'privacy@facebook.com."\n\nGoogle declined to comment on the privacy implications of its use of data, '
859
+ "but said in a statement to The Associated Press that"
860
+ ],
861
+ )
862
+
863
+ @require_flash_attn
864
+ @require_torch_gpu
865
+ @pytest.mark.flash_attn_test
866
+ @slow
867
+ def test_flash_attn_2_generate_padding_left(self):
868
+ """
869
+ Overwritting the common test as the test is flaky on tiny models
870
+ """
871
+ model = GPT2LMHeadModel.from_pretrained("gpt2", torch_dtype=torch.float16).to(0)
872
+
873
+ tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
874
+
875
+ texts = ["hi", "Hello this is a very long sentence"]
876
+
877
+ tokenizer.padding_side = "left"
878
+ tokenizer.pad_token = tokenizer.eos_token
879
+
880
+ inputs = tokenizer(texts, return_tensors="pt", padding=True).to(0)
881
+
882
+ output_native = model.generate(**inputs, max_new_tokens=20, do_sample=False)
883
+ output_native = tokenizer.batch_decode(output_native)
884
+
885
+ model = GPT2LMHeadModel.from_pretrained(
886
+ "gpt2", device_map={"": 0}, attn_implementation="flash_attention_2", torch_dtype=torch.float16
887
+ )
888
+
889
+ output_fa_2 = model.generate(**inputs, max_new_tokens=20, do_sample=False)
890
+ output_fa_2 = tokenizer.batch_decode(output_fa_2)
891
+
892
+ expected_output = [
893
+ "<|endoftext|><|endoftext|><|endoftext|><|endoftext|><|endoftext|><|endoftext|>hi, who was born in the city of Kolkata, was a member of the Kolkata",
894
+ "Hello this is a very long sentence. I'm sorry. I'm sorry. I'm sorry. I'm sorry. I'm sorry",
895
+ ]
896
+
897
+ self.assertListEqual(output_native, output_fa_2)
898
+ self.assertListEqual(output_native, expected_output)
tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt2/test_modeling_tf_gpt2.py ADDED
@@ -0,0 +1,733 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 GPT2Config, is_tf_available
21
+ from transformers.testing_utils import require_tf, require_tf2onnx, slow
22
+
23
+ from ...test_configuration_common import ConfigTester
24
+ from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
25
+ from ...test_pipeline_mixin import PipelineTesterMixin
26
+ from ...utils.test_modeling_tf_core import TFCoreModelTesterMixin
27
+
28
+
29
+ if is_tf_available():
30
+ import tensorflow as tf
31
+
32
+ from transformers import GPT2Tokenizer
33
+ from transformers.models.gpt2.modeling_tf_gpt2 import (
34
+ TFGPT2DoubleHeadsModel,
35
+ TFGPT2ForSequenceClassification,
36
+ TFGPT2LMHeadModel,
37
+ TFGPT2Model,
38
+ )
39
+ from transformers.tf_utils import shape_list
40
+
41
+
42
+ class TFGPT2ModelTester:
43
+ def __init__(
44
+ self,
45
+ parent,
46
+ ):
47
+ self.parent = parent
48
+ self.batch_size = 13
49
+ self.seq_length = 7
50
+ self.is_training = True
51
+ self.use_token_type_ids = True
52
+ self.use_input_mask = True
53
+ self.use_labels = True
54
+ self.use_mc_token_ids = True
55
+ self.vocab_size = 99
56
+ self.hidden_size = 32
57
+ self.num_hidden_layers = 2
58
+ self.num_attention_heads = 4
59
+ self.intermediate_size = 37
60
+ self.hidden_act = "gelu"
61
+ self.hidden_dropout_prob = 0.1
62
+ self.attention_probs_dropout_prob = 0.1
63
+ self.max_position_embeddings = 512
64
+ self.type_vocab_size = 16
65
+ self.type_sequence_label_size = 2
66
+ self.initializer_range = 0.02
67
+ self.num_labels = 3
68
+ self.num_choices = 4
69
+ self.scope = None
70
+ self.bos_token_id = self.vocab_size - 1
71
+ self.eos_token_id = self.vocab_size - 1
72
+ self.pad_token_id = self.vocab_size - 1
73
+
74
+ def prepare_config_and_inputs(self):
75
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
76
+
77
+ input_mask = None
78
+ if self.use_input_mask:
79
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
80
+
81
+ token_type_ids = None
82
+ if self.use_token_type_ids:
83
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
84
+
85
+ mc_token_ids = None
86
+ if self.use_mc_token_ids:
87
+ mc_token_ids = ids_tensor([self.batch_size, self.num_choices], self.seq_length)
88
+
89
+ sequence_labels = None
90
+ token_labels = None
91
+ choice_labels = None
92
+ if self.use_labels:
93
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
94
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
95
+ choice_labels = ids_tensor([self.batch_size], self.num_choices)
96
+
97
+ config = GPT2Config(
98
+ vocab_size=self.vocab_size,
99
+ n_embd=self.hidden_size,
100
+ n_layer=self.num_hidden_layers,
101
+ n_head=self.num_attention_heads,
102
+ # intermediate_size=self.intermediate_size,
103
+ # hidden_act=self.hidden_act,
104
+ # hidden_dropout_prob=self.hidden_dropout_prob,
105
+ # attention_probs_dropout_prob=self.attention_probs_dropout_prob,
106
+ n_positions=self.max_position_embeddings,
107
+ # type_vocab_size=self.type_vocab_size,
108
+ # initializer_range=self.initializer_range
109
+ bos_token_id=self.bos_token_id,
110
+ eos_token_id=self.eos_token_id,
111
+ pad_token_id=self.pad_token_id,
112
+ return_dict=True,
113
+ )
114
+
115
+ head_mask = ids_tensor([self.num_hidden_layers, self.num_attention_heads], 2)
116
+
117
+ return (
118
+ config,
119
+ input_ids,
120
+ input_mask,
121
+ head_mask,
122
+ token_type_ids,
123
+ mc_token_ids,
124
+ sequence_labels,
125
+ token_labels,
126
+ choice_labels,
127
+ )
128
+
129
+ def prepare_config_and_inputs_for_decoder(self):
130
+ (
131
+ config,
132
+ input_ids,
133
+ input_mask,
134
+ head_mask,
135
+ token_type_ids,
136
+ mc_token_ids,
137
+ sequence_labels,
138
+ token_labels,
139
+ choice_labels,
140
+ ) = self.prepare_config_and_inputs()
141
+
142
+ encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
143
+ encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
144
+
145
+ return (
146
+ config,
147
+ input_ids,
148
+ input_mask,
149
+ head_mask,
150
+ token_type_ids,
151
+ sequence_labels,
152
+ token_labels,
153
+ choice_labels,
154
+ encoder_hidden_states,
155
+ encoder_attention_mask,
156
+ )
157
+
158
+ def create_and_check_gpt2_model(self, config, input_ids, input_mask, head_mask, token_type_ids, *args):
159
+ model = TFGPT2Model(config=config)
160
+ inputs = {
161
+ "input_ids": input_ids,
162
+ "attention_mask": input_mask,
163
+ "token_type_ids": token_type_ids,
164
+ }
165
+ result = model(inputs)
166
+
167
+ inputs = [input_ids, None, input_mask] # None is the input for 'past'
168
+ result = model(inputs)
169
+
170
+ result = model(input_ids)
171
+
172
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
173
+
174
+ def create_and_check_gpt2_model_past(self, config, input_ids, input_mask, head_mask, token_type_ids, *args):
175
+ model = TFGPT2Model(config=config)
176
+
177
+ # first forward pass
178
+ outputs = model(input_ids, token_type_ids=token_type_ids, use_cache=True)
179
+ outputs_use_cache_conf = model(input_ids, token_type_ids=token_type_ids)
180
+ outputs_no_past = model(input_ids, token_type_ids=token_type_ids, use_cache=False)
181
+
182
+ self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))
183
+ self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)
184
+
185
+ output, past_key_values = outputs.to_tuple()
186
+
187
+ # create hypothetical next token and extent to next_input_ids
188
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
189
+ next_token_types = ids_tensor([self.batch_size, 1], self.type_vocab_size)
190
+
191
+ # append to next input_ids and token_type_ids
192
+ next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
193
+ next_token_type_ids = tf.concat([token_type_ids, next_token_types], axis=-1)
194
+
195
+ output_from_no_past = model(next_input_ids, token_type_ids=next_token_type_ids)["last_hidden_state"]
196
+ output_from_past = model(next_tokens, token_type_ids=next_token_types, past_key_values=past_key_values)[
197
+ "last_hidden_state"
198
+ ]
199
+
200
+ # select random slice
201
+ random_slice_idx = int(ids_tensor((1,), shape_list(output_from_past)[-1]))
202
+ output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx]
203
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx]
204
+
205
+ # test that outputs are equal for slice
206
+ tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-6)
207
+
208
+ def create_and_check_gpt2_model_attention_mask_past(
209
+ self, config, input_ids, input_mask, head_mask, token_type_ids, *args
210
+ ):
211
+ model = TFGPT2Model(config=config)
212
+
213
+ # create attention mask
214
+ half_seq_length = self.seq_length // 2
215
+ attn_mask_begin = tf.ones((self.batch_size, half_seq_length), dtype=tf.int32)
216
+ attn_mask_end = tf.zeros((self.batch_size, self.seq_length - half_seq_length), dtype=tf.int32)
217
+ attn_mask = tf.concat([attn_mask_begin, attn_mask_end], axis=1)
218
+
219
+ # first forward pass
220
+ output, past_key_values = model(input_ids, attention_mask=attn_mask).to_tuple()
221
+
222
+ # create hypothetical next token and extent to next_input_ids
223
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
224
+
225
+ # change a random masked slice from input_ids
226
+ random_seq_idx_to_change = ids_tensor((1,), half_seq_length).numpy() + 1
227
+ random_other_next_tokens = ids_tensor((self.batch_size, self.seq_length), config.vocab_size)
228
+ vector_condition = tf.range(self.seq_length) == (self.seq_length - random_seq_idx_to_change)
229
+ condition = tf.transpose(
230
+ tf.broadcast_to(tf.expand_dims(vector_condition, -1), (self.seq_length, self.batch_size))
231
+ )
232
+ input_ids = tf.where(condition, random_other_next_tokens, input_ids)
233
+
234
+ # append to next input_ids and attn_mask
235
+ next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
236
+ attn_mask = tf.concat([attn_mask, tf.ones((shape_list(attn_mask)[0], 1), dtype=tf.int32)], axis=1)
237
+
238
+ # get two different outputs
239
+ output_from_no_past = model(next_input_ids, attention_mask=attn_mask)["last_hidden_state"]
240
+ output_from_past = model(next_tokens, past_key_values=past_key_values, attention_mask=attn_mask)[
241
+ "last_hidden_state"
242
+ ]
243
+
244
+ # select random slice
245
+ random_slice_idx = int(ids_tensor((1,), shape_list(output_from_past)[-1]))
246
+ output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx]
247
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx]
248
+
249
+ # test that outputs are equal for slice
250
+ tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-12)
251
+
252
+ def create_and_check_gpt2_model_past_large_inputs(
253
+ self, config, input_ids, input_mask, head_mask, token_type_ids, *args
254
+ ):
255
+ model = TFGPT2Model(config=config)
256
+
257
+ input_ids = input_ids[:1, :]
258
+ input_mask = input_mask[:1, :]
259
+ token_type_ids = token_type_ids[:1, :]
260
+ self.batch_size = 1
261
+
262
+ # first forward pass
263
+ outputs = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, use_cache=True)
264
+
265
+ output, past_key_values = outputs.to_tuple()
266
+
267
+ # create hypothetical next token and extent to next_input_ids
268
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
269
+ next_attn_mask = ids_tensor((self.batch_size, 3), 2)
270
+ next_token_types = ids_tensor((self.batch_size, 3), self.type_vocab_size)
271
+
272
+ # append to next input_ids and token_type_ids
273
+ next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
274
+ next_attention_mask = tf.concat([input_mask, next_attn_mask], axis=-1)
275
+ next_token_type_ids = tf.concat([token_type_ids, next_token_types], axis=-1)
276
+
277
+ output_from_no_past = model(
278
+ next_input_ids, token_type_ids=next_token_type_ids, attention_mask=next_attention_mask
279
+ )["last_hidden_state"]
280
+ output_from_past = model(
281
+ next_tokens,
282
+ token_type_ids=next_token_types,
283
+ attention_mask=next_attention_mask,
284
+ past_key_values=past_key_values,
285
+ )["last_hidden_state"]
286
+ self.parent.assertTrue(output_from_past.shape[1] == next_tokens.shape[1])
287
+
288
+ # select random slice
289
+ random_slice_idx = int(ids_tensor((1,), shape_list(output_from_past)[-1]))
290
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx]
291
+ output_from_past_slice = output_from_past[:, :, random_slice_idx]
292
+
293
+ # test that outputs are equal for slice
294
+ tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3)
295
+
296
+ def create_and_check_gpt2_lm_head(self, config, input_ids, input_mask, head_mask, token_type_ids, *args):
297
+ model = TFGPT2LMHeadModel(config=config)
298
+ inputs = {
299
+ "input_ids": input_ids,
300
+ "attention_mask": input_mask,
301
+ "token_type_ids": token_type_ids,
302
+ }
303
+ result = model(inputs)
304
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
305
+
306
+ def create_and_check_gpt2_double_head(
307
+ self, config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, *args
308
+ ):
309
+ model = TFGPT2DoubleHeadsModel(config=config)
310
+
311
+ multiple_choice_inputs_ids = tf.tile(tf.expand_dims(input_ids, 1), (1, self.num_choices, 1))
312
+ multiple_choice_input_mask = tf.tile(tf.expand_dims(input_mask, 1), (1, self.num_choices, 1))
313
+ multiple_choice_token_type_ids = tf.tile(tf.expand_dims(token_type_ids, 1), (1, self.num_choices, 1))
314
+
315
+ inputs = {
316
+ "input_ids": multiple_choice_inputs_ids,
317
+ "mc_token_ids": mc_token_ids,
318
+ "attention_mask": multiple_choice_input_mask,
319
+ "token_type_ids": multiple_choice_token_type_ids,
320
+ }
321
+ result = model(inputs)
322
+ self.parent.assertEqual(
323
+ result.logits.shape, (self.batch_size, self.num_choices, self.seq_length, self.vocab_size)
324
+ )
325
+ self.parent.assertEqual(result.mc_logits.shape, (self.batch_size, self.num_choices))
326
+
327
+ def create_and_check_gpt2_for_sequence_classification(
328
+ self, config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, *args
329
+ ):
330
+ config.num_labels = self.num_labels
331
+ inputs = {
332
+ "input_ids": input_ids,
333
+ "attention_mask": input_mask,
334
+ "token_type_ids": token_type_ids,
335
+ "labels": sequence_labels,
336
+ }
337
+ model = TFGPT2ForSequenceClassification(config)
338
+
339
+ result = model(inputs)
340
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
341
+
342
+ def prepare_config_and_inputs_for_common(self):
343
+ config_and_inputs = self.prepare_config_and_inputs()
344
+
345
+ (
346
+ config,
347
+ input_ids,
348
+ input_mask,
349
+ head_mask,
350
+ token_type_ids,
351
+ mc_token_ids,
352
+ sequence_labels,
353
+ token_labels,
354
+ choice_labels,
355
+ ) = config_and_inputs
356
+
357
+ inputs_dict = {
358
+ "input_ids": input_ids,
359
+ "token_type_ids": token_type_ids,
360
+ "attention_mask": input_mask,
361
+ }
362
+ return config, inputs_dict
363
+
364
+
365
+ @require_tf
366
+ class TFGPT2ModelTest(TFModelTesterMixin, TFCoreModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
367
+ all_model_classes = (
368
+ (TFGPT2Model, TFGPT2LMHeadModel, TFGPT2ForSequenceClassification, TFGPT2DoubleHeadsModel)
369
+ if is_tf_available()
370
+ else ()
371
+ )
372
+ all_generative_model_classes = (TFGPT2LMHeadModel,) if is_tf_available() else ()
373
+ pipeline_model_mapping = (
374
+ {
375
+ "feature-extraction": TFGPT2Model,
376
+ "text-classification": TFGPT2ForSequenceClassification,
377
+ "text-generation": TFGPT2LMHeadModel,
378
+ "zero-shot": TFGPT2ForSequenceClassification,
379
+ }
380
+ if is_tf_available()
381
+ else {}
382
+ )
383
+ test_head_masking = False
384
+ test_onnx = True
385
+ onnx_min_opset = 10
386
+
387
+ def setUp(self):
388
+ self.model_tester = TFGPT2ModelTester(self)
389
+ self.config_tester = ConfigTester(self, config_class=GPT2Config, n_embd=37)
390
+
391
+ def test_config(self):
392
+ self.config_tester.run_common_tests()
393
+
394
+ def test_gpt2_model(self):
395
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
396
+ self.model_tester.create_and_check_gpt2_model(*config_and_inputs)
397
+
398
+ def test_gpt2_model_past(self):
399
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
400
+ self.model_tester.create_and_check_gpt2_model_past(*config_and_inputs)
401
+
402
+ def test_gpt2_model_att_mask_past(self):
403
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
404
+ self.model_tester.create_and_check_gpt2_model_attention_mask_past(*config_and_inputs)
405
+
406
+ def test_gpt2_model_past_large_inputs(self):
407
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
408
+ self.model_tester.create_and_check_gpt2_model_past_large_inputs(*config_and_inputs)
409
+
410
+ def test_gpt2_lm_head(self):
411
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
412
+ self.model_tester.create_and_check_gpt2_lm_head(*config_and_inputs)
413
+
414
+ def test_gpt2_double_head(self):
415
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
416
+ self.model_tester.create_and_check_gpt2_double_head(*config_and_inputs)
417
+
418
+ def test_gpt2_sequence_classification_model(self):
419
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
420
+ self.model_tester.create_and_check_gpt2_for_sequence_classification(*config_and_inputs)
421
+
422
+ @slow
423
+ def test_model_from_pretrained(self):
424
+ model_name = "openai-community/gpt2"
425
+ model = TFGPT2Model.from_pretrained(model_name)
426
+ self.assertIsNotNone(model)
427
+
428
+ # overwrite from common since ONNX runtime optimization doesn't work with tf.gather() when the argument
429
+ # `batch_dims` > 0"
430
+ @require_tf2onnx
431
+ @slow
432
+ def test_onnx_runtime_optimize(self):
433
+ if not self.test_onnx:
434
+ return
435
+
436
+ import onnxruntime
437
+ import tf2onnx
438
+
439
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
440
+
441
+ for model_class in self.all_model_classes:
442
+ # Skip these 2 classes which uses `tf.gather` with `batch_dims=1`
443
+ if model_class in [TFGPT2ForSequenceClassification, TFGPT2DoubleHeadsModel]:
444
+ continue
445
+
446
+ model = model_class(config)
447
+ model.build_in_name_scope()
448
+
449
+ onnx_model_proto, _ = tf2onnx.convert.from_keras(model, opset=self.onnx_min_opset)
450
+
451
+ onnxruntime.InferenceSession(onnx_model_proto.SerializeToString())
452
+
453
+ # TODO (Joao): fix me
454
+ @unittest.skip("Onnx compliancy broke with TF 2.10")
455
+ def test_onnx_compliancy(self):
456
+ pass
457
+
458
+
459
+ @require_tf
460
+ class TFGPT2ModelLanguageGenerationTest(unittest.TestCase):
461
+ @slow
462
+ def test_lm_generate_greedy_distilgpt2_batch_special(self):
463
+ model = TFGPT2LMHeadModel.from_pretrained("distilbert/distilgpt2")
464
+ tokenizer = GPT2Tokenizer.from_pretrained("distilbert/distilgpt2")
465
+
466
+ tokenizer.pad_token = tokenizer.eos_token
467
+ tokenizer.padding_side = "left"
468
+
469
+ sentences = ["Today is a beautiful day and", "Yesterday was"]
470
+ input_ids = tokenizer(sentences, return_tensors="tf", padding=True)
471
+
472
+ generation_kwargs = {
473
+ "bad_words_ids": [tokenizer("is").input_ids, tokenizer("angry about").input_ids],
474
+ "no_repeat_ngram_size": 2,
475
+ "do_sample": False,
476
+ "repetition_penalty": 1.3,
477
+ }
478
+
479
+ output_ids = model.generate(**input_ids, **generation_kwargs)
480
+
481
+ output_strings = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
482
+ expected_output_string = [
483
+ "Today is a beautiful day and I am so happy to be able take part in this amazing event.",
484
+ "Yesterday was a very interesting time for the world to see how much of this is",
485
+ ]
486
+ self.assertListEqual(output_strings, expected_output_string)
487
+
488
+ @slow
489
+ def test_lm_generate_sample_distilgpt2_batch_special(self):
490
+ model = TFGPT2LMHeadModel.from_pretrained("distilbert/distilgpt2")
491
+ tokenizer = GPT2Tokenizer.from_pretrained("distilbert/distilgpt2")
492
+
493
+ tokenizer.pad_token = tokenizer.eos_token
494
+ tokenizer.padding_side = "left"
495
+
496
+ sentences = ["Today is a beautiful day and", "Yesterday was"]
497
+ input_ids = tokenizer(sentences, return_tensors="tf", padding=True)
498
+
499
+ generation_kwargs = {
500
+ "do_sample": True,
501
+ "bad_words_ids": [tokenizer("is").input_ids, tokenizer("angry about").input_ids],
502
+ "no_repeat_ngram_size": 2,
503
+ "repetition_penalty": 1.3,
504
+ "temperature": 1.5,
505
+ "top_k": 500,
506
+ "top_p": 0.9,
507
+ "seed": [42, 0], # seed set -> deterministic sampling sequence -> deterministic generation
508
+ }
509
+
510
+ # forces the generation to happen on CPU, to avoid GPU-related quirks
511
+ with tf.device(":/CPU:0"):
512
+ output_ids = model.generate(**input_ids, **generation_kwargs)
513
+
514
+ output_strings = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
515
+
516
+ expected_output_string = [
517
+ "Today is a beautiful day and we will make you feel very hot/terrific in all your",
518
+ "Yesterday was known by national television networks as Le Big Show or Wild Dog Jeopard",
519
+ ]
520
+ self.assertListEqual(output_strings, expected_output_string)
521
+
522
+ @slow
523
+ def test_lm_generate_greedy_distilgpt2_beam_search_special(self):
524
+ model = TFGPT2LMHeadModel.from_pretrained("distilbert/distilgpt2")
525
+ tokenizer = GPT2Tokenizer.from_pretrained("distilbert/distilgpt2")
526
+
527
+ tokenizer.pad_token = tokenizer.eos_token
528
+ tokenizer.padding_side = "left"
529
+
530
+ sentences = ["Today is a beautiful day and", "Yesterday was"]
531
+ input_ids = tokenizer(sentences, return_tensors="tf", padding=True)
532
+
533
+ generation_kwargs = {
534
+ "bad_words_ids": [tokenizer("is").input_ids, tokenizer("angry about").input_ids],
535
+ "no_repeat_ngram_size": 2,
536
+ "do_sample": False,
537
+ "num_beams": 2,
538
+ }
539
+
540
+ output_ids = model.generate(**input_ids, **generation_kwargs)
541
+
542
+ output_strings = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
543
+ expected_output_string = [
544
+ "Today is a beautiful day and a great day for all of us.\n\nI’m",
545
+ "Yesterday was the first time that a person has been arrested in the United States for",
546
+ ]
547
+ self.assertListEqual(output_strings, expected_output_string)
548
+
549
+ @slow
550
+ def test_lm_generate_distilgpt2_left_padding(self):
551
+ """Tests that the generated text is the same, regarless of left padding"""
552
+ model = TFGPT2LMHeadModel.from_pretrained("distilbert/distilgpt2")
553
+ tokenizer = GPT2Tokenizer.from_pretrained("distilbert/distilgpt2")
554
+
555
+ tokenizer.pad_token = tokenizer.eos_token
556
+ tokenizer.padding_side = "left"
557
+
558
+ generation_kwargs = {
559
+ "bad_words_ids": [tokenizer("is").input_ids, tokenizer("angry about").input_ids],
560
+ "no_repeat_ngram_size": 2,
561
+ "do_sample": False,
562
+ "repetition_penalty": 1.3,
563
+ }
564
+ expected_output_string = (
565
+ "Today is a beautiful day and I am so happy to be able take part in this amazing event."
566
+ )
567
+
568
+ sentences = ["Today is a beautiful day and"]
569
+ input_ids = tokenizer(sentences, return_tensors="tf", padding=True)
570
+ # using default length
571
+ output_ids = model.generate(**input_ids, **generation_kwargs)
572
+ output_strings = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
573
+ self.assertEqual(output_strings[0], expected_output_string)
574
+
575
+ sentences = ["Today is a beautiful day and", "This is a very long input that we absolutely don't care about"]
576
+ input_ids = tokenizer(sentences, return_tensors="tf", padding=True)
577
+ # longer max length to capture the full length (remember: it is left padded)
578
+ output_ids = model.generate(**input_ids, **generation_kwargs, max_length=27)
579
+ output_strings = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
580
+ self.assertEqual(output_strings[0], expected_output_string)
581
+
582
+ @slow
583
+ def test_lm_generate_gpt2_greedy_xla(self):
584
+ model = TFGPT2LMHeadModel.from_pretrained("openai-community/gpt2")
585
+ tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
586
+
587
+ tokenizer.pad_token = tokenizer.eos_token
588
+ tokenizer.padding_side = "left"
589
+
590
+ sentences = ["The dog", "The flying machine"]
591
+ expected_output_strings = [
592
+ "The dog was found in a field near the intersection of West and West Streets.\n\nThe",
593
+ "The flying machine is a small, lightweight, and lightweight aircraft that can be used for any type of",
594
+ ]
595
+ input_ids = tokenizer(sentences, return_tensors="tf", padding=True)
596
+
597
+ output_ids = model.generate(**input_ids, do_sample=False)
598
+ output_strings = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
599
+ self.assertListEqual(output_strings, expected_output_strings)
600
+
601
+ xla_generate = tf.function(model.generate, jit_compile=True)
602
+ output_ids = xla_generate(**input_ids, do_sample=False)
603
+ output_strings = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
604
+ self.assertListEqual(output_strings, expected_output_strings)
605
+
606
+ @slow
607
+ def test_lm_generate_gpt2_sample_xla(self):
608
+ # NOTE: due to the small numerical differences that are natural when we compile to XLA, sampling the same
609
+ # output out of the same seed is far from guaranteed. We can, however, confirm that the results are sensible
610
+ # and that we can seed both versions.
611
+
612
+ # forces the generation to happen on CPU, to avoid GPU-related quirks
613
+ with tf.device(":/CPU:0"):
614
+ model = TFGPT2LMHeadModel.from_pretrained("openai-community/gpt2")
615
+ tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
616
+
617
+ tokenizer.pad_token = tokenizer.eos_token
618
+ tokenizer.padding_side = "left"
619
+
620
+ sentence = ["The dog", "The flying machine"]
621
+ expected_output_string = [
622
+ "The dog owner asked why did our vet decide there needed to be extra ventilation inside because most"
623
+ " puppies",
624
+ "The flying machine was made by an artist who found it difficult to control it as it did not use",
625
+ ]
626
+ expected_output_string_xla = [
627
+ "The dog has been named in connection with the murder of a 20-year-old man in",
628
+ "The flying machine is a new and improved system to operate and operate a new system and system "
629
+ "system system",
630
+ ]
631
+ input_ids = tokenizer(sentence, return_tensors="tf", padding=True)
632
+
633
+ output_ids = model.generate(**input_ids, do_sample=True, seed=[7, 0])
634
+ output_strings = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
635
+ self.assertListEqual(output_strings, expected_output_string)
636
+
637
+ xla_generate = tf.function(model.generate, jit_compile=True)
638
+ output_ids = xla_generate(**input_ids, do_sample=True, seed=[7, 0])
639
+ output_strings = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
640
+ self.assertListEqual(output_strings, expected_output_string_xla)
641
+
642
+ @slow
643
+ def test_lm_generate_gpt2_beam_search_xla(self):
644
+ model = TFGPT2LMHeadModel.from_pretrained("openai-community/gpt2")
645
+ tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
646
+
647
+ tokenizer.pad_token = tokenizer.eos_token
648
+ tokenizer.padding_side = "left"
649
+
650
+ sentences = ["The dog", "The flying machine"]
651
+ expected_output_strings = [
652
+ "The dog was found in the backyard of a home in the 6500 block of South Main Street",
653
+ "The flying machine is a very powerful machine, but it's not a very powerful machine. It's",
654
+ ]
655
+ input_ids = tokenizer(sentences, return_tensors="tf", padding=True)
656
+
657
+ output_ids = model.generate(**input_ids, do_sample=False, num_beams=2)
658
+ output_strings = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
659
+ self.assertListEqual(output_strings, expected_output_strings)
660
+
661
+ xla_generate = tf.function(model.generate, jit_compile=True)
662
+ output_ids = xla_generate(**input_ids, do_sample=False, num_beams=2)
663
+ output_strings = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
664
+ self.assertListEqual(output_strings, expected_output_strings)
665
+
666
+ @slow
667
+ def test_contrastive_search_gpt2(self):
668
+ article = (
669
+ "DeepMind Technologies is a British artificial intelligence subsidiary of Alphabet Inc. and research "
670
+ "laboratory founded in 2010. DeepMind was acquired by Google in 2014. The company is based"
671
+ )
672
+
673
+ gpt2_tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2-large")
674
+ gpt2_model = TFGPT2LMHeadModel.from_pretrained("openai-community/gpt2-large")
675
+ input_ids = gpt2_tokenizer(article, return_tensors="tf")
676
+
677
+ outputs = gpt2_model.generate(**input_ids, penalty_alpha=0.6, top_k=4, max_length=256)
678
+
679
+ generated_text = gpt2_tokenizer.batch_decode(outputs, skip_special_tokens=True)
680
+
681
+ self.assertListEqual(
682
+ generated_text,
683
+ [
684
+ "DeepMind Technologies is a British artificial intelligence subsidiary of Alphabet Inc. and research "
685
+ "laboratory founded in 2010. DeepMind was acquired by Google in 2014. The company is based in London, "
686
+ "United Kingdom\n\nGoogle has a lot of data on its users and uses it to improve its products, such as "
687
+ "Google Now, which helps users find the information they're looking for on the web. But the company "
688
+ "is not the only one to collect data on its users. Facebook, for example, has its own facial "
689
+ "recognition technology, as well as a database of millions of photos that it uses to personalize its "
690
+ "News Feed.\n\nFacebook's use of data is a hot topic in the tech industry, with privacy advocates "
691
+ "concerned about the company's ability to keep users' information private. In a blog post last "
692
+ 'year, Facebook CEO Mark Zuckerberg said his company would "do our best to be transparent about our '
693
+ 'data use and how we use it."\n\n"We have made it clear that we do not sell or share your data with '
694
+ 'third parties," Zuckerberg wrote. "If you have questions or concerns, please reach out to us at '
695
+ 'privacy@facebook.com."\n\nGoogle declined to comment on the privacy implications of its use of data, '
696
+ "but said in a statement to The Associated Press that"
697
+ ],
698
+ )
699
+
700
+ @slow
701
+ def test_contrastive_search_gpt2_xla(self):
702
+ article = (
703
+ "DeepMind Technologies is a British artificial intelligence subsidiary of Alphabet Inc. and research "
704
+ "laboratory founded in 2010. DeepMind was acquired by Google in 2014. The company is based"
705
+ )
706
+
707
+ gpt2_tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2-large")
708
+ gpt2_model = TFGPT2LMHeadModel.from_pretrained("openai-community/gpt2-large")
709
+ input_ids = gpt2_tokenizer(article, return_tensors="tf")
710
+
711
+ xla_generate = tf.function(gpt2_model.generate, jit_compile=True)
712
+ outputs = xla_generate(**input_ids, penalty_alpha=0.6, top_k=4, max_length=256)
713
+
714
+ generated_text = gpt2_tokenizer.batch_decode(outputs, skip_special_tokens=True)
715
+
716
+ self.assertListEqual(
717
+ generated_text,
718
+ [
719
+ "DeepMind Technologies is a British artificial intelligence subsidiary of Alphabet Inc. and research "
720
+ "laboratory founded in 2010. DeepMind was acquired by Google in 2014. The company is based in London, "
721
+ "United Kingdom\n\nGoogle has a lot of data on its users and uses it to improve its products, such as "
722
+ "Google Now, which helps users find the information they're looking for on the web. But the company "
723
+ "is not the only one to collect data on its users. Facebook, for example, has its own facial "
724
+ "recognition technology, as well as a database of millions of photos that it uses to personalize its "
725
+ "News Feed.\n\nFacebook's use of data is a hot topic in the tech industry, with privacy advocates "
726
+ "concerned about the company's ability to keep users' information private. In a blog post last "
727
+ 'year, Facebook CEO Mark Zuckerberg said his company would "do our best to be transparent about our '
728
+ 'data use and how we use it."\n\n"We have made it clear that we do not sell or share your data with '
729
+ 'third parties," Zuckerberg wrote. "If you have questions or concerns, please reach out to us at '
730
+ 'privacy@facebook.com."\n\nGoogle declined to comment on the privacy implications of its use of data, '
731
+ "but said in a statement to The Associated Press that"
732
+ ],
733
+ )
tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt2/test_tokenization_gpt2.py ADDED
@@ -0,0 +1,355 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
17
+ import json
18
+ import os
19
+ import unittest
20
+
21
+ from transformers import AutoTokenizer, GPT2Tokenizer, GPT2TokenizerFast
22
+ from transformers.models.gpt2.tokenization_gpt2 import VOCAB_FILES_NAMES
23
+ from transformers.testing_utils import require_jinja, require_tokenizers
24
+
25
+ from ...test_tokenization_common import TokenizerTesterMixin
26
+
27
+
28
+ @require_tokenizers
29
+ class GPT2TokenizationTest(TokenizerTesterMixin, unittest.TestCase):
30
+ from_pretrained_id = "openai-community/gpt2"
31
+ tokenizer_class = GPT2Tokenizer
32
+ rust_tokenizer_class = GPT2TokenizerFast
33
+ test_rust_tokenizer = True
34
+ from_pretrained_kwargs = {"add_prefix_space": True}
35
+ test_seq2seq = False
36
+
37
+ def setUp(self):
38
+ super().setUp()
39
+
40
+ # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
41
+ vocab = [
42
+ "l",
43
+ "o",
44
+ "w",
45
+ "e",
46
+ "r",
47
+ "s",
48
+ "t",
49
+ "i",
50
+ "d",
51
+ "n",
52
+ "\u0120",
53
+ "\u0120l",
54
+ "\u0120n",
55
+ "\u0120lo",
56
+ "\u0120low",
57
+ "er",
58
+ "\u0120lowest",
59
+ "\u0120newer",
60
+ "\u0120wider",
61
+ "<unk>",
62
+ "<|endoftext|>",
63
+ ]
64
+ vocab_tokens = dict(zip(vocab, range(len(vocab))))
65
+ merges = ["#version: 0.2", "\u0120 l", "\u0120l o", "\u0120lo w", "e r", ""]
66
+ self.special_tokens_map = {"unk_token": "<unk>"}
67
+
68
+ self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"])
69
+ self.merges_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["merges_file"])
70
+ with open(self.vocab_file, "w", encoding="utf-8") as fp:
71
+ fp.write(json.dumps(vocab_tokens) + "\n")
72
+ with open(self.merges_file, "w", encoding="utf-8") as fp:
73
+ fp.write("\n".join(merges))
74
+
75
+ def get_tokenizer(self, **kwargs):
76
+ kwargs.update(self.special_tokens_map)
77
+ return GPT2Tokenizer.from_pretrained(self.tmpdirname, **kwargs)
78
+
79
+ def get_rust_tokenizer(self, **kwargs):
80
+ kwargs.update(self.special_tokens_map)
81
+ return GPT2TokenizerFast.from_pretrained(self.tmpdirname, **kwargs)
82
+
83
+ def get_input_output_texts(self, tokenizer):
84
+ input_text = "lower newer"
85
+ output_text = "lower newer"
86
+ return input_text, output_text
87
+
88
+ def test_full_tokenizer(self):
89
+ tokenizer = GPT2Tokenizer(self.vocab_file, self.merges_file, **self.special_tokens_map)
90
+ text = "lower newer"
91
+ bpe_tokens = ["\u0120low", "er", "\u0120", "n", "e", "w", "er"]
92
+ tokens = tokenizer.tokenize(text, add_prefix_space=True)
93
+ self.assertListEqual(tokens, bpe_tokens)
94
+
95
+ input_tokens = tokens + [tokenizer.unk_token]
96
+ input_bpe_tokens = [14, 15, 10, 9, 3, 2, 15, 19]
97
+ self.assertListEqual(tokenizer.convert_tokens_to_ids(input_tokens), input_bpe_tokens)
98
+
99
+ def test_rust_and_python_full_tokenizers(self):
100
+ if not self.test_rust_tokenizer:
101
+ self.skipTest(reason="test_rust_tokenizer is set to False")
102
+
103
+ tokenizer = self.get_tokenizer()
104
+ rust_tokenizer = self.get_rust_tokenizer(add_prefix_space=True)
105
+
106
+ sequence = "lower newer"
107
+
108
+ # Testing tokenization
109
+ tokens = tokenizer.tokenize(sequence, add_prefix_space=True)
110
+ rust_tokens = rust_tokenizer.tokenize(sequence)
111
+ self.assertListEqual(tokens, rust_tokens)
112
+
113
+ # Testing conversion to ids without special tokens
114
+ ids = tokenizer.encode(sequence, add_special_tokens=False, add_prefix_space=True)
115
+ rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False)
116
+ self.assertListEqual(ids, rust_ids)
117
+
118
+ # Testing conversion to ids with special tokens
119
+ rust_tokenizer = self.get_rust_tokenizer(add_prefix_space=True)
120
+ ids = tokenizer.encode(sequence, add_prefix_space=True)
121
+ rust_ids = rust_tokenizer.encode(sequence)
122
+ self.assertListEqual(ids, rust_ids)
123
+
124
+ # Testing the unknown token
125
+ input_tokens = tokens + [rust_tokenizer.unk_token]
126
+ input_bpe_tokens = [14, 15, 10, 9, 3, 2, 15, 19]
127
+ self.assertListEqual(rust_tokenizer.convert_tokens_to_ids(input_tokens), input_bpe_tokens)
128
+
129
+ @unittest.skip
130
+ def test_pretokenized_inputs(self, *args, **kwargs):
131
+ # It's very difficult to mix/test pretokenization with byte-level
132
+ # And get both GPT2 and Roberta to work at the same time (mostly an issue of adding a space before the string)
133
+ pass
134
+
135
+ def test_padding(self, max_length=15):
136
+ for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
137
+ with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
138
+ tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
139
+
140
+ # Simple input
141
+ s = "This is a simple input"
142
+ s2 = ["This is a simple input 1", "This is a simple input 2"]
143
+ p = ("This is a simple input", "This is a pair")
144
+ p2 = [
145
+ ("This is a simple input 1", "This is a simple input 2"),
146
+ ("This is a simple pair 1", "This is a simple pair 2"),
147
+ ]
148
+
149
+ # Simple input tests
150
+ self.assertRaises(ValueError, tokenizer_r.encode, s, max_length=max_length, padding="max_length")
151
+
152
+ # Simple input
153
+ self.assertRaises(ValueError, tokenizer_r.encode_plus, s, max_length=max_length, padding="max_length")
154
+
155
+ # Simple input
156
+ self.assertRaises(
157
+ ValueError,
158
+ tokenizer_r.batch_encode_plus,
159
+ s2,
160
+ max_length=max_length,
161
+ padding="max_length",
162
+ )
163
+
164
+ # Pair input
165
+ self.assertRaises(ValueError, tokenizer_r.encode, p, max_length=max_length, padding="max_length")
166
+
167
+ # Pair input
168
+ self.assertRaises(ValueError, tokenizer_r.encode_plus, p, max_length=max_length, padding="max_length")
169
+
170
+ # Pair input
171
+ self.assertRaises(
172
+ ValueError,
173
+ tokenizer_r.batch_encode_plus,
174
+ p2,
175
+ max_length=max_length,
176
+ padding="max_length",
177
+ )
178
+
179
+ def test_padding_if_pad_token_set_slow(self):
180
+ tokenizer = GPT2Tokenizer.from_pretrained(self.tmpdirname, pad_token="<pad>")
181
+
182
+ # Simple input
183
+ s = "This is a simple input"
184
+ s2 = ["This is a simple input looooooooong", "This is a simple input"]
185
+ p = ("This is a simple input", "This is a pair")
186
+ p2 = [
187
+ ("This is a simple input loooooong", "This is a simple input"),
188
+ ("This is a simple pair loooooong", "This is a simple pair"),
189
+ ]
190
+
191
+ pad_token_id = tokenizer.pad_token_id
192
+
193
+ out_s = tokenizer(s, padding="max_length", max_length=30, return_tensors="np")
194
+ out_s2 = tokenizer(s2, padding=True, truncate=True, return_tensors="np")
195
+ out_p = tokenizer(*p, padding="max_length", max_length=60, return_tensors="np")
196
+ out_p2 = tokenizer(p2, padding=True, truncate=True, return_tensors="np")
197
+
198
+ # s
199
+ # test single string max_length padding
200
+ self.assertEqual(out_s["input_ids"].shape[-1], 30)
201
+ self.assertTrue(pad_token_id in out_s["input_ids"])
202
+ self.assertTrue(0 in out_s["attention_mask"])
203
+
204
+ # s2
205
+ # test automatic padding
206
+ self.assertEqual(out_s2["input_ids"].shape[-1], 33)
207
+ # long slice doesn't have padding
208
+ self.assertFalse(pad_token_id in out_s2["input_ids"][0])
209
+ self.assertFalse(0 in out_s2["attention_mask"][0])
210
+ # short slice does have padding
211
+ self.assertTrue(pad_token_id in out_s2["input_ids"][1])
212
+ self.assertTrue(0 in out_s2["attention_mask"][1])
213
+
214
+ # p
215
+ # test single pair max_length padding
216
+ self.assertEqual(out_p["input_ids"].shape[-1], 60)
217
+ self.assertTrue(pad_token_id in out_p["input_ids"])
218
+ self.assertTrue(0 in out_p["attention_mask"])
219
+
220
+ # p2
221
+ # test automatic padding pair
222
+ self.assertEqual(out_p2["input_ids"].shape[-1], 52)
223
+ # long slice pair doesn't have padding
224
+ self.assertFalse(pad_token_id in out_p2["input_ids"][0])
225
+ self.assertFalse(0 in out_p2["attention_mask"][0])
226
+ # short slice pair does have padding
227
+ self.assertTrue(pad_token_id in out_p2["input_ids"][1])
228
+ self.assertTrue(0 in out_p2["attention_mask"][1])
229
+
230
+ def test_add_bos_token_slow(self):
231
+ bos_token = "$$$"
232
+ tokenizer = GPT2Tokenizer.from_pretrained(self.tmpdirname, bos_token=bos_token, add_bos_token=True)
233
+
234
+ s = "This is a simple input"
235
+ s2 = ["This is a simple input 1", "This is a simple input 2"]
236
+
237
+ bos_token_id = tokenizer.bos_token_id
238
+
239
+ out_s = tokenizer(s)
240
+ out_s2 = tokenizer(s2)
241
+
242
+ self.assertEqual(out_s.input_ids[0], bos_token_id)
243
+ self.assertTrue(all(o[0] == bos_token_id for o in out_s2.input_ids))
244
+
245
+ decode_s = tokenizer.decode(out_s.input_ids)
246
+ decode_s2 = tokenizer.batch_decode(out_s2.input_ids)
247
+
248
+ self.assertTrue(decode_s.startswith(bos_token))
249
+ self.assertTrue(all(d.startswith(bos_token) for d in decode_s2))
250
+
251
+ @unittest.skip(reason="tokenizer has no padding token")
252
+ def test_padding_different_model_input_name(self):
253
+ pass
254
+
255
+ def test_special_tokens_mask_input_pairs_and_bos_token(self):
256
+ # TODO: change to self.get_tokenizers() when the fast version is implemented
257
+ tokenizers = [self.get_tokenizer(do_lower_case=False, add_bos_token=True)]
258
+ for tokenizer in tokenizers:
259
+ with self.subTest(f"{tokenizer.__class__.__name__}"):
260
+ sequence_0 = "Encode this."
261
+ sequence_1 = "This one too please."
262
+ encoded_sequence = tokenizer.encode(sequence_0, add_special_tokens=False)
263
+ encoded_sequence += tokenizer.encode(sequence_1, add_special_tokens=False)
264
+ encoded_sequence_dict = tokenizer.encode_plus(
265
+ sequence_0,
266
+ sequence_1,
267
+ add_special_tokens=True,
268
+ return_special_tokens_mask=True,
269
+ )
270
+ encoded_sequence_w_special = encoded_sequence_dict["input_ids"]
271
+ special_tokens_mask = encoded_sequence_dict["special_tokens_mask"]
272
+ self.assertEqual(len(special_tokens_mask), len(encoded_sequence_w_special))
273
+
274
+ filtered_sequence = [
275
+ (x if not special_tokens_mask[i] else None) for i, x in enumerate(encoded_sequence_w_special)
276
+ ]
277
+ filtered_sequence = [x for x in filtered_sequence if x is not None]
278
+ self.assertEqual(encoded_sequence, filtered_sequence)
279
+
280
+ @require_jinja
281
+ def test_tokenization_for_chat(self):
282
+ tokenizer = GPT2Tokenizer.from_pretrained(self.tmpdirname)
283
+ tokenizer.chat_template = "{% for message in messages %}{{ message.content }}{{ eos_token }}{% endfor %}"
284
+ test_chats = [
285
+ [{"role": "system", "content": "You are a helpful chatbot."}, {"role": "user", "content": "Hello!"}],
286
+ [
287
+ {"role": "system", "content": "You are a helpful chatbot."},
288
+ {"role": "user", "content": "Hello!"},
289
+ {"role": "assistant", "content": "Nice to meet you."},
290
+ ],
291
+ [{"role": "assistant", "content": "Nice to meet you."}, {"role": "user", "content": "Hello!"}],
292
+ ]
293
+ tokenized_chats = [tokenizer.apply_chat_template(test_chat) for test_chat in test_chats]
294
+ # fmt: off
295
+ expected_tokens = [[20, 1, 20, 10, 20, 4, 3, 10, 20, 10, 20, 3, 0, 20, 20, 20, 0, 10, 20, 20, 20, 6, 20, 1, 6, 20, 20, 20, 3, 0, 0, 1, 20, 20],
296
+ [20, 1, 20, 10, 20, 4, 3, 10, 20, 10, 20, 3, 0, 20, 20, 20, 0, 10, 20, 20, 20, 6, 20, 1, 6, 20, 20, 20, 3, 0, 0, 1, 20, 20, 20, 7, 20, 3, 10, 6, 1, 10, 20, 3, 3, 6, 10, 20, 1, 20, 20, 20],
297
+ [20, 7, 20, 3, 10, 6, 1, 10, 20, 3, 3, 6, 10, 20, 1, 20, 20, 20, 20, 3, 0, 0, 1, 20, 20]]
298
+ # fmt: on
299
+ for tokenized_chat, expected_tokens in zip(tokenized_chats, expected_tokens):
300
+ self.assertListEqual(tokenized_chat, expected_tokens)
301
+
302
+
303
+ @require_tokenizers
304
+ class OPTTokenizationTest(unittest.TestCase):
305
+ def test_serialize_deserialize_fast_opt(self):
306
+ # More context:
307
+ # https://huggingface.co/wjmcat/opt-350m-paddle/discussions/1
308
+ # https://huggingface.slack.com/archives/C01N44FJDHT/p1653511495183519
309
+ # https://github.com/huggingface/transformers/pull/17088#discussion_r871246439
310
+
311
+ tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m", from_slow=True)
312
+ text = "A photo of a cat"
313
+
314
+ tokens_ids = tokenizer.encode(
315
+ text,
316
+ )
317
+ self.assertEqual(tokens_ids, [2, 250, 1345, 9, 10, 4758])
318
+ tokenizer.save_pretrained("test_opt")
319
+
320
+ tokenizer = AutoTokenizer.from_pretrained("./test_opt")
321
+ tokens_ids = tokenizer.encode(
322
+ text,
323
+ )
324
+ self.assertEqual(tokens_ids, [2, 250, 1345, 9, 10, 4758])
325
+
326
+ def test_fast_slow_equivalence(self):
327
+ tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m", use_slow=True)
328
+ text = "A photo of a cat"
329
+
330
+ tokens_ids = tokenizer.encode(
331
+ text,
332
+ )
333
+ # Same as above
334
+ self.assertEqual(tokens_ids, [2, 250, 1345, 9, 10, 4758])
335
+
336
+ @unittest.skip(reason="This test is failing because of a bug in the fast tokenizer")
337
+ def test_users_can_modify_bos(self):
338
+ tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m", from_slow=True)
339
+
340
+ tokenizer.bos_token = "bos"
341
+ tokenizer.bos_token_id = tokenizer.get_vocab()["bos"]
342
+
343
+ text = "A photo of a cat"
344
+ tokens_ids = tokenizer.encode(
345
+ text,
346
+ )
347
+ # We changed the bos token
348
+ self.assertEqual(tokens_ids, [31957, 250, 1345, 9, 10, 4758])
349
+ tokenizer.save_pretrained("./tok")
350
+ tokenizer = AutoTokenizer.from_pretrained("./tok")
351
+ self.assertTrue(tokenizer.is_fast)
352
+ tokens_ids = tokenizer.encode(
353
+ text,
354
+ )
355
+ self.assertEqual(tokens_ids, [31957, 250, 1345, 9, 10, 4758])
tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt2/test_tokenization_gpt2_tf.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import unittest
2
+ from pathlib import Path
3
+ from tempfile import TemporaryDirectory
4
+
5
+ from transformers import AutoConfig, TFGPT2LMHeadModel, is_keras_nlp_available, is_tf_available
6
+ from transformers.models.gpt2.tokenization_gpt2 import GPT2Tokenizer
7
+ from transformers.testing_utils import require_keras_nlp, require_tf, slow
8
+
9
+
10
+ if is_tf_available():
11
+ import tensorflow as tf
12
+
13
+
14
+ if is_keras_nlp_available():
15
+ from transformers.models.gpt2 import TFGPT2Tokenizer
16
+
17
+
18
+ TOKENIZER_CHECKPOINTS = ["openai-community/gpt2"]
19
+ TINY_MODEL_CHECKPOINT = "openai-community/gpt2"
20
+
21
+ if is_tf_available():
22
+
23
+ class ModelToSave(tf.Module):
24
+ def __init__(self, tokenizer):
25
+ super().__init__()
26
+ self.tokenizer = tokenizer
27
+ config = AutoConfig.from_pretrained(TINY_MODEL_CHECKPOINT)
28
+ self.model = TFGPT2LMHeadModel.from_config(config)
29
+
30
+ @tf.function(input_signature=(tf.TensorSpec((None,), tf.string, name="text"),))
31
+ def serving(self, text):
32
+ tokenized = self.tokenizer(text)
33
+ input_ids_dense = tokenized["input_ids"].to_tensor()
34
+
35
+ input_mask = tf.cast(input_ids_dense > 0, tf.int32)
36
+ # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN])
37
+
38
+ outputs = self.model(input_ids=input_ids_dense, attention_mask=input_mask)["logits"]
39
+
40
+ return outputs
41
+
42
+
43
+ @require_tf
44
+ @require_keras_nlp
45
+ class GPTTokenizationTest(unittest.TestCase):
46
+ # The TF tokenizers are usually going to be used as pretrained tokenizers from existing model checkpoints,
47
+ # so that's what we focus on here.
48
+
49
+ def setUp(self):
50
+ super().setUp()
51
+
52
+ self.tokenizers = [GPT2Tokenizer.from_pretrained(checkpoint) for checkpoint in (TOKENIZER_CHECKPOINTS)]
53
+ self.tf_tokenizers = [TFGPT2Tokenizer.from_pretrained(checkpoint) for checkpoint in TOKENIZER_CHECKPOINTS]
54
+ assert len(self.tokenizers) == len(self.tf_tokenizers)
55
+
56
+ self.test_sentences = [
57
+ "This is a straightforward English test sentence.",
58
+ "This one has some weird characters\rto\nsee\r\nif those\u00e9break things.",
59
+ "Now we're going to add some Chinese: 一 二 三 一二三",
60
+ "And some much more rare Chinese: 齉 堃 齉堃",
61
+ "Je vais aussi écrire en français pour tester les accents",
62
+ "Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ",
63
+ ]
64
+ self.paired_sentences = list(zip(self.test_sentences, self.test_sentences[::-1]))
65
+
66
+ def test_output_equivalence(self):
67
+ for tokenizer, tf_tokenizer in zip(self.tokenizers, self.tf_tokenizers):
68
+ for test_inputs in self.test_sentences:
69
+ python_outputs = tokenizer([test_inputs], return_tensors="tf")
70
+ tf_outputs = tf_tokenizer([test_inputs])
71
+
72
+ for key in python_outputs.keys():
73
+ # convert them to numpy to avoid messing with ragged tensors
74
+ python_outputs_values = python_outputs[key].numpy()
75
+ tf_outputs_values = tf_outputs[key].numpy()
76
+
77
+ self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape))
78
+ self.assertTrue(tf.reduce_all(tf.cast(python_outputs_values, tf.int64) == tf_outputs_values))
79
+
80
+ @slow
81
+ def test_graph_mode(self):
82
+ for tf_tokenizer in self.tf_tokenizers:
83
+ compiled_tokenizer = tf.function(tf_tokenizer)
84
+ for test_inputs in self.test_sentences:
85
+ test_inputs = tf.constant(test_inputs)
86
+ compiled_outputs = compiled_tokenizer(test_inputs)
87
+ eager_outputs = tf_tokenizer(test_inputs)
88
+
89
+ for key in eager_outputs.keys():
90
+ self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key]))
91
+
92
+ @slow
93
+ def test_saved_model(self):
94
+ for tf_tokenizer in self.tf_tokenizers:
95
+ model = ModelToSave(tokenizer=tf_tokenizer)
96
+ test_inputs = tf.convert_to_tensor([self.test_sentences[0]])
97
+ out = model.serving(test_inputs) # Build model with some sample inputs
98
+ with TemporaryDirectory() as tempdir:
99
+ save_path = Path(tempdir) / "saved.model"
100
+ tf.saved_model.save(model, save_path, signatures={"serving_default": model.serving})
101
+ loaded_model = tf.saved_model.load(save_path)
102
+ loaded_output = loaded_model.signatures["serving_default"](test_inputs)["output_0"]
103
+ # We may see small differences because the loaded model is compiled, so we need an epsilon for the test
104
+ self.assertTrue(tf.reduce_all(out == loaded_output))
105
+
106
+ @slow
107
+ def test_from_config(self):
108
+ for tf_tokenizer in self.tf_tokenizers:
109
+ test_inputs = tf.convert_to_tensor([self.test_sentences[0]])
110
+ out = tf_tokenizer(test_inputs) # Build model with some sample inputs
111
+
112
+ config = tf_tokenizer.get_config()
113
+ model_from_config = TFGPT2Tokenizer.from_config(config)
114
+ from_config_output = model_from_config(test_inputs)
115
+
116
+ for key in from_config_output.keys():
117
+ self.assertTrue(tf.reduce_all(from_config_output[key] == out[key]))
118
+
119
+ @slow
120
+ def test_padding(self):
121
+ for tf_tokenizer in self.tf_tokenizers:
122
+ # for the test to run
123
+ tf_tokenizer.pad_token_id = 123123
124
+
125
+ for max_length in [3, 5, 1024]:
126
+ test_inputs = tf.convert_to_tensor([self.test_sentences[0]])
127
+ out = tf_tokenizer(test_inputs, max_length=max_length)
128
+
129
+ out_length = out["input_ids"].numpy().shape[1]
130
+
131
+ assert out_length == max_length
tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_bigcode/__init__.py ADDED
File without changes
tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_bigcode/test_modeling_gpt_bigcode.py ADDED
@@ -0,0 +1,595 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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
+ import math
16
+ import unittest
17
+
18
+ from parameterized import parameterized
19
+
20
+ from transformers import GPTBigCodeConfig, is_torch_available
21
+ from transformers.testing_utils import cleanup, 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
+ GPT2TokenizerFast,
34
+ GPTBigCodeForCausalLM,
35
+ GPTBigCodeForSequenceClassification,
36
+ GPTBigCodeForTokenClassification,
37
+ GPTBigCodeModel,
38
+ )
39
+ from transformers.models.gpt_bigcode.modeling_gpt_bigcode import GPTBigCodeAttention
40
+
41
+
42
+ class GPTBigCodeModelTester:
43
+ def __init__(
44
+ self,
45
+ parent,
46
+ batch_size=14,
47
+ seq_length=7,
48
+ is_training=True,
49
+ use_token_type_ids=True,
50
+ use_input_mask=True,
51
+ use_labels=True,
52
+ use_mc_token_ids=True,
53
+ vocab_size=99,
54
+ hidden_size=32,
55
+ num_hidden_layers=2,
56
+ num_attention_heads=4,
57
+ intermediate_size=37,
58
+ hidden_act="relu",
59
+ hidden_dropout_prob=0.1,
60
+ attention_probs_dropout_prob=0.1,
61
+ max_position_embeddings=512,
62
+ type_vocab_size=16,
63
+ type_sequence_label_size=2,
64
+ initializer_range=0.02,
65
+ num_labels=3,
66
+ num_choices=4,
67
+ multi_query=True,
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_probs_dropout_prob = attention_probs_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 - 2
95
+ self.pad_token_id = vocab_size - 3
96
+ self.multi_query = multi_query
97
+
98
+ def get_large_model_config(self):
99
+ return GPTBigCodeConfig.from_pretrained("bigcode/gpt_bigcode-santacoder")
100
+
101
+ def prepare_config_and_inputs(
102
+ self, gradient_checkpointing=False, scale_attn_by_inverse_layer_idx=False, reorder_and_upcast_attn=False
103
+ ):
104
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
105
+
106
+ input_mask = None
107
+ if self.use_input_mask:
108
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
109
+
110
+ token_type_ids = None
111
+ if self.use_token_type_ids:
112
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
113
+
114
+ mc_token_ids = None
115
+ if self.use_mc_token_ids:
116
+ mc_token_ids = ids_tensor([self.batch_size, self.num_choices], self.seq_length)
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
+ gradient_checkpointing=gradient_checkpointing,
128
+ scale_attn_by_inverse_layer_idx=scale_attn_by_inverse_layer_idx,
129
+ reorder_and_upcast_attn=reorder_and_upcast_attn,
130
+ )
131
+
132
+ head_mask = ids_tensor([self.num_hidden_layers, self.num_attention_heads], 2)
133
+
134
+ return (
135
+ config,
136
+ input_ids,
137
+ input_mask,
138
+ head_mask,
139
+ token_type_ids,
140
+ mc_token_ids,
141
+ sequence_labels,
142
+ token_labels,
143
+ choice_labels,
144
+ )
145
+
146
+ def get_config(
147
+ self, gradient_checkpointing=False, scale_attn_by_inverse_layer_idx=False, reorder_and_upcast_attn=False
148
+ ):
149
+ return GPTBigCodeConfig(
150
+ vocab_size=self.vocab_size,
151
+ n_embd=self.hidden_size,
152
+ n_layer=self.num_hidden_layers,
153
+ n_head=self.num_attention_heads,
154
+ n_inner=self.intermediate_size,
155
+ activation_function=self.hidden_act,
156
+ resid_pdrop=self.hidden_dropout_prob,
157
+ attn_pdrop=self.attention_probs_dropout_prob,
158
+ n_positions=self.max_position_embeddings,
159
+ type_vocab_size=self.type_vocab_size,
160
+ initializer_range=self.initializer_range,
161
+ use_cache=True,
162
+ bos_token_id=self.bos_token_id,
163
+ eos_token_id=self.eos_token_id,
164
+ pad_token_id=self.pad_token_id,
165
+ gradient_checkpointing=gradient_checkpointing,
166
+ scale_attn_by_inverse_layer_idx=scale_attn_by_inverse_layer_idx,
167
+ reorder_and_upcast_attn=reorder_and_upcast_attn,
168
+ attention_softmax_in_fp32=False,
169
+ scale_attention_softmax_in_fp32=False,
170
+ multi_query=self.multi_query,
171
+ )
172
+
173
+ def get_pipeline_config(self):
174
+ config = self.get_config()
175
+ config.vocab_size = 300
176
+ return config
177
+
178
+ def create_and_check_gpt_bigcode_model(self, config, input_ids, input_mask, head_mask, token_type_ids, *args):
179
+ model = GPTBigCodeModel(config=config)
180
+ model.to(torch_device)
181
+ model.eval()
182
+
183
+ result = model(input_ids, token_type_ids=token_type_ids, head_mask=head_mask)
184
+ result = model(input_ids, token_type_ids=token_type_ids)
185
+ result = model(input_ids)
186
+
187
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
188
+ self.parent.assertEqual(len(result.past_key_values), config.n_layer)
189
+
190
+ def create_and_check_gpt_bigcode_model_past(self, config, input_ids, input_mask, head_mask, token_type_ids, *args):
191
+ model = GPTBigCodeModel(config=config)
192
+ model.to(torch_device)
193
+ model.eval()
194
+
195
+ # first forward pass
196
+ outputs = model(input_ids, token_type_ids=token_type_ids, use_cache=True)
197
+ outputs_use_cache_conf = model(input_ids, token_type_ids=token_type_ids)
198
+ outputs_no_past = model(input_ids, token_type_ids=token_type_ids, use_cache=False)
199
+
200
+ self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))
201
+ self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)
202
+
203
+ output, past = outputs.to_tuple()
204
+
205
+ # create hypothetical next token and extent to next_input_ids
206
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
207
+ next_token_types = ids_tensor([self.batch_size, 1], self.type_vocab_size)
208
+
209
+ # append to next input_ids and token_type_ids
210
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
211
+ next_token_type_ids = torch.cat([token_type_ids, next_token_types], dim=-1)
212
+
213
+ output_from_no_past = model(next_input_ids, token_type_ids=next_token_type_ids)["last_hidden_state"]
214
+ output_from_past = model(next_tokens, token_type_ids=next_token_types, past_key_values=past)[
215
+ "last_hidden_state"
216
+ ]
217
+
218
+ # select random slice
219
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
220
+ output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach()
221
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
222
+
223
+ # test that outputs are equal for slice
224
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
225
+
226
+ def create_and_check_gpt_bigcode_model_attention_mask_past(
227
+ self, config, input_ids, input_mask, head_mask, token_type_ids, *args
228
+ ):
229
+ model = GPTBigCodeModel(config=config)
230
+ model.to(torch_device)
231
+ model.eval()
232
+
233
+ # create attention mask
234
+ attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
235
+ half_seq_length = self.seq_length // 2
236
+ attn_mask[:, half_seq_length:] = 0
237
+
238
+ # first forward pass
239
+ output, past = model(input_ids, attention_mask=attn_mask).to_tuple()
240
+
241
+ # create hypothetical next token and extent to next_input_ids
242
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
243
+
244
+ # change a random masked slice from input_ids
245
+ random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1
246
+ random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1)
247
+ input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens
248
+
249
+ # append to next input_ids and attn_mask
250
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
251
+ attn_mask = torch.cat(
252
+ [attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)],
253
+ dim=1,
254
+ )
255
+
256
+ # get two different outputs
257
+ output_from_no_past = model(next_input_ids, attention_mask=attn_mask)["last_hidden_state"]
258
+ output_from_past = model(next_tokens, past_key_values=past, attention_mask=attn_mask)["last_hidden_state"]
259
+
260
+ # select random slice
261
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
262
+ output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach()
263
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
264
+
265
+ # test that outputs are equal for slice
266
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
267
+
268
+ def create_and_check_gpt_bigcode_model_past_large_inputs(
269
+ self, config, input_ids, input_mask, head_mask, token_type_ids, *args
270
+ ):
271
+ model = GPTBigCodeModel(config=config)
272
+ model.to(torch_device)
273
+ model.eval()
274
+
275
+ # first forward pass
276
+ outputs = model(input_ids, token_type_ids=token_type_ids, attention_mask=input_mask, use_cache=True)
277
+
278
+ output, past = outputs.to_tuple()
279
+
280
+ # create hypothetical next token and extent to next_input_ids
281
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
282
+ next_token_types = ids_tensor([self.batch_size, 3], self.type_vocab_size)
283
+ next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
284
+
285
+ # append to next input_ids and token_type_ids
286
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
287
+ next_token_type_ids = torch.cat([token_type_ids, next_token_types], dim=-1)
288
+ next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
289
+
290
+ output_from_no_past = model(
291
+ next_input_ids, token_type_ids=next_token_type_ids, attention_mask=next_attention_mask
292
+ )["last_hidden_state"]
293
+ output_from_past = model(
294
+ next_tokens, token_type_ids=next_token_types, attention_mask=next_attention_mask, past_key_values=past
295
+ )["last_hidden_state"]
296
+ self.parent.assertTrue(output_from_past.shape[1] == next_tokens.shape[1])
297
+
298
+ # select random slice
299
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
300
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
301
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
302
+
303
+ # test that outputs are equal for slice
304
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
305
+
306
+ def create_and_check_lm_head_model(self, config, input_ids, input_mask, head_mask, token_type_ids, *args):
307
+ model = GPTBigCodeForCausalLM(config)
308
+ model.to(torch_device)
309
+ model.eval()
310
+
311
+ result = model(input_ids, token_type_ids=token_type_ids, labels=input_ids)
312
+ self.parent.assertEqual(result.loss.shape, ())
313
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
314
+
315
+ def create_and_check_forward_and_backwards(
316
+ self, config, input_ids, input_mask, head_mask, token_type_ids, *args, gradient_checkpointing=False
317
+ ):
318
+ model = GPTBigCodeForCausalLM(config)
319
+ model.to(torch_device)
320
+ if gradient_checkpointing:
321
+ model.gradient_checkpointing_enable()
322
+
323
+ result = model(input_ids, token_type_ids=token_type_ids, labels=input_ids)
324
+ self.parent.assertEqual(result.loss.shape, ())
325
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
326
+ result.loss.backward()
327
+
328
+ def create_and_check_gpt_bigcode_for_sequence_classification(
329
+ self, config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, *args
330
+ ):
331
+ config.num_labels = self.num_labels
332
+ model = GPTBigCodeForSequenceClassification(config)
333
+ model.to(torch_device)
334
+ model.eval()
335
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels)
336
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
337
+
338
+ def create_and_check_gpt_bigcode_for_token_classification(
339
+ self, config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, *args
340
+ ):
341
+ config.num_labels = self.num_labels
342
+ model = GPTBigCodeForTokenClassification(config)
343
+ model.to(torch_device)
344
+ model.eval()
345
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
346
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
347
+
348
+ def create_and_check_gpt_bigcode_weight_initialization(self, config, *args):
349
+ model = GPTBigCodeModel(config)
350
+ model_std = model.config.initializer_range / math.sqrt(2 * model.config.n_layer)
351
+ for key in model.state_dict().keys():
352
+ if "c_proj" in key and "weight" in key:
353
+ self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key]) - model_std), 0.001)
354
+ self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key]) - 0.0), 0.01)
355
+
356
+ def prepare_config_and_inputs_for_common(self):
357
+ config_and_inputs = self.prepare_config_and_inputs()
358
+
359
+ (
360
+ config,
361
+ input_ids,
362
+ input_mask,
363
+ head_mask,
364
+ token_type_ids,
365
+ mc_token_ids,
366
+ sequence_labels,
367
+ token_labels,
368
+ choice_labels,
369
+ ) = config_and_inputs
370
+
371
+ inputs_dict = {
372
+ "input_ids": input_ids,
373
+ "token_type_ids": token_type_ids,
374
+ "head_mask": head_mask,
375
+ }
376
+
377
+ return config, inputs_dict
378
+
379
+
380
+ @require_torch
381
+ class GPTBigCodeModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
382
+ # TODO: Update the tests to use valid pretrained models.
383
+ all_model_classes = (
384
+ (
385
+ GPTBigCodeModel,
386
+ GPTBigCodeForCausalLM,
387
+ GPTBigCodeForSequenceClassification,
388
+ GPTBigCodeForTokenClassification,
389
+ )
390
+ if is_torch_available()
391
+ else ()
392
+ )
393
+ pipeline_model_mapping = (
394
+ {
395
+ "feature-extraction": GPTBigCodeModel,
396
+ "text-classification": GPTBigCodeForSequenceClassification,
397
+ "text-generation": GPTBigCodeForCausalLM,
398
+ "token-classification": GPTBigCodeForTokenClassification,
399
+ "zero-shot": GPTBigCodeForSequenceClassification,
400
+ }
401
+ if is_torch_available()
402
+ else {}
403
+ )
404
+ fx_compatible = False
405
+ test_missing_keys = False
406
+ test_pruning = False
407
+ test_torchscript = False
408
+ multi_query = True
409
+
410
+ # special case for DoubleHeads model
411
+ def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
412
+ inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
413
+
414
+ return inputs_dict
415
+
416
+ def setUp(self):
417
+ self.model_tester = GPTBigCodeModelTester(self, multi_query=self.multi_query)
418
+ self.config_tester = ConfigTester(self, config_class=GPTBigCodeConfig, n_embd=37)
419
+
420
+ def tearDown(self):
421
+ super().tearDown()
422
+ # clean-up as much as possible GPU memory occupied by PyTorch
423
+ cleanup(torch_device)
424
+
425
+ def test_config(self):
426
+ self.config_tester.run_common_tests()
427
+
428
+ @unittest.skip(reason="MQA models does not support retain_grad")
429
+ def test_retain_grad_hidden_states_attentions(self):
430
+ pass
431
+
432
+ @unittest.skip(reason="Contrastive search not supported due to non-standard caching mechanism")
433
+ def test_contrastive_generate(self):
434
+ pass
435
+
436
+ @unittest.skip(reason="Contrastive search not supported due to non-standard caching mechanism")
437
+ def test_contrastive_generate_dict_outputs_use_cache(self):
438
+ pass
439
+
440
+ @unittest.skip(reason="CPU offload seems to be broken for some reason - tiny models keep hitting corner cases")
441
+ def test_cpu_offload(self):
442
+ pass
443
+
444
+ @unittest.skip(reason="Disk offload seems to be broken for some reason - tiny models keep hitting corner cases")
445
+ def test_disk_offload(self):
446
+ pass
447
+
448
+ @unittest.skip(reason="BigCodeGPT has a non-standard KV cache format.")
449
+ def test_past_key_values_format(self):
450
+ pass
451
+
452
+ @unittest.skip(reason="BigCodeGPT has a non-standard KV cache format and breaks this test.")
453
+ def test_generate_continue_from_inputs_embeds(self):
454
+ pass
455
+
456
+ def test_gpt_bigcode_model(self):
457
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
458
+ self.model_tester.create_and_check_gpt_bigcode_model(*config_and_inputs)
459
+
460
+ def test_gpt_bigcode_model_past(self):
461
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
462
+ self.model_tester.create_and_check_gpt_bigcode_model_past(*config_and_inputs)
463
+
464
+ def test_gpt_bigcode_model_att_mask_past(self):
465
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
466
+ self.model_tester.create_and_check_gpt_bigcode_model_attention_mask_past(*config_and_inputs)
467
+
468
+ def test_gpt_bigcode_model_past_large_inputs(self):
469
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
470
+ self.model_tester.create_and_check_gpt_bigcode_model_past_large_inputs(*config_and_inputs)
471
+
472
+ def test_gpt_bigcode_lm_head_model(self):
473
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
474
+ self.model_tester.create_and_check_lm_head_model(*config_and_inputs)
475
+
476
+ def test_gpt_bigcode_sequence_classification_model(self):
477
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
478
+ self.model_tester.create_and_check_gpt_bigcode_for_sequence_classification(*config_and_inputs)
479
+
480
+ def test_gpt_bigcode_token_classification_model(self):
481
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
482
+ self.model_tester.create_and_check_gpt_bigcode_for_token_classification(*config_and_inputs)
483
+
484
+ def test_gpt_bigcode_gradient_checkpointing(self):
485
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
486
+ self.model_tester.create_and_check_forward_and_backwards(*config_and_inputs, gradient_checkpointing=True)
487
+
488
+ def test_gpt_bigcode_scale_attn_by_inverse_layer_idx(self):
489
+ config_and_inputs = self.model_tester.prepare_config_and_inputs(scale_attn_by_inverse_layer_idx=True)
490
+ self.model_tester.create_and_check_forward_and_backwards(*config_and_inputs)
491
+
492
+ def test_gpt_bigcode_reorder_and_upcast_attn(self):
493
+ config_and_inputs = self.model_tester.prepare_config_and_inputs(reorder_and_upcast_attn=True)
494
+ self.model_tester.create_and_check_forward_and_backwards(*config_and_inputs)
495
+
496
+ def test_gpt_bigcode_weight_initialization(self):
497
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
498
+ self.model_tester.create_and_check_gpt_bigcode_weight_initialization(*config_and_inputs)
499
+
500
+
501
+ @require_torch
502
+ class GPTBigCodeMHAModelTest(GPTBigCodeModelTest):
503
+ # `parameterized_class` breaks with mixins, so we use inheritance instead
504
+ multi_query = False
505
+
506
+
507
+ @slow
508
+ @require_torch
509
+ class GPTBigCodeModelLanguageGenerationTest(unittest.TestCase):
510
+ def test_generate_simple(self):
511
+ model = GPTBigCodeForCausalLM.from_pretrained("bigcode/gpt_bigcode-santacoder").to(torch_device)
512
+ tokenizer = GPT2TokenizerFast.from_pretrained("bigcode/gpt_bigcode-santacoder")
513
+
514
+ input_ids = tokenizer("def print_hello_world():", return_tensors="pt").input_ids.to(torch_device)
515
+
516
+ output_sequence = model.generate(input_ids)
517
+ output_sentence = tokenizer.decode(output_sequence[0], skip_special_tokens=True)
518
+
519
+ expected_output = """def print_hello_world():\n print("Hello World!")\n\n\ndef print_hello_"""
520
+ self.assertEqual(output_sentence, expected_output)
521
+
522
+ def test_generate_batched(self):
523
+ tokenizer = GPT2TokenizerFast.from_pretrained("bigcode/gpt_bigcode-santacoder")
524
+ tokenizer.pad_token = tokenizer.eos_token
525
+ tokenizer.padding_side = "left"
526
+
527
+ model = GPTBigCodeForCausalLM.from_pretrained("bigcode/gpt_bigcode-santacoder").to(torch_device)
528
+
529
+ inputs = tokenizer(["def print_hello_world():", "def say_hello():"], return_tensors="pt", padding=True).to(
530
+ torch_device
531
+ )
532
+ outputs = model.generate(**inputs)
533
+ outputs = tokenizer.batch_decode(outputs, skip_special_tokens=True)
534
+
535
+ expected_output = [
536
+ 'def print_hello_world():\n print("Hello World!")\n\n\ndef print_hello_',
537
+ 'def say_hello():\n print("Hello, World!")\n\n\nsay_hello()',
538
+ ]
539
+ self.assertListEqual(outputs, expected_output)
540
+
541
+
542
+ @require_torch
543
+ class GPTBigCodeMQATest(unittest.TestCase):
544
+ def get_attention(self, multi_query):
545
+ config = GPTBigCodeConfig.from_pretrained(
546
+ "bigcode/gpt_bigcode-santacoder",
547
+ multi_query=multi_query,
548
+ attn_pdrop=0,
549
+ resid_pdrop=0,
550
+ )
551
+ return GPTBigCodeAttention(config)
552
+
553
+ @parameterized.expand([(seed, is_train_mode) for seed in range(5) for is_train_mode in [True, False]])
554
+ def test_mqa_reduces_to_mha(self, seed, is_train_mode=True):
555
+ torch.manual_seed(seed)
556
+
557
+ # CREATE MQA AND MHA ATTENTIONS
558
+ attention_mqa = self.get_attention(True)
559
+ attention_mha = self.get_attention(False)
560
+
561
+ # ENFORCE MATCHING WEIGHTS
562
+ num_heads = attention_mqa.num_heads
563
+ embed_dim = attention_mqa.embed_dim
564
+ head_dim = attention_mqa.head_dim
565
+
566
+ with torch.no_grad():
567
+ mqa_q_weight = attention_mqa.c_attn.weight[:embed_dim, :].view(num_heads, 1, head_dim, embed_dim)
568
+ mqa_kv_weight = attention_mqa.c_attn.weight[embed_dim:, :].view(1, 2, head_dim, embed_dim)
569
+ mha_c_weight = torch.cat(
570
+ [mqa_q_weight, mqa_kv_weight.expand(num_heads, 2, head_dim, embed_dim)], dim=1
571
+ ).view(3 * num_heads * head_dim, embed_dim)
572
+
573
+ mqa_q_bias = attention_mqa.c_attn.bias[:embed_dim].view(num_heads, 1, head_dim)
574
+ mqa_kv_bias = attention_mqa.c_attn.bias[embed_dim:].view(1, 2, head_dim)
575
+ mha_c_bias = torch.cat([mqa_q_bias, mqa_kv_bias.expand(num_heads, 2, head_dim)], dim=1).view(
576
+ 3 * num_heads * head_dim
577
+ )
578
+
579
+ attention_mha.c_attn.weight.copy_(mha_c_weight)
580
+ attention_mha.c_attn.bias.copy_(mha_c_bias)
581
+ attention_mha.c_proj.weight.copy_(attention_mqa.c_proj.weight)
582
+ attention_mha.c_proj.bias.copy_(attention_mqa.c_proj.bias)
583
+
584
+ # PUT THE MODEL INTO THE CORRECT MODE
585
+ attention_mha.train(is_train_mode)
586
+ attention_mqa.train(is_train_mode)
587
+
588
+ # RUN AN INPUT THROUGH THE MODELS
589
+ num_tokens = 5
590
+ hidden_states = torch.randn(1, num_tokens, embed_dim)
591
+ attention_mha_result = attention_mha(hidden_states)[0]
592
+ attention_mqa_result = attention_mqa(hidden_states)[0]
593
+
594
+ # CHECK THAT ALL OUTPUTS ARE THE SAME
595
+ torch.testing.assert_close(attention_mha_result, attention_mqa_result, rtol=1e-5, atol=1e-5)
tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_neo/__init__.py ADDED
File without changes
tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_neo/test_modeling_flax_gpt_neo.py ADDED
@@ -0,0 +1,223 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
16
+ import unittest
17
+
18
+ import numpy as np
19
+
20
+ from transformers import GPT2Tokenizer, GPTNeoConfig, is_flax_available
21
+ from transformers.testing_utils import require_flax, slow
22
+
23
+ from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask
24
+
25
+
26
+ if is_flax_available():
27
+ import jax
28
+ import jax.numpy as jnp
29
+
30
+ from transformers.models.gpt_neo.modeling_flax_gpt_neo import FlaxGPTNeoForCausalLM, FlaxGPTNeoModel
31
+
32
+
33
+ class FlaxGPTNeoModelTester:
34
+ def __init__(
35
+ self,
36
+ parent,
37
+ batch_size=14,
38
+ seq_length=7,
39
+ is_training=True,
40
+ use_input_mask=True,
41
+ use_token_type_ids=False,
42
+ use_labels=True,
43
+ vocab_size=99,
44
+ hidden_size=32,
45
+ num_hidden_layers=2,
46
+ num_attention_heads=4,
47
+ attention_types=[[["global", "local"], 1]],
48
+ intermediate_size=37,
49
+ hidden_act="gelu",
50
+ hidden_dropout_prob=0.1,
51
+ attention_probs_dropout_prob=0.1,
52
+ max_position_embeddings=512,
53
+ window_size=7,
54
+ initializer_range=0.02,
55
+ ):
56
+ self.parent = parent
57
+ self.batch_size = batch_size
58
+ self.seq_length = seq_length
59
+ self.is_training = is_training
60
+ self.use_input_mask = use_input_mask
61
+ self.use_token_type_ids = use_token_type_ids
62
+ self.use_labels = use_labels
63
+ self.vocab_size = vocab_size
64
+ self.hidden_size = hidden_size
65
+ self.num_hidden_layers = num_hidden_layers
66
+ self.num_attention_heads = num_attention_heads
67
+ self.attention_types = attention_types
68
+ self.intermediate_size = intermediate_size
69
+ self.hidden_act = hidden_act
70
+ self.hidden_dropout_prob = hidden_dropout_prob
71
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
72
+ self.max_position_embeddings = max_position_embeddings
73
+ self.window_size = window_size
74
+ self.initializer_range = initializer_range
75
+ self.scope = None
76
+ self.bos_token_id = vocab_size - 1
77
+ self.eos_token_id = vocab_size - 1
78
+ self.pad_token_id = vocab_size - 1
79
+
80
+ def prepare_config_and_inputs(self):
81
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
82
+
83
+ input_mask = None
84
+ if self.use_input_mask:
85
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
86
+
87
+ config = GPTNeoConfig(
88
+ vocab_size=self.vocab_size,
89
+ hidden_size=self.hidden_size,
90
+ num_layers=self.num_hidden_layers,
91
+ num_heads=self.num_attention_heads,
92
+ max_position_embeddings=self.max_position_embeddings,
93
+ use_cache=False,
94
+ bos_token_id=self.bos_token_id,
95
+ eos_token_id=self.eos_token_id,
96
+ pad_token_id=self.pad_token_id,
97
+ window_size=self.window_size,
98
+ attention_types=self.attention_types,
99
+ )
100
+
101
+ return (config, input_ids, input_mask)
102
+
103
+ def prepare_config_and_inputs_for_common(self):
104
+ config_and_inputs = self.prepare_config_and_inputs()
105
+ config, input_ids, attention_mask = config_and_inputs
106
+ inputs_dict = {"input_ids": input_ids, "attention_mask": attention_mask}
107
+ return config, inputs_dict
108
+
109
+ def check_use_cache_forward(self, model_class_name, config, input_ids, attention_mask):
110
+ max_decoder_length = 20
111
+ model = model_class_name(config)
112
+
113
+ past_key_values = model.init_cache(input_ids.shape[0], max_decoder_length)
114
+ attention_mask = jnp.ones((input_ids.shape[0], max_decoder_length), dtype="i4")
115
+
116
+ position_ids = jnp.broadcast_to(
117
+ jnp.arange(input_ids.shape[-1] - 1)[None, :], (input_ids.shape[0], input_ids.shape[-1] - 1)
118
+ )
119
+ outputs_cache = model(
120
+ input_ids[:, :-1],
121
+ attention_mask=attention_mask,
122
+ past_key_values=past_key_values,
123
+ position_ids=position_ids,
124
+ )
125
+
126
+ position_ids = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]], dtype="i4")
127
+ outputs_cache_next = model(
128
+ input_ids[:, -1:],
129
+ attention_mask=attention_mask,
130
+ past_key_values=outputs_cache.past_key_values,
131
+ position_ids=position_ids,
132
+ )
133
+
134
+ outputs = model(input_ids)
135
+
136
+ diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
137
+ self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}")
138
+
139
+ def check_use_cache_forward_with_attn_mask(self, model_class_name, config, input_ids, attention_mask):
140
+ max_decoder_length = 20
141
+ model = model_class_name(config)
142
+
143
+ attention_mask_cache = jnp.concatenate(
144
+ [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]))],
145
+ axis=-1,
146
+ )
147
+
148
+ past_key_values = model.init_cache(input_ids.shape[0], max_decoder_length)
149
+ position_ids = jnp.broadcast_to(
150
+ jnp.arange(input_ids.shape[-1] - 1)[None, :], (input_ids.shape[0], input_ids.shape[-1] - 1)
151
+ )
152
+
153
+ outputs_cache = model(
154
+ input_ids[:, :-1],
155
+ attention_mask=attention_mask_cache,
156
+ past_key_values=past_key_values,
157
+ position_ids=position_ids,
158
+ )
159
+ position_ids = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]], dtype="i4")
160
+ outputs_cache_next = model(
161
+ input_ids[:, -1:],
162
+ past_key_values=outputs_cache.past_key_values,
163
+ attention_mask=attention_mask_cache,
164
+ position_ids=position_ids,
165
+ )
166
+
167
+ outputs = model(input_ids, attention_mask=attention_mask)
168
+
169
+ diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
170
+ self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}")
171
+
172
+
173
+ @require_flax
174
+ class FlaxGPTNeoModelTest(FlaxModelTesterMixin, unittest.TestCase):
175
+ all_model_classes = (FlaxGPTNeoModel, FlaxGPTNeoForCausalLM) if is_flax_available() else ()
176
+
177
+ def setUp(self):
178
+ self.model_tester = FlaxGPTNeoModelTester(self)
179
+
180
+ def test_use_cache_forward(self):
181
+ for model_class_name in self.all_model_classes:
182
+ config, input_ids, attention_mask = self.model_tester.prepare_config_and_inputs()
183
+ self.model_tester.check_use_cache_forward(model_class_name, config, input_ids, attention_mask)
184
+
185
+ def test_use_cache_forward_with_attn_mask(self):
186
+ for model_class_name in self.all_model_classes:
187
+ config, input_ids, attention_mask = self.model_tester.prepare_config_and_inputs()
188
+ self.model_tester.check_use_cache_forward_with_attn_mask(
189
+ model_class_name, config, input_ids, attention_mask
190
+ )
191
+
192
+ @slow
193
+ def test_batch_generation(self):
194
+ tokenizer = GPT2Tokenizer.from_pretrained(
195
+ "openai-community/gpt2", pad_token="<|endoftext|>", padding_side="left"
196
+ )
197
+ inputs = tokenizer(["Hello this is a long string", "Hey"], return_tensors="np", padding=True, truncation=True)
198
+
199
+ model = FlaxGPTNeoForCausalLM.from_pretrained("EleutherAI/gpt-neo-125M")
200
+ model.do_sample = False
201
+ model.config.pad_token_id = model.config.eos_token_id
202
+
203
+ jit_generate = jax.jit(model.generate)
204
+
205
+ output_sequences = jit_generate(
206
+ inputs["input_ids"], attention_mask=inputs["attention_mask"], pad_token_id=tokenizer.pad_token_id
207
+ ).sequences
208
+
209
+ output_string = tokenizer.batch_decode(output_sequences, skip_special_tokens=True)
210
+
211
+ expected_string = [
212
+ "Hello this is a long string of text.\n\nI'm trying to get the text of the",
213
+ "Hey, I'm a little late to the party. I'm going to",
214
+ ]
215
+
216
+ self.assertListEqual(output_string, expected_string)
217
+
218
+ @slow
219
+ def test_model_from_pretrained(self):
220
+ for model_class_name in self.all_model_classes:
221
+ model = model_class_name.from_pretrained("EleutherAI/gpt-neo-125M")
222
+ outputs = model(np.ones((1, 1)))
223
+ self.assertIsNotNone(outputs)
tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_neo/test_modeling_gpt_neo.py ADDED
@@ -0,0 +1,574 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 GPT Neo model."""
16
+
17
+ import unittest
18
+
19
+ from transformers import GPTNeoConfig, is_torch_available
20
+ from transformers.testing_utils import require_torch, slow, torch_device
21
+ from transformers.utils import cached_property
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
+ GPT2Tokenizer,
34
+ GPTNeoForCausalLM,
35
+ GPTNeoForQuestionAnswering,
36
+ GPTNeoForSequenceClassification,
37
+ GPTNeoForTokenClassification,
38
+ GPTNeoModel,
39
+ )
40
+
41
+
42
+ class GPTNeoModelTester:
43
+ def __init__(
44
+ self,
45
+ parent,
46
+ batch_size=14,
47
+ seq_length=7,
48
+ is_training=True,
49
+ use_token_type_ids=True,
50
+ use_input_mask=True,
51
+ use_labels=True,
52
+ use_mc_token_ids=True,
53
+ vocab_size=99,
54
+ hidden_size=32,
55
+ num_hidden_layers=2,
56
+ attention_types=[[["global", "local"], 1]],
57
+ num_attention_heads=4,
58
+ intermediate_size=37,
59
+ hidden_act="gelu",
60
+ hidden_dropout_prob=0.1,
61
+ attention_probs_dropout_prob=0.1,
62
+ max_position_embeddings=512,
63
+ window_size=7,
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
+ ):
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_probs_dropout_prob = attention_probs_dropout_prob
86
+ self.max_position_embeddings = max_position_embeddings
87
+ self.window_size = window_size
88
+ self.type_vocab_size = type_vocab_size
89
+ self.type_sequence_label_size = type_sequence_label_size
90
+ self.initializer_range = initializer_range
91
+ self.num_labels = num_labels
92
+ self.num_choices = num_choices
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
+ self.attention_types = attention_types
97
+
98
+ def get_large_model_config(self):
99
+ return GPTNeoConfig.from_pretrained("gpt-neo-125M")
100
+
101
+ def prepare_config_and_inputs(self):
102
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
103
+
104
+ input_mask = None
105
+ if self.use_input_mask:
106
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
107
+
108
+ token_type_ids = None
109
+ if self.use_token_type_ids:
110
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
111
+
112
+ mc_token_ids = None
113
+ if self.use_mc_token_ids:
114
+ mc_token_ids = ids_tensor([self.batch_size, self.num_choices], self.seq_length)
115
+
116
+ sequence_labels = None
117
+ token_labels = None
118
+ choice_labels = None
119
+ if self.use_labels:
120
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
121
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
122
+ choice_labels = ids_tensor([self.batch_size], self.num_choices)
123
+
124
+ config = self.get_config()
125
+
126
+ head_mask = ids_tensor([self.num_hidden_layers, self.num_attention_heads], 2)
127
+
128
+ return (
129
+ config,
130
+ input_ids,
131
+ input_mask,
132
+ head_mask,
133
+ token_type_ids,
134
+ mc_token_ids,
135
+ sequence_labels,
136
+ token_labels,
137
+ choice_labels,
138
+ )
139
+
140
+ def get_config(self):
141
+ return GPTNeoConfig(
142
+ vocab_size=self.vocab_size,
143
+ hidden_size=self.hidden_size,
144
+ num_layers=self.num_hidden_layers,
145
+ num_heads=self.num_attention_heads,
146
+ max_position_embeddings=self.max_position_embeddings,
147
+ use_cache=True,
148
+ bos_token_id=self.bos_token_id,
149
+ eos_token_id=self.eos_token_id,
150
+ pad_token_id=self.pad_token_id,
151
+ window_size=self.window_size,
152
+ attention_types=self.attention_types,
153
+ )
154
+
155
+ def get_pipeline_config(self):
156
+ config = self.get_config()
157
+ config.vocab_size = 300
158
+ return config
159
+
160
+ def create_and_check_gpt_neo_model(self, config, input_ids, input_mask, head_mask, token_type_ids, *args):
161
+ model = GPTNeoModel(config=config)
162
+ model.to(torch_device)
163
+ model.eval()
164
+
165
+ result = model(input_ids, token_type_ids=token_type_ids, head_mask=head_mask)
166
+ result = model(input_ids, token_type_ids=token_type_ids)
167
+ result = model(input_ids)
168
+
169
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
170
+ # past_key_values is not implemented
171
+ # self.parent.assertEqual(len(result.past_key_values), config.n_layer)
172
+
173
+ def create_and_check_gpt_neo_model_past(self, config, input_ids, input_mask, head_mask, token_type_ids, *args):
174
+ model = GPTNeoModel(config=config)
175
+ model.to(torch_device)
176
+ model.eval()
177
+
178
+ # first forward pass
179
+ outputs = model(input_ids, token_type_ids=token_type_ids, use_cache=True)
180
+ outputs_use_cache_conf = model(input_ids, token_type_ids=token_type_ids)
181
+ outputs_no_past = model(input_ids, token_type_ids=token_type_ids, use_cache=False)
182
+
183
+ self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))
184
+ self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)
185
+
186
+ output, past = outputs.to_tuple()
187
+
188
+ # create hypothetical next token and extent to next_input_ids
189
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
190
+ next_token_types = ids_tensor([self.batch_size, 1], self.type_vocab_size)
191
+
192
+ # append to next input_ids and token_type_ids
193
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
194
+ next_token_type_ids = torch.cat([token_type_ids, next_token_types], dim=-1)
195
+
196
+ output_from_no_past = model(next_input_ids, token_type_ids=next_token_type_ids)["last_hidden_state"]
197
+ output_from_past = model(next_tokens, token_type_ids=next_token_types, past_key_values=past)[
198
+ "last_hidden_state"
199
+ ]
200
+
201
+ # select random slice
202
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
203
+ output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach()
204
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
205
+
206
+ # test that outputs are equal for slice
207
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
208
+
209
+ def create_and_check_gpt_neo_model_attention_mask_past(
210
+ self, config, input_ids, input_mask, head_mask, token_type_ids, *args
211
+ ):
212
+ model = GPTNeoModel(config=config)
213
+ model.to(torch_device)
214
+ model.eval()
215
+
216
+ # create attention mask
217
+ attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
218
+ half_seq_length = self.seq_length // 2
219
+ attn_mask[:, half_seq_length:] = 0
220
+
221
+ # first forward pass
222
+ output, past = model(input_ids, attention_mask=attn_mask).to_tuple()
223
+
224
+ # create hypothetical next token and extent to next_input_ids
225
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
226
+
227
+ # change a random masked slice from input_ids
228
+ random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1
229
+ random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1)
230
+ input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens
231
+
232
+ # append to next input_ids and attn_mask
233
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
234
+ attn_mask = torch.cat(
235
+ [attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)],
236
+ dim=1,
237
+ )
238
+
239
+ # get two different outputs
240
+ output_from_no_past = model(next_input_ids, attention_mask=attn_mask)["last_hidden_state"]
241
+ output_from_past = model(next_tokens, past_key_values=past, attention_mask=attn_mask)["last_hidden_state"]
242
+
243
+ # select random slice
244
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
245
+ output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach()
246
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
247
+
248
+ # test that outputs are equal for slice
249
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
250
+
251
+ def create_and_check_gpt_neo_model_past_large_inputs(
252
+ self, config, input_ids, input_mask, head_mask, token_type_ids, *args
253
+ ):
254
+ model = GPTNeoModel(config=config)
255
+ model.to(torch_device)
256
+ model.eval()
257
+
258
+ # first forward pass
259
+ outputs = model(input_ids, token_type_ids=token_type_ids, attention_mask=input_mask, use_cache=True)
260
+
261
+ output, past = outputs.to_tuple()
262
+
263
+ # create hypothetical next token and extent to next_input_ids
264
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
265
+ next_token_types = ids_tensor([self.batch_size, 3], self.type_vocab_size)
266
+ next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
267
+
268
+ # append to next input_ids and token_type_ids
269
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
270
+ next_token_type_ids = torch.cat([token_type_ids, next_token_types], dim=-1)
271
+ next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
272
+
273
+ output_from_no_past = model(
274
+ next_input_ids, token_type_ids=next_token_type_ids, attention_mask=next_attention_mask
275
+ )["last_hidden_state"]
276
+ output_from_past = model(
277
+ next_tokens, token_type_ids=next_token_types, attention_mask=next_attention_mask, past_key_values=past
278
+ )["last_hidden_state"]
279
+ self.parent.assertTrue(output_from_past.shape[1] == next_tokens.shape[1])
280
+
281
+ # select random slice
282
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
283
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
284
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
285
+
286
+ # test that outputs are equal for slice
287
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
288
+
289
+ def create_and_check_lm_head_model(self, config, input_ids, input_mask, head_mask, token_type_ids, *args):
290
+ model = GPTNeoForCausalLM(config)
291
+ model.to(torch_device)
292
+ model.eval()
293
+
294
+ result = model(input_ids, token_type_ids=token_type_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
+
298
+ def create_and_check_gpt_neo_for_question_answering(
299
+ self, config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, *args
300
+ ):
301
+ config.num_labels = self.num_labels
302
+ model = GPTNeoForQuestionAnswering(config)
303
+ model.to(torch_device)
304
+ model.eval()
305
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
306
+ self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
307
+ self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
308
+
309
+ def create_and_check_gpt_neo_for_sequence_classification(
310
+ self, config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, *args
311
+ ):
312
+ config.num_labels = self.num_labels
313
+ model = GPTNeoForSequenceClassification(config)
314
+ model.to(torch_device)
315
+ model.eval()
316
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels)
317
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
318
+
319
+ def create_and_check_gpt_neo_for_token_classification(
320
+ self, config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, *args
321
+ ):
322
+ config.num_labels = self.num_labels
323
+ model = GPTNeoForTokenClassification(config)
324
+ model.to(torch_device)
325
+ model.eval()
326
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
327
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
328
+
329
+ def create_and_check_forward_and_backwards(
330
+ self, config, input_ids, input_mask, head_mask, token_type_ids, *args, gradient_checkpointing=False
331
+ ):
332
+ model = GPTNeoForCausalLM(config)
333
+ if gradient_checkpointing:
334
+ model.gradient_checkpointing_enable()
335
+ model.to(torch_device)
336
+
337
+ result = model(input_ids, token_type_ids=token_type_ids, labels=input_ids)
338
+ self.parent.assertEqual(result.loss.shape, ())
339
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
340
+ result.loss.backward()
341
+
342
+ def prepare_config_and_inputs_for_common(self):
343
+ config_and_inputs = self.prepare_config_and_inputs()
344
+
345
+ (
346
+ config,
347
+ input_ids,
348
+ input_mask,
349
+ head_mask,
350
+ token_type_ids,
351
+ mc_token_ids,
352
+ sequence_labels,
353
+ token_labels,
354
+ choice_labels,
355
+ ) = config_and_inputs
356
+
357
+ inputs_dict = {
358
+ "input_ids": input_ids,
359
+ "token_type_ids": token_type_ids,
360
+ "head_mask": head_mask,
361
+ }
362
+
363
+ return config, inputs_dict
364
+
365
+
366
+ @require_torch
367
+ class GPTNeoModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
368
+ all_model_classes = (
369
+ (
370
+ GPTNeoModel,
371
+ GPTNeoForCausalLM,
372
+ GPTNeoForQuestionAnswering,
373
+ GPTNeoForSequenceClassification,
374
+ GPTNeoForTokenClassification,
375
+ )
376
+ if is_torch_available()
377
+ else ()
378
+ )
379
+ pipeline_model_mapping = (
380
+ {
381
+ "feature-extraction": GPTNeoModel,
382
+ "question-answering": GPTNeoForQuestionAnswering,
383
+ "text-classification": GPTNeoForSequenceClassification,
384
+ "text-generation": GPTNeoForCausalLM,
385
+ "token-classification": GPTNeoForTokenClassification,
386
+ "zero-shot": GPTNeoForSequenceClassification,
387
+ }
388
+ if is_torch_available()
389
+ else {}
390
+ )
391
+ fx_compatible = True
392
+ test_missing_keys = False
393
+ test_pruning = False
394
+ test_model_parallel = False
395
+
396
+ # special case for DoubleHeads model
397
+ def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
398
+ inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
399
+ return inputs_dict
400
+
401
+ def setUp(self):
402
+ self.model_tester = GPTNeoModelTester(self)
403
+ self.config_tester = ConfigTester(self, config_class=GPTNeoConfig, n_embd=37)
404
+
405
+ def test_config(self):
406
+ self.config_tester.run_common_tests()
407
+
408
+ def test_gpt_neo_model(self):
409
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
410
+ self.model_tester.create_and_check_gpt_neo_model(*config_and_inputs)
411
+
412
+ def test_gpt_neo_model_past(self):
413
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
414
+ self.model_tester.create_and_check_gpt_neo_model_past(*config_and_inputs)
415
+
416
+ def test_gpt_neo_model_att_mask_past(self):
417
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
418
+ self.model_tester.create_and_check_gpt_neo_model_attention_mask_past(*config_and_inputs)
419
+
420
+ def test_gpt_neo_model_past_large_inputs(self):
421
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
422
+ self.model_tester.create_and_check_gpt_neo_model_past_large_inputs(*config_and_inputs)
423
+
424
+ def test_gpt_neo_lm_head_model(self):
425
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
426
+ self.model_tester.create_and_check_lm_head_model(*config_and_inputs)
427
+
428
+ def test_gpt_neo_question_answering_model(self):
429
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
430
+ self.model_tester.create_and_check_gpt_neo_for_question_answering(*config_and_inputs)
431
+
432
+ def test_gpt_neo_sequence_classification_model(self):
433
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
434
+ self.model_tester.create_and_check_gpt_neo_for_sequence_classification(*config_and_inputs)
435
+
436
+ def test_gpt_neo_token_classification_model(self):
437
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
438
+ self.model_tester.create_and_check_gpt_neo_for_token_classification(*config_and_inputs)
439
+
440
+ def test_gpt_neo_gradient_checkpointing(self):
441
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
442
+ self.model_tester.create_and_check_forward_and_backwards(*config_and_inputs, gradient_checkpointing=True)
443
+
444
+ def _get_hidden_states(self):
445
+ return torch.tensor(
446
+ [
447
+ [
448
+ [0.4983, -0.7584, -1.6944, 0.5440],
449
+ [2.6918, 0.4206, 0.4176, 0.2055],
450
+ [-0.0071, -0.0405, -1.4920, -0.3630],
451
+ [1.0492, 0.1599, -1.7648, 0.2419],
452
+ [-1.8348, 2.0514, -0.1946, 0.3203],
453
+ [0.7672, -1.1600, -1.7118, -0.9056],
454
+ [0.2986, 0.5372, 0.7729, -0.1927],
455
+ [0.0285, 0.2629, -1.1156, -1.1992],
456
+ ]
457
+ ],
458
+ dtype=torch.float32,
459
+ device=torch_device,
460
+ )
461
+
462
+ def test_local_attn_probs(self):
463
+ model = GPTNeoModel.from_pretrained("valhalla/gpt-neo-random-tiny").eval()
464
+ layer = model.h[1].attn.attention.to(torch_device)
465
+ hidden_states = self._get_hidden_states()
466
+ hidden_states = torch.cat([hidden_states, hidden_states - 0.5], dim=2)
467
+
468
+ batch_size, seq_length, _ = hidden_states.shape
469
+ mask_tokens = 2
470
+ attention_mask = torch.ones(batch_size, seq_length, device=torch_device, dtype=torch.long)
471
+ attention_mask[:, -mask_tokens:] = 0 # dont attend last mask_tokens
472
+
473
+ attention_mask = attention_mask.view(batch_size, -1)
474
+ attention_mask = attention_mask[:, None, None, :]
475
+ attention_mask = (1.0 - attention_mask) * -10000.0
476
+
477
+ attn_probs = layer(hidden_states, attention_mask=attention_mask, output_attentions=True)[-1]
478
+
479
+ # the last 2 tokens are masked, and should have 0 attn_probs
480
+ self.assertTrue(torch.all(attn_probs[:, :, -mask_tokens:, -mask_tokens:] == 0))
481
+
482
+ # in loacal attention each token can only attend to the previous window_size tokens (inlcuding itself)
483
+ # here window_size is 4, so a token at index 5 can only attend to indcies [2, 3, 4, 5]
484
+ # and the attn_probs should be 0 for token [0, 1]
485
+ self.assertTrue(torch.all(attn_probs[:, :, 5, 2:6] != 0))
486
+ self.assertTrue(torch.all(attn_probs[:, :, 5, :2] == 0))
487
+
488
+
489
+ @require_torch
490
+ class GPTNeoModelLanguageGenerationTest(unittest.TestCase):
491
+ @cached_property
492
+ def model(self):
493
+ return GPTNeoForCausalLM.from_pretrained("EleutherAI/gpt-neo-1.3B").to(torch_device)
494
+
495
+ @cached_property
496
+ def tokenizer(self):
497
+ return GPT2Tokenizer.from_pretrained("EleutherAI/gpt-neo-1.3B")
498
+
499
+ @slow
500
+ def test_lm_generate_gpt_neo(self):
501
+ for checkpointing in [True, False]:
502
+ model = self.model
503
+ if checkpointing:
504
+ model.gradient_checkpointing_enable()
505
+ else:
506
+ model.gradient_checkpointing_disable()
507
+ input_ids = torch.tensor([[464, 3290]], dtype=torch.long, device=torch_device) # The dog
508
+ # The dog-eared copy of the book, which is a collection of essays by the late author,
509
+ expected_output_ids = [464, 3290, 12, 3380, 4866, 286, 262, 1492, 11, 543, 318, 257, 4947, 286, 27126, 416, 262, 2739, 1772, 11] # fmt: skip
510
+ output_ids = model.generate(input_ids, do_sample=False)
511
+ self.assertListEqual(output_ids[0].tolist(), expected_output_ids)
512
+
513
+ @slow
514
+ def test_gpt_neo_sample(self):
515
+ model = self.model
516
+ tokenizer = self.tokenizer
517
+
518
+ torch.manual_seed(0)
519
+ tokenized = tokenizer("Today is a nice day and", return_tensors="pt", return_token_type_ids=True)
520
+ input_ids = tokenized.input_ids.to(torch_device)
521
+ output_ids = model.generate(input_ids, do_sample=True)
522
+ output_str = tokenizer.decode(output_ids[0], skip_special_tokens=True)
523
+
524
+ EXPECTED_OUTPUT_STR = "Today is a nice day and if you don’t get the memo here is what you can"
525
+ self.assertEqual(output_str, EXPECTED_OUTPUT_STR)
526
+
527
+ @slow
528
+ def test_batch_generation(self):
529
+ model = self.model
530
+ tokenizer = self.tokenizer
531
+
532
+ tokenizer.padding_side = "left"
533
+
534
+ # Define PAD Token = EOS Token = 50256
535
+ tokenizer.pad_token = tokenizer.eos_token
536
+ model.config.pad_token_id = model.config.eos_token_id
537
+
538
+ # use different length sentences to test batching
539
+ sentences = [
540
+ "Hello, my dog is a little",
541
+ "Today, I am",
542
+ ]
543
+
544
+ inputs = tokenizer(sentences, return_tensors="pt", padding=True)
545
+ input_ids = inputs["input_ids"].to(torch_device)
546
+
547
+ outputs = model.generate(
548
+ input_ids=input_ids,
549
+ attention_mask=inputs["attention_mask"].to(torch_device),
550
+ )
551
+
552
+ inputs_non_padded = tokenizer(sentences[0], return_tensors="pt").input_ids.to(torch_device)
553
+ output_non_padded = model.generate(input_ids=inputs_non_padded)
554
+
555
+ num_paddings = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item()
556
+ inputs_padded = tokenizer(sentences[1], return_tensors="pt").input_ids.to(torch_device)
557
+ output_padded = model.generate(input_ids=inputs_padded, max_length=model.config.max_length - num_paddings)
558
+
559
+ batch_out_sentence = tokenizer.batch_decode(outputs, skip_special_tokens=True)
560
+ non_padded_sentence = tokenizer.decode(output_non_padded[0], skip_special_tokens=True)
561
+ padded_sentence = tokenizer.decode(output_padded[0], skip_special_tokens=True)
562
+
563
+ expected_output_sentence = [
564
+ "Hello, my dog is a little bit of a kitty. She is a very sweet and loving",
565
+ "Today, I am going to talk about the best way to get a job in the",
566
+ ]
567
+ self.assertListEqual(expected_output_sentence, batch_out_sentence)
568
+ self.assertListEqual(expected_output_sentence, [non_padded_sentence, padded_sentence])
569
+
570
+ @slow
571
+ def test_model_from_pretrained(self):
572
+ model_name = "EleutherAI/gpt-neo-1.3B"
573
+ model = GPTNeoModel.from_pretrained(model_name)
574
+ self.assertIsNotNone(model)
tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_neox/__init__.py ADDED
File without changes
tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_neox/test_modeling_gpt_neox.py ADDED
@@ -0,0 +1,483 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 GPTNeoX model."""
16
+
17
+ import unittest
18
+
19
+ from parameterized import parameterized
20
+
21
+ from transformers import AutoTokenizer, DynamicCache, GPTNeoXConfig, is_torch_available, set_seed
22
+ from transformers.testing_utils import require_torch, slow, torch_device
23
+
24
+ from ...generation.test_utils import GenerationTesterMixin
25
+ from ...test_configuration_common import ConfigTester
26
+ from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
27
+ from ...test_pipeline_mixin import PipelineTesterMixin
28
+
29
+
30
+ if is_torch_available():
31
+ import torch
32
+
33
+ from transformers import (
34
+ GPTNeoXForCausalLM,
35
+ GPTNeoXForQuestionAnswering,
36
+ GPTNeoXForSequenceClassification,
37
+ GPTNeoXForTokenClassification,
38
+ GPTNeoXModel,
39
+ )
40
+ from transformers.models.gpt_neox.modeling_gpt_neox import GPTNeoXRotaryEmbedding
41
+
42
+
43
+ class GPTNeoXModelTester:
44
+ def __init__(
45
+ self,
46
+ parent,
47
+ batch_size=13,
48
+ seq_length=7,
49
+ is_training=True,
50
+ use_input_mask=True,
51
+ use_token_type_ids=True,
52
+ use_labels=True,
53
+ vocab_size=99,
54
+ hidden_size=64,
55
+ num_hidden_layers=2,
56
+ num_attention_heads=4,
57
+ intermediate_size=37,
58
+ hidden_act="gelu",
59
+ hidden_dropout_prob=0.1,
60
+ attention_probs_dropout_prob=0.1,
61
+ max_position_embeddings=512,
62
+ type_vocab_size=16,
63
+ type_sequence_label_size=2,
64
+ initializer_range=0.02,
65
+ num_labels=3,
66
+ num_choices=4,
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.scope = scope
91
+ self.pad_token_id = vocab_size - 1
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_labels = None
101
+ if self.use_labels:
102
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
103
+
104
+ config = self.get_config()
105
+
106
+ return config, input_ids, input_mask, token_labels
107
+
108
+ def get_config(self):
109
+ return GPTNeoXConfig(
110
+ vocab_size=self.vocab_size,
111
+ hidden_size=self.hidden_size,
112
+ num_hidden_layers=self.num_hidden_layers,
113
+ num_attention_heads=self.num_attention_heads,
114
+ intermediate_size=self.intermediate_size,
115
+ hidden_act=self.hidden_act,
116
+ hidden_dropout_prob=self.hidden_dropout_prob,
117
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
118
+ max_position_embeddings=self.max_position_embeddings,
119
+ type_vocab_size=self.type_vocab_size,
120
+ is_decoder=False,
121
+ initializer_range=self.initializer_range,
122
+ pad_token_id=self.pad_token_id,
123
+ )
124
+
125
+ def prepare_config_and_inputs_for_decoder(self):
126
+ config, input_ids, input_mask, token_labels = self.prepare_config_and_inputs()
127
+
128
+ config.is_decoder = True
129
+
130
+ return config, input_ids, input_mask, token_labels
131
+
132
+ def create_and_check_model(self, config, input_ids, input_mask):
133
+ model = GPTNeoXModel(config=config)
134
+ model.to(torch_device)
135
+ model.eval()
136
+ _ = model(input_ids, attention_mask=input_mask)
137
+ result = model(input_ids)
138
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
139
+
140
+ def create_and_check_model_as_decoder(self, config, input_ids, input_mask):
141
+ config.add_cross_attention = True
142
+ model = GPTNeoXModel(config)
143
+ model.to(torch_device)
144
+ model.eval()
145
+ result = model(input_ids, attention_mask=input_mask)
146
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
147
+
148
+ def create_and_check_for_causal_lm(self, config, input_ids, input_mask, token_labels):
149
+ model = GPTNeoXForCausalLM(config=config)
150
+ model.to(torch_device)
151
+ model.eval()
152
+ result = model(input_ids, attention_mask=input_mask, labels=token_labels)
153
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
154
+
155
+ def create_and_check_for_question_answering(self, config, input_ids, input_mask, token_labels):
156
+ config.num_labels = self.num_labels
157
+ model = GPTNeoXForQuestionAnswering(config)
158
+ model.to(torch_device)
159
+ model.eval()
160
+ result = model(input_ids, attention_mask=input_mask)
161
+ self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
162
+ self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
163
+
164
+ def create_and_check_for_sequence_classification(self, config, input_ids, input_mask, token_labels):
165
+ config.num_labels = self.num_labels
166
+ model = GPTNeoXForSequenceClassification(config)
167
+ model.to(torch_device)
168
+ model.eval()
169
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
170
+ result = model(input_ids, attention_mask=input_mask, labels=sequence_labels)
171
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
172
+
173
+ def create_and_check_for_token_classification(self, config, input_ids, input_mask, token_labels):
174
+ config.num_labels = self.num_labels
175
+ model = GPTNeoXForTokenClassification(config)
176
+ model.to(torch_device)
177
+ model.eval()
178
+ result = model(input_ids, attention_mask=input_mask, labels=token_labels)
179
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
180
+
181
+ def create_and_check_decoder_model_past_large_inputs(self, config, input_ids, input_mask):
182
+ config.is_decoder = True
183
+ model = GPTNeoXForCausalLM(config=config)
184
+ model.to(torch_device)
185
+ model.eval()
186
+
187
+ # first forward pass
188
+ outputs = model(input_ids, attention_mask=input_mask, use_cache=True)
189
+ past_key_values = outputs.past_key_values
190
+
191
+ # create hypothetical multiple next token and extent to next_input_ids
192
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
193
+ next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
194
+
195
+ # append to next input_ids and
196
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
197
+ next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
198
+
199
+ output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask, output_hidden_states=True)
200
+ output_from_no_past = output_from_no_past["hidden_states"][0]
201
+ output_from_past = model(
202
+ next_tokens,
203
+ attention_mask=next_attention_mask,
204
+ past_key_values=past_key_values,
205
+ output_hidden_states=True,
206
+ )["hidden_states"][0]
207
+
208
+ # select random slice
209
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
210
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
211
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
212
+
213
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
214
+
215
+ # test that outputs are equal for slice
216
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
217
+
218
+ def create_and_check_cached_forward_with_and_without_attention_mask(self, config, input_ids, *args):
219
+ # Relevant issue: https://github.com/huggingface/transformers/issues/31943
220
+ model = GPTNeoXModel(config)
221
+ model.to(torch_device)
222
+ model.eval()
223
+
224
+ # We want this for SDPA, eager works with a `None` attention mask
225
+ assert (
226
+ model.config._attn_implementation == "sdpa"
227
+ ), "This test assumes the model to have the SDPA implementation for its attention calculations."
228
+
229
+ # Prepare cache and non_cache input, needs a full attention mask
230
+ cached_len = input_ids.shape[-1] // 2
231
+ input_mask = torch.ones(size=input_ids.size()).to(torch_device)
232
+ cache_inputs = {"input_ids": input_ids[:, :cached_len], "attention_mask": input_mask[:, :cached_len]}
233
+ non_cache_inputs = {"input_ids": input_ids[:, cached_len:], "attention_mask": input_mask}
234
+
235
+ def copy_cache(cache: DynamicCache):
236
+ """Deep copy a DynamicCache to reuse the same one multiple times."""
237
+ new_cache = cache
238
+ for i in range(len(cache)):
239
+ new_cache.key_cache[i] = cache.key_cache[i].clone()
240
+ new_cache.value_cache[i] = cache.value_cache[i].clone()
241
+
242
+ # Cached forward once with the attention mask provided and the other time without it (which should assume full attention)
243
+ # We need to run both on a copy of the cache, otherwise it is modified in-place
244
+ cache_outputs = model(**cache_inputs)
245
+ cache = cache_outputs.past_key_values
246
+ full_outputs_with_attention_mask = model(
247
+ **non_cache_inputs, past_key_values=copy_cache(cache)
248
+ ).last_hidden_state
249
+ full_outputs_without_attention_mask = model(
250
+ non_cache_inputs["input_ids"], past_key_values=copy_cache(cache)
251
+ ).last_hidden_state
252
+
253
+ self.parent.assertTrue(
254
+ torch.allclose(full_outputs_with_attention_mask, full_outputs_without_attention_mask, atol=1e-5)
255
+ )
256
+
257
+ def prepare_config_and_inputs_for_common(self):
258
+ config_and_inputs = self.prepare_config_and_inputs()
259
+ config, input_ids, input_mask, token_labels = config_and_inputs
260
+ inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
261
+ return config, inputs_dict
262
+
263
+
264
+ @require_torch
265
+ class GPTNeoXModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
266
+ all_model_classes = (
267
+ (
268
+ GPTNeoXModel,
269
+ GPTNeoXForCausalLM,
270
+ GPTNeoXForQuestionAnswering,
271
+ GPTNeoXForSequenceClassification,
272
+ GPTNeoXForTokenClassification,
273
+ )
274
+ if is_torch_available()
275
+ else ()
276
+ )
277
+ pipeline_model_mapping = (
278
+ {
279
+ "feature-extraction": GPTNeoXModel,
280
+ "question-answering": GPTNeoXForQuestionAnswering,
281
+ "text-classification": GPTNeoXForSequenceClassification,
282
+ "text-generation": GPTNeoXForCausalLM,
283
+ "token-classification": GPTNeoXForTokenClassification,
284
+ "zero-shot": GPTNeoXForSequenceClassification,
285
+ }
286
+ if is_torch_available()
287
+ else {}
288
+ )
289
+ test_pruning = False
290
+ test_missing_keys = False
291
+ test_model_parallel = False
292
+ test_head_masking = False
293
+
294
+ def setUp(self):
295
+ self.model_tester = GPTNeoXModelTester(self)
296
+ self.config_tester = ConfigTester(self, config_class=GPTNeoXConfig, hidden_size=64, num_attention_heads=8)
297
+
298
+ def test_config(self):
299
+ self.config_tester.run_common_tests()
300
+
301
+ def test_model(self):
302
+ config, input_ids, input_mask, token_labels = self.model_tester.prepare_config_and_inputs()
303
+ self.model_tester.create_and_check_model(config, input_ids, input_mask)
304
+
305
+ def test_model_as_decoder(self):
306
+ config, input_ids, input_mask, token_labels = self.model_tester.prepare_config_and_inputs_for_decoder()
307
+ self.model_tester.create_and_check_model_as_decoder(config, input_ids, input_mask)
308
+
309
+ def test_model_as_decoder_with_default_input_mask(self):
310
+ # This regression test was failing with PyTorch < 1.3
311
+ config, input_ids, input_mask, token_labels = self.model_tester.prepare_config_and_inputs_for_decoder()
312
+
313
+ input_mask = None
314
+
315
+ self.model_tester.create_and_check_model_as_decoder(config, input_ids, input_mask)
316
+
317
+ def test_decoder_model_past_large_inputs(self):
318
+ config, input_ids, input_mask, token_labels = self.model_tester.prepare_config_and_inputs()
319
+ self.model_tester.create_and_check_decoder_model_past_large_inputs(config, input_ids, input_mask)
320
+
321
+ def test_model_for_causal_lm(self):
322
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
323
+ self.model_tester.create_and_check_for_causal_lm(*config_and_inputs)
324
+
325
+ def test_model_for_question_answering(self):
326
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
327
+ self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
328
+
329
+ def test_model_for_sequence_classification(self):
330
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
331
+ self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs)
332
+
333
+ def test_model_for_token_classification(self):
334
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
335
+ self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
336
+
337
+ def test_cached_forward_with_and_without_attention_mask(self):
338
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
339
+ self.model_tester.create_and_check_cached_forward_with_and_without_attention_mask(*config_and_inputs)
340
+
341
+ @unittest.skip(reason="Feed forward chunking is not implemented")
342
+ def test_feed_forward_chunking(self):
343
+ pass
344
+
345
+ @parameterized.expand([("linear",), ("dynamic",)])
346
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_model_rope_scaling_from_config with Llama->GPTNeoX
347
+ def test_model_rope_scaling_from_config(self, scaling_type):
348
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
349
+ short_input = ids_tensor([1, 10], config.vocab_size)
350
+ long_input = ids_tensor([1, int(config.max_position_embeddings * 1.5)], config.vocab_size)
351
+
352
+ set_seed(42) # Fixed seed at init time so the two models get the same random weights
353
+ original_model = GPTNeoXModel(config)
354
+ original_model.to(torch_device)
355
+ original_model.eval()
356
+ original_short_output = original_model(short_input).last_hidden_state
357
+ original_long_output = original_model(long_input).last_hidden_state
358
+
359
+ set_seed(42) # Fixed seed at init time so the two models get the same random weights
360
+ config.rope_scaling = {"type": scaling_type, "factor": 10.0}
361
+ scaled_model = GPTNeoXModel(config)
362
+ scaled_model.to(torch_device)
363
+ scaled_model.eval()
364
+ scaled_short_output = scaled_model(short_input).last_hidden_state
365
+ scaled_long_output = scaled_model(long_input).last_hidden_state
366
+
367
+ # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
368
+ # maximum sequence length, so the outputs for the short input should match.
369
+ if scaling_type == "dynamic":
370
+ torch.testing.assert_close(original_short_output, scaled_short_output, rtol=1e-5, atol=1e-5)
371
+ else:
372
+ self.assertFalse(torch.allclose(original_short_output, scaled_short_output, atol=1e-5))
373
+
374
+ # The output should be different for long inputs
375
+ self.assertFalse(torch.allclose(original_long_output, scaled_long_output, atol=1e-5))
376
+
377
+ def test_model_rope_scaling(self):
378
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
379
+ scaling_factor = 10
380
+ short_input_length = 10
381
+ long_input_length = int(config.max_position_embeddings * 1.5)
382
+
383
+ # Inputs
384
+ x = torch.randn(1, dtype=torch.float32, device=torch_device) # used exlusively to get the dtype and the device
385
+ position_ids_short = torch.arange(short_input_length, dtype=torch.long, device=torch_device)
386
+ position_ids_short = position_ids_short.unsqueeze(0)
387
+ position_ids_long = torch.arange(long_input_length, dtype=torch.long, device=torch_device)
388
+ position_ids_long = position_ids_long.unsqueeze(0)
389
+
390
+ # Sanity check original RoPE
391
+ original_rope = GPTNeoXRotaryEmbedding(config).to(torch_device)
392
+ original_cos_short, original_sin_short = original_rope(x, position_ids_short)
393
+ original_cos_long, original_sin_long = original_rope(x, position_ids_long)
394
+ torch.testing.assert_close(original_cos_short, original_cos_long[:, :short_input_length, :])
395
+ torch.testing.assert_close(original_sin_short, original_sin_long[:, :short_input_length, :])
396
+
397
+ # Sanity check linear RoPE scaling
398
+ # New position "x" should match original position with index "x/scaling_factor"
399
+ config.rope_scaling = {"type": "linear", "factor": scaling_factor}
400
+ linear_scaling_rope = GPTNeoXRotaryEmbedding(config).to(torch_device)
401
+ linear_cos_short, linear_sin_short = linear_scaling_rope(x, position_ids_short)
402
+ linear_cos_long, linear_sin_long = linear_scaling_rope(x, position_ids_long)
403
+ torch.testing.assert_close(linear_cos_short, linear_cos_long[:, :short_input_length, :])
404
+ torch.testing.assert_close(linear_sin_short, linear_sin_long[:, :short_input_length, :])
405
+ for new_position in range(0, long_input_length, scaling_factor):
406
+ original_position = int(new_position // scaling_factor)
407
+ torch.testing.assert_close(linear_cos_long[:, new_position, :], original_cos_long[:, original_position, :])
408
+ torch.testing.assert_close(linear_sin_long[:, new_position, :], original_sin_long[:, original_position, :])
409
+
410
+ # Sanity check Dynamic NTK RoPE scaling
411
+ # Scaling should only be observed after a long input is fed. We can observe that the frequencies increase
412
+ # with scaling_factor (or that `inv_freq` decreases)
413
+ config.rope_scaling = {"type": "dynamic", "factor": scaling_factor}
414
+ ntk_scaling_rope = GPTNeoXRotaryEmbedding(config).to(torch_device)
415
+ ntk_cos_short, ntk_sin_short = ntk_scaling_rope(x, position_ids_short)
416
+ ntk_cos_long, ntk_sin_long = ntk_scaling_rope(x, position_ids_long)
417
+ torch.testing.assert_close(ntk_cos_short, original_cos_short)
418
+ torch.testing.assert_close(ntk_sin_short, original_sin_short)
419
+ with self.assertRaises(AssertionError):
420
+ torch.testing.assert_close(ntk_cos_long, original_cos_long)
421
+ with self.assertRaises(AssertionError):
422
+ torch.testing.assert_close(ntk_sin_long, original_sin_long)
423
+ self.assertTrue((ntk_scaling_rope.inv_freq <= original_rope.inv_freq).all())
424
+
425
+
426
+ @require_torch
427
+ class GPTNeoXLanguageGenerationTest(unittest.TestCase):
428
+ @slow
429
+ def test_lm_generate_gptneox(self):
430
+ tokenizer = AutoTokenizer.from_pretrained("EleutherAI/pythia-410m-deduped")
431
+ for checkpointing in [True, False]:
432
+ model = GPTNeoXForCausalLM.from_pretrained("EleutherAI/pythia-410m-deduped")
433
+
434
+ if checkpointing:
435
+ model.gradient_checkpointing_enable()
436
+ else:
437
+ model.gradient_checkpointing_disable()
438
+ model.to(torch_device)
439
+
440
+ inputs = tokenizer("My favorite food is", return_tensors="pt").to(torch_device)
441
+ # The hub repo. is updated on 2023-04-04, resulting in poor outputs.
442
+ # See: https://github.com/huggingface/transformers/pull/24193
443
+ expected_output = "My favorite food is a good old-fashioned, old-fashioned, old-fashioned.\n\nI'm not sure"
444
+
445
+ output_ids = model.generate(**inputs, do_sample=False, max_new_tokens=20)
446
+ output_str = tokenizer.batch_decode(output_ids)[0]
447
+
448
+ self.assertEqual(output_str, expected_output)
449
+
450
+ @slow
451
+ def test_lm_generate_flex_attn_gptneox(self):
452
+ tokenizer = AutoTokenizer.from_pretrained("EleutherAI/pythia-410m-deduped")
453
+ for checkpointing in [True, False]:
454
+ model = GPTNeoXForCausalLM.from_pretrained(
455
+ "EleutherAI/pythia-410m-deduped", attn_implementation="flex_attention"
456
+ )
457
+ self.assertTrue(model.config._attn_implementation == "flex_attention")
458
+
459
+ if checkpointing:
460
+ model.gradient_checkpointing_enable()
461
+ else:
462
+ model.gradient_checkpointing_disable()
463
+ model.to(torch_device)
464
+
465
+ inputs = tokenizer("My favorite food is", return_tensors="pt").to(torch_device)
466
+ # The hub repo. is updated on 2023-04-04, resulting in poor outputs.
467
+ # See: https://github.com/huggingface/transformers/pull/24193
468
+ expected_output = "My favorite food is a good old-fashioned, old-fashioned, old-fashioned.\n\nI'm not sure"
469
+
470
+ output_ids = model.generate(**inputs, do_sample=False, max_new_tokens=20)
471
+ output_str = tokenizer.batch_decode(output_ids)[0]
472
+
473
+ self.assertEqual(output_str, expected_output)
474
+
475
+ def pythia_integration_test(self):
476
+ model_name_or_path = "EleutherAI/pythia-70m"
477
+ model = GPTNeoXForCausalLM.from_pretrained(model_name_or_path, torch_dtype=torch.float16).to(torch_device)
478
+ EXPECTED_LOGITS = torch.tensor([1069.0000, 228.7500, 1072.0000, 1072.0000, 1069.0000, 1068.0000, 1068.0000, 1071.0000, 1071.0000, 1071.0000, 1073.0000, 1070.0000, 1071.0000, 1075.0000, 1073.0000, 1075.0000, 1074.0000, 1069.0000, 1072.0000, 1071.0000, 1071.0000, 1071.0000, 1070.0000, 1069.0000, 1069.0000, 1069.0000, 1070.0000, 1075.0000, 1073.0000, 1074.0000]) # fmt: skip
479
+ input_ids = [29, 93, 303, 64, 5478, 49651, 10394, 187, 34, 12939, 875]
480
+ # alternative: tokenizer('<|im_start|>system\nA chat between')
481
+ input_ids = torch.as_tensor(input_ids)[None].to(torch_device)
482
+ outputs = model(input_ids)["logits"][:, -1][0, :30]
483
+ torch.testing.assert_close(EXPECTED_LOGITS, outputs, rtol=1e-5, atol=1e-5)
tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_neox_japanese/__init__.py ADDED
File without changes
tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_neox_japanese/test_modeling_gpt_neox_japanese.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 GPTNeoXJapanese model."""
16
+
17
+ import unittest
18
+
19
+ from transformers import GPTNeoXJapaneseConfig, is_torch_available
20
+ from transformers.models.gpt_neox_japanese.tokenization_gpt_neox_japanese import GPTNeoXJapaneseTokenizer
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 GPTNeoXJapaneseForCausalLM, GPTNeoXJapaneseModel
33
+
34
+
35
+ class GPTNeoXJapaneseModelTester:
36
+ def __init__(
37
+ self,
38
+ parent,
39
+ batch_size=13,
40
+ seq_length=7,
41
+ is_training=True,
42
+ use_input_mask=True,
43
+ use_token_type_ids=True,
44
+ use_labels=True,
45
+ vocab_size=99,
46
+ hidden_size=32,
47
+ num_hidden_layers=2,
48
+ num_attention_heads=4,
49
+ intermediate_multiple_size=4,
50
+ hidden_act="gelu",
51
+ hidden_dropout=0.0,
52
+ attention_dropout=0.1,
53
+ weight_tying=True,
54
+ max_position_embeddings=512,
55
+ type_vocab_size=16,
56
+ type_sequence_label_size=2,
57
+ initializer_range=0.02,
58
+ num_labels=3,
59
+ num_choices=4,
60
+ bos_token_id=1,
61
+ eos_token_id=0,
62
+ scope=None,
63
+ ):
64
+ self.parent = parent
65
+ self.batch_size = batch_size
66
+ self.seq_length = seq_length
67
+ self.is_training = is_training
68
+ self.use_input_mask = use_input_mask
69
+ self.use_token_type_ids = use_token_type_ids
70
+ self.use_labels = use_labels
71
+ self.vocab_size = vocab_size
72
+ self.hidden_size = hidden_size
73
+ self.num_hidden_layers = num_hidden_layers
74
+ self.num_attention_heads = num_attention_heads
75
+ self.intermediate_multiple_size = intermediate_multiple_size
76
+ self.hidden_act = hidden_act
77
+ self.hidden_dropout = hidden_dropout
78
+ self.attention_dropout = attention_dropout
79
+ self.weight_tying = weight_tying
80
+ self.max_position_embeddings = max_position_embeddings
81
+ self.type_vocab_size = type_vocab_size
82
+ self.type_sequence_label_size = type_sequence_label_size
83
+ self.initializer_range = initializer_range
84
+ self.num_labels = num_labels
85
+ self.num_choices = num_choices
86
+ self.scope = scope
87
+ self.eos_token_id = eos_token_id
88
+ self.bos_token_id = bos_token_id
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_labels = None
98
+ if self.use_labels:
99
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
100
+
101
+ config = self.get_config()
102
+
103
+ return config, input_ids, input_mask, token_labels
104
+
105
+ def get_config(self):
106
+ return GPTNeoXJapaneseConfig(
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_multiple_size=self.intermediate_multiple_size,
112
+ hidden_act=self.hidden_act,
113
+ hidden_dropout=self.hidden_dropout,
114
+ attention_dropout=self.attention_dropout,
115
+ weight_tying=self.weight_tying,
116
+ max_position_embeddings=self.max_position_embeddings,
117
+ type_vocab_size=self.type_vocab_size,
118
+ is_decoder=False,
119
+ initializer_range=self.initializer_range,
120
+ eos_token_id=self.eos_token_id,
121
+ bos_token_id=self.bos_token_id,
122
+ )
123
+
124
+ def prepare_config_and_inputs_for_decoder(self):
125
+ config, input_ids, input_mask, token_labels = self.prepare_config_and_inputs()
126
+
127
+ config.is_decoder = True
128
+
129
+ return config, input_ids, input_mask, token_labels
130
+
131
+ def create_and_check_model(self, config, input_ids, input_mask):
132
+ model = GPTNeoXJapaneseModel(config=config)
133
+ model.to(torch_device)
134
+ model.eval()
135
+ _ = 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_model_as_decoder(self, config, input_ids, input_mask):
140
+ config.add_cross_attention = True
141
+ model = GPTNeoXJapaneseModel(config)
142
+ model.to(torch_device)
143
+ model.eval()
144
+ result = model(input_ids, attention_mask=input_mask)
145
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
146
+
147
+ def create_and_check_for_causal_lm(self, config, input_ids, input_mask, token_labels):
148
+ model = GPTNeoXJapaneseForCausalLM(config=config)
149
+ model.to(torch_device)
150
+ model.eval()
151
+ result = model(input_ids, attention_mask=input_mask, labels=token_labels)
152
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
153
+
154
+ def create_and_check_decoder_model_past_large_inputs(self, config, input_ids, input_mask):
155
+ config.is_decoder = True
156
+ model = GPTNeoXJapaneseForCausalLM(config=config)
157
+ model.to(torch_device)
158
+ model.eval()
159
+
160
+ # first forward pass
161
+ outputs = model(input_ids, attention_mask=input_mask, use_cache=True)
162
+ past_key_values = outputs.past_key_values
163
+
164
+ # create hypothetical multiple next token and extent to next_input_ids
165
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
166
+ next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
167
+
168
+ # append to next input_ids and
169
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
170
+ next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
171
+
172
+ output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask, output_hidden_states=True)
173
+ output_from_no_past = output_from_no_past["hidden_states"][0]
174
+ output_from_past = model(
175
+ next_tokens,
176
+ attention_mask=next_attention_mask,
177
+ past_key_values=past_key_values,
178
+ output_hidden_states=True,
179
+ )["hidden_states"][0]
180
+
181
+ # select random slice
182
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
183
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
184
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
185
+
186
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
187
+
188
+ # test that outputs are equal for slice
189
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
190
+
191
+ def prepare_config_and_inputs_for_common(self):
192
+ config_and_inputs = self.prepare_config_and_inputs()
193
+ config, input_ids, input_mask, token_labels = config_and_inputs
194
+ inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
195
+ return config, inputs_dict
196
+
197
+
198
+ @require_torch
199
+ class GPTNeoXModelJapaneseTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
200
+ all_model_classes = (GPTNeoXJapaneseModel, GPTNeoXJapaneseForCausalLM) if is_torch_available() else ()
201
+ pipeline_model_mapping = (
202
+ {"feature-extraction": GPTNeoXJapaneseModel, "text-generation": GPTNeoXJapaneseForCausalLM}
203
+ if is_torch_available()
204
+ else {}
205
+ )
206
+ test_pruning = False
207
+ test_missing_keys = False
208
+ test_model_parallel = False
209
+ test_head_masking = False
210
+
211
+ def setUp(self):
212
+ self.model_tester = GPTNeoXJapaneseModelTester(self)
213
+ self.config_tester = ConfigTester(self, config_class=GPTNeoXJapaneseConfig, hidden_size=37)
214
+
215
+ def test_config(self):
216
+ self.config_tester.run_common_tests()
217
+
218
+ def test_model(self):
219
+ config, input_ids, input_mask, token_labels = self.model_tester.prepare_config_and_inputs()
220
+ self.model_tester.create_and_check_model(config, input_ids, input_mask)
221
+
222
+ def test_model_as_decoder(self):
223
+ config, input_ids, input_mask, token_labels = self.model_tester.prepare_config_and_inputs_for_decoder()
224
+ self.model_tester.create_and_check_model_as_decoder(config, input_ids, input_mask)
225
+
226
+ def test_model_as_decoder_with_default_input_mask(self):
227
+ # This regression test was failing with PyTorch < 1.3
228
+ config, input_ids, input_mask, token_labels = self.model_tester.prepare_config_and_inputs_for_decoder()
229
+
230
+ input_mask = None
231
+
232
+ self.model_tester.create_and_check_model_as_decoder(config, input_ids, input_mask)
233
+
234
+ def test_decoder_model_past_large_inputs(self):
235
+ config, input_ids, input_mask, token_labels = self.model_tester.prepare_config_and_inputs()
236
+ self.model_tester.create_and_check_decoder_model_past_large_inputs(config, input_ids, input_mask)
237
+
238
+ def test_model_for_causal_lm(self):
239
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
240
+ self.model_tester.create_and_check_for_causal_lm(*config_and_inputs)
241
+
242
+ @slow
243
+ def test_generation(self):
244
+ model_id = "abeja/gpt-neox-japanese-2.7b"
245
+
246
+ prompts = ["データサイエンティストとは、", "100年後に必要とされる会社は、", "フルリモートの環境で働くために必要なことは、", "国境の長いトンネルを抜けると", "美味しい日本食といえば、"] # fmt: skip
247
+
248
+ EXPECTED_OUTPUTS = [
249
+ "データサイエンティストとは、データを分析し、ビジネスに役立つ知見を導き出す専門家のことです。",
250
+ "100年後に必要とされる会社は、「人」が中心の会社です。",
251
+ "フルリモートの環境で働くために必要なことは、「自分の時間をコントロールする」ことです。",
252
+ "国境の長いトンネルを抜けると、そこは雪国だった。",
253
+ "美味しい日本食といえば、やっぱりお寿司ですよね。",
254
+ ]
255
+
256
+ tokenizer = GPTNeoXJapaneseTokenizer.from_pretrained(model_id)
257
+ model = GPTNeoXJapaneseForCausalLM.from_pretrained(model_id)
258
+
259
+ predicted_outputs = []
260
+ for prompt in prompts:
261
+ input_ids = tokenizer(prompt, return_tensors="pt").input_ids
262
+ generated_ids = model.generate(input_ids, max_length=50)
263
+ generated_string = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
264
+ predicted_outputs += generated_string
265
+ self.assertListEqual(predicted_outputs, EXPECTED_OUTPUTS)
266
+
267
+ @unittest.skip("GPTNeoXJapanese applies bias to attention scores")
268
+ def test_custom_4d_attention_mask(self):
269
+ pass
tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_neox_japanese/test_tokenization_gpt_neox_japanese.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
17
+ import json
18
+ import os
19
+ import unittest
20
+
21
+ from transformers.models.gpt_neox_japanese.tokenization_gpt_neox_japanese import (
22
+ VOCAB_FILES_NAMES,
23
+ GPTNeoXJapaneseTokenizer,
24
+ )
25
+ from transformers.testing_utils import require_tokenizers, slow
26
+
27
+ from ...test_tokenization_common import TokenizerTesterMixin
28
+
29
+
30
+ @require_tokenizers
31
+ class GPTNeoXJapaneseTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
32
+ from_pretrained_id = "abeja/gpt-neox-japanese-2.7b"
33
+ tokenizer_class = GPTNeoXJapaneseTokenizer
34
+ test_rust_tokenizer = False
35
+ from_pretrained_kwargs = {"do_clean_text": False, "add_prefix_space": False}
36
+
37
+ def setUp(self):
38
+ super().setUp()
39
+
40
+ vocab_tokens = [
41
+ "こん",
42
+ "こんに",
43
+ "にちは",
44
+ "ばんは",
45
+ "世界,㔺界",
46
+ "、",
47
+ "。",
48
+ "<BR>",
49
+ "<SP>",
50
+ "<TAB>",
51
+ "<URL>",
52
+ "<EMAIL>",
53
+ "<TEL>",
54
+ "<DATE>",
55
+ "<PRICE>",
56
+ "<BLOCK>",
57
+ "<KIGOU>",
58
+ "<U2000U2BFF>",
59
+ "<|emoji1|>",
60
+ "<unk>",
61
+ "<|startoftext|>",
62
+ "<|endoftext|>",
63
+ ]
64
+ emoji_tokens = {"emoji": {"\ud83d\ude00": "<|emoji1|>"}, "emoji_inv": {"<|emoji1|>": "\ud83d\ude00"}} # 😀
65
+ self.special_tokens_map = {"unk_token": "<unk>"}
66
+
67
+ self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"])
68
+ self.emoji_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["emoji_file"])
69
+ with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer:
70
+ vocab_writer.write("".join([x + "\n" for x in vocab_tokens]))
71
+ with open(self.emoji_file, "w") as emoji_writer:
72
+ emoji_writer.write(json.dumps(emoji_tokens))
73
+
74
+ def get_tokenizer(self, **kwargs):
75
+ kwargs.update(self.special_tokens_map)
76
+ return GPTNeoXJapaneseTokenizer.from_pretrained(self.tmpdirname, **kwargs)
77
+
78
+ def get_input_output_texts(self, tokenizer):
79
+ input_text = "こんにちは、世界。 \nこんばんは、㔺界。😀"
80
+ output_text = "こんにちは、世界。 \nこんばんは、世界。😀"
81
+ return input_text, output_text
82
+
83
+ def get_clean_sequence(self, tokenizer):
84
+ input_text, output_text = self.get_input_output_texts(tokenizer)
85
+ ids = tokenizer.encode(output_text, add_special_tokens=False)
86
+ text = tokenizer.decode(ids, clean_up_tokenization_spaces=False)
87
+ return text, ids
88
+
89
+ def test_pretokenized_inputs(self):
90
+ pass # TODO add if relevant
91
+
92
+ def test_maximum_encoding_length_pair_input(self):
93
+ pass # TODO add if relevant
94
+
95
+ def test_maximum_encoding_length_single_input(self):
96
+ pass # TODO add if relevant
97
+
98
+ def test_full_tokenizer(self):
99
+ tokenizer = self.get_tokenizer()
100
+
101
+ # Testing tokenization
102
+ input_text = "こんにちは、世界。 こんばんは、㔺界。"
103
+ expected_token = ["こん", "にちは", "、", "世界", "。", "<SP>", "こん", "ばんは", "、", "㔺界", "。"]
104
+ tokens = tokenizer.tokenize(input_text)
105
+ self.assertListEqual(tokens, expected_token)
106
+
107
+ # Testing conversion to ids without special tokens
108
+ expected_ids = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6]
109
+ input_ids = tokenizer.convert_tokens_to_ids(tokens)
110
+ self.assertListEqual(input_ids, expected_ids)
111
+
112
+ # Testing conversion to ids with special tokens
113
+ input_tokens = tokens + [tokenizer.unk_token]
114
+ expected_ids = [0, 2, 5, 4, 6, 8, 0, 3, 5, 4, 6, 19]
115
+ input_ids = tokenizer.convert_tokens_to_ids(input_tokens)
116
+ self.assertListEqual(input_ids, expected_ids)
117
+
118
+ @slow
119
+ def test_sequence_builders(self):
120
+ tokenizer = self.tokenizer_class.from_pretrained("abeja/gpt-neox-japanese-2.7b")
121
+
122
+ ids_1 = tokenizer.encode("ありがとう。", add_special_tokens=False)
123
+ ids_2 = tokenizer.encode("どういたしまして。", add_special_tokens=False)
124
+
125
+ encoded_sentence = tokenizer.build_inputs_with_special_tokens(ids_1)
126
+ encoded_pair = tokenizer.build_inputs_with_special_tokens(ids_1, ids_2)
127
+
128
+ assert encoded_sentence == ids_1
129
+ assert encoded_pair == ids_1 + ids_2
130
+
131
+ @unittest.skip
132
+ def test_conversion_reversible(self):
133
+ # Intentionally convert some words to accommodate character fluctuations unique to Japanese
134
+ pass
135
+
136
+ @unittest.skip(reason="tokenizer has no padding token")
137
+ def test_padding_different_model_input_name(self):
138
+ pass
tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_sw3/__init__.py ADDED
File without changes
tasks/tasksmith-441eeab80047/tests/source/tests/models/gpt_sw3/test_tokenization_gpt_sw3.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 Hugging Face 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
+ import unittest
17
+
18
+ from transformers import GPTSw3Tokenizer
19
+ from transformers.testing_utils import get_tests_dir, require_jinja, require_sentencepiece, require_tokenizers, slow
20
+
21
+ from ...test_tokenization_common import TokenizerTesterMixin
22
+
23
+
24
+ SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece_with_bytefallback.model")
25
+
26
+
27
+ @require_sentencepiece
28
+ @require_tokenizers
29
+ class GPTSw3TokenizationTest(TokenizerTesterMixin, unittest.TestCase):
30
+ from_pretrained_id = "AI-Sweden-Models/gpt-sw3-126m"
31
+ tokenizer_class = GPTSw3Tokenizer
32
+ test_rust_tokenizer = False
33
+ test_sentencepiece = True
34
+ test_sentencepiece_ignore_case = False
35
+
36
+ def setUp(self):
37
+ super().setUp()
38
+
39
+ # We have a SentencePiece fixture for testing
40
+ tokenizer = GPTSw3Tokenizer(SAMPLE_VOCAB, eos_token="<unk>", bos_token="<unk>", pad_token="<unk>")
41
+
42
+ tokenizer.save_pretrained(self.tmpdirname)
43
+
44
+ def get_input_output_texts(self, tokenizer):
45
+ input_text = "This is a test"
46
+ output_text = "This is a test"
47
+ return input_text, output_text
48
+
49
+ def test_convert_token_and_id(self):
50
+ """Test ``_convert_token_to_id`` and ``_convert_id_to_token``."""
51
+ token = "<s>"
52
+ token_id = 1
53
+
54
+ self.assertEqual(self.get_tokenizer()._convert_token_to_id(token), token_id)
55
+ self.assertEqual(self.get_tokenizer()._convert_id_to_token(token_id), token)
56
+
57
+ def test_get_vocab(self):
58
+ vocab_keys = list(self.get_tokenizer().get_vocab().keys())
59
+
60
+ self.assertEqual(vocab_keys[0], "<unk>")
61
+ self.assertEqual(vocab_keys[1], "<s>")
62
+ self.assertEqual(vocab_keys[-1], "j")
63
+ self.assertEqual(len(vocab_keys), 2_000)
64
+
65
+ def test_vocab_size(self):
66
+ self.assertEqual(self.get_tokenizer().vocab_size, 2_000)
67
+
68
+ def test_full_tokenizer(self):
69
+ tokenizer = GPTSw3Tokenizer(SAMPLE_VOCAB)
70
+
71
+ tokens = tokenizer.tokenize("This is a test")
72
+ self.assertListEqual(tokens, ["▁This", "▁is", "▁a", "▁t", "est"])
73
+
74
+ self.assertListEqual(tokenizer.convert_tokens_to_ids(tokens), [465, 287, 265, 631, 842])
75
+
76
+ tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.")
77
+ # fmt: off
78
+ self.assertListEqual(
79
+ tokens,
80
+ ["▁I", "▁was", "▁bor", "n", "▁in", "▁", "<0x39>", "2", "0", "0", "0", ",", "▁and", "▁this", "▁is", "▁f", "al", "s", "<0xC3>", "<0xA9>", "."],
81
+ )
82
+ # fmt: on
83
+
84
+ ids = tokenizer.convert_tokens_to_ids(tokens)
85
+ self.assertListEqual(
86
+ ids,
87
+ [262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260],
88
+ )
89
+
90
+ back_tokens = tokenizer.convert_ids_to_tokens(ids)
91
+ # fmt: off
92
+ self.assertListEqual(
93
+ back_tokens,
94
+ ["▁I", "▁was", "▁bor", "n", "▁in", "▁", "<0x39>", "2", "0", "0", "0", ",", "▁and", "▁this", "▁is", "▁f", "al", "s", "<0xC3>", "<0xA9>", "."]
95
+ )
96
+ # fmt: on
97
+
98
+ def test_fast_encode_decode(self):
99
+ tokenizer = GPTSw3Tokenizer(SAMPLE_VOCAB)
100
+ texts = ["This is a test", "I was born in 92000, and this is falsé."]
101
+ expected_ids_list = [
102
+ [465, 287, 265, 631, 842],
103
+ [262, 272, 1525, 286, 271, 268, 60, 916, 633, 633, 633, 259, 266, 301, 287, 384, 367, 263, 198, 172, 260],
104
+ ]
105
+
106
+ # Test that encode_fast returns the same as tokenize + convert_tokens_to_ids
107
+ for text, expected_ids in zip(texts, expected_ids_list):
108
+ self.assertListEqual(tokenizer.encode_fast(text), expected_ids)
109
+
110
+ # Test that decode_fast returns the input text
111
+ for text, token_ids in zip(texts, expected_ids_list):
112
+ self.assertEqual(tokenizer.decode_fast(token_ids), text)
113
+
114
+ @slow
115
+ def test_tokenizer_integration(self):
116
+ sequences = [
117
+ "<|python|>def fibonacci(n)\n if n < 0:\n print('Incorrect input')",
118
+ "Hey there, how are you doing this fine day?",
119
+ "This is a text with a trailing spaces followed by a dot .",
120
+ "Häj sväjs lillebrör! =)",
121
+ "Det är inget fel på Mr. Cool",
122
+ ]
123
+
124
+ expected_encoding = {"input_ids": [[63423, 5, 6811, 14954, 282, 816, 3821, 63466, 63425, 63462, 18, 63978, 678, 301, 1320, 63423, 63455, 63458, 18, 63982, 4246, 3940, 1901, 47789, 5547, 18994], [19630, 1100, 63446, 1342, 633, 544, 4488, 593, 5102, 2416, 63495, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1652, 428, 268, 1936, 515, 268, 58593, 22413, 9106, 546, 268, 33213, 63979, 698, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [55130, 63450, 924, 63449, 2249, 4062, 1558, 318, 63504, 21498, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [509, 377, 2827, 2559, 332, 6575, 63443, 26801, 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, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [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], [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]]} # fmt: skip
125
+ self.tokenizer_integration_test_util(
126
+ expected_encoding=expected_encoding,
127
+ model_name="AI-Sweden-Models/gpt-sw3-126m",
128
+ sequences=sequences,
129
+ )
130
+
131
+ @require_jinja
132
+ def test_tokenization_for_chat(self):
133
+ tokenizer = GPTSw3Tokenizer(SAMPLE_VOCAB)
134
+ tokenizer.chat_template = (
135
+ "{{ eos_token }}{{ bos_token }}"
136
+ "{% for message in messages %}"
137
+ "{% if message['role'] == 'user' %}{{ 'User: ' + message['content']}}"
138
+ "{% else %}{{ 'Bot: ' + message['content']}}{% endif %}"
139
+ "{{ message['text'] }}{{ bos_token }}"
140
+ "{% endfor %}"
141
+ "Bot:"
142
+ )
143
+ # This is in English, but it's just here to make sure the chat control tokens are being added properly
144
+ test_chats = [
145
+ [{"role": "system", "content": "You are a helpful chatbot."}, {"role": "user", "content": "Hello!"}],
146
+ [
147
+ {"role": "system", "content": "You are a helpful chatbot."},
148
+ {"role": "user", "content": "Hello!"},
149
+ {"role": "assistant", "content": "Nice to meet you."},
150
+ ],
151
+ [{"role": "assistant", "content": "Nice to meet you."}, {"role": "user", "content": "Hello!"}],
152
+ ]
153
+ tokenized_chats = [tokenizer.apply_chat_template(test_chat) for test_chat in test_chats]
154
+ # fmt: off
155
+ expected_tokens = [
156
+ [2000, 1, 575, 541, 419, 530, 339, 265, 878, 708, 727, 275, 347, 541, 260, 1, 968, 263, 314, 419, 366, 354, 294, 360, 1, 575, 541, 419],
157
+ [2000, 1, 575, 541, 419, 530, 339, 265, 878, 708, 727, 275, 347, 541, 260, 1, 968, 263, 314, 419, 366, 354, 294, 360, 1, 575, 541, 419, 984, 429, 281, 264, 1261, 291, 260, 1, 575, 541, 419],
158
+ [2000, 1, 575, 541, 419, 984, 429, 281, 264, 1261, 291, 260, 1, 968, 263, 314, 419, 366, 354, 294, 360, 1, 575, 541, 419]
159
+ ]
160
+ # fmt: on
161
+ for tokenized_chat, expected_tokens in zip(tokenized_chats, expected_tokens):
162
+ self.assertListEqual(tokenized_chat, expected_tokens)
tasks/tasksmith-441eeab80047/tests/source/tests/models/gptj/__init__.py ADDED
File without changes
tasks/tasksmith-441eeab80047/tests/source/tests/models/gptj/test_modeling_flax_gptj.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
16
+ import unittest
17
+
18
+ import numpy as np
19
+
20
+ from transformers import GPT2Tokenizer, GPTJConfig, is_flax_available
21
+ from transformers.testing_utils import require_flax, tooslow
22
+
23
+ from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask
24
+
25
+
26
+ if is_flax_available():
27
+ import jax
28
+ import jax.numpy as jnp
29
+
30
+ from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel
31
+
32
+
33
+ class FlaxGPTJModelTester:
34
+ def __init__(
35
+ self,
36
+ parent,
37
+ batch_size=14,
38
+ seq_length=7,
39
+ is_training=True,
40
+ use_input_mask=True,
41
+ use_token_type_ids=False,
42
+ use_labels=True,
43
+ vocab_size=99,
44
+ hidden_size=32,
45
+ rotary_dim=4,
46
+ num_hidden_layers=2,
47
+ num_attention_heads=4,
48
+ intermediate_size=37,
49
+ hidden_act="gelu",
50
+ hidden_dropout_prob=0.1,
51
+ attention_probs_dropout_prob=0.1,
52
+ max_position_embeddings=512,
53
+ initializer_range=0.02,
54
+ ):
55
+ self.parent = parent
56
+ self.batch_size = batch_size
57
+ self.seq_length = seq_length
58
+ self.is_training = is_training
59
+ self.use_input_mask = use_input_mask
60
+ self.use_token_type_ids = use_token_type_ids
61
+ self.use_labels = use_labels
62
+ self.vocab_size = vocab_size
63
+ self.hidden_size = hidden_size
64
+ self.rotary_dim = rotary_dim
65
+ self.num_hidden_layers = num_hidden_layers
66
+ self.num_attention_heads = num_attention_heads
67
+ self.intermediate_size = intermediate_size
68
+ self.hidden_act = hidden_act
69
+ self.hidden_dropout_prob = hidden_dropout_prob
70
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
71
+ self.max_position_embeddings = max_position_embeddings
72
+ self.initializer_range = initializer_range
73
+ self.scope = None
74
+ self.bos_token_id = vocab_size - 1
75
+ self.eos_token_id = vocab_size - 1
76
+ self.pad_token_id = vocab_size - 1
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
+ config = GPTJConfig(
86
+ vocab_size=self.vocab_size,
87
+ n_embd=self.hidden_size,
88
+ n_layer=self.num_hidden_layers,
89
+ n_head=self.num_attention_heads,
90
+ n_positions=self.max_position_embeddings,
91
+ use_cache=False,
92
+ bos_token_id=self.bos_token_id,
93
+ eos_token_id=self.eos_token_id,
94
+ pad_token_id=self.pad_token_id,
95
+ rotary_dim=self.rotary_dim,
96
+ )
97
+
98
+ return (config, input_ids, input_mask)
99
+
100
+ def prepare_config_and_inputs_for_common(self):
101
+ config_and_inputs = self.prepare_config_and_inputs()
102
+ config, input_ids, attention_mask = config_and_inputs
103
+ inputs_dict = {"input_ids": input_ids, "attention_mask": attention_mask}
104
+ return config, inputs_dict
105
+
106
+ def check_use_cache_forward(self, model_class_name, config, input_ids, attention_mask):
107
+ max_decoder_length = 20
108
+ model = model_class_name(config)
109
+
110
+ past_key_values = model.init_cache(input_ids.shape[0], max_decoder_length)
111
+ attention_mask = jnp.ones((input_ids.shape[0], max_decoder_length), dtype="i4")
112
+
113
+ position_ids = jnp.broadcast_to(
114
+ jnp.arange(input_ids.shape[-1] - 1)[None, :], (input_ids.shape[0], input_ids.shape[-1] - 1)
115
+ )
116
+ outputs_cache = model(
117
+ input_ids[:, :-1],
118
+ attention_mask=attention_mask,
119
+ past_key_values=past_key_values,
120
+ position_ids=position_ids,
121
+ )
122
+
123
+ position_ids = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]], dtype="i4")
124
+ outputs_cache_next = model(
125
+ input_ids[:, -1:],
126
+ attention_mask=attention_mask,
127
+ past_key_values=outputs_cache.past_key_values,
128
+ position_ids=position_ids,
129
+ )
130
+
131
+ outputs = model(input_ids)
132
+
133
+ diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
134
+ self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}")
135
+
136
+ def check_use_cache_forward_with_attn_mask(self, model_class_name, config, input_ids, attention_mask):
137
+ max_decoder_length = 20
138
+ model = model_class_name(config)
139
+
140
+ attention_mask_cache = jnp.concatenate(
141
+ [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]))],
142
+ axis=-1,
143
+ )
144
+
145
+ past_key_values = model.init_cache(input_ids.shape[0], max_decoder_length)
146
+ position_ids = jnp.broadcast_to(
147
+ jnp.arange(input_ids.shape[-1] - 1)[None, :], (input_ids.shape[0], input_ids.shape[-1] - 1)
148
+ )
149
+
150
+ outputs_cache = model(
151
+ input_ids[:, :-1],
152
+ attention_mask=attention_mask_cache,
153
+ past_key_values=past_key_values,
154
+ position_ids=position_ids,
155
+ )
156
+ position_ids = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]], dtype="i4")
157
+ outputs_cache_next = model(
158
+ input_ids[:, -1:],
159
+ past_key_values=outputs_cache.past_key_values,
160
+ attention_mask=attention_mask_cache,
161
+ position_ids=position_ids,
162
+ )
163
+
164
+ outputs = model(input_ids, attention_mask=attention_mask)
165
+
166
+ diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
167
+ self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}")
168
+
169
+
170
+ @require_flax
171
+ class FlaxGPTJModelTest(FlaxModelTesterMixin, unittest.TestCase):
172
+ all_model_classes = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else ()
173
+
174
+ def setUp(self):
175
+ self.model_tester = FlaxGPTJModelTester(self)
176
+
177
+ def test_use_cache_forward(self):
178
+ for model_class_name in self.all_model_classes:
179
+ config, input_ids, attention_mask = self.model_tester.prepare_config_and_inputs()
180
+ self.model_tester.check_use_cache_forward(model_class_name, config, input_ids, attention_mask)
181
+
182
+ def test_use_cache_forward_with_attn_mask(self):
183
+ for model_class_name in self.all_model_classes:
184
+ config, input_ids, attention_mask = self.model_tester.prepare_config_and_inputs()
185
+ self.model_tester.check_use_cache_forward_with_attn_mask(
186
+ model_class_name, config, input_ids, attention_mask
187
+ )
188
+
189
+ @tooslow
190
+ def test_batch_generation(self):
191
+ tokenizer = GPT2Tokenizer.from_pretrained(
192
+ "openai-community/gpt2", pad_token="<|endoftext|>", padding_side="left"
193
+ )
194
+ inputs = tokenizer(["Hello this is a long string", "Hey"], return_tensors="np", padding=True, truncation=True)
195
+
196
+ model = FlaxGPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B")
197
+ model.do_sample = False
198
+ model.config.pad_token_id = model.config.eos_token_id
199
+
200
+ jit_generate = jax.jit(model.generate)
201
+
202
+ output_sequences = jit_generate(
203
+ inputs["input_ids"], attention_mask=inputs["attention_mask"], pad_token_id=tokenizer.pad_token_id
204
+ ).sequences
205
+
206
+ output_string = tokenizer.batch_decode(output_sequences, skip_special_tokens=True)
207
+
208
+ expected_string = [
209
+ "Hello this is a long string of text.\n\nI'm trying to get the text of the",
210
+ "Hey, I'm a little late to the party. I'm going to",
211
+ ]
212
+
213
+ self.assertListEqual(output_string, expected_string)
214
+
215
+ @tooslow
216
+ def test_model_from_pretrained(self):
217
+ for model_class_name in self.all_model_classes:
218
+ model = model_class_name.from_pretrained("EleutherAI/gpt-j-6B")
219
+ outputs = model(np.ones((1, 1)))
220
+ self.assertIsNotNone(outputs)
tasks/tasksmith-441eeab80047/tests/source/tests/models/gptj/test_modeling_gptj.py ADDED
@@ -0,0 +1,580 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 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 unittest
18
+
19
+ from transformers import GPTJConfig, is_torch_available
20
+ from transformers.testing_utils import (
21
+ require_torch,
22
+ slow,
23
+ tooslow,
24
+ torch_device,
25
+ )
26
+
27
+ from ...generation.test_utils import GenerationTesterMixin
28
+ from ...test_configuration_common import ConfigTester
29
+ from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
30
+ from ...test_pipeline_mixin import PipelineTesterMixin
31
+
32
+
33
+ if is_torch_available():
34
+ import torch
35
+
36
+ from transformers import (
37
+ AutoTokenizer,
38
+ GPTJForCausalLM,
39
+ GPTJForQuestionAnswering,
40
+ GPTJForSequenceClassification,
41
+ GPTJModel,
42
+ )
43
+
44
+
45
+ class GPTJModelTester:
46
+ def __init__(
47
+ self,
48
+ parent,
49
+ batch_size=14,
50
+ seq_length=7,
51
+ is_training=True,
52
+ use_token_type_ids=True,
53
+ use_input_mask=True,
54
+ use_labels=True,
55
+ use_mc_token_ids=True,
56
+ vocab_size=99,
57
+ hidden_size=32,
58
+ rotary_dim=4,
59
+ num_hidden_layers=2,
60
+ num_attention_heads=4,
61
+ intermediate_size=37,
62
+ hidden_act="gelu",
63
+ hidden_dropout_prob=0.0,
64
+ attention_probs_dropout_prob=0.0,
65
+ max_position_embeddings=512,
66
+ type_vocab_size=16,
67
+ type_sequence_label_size=2,
68
+ initializer_range=0.02,
69
+ num_labels=3,
70
+ num_choices=4,
71
+ ):
72
+ self.parent = parent
73
+ self.batch_size = batch_size
74
+ self.seq_length = seq_length
75
+ self.is_training = is_training
76
+ self.use_token_type_ids = use_token_type_ids
77
+ self.use_input_mask = use_input_mask
78
+ self.use_labels = use_labels
79
+ self.use_mc_token_ids = use_mc_token_ids
80
+ self.vocab_size = vocab_size
81
+ self.hidden_size = hidden_size
82
+ self.rotary_dim = rotary_dim
83
+ self.num_hidden_layers = num_hidden_layers
84
+ self.num_attention_heads = num_attention_heads
85
+ self.intermediate_size = intermediate_size
86
+ self.hidden_act = hidden_act
87
+ self.hidden_dropout_prob = hidden_dropout_prob
88
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
89
+ self.max_position_embeddings = max_position_embeddings
90
+ self.type_vocab_size = type_vocab_size
91
+ self.type_sequence_label_size = type_sequence_label_size
92
+ self.initializer_range = initializer_range
93
+ self.num_labels = num_labels
94
+ self.num_choices = num_choices
95
+ self.scope = None
96
+ self.bos_token_id = vocab_size - 1
97
+ self.eos_token_id = vocab_size - 1
98
+ self.pad_token_id = vocab_size - 1
99
+
100
+ def get_large_model_config(self):
101
+ return GPTJConfig.from_pretrained("EleutherAI/gpt-j-6B")
102
+
103
+ def prepare_config_and_inputs(self):
104
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
105
+
106
+ input_mask = None
107
+ if self.use_input_mask:
108
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
109
+
110
+ token_type_ids = None
111
+ if self.use_token_type_ids:
112
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
113
+
114
+ mc_token_ids = None
115
+ if self.use_mc_token_ids:
116
+ mc_token_ids = ids_tensor([self.batch_size, self.num_choices], self.seq_length)
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
+ head_mask = ids_tensor([self.num_hidden_layers, self.num_attention_heads], 2)
129
+
130
+ return (
131
+ config,
132
+ input_ids,
133
+ input_mask,
134
+ head_mask,
135
+ token_type_ids,
136
+ mc_token_ids,
137
+ sequence_labels,
138
+ token_labels,
139
+ choice_labels,
140
+ )
141
+
142
+ def get_config(self):
143
+ return GPTJConfig(
144
+ vocab_size=self.vocab_size,
145
+ n_embd=self.hidden_size,
146
+ n_layer=self.num_hidden_layers,
147
+ n_head=self.num_attention_heads,
148
+ intermediate_size=self.intermediate_size,
149
+ hidden_act=self.hidden_act,
150
+ hidden_dropout_prob=self.hidden_dropout_prob,
151
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
152
+ n_positions=self.max_position_embeddings,
153
+ type_vocab_size=self.type_vocab_size,
154
+ initializer_range=self.initializer_range,
155
+ use_cache=True,
156
+ bos_token_id=self.bos_token_id,
157
+ eos_token_id=self.eos_token_id,
158
+ pad_token_id=self.pad_token_id,
159
+ rotary_dim=self.rotary_dim,
160
+ )
161
+
162
+ def get_pipeline_config(self):
163
+ config = self.get_config()
164
+ config.vocab_size = 300
165
+ return config
166
+
167
+ def create_and_check_gptj_model(self, config, input_ids, input_mask, head_mask, token_type_ids, *args):
168
+ model = GPTJModel(config=config)
169
+ model.to(torch_device)
170
+ model.eval()
171
+
172
+ result = model(input_ids, token_type_ids=token_type_ids, head_mask=head_mask)
173
+ result = model(input_ids, token_type_ids=token_type_ids)
174
+ result = model(input_ids)
175
+
176
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
177
+ self.parent.assertEqual(len(result.past_key_values), config.n_layer)
178
+
179
+ def create_and_check_gptj_model_past(self, config, input_ids, input_mask, head_mask, token_type_ids, *args):
180
+ model = GPTJModel(config=config)
181
+ model.to(torch_device)
182
+ model.eval()
183
+
184
+ # first forward pass
185
+ outputs = model(input_ids, token_type_ids=token_type_ids, use_cache=True)
186
+ outputs_use_cache_conf = model(input_ids, token_type_ids=token_type_ids)
187
+ outputs_no_past = model(input_ids, token_type_ids=token_type_ids, use_cache=False)
188
+
189
+ self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))
190
+ self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)
191
+
192
+ output, past = outputs.to_tuple()
193
+
194
+ # create hypothetical next token and extent to next_input_ids
195
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
196
+ next_token_types = ids_tensor([self.batch_size, 1], self.type_vocab_size)
197
+
198
+ # append to next input_ids and token_type_ids
199
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
200
+ next_token_type_ids = torch.cat([token_type_ids, next_token_types], dim=-1)
201
+
202
+ output_from_no_past = model(next_input_ids, token_type_ids=next_token_type_ids)["last_hidden_state"]
203
+ output_from_past = model(next_tokens, token_type_ids=next_token_types, past_key_values=past)[
204
+ "last_hidden_state"
205
+ ]
206
+
207
+ # select random slice
208
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
209
+ output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach()
210
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
211
+
212
+ # test that outputs are equal for slice
213
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
214
+
215
+ def create_and_check_gptj_model_attention_mask_past(
216
+ self, config, input_ids, input_mask, head_mask, token_type_ids, *args
217
+ ):
218
+ model = GPTJModel(config=config)
219
+ model.to(torch_device)
220
+ model.eval()
221
+
222
+ # create attention mask
223
+ attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
224
+ half_seq_length = self.seq_length // 2
225
+ attn_mask[:, half_seq_length:] = 0
226
+
227
+ # first forward pass
228
+ output, past = model(input_ids, attention_mask=attn_mask).to_tuple()
229
+
230
+ # create hypothetical next token and extent to next_input_ids
231
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
232
+
233
+ # change a random masked slice from input_ids
234
+ random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1
235
+ random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1)
236
+ input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens
237
+
238
+ # append to next input_ids and attn_mask
239
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
240
+ attn_mask = torch.cat(
241
+ [attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)],
242
+ dim=1,
243
+ )
244
+
245
+ # get two different outputs
246
+ output_from_no_past = model(next_input_ids, attention_mask=attn_mask)["last_hidden_state"]
247
+ output_from_past = model(next_tokens, past_key_values=past, attention_mask=attn_mask)["last_hidden_state"]
248
+
249
+ # select random slice
250
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
251
+ output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach()
252
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
253
+
254
+ # test that outputs are equal for slice
255
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
256
+
257
+ def create_and_check_gptj_model_past_large_inputs(
258
+ self, config, input_ids, input_mask, head_mask, token_type_ids, *args
259
+ ):
260
+ model = GPTJModel(config=config)
261
+ model.to(torch_device)
262
+ model.eval()
263
+
264
+ # first forward pass
265
+ outputs = model(input_ids, token_type_ids=token_type_ids, attention_mask=input_mask, use_cache=True)
266
+
267
+ output, past = outputs.to_tuple()
268
+
269
+ # create hypothetical next token and extent to next_input_ids
270
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
271
+ next_token_types = ids_tensor([self.batch_size, 3], self.type_vocab_size)
272
+ next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
273
+
274
+ # append to next input_ids and token_type_ids
275
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
276
+ next_token_type_ids = torch.cat([token_type_ids, next_token_types], dim=-1)
277
+ next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
278
+
279
+ output_from_no_past = model(
280
+ next_input_ids, token_type_ids=next_token_type_ids, attention_mask=next_attention_mask
281
+ )["last_hidden_state"]
282
+ output_from_past = model(
283
+ next_tokens, token_type_ids=next_token_types, attention_mask=next_attention_mask, past_key_values=past
284
+ )["last_hidden_state"]
285
+ self.parent.assertTrue(output_from_past.shape[1] == next_tokens.shape[1])
286
+
287
+ # select random slice
288
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
289
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
290
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
291
+
292
+ # test that outputs are equal for slice
293
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
294
+
295
+ def create_and_check_lm_head_model(self, config, input_ids, input_mask, head_mask, token_type_ids, *args):
296
+ model = GPTJForCausalLM(config)
297
+ model.to(torch_device)
298
+ model.eval()
299
+
300
+ result = model(input_ids, token_type_ids=token_type_ids, labels=input_ids)
301
+ self.parent.assertEqual(result.loss.shape, ())
302
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
303
+
304
+ def create_and_check_forward_and_backwards(
305
+ self, config, input_ids, input_mask, head_mask, token_type_ids, *args, gradient_checkpointing=False
306
+ ):
307
+ model = GPTJForCausalLM(config)
308
+ if gradient_checkpointing:
309
+ model.gradient_checkpointing_enable()
310
+ model.to(torch_device)
311
+
312
+ result = model(input_ids, token_type_ids=token_type_ids, labels=input_ids)
313
+ self.parent.assertEqual(result.loss.shape, ())
314
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
315
+ result.loss.backward()
316
+
317
+ def prepare_config_and_inputs_for_common(self):
318
+ config_and_inputs = self.prepare_config_and_inputs()
319
+
320
+ (
321
+ config,
322
+ input_ids,
323
+ input_mask,
324
+ head_mask,
325
+ token_type_ids,
326
+ mc_token_ids,
327
+ sequence_labels,
328
+ token_labels,
329
+ choice_labels,
330
+ ) = config_and_inputs
331
+
332
+ inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "head_mask": head_mask}
333
+
334
+ return config, inputs_dict
335
+
336
+
337
+ @require_torch
338
+ class GPTJModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
339
+ all_model_classes = (
340
+ (GPTJModel, GPTJForCausalLM, GPTJForSequenceClassification, GPTJForQuestionAnswering)
341
+ if is_torch_available()
342
+ else ()
343
+ )
344
+ pipeline_model_mapping = (
345
+ {
346
+ "feature-extraction": GPTJModel,
347
+ "question-answering": GPTJForQuestionAnswering,
348
+ "text-classification": GPTJForSequenceClassification,
349
+ "text-generation": GPTJForCausalLM,
350
+ "zero-shot": GPTJForSequenceClassification,
351
+ }
352
+ if is_torch_available()
353
+ else {}
354
+ )
355
+ fx_compatible = True
356
+ test_pruning = False
357
+ test_missing_keys = False
358
+ test_model_parallel = False
359
+ test_head_masking = False
360
+
361
+ def test_torch_fx(self):
362
+ super().test_torch_fx()
363
+
364
+ def test_torch_fx_output_loss(self):
365
+ super().test_torch_fx_output_loss()
366
+
367
+ # TODO: Fix the failed tests
368
+ def is_pipeline_test_to_skip(
369
+ self,
370
+ pipeline_test_case_name,
371
+ config_class,
372
+ model_architecture,
373
+ tokenizer_name,
374
+ image_processor_name,
375
+ feature_extractor_name,
376
+ processor_name,
377
+ ):
378
+ if (
379
+ pipeline_test_case_name == "QAPipelineTests"
380
+ and tokenizer_name is not None
381
+ and not tokenizer_name.endswith("Fast")
382
+ ):
383
+ # `QAPipelineTests` fails for a few models when the slower tokenizer are used.
384
+ # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
385
+ # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
386
+ return True
387
+
388
+ return False
389
+
390
+ # special case for DoubleHeads model
391
+ def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
392
+ inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
393
+ return inputs_dict
394
+
395
+ def setUp(self):
396
+ self.model_tester = GPTJModelTester(self)
397
+ self.config_tester = ConfigTester(self, config_class=GPTJConfig, n_embd=37)
398
+
399
+ def test_config(self):
400
+ self.config_tester.run_common_tests()
401
+
402
+ def test_gptj_model(self):
403
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
404
+ self.model_tester.create_and_check_gptj_model(*config_and_inputs)
405
+
406
+ def test_gptj_model_past(self):
407
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
408
+ self.model_tester.create_and_check_gptj_model_past(*config_and_inputs)
409
+
410
+ def test_gptj_model_att_mask_past(self):
411
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
412
+ self.model_tester.create_and_check_gptj_model_attention_mask_past(*config_and_inputs)
413
+
414
+ def test_gptj_model_past_large_inputs(self):
415
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
416
+ self.model_tester.create_and_check_gptj_model_past_large_inputs(*config_and_inputs)
417
+
418
+ def test_gptj_lm_head_model(self):
419
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
420
+ self.model_tester.create_and_check_lm_head_model(*config_and_inputs)
421
+
422
+ def test_gptj_gradient_checkpointing(self):
423
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
424
+ self.model_tester.create_and_check_forward_and_backwards(*config_and_inputs, gradient_checkpointing=True)
425
+
426
+ @tooslow
427
+ def test_batch_generation(self):
428
+ # Marked as @tooslow due to GPU OOM
429
+ model = GPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B", revision="float16", torch_dtype=torch.float16)
430
+ model.to(torch_device)
431
+ tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-j-6B", revision="float16")
432
+
433
+ tokenizer.padding_side = "left"
434
+
435
+ # Define PAD Token = EOS Token = 50256
436
+ tokenizer.pad_token = tokenizer.eos_token
437
+ model.config.pad_token_id = model.config.eos_token_id
438
+
439
+ # use different length sentences to test batching
440
+ sentences = [
441
+ "Hello, my dog is a little",
442
+ "Today, I",
443
+ ]
444
+
445
+ inputs = tokenizer(sentences, return_tensors="pt", padding=True)
446
+ input_ids = inputs["input_ids"].to(torch_device)
447
+ token_type_ids = torch.cat(
448
+ [
449
+ input_ids.new_full((input_ids.shape[0], input_ids.shape[1] - 1), 0),
450
+ input_ids.new_full((input_ids.shape[0], 1), 500),
451
+ ],
452
+ dim=-1,
453
+ )
454
+
455
+ outputs = model.generate(
456
+ input_ids=input_ids,
457
+ attention_mask=inputs["attention_mask"].to(torch_device),
458
+ )
459
+
460
+ outputs_tt = model.generate(
461
+ input_ids=input_ids,
462
+ attention_mask=inputs["attention_mask"].to(torch_device),
463
+ token_type_ids=token_type_ids,
464
+ )
465
+
466
+ inputs_non_padded = tokenizer(sentences[0], return_tensors="pt").input_ids.to(torch_device)
467
+ output_non_padded = model.generate(input_ids=inputs_non_padded)
468
+
469
+ num_paddings = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item()
470
+ inputs_padded = tokenizer(sentences[1], return_tensors="pt").input_ids.to(torch_device)
471
+ output_padded = model.generate(input_ids=inputs_padded, max_length=model.config.max_length - num_paddings)
472
+
473
+ batch_out_sentence = tokenizer.batch_decode(outputs, skip_special_tokens=True)
474
+ batch_out_sentence_tt = tokenizer.batch_decode(outputs_tt, skip_special_tokens=True)
475
+ non_padded_sentence = tokenizer.decode(output_non_padded[0], skip_special_tokens=True)
476
+ padded_sentence = tokenizer.decode(output_padded[0], skip_special_tokens=True)
477
+
478
+ expected_output_sentence = [
479
+ "Hello, my dog is a little over a year old and has been diagnosed with a heart murmur",
480
+ "Today, I’m going to talk about the most important thing in the",
481
+ ]
482
+ self.assertListEqual(expected_output_sentence, batch_out_sentence)
483
+ self.assertTrue(batch_out_sentence_tt != batch_out_sentence) # token_type_ids should change output
484
+ self.assertListEqual(expected_output_sentence, [non_padded_sentence, padded_sentence])
485
+
486
+ @slow
487
+ def test_model_from_pretrained(self):
488
+ model_name = "EleutherAI/gpt-j-6B"
489
+ model = GPTJModel.from_pretrained(model_name, revision="float16", torch_dtype=torch.float16)
490
+ self.assertIsNotNone(model)
491
+
492
+
493
+ @require_torch
494
+ class GPTJModelLanguageGenerationTest(unittest.TestCase):
495
+ @tooslow
496
+ def test_lm_generate_gptj(self):
497
+ # Marked as @tooslow due to GPU OOM
498
+ for checkpointing in [True, False]:
499
+ model = GPTJForCausalLM.from_pretrained(
500
+ "EleutherAI/gpt-j-6B", revision="float16", torch_dtype=torch.float16
501
+ )
502
+ if checkpointing:
503
+ model.gradient_checkpointing_enable()
504
+ else:
505
+ model.gradient_checkpointing_disable()
506
+ model.to(torch_device)
507
+ input_ids = torch.tensor([[464, 3290]], dtype=torch.long, device=torch_device) # The dog
508
+ # The dog is a man's best friend. It is a loyal companion, and it is a friend
509
+ expected_output_ids = [464, 3290, 318, 257, 582, 338, 1266, 1545, 13, 632, 318, 257, 9112, 15185, 11, 290, 340, 318, 257, 1545] # fmt: skip
510
+ output_ids = model.generate(input_ids, do_sample=False)
511
+ self.assertListEqual(output_ids[0].tolist(), expected_output_ids)
512
+
513
+ @tooslow
514
+ def test_gptj_sample(self):
515
+ # Marked as @tooslow due to GPU OOM (issue #13676)
516
+ tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-j-6B", revision="float16")
517
+ model = GPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B", revision="float16", torch_dtype=torch.float16)
518
+ model.to(torch_device)
519
+
520
+ torch.manual_seed(0)
521
+ tokenized = tokenizer("Today is a nice day and", return_tensors="pt", return_token_type_ids=True)
522
+ input_ids = tokenized.input_ids.to(torch_device)
523
+ output_ids = model.generate(input_ids, do_sample=True)
524
+ output_str = tokenizer.decode(output_ids[0], skip_special_tokens=True)
525
+
526
+ token_type_ids = tokenized.token_type_ids.to(torch_device)
527
+ output_seq = model.generate(input_ids=input_ids, do_sample=True, num_return_sequences=5)
528
+ output_seq_tt = model.generate(
529
+ input_ids=input_ids, token_type_ids=token_type_ids, do_sample=True, num_return_sequences=5
530
+ )
531
+ output_seq_strs = tokenizer.batch_decode(output_seq, skip_special_tokens=True)
532
+ output_seq_tt_strs = tokenizer.batch_decode(output_seq_tt, skip_special_tokens=True)
533
+
534
+ if torch_device != "cpu":
535
+ # currently this expect value is only for `cuda`
536
+ EXPECTED_OUTPUT_STR = (
537
+ "Today is a nice day and I've already been enjoying it. I walked to work with my wife"
538
+ )
539
+ else:
540
+ EXPECTED_OUTPUT_STR = "Today is a nice day and one of those days that feels a bit more alive. I am ready"
541
+
542
+ self.assertEqual(output_str, EXPECTED_OUTPUT_STR)
543
+ self.assertTrue(
544
+ all(output_seq_strs[idx] != output_seq_tt_strs[idx] for idx in range(len(output_seq_tt_strs)))
545
+ ) # token_type_ids should change output
546
+
547
+ @tooslow
548
+ def test_contrastive_search_gptj(self):
549
+ article = (
550
+ "DeepMind Technologies is a British artificial intelligence subsidiary of Alphabet Inc. and "
551
+ "research laboratory founded in 2010. DeepMind was acquired by Google in 2014. The company is based"
552
+ )
553
+
554
+ tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-j-6B")
555
+ model = GPTJForCausalLM.from_pretrained(
556
+ "EleutherAI/gpt-j-6B", revision="float16", torch_dtype=torch.float16
557
+ ).to(torch_device)
558
+ input_ids = tokenizer(article, return_tensors="pt").input_ids.to(torch_device)
559
+
560
+ outputs = model.generate(input_ids, penalty_alpha=0.6, top_k=4, max_length=256)
561
+ generated_text = tokenizer.batch_decode(outputs, skip_special_tokens=True)
562
+
563
+ self.assertListEqual(
564
+ generated_text,
565
+ [
566
+ "DeepMind Technologies is a British artificial intelligence subsidiary of Alphabet Inc. and research "
567
+ "laboratory founded in 2010. DeepMind was acquired by Google in 2014. The company is based in London, "
568
+ "United Kingdom with offices in Mountain View, San Francisco, New York City, Paris, Tokyo, Seoul, "
569
+ "Beijing, Singapore, Tel Aviv, Dublin, Sydney, and Melbourne.[1]\n\nContents\n\nIn 2010, Google's "
570
+ "parent company, Alphabet, announced a $500 million investment in DeepMind, with the aim of creating "
571
+ "a company that would apply deep learning to problems in healthcare, energy, transportation, and "
572
+ "other areas.[2]\n\nOn April 23, 2014, Google announced that it had acquired DeepMind for $400 "
573
+ "million in cash and stock.[3] The acquisition was seen as a way for Google to enter the "
574
+ "fast-growing field of artificial intelligence (AI), which it had so far avoided due to concerns "
575
+ 'about ethical and social implications.[4] Google co-founder Sergey Brin said that he was "thrilled" '
576
+ 'to have acquired DeepMind, and that it would "help us push the boundaries of AI even further."'
577
+ "[5]\n\nDeepMind's founders, Demis Hassabis and Mustafa Suleyman, were joined by a number of Google "
578
+ "employees"
579
+ ],
580
+ )