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

Stage Harbor release files 51001-51500

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/openai/test_tokenization_openai.py +145 -0
  2. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/opt/__init__.py +0 -0
  3. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/opt/test_modeling_flax_opt.py +406 -0
  4. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/opt/test_modeling_opt.py +584 -0
  5. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/opt/test_modeling_tf_opt.py +406 -0
  6. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/owlv2/__init__.py +0 -0
  7. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/owlv2/test_image_processing_owlv2.py +174 -0
  8. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/owlv2/test_modeling_owlv2.py +1052 -0
  9. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/owlvit/__init__.py +0 -0
  10. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/owlvit/test_image_processing_owlvit.py +121 -0
  11. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/owlvit/test_modeling_owlvit.py +1041 -0
  12. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/owlvit/test_processor_owlvit.py +246 -0
  13. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/paligemma/__init__.py +0 -0
  14. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/paligemma/test_modeling_paligemma.py +630 -0
  15. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/paligemma/test_processor_paligemma.py +93 -0
  16. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/patchtsmixer/__init__.py +0 -0
  17. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/patchtsmixer/test_modeling_patchtsmixer.py +1118 -0
  18. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/patchtst/__init__.py +0 -0
  19. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/patchtst/test_modeling_patchtst.py +388 -0
  20. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pegasus/__init__.py +0 -0
  21. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pegasus/test_modeling_flax_pegasus.py +338 -0
  22. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pegasus/test_modeling_pegasus.py +589 -0
  23. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pegasus/test_modeling_tf_pegasus.py +250 -0
  24. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pegasus/test_tokenization_pegasus.py +213 -0
  25. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pegasus_x/__init__.py +0 -0
  26. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pegasus_x/test_modeling_pegasus_x.py +877 -0
  27. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/perceiver/__init__.py +0 -0
  28. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/perceiver/test_modeling_perceiver.py +1053 -0
  29. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/perceiver/test_tokenization_perceiver.py +295 -0
  30. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/persimmon/__init__.py +0 -0
  31. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/persimmon/test_modeling_persimmon.py +519 -0
  32. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/phi/__init__.py +0 -0
  33. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/phi/test_modeling_phi.py +517 -0
  34. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/phi3/__init__.py +0 -0
  35. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/phi3/test_modeling_phi3.py +707 -0
  36. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/phimoe/__init__.py +0 -0
  37. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/phimoe/test_modeling_phimoe.py +566 -0
  38. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/phobert/__init__.py +0 -0
  39. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/phobert/test_tokenization_phobert.py +67 -0
  40. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pix2struct/__init__.py +0 -0
  41. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pix2struct/test_image_processing_pix2struct.py +350 -0
  42. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pix2struct/test_modeling_pix2struct.py +895 -0
  43. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pix2struct/test_processor_pix2struct.py +329 -0
  44. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pixtral/__init__.py +0 -0
  45. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pixtral/test_image_processing_pixtral.py +307 -0
  46. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pixtral/test_modeling_pixtral.py +254 -0
  47. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pixtral/test_processor_pixtral.py +276 -0
  48. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/plbart/__init__.py +0 -0
  49. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/plbart/test_modeling_plbart.py +682 -0
  50. tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/plbart/test_tokenization_plbart.py +376 -0
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/openai/test_tokenization_openai.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 The Google AI Language Team Authors.
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 OpenAIGPTTokenizer, OpenAIGPTTokenizerFast
22
+ from transformers.models.openai.tokenization_openai import VOCAB_FILES_NAMES
23
+ from transformers.testing_utils import require_ftfy, require_spacy, require_tokenizers
24
+
25
+ from ...test_tokenization_common import TokenizerTesterMixin
26
+
27
+
28
+ @require_tokenizers
29
+ class OpenAIGPTTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
30
+ from_pretrained_id = "openai-community/openai-gpt"
31
+ """Tests OpenAIGPTTokenizer that uses BERT BasicTokenizer."""
32
+
33
+ tokenizer_class = OpenAIGPTTokenizer
34
+ rust_tokenizer_class = OpenAIGPTTokenizerFast
35
+ test_rust_tokenizer = True
36
+ test_seq2seq = False
37
+
38
+ def setUp(self):
39
+ super().setUp()
40
+
41
+ # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
42
+ vocab = [
43
+ "l",
44
+ "o",
45
+ "w",
46
+ "e",
47
+ "r",
48
+ "s",
49
+ "t",
50
+ "i",
51
+ "d",
52
+ "n",
53
+ "w</w>",
54
+ "r</w>",
55
+ "t</w>",
56
+ "lo",
57
+ "low",
58
+ "er</w>",
59
+ "low</w>",
60
+ "lowest</w>",
61
+ "newer</w>",
62
+ "wider</w>",
63
+ "<unk>",
64
+ ]
65
+ vocab_tokens = dict(zip(vocab, range(len(vocab))))
66
+ merges = ["#version: 0.2", "l o", "lo w", "e r</w>", ""]
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") as fp:
71
+ fp.write(json.dumps(vocab_tokens))
72
+ with open(self.merges_file, "w") as fp:
73
+ fp.write("\n".join(merges))
74
+
75
+ def get_input_output_texts(self, tokenizer):
76
+ return "lower newer", "lower newer"
77
+
78
+ def test_full_tokenizer(self):
79
+ tokenizer = OpenAIGPTTokenizer(self.vocab_file, self.merges_file)
80
+
81
+ text = "lower"
82
+ bpe_tokens = ["low", "er</w>"]
83
+ tokens = tokenizer.tokenize(text)
84
+ self.assertListEqual(tokens, bpe_tokens)
85
+
86
+ input_tokens = tokens + ["<unk>"]
87
+ input_bpe_tokens = [14, 15, 20]
88
+ self.assertListEqual(tokenizer.convert_tokens_to_ids(input_tokens), input_bpe_tokens)
89
+
90
+ def test_padding(self, max_length=15):
91
+ for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
92
+ with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
93
+ tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
94
+
95
+ # Simple input
96
+ s = "This is a simple input"
97
+ s2 = ["This is a simple input 1", "This is a simple input 2"]
98
+ p = ("This is a simple input", "This is a pair")
99
+ p2 = [
100
+ ("This is a simple input 1", "This is a simple input 2"),
101
+ ("This is a simple pair 1", "This is a simple pair 2"),
102
+ ]
103
+
104
+ # Simple input tests
105
+ self.assertRaises(ValueError, tokenizer_r.encode, s, max_length=max_length, padding="max_length")
106
+
107
+ # Simple input
108
+ self.assertRaises(ValueError, tokenizer_r.encode_plus, s, max_length=max_length, padding="max_length")
109
+
110
+ # Simple input
111
+ self.assertRaises(
112
+ ValueError,
113
+ tokenizer_r.batch_encode_plus,
114
+ s2,
115
+ max_length=max_length,
116
+ padding="max_length",
117
+ )
118
+
119
+ # Pair input
120
+ self.assertRaises(ValueError, tokenizer_r.encode, p, max_length=max_length, padding="max_length")
121
+
122
+ # Pair input
123
+ self.assertRaises(ValueError, tokenizer_r.encode_plus, p, max_length=max_length, padding="max_length")
124
+
125
+ # Pair input
126
+ self.assertRaises(
127
+ ValueError,
128
+ tokenizer_r.batch_encode_plus,
129
+ p2,
130
+ max_length=max_length,
131
+ padding="max_length",
132
+ )
133
+
134
+ @unittest.skip(reason="tokenizer has no padding token")
135
+ def test_padding_different_model_input_name(self):
136
+ pass
137
+
138
+
139
+ @require_ftfy
140
+ @require_spacy
141
+ @require_tokenizers
142
+ class OpenAIGPTTokenizationTestWithSpacy(OpenAIGPTTokenizationTest):
143
+ """Tests OpenAIGPTTokenizer that uses SpaCy and ftfy."""
144
+
145
+ pass
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/opt/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/opt/test_modeling_flax_opt.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 unittest
15
+
16
+ import numpy as np
17
+ import timeout_decorator # noqa
18
+
19
+ from transformers import OPTConfig, is_flax_available
20
+ from transformers.testing_utils import require_flax, require_sentencepiece, slow
21
+
22
+ from ...generation.test_flax_utils import FlaxGenerationTesterMixin
23
+ from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor
24
+
25
+
26
+ if is_flax_available():
27
+ import os
28
+
29
+ # The slow tests are often failing with OOM error on GPU
30
+ # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
31
+ # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
32
+ os.environ["XLA_PYTHON_CLIENT_ALLOCATOR"] = "platform"
33
+
34
+ import jax
35
+ import jax.numpy as jnp
36
+
37
+ from transformers import FlaxOPTForCausalLM, FlaxOPTModel, GPT2Tokenizer
38
+
39
+
40
+ def prepare_opt_inputs_dict(config, input_ids, attention_mask=None, head_mask=None):
41
+ if attention_mask is None:
42
+ attention_mask = np.where(input_ids != config.pad_token_id, 1, 0)
43
+ return {
44
+ "input_ids": input_ids,
45
+ "attention_mask": attention_mask,
46
+ }
47
+
48
+
49
+ @require_flax
50
+ class FlaxOPTModelTester:
51
+ def __init__(
52
+ self,
53
+ parent,
54
+ batch_size=13,
55
+ seq_length=7,
56
+ is_training=True,
57
+ use_labels=False,
58
+ vocab_size=99,
59
+ hidden_size=16,
60
+ num_hidden_layers=2,
61
+ num_attention_heads=4,
62
+ intermediate_size=4,
63
+ hidden_act="gelu",
64
+ hidden_dropout_prob=0.1,
65
+ attention_probs_dropout_prob=0.1,
66
+ max_position_embeddings=20,
67
+ eos_token_id=2,
68
+ pad_token_id=1,
69
+ bos_token_id=0,
70
+ embed_dim=16,
71
+ word_embed_proj_dim=16,
72
+ initializer_range=0.02,
73
+ attn_implemetation="eager",
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_labels = use_labels
80
+ self.vocab_size = vocab_size
81
+ self.hidden_size = hidden_size
82
+ self.num_hidden_layers = num_hidden_layers
83
+ self.num_attention_heads = num_attention_heads
84
+ self.intermediate_size = intermediate_size
85
+ self.hidden_act = hidden_act
86
+ self.hidden_dropout_prob = hidden_dropout_prob
87
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
88
+ self.max_position_embeddings = max_position_embeddings
89
+ self.eos_token_id = eos_token_id
90
+ self.pad_token_id = pad_token_id
91
+ self.bos_token_id = bos_token_id
92
+ self.embed_dim = embed_dim
93
+ self.word_embed_proj_dim = word_embed_proj_dim
94
+ self.initializer_range = initializer_range
95
+ self.is_encoder_decoder = False
96
+ self.attn_implementation = attn_implemetation
97
+
98
+ def prepare_config_and_inputs(self):
99
+ input_ids = np.clip(ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size), 3, self.vocab_size)
100
+ input_ids = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1), dtype=np.int64)), -1)
101
+
102
+ config = OPTConfig(
103
+ vocab_size=self.vocab_size,
104
+ hidden_size=self.hidden_size,
105
+ num_hidden_layers=self.num_hidden_layers,
106
+ num_attention_heads=self.num_attention_heads,
107
+ ffn_dim=self.intermediate_size,
108
+ dropout=self.hidden_dropout_prob,
109
+ attention_dropout=self.attention_probs_dropout_prob,
110
+ max_position_embeddings=self.max_position_embeddings,
111
+ eos_token_id=self.eos_token_id,
112
+ bos_token_id=self.bos_token_id,
113
+ pad_token_id=self.pad_token_id,
114
+ embed_dim=self.embed_dim,
115
+ is_encoder_decoder=False,
116
+ word_embed_proj_dim=self.word_embed_proj_dim,
117
+ initializer_range=self.initializer_range,
118
+ use_cache=False,
119
+ attn_implementation=self.attn_implementation,
120
+ )
121
+ inputs_dict = prepare_opt_inputs_dict(config, input_ids)
122
+ return config, inputs_dict
123
+
124
+ def prepare_config_and_inputs_for_common(self):
125
+ config, inputs_dict = self.prepare_config_and_inputs()
126
+ return config, inputs_dict
127
+
128
+ def check_use_cache_forward(self, model_class_name, config, inputs_dict):
129
+ max_length = 20
130
+ model = model_class_name(config)
131
+
132
+ input_ids = inputs_dict["input_ids"]
133
+ attention_mask = inputs_dict["attention_mask"]
134
+
135
+ past_key_values = model.init_cache(input_ids.shape[0], max_length)
136
+ attention_mask = jnp.ones((input_ids.shape[0], max_length), dtype="i4")
137
+
138
+ position_ids = jnp.broadcast_to(
139
+ jnp.arange(input_ids.shape[-1] - 1)[None, :],
140
+ (input_ids.shape[0], input_ids.shape[-1] - 1),
141
+ )
142
+ outputs_cache = model(
143
+ input_ids[:, :-1],
144
+ attention_mask=attention_mask,
145
+ past_key_values=past_key_values,
146
+ position_ids=position_ids,
147
+ )
148
+
149
+ position_ids = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]], dtype="i4")
150
+ outputs_cache_next = model(
151
+ input_ids[:, -1:],
152
+ attention_mask=attention_mask,
153
+ past_key_values=outputs_cache.past_key_values,
154
+ position_ids=position_ids,
155
+ )
156
+
157
+ outputs = model(input_ids)
158
+
159
+ diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
160
+ self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}")
161
+
162
+ def check_use_cache_forward_with_attn_mask(self, model_class_name, config, inputs_dict):
163
+ max_length = 20
164
+ model = model_class_name(config)
165
+
166
+ input_ids, attention_mask = (
167
+ inputs_dict["input_ids"],
168
+ inputs_dict["attention_mask"],
169
+ )
170
+
171
+ attention_mask_cache = jnp.concatenate(
172
+ [
173
+ attention_mask,
174
+ jnp.zeros((attention_mask.shape[0], max_length - attention_mask.shape[1])),
175
+ ],
176
+ axis=-1,
177
+ )
178
+
179
+ past_key_values = model.init_cache(input_ids.shape[0], max_length)
180
+ position_ids = jnp.broadcast_to(
181
+ jnp.arange(input_ids.shape[-1] - 1)[None, :],
182
+ (input_ids.shape[0], input_ids.shape[-1] - 1),
183
+ )
184
+
185
+ outputs_cache = model(
186
+ input_ids[:, :-1],
187
+ attention_mask=attention_mask_cache,
188
+ past_key_values=past_key_values,
189
+ position_ids=position_ids,
190
+ )
191
+ position_ids = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]], dtype="i4")
192
+ outputs_cache_next = model(
193
+ input_ids[:, -1:],
194
+ past_key_values=outputs_cache.past_key_values,
195
+ attention_mask=attention_mask_cache,
196
+ position_ids=position_ids,
197
+ )
198
+
199
+ outputs = model(input_ids, attention_mask=attention_mask)
200
+
201
+ diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
202
+ self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}")
203
+
204
+
205
+ @require_flax
206
+ class FlaxOPTModelTest(FlaxModelTesterMixin, unittest.TestCase, FlaxGenerationTesterMixin):
207
+ all_model_classes = (FlaxOPTModel, FlaxOPTForCausalLM) if is_flax_available() else ()
208
+ all_generative_model_classes = () if is_flax_available() else ()
209
+
210
+ def setUp(self):
211
+ self.model_tester = FlaxOPTModelTester(self)
212
+
213
+ def test_use_cache_forward(self):
214
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
215
+ for model_class in self.all_model_classes:
216
+ self.model_tester.check_use_cache_forward(model_class, config, inputs_dict)
217
+
218
+ def test_use_cache_forward_with_attn_mask(self):
219
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
220
+ for model_class in self.all_model_classes:
221
+ self.model_tester.check_use_cache_forward_with_attn_mask(model_class, config, inputs_dict)
222
+
223
+ @slow
224
+ def test_model_from_pretrained(self):
225
+ for model_class_name in self.all_model_classes:
226
+ model = model_class_name.from_pretrained("facebook/opt-125m")
227
+ input_ids = np.ones((1, 1)) * model.config.eos_token_id
228
+ outputs = model(input_ids)
229
+ self.assertIsNotNone(outputs)
230
+
231
+
232
+ @require_sentencepiece
233
+ @require_flax
234
+ class FlaxOPTModelIntegrationTests(unittest.TestCase):
235
+ @slow
236
+ def test_inference_no_head(self):
237
+ model = FlaxOPTModel.from_pretrained("facebook/opt-350m")
238
+ input_ids = jnp.array([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
239
+ output = model(input_ids=input_ids).last_hidden_state
240
+ expected_shape = (1, 11, 512)
241
+ self.assertEqual(output.shape, expected_shape)
242
+ expected_slice = jnp.array(
243
+ [[-0.2867, -1.9256, -0.3062], [-1.2711, -0.1337, -0.1897], [0.4109, 0.1187, -1.3142]]
244
+ )
245
+ self.assertTrue(jnp.allclose(output[:, :3, :3], expected_slice, atol=4e-2))
246
+
247
+
248
+ @require_flax
249
+ @slow
250
+ class FlaxOPTEmbeddingsTest(unittest.TestCase):
251
+ def setUp(self):
252
+ super().setUp()
253
+ self.path_model = "facebook/opt-350m"
254
+
255
+ def test_logits(self):
256
+ model = FlaxOPTForCausalLM.from_pretrained(self.path_model)
257
+ tokenizer = GPT2Tokenizer.from_pretrained(self.path_model)
258
+
259
+ prompts = [
260
+ "Today is a beautiful day and I want to",
261
+ "In the city of",
262
+ "Paris is the capital of France and",
263
+ "Computers and mobile phones have taken",
264
+ ]
265
+ # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False
266
+ inputs = tokenizer(prompts, return_tensors="jax", padding=True, add_special_tokens=False)
267
+ logits = model(inputs.input_ids, attention_mask=inputs.attention_mask)[0].mean(axis=-1)
268
+ logits_meta = jnp.array(
269
+ [
270
+ [1.3851, -13.8923, -10.5229, -10.7533, -0.2309, -10.2384, -0.5365, -9.0947, -5.1670],
271
+ [-4.7073, -10.6276, -3.9415, -21.5242, -0.2822, -0.2822, -0.2822, -0.2822, -0.2822],
272
+ [0.6247, -3.4229, -8.9179, -1.4297, -14.1650, 1.4146, -9.0218, -0.2703, -0.2703],
273
+ [6.4783, -1.9913, -10.7926, -2.3336, 1.5092, -0.9974, -6.8213, 1.3477, 1.3477],
274
+ ]
275
+ )
276
+ self.assertTrue(jnp.allclose(logits, logits_meta, atol=4e-2))
277
+
278
+ model = jax.jit(model)
279
+ logits = model(inputs.input_ids, attention_mask=inputs.attention_mask)[0].mean(axis=-1)
280
+ self.assertTrue(jnp.allclose(logits, logits_meta, atol=4e-2))
281
+
282
+
283
+ @require_flax
284
+ @slow
285
+ class FlaxOPTGenerationTest(unittest.TestCase):
286
+ @property
287
+ def prompts(self):
288
+ return [
289
+ "Today is a beautiful day and I want",
290
+ "In the city of",
291
+ "Paris is the capital of France and",
292
+ "Computers and mobile phones have taken",
293
+ ]
294
+
295
+ def test_generation_pre_attn_layer_norm(self):
296
+ model_id = "facebook/opt-125m"
297
+
298
+ EXPECTED_OUTPUTS = [
299
+ "Today is a beautiful day and I want to",
300
+ "In the city of New York, the city",
301
+ "Paris is the capital of France and the capital",
302
+ "Computers and mobile phones have taken over the",
303
+ ]
304
+
305
+ predicted_outputs = []
306
+
307
+ model = FlaxOPTForCausalLM.from_pretrained(model_id)
308
+ tokenizer = GPT2Tokenizer.from_pretrained(model_id)
309
+
310
+ for prompt in self.prompts:
311
+ input_ids = tokenizer(prompt, return_tensors="jax").input_ids
312
+
313
+ generated_ids = model.generate(input_ids, max_length=10)
314
+ generated_ids = generated_ids[0]
315
+
316
+ generated_string = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
317
+ predicted_outputs += generated_string
318
+
319
+ self.assertListEqual(predicted_outputs, EXPECTED_OUTPUTS)
320
+
321
+ def test_generation_post_attn_layer_norm(self):
322
+ model_id = "facebook/opt-350m"
323
+
324
+ EXPECTED_OUTPUTS = [
325
+ "Today is a beautiful day and I want to",
326
+ "In the city of San Francisco, the city",
327
+ "Paris is the capital of France and the capital",
328
+ "Computers and mobile phones have taken over the",
329
+ ]
330
+
331
+ predicted_outputs = []
332
+ model = FlaxOPTForCausalLM.from_pretrained(model_id)
333
+ tokenizer = GPT2Tokenizer.from_pretrained(model_id)
334
+
335
+ for prompt in self.prompts:
336
+ input_ids = tokenizer(prompt, return_tensors="jax").input_ids
337
+
338
+ generated_ids = model.generate(input_ids, max_length=10)
339
+ generated_ids = generated_ids[0]
340
+
341
+ generated_string = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
342
+ predicted_outputs += generated_string
343
+
344
+ self.assertListEqual(predicted_outputs, EXPECTED_OUTPUTS)
345
+
346
+ def test_jitted_batch_generation(self):
347
+ model_id = "facebook/opt-125m"
348
+ EXPECTED_OUTPUTS = [
349
+ "Today is a beautiful day and I want to thank",
350
+ "In the city of Rome Canaver Canaver Canaver Canaver",
351
+ ]
352
+ model = FlaxOPTForCausalLM.from_pretrained(model_id)
353
+ tokenizer = GPT2Tokenizer.from_pretrained(model_id)
354
+ inputs = tokenizer(
355
+ [
356
+ "Today is a beautiful day and I want to",
357
+ "In the city of",
358
+ ],
359
+ return_tensors="jax",
360
+ padding=True,
361
+ )
362
+
363
+ jit_generate = jax.jit(model.generate)
364
+
365
+ output_sequences = jit_generate(inputs["input_ids"], attention_mask=inputs["attention_mask"]).sequences
366
+
367
+ output_string = tokenizer.batch_decode(output_sequences, skip_special_tokens=True)
368
+
369
+ self.assertIsNotNone(output_string, EXPECTED_OUTPUTS)
370
+
371
+ def test_batch_generation(self):
372
+ model_id = "facebook/opt-350m"
373
+
374
+ tokenizer = GPT2Tokenizer.from_pretrained(model_id)
375
+ model = FlaxOPTForCausalLM.from_pretrained(model_id)
376
+
377
+ tokenizer.padding_side = "left"
378
+
379
+ # use different length sentences to test batching
380
+ sentences = [
381
+ "Hello, my dog is a little",
382
+ "Today, I",
383
+ ]
384
+
385
+ inputs = tokenizer(sentences, return_tensors="jax", padding=True)
386
+ input_ids = inputs["input_ids"]
387
+
388
+ outputs = model.generate(input_ids=input_ids, attention_mask=inputs["attention_mask"], trace=False)
389
+
390
+ inputs_non_padded = tokenizer(sentences[0], return_tensors="jax").input_ids
391
+ output_non_padded = model.generate(input_ids=inputs_non_padded)
392
+
393
+ num_paddings = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].sum()
394
+ inputs_padded = tokenizer(sentences[1], return_tensors="jax").input_ids
395
+ output_padded = model.generate(input_ids=inputs_padded, max_length=model.config.max_length - num_paddings)
396
+
397
+ batch_out_sentence = tokenizer.batch_decode(outputs[0], skip_special_tokens=True)
398
+ non_padded_sentence = tokenizer.decode(output_non_padded[0][0], skip_special_tokens=True)
399
+ padded_sentence = tokenizer.decode(output_padded[0][0], skip_special_tokens=True)
400
+
401
+ expected_output_sentence = [
402
+ "Hello, my dog is a little bit of a dork.\nI'm a little bit",
403
+ "Today, I was in the middle of a conversation with a friend about the",
404
+ ]
405
+ self.assertListEqual(expected_output_sentence, batch_out_sentence)
406
+ self.assertListEqual(batch_out_sentence, [non_padded_sentence, padded_sentence])
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/opt/test_modeling_opt.py ADDED
@@ -0,0 +1,584 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 OPT model."""
16
+
17
+ import copy
18
+ import tempfile
19
+ import unittest
20
+
21
+ import timeout_decorator # noqa
22
+
23
+ from transformers import OPTConfig, is_torch_available
24
+ from transformers.testing_utils import (
25
+ require_torch,
26
+ require_torch_accelerator,
27
+ require_torch_fp16,
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
+ GPT2Tokenizer,
43
+ OPTForCausalLM,
44
+ OPTForQuestionAnswering,
45
+ OPTForSequenceClassification,
46
+ OPTModel,
47
+ )
48
+
49
+
50
+ def prepare_opt_inputs_dict(
51
+ config,
52
+ input_ids,
53
+ decoder_input_ids=None,
54
+ attention_mask=None,
55
+ decoder_attention_mask=None,
56
+ head_mask=None,
57
+ decoder_head_mask=None,
58
+ ):
59
+ if attention_mask is None:
60
+ attention_mask = input_ids.ne(config.pad_token_id)
61
+ return {
62
+ "input_ids": input_ids,
63
+ "attention_mask": attention_mask,
64
+ "head_mask": head_mask,
65
+ }
66
+
67
+
68
+ class OPTModelTester:
69
+ def __init__(
70
+ self,
71
+ parent,
72
+ batch_size=13,
73
+ seq_length=7,
74
+ is_training=True,
75
+ use_labels=False,
76
+ vocab_size=99,
77
+ hidden_size=16,
78
+ num_hidden_layers=2,
79
+ num_attention_heads=4,
80
+ intermediate_size=4,
81
+ hidden_act="gelu",
82
+ hidden_dropout_prob=0.1,
83
+ attention_probs_dropout_prob=0.1,
84
+ max_position_embeddings=20,
85
+ eos_token_id=2,
86
+ pad_token_id=1,
87
+ bos_token_id=0,
88
+ embed_dim=16,
89
+ num_labels=3,
90
+ word_embed_proj_dim=16,
91
+ type_sequence_label_size=2,
92
+ attn_implementation="eager",
93
+ ):
94
+ self.parent = parent
95
+ self.batch_size = batch_size
96
+ self.seq_length = seq_length
97
+ self.is_training = is_training
98
+ self.use_labels = use_labels
99
+ self.vocab_size = vocab_size
100
+ self.hidden_size = hidden_size
101
+ self.num_hidden_layers = num_hidden_layers
102
+ self.num_attention_heads = num_attention_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.eos_token_id = eos_token_id
109
+ self.pad_token_id = pad_token_id
110
+ self.bos_token_id = bos_token_id
111
+ self.embed_dim = embed_dim
112
+ self.num_labels = num_labels
113
+ self.type_sequence_label_size = type_sequence_label_size
114
+ self.word_embed_proj_dim = word_embed_proj_dim
115
+ self.is_encoder_decoder = False
116
+ self.attn_implementation = attn_implementation
117
+
118
+ def prepare_config_and_inputs(self):
119
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size).clamp(
120
+ 3,
121
+ )
122
+ input_ids[:, -1] = self.eos_token_id # Eos Token
123
+
124
+ decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
125
+
126
+ config = self.get_config()
127
+ inputs_dict = prepare_opt_inputs_dict(config, input_ids, decoder_input_ids)
128
+ return config, inputs_dict
129
+
130
+ def get_config(self):
131
+ return OPTConfig(
132
+ vocab_size=self.vocab_size,
133
+ hidden_size=self.hidden_size,
134
+ num_hidden_layers=self.num_hidden_layers,
135
+ num_attention_heads=self.num_attention_heads,
136
+ ffn_dim=self.intermediate_size,
137
+ dropout=self.hidden_dropout_prob,
138
+ attention_dropout=self.attention_probs_dropout_prob,
139
+ max_position_embeddings=self.max_position_embeddings,
140
+ eos_token_id=self.eos_token_id,
141
+ bos_token_id=self.bos_token_id,
142
+ pad_token_id=self.pad_token_id,
143
+ embed_dim=self.embed_dim,
144
+ is_encoder_decoder=False,
145
+ word_embed_proj_dim=self.word_embed_proj_dim,
146
+ attn_implementation=self.attn_implementation,
147
+ )
148
+
149
+ def get_pipeline_config(self):
150
+ config = self.get_config()
151
+ config.max_position_embeddings = 100
152
+ return config
153
+
154
+ def prepare_config_and_inputs_for_common(self):
155
+ config, inputs_dict = self.prepare_config_and_inputs()
156
+ return config, inputs_dict
157
+
158
+ def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict):
159
+ model = OPTModel(config=config).to(torch_device).eval()
160
+
161
+ input_ids = inputs_dict["input_ids"]
162
+ attention_mask = inputs_dict["attention_mask"]
163
+ head_mask = inputs_dict["head_mask"]
164
+
165
+ # first forward pass
166
+ outputs = model(input_ids, attention_mask=attention_mask, head_mask=head_mask, use_cache=True)
167
+
168
+ output, past_key_values = outputs.to_tuple()
169
+
170
+ # create hypothetical multiple next token and extent to next_input_ids
171
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
172
+ next_attn_mask = ids_tensor((self.batch_size, 3), 2)
173
+
174
+ # append to next input_ids and
175
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
176
+ next_attention_mask = torch.cat([attention_mask, next_attn_mask], dim=-1)
177
+
178
+ output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"]
179
+ output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[
180
+ "last_hidden_state"
181
+ ]
182
+
183
+ # select random slice
184
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
185
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
186
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
187
+
188
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
189
+
190
+ # test that outputs are equal for slice
191
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
192
+
193
+ # test no attention_mask works
194
+ outputs = model(input_ids, attention_mask=attention_mask, head_mask=head_mask, use_cache=True)
195
+ _, past_key_values = outputs.to_tuple()
196
+ output_from_no_past = model(next_input_ids)["last_hidden_state"]
197
+
198
+ output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"]
199
+
200
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
201
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
202
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
203
+ # test that outputs are equal for slice
204
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
205
+
206
+
207
+ @require_torch
208
+ class OPTModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
209
+ all_model_classes = (
210
+ (OPTModel, OPTForCausalLM, OPTForSequenceClassification, OPTForQuestionAnswering)
211
+ if is_torch_available()
212
+ else ()
213
+ )
214
+ all_generative_model_classes = (OPTForCausalLM,) if is_torch_available() else ()
215
+ pipeline_model_mapping = (
216
+ {
217
+ "feature-extraction": OPTModel,
218
+ "question-answering": OPTForQuestionAnswering,
219
+ "text-classification": OPTForSequenceClassification,
220
+ "text-generation": OPTForCausalLM,
221
+ "zero-shot": OPTForSequenceClassification,
222
+ }
223
+ if is_torch_available()
224
+ else {}
225
+ )
226
+ is_encoder_decoder = False
227
+ fx_compatible = True
228
+ test_pruning = False
229
+ test_missing_keys = False
230
+
231
+ # TODO: Fix the failed tests
232
+ def is_pipeline_test_to_skip(
233
+ self,
234
+ pipeline_test_case_name,
235
+ config_class,
236
+ model_architecture,
237
+ tokenizer_name,
238
+ image_processor_name,
239
+ feature_extractor_name,
240
+ processor_name,
241
+ ):
242
+ if (
243
+ pipeline_test_case_name == "QAPipelineTests"
244
+ and tokenizer_name is not None
245
+ and not tokenizer_name.endswith("Fast")
246
+ ):
247
+ # `QAPipelineTests` fails for a few models when the slower tokenizer are used.
248
+ # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
249
+ # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
250
+ return True
251
+
252
+ return False
253
+
254
+ def setUp(self):
255
+ self.model_tester = OPTModelTester(self)
256
+ self.config_tester = ConfigTester(self, config_class=OPTConfig)
257
+
258
+ def test_config(self):
259
+ self.config_tester.run_common_tests()
260
+
261
+ def test_save_load_strict(self):
262
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
263
+ for model_class in self.all_model_classes:
264
+ model = model_class(config)
265
+
266
+ with tempfile.TemporaryDirectory() as tmpdirname:
267
+ model.save_pretrained(tmpdirname)
268
+ model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True)
269
+ self.assertEqual(info["missing_keys"], [])
270
+
271
+ def test_decoder_model_past_with_large_inputs(self):
272
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
273
+ self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
274
+
275
+ def test_inputs_embeds(self):
276
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
277
+
278
+ for model_class in (OPTModel,):
279
+ model = model_class(config)
280
+ model.to(torch_device)
281
+ model.eval()
282
+
283
+ inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class))
284
+
285
+ if not self.is_encoder_decoder:
286
+ input_ids = inputs["input_ids"]
287
+ del inputs["input_ids"]
288
+ else:
289
+ encoder_input_ids = inputs["input_ids"]
290
+ decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids)
291
+ del inputs["input_ids"]
292
+ inputs.pop("decoder_input_ids", None)
293
+
294
+ wte = model.get_input_embeddings()
295
+ if not self.is_encoder_decoder:
296
+ inputs["inputs_embeds"] = wte(input_ids)
297
+ else:
298
+ inputs["inputs_embeds"] = wte(encoder_input_ids)
299
+ inputs["decoder_inputs_embeds"] = wte(decoder_input_ids)
300
+
301
+ with torch.no_grad():
302
+ model(**inputs)[0]
303
+
304
+ @require_torch_fp16
305
+ def test_generate_fp16(self):
306
+ config, input_dict = self.model_tester.prepare_config_and_inputs()
307
+ input_ids = input_dict["input_ids"]
308
+ attention_mask = input_ids.ne(1).to(torch_device)
309
+ model = OPTForCausalLM(config).eval().to(torch_device)
310
+ model.half()
311
+ model.generate(input_ids, attention_mask=attention_mask)
312
+ model.generate(num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3)
313
+
314
+ def test_opt_sequence_classification_model(self):
315
+ config, input_dict = self.model_tester.prepare_config_and_inputs()
316
+ config.num_labels = 3
317
+ input_ids = input_dict["input_ids"]
318
+ attention_mask = input_ids.ne(1).to(torch_device)
319
+ sequence_labels = ids_tensor([self.model_tester.batch_size], self.model_tester.type_sequence_label_size)
320
+ model = OPTForSequenceClassification(config)
321
+ model.to(torch_device)
322
+ model.eval()
323
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
324
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
325
+
326
+ def test_opt_sequence_classification_model_for_multi_label(self):
327
+ config, input_dict = self.model_tester.prepare_config_and_inputs()
328
+ config.num_labels = 3
329
+ config.problem_type = "multi_label_classification"
330
+ input_ids = input_dict["input_ids"]
331
+ attention_mask = input_ids.ne(1).to(torch_device)
332
+ sequence_labels = ids_tensor(
333
+ [self.model_tester.batch_size, config.num_labels], self.model_tester.type_sequence_label_size
334
+ ).to(torch.float)
335
+ model = OPTForSequenceClassification(config)
336
+ model.to(torch_device)
337
+ model.eval()
338
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
339
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
340
+
341
+ @unittest.skip(reason="Does not work on the tiny model as we keep hitting edge cases.")
342
+ def test_model_parallelism(self):
343
+ super().test_model_parallelism()
344
+
345
+
346
+ def assert_tensors_close(a, b, atol=1e-12, prefix=""):
347
+ """If tensors have different shapes, different values or a and b are not both tensors, raise a nice Assertion error."""
348
+ if a is None and b is None:
349
+ return True
350
+ try:
351
+ if torch.allclose(a, b, atol=atol):
352
+ return True
353
+ raise
354
+ except Exception:
355
+ pct_different = (torch.gt((a - b).abs(), atol)).float().mean().item()
356
+ if a.numel() > 100:
357
+ msg = f"tensor values are {pct_different:.1%} percent different."
358
+ else:
359
+ msg = f"{a} != {b}"
360
+ if prefix:
361
+ msg = prefix + ": " + msg
362
+ raise AssertionError(msg)
363
+
364
+
365
+ def _long_tensor(tok_lst):
366
+ return torch.tensor(tok_lst, dtype=torch.long, device=torch_device)
367
+
368
+
369
+ @require_torch
370
+ class OPTModelIntegrationTests(unittest.TestCase):
371
+ @slow
372
+ def test_inference_no_head(self):
373
+ model = OPTModel.from_pretrained("facebook/opt-350m").to(torch_device)
374
+ input_ids = _long_tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
375
+
376
+ with torch.no_grad():
377
+ output = model(input_ids=input_ids).last_hidden_state
378
+
379
+ expected_shape = torch.Size((1, 11, 512))
380
+ self.assertEqual(output.shape, expected_shape)
381
+ # expected value works for CPU, as well as GPU (with TF32 disabled)
382
+ expected_slice = torch.tensor(
383
+ [
384
+ [-0.28726277, -1.9241608, -0.3058734],
385
+ [-1.2737825, -0.13332152, -0.18766522],
386
+ [0.41159445, 0.1191957, -1.3107123],
387
+ ],
388
+ device=torch_device,
389
+ )
390
+ assert_tensors_close(output[0, :3, :3], expected_slice, atol=5e-5)
391
+
392
+
393
+ @require_torch
394
+ @slow
395
+ class OPTEmbeddingsTest(unittest.TestCase):
396
+ def setUp(self):
397
+ super().setUp()
398
+ self.path_model = "facebook/opt-350m"
399
+
400
+ def test_load_model(self):
401
+ try:
402
+ _ = OPTForCausalLM.from_pretrained(self.path_model)
403
+ except BaseException:
404
+ self.fail("Failed loading model")
405
+
406
+ def test_logits(self):
407
+ model = OPTForCausalLM.from_pretrained(self.path_model)
408
+ model = model.eval()
409
+ tokenizer = GPT2Tokenizer.from_pretrained(self.path_model)
410
+
411
+ prompts = [
412
+ "Today is a beautiful day and I want to",
413
+ "In the city of",
414
+ "Paris is the capital of France and",
415
+ "Computers and mobile phones have taken",
416
+ ]
417
+ # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False
418
+ inputs = tokenizer(prompts, return_tensors="pt", padding=True, add_special_tokens=False)
419
+ logits = model(inputs.input_ids, attention_mask=inputs.attention_mask)[0].mean(dim=-1)
420
+ # logits_meta = torch.load(self.path_logits_meta)
421
+ logits_meta = torch.Tensor(
422
+ [
423
+ [1.3851, -13.8923, -10.5229, -10.7533, -0.2309, -10.2384, -0.5365, -9.0947, -5.1670],
424
+ [-4.7073, -10.6276, -3.9415, -21.5242, -0.2822, -0.2822, -0.2822, -0.2822, -0.2822],
425
+ [0.6247, -3.4229, -8.9179, -1.4297, -14.1650, 1.4146, -9.0218, -0.2703, -0.2703],
426
+ [6.4783, -1.9913, -10.7926, -2.3336, 1.5092, -0.9974, -6.8213, 1.3477, 1.3477],
427
+ ]
428
+ )
429
+ assert torch.allclose(logits, logits_meta, atol=1e-4)
430
+
431
+
432
+ @slow
433
+ class OPTGenerationTest(unittest.TestCase):
434
+ @property
435
+ def prompts(self):
436
+ return [
437
+ "Today is a beautiful day and I want",
438
+ "In the city of",
439
+ "Paris is the capital of France and",
440
+ "Computers and mobile phones have taken",
441
+ ]
442
+
443
+ def test_generation_pre_attn_layer_norm(self):
444
+ model_id = "facebook/opt-125m"
445
+
446
+ EXPECTED_OUTPUTS = [
447
+ "Today is a beautiful day and I want to",
448
+ "In the city of New York, the city",
449
+ "Paris is the capital of France and the capital",
450
+ "Computers and mobile phones have taken over the",
451
+ ]
452
+
453
+ predicted_outputs = []
454
+ tokenizer = GPT2Tokenizer.from_pretrained(model_id)
455
+ model = OPTForCausalLM.from_pretrained(model_id)
456
+
457
+ for prompt in self.prompts:
458
+ input_ids = tokenizer(prompt, return_tensors="pt").input_ids
459
+
460
+ generated_ids = model.generate(input_ids, max_length=10)
461
+
462
+ generated_string = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
463
+ predicted_outputs += generated_string
464
+
465
+ self.assertListEqual(predicted_outputs, EXPECTED_OUTPUTS)
466
+
467
+ def test_batch_generation(self):
468
+ model_id = "facebook/opt-350m"
469
+
470
+ tokenizer = GPT2Tokenizer.from_pretrained(model_id)
471
+ model = OPTForCausalLM.from_pretrained(model_id)
472
+ model.to(torch_device)
473
+
474
+ tokenizer.padding_side = "left"
475
+
476
+ # use different length sentences to test batching
477
+ sentences = [
478
+ "Hello, my dog is a little",
479
+ "Today, I",
480
+ ]
481
+
482
+ inputs = tokenizer(sentences, return_tensors="pt", padding=True)
483
+ input_ids = inputs["input_ids"].to(torch_device)
484
+
485
+ outputs = model.generate(
486
+ input_ids=input_ids,
487
+ attention_mask=inputs["attention_mask"].to(torch_device),
488
+ )
489
+
490
+ inputs_non_padded = tokenizer(sentences[0], return_tensors="pt").input_ids.to(torch_device)
491
+ output_non_padded = model.generate(input_ids=inputs_non_padded)
492
+
493
+ num_paddings = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item()
494
+ inputs_padded = tokenizer(sentences[1], return_tensors="pt").input_ids.to(torch_device)
495
+ output_padded = model.generate(input_ids=inputs_padded, max_length=model.config.max_length - num_paddings)
496
+
497
+ batch_out_sentence = tokenizer.batch_decode(outputs, skip_special_tokens=True)
498
+ non_padded_sentence = tokenizer.decode(output_non_padded[0], skip_special_tokens=True)
499
+ padded_sentence = tokenizer.decode(output_padded[0], skip_special_tokens=True)
500
+
501
+ expected_output_sentence = [
502
+ "Hello, my dog is a little bit of a dork.\nI'm a little bit",
503
+ "Today, I was in the middle of a conversation with a friend about the",
504
+ ]
505
+ self.assertListEqual(expected_output_sentence, batch_out_sentence)
506
+ self.assertListEqual(batch_out_sentence, [non_padded_sentence, padded_sentence])
507
+
508
+ def test_generation_post_attn_layer_norm(self):
509
+ model_id = "facebook/opt-350m"
510
+
511
+ EXPECTED_OUTPUTS = [
512
+ "Today is a beautiful day and I want to",
513
+ "In the city of San Francisco, the city",
514
+ "Paris is the capital of France and the capital",
515
+ "Computers and mobile phones have taken over the",
516
+ ]
517
+
518
+ predicted_outputs = []
519
+ tokenizer = GPT2Tokenizer.from_pretrained(model_id)
520
+ model = OPTForCausalLM.from_pretrained(model_id)
521
+
522
+ for prompt in self.prompts:
523
+ input_ids = tokenizer(prompt, return_tensors="pt").input_ids
524
+
525
+ generated_ids = model.generate(input_ids, max_length=10)
526
+
527
+ generated_string = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
528
+ predicted_outputs += generated_string
529
+
530
+ self.assertListEqual(predicted_outputs, EXPECTED_OUTPUTS)
531
+
532
+ @require_torch_accelerator
533
+ @require_torch_fp16
534
+ def test_batched_nan_fp16(self):
535
+ # a bug manifested starting at models facebook/opt-1.3 and larger when running batched generations,
536
+ # therefore not using a tiny model, but the smallest model the problem was seen with which is opt-1.3b.
537
+ # please refer to this github thread: https://github.com/huggingface/transformers/pull/17437 for more details
538
+ model_name = "facebook/opt-1.3b"
539
+ tokenizer = GPT2Tokenizer.from_pretrained(model_name, use_fast=False, padding_side="left")
540
+
541
+ model = OPTForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, use_cache=True).to(torch_device)
542
+ model = model.eval()
543
+
544
+ batch = tokenizer(["Who are you?", "Joe Biden is the president of"], padding=True, return_tensors="pt")
545
+
546
+ input_ids = batch["input_ids"].to(torch_device)
547
+ attention_mask = batch["attention_mask"].to(torch_device)
548
+
549
+ with torch.no_grad():
550
+ outputs = model(input_ids, attention_mask=attention_mask)
551
+ self.assertFalse(
552
+ torch.isnan(outputs.logits[0]).any().item()
553
+ ) # the first logits could contain NaNs if it fails
554
+
555
+ @slow
556
+ def test_contrastive_search_opt(self):
557
+ article = (
558
+ "A chat between a curious human and the Statue of Liberty.\n\nHuman: What is your name?\nStatue: I am the "
559
+ "Statue of Liberty.\nHuman: Where do you live?\nStatue: New York City.\nHuman: How long have you lived "
560
+ "there?"
561
+ )
562
+
563
+ opt_tokenizer = GPT2Tokenizer.from_pretrained("facebook/opt-1.3b")
564
+ opt_model = OPTForCausalLM.from_pretrained("facebook/opt-1.3b").to(torch_device)
565
+ input_ids = opt_tokenizer(article, return_tensors="pt").input_ids.to(torch_device)
566
+
567
+ outputs = opt_model.generate(input_ids, penalty_alpha=0.6, top_k=5, max_length=256)
568
+ generated_text = opt_tokenizer.batch_decode(outputs, skip_special_tokens=True)
569
+
570
+ self.assertListEqual(
571
+ generated_text,
572
+ [
573
+ "A chat between a curious human and the Statue of Liberty.\n\nHuman: What is your name?\nStatue: I "
574
+ "am the Statue of Liberty.\nHuman: Where do you live?\nStatue: New York City.\nHuman: How long have "
575
+ "you lived there?\nStatue: A hundred years.\nHuman: And you’re from what country?\nStatue: The United "
576
+ "States of America.\nHuman: Why did you come to America?\nStatue: I came to escape the tyranny of my "
577
+ "country.\nHuman: What tyranny?\nStatue: They didn’t let me speak my mind.\nHuman: What was your "
578
+ "country?\nStatue: It was a country of immigrants.\nHuman: Who were the immigrants?\nStatue: They "
579
+ "were from all over the world.\nHuman: What language did they speak?\nStatue: French, Spanish, "
580
+ "Italian, German, English—you name it.\nHuman: And where did they come from?\nStatue: They came from "
581
+ "every country in the world.\nHuman: And you were born in what country?\nStatue: I was born in "
582
+ "France.\nHuman: And your parents were French?\nStatue"
583
+ ],
584
+ )
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/opt/test_modeling_tf_opt.py ADDED
@@ -0,0 +1,406 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
16
+ from __future__ import annotations
17
+
18
+ import unittest
19
+
20
+ import numpy as np
21
+
22
+ from transformers import OPTConfig, is_tf_available
23
+ from transformers.testing_utils import require_sentencepiece, require_tf, slow
24
+
25
+ from ...test_configuration_common import ConfigTester
26
+ from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
27
+ from ...test_pipeline_mixin import PipelineTesterMixin
28
+
29
+
30
+ if is_tf_available():
31
+ import tensorflow as tf
32
+
33
+ from transformers import GPT2Tokenizer, TFOPTForCausalLM, TFOPTModel
34
+
35
+
36
+ def prepare_opt_inputs_dict(config, input_ids, attention_mask=None, head_mask=None):
37
+ if attention_mask is None:
38
+ attention_mask = tf.cast(tf.math.not_equal(input_ids, config.pad_token_id), tf.int8)
39
+ return {"input_ids": input_ids, "attention_mask": attention_mask}
40
+
41
+
42
+ @require_tf
43
+ class TFOPTModelTester:
44
+ config_cls = OPTConfig
45
+ config_updates = {}
46
+ hidden_act = "gelu"
47
+
48
+ def __init__(
49
+ self,
50
+ parent,
51
+ batch_size=13,
52
+ seq_length=7,
53
+ is_training=True,
54
+ use_labels=False,
55
+ vocab_size=99,
56
+ hidden_size=16,
57
+ num_hidden_layers=2,
58
+ num_attention_heads=4,
59
+ intermediate_size=4,
60
+ hidden_act="gelu",
61
+ hidden_dropout_prob=0.1,
62
+ attention_probs_dropout_prob=0.1,
63
+ max_position_embeddings=20,
64
+ eos_token_id=2,
65
+ pad_token_id=1,
66
+ bos_token_id=0,
67
+ embed_dim=16,
68
+ word_embed_proj_dim=16,
69
+ attn_implementation="eager",
70
+ ):
71
+ self.parent = parent
72
+ self.batch_size = batch_size
73
+ self.seq_length = seq_length
74
+ self.is_training = is_training
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.eos_token_id = eos_token_id
86
+ self.pad_token_id = pad_token_id
87
+ self.bos_token_id = bos_token_id
88
+ self.embed_dim = embed_dim
89
+ self.word_embed_proj_dim = word_embed_proj_dim
90
+ self.is_encoder_decoder = False
91
+ self.attn_implementation = attn_implementation
92
+
93
+ def prepare_config_and_inputs_for_common(self):
94
+ input_ids = ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size)
95
+ eos_tensor = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size), 1)
96
+ input_ids = tf.concat([input_ids, eos_tensor], axis=1)
97
+
98
+ config = self.config_cls(
99
+ vocab_size=self.vocab_size,
100
+ hidden_size=self.hidden_size,
101
+ num_hidden_layers=self.num_hidden_layers,
102
+ num_attention_heads=self.num_attention_heads,
103
+ ffn_dim=self.intermediate_size,
104
+ dropout=self.hidden_dropout_prob,
105
+ attention_dropout=self.attention_probs_dropout_prob,
106
+ max_position_embeddings=self.max_position_embeddings,
107
+ eos_token_id=self.eos_token_id,
108
+ bos_token_id=self.bos_token_id,
109
+ pad_token_id=self.pad_token_id,
110
+ embed_dim=self.embed_dim,
111
+ word_embed_proj_dim=self.word_embed_proj_dim,
112
+ is_encoder_decoder=False,
113
+ attn_implementation=self.attn_implementation,
114
+ **self.config_updates,
115
+ )
116
+ inputs_dict = prepare_opt_inputs_dict(config, input_ids)
117
+ return config, inputs_dict
118
+
119
+ def check_decoder_model_past_large_inputs(self, config, inputs_dict):
120
+ model = TFOPTModel(config=config)
121
+ input_ids = inputs_dict["input_ids"]
122
+
123
+ input_ids = input_ids[:1, :]
124
+ attention_mask = inputs_dict["attention_mask"][:1, :]
125
+ self.batch_size = 1
126
+
127
+ # first forward pass
128
+ outputs = model(input_ids, attention_mask=attention_mask, use_cache=True)
129
+
130
+ output, past_key_values = outputs.to_tuple()
131
+
132
+ # create hypothetical next token and extent to next_input_ids
133
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
134
+ next_attn_mask = tf.cast(ids_tensor((self.batch_size, 3), 2), tf.int8)
135
+
136
+ # append to next input_ids and
137
+ next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
138
+ next_attention_mask = tf.concat([attention_mask, next_attn_mask], axis=-1)
139
+
140
+ output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)[0]
141
+ output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[0]
142
+
143
+ self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1])
144
+
145
+ # select random slice
146
+ random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1]))
147
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx]
148
+ output_from_past_slice = output_from_past[:, :, random_slice_idx]
149
+
150
+ # test that outputs are equal for slice
151
+ tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3)
152
+
153
+
154
+ @require_tf
155
+ class TFOPTModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
156
+ all_model_classes = (TFOPTModel, TFOPTForCausalLM) if is_tf_available() else ()
157
+ all_generative_model_classes = (TFOPTForCausalLM,) if is_tf_available() else ()
158
+ pipeline_model_mapping = (
159
+ {"feature-extraction": TFOPTModel, "text-generation": TFOPTForCausalLM} if is_tf_available() else {}
160
+ )
161
+ is_encoder_decoder = False
162
+ test_pruning = False
163
+ test_onnx = False
164
+ onnx_min_opset = 10
165
+
166
+ def setUp(self):
167
+ self.model_tester = TFOPTModelTester(self)
168
+ self.config_tester = ConfigTester(self, config_class=OPTConfig)
169
+
170
+ def test_config(self):
171
+ self.config_tester.run_common_tests()
172
+
173
+ def test_decoder_model_past_large_inputs(self):
174
+ config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common()
175
+ self.model_tester.check_decoder_model_past_large_inputs(*config_and_inputs)
176
+
177
+ def test_resize_token_embeddings(self):
178
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
179
+
180
+ def _get_word_embedding_weight(model, embedding_layer):
181
+ if hasattr(embedding_layer, "weight"):
182
+ return embedding_layer.weight
183
+ else:
184
+ # Here we build the word embeddings weights if not exists.
185
+ # And then we retry to get the attribute once built.
186
+ model.build_in_name_scope()
187
+ if hasattr(embedding_layer, "weight"):
188
+ return embedding_layer.weight
189
+ else:
190
+ return None
191
+
192
+ for model_class in self.all_model_classes:
193
+ for size in [config.vocab_size - 10, config.vocab_size + 10]:
194
+ # build the embeddings
195
+ model = model_class(config=config)
196
+ old_input_embeddings = _get_word_embedding_weight(model, model.get_input_embeddings())
197
+ old_output_embeddings = _get_word_embedding_weight(model, model.get_output_embeddings())
198
+
199
+ # reshape the embeddings
200
+ model.resize_token_embeddings(size)
201
+ new_input_embeddings = _get_word_embedding_weight(model, model.get_input_embeddings())
202
+ new_output_embeddings = _get_word_embedding_weight(model, model.get_output_embeddings())
203
+
204
+ # check that the resized embeddings size matches the desired size.
205
+ assert_size = size if size is not None else config.vocab_size
206
+
207
+ self.assertEqual(new_input_embeddings.shape[0], assert_size)
208
+
209
+ # check that weights remain the same after resizing
210
+ models_equal = True
211
+ for p1, p2 in zip(old_input_embeddings.value(), new_input_embeddings.value()):
212
+ if tf.math.reduce_sum(tf.math.abs(p1 - p2)) > 0:
213
+ models_equal = False
214
+ self.assertTrue(models_equal)
215
+
216
+ if old_output_embeddings is not None and new_output_embeddings is not None:
217
+ self.assertEqual(new_output_embeddings.shape[0], assert_size)
218
+
219
+ models_equal = True
220
+ for p1, p2 in zip(old_output_embeddings.value(), new_output_embeddings.value()):
221
+ if tf.math.reduce_sum(tf.math.abs(p1 - p2)) > 0:
222
+ models_equal = False
223
+ self.assertTrue(models_equal)
224
+
225
+
226
+ def _long_tensor(tok_lst):
227
+ return tf.constant(tok_lst, dtype=tf.int32)
228
+
229
+
230
+ @require_tf
231
+ class TFOPTHeadTests(unittest.TestCase):
232
+ vocab_size = 99
233
+
234
+ def _get_config_and_data(self):
235
+ eos_column_vector = tf.ones((4, 1), dtype=tf.int32) * 2
236
+ input_ids = tf.concat([ids_tensor((4, 6), self.vocab_size - 3) + 3, eos_column_vector], axis=1)
237
+ batch_size = input_ids.shape[0]
238
+ config = OPTConfig(
239
+ vocab_size=self.vocab_size,
240
+ hidden_size=24,
241
+ num_hidden_layers=2,
242
+ num_attention_heads=2,
243
+ ffn_dim=32,
244
+ max_position_embeddings=48,
245
+ eos_token_id=2,
246
+ pad_token_id=1,
247
+ bos_token_id=0,
248
+ )
249
+ return config, input_ids, batch_size
250
+
251
+
252
+ @require_sentencepiece
253
+ @require_tf
254
+ class OPTModelIntegrationTests(unittest.TestCase):
255
+ @slow
256
+ def test_inference_no_head(self):
257
+ model = TFOPTModel.from_pretrained("facebook/opt-350m")
258
+ input_ids = _long_tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
259
+ attention_mask = tf.not_equal(input_ids, model.config.pad_token_id)
260
+ with tf.GradientTape():
261
+ output = model(input_ids=input_ids, attention_mask=attention_mask).last_hidden_state
262
+ expected_shape = (1, 11, 512)
263
+ self.assertEqual(output.shape, expected_shape)
264
+ expected_slice = tf.constant(
265
+ [[-0.2873, -1.9218, -0.3033], [-1.2710, -0.1338, -0.1902], [0.4095, 0.1214, -1.3121]]
266
+ )
267
+ self.assertTrue(np.allclose(output[:, :3, :3], expected_slice, atol=4e-3))
268
+
269
+ xla_generate = tf.function(model, jit_compile=True)
270
+ output = xla_generate(input_ids, attention_mask)[0]
271
+ self.assertTrue(np.allclose(output[:, :3, :3], expected_slice, atol=4e-2))
272
+
273
+
274
+ @require_tf
275
+ @slow
276
+ class TFOPTEmbeddingsTest(unittest.TestCase):
277
+ def setUp(self):
278
+ super().setUp()
279
+ self.path_model = "facebook/opt-350m"
280
+
281
+ def test_logits(self):
282
+ model = TFOPTForCausalLM.from_pretrained(self.path_model)
283
+ tokenizer = GPT2Tokenizer.from_pretrained(self.path_model)
284
+
285
+ prompts = [
286
+ "Today is a beautiful day and I want to",
287
+ "In the city of",
288
+ "Paris is the capital of France and",
289
+ "Computers and mobile phones have taken",
290
+ ]
291
+ # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False
292
+ inputs = tokenizer(prompts, return_tensors="tf", padding=True, add_special_tokens=False)
293
+ logits = tf.math.reduce_mean(model(inputs.input_ids, attention_mask=inputs.attention_mask)[0], axis=-1)
294
+ logits_meta = tf.constant(
295
+ [
296
+ [1.3851, -13.8923, -10.5229, -10.7533, -0.2309, -10.2384, -0.5365, -9.0947, -5.1670],
297
+ [-4.7073, -10.6276, -3.9415, -21.5242, -0.2822, -0.2822, -0.2822, -0.2822, -0.2822],
298
+ [0.6247, -3.4229, -8.9179, -1.4297, -14.1650, 1.4146, -9.0218, -0.2703, -0.2703],
299
+ [6.4783, -1.9913, -10.7926, -2.3336, 1.5092, -0.9974, -6.8213, 1.3477, 1.3477],
300
+ ]
301
+ )
302
+ self.assertTrue(np.allclose(logits, logits_meta, atol=1e-4))
303
+
304
+ xla_generate = tf.function(model, jit_compile=True)
305
+ logits = tf.math.reduce_mean(xla_generate(inputs.input_ids, attention_mask=inputs.attention_mask)[0], axis=-1)
306
+ self.assertTrue(np.allclose(logits, logits_meta, atol=1e-4))
307
+
308
+
309
+ @require_tf
310
+ @slow
311
+ class TFOPTGenerationTest(unittest.TestCase):
312
+ @property
313
+ def prompts(self):
314
+ return [
315
+ "Today is a beautiful day and I want",
316
+ "In the city of",
317
+ "Paris is the capital of France and",
318
+ "Computers and mobile phones have taken",
319
+ ]
320
+
321
+ def test_generation_pre_attn_layer_norm(self):
322
+ model_id = "facebook/opt-125m"
323
+
324
+ EXPECTED_OUTPUTS = [
325
+ "Today is a beautiful day and I want to",
326
+ "In the city of New York, the city",
327
+ "Paris is the capital of France and the capital",
328
+ "Computers and mobile phones have taken over the",
329
+ ]
330
+
331
+ predicted_outputs = []
332
+ tokenizer = GPT2Tokenizer.from_pretrained(model_id)
333
+ model = TFOPTForCausalLM.from_pretrained(model_id)
334
+
335
+ for prompt in self.prompts:
336
+ input_ids = tokenizer(prompt, return_tensors="tf").input_ids
337
+
338
+ generated_ids = model.generate(input_ids, max_length=10)
339
+
340
+ generated_string = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
341
+ predicted_outputs += generated_string
342
+
343
+ self.assertListEqual(predicted_outputs, EXPECTED_OUTPUTS)
344
+
345
+ def test_batch_generation(self):
346
+ model_id = "facebook/opt-350m"
347
+
348
+ tokenizer = GPT2Tokenizer.from_pretrained(model_id)
349
+ model = TFOPTForCausalLM.from_pretrained(model_id)
350
+
351
+ tokenizer.padding_side = "left"
352
+
353
+ # use different length sentences to test batching
354
+ sentences = [
355
+ "Hello, my dog is a little",
356
+ "Today, I",
357
+ ]
358
+
359
+ inputs = tokenizer(sentences, return_tensors="tf", padding=True)
360
+ input_ids = inputs["input_ids"]
361
+
362
+ outputs = model.generate(input_ids=input_ids, attention_mask=inputs["attention_mask"])
363
+
364
+ inputs_non_padded = tokenizer(sentences[0], return_tensors="tf").input_ids
365
+ output_non_padded = model.generate(input_ids=inputs_non_padded)
366
+
367
+ num_paddings = inputs_non_padded.shape[-1] - tf.math.reduce_sum(
368
+ tf.cast(inputs["attention_mask"][-1], tf.int64)
369
+ )
370
+ inputs_padded = tokenizer(sentences[1], return_tensors="tf").input_ids
371
+ output_padded = model.generate(input_ids=inputs_padded, max_length=model.config.max_length - num_paddings)
372
+
373
+ batch_out_sentence = tokenizer.batch_decode(outputs, skip_special_tokens=True)
374
+ non_padded_sentence = tokenizer.decode(output_non_padded[0], skip_special_tokens=True)
375
+ padded_sentence = tokenizer.decode(output_padded[0], skip_special_tokens=True)
376
+
377
+ expected_output_sentence = [
378
+ "Hello, my dog is a little bit of a dork.\nI'm a little bit",
379
+ "Today, I was in the middle of a conversation with a friend about the",
380
+ ]
381
+ self.assertListEqual(expected_output_sentence, batch_out_sentence)
382
+ self.assertListEqual(batch_out_sentence, [non_padded_sentence, padded_sentence])
383
+
384
+ def test_generation_post_attn_layer_norm(self):
385
+ model_id = "facebook/opt-350m"
386
+
387
+ EXPECTED_OUTPUTS = [
388
+ "Today is a beautiful day and I want to",
389
+ "In the city of San Francisco, the city",
390
+ "Paris is the capital of France and the capital",
391
+ "Computers and mobile phones have taken over the",
392
+ ]
393
+
394
+ predicted_outputs = []
395
+ tokenizer = GPT2Tokenizer.from_pretrained(model_id)
396
+ model = TFOPTForCausalLM.from_pretrained(model_id)
397
+
398
+ for prompt in self.prompts:
399
+ input_ids = tokenizer(prompt, return_tensors="tf").input_ids
400
+
401
+ generated_ids = model.generate(input_ids, max_length=10)
402
+
403
+ generated_string = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
404
+ predicted_outputs += generated_string
405
+
406
+ self.assertListEqual(predicted_outputs, EXPECTED_OUTPUTS)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/owlv2/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/owlv2/test_image_processing_owlv2.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 HuggingFace Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+
17
+ import unittest
18
+
19
+ from transformers.testing_utils import require_torch, require_vision, slow
20
+ from transformers.utils import is_torch_available, is_vision_available
21
+
22
+ from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs
23
+
24
+
25
+ if is_vision_available():
26
+ from PIL import Image
27
+
28
+ from transformers import AutoProcessor, Owlv2ForObjectDetection, Owlv2ImageProcessor
29
+
30
+ if is_torch_available():
31
+ import torch
32
+
33
+
34
+ class Owlv2ImageProcessingTester(unittest.TestCase):
35
+ def __init__(
36
+ self,
37
+ parent,
38
+ batch_size=7,
39
+ num_channels=3,
40
+ image_size=18,
41
+ min_resolution=30,
42
+ max_resolution=400,
43
+ do_resize=True,
44
+ size=None,
45
+ do_normalize=True,
46
+ image_mean=[0.48145466, 0.4578275, 0.40821073],
47
+ image_std=[0.26862954, 0.26130258, 0.27577711],
48
+ do_convert_rgb=True,
49
+ ):
50
+ super().__init__()
51
+ self.parent = parent
52
+ self.batch_size = batch_size
53
+ self.num_channels = num_channels
54
+ self.image_size = image_size
55
+ self.min_resolution = min_resolution
56
+ self.max_resolution = max_resolution
57
+ self.do_resize = do_resize
58
+ self.size = size if size is not None else {"height": 18, "width": 18}
59
+ self.do_normalize = do_normalize
60
+ self.image_mean = image_mean
61
+ self.image_std = image_std
62
+ self.do_convert_rgb = do_convert_rgb
63
+
64
+ def prepare_image_processor_dict(self):
65
+ return {
66
+ "do_resize": self.do_resize,
67
+ "size": self.size,
68
+ "do_normalize": self.do_normalize,
69
+ "image_mean": self.image_mean,
70
+ "image_std": self.image_std,
71
+ }
72
+
73
+ def expected_output_image_shape(self, images):
74
+ return self.num_channels, self.size["height"], self.size["width"]
75
+
76
+ def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
77
+ return prepare_image_inputs(
78
+ batch_size=self.batch_size,
79
+ num_channels=self.num_channels,
80
+ min_resolution=self.min_resolution,
81
+ max_resolution=self.max_resolution,
82
+ equal_resolution=equal_resolution,
83
+ numpify=numpify,
84
+ torchify=torchify,
85
+ )
86
+
87
+
88
+ @require_torch
89
+ @require_vision
90
+ class Owlv2ImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
91
+ image_processing_class = Owlv2ImageProcessor if is_vision_available() else None
92
+
93
+ def setUp(self):
94
+ super().setUp()
95
+ self.image_processor_tester = Owlv2ImageProcessingTester(self)
96
+
97
+ @property
98
+ def image_processor_dict(self):
99
+ return self.image_processor_tester.prepare_image_processor_dict()
100
+
101
+ def test_image_processor_properties(self):
102
+ image_processing = self.image_processing_class(**self.image_processor_dict)
103
+ self.assertTrue(hasattr(image_processing, "do_resize"))
104
+ self.assertTrue(hasattr(image_processing, "size"))
105
+ self.assertTrue(hasattr(image_processing, "do_normalize"))
106
+ self.assertTrue(hasattr(image_processing, "image_mean"))
107
+ self.assertTrue(hasattr(image_processing, "image_std"))
108
+
109
+ def test_image_processor_from_dict_with_kwargs(self):
110
+ image_processor = self.image_processing_class.from_dict(self.image_processor_dict)
111
+ self.assertEqual(image_processor.size, {"height": 18, "width": 18})
112
+
113
+ image_processor = self.image_processing_class.from_dict(
114
+ self.image_processor_dict, size={"height": 42, "width": 42}
115
+ )
116
+ self.assertEqual(image_processor.size, {"height": 42, "width": 42})
117
+
118
+ @slow
119
+ def test_image_processor_integration_test(self):
120
+ processor = Owlv2ImageProcessor()
121
+
122
+ image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
123
+ pixel_values = processor(image, return_tensors="pt").pixel_values
124
+
125
+ mean_value = round(pixel_values.mean().item(), 4)
126
+ self.assertEqual(mean_value, 0.2353)
127
+
128
+ @slow
129
+ def test_image_processor_integration_test_resize(self):
130
+ checkpoint = "google/owlv2-base-patch16-ensemble"
131
+ processor = AutoProcessor.from_pretrained(checkpoint)
132
+ model = Owlv2ForObjectDetection.from_pretrained(checkpoint)
133
+
134
+ image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
135
+ text = ["cat"]
136
+ target_size = image.size[::-1]
137
+ expected_boxes = torch.tensor(
138
+ [
139
+ [341.66656494140625, 23.38756561279297, 642.321044921875, 371.3482971191406],
140
+ [6.753320693969727, 51.96149826049805, 326.61810302734375, 473.12982177734375],
141
+ ]
142
+ )
143
+
144
+ # single image
145
+ inputs = processor(text=[text], images=[image], return_tensors="pt")
146
+ with torch.no_grad():
147
+ outputs = model(**inputs)
148
+
149
+ results = processor.post_process_object_detection(outputs, threshold=0.2, target_sizes=[target_size])[0]
150
+
151
+ boxes = results["boxes"]
152
+ self.assertTrue(
153
+ torch.allclose(boxes, expected_boxes, atol=1e-2),
154
+ f"Single image bounding boxes fail. Expected {expected_boxes}, got {boxes}",
155
+ )
156
+
157
+ # batch of images
158
+ inputs = processor(text=[text, text], images=[image, image], return_tensors="pt")
159
+ with torch.no_grad():
160
+ outputs = model(**inputs)
161
+ results = processor.post_process_object_detection(
162
+ outputs, threshold=0.2, target_sizes=[target_size, target_size]
163
+ )
164
+
165
+ for result in results:
166
+ boxes = result["boxes"]
167
+ self.assertTrue(
168
+ torch.allclose(boxes, expected_boxes, atol=1e-2),
169
+ f"Batch image bounding boxes fail. Expected {expected_boxes}, got {boxes}",
170
+ )
171
+
172
+ @unittest.skip(reason="OWLv2 doesn't treat 4 channel PIL and numpy consistently yet") # FIXME Amy
173
+ def test_call_numpy_4_channels(self):
174
+ pass
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/owlv2/test_modeling_owlv2.py ADDED
@@ -0,0 +1,1052 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Owlv2 model."""
16
+
17
+ import inspect
18
+ import os
19
+ import tempfile
20
+ import unittest
21
+
22
+ import numpy as np
23
+ import requests
24
+
25
+ from transformers import Owlv2Config, Owlv2TextConfig, Owlv2VisionConfig
26
+ from transformers.testing_utils import (
27
+ require_torch,
28
+ require_torch_accelerator,
29
+ require_torch_fp16,
30
+ require_vision,
31
+ slow,
32
+ torch_device,
33
+ )
34
+ from transformers.utils import is_torch_available, is_vision_available
35
+
36
+ from ...test_configuration_common import ConfigTester
37
+ from ...test_modeling_common import (
38
+ ModelTesterMixin,
39
+ _config_zero_init,
40
+ floats_tensor,
41
+ ids_tensor,
42
+ random_attention_mask,
43
+ )
44
+ from ...test_pipeline_mixin import PipelineTesterMixin
45
+
46
+
47
+ if is_torch_available():
48
+ import torch
49
+ from torch import nn
50
+
51
+ from transformers import Owlv2ForObjectDetection, Owlv2Model, Owlv2TextModel, Owlv2VisionModel
52
+
53
+
54
+ if is_vision_available():
55
+ from PIL import Image
56
+
57
+ from transformers import OwlViTProcessor
58
+
59
+
60
+ # Copied from tests.models.owlvit.test_modeling_owlvit.OwlViTVisionModelTester with OwlViT->Owlv2
61
+ class Owlv2VisionModelTester:
62
+ def __init__(
63
+ self,
64
+ parent,
65
+ batch_size=12,
66
+ image_size=32,
67
+ patch_size=2,
68
+ num_channels=3,
69
+ is_training=True,
70
+ hidden_size=32,
71
+ num_hidden_layers=2,
72
+ num_attention_heads=4,
73
+ intermediate_size=37,
74
+ dropout=0.1,
75
+ attention_dropout=0.1,
76
+ initializer_range=0.02,
77
+ scope=None,
78
+ ):
79
+ self.parent = parent
80
+ self.batch_size = batch_size
81
+ self.image_size = image_size
82
+ self.patch_size = patch_size
83
+ self.num_channels = num_channels
84
+ self.is_training = is_training
85
+ self.hidden_size = hidden_size
86
+ self.num_hidden_layers = num_hidden_layers
87
+ self.num_attention_heads = num_attention_heads
88
+ self.intermediate_size = intermediate_size
89
+ self.dropout = dropout
90
+ self.attention_dropout = attention_dropout
91
+ self.initializer_range = initializer_range
92
+ self.scope = scope
93
+
94
+ # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
95
+ num_patches = (image_size // patch_size) ** 2
96
+ self.seq_length = num_patches + 1
97
+
98
+ def prepare_config_and_inputs(self):
99
+ pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
100
+ config = self.get_config()
101
+
102
+ return config, pixel_values
103
+
104
+ def get_config(self):
105
+ return Owlv2VisionConfig(
106
+ image_size=self.image_size,
107
+ patch_size=self.patch_size,
108
+ num_channels=self.num_channels,
109
+ hidden_size=self.hidden_size,
110
+ num_hidden_layers=self.num_hidden_layers,
111
+ num_attention_heads=self.num_attention_heads,
112
+ intermediate_size=self.intermediate_size,
113
+ dropout=self.dropout,
114
+ attention_dropout=self.attention_dropout,
115
+ initializer_range=self.initializer_range,
116
+ )
117
+
118
+ def create_and_check_model(self, config, pixel_values):
119
+ model = Owlv2VisionModel(config=config).to(torch_device)
120
+ model.eval()
121
+
122
+ pixel_values = pixel_values.to(torch.float32)
123
+
124
+ with torch.no_grad():
125
+ result = model(pixel_values)
126
+ # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
127
+ num_patches = (self.image_size // self.patch_size) ** 2
128
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, num_patches + 1, self.hidden_size))
129
+ self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
130
+
131
+ def prepare_config_and_inputs_for_common(self):
132
+ config_and_inputs = self.prepare_config_and_inputs()
133
+ config, pixel_values = config_and_inputs
134
+ inputs_dict = {"pixel_values": pixel_values}
135
+ return config, inputs_dict
136
+
137
+
138
+ @require_torch
139
+ # Copied from tests.models.owlvit.test_modeling_owlvit.OwlViTVisionModelTest with OwlViT->Owlv2, OWL-ViT->OwlV2, OWLVIT->OWLV2, owlvit-base-patch32->owlv2-base-patch16-ensemble
140
+ class Owlv2VisionModelTest(ModelTesterMixin, unittest.TestCase):
141
+ """
142
+ Here we also overwrite some of the tests of test_modeling_common.py, as OWLV2 does not use input_ids, inputs_embeds,
143
+ attention_mask and seq_length.
144
+ """
145
+
146
+ all_model_classes = (Owlv2VisionModel,) if is_torch_available() else ()
147
+ fx_compatible = False
148
+ test_pruning = False
149
+ test_resize_embeddings = False
150
+ test_head_masking = False
151
+
152
+ def setUp(self):
153
+ self.model_tester = Owlv2VisionModelTester(self)
154
+ self.config_tester = ConfigTester(
155
+ self, config_class=Owlv2VisionConfig, has_text_modality=False, hidden_size=37
156
+ )
157
+
158
+ def test_config(self):
159
+ self.config_tester.run_common_tests()
160
+
161
+ @unittest.skip(reason="OWLV2 does not use inputs_embeds")
162
+ def test_inputs_embeds(self):
163
+ pass
164
+
165
+ def test_model_get_set_embeddings(self):
166
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
167
+
168
+ for model_class in self.all_model_classes:
169
+ model = model_class(config)
170
+ self.assertIsInstance(model.get_input_embeddings(), (nn.Module))
171
+ x = model.get_output_embeddings()
172
+ self.assertTrue(x is None or isinstance(x, nn.Linear))
173
+
174
+ def test_forward_signature(self):
175
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
176
+
177
+ for model_class in self.all_model_classes:
178
+ model = model_class(config)
179
+ signature = inspect.signature(model.forward)
180
+ # signature.parameters is an OrderedDict => so arg_names order is deterministic
181
+ arg_names = [*signature.parameters.keys()]
182
+
183
+ expected_arg_names = ["pixel_values"]
184
+ self.assertListEqual(arg_names[:1], expected_arg_names)
185
+
186
+ def test_model(self):
187
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
188
+ self.model_tester.create_and_check_model(*config_and_inputs)
189
+
190
+ @unittest.skip(reason="OwlV2 does not support training yet")
191
+ def test_training(self):
192
+ pass
193
+
194
+ @unittest.skip(reason="OwlV2 does not support training yet")
195
+ def test_training_gradient_checkpointing(self):
196
+ pass
197
+
198
+ @unittest.skip(
199
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
200
+ )
201
+ def test_training_gradient_checkpointing_use_reentrant(self):
202
+ pass
203
+
204
+ @unittest.skip(
205
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
206
+ )
207
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
208
+ pass
209
+
210
+ @unittest.skip(reason="Owlv2VisionModel has no base class and is not available in MODEL_MAPPING")
211
+ def test_save_load_fast_init_from_base(self):
212
+ pass
213
+
214
+ @unittest.skip(reason="Owlv2VisionModel has no base class and is not available in MODEL_MAPPING")
215
+ def test_save_load_fast_init_to_base(self):
216
+ pass
217
+
218
+ @slow
219
+ def test_model_from_pretrained(self):
220
+ model_name = "google/owlv2-base-patch16-ensemble"
221
+ model = Owlv2VisionModel.from_pretrained(model_name)
222
+ self.assertIsNotNone(model)
223
+
224
+
225
+ # Copied from tests.models.owlvit.test_modeling_owlvit.OwlViTTextModelTester with OwlViT->Owlv2
226
+ class Owlv2TextModelTester:
227
+ def __init__(
228
+ self,
229
+ parent,
230
+ batch_size=12,
231
+ num_queries=4,
232
+ seq_length=16,
233
+ is_training=True,
234
+ use_input_mask=True,
235
+ use_labels=True,
236
+ vocab_size=99,
237
+ hidden_size=64,
238
+ num_hidden_layers=12,
239
+ num_attention_heads=4,
240
+ intermediate_size=37,
241
+ dropout=0.1,
242
+ attention_dropout=0.1,
243
+ max_position_embeddings=16,
244
+ initializer_range=0.02,
245
+ scope=None,
246
+ ):
247
+ self.parent = parent
248
+ self.batch_size = batch_size
249
+ self.num_queries = num_queries
250
+ self.seq_length = seq_length
251
+ self.is_training = is_training
252
+ self.use_input_mask = use_input_mask
253
+ self.use_labels = use_labels
254
+ self.vocab_size = vocab_size
255
+ self.hidden_size = hidden_size
256
+ self.num_hidden_layers = num_hidden_layers
257
+ self.num_attention_heads = num_attention_heads
258
+ self.intermediate_size = intermediate_size
259
+ self.dropout = dropout
260
+ self.attention_dropout = attention_dropout
261
+ self.max_position_embeddings = max_position_embeddings
262
+ self.initializer_range = initializer_range
263
+ self.scope = scope
264
+
265
+ def prepare_config_and_inputs(self):
266
+ input_ids = ids_tensor([self.batch_size * self.num_queries, self.seq_length], self.vocab_size)
267
+ input_mask = None
268
+
269
+ if self.use_input_mask:
270
+ input_mask = random_attention_mask([self.batch_size * self.num_queries, self.seq_length])
271
+
272
+ if input_mask is not None:
273
+ num_text, seq_length = input_mask.shape
274
+
275
+ rnd_start_indices = np.random.randint(1, seq_length - 1, size=(num_text,))
276
+ for idx, start_index in enumerate(rnd_start_indices):
277
+ input_mask[idx, :start_index] = 1
278
+ input_mask[idx, start_index:] = 0
279
+
280
+ config = self.get_config()
281
+
282
+ return config, input_ids, input_mask
283
+
284
+ def get_config(self):
285
+ return Owlv2TextConfig(
286
+ vocab_size=self.vocab_size,
287
+ hidden_size=self.hidden_size,
288
+ num_hidden_layers=self.num_hidden_layers,
289
+ num_attention_heads=self.num_attention_heads,
290
+ intermediate_size=self.intermediate_size,
291
+ dropout=self.dropout,
292
+ attention_dropout=self.attention_dropout,
293
+ max_position_embeddings=self.max_position_embeddings,
294
+ initializer_range=self.initializer_range,
295
+ )
296
+
297
+ def create_and_check_model(self, config, input_ids, input_mask):
298
+ model = Owlv2TextModel(config=config).to(torch_device)
299
+ model.eval()
300
+ with torch.no_grad():
301
+ result = model(input_ids=input_ids, attention_mask=input_mask)
302
+
303
+ self.parent.assertEqual(
304
+ result.last_hidden_state.shape, (self.batch_size * self.num_queries, self.seq_length, self.hidden_size)
305
+ )
306
+ self.parent.assertEqual(result.pooler_output.shape, (self.batch_size * self.num_queries, self.hidden_size))
307
+
308
+ def prepare_config_and_inputs_for_common(self):
309
+ config_and_inputs = self.prepare_config_and_inputs()
310
+ config, input_ids, input_mask = config_and_inputs
311
+ inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
312
+ return config, inputs_dict
313
+
314
+
315
+ @require_torch
316
+ # Copied from tests.models.owlvit.test_modeling_owlvit.OwlViTTextModelTest with OwlViT->Owlv2, OWL-ViT->OwlV2, OWLVIT->OWLV2, owlvit-base-patch32->owlv2-base-patch16-ensemble
317
+ class Owlv2TextModelTest(ModelTesterMixin, unittest.TestCase):
318
+ all_model_classes = (Owlv2TextModel,) if is_torch_available() else ()
319
+ fx_compatible = False
320
+ test_pruning = False
321
+ test_head_masking = False
322
+
323
+ def setUp(self):
324
+ self.model_tester = Owlv2TextModelTester(self)
325
+ self.config_tester = ConfigTester(self, config_class=Owlv2TextConfig, hidden_size=37)
326
+
327
+ def test_config(self):
328
+ self.config_tester.run_common_tests()
329
+
330
+ def test_model(self):
331
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
332
+ self.model_tester.create_and_check_model(*config_and_inputs)
333
+
334
+ @unittest.skip(reason="OwlV2 does not support training yet")
335
+ def test_training(self):
336
+ pass
337
+
338
+ @unittest.skip(reason="OwlV2 does not support training yet")
339
+ def test_training_gradient_checkpointing(self):
340
+ pass
341
+
342
+ @unittest.skip(
343
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
344
+ )
345
+ def test_training_gradient_checkpointing_use_reentrant(self):
346
+ pass
347
+
348
+ @unittest.skip(
349
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
350
+ )
351
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
352
+ pass
353
+
354
+ @unittest.skip(reason="OWLV2 does not use inputs_embeds")
355
+ def test_inputs_embeds(self):
356
+ pass
357
+
358
+ @unittest.skip(reason="Owlv2TextModel has no base class and is not available in MODEL_MAPPING")
359
+ def test_save_load_fast_init_from_base(self):
360
+ pass
361
+
362
+ @unittest.skip(reason="Owlv2TextModel has no base class and is not available in MODEL_MAPPING")
363
+ def test_save_load_fast_init_to_base(self):
364
+ pass
365
+
366
+ @slow
367
+ def test_model_from_pretrained(self):
368
+ model_name = "google/owlv2-base-patch16-ensemble"
369
+ model = Owlv2TextModel.from_pretrained(model_name)
370
+ self.assertIsNotNone(model)
371
+
372
+
373
+ class Owlv2ModelTester:
374
+ def __init__(self, parent, text_kwargs=None, vision_kwargs=None, is_training=True):
375
+ if text_kwargs is None:
376
+ text_kwargs = {}
377
+ if vision_kwargs is None:
378
+ vision_kwargs = {}
379
+
380
+ self.parent = parent
381
+ self.text_model_tester = Owlv2TextModelTester(parent, **text_kwargs)
382
+ self.vision_model_tester = Owlv2VisionModelTester(parent, **vision_kwargs)
383
+ self.is_training = is_training
384
+ self.text_config = self.text_model_tester.get_config().to_dict()
385
+ self.vision_config = self.vision_model_tester.get_config().to_dict()
386
+ self.batch_size = self.text_model_tester.batch_size # need bs for batching_equivalence test
387
+
388
+ def prepare_config_and_inputs(self):
389
+ text_config, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs()
390
+ vision_config, pixel_values = self.vision_model_tester.prepare_config_and_inputs()
391
+ config = self.get_config()
392
+ return config, input_ids, attention_mask, pixel_values
393
+
394
+ def get_config(self):
395
+ return Owlv2Config.from_text_vision_configs(self.text_config, self.vision_config, projection_dim=64)
396
+
397
+ def create_and_check_model(self, config, input_ids, attention_mask, pixel_values):
398
+ model = Owlv2Model(config).to(torch_device).eval()
399
+
400
+ with torch.no_grad():
401
+ result = model(
402
+ input_ids=input_ids,
403
+ pixel_values=pixel_values,
404
+ attention_mask=attention_mask,
405
+ )
406
+
407
+ image_logits_size = (
408
+ self.vision_model_tester.batch_size,
409
+ self.text_model_tester.batch_size * self.text_model_tester.num_queries,
410
+ )
411
+ text_logits_size = (
412
+ self.text_model_tester.batch_size * self.text_model_tester.num_queries,
413
+ self.vision_model_tester.batch_size,
414
+ )
415
+ self.parent.assertEqual(result.logits_per_image.shape, image_logits_size)
416
+ self.parent.assertEqual(result.logits_per_text.shape, text_logits_size)
417
+
418
+ def prepare_config_and_inputs_for_common(self):
419
+ config_and_inputs = self.prepare_config_and_inputs()
420
+ config, input_ids, attention_mask, pixel_values = config_and_inputs
421
+ inputs_dict = {
422
+ "pixel_values": pixel_values,
423
+ "input_ids": input_ids,
424
+ "attention_mask": attention_mask,
425
+ "return_loss": False,
426
+ }
427
+ return config, inputs_dict
428
+
429
+
430
+ @require_torch
431
+ # Copied from tests.models.owlvit.test_modeling_owlvit.OwlViTModelTest with OwlViT->Owlv2, OWL-ViT->OwlV2, OWLVIT->OWLV2, owlvit-base-patch32->owlv2-base-patch16-ensemble
432
+ class Owlv2ModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
433
+ all_model_classes = (Owlv2Model,) if is_torch_available() else ()
434
+ pipeline_model_mapping = (
435
+ {
436
+ "feature-extraction": Owlv2Model,
437
+ "zero-shot-object-detection": Owlv2ForObjectDetection,
438
+ }
439
+ if is_torch_available()
440
+ else {}
441
+ )
442
+ fx_compatible = False
443
+ test_head_masking = False
444
+ test_pruning = False
445
+ test_resize_embeddings = False
446
+ test_attention_outputs = False
447
+
448
+ def setUp(self):
449
+ self.model_tester = Owlv2ModelTester(self)
450
+ common_properties = ["projection_dim", "logit_scale_init_value"]
451
+ self.config_tester = ConfigTester(
452
+ self, config_class=Owlv2Config, has_text_modality=False, common_properties=common_properties
453
+ )
454
+
455
+ def test_config(self):
456
+ self.config_tester.run_common_tests()
457
+
458
+ def test_model(self):
459
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
460
+ self.model_tester.create_and_check_model(*config_and_inputs)
461
+
462
+ @unittest.skip(reason="Hidden_states is tested in individual model tests")
463
+ def test_hidden_states_output(self):
464
+ pass
465
+
466
+ @unittest.skip(reason="Inputs_embeds is tested in individual model tests")
467
+ def test_inputs_embeds(self):
468
+ pass
469
+
470
+ @unittest.skip(reason="Retain_grad is tested in individual model tests")
471
+ def test_retain_grad_hidden_states_attentions(self):
472
+ pass
473
+
474
+ @unittest.skip(reason="Owlv2Model does not have input/output embeddings")
475
+ def test_model_get_set_embeddings(self):
476
+ pass
477
+
478
+ # override as the `logit_scale` parameter initilization is different for OWLV2
479
+ def test_initialization(self):
480
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
481
+
482
+ configs_no_init = _config_zero_init(config)
483
+ for model_class in self.all_model_classes:
484
+ model = model_class(config=configs_no_init)
485
+ for name, param in model.named_parameters():
486
+ if param.requires_grad:
487
+ # check if `logit_scale` is initilized as per the original implementation
488
+ if name == "logit_scale":
489
+ self.assertAlmostEqual(
490
+ param.data.item(),
491
+ np.log(1 / 0.07),
492
+ delta=1e-3,
493
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
494
+ )
495
+ else:
496
+ self.assertIn(
497
+ ((param.data.mean() * 1e9).round() / 1e9).item(),
498
+ [0.0, 1.0],
499
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
500
+ )
501
+
502
+ def _create_and_check_torchscript(self, config, inputs_dict):
503
+ if not self.test_torchscript:
504
+ self.skipTest(reason="test_torchscript is set to False")
505
+
506
+ configs_no_init = _config_zero_init(config) # To be sure we have no Nan
507
+ configs_no_init.torchscript = True
508
+ configs_no_init.return_dict = False
509
+ for model_class in self.all_model_classes:
510
+ model = model_class(config=configs_no_init).to(torch_device)
511
+ model.eval()
512
+
513
+ try:
514
+ input_ids = inputs_dict["input_ids"]
515
+ pixel_values = inputs_dict["pixel_values"] # OWLV2 needs pixel_values
516
+ traced_model = torch.jit.trace(model, (input_ids, pixel_values))
517
+ except RuntimeError:
518
+ self.fail("Couldn't trace module.")
519
+
520
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
521
+ pt_file_name = os.path.join(tmp_dir_name, "traced_model.pt")
522
+
523
+ try:
524
+ torch.jit.save(traced_model, pt_file_name)
525
+ except Exception:
526
+ self.fail("Couldn't save module.")
527
+
528
+ try:
529
+ loaded_model = torch.jit.load(pt_file_name)
530
+ except Exception:
531
+ self.fail("Couldn't load module.")
532
+
533
+ loaded_model = loaded_model.to(torch_device)
534
+ loaded_model.eval()
535
+
536
+ model_state_dict = model.state_dict()
537
+ loaded_model_state_dict = loaded_model.state_dict()
538
+
539
+ non_persistent_buffers = {}
540
+ for key in loaded_model_state_dict.keys():
541
+ if key not in model_state_dict.keys():
542
+ non_persistent_buffers[key] = loaded_model_state_dict[key]
543
+
544
+ loaded_model_state_dict = {
545
+ key: value for key, value in loaded_model_state_dict.items() if key not in non_persistent_buffers
546
+ }
547
+
548
+ self.assertEqual(set(model_state_dict.keys()), set(loaded_model_state_dict.keys()))
549
+
550
+ model_buffers = list(model.buffers())
551
+ for non_persistent_buffer in non_persistent_buffers.values():
552
+ found_buffer = False
553
+ for i, model_buffer in enumerate(model_buffers):
554
+ if torch.equal(non_persistent_buffer, model_buffer):
555
+ found_buffer = True
556
+ break
557
+
558
+ self.assertTrue(found_buffer)
559
+ model_buffers.pop(i)
560
+
561
+ models_equal = True
562
+ for layer_name, p1 in model_state_dict.items():
563
+ p2 = loaded_model_state_dict[layer_name]
564
+ if p1.data.ne(p2.data).sum() > 0:
565
+ models_equal = False
566
+
567
+ self.assertTrue(models_equal)
568
+
569
+ def test_load_vision_text_config(self):
570
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
571
+
572
+ # Save Owlv2Config and check if we can load Owlv2VisionConfig from it
573
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
574
+ config.save_pretrained(tmp_dir_name)
575
+ vision_config = Owlv2VisionConfig.from_pretrained(tmp_dir_name)
576
+ self.assertDictEqual(config.vision_config.to_dict(), vision_config.to_dict())
577
+
578
+ # Save Owlv2Config and check if we can load Owlv2TextConfig from it
579
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
580
+ config.save_pretrained(tmp_dir_name)
581
+ text_config = Owlv2TextConfig.from_pretrained(tmp_dir_name)
582
+ self.assertDictEqual(config.text_config.to_dict(), text_config.to_dict())
583
+
584
+ @slow
585
+ def test_model_from_pretrained(self):
586
+ model_name = "google/owlv2-base-patch16-ensemble"
587
+ model = Owlv2Model.from_pretrained(model_name)
588
+ self.assertIsNotNone(model)
589
+
590
+
591
+ # Copied from tests.models.owlvit.test_modeling_owlvit.OwlViTForObjectDetectionTester with OwlViT->Owlv2, OWL-ViT->OwlV2, OWLVIT->OWLV2
592
+ class Owlv2ForObjectDetectionTester:
593
+ def __init__(self, parent, is_training=True):
594
+ self.parent = parent
595
+ self.text_model_tester = Owlv2TextModelTester(parent)
596
+ self.vision_model_tester = Owlv2VisionModelTester(parent)
597
+ self.is_training = is_training
598
+ self.text_config = self.text_model_tester.get_config().to_dict()
599
+ self.vision_config = self.vision_model_tester.get_config().to_dict()
600
+ self.batch_size = self.text_model_tester.batch_size # need bs for batching_equivalence test
601
+
602
+ def prepare_config_and_inputs(self):
603
+ text_config, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs()
604
+ vision_config, pixel_values = self.vision_model_tester.prepare_config_and_inputs()
605
+ config = self.get_config()
606
+ return config, pixel_values, input_ids, attention_mask
607
+
608
+ def get_config(self):
609
+ return Owlv2Config.from_text_vision_configs(self.text_config, self.vision_config, projection_dim=64)
610
+
611
+ def create_and_check_model(self, config, pixel_values, input_ids, attention_mask):
612
+ model = Owlv2ForObjectDetection(config).to(torch_device).eval()
613
+ with torch.no_grad():
614
+ result = model(
615
+ pixel_values=pixel_values,
616
+ input_ids=input_ids,
617
+ attention_mask=attention_mask,
618
+ return_dict=True,
619
+ )
620
+
621
+ pred_boxes_size = (
622
+ self.vision_model_tester.batch_size,
623
+ (self.vision_model_tester.image_size // self.vision_model_tester.patch_size) ** 2,
624
+ 4,
625
+ )
626
+ pred_logits_size = (
627
+ self.vision_model_tester.batch_size,
628
+ (self.vision_model_tester.image_size // self.vision_model_tester.patch_size) ** 2,
629
+ 4,
630
+ )
631
+ pred_class_embeds_size = (
632
+ self.vision_model_tester.batch_size,
633
+ (self.vision_model_tester.image_size // self.vision_model_tester.patch_size) ** 2,
634
+ self.text_model_tester.hidden_size,
635
+ )
636
+ self.parent.assertEqual(result.pred_boxes.shape, pred_boxes_size)
637
+ self.parent.assertEqual(result.logits.shape, pred_logits_size)
638
+ self.parent.assertEqual(result.class_embeds.shape, pred_class_embeds_size)
639
+
640
+ def prepare_config_and_inputs_for_common(self):
641
+ config_and_inputs = self.prepare_config_and_inputs()
642
+ config, pixel_values, input_ids, attention_mask = config_and_inputs
643
+ inputs_dict = {
644
+ "pixel_values": pixel_values,
645
+ "input_ids": input_ids,
646
+ "attention_mask": attention_mask,
647
+ }
648
+ return config, inputs_dict
649
+
650
+
651
+ @require_torch
652
+ # Copied from tests.models.owlvit.test_modeling_owlvit.OwlViTForObjectDetectionTest with OwlViT->Owlv2, OWL-ViT->OwlV2, OWLVIT->OWLV2, owlvit-base-patch32->owlv2-base-patch16-ensemble
653
+ class Owlv2ForObjectDetectionTest(ModelTesterMixin, unittest.TestCase):
654
+ all_model_classes = (Owlv2ForObjectDetection,) if is_torch_available() else ()
655
+ fx_compatible = False
656
+ test_head_masking = False
657
+ test_pruning = False
658
+ test_resize_embeddings = False
659
+ test_attention_outputs = False
660
+
661
+ def setUp(self):
662
+ self.model_tester = Owlv2ForObjectDetectionTester(self)
663
+
664
+ def test_model(self):
665
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
666
+ self.model_tester.create_and_check_model(*config_and_inputs)
667
+
668
+ @unittest.skip(reason="Hidden_states is tested in individual model tests")
669
+ def test_hidden_states_output(self):
670
+ pass
671
+
672
+ @unittest.skip(reason="Inputs_embeds is tested in individual model tests")
673
+ def test_inputs_embeds(self):
674
+ pass
675
+
676
+ @unittest.skip(reason="Retain_grad is tested in individual model tests")
677
+ def test_retain_grad_hidden_states_attentions(self):
678
+ pass
679
+
680
+ @unittest.skip(reason="Owlv2Model does not have input/output embeddings")
681
+ def test_model_get_set_embeddings(self):
682
+ pass
683
+
684
+ @unittest.skip(reason="Test_initialization is tested in individual model tests")
685
+ def test_initialization(self):
686
+ pass
687
+
688
+ @unittest.skip(reason="Test_forward_signature is tested in individual model tests")
689
+ def test_forward_signature(self):
690
+ pass
691
+
692
+ @unittest.skip(reason="Test_save_load_fast_init_from_base is tested in individual model tests")
693
+ def test_save_load_fast_init_from_base(self):
694
+ pass
695
+
696
+ @unittest.skip(reason="OwlV2 does not support training yet")
697
+ def test_training(self):
698
+ pass
699
+
700
+ @unittest.skip(reason="OwlV2 does not support training yet")
701
+ def test_training_gradient_checkpointing(self):
702
+ pass
703
+
704
+ @unittest.skip(
705
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
706
+ )
707
+ def test_training_gradient_checkpointing_use_reentrant(self):
708
+ pass
709
+
710
+ @unittest.skip(
711
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
712
+ )
713
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
714
+ pass
715
+
716
+ def _create_and_check_torchscript(self, config, inputs_dict):
717
+ if not self.test_torchscript:
718
+ self.skipTest(reason="test_torchscript is set to False")
719
+
720
+ configs_no_init = _config_zero_init(config) # To be sure we have no Nan
721
+ configs_no_init.torchscript = True
722
+ configs_no_init.return_dict = False
723
+ for model_class in self.all_model_classes:
724
+ model = model_class(config=configs_no_init).to(torch_device)
725
+ model.eval()
726
+
727
+ try:
728
+ input_ids = inputs_dict["input_ids"]
729
+ pixel_values = inputs_dict["pixel_values"] # OWLV2 needs pixel_values
730
+ traced_model = torch.jit.trace(model, (input_ids, pixel_values))
731
+ except RuntimeError:
732
+ self.fail("Couldn't trace module.")
733
+
734
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
735
+ pt_file_name = os.path.join(tmp_dir_name, "traced_model.pt")
736
+
737
+ try:
738
+ torch.jit.save(traced_model, pt_file_name)
739
+ except Exception:
740
+ self.fail("Couldn't save module.")
741
+
742
+ try:
743
+ loaded_model = torch.jit.load(pt_file_name)
744
+ except Exception:
745
+ self.fail("Couldn't load module.")
746
+
747
+ loaded_model = loaded_model.to(torch_device)
748
+ loaded_model.eval()
749
+
750
+ model_state_dict = model.state_dict()
751
+ loaded_model_state_dict = loaded_model.state_dict()
752
+
753
+ non_persistent_buffers = {}
754
+ for key in loaded_model_state_dict.keys():
755
+ if key not in model_state_dict.keys():
756
+ non_persistent_buffers[key] = loaded_model_state_dict[key]
757
+
758
+ loaded_model_state_dict = {
759
+ key: value for key, value in loaded_model_state_dict.items() if key not in non_persistent_buffers
760
+ }
761
+
762
+ self.assertEqual(set(model_state_dict.keys()), set(loaded_model_state_dict.keys()))
763
+
764
+ model_buffers = list(model.buffers())
765
+ for non_persistent_buffer in non_persistent_buffers.values():
766
+ found_buffer = False
767
+ for i, model_buffer in enumerate(model_buffers):
768
+ if torch.equal(non_persistent_buffer, model_buffer):
769
+ found_buffer = True
770
+ break
771
+
772
+ self.assertTrue(found_buffer)
773
+ model_buffers.pop(i)
774
+
775
+ models_equal = True
776
+ for layer_name, p1 in model_state_dict.items():
777
+ p2 = loaded_model_state_dict[layer_name]
778
+ if p1.data.ne(p2.data).sum() > 0:
779
+ models_equal = False
780
+
781
+ self.assertTrue(models_equal)
782
+
783
+ @slow
784
+ def test_model_from_pretrained(self):
785
+ model_name = "google/owlv2-base-patch16-ensemble"
786
+ model = Owlv2ForObjectDetection.from_pretrained(model_name)
787
+ self.assertIsNotNone(model)
788
+
789
+
790
+ # We will verify our results on an image of cute cats
791
+ def prepare_img():
792
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
793
+ im = Image.open(requests.get(url, stream=True).raw)
794
+ return im
795
+
796
+
797
+ @require_vision
798
+ @require_torch
799
+ class Owlv2ModelIntegrationTest(unittest.TestCase):
800
+ @slow
801
+ def test_inference(self):
802
+ model_name = "google/owlv2-base-patch16"
803
+ model = Owlv2Model.from_pretrained(model_name).to(torch_device)
804
+ processor = OwlViTProcessor.from_pretrained(model_name)
805
+
806
+ image = prepare_img()
807
+ inputs = processor(
808
+ text=[["a photo of a cat", "a photo of a dog"]],
809
+ images=image,
810
+ max_length=16,
811
+ padding="max_length",
812
+ return_tensors="pt",
813
+ ).to(torch_device)
814
+
815
+ # forward pass
816
+ with torch.no_grad():
817
+ outputs = model(**inputs)
818
+
819
+ # verify the logits
820
+ self.assertEqual(
821
+ outputs.logits_per_image.shape,
822
+ torch.Size((inputs.pixel_values.shape[0], inputs.input_ids.shape[0])),
823
+ )
824
+ self.assertEqual(
825
+ outputs.logits_per_text.shape,
826
+ torch.Size((inputs.input_ids.shape[0], inputs.pixel_values.shape[0])),
827
+ )
828
+ expected_logits = torch.tensor([[-6.2229, -8.2601]], device=torch_device)
829
+ self.assertTrue(torch.allclose(outputs.logits_per_image, expected_logits, atol=1e-3))
830
+
831
+ @slow
832
+ def test_inference_interpolate_pos_encoding(self):
833
+ model_name = "google/owlv2-base-patch16"
834
+ model = Owlv2Model.from_pretrained(model_name).to(torch_device)
835
+ processor = OwlViTProcessor.from_pretrained(model_name)
836
+ processor.image_processor.size = {"height": 1024, "width": 1024}
837
+
838
+ image = prepare_img()
839
+ inputs = processor(
840
+ text=[["a photo of a cat", "a photo of a dog"]],
841
+ images=image,
842
+ max_length=16,
843
+ padding="max_length",
844
+ return_tensors="pt",
845
+ ).to(torch_device)
846
+
847
+ # forward pass
848
+ with torch.no_grad():
849
+ outputs = model(**inputs, interpolate_pos_encoding=True)
850
+
851
+ # verify the logits
852
+ self.assertEqual(
853
+ outputs.logits_per_image.shape,
854
+ torch.Size((inputs.pixel_values.shape[0], inputs.input_ids.shape[0])),
855
+ )
856
+ self.assertEqual(
857
+ outputs.logits_per_text.shape,
858
+ torch.Size((inputs.input_ids.shape[0], inputs.pixel_values.shape[0])),
859
+ )
860
+ expected_logits = torch.tensor([[-6.2520, -8.2970]], device=torch_device)
861
+ self.assertTrue(torch.allclose(outputs.logits_per_image, expected_logits, atol=1e-3))
862
+ expected_shape = torch.Size((1, 4097, 768))
863
+ self.assertEqual(outputs.vision_model_output.last_hidden_state.shape, expected_shape)
864
+
865
+ # Owlv2ForObjectDetection part.
866
+ model = Owlv2ForObjectDetection.from_pretrained(model_name).to(torch_device)
867
+ processor.image_processor.size = {"height": 1024, "width": 1024}
868
+
869
+ with torch.no_grad():
870
+ outputs = model(**inputs, interpolate_pos_encoding=True)
871
+
872
+ num_queries = int((inputs.pixel_values.shape[-1] / model.config.vision_config.patch_size) ** 2)
873
+ self.assertEqual(outputs.pred_boxes.shape, torch.Size((1, num_queries, 4)))
874
+ expected_slice_boxes = torch.tensor(
875
+ [[0.2407, 0.0553, 0.4636], [0.1082, 0.0494, 0.1861], [0.2459, 0.0527, 0.4398]]
876
+ ).to(torch_device)
877
+ self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3], expected_slice_boxes, atol=1e-4))
878
+
879
+ model = Owlv2ForObjectDetection.from_pretrained(model_name).to(torch_device)
880
+ query_image = prepare_img()
881
+ inputs = processor(
882
+ images=image,
883
+ query_images=query_image,
884
+ max_length=16,
885
+ padding="max_length",
886
+ return_tensors="pt",
887
+ ).to(torch_device)
888
+
889
+ with torch.no_grad():
890
+ outputs = model.image_guided_detection(**inputs, interpolate_pos_encoding=True)
891
+
892
+ # No need to check the logits, we just check inference runs fine.
893
+ num_queries = int((inputs.pixel_values.shape[-1] / model.config.vision_config.patch_size) ** 2)
894
+ self.assertEqual(outputs.target_pred_boxes.shape, torch.Size((1, num_queries, 4)))
895
+
896
+ # Deactivate interpolate_pos_encoding on same model, and use default image size.
897
+ # Verify the dynamic change caused by the activation/deactivation of interpolate_pos_encoding of variables: self.sqrt_num_patches, self.box_bias from (OwlViTForObjectDetection).
898
+ processor = OwlViTProcessor.from_pretrained(model_name)
899
+
900
+ image = prepare_img()
901
+ inputs = processor(
902
+ text=[["a photo of a cat", "a photo of a dog"]],
903
+ images=image,
904
+ max_length=16,
905
+ padding="max_length",
906
+ return_tensors="pt",
907
+ ).to(torch_device)
908
+
909
+ with torch.no_grad():
910
+ outputs = model(**inputs, interpolate_pos_encoding=False)
911
+
912
+ num_queries = int((inputs.pixel_values.shape[-1] // model.config.vision_config.patch_size) ** 2)
913
+ self.assertEqual(outputs.pred_boxes.shape, torch.Size((1, num_queries, 4)))
914
+
915
+ expected_default_box_bias = torch.tensor(
916
+ [
917
+ [-4.0717, -4.0717, -4.0717, -4.0717],
918
+ [-3.3644, -4.0717, -4.0717, -4.0717],
919
+ [-2.9425, -4.0717, -4.0717, -4.0717],
920
+ ]
921
+ )
922
+
923
+ self.assertTrue(torch.allclose(model.box_bias[:3, :4], expected_default_box_bias, atol=1e-4))
924
+
925
+ # Interpolate with any resolution size.
926
+ processor.image_processor.size = {"height": 1264, "width": 1024}
927
+
928
+ image = prepare_img()
929
+ inputs = processor(
930
+ text=[["a photo of a cat", "a photo of a dog"]],
931
+ images=image,
932
+ max_length=16,
933
+ padding="max_length",
934
+ return_tensors="pt",
935
+ ).to(torch_device)
936
+
937
+ with torch.no_grad():
938
+ outputs = model(**inputs, interpolate_pos_encoding=True)
939
+
940
+ num_queries = int(
941
+ (inputs.pixel_values.shape[-2] // model.config.vision_config.patch_size)
942
+ * (inputs.pixel_values.shape[-1] // model.config.vision_config.patch_size)
943
+ )
944
+ self.assertEqual(outputs.pred_boxes.shape, torch.Size((1, num_queries, 4)))
945
+ expected_slice_boxes = torch.tensor(
946
+ [[0.2438, 0.0945, 0.4675], [0.1361, 0.0431, 0.2406], [0.2465, 0.0428, 0.4429]]
947
+ ).to(torch_device)
948
+ self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3], expected_slice_boxes, atol=1e-4))
949
+
950
+ query_image = prepare_img()
951
+ inputs = processor(
952
+ images=image,
953
+ query_images=query_image,
954
+ max_length=16,
955
+ padding="max_length",
956
+ return_tensors="pt",
957
+ ).to(torch_device)
958
+
959
+ with torch.no_grad():
960
+ outputs = model.image_guided_detection(**inputs, interpolate_pos_encoding=True)
961
+
962
+ # No need to check the logits, we just check inference runs fine.
963
+ num_queries = int(
964
+ (inputs.pixel_values.shape[-2] // model.config.vision_config.patch_size)
965
+ * (inputs.pixel_values.shape[-1] // model.config.vision_config.patch_size)
966
+ )
967
+ self.assertEqual(outputs.target_pred_boxes.shape, torch.Size((1, num_queries, 4)))
968
+
969
+ @slow
970
+ def test_inference_object_detection(self):
971
+ model_name = "google/owlv2-base-patch16"
972
+ model = Owlv2ForObjectDetection.from_pretrained(model_name).to(torch_device)
973
+
974
+ processor = OwlViTProcessor.from_pretrained(model_name)
975
+
976
+ image = prepare_img()
977
+ inputs = processor(
978
+ text=[["a photo of a cat", "a photo of a dog"]],
979
+ images=image,
980
+ max_length=16,
981
+ padding="max_length",
982
+ return_tensors="pt",
983
+ ).to(torch_device)
984
+
985
+ with torch.no_grad():
986
+ outputs = model(**inputs)
987
+
988
+ num_queries = int((model.config.vision_config.image_size / model.config.vision_config.patch_size) ** 2)
989
+ self.assertEqual(outputs.pred_boxes.shape, torch.Size((1, num_queries, 4)))
990
+
991
+ expected_slice_logits = torch.tensor(
992
+ [[-21.413497, -21.612638], [-19.008193, -19.548841], [-20.958896, -21.382694]]
993
+ ).to(torch_device)
994
+ self.assertTrue(torch.allclose(outputs.logits[0, :3, :3], expected_slice_logits, atol=1e-4))
995
+ expected_slice_boxes = torch.tensor(
996
+ [[0.241309, 0.051896, 0.453267], [0.139474, 0.045701, 0.250660], [0.233022, 0.050479, 0.427671]],
997
+ ).to(torch_device)
998
+ self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3], expected_slice_boxes, atol=1e-4))
999
+
1000
+ @slow
1001
+ def test_inference_one_shot_object_detection(self):
1002
+ model_name = "google/owlv2-base-patch16"
1003
+ model = Owlv2ForObjectDetection.from_pretrained(model_name).to(torch_device)
1004
+
1005
+ processor = OwlViTProcessor.from_pretrained(model_name)
1006
+
1007
+ image = prepare_img()
1008
+ query_image = prepare_img()
1009
+ inputs = processor(
1010
+ images=image,
1011
+ query_images=query_image,
1012
+ max_length=16,
1013
+ padding="max_length",
1014
+ return_tensors="pt",
1015
+ ).to(torch_device)
1016
+
1017
+ with torch.no_grad():
1018
+ outputs = model.image_guided_detection(**inputs)
1019
+
1020
+ num_queries = int((model.config.vision_config.image_size / model.config.vision_config.patch_size) ** 2)
1021
+ self.assertEqual(outputs.target_pred_boxes.shape, torch.Size((1, num_queries, 4)))
1022
+
1023
+ expected_slice_boxes = torch.tensor(
1024
+ [[0.2413, 0.0519, 0.4533], [0.1395, 0.0457, 0.2507], [0.2330, 0.0505, 0.4277]],
1025
+ ).to(torch_device)
1026
+ self.assertTrue(torch.allclose(outputs.target_pred_boxes[0, :3, :3], expected_slice_boxes, atol=1e-4))
1027
+
1028
+ @slow
1029
+ @require_torch_accelerator
1030
+ @require_torch_fp16
1031
+ def test_inference_one_shot_object_detection_fp16(self):
1032
+ model_name = "google/owlv2-base-patch16"
1033
+ model = Owlv2ForObjectDetection.from_pretrained(model_name, torch_dtype=torch.float16).to(torch_device)
1034
+
1035
+ processor = OwlViTProcessor.from_pretrained(model_name)
1036
+
1037
+ image = prepare_img()
1038
+ query_image = prepare_img()
1039
+ inputs = processor(
1040
+ images=image,
1041
+ query_images=query_image,
1042
+ max_length=16,
1043
+ padding="max_length",
1044
+ return_tensors="pt",
1045
+ ).to(torch_device)
1046
+
1047
+ with torch.no_grad():
1048
+ outputs = model.image_guided_detection(**inputs)
1049
+
1050
+ # No need to check the logits, we just check inference runs fine.
1051
+ num_queries = int((model.config.vision_config.image_size / model.config.vision_config.patch_size) ** 2)
1052
+ self.assertEqual(outputs.target_pred_boxes.shape, torch.Size((1, num_queries, 4)))
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/owlvit/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/owlvit/test_image_processing_owlvit.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 HuggingFace Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+
17
+ import unittest
18
+
19
+ from transformers.testing_utils import require_torch, require_vision
20
+ from transformers.utils import is_vision_available
21
+
22
+ from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs
23
+
24
+
25
+ if is_vision_available():
26
+ from transformers import OwlViTImageProcessor
27
+
28
+
29
+ class OwlViTImageProcessingTester(unittest.TestCase):
30
+ def __init__(
31
+ self,
32
+ parent,
33
+ batch_size=7,
34
+ num_channels=3,
35
+ image_size=18,
36
+ min_resolution=30,
37
+ max_resolution=400,
38
+ do_resize=True,
39
+ size=None,
40
+ do_center_crop=True,
41
+ crop_size=None,
42
+ do_normalize=True,
43
+ image_mean=[0.48145466, 0.4578275, 0.40821073],
44
+ image_std=[0.26862954, 0.26130258, 0.27577711],
45
+ do_convert_rgb=True,
46
+ ):
47
+ super().__init__()
48
+ self.parent = parent
49
+ self.batch_size = batch_size
50
+ self.num_channels = num_channels
51
+ self.image_size = image_size
52
+ self.min_resolution = min_resolution
53
+ self.max_resolution = max_resolution
54
+ self.do_resize = do_resize
55
+ self.size = size if size is not None else {"height": 18, "width": 18}
56
+ self.do_center_crop = do_center_crop
57
+ self.crop_size = crop_size if crop_size is not None else {"height": 18, "width": 18}
58
+ self.do_normalize = do_normalize
59
+ self.image_mean = image_mean
60
+ self.image_std = image_std
61
+ self.do_convert_rgb = do_convert_rgb
62
+
63
+ def prepare_image_processor_dict(self):
64
+ return {
65
+ "do_resize": self.do_resize,
66
+ "size": self.size,
67
+ "do_center_crop": self.do_center_crop,
68
+ "crop_size": self.crop_size,
69
+ "do_normalize": self.do_normalize,
70
+ "image_mean": self.image_mean,
71
+ "image_std": self.image_std,
72
+ "do_convert_rgb": self.do_convert_rgb,
73
+ }
74
+
75
+ def expected_output_image_shape(self, images):
76
+ return self.num_channels, self.crop_size["height"], self.crop_size["width"]
77
+
78
+ def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
79
+ return prepare_image_inputs(
80
+ batch_size=self.batch_size,
81
+ num_channels=self.num_channels,
82
+ min_resolution=self.min_resolution,
83
+ max_resolution=self.max_resolution,
84
+ equal_resolution=equal_resolution,
85
+ numpify=numpify,
86
+ torchify=torchify,
87
+ )
88
+
89
+
90
+ @require_torch
91
+ @require_vision
92
+ class OwlViTImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
93
+ image_processing_class = OwlViTImageProcessor if is_vision_available() else None
94
+
95
+ def setUp(self):
96
+ super().setUp()
97
+ self.image_processor_tester = OwlViTImageProcessingTester(self)
98
+
99
+ @property
100
+ def image_processor_dict(self):
101
+ return self.image_processor_tester.prepare_image_processor_dict()
102
+
103
+ def test_image_processor_properties(self):
104
+ image_processing = self.image_processing_class(**self.image_processor_dict)
105
+ self.assertTrue(hasattr(image_processing, "do_resize"))
106
+ self.assertTrue(hasattr(image_processing, "size"))
107
+ self.assertTrue(hasattr(image_processing, "do_center_crop"))
108
+ self.assertTrue(hasattr(image_processing, "center_crop"))
109
+ self.assertTrue(hasattr(image_processing, "do_normalize"))
110
+ self.assertTrue(hasattr(image_processing, "image_mean"))
111
+ self.assertTrue(hasattr(image_processing, "image_std"))
112
+ self.assertTrue(hasattr(image_processing, "do_convert_rgb"))
113
+
114
+ def test_image_processor_from_dict_with_kwargs(self):
115
+ image_processor = self.image_processing_class.from_dict(self.image_processor_dict)
116
+ self.assertEqual(image_processor.size, {"height": 18, "width": 18})
117
+ self.assertEqual(image_processor.crop_size, {"height": 18, "width": 18})
118
+
119
+ image_processor = self.image_processing_class.from_dict(self.image_processor_dict, size=42, crop_size=84)
120
+ self.assertEqual(image_processor.size, {"height": 42, "width": 42})
121
+ self.assertEqual(image_processor.crop_size, {"height": 84, "width": 84})
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/owlvit/test_modeling_owlvit.py ADDED
@@ -0,0 +1,1041 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 OwlViT model."""
16
+
17
+ import inspect
18
+ import os
19
+ import tempfile
20
+ import unittest
21
+
22
+ import numpy as np
23
+ import requests
24
+
25
+ from transformers import OwlViTConfig, OwlViTTextConfig, OwlViTVisionConfig
26
+ from transformers.testing_utils import (
27
+ require_torch,
28
+ require_torch_accelerator,
29
+ require_torch_fp16,
30
+ require_vision,
31
+ slow,
32
+ torch_device,
33
+ )
34
+ from transformers.utils import is_torch_available, is_vision_available
35
+
36
+ from ...test_configuration_common import ConfigTester
37
+ from ...test_modeling_common import (
38
+ ModelTesterMixin,
39
+ _config_zero_init,
40
+ floats_tensor,
41
+ ids_tensor,
42
+ random_attention_mask,
43
+ )
44
+ from ...test_pipeline_mixin import PipelineTesterMixin
45
+
46
+
47
+ if is_torch_available():
48
+ import torch
49
+ from torch import nn
50
+
51
+ from transformers import OwlViTForObjectDetection, OwlViTModel, OwlViTTextModel, OwlViTVisionModel
52
+
53
+
54
+ if is_vision_available():
55
+ from PIL import Image
56
+
57
+ from transformers import OwlViTProcessor
58
+
59
+
60
+ class OwlViTVisionModelTester:
61
+ def __init__(
62
+ self,
63
+ parent,
64
+ batch_size=12,
65
+ image_size=32,
66
+ patch_size=2,
67
+ num_channels=3,
68
+ is_training=True,
69
+ hidden_size=32,
70
+ num_hidden_layers=2,
71
+ num_attention_heads=4,
72
+ intermediate_size=37,
73
+ dropout=0.1,
74
+ attention_dropout=0.1,
75
+ initializer_range=0.02,
76
+ scope=None,
77
+ ):
78
+ self.parent = parent
79
+ self.batch_size = batch_size
80
+ self.image_size = image_size
81
+ self.patch_size = patch_size
82
+ self.num_channels = num_channels
83
+ self.is_training = is_training
84
+ self.hidden_size = hidden_size
85
+ self.num_hidden_layers = num_hidden_layers
86
+ self.num_attention_heads = num_attention_heads
87
+ self.intermediate_size = intermediate_size
88
+ self.dropout = dropout
89
+ self.attention_dropout = attention_dropout
90
+ self.initializer_range = initializer_range
91
+ self.scope = scope
92
+
93
+ # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
94
+ num_patches = (image_size // patch_size) ** 2
95
+ self.seq_length = num_patches + 1
96
+
97
+ def prepare_config_and_inputs(self):
98
+ pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
99
+ config = self.get_config()
100
+
101
+ return config, pixel_values
102
+
103
+ def get_config(self):
104
+ return OwlViTVisionConfig(
105
+ image_size=self.image_size,
106
+ patch_size=self.patch_size,
107
+ num_channels=self.num_channels,
108
+ hidden_size=self.hidden_size,
109
+ num_hidden_layers=self.num_hidden_layers,
110
+ num_attention_heads=self.num_attention_heads,
111
+ intermediate_size=self.intermediate_size,
112
+ dropout=self.dropout,
113
+ attention_dropout=self.attention_dropout,
114
+ initializer_range=self.initializer_range,
115
+ )
116
+
117
+ def create_and_check_model(self, config, pixel_values):
118
+ model = OwlViTVisionModel(config=config).to(torch_device)
119
+ model.eval()
120
+
121
+ pixel_values = pixel_values.to(torch.float32)
122
+
123
+ with torch.no_grad():
124
+ result = model(pixel_values)
125
+ # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
126
+ num_patches = (self.image_size // self.patch_size) ** 2
127
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, num_patches + 1, self.hidden_size))
128
+ self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
129
+
130
+ def prepare_config_and_inputs_for_common(self):
131
+ config_and_inputs = self.prepare_config_and_inputs()
132
+ config, pixel_values = config_and_inputs
133
+ inputs_dict = {"pixel_values": pixel_values}
134
+ return config, inputs_dict
135
+
136
+
137
+ @require_torch
138
+ class OwlViTVisionModelTest(ModelTesterMixin, unittest.TestCase):
139
+ """
140
+ Here we also overwrite some of the tests of test_modeling_common.py, as OWLVIT does not use input_ids, inputs_embeds,
141
+ attention_mask and seq_length.
142
+ """
143
+
144
+ all_model_classes = (OwlViTVisionModel,) if is_torch_available() else ()
145
+ fx_compatible = False
146
+ test_pruning = False
147
+ test_resize_embeddings = False
148
+ test_head_masking = False
149
+
150
+ def setUp(self):
151
+ self.model_tester = OwlViTVisionModelTester(self)
152
+ self.config_tester = ConfigTester(
153
+ self, config_class=OwlViTVisionConfig, has_text_modality=False, hidden_size=37
154
+ )
155
+
156
+ def test_config(self):
157
+ self.config_tester.run_common_tests()
158
+
159
+ @unittest.skip(reason="OWLVIT does not use inputs_embeds")
160
+ def test_inputs_embeds(self):
161
+ pass
162
+
163
+ def test_model_get_set_embeddings(self):
164
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
165
+
166
+ for model_class in self.all_model_classes:
167
+ model = model_class(config)
168
+ self.assertIsInstance(model.get_input_embeddings(), (nn.Module))
169
+ x = model.get_output_embeddings()
170
+ self.assertTrue(x is None or isinstance(x, nn.Linear))
171
+
172
+ def test_forward_signature(self):
173
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
174
+
175
+ for model_class in self.all_model_classes:
176
+ model = model_class(config)
177
+ signature = inspect.signature(model.forward)
178
+ # signature.parameters is an OrderedDict => so arg_names order is deterministic
179
+ arg_names = [*signature.parameters.keys()]
180
+
181
+ expected_arg_names = ["pixel_values"]
182
+ self.assertListEqual(arg_names[:1], expected_arg_names)
183
+
184
+ def test_model(self):
185
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
186
+ self.model_tester.create_and_check_model(*config_and_inputs)
187
+
188
+ @unittest.skip(reason="OWL-ViT does not support training yet")
189
+ def test_training(self):
190
+ pass
191
+
192
+ @unittest.skip(reason="OWL-ViT does not support training yet")
193
+ def test_training_gradient_checkpointing(self):
194
+ pass
195
+
196
+ @unittest.skip(
197
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
198
+ )
199
+ def test_training_gradient_checkpointing_use_reentrant(self):
200
+ pass
201
+
202
+ @unittest.skip(
203
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
204
+ )
205
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
206
+ pass
207
+
208
+ @unittest.skip(reason="OwlViTVisionModel has no base class and is not available in MODEL_MAPPING")
209
+ def test_save_load_fast_init_from_base(self):
210
+ pass
211
+
212
+ @unittest.skip(reason="OwlViTVisionModel has no base class and is not available in MODEL_MAPPING")
213
+ def test_save_load_fast_init_to_base(self):
214
+ pass
215
+
216
+ @slow
217
+ def test_model_from_pretrained(self):
218
+ model_name = "google/owlvit-base-patch32"
219
+ model = OwlViTVisionModel.from_pretrained(model_name)
220
+ self.assertIsNotNone(model)
221
+
222
+
223
+ class OwlViTTextModelTester:
224
+ def __init__(
225
+ self,
226
+ parent,
227
+ batch_size=12,
228
+ num_queries=4,
229
+ seq_length=16,
230
+ is_training=True,
231
+ use_input_mask=True,
232
+ use_labels=True,
233
+ vocab_size=99,
234
+ hidden_size=64,
235
+ num_hidden_layers=12,
236
+ num_attention_heads=4,
237
+ intermediate_size=37,
238
+ dropout=0.1,
239
+ attention_dropout=0.1,
240
+ max_position_embeddings=16,
241
+ initializer_range=0.02,
242
+ scope=None,
243
+ ):
244
+ self.parent = parent
245
+ self.batch_size = batch_size
246
+ self.num_queries = num_queries
247
+ self.seq_length = seq_length
248
+ self.is_training = is_training
249
+ self.use_input_mask = use_input_mask
250
+ self.use_labels = use_labels
251
+ self.vocab_size = vocab_size
252
+ self.hidden_size = hidden_size
253
+ self.num_hidden_layers = num_hidden_layers
254
+ self.num_attention_heads = num_attention_heads
255
+ self.intermediate_size = intermediate_size
256
+ self.dropout = dropout
257
+ self.attention_dropout = attention_dropout
258
+ self.max_position_embeddings = max_position_embeddings
259
+ self.initializer_range = initializer_range
260
+ self.scope = scope
261
+
262
+ def prepare_config_and_inputs(self):
263
+ input_ids = ids_tensor([self.batch_size * self.num_queries, self.seq_length], self.vocab_size)
264
+ input_mask = None
265
+
266
+ if self.use_input_mask:
267
+ input_mask = random_attention_mask([self.batch_size * self.num_queries, self.seq_length])
268
+
269
+ if input_mask is not None:
270
+ num_text, seq_length = input_mask.shape
271
+
272
+ rnd_start_indices = np.random.randint(1, seq_length - 1, size=(num_text,))
273
+ for idx, start_index in enumerate(rnd_start_indices):
274
+ input_mask[idx, :start_index] = 1
275
+ input_mask[idx, start_index:] = 0
276
+
277
+ config = self.get_config()
278
+
279
+ return config, input_ids, input_mask
280
+
281
+ def get_config(self):
282
+ return OwlViTTextConfig(
283
+ vocab_size=self.vocab_size,
284
+ hidden_size=self.hidden_size,
285
+ num_hidden_layers=self.num_hidden_layers,
286
+ num_attention_heads=self.num_attention_heads,
287
+ intermediate_size=self.intermediate_size,
288
+ dropout=self.dropout,
289
+ attention_dropout=self.attention_dropout,
290
+ max_position_embeddings=self.max_position_embeddings,
291
+ initializer_range=self.initializer_range,
292
+ )
293
+
294
+ def create_and_check_model(self, config, input_ids, input_mask):
295
+ model = OwlViTTextModel(config=config).to(torch_device)
296
+ model.eval()
297
+ with torch.no_grad():
298
+ result = model(input_ids=input_ids, attention_mask=input_mask)
299
+
300
+ self.parent.assertEqual(
301
+ result.last_hidden_state.shape, (self.batch_size * self.num_queries, self.seq_length, self.hidden_size)
302
+ )
303
+ self.parent.assertEqual(result.pooler_output.shape, (self.batch_size * self.num_queries, self.hidden_size))
304
+
305
+ def prepare_config_and_inputs_for_common(self):
306
+ config_and_inputs = self.prepare_config_and_inputs()
307
+ config, input_ids, input_mask = config_and_inputs
308
+ inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
309
+ return config, inputs_dict
310
+
311
+
312
+ @require_torch
313
+ class OwlViTTextModelTest(ModelTesterMixin, unittest.TestCase):
314
+ all_model_classes = (OwlViTTextModel,) if is_torch_available() else ()
315
+ fx_compatible = False
316
+ test_pruning = False
317
+ test_head_masking = False
318
+
319
+ def setUp(self):
320
+ self.model_tester = OwlViTTextModelTester(self)
321
+ self.config_tester = ConfigTester(self, config_class=OwlViTTextConfig, hidden_size=37)
322
+
323
+ def test_config(self):
324
+ self.config_tester.run_common_tests()
325
+
326
+ def test_model(self):
327
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
328
+ self.model_tester.create_and_check_model(*config_and_inputs)
329
+
330
+ @unittest.skip(reason="OWL-ViT does not support training yet")
331
+ def test_training(self):
332
+ pass
333
+
334
+ @unittest.skip(reason="OWL-ViT does not support training yet")
335
+ def test_training_gradient_checkpointing(self):
336
+ pass
337
+
338
+ @unittest.skip(
339
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
340
+ )
341
+ def test_training_gradient_checkpointing_use_reentrant(self):
342
+ pass
343
+
344
+ @unittest.skip(
345
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
346
+ )
347
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
348
+ pass
349
+
350
+ @unittest.skip(reason="OWLVIT does not use inputs_embeds")
351
+ def test_inputs_embeds(self):
352
+ pass
353
+
354
+ @unittest.skip(reason="OwlViTTextModel has no base class and is not available in MODEL_MAPPING")
355
+ def test_save_load_fast_init_from_base(self):
356
+ pass
357
+
358
+ @unittest.skip(reason="OwlViTTextModel has no base class and is not available in MODEL_MAPPING")
359
+ def test_save_load_fast_init_to_base(self):
360
+ pass
361
+
362
+ @slow
363
+ def test_model_from_pretrained(self):
364
+ model_name = "google/owlvit-base-patch32"
365
+ model = OwlViTTextModel.from_pretrained(model_name)
366
+ self.assertIsNotNone(model)
367
+
368
+
369
+ class OwlViTModelTester:
370
+ def __init__(self, parent, text_kwargs=None, vision_kwargs=None, is_training=True):
371
+ if text_kwargs is None:
372
+ text_kwargs = {}
373
+ if vision_kwargs is None:
374
+ vision_kwargs = {}
375
+
376
+ self.parent = parent
377
+ self.text_model_tester = OwlViTTextModelTester(parent, **text_kwargs)
378
+ self.vision_model_tester = OwlViTVisionModelTester(parent, **vision_kwargs)
379
+ self.is_training = is_training
380
+ self.text_config = self.text_model_tester.get_config().to_dict()
381
+ self.vision_config = self.vision_model_tester.get_config().to_dict()
382
+ self.batch_size = self.text_model_tester.batch_size # need bs for batching_equivalence test
383
+
384
+ def prepare_config_and_inputs(self):
385
+ text_config, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs()
386
+ vision_config, pixel_values = self.vision_model_tester.prepare_config_and_inputs()
387
+ config = self.get_config()
388
+ return config, input_ids, attention_mask, pixel_values
389
+
390
+ def get_config(self):
391
+ return OwlViTConfig.from_text_vision_configs(self.text_config, self.vision_config, projection_dim=64)
392
+
393
+ def create_and_check_model(self, config, input_ids, attention_mask, pixel_values):
394
+ model = OwlViTModel(config).to(torch_device).eval()
395
+
396
+ with torch.no_grad():
397
+ result = model(
398
+ input_ids=input_ids,
399
+ pixel_values=pixel_values,
400
+ attention_mask=attention_mask,
401
+ )
402
+
403
+ image_logits_size = (
404
+ self.vision_model_tester.batch_size,
405
+ self.text_model_tester.batch_size * self.text_model_tester.num_queries,
406
+ )
407
+ text_logits_size = (
408
+ self.text_model_tester.batch_size * self.text_model_tester.num_queries,
409
+ self.vision_model_tester.batch_size,
410
+ )
411
+ self.parent.assertEqual(result.logits_per_image.shape, image_logits_size)
412
+ self.parent.assertEqual(result.logits_per_text.shape, text_logits_size)
413
+
414
+ def prepare_config_and_inputs_for_common(self):
415
+ config_and_inputs = self.prepare_config_and_inputs()
416
+ config, input_ids, attention_mask, pixel_values = config_and_inputs
417
+ inputs_dict = {
418
+ "pixel_values": pixel_values,
419
+ "input_ids": input_ids,
420
+ "attention_mask": attention_mask,
421
+ "return_loss": False,
422
+ }
423
+ return config, inputs_dict
424
+
425
+
426
+ @require_torch
427
+ class OwlViTModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
428
+ all_model_classes = (OwlViTModel,) if is_torch_available() else ()
429
+ pipeline_model_mapping = (
430
+ {
431
+ "feature-extraction": OwlViTModel,
432
+ "zero-shot-object-detection": OwlViTForObjectDetection,
433
+ }
434
+ if is_torch_available()
435
+ else {}
436
+ )
437
+ fx_compatible = False
438
+ test_head_masking = False
439
+ test_pruning = False
440
+ test_resize_embeddings = False
441
+ test_attention_outputs = False
442
+
443
+ def setUp(self):
444
+ self.model_tester = OwlViTModelTester(self)
445
+ common_properties = ["projection_dim", "logit_scale_init_value"]
446
+ self.config_tester = ConfigTester(
447
+ self, config_class=OwlViTConfig, has_text_modality=False, common_properties=common_properties
448
+ )
449
+
450
+ def test_config(self):
451
+ self.config_tester.run_common_tests()
452
+
453
+ def test_model(self):
454
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
455
+ self.model_tester.create_and_check_model(*config_and_inputs)
456
+
457
+ @unittest.skip(reason="Hidden_states is tested in individual model tests")
458
+ def test_hidden_states_output(self):
459
+ pass
460
+
461
+ @unittest.skip(reason="Inputs_embeds is tested in individual model tests")
462
+ def test_inputs_embeds(self):
463
+ pass
464
+
465
+ @unittest.skip(reason="Retain_grad is tested in individual model tests")
466
+ def test_retain_grad_hidden_states_attentions(self):
467
+ pass
468
+
469
+ @unittest.skip(reason="OwlViTModel does not have input/output embeddings")
470
+ def test_model_get_set_embeddings(self):
471
+ pass
472
+
473
+ # override as the `logit_scale` parameter initilization is different for OWLVIT
474
+ def test_initialization(self):
475
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
476
+
477
+ configs_no_init = _config_zero_init(config)
478
+ for model_class in self.all_model_classes:
479
+ model = model_class(config=configs_no_init)
480
+ for name, param in model.named_parameters():
481
+ if param.requires_grad:
482
+ # check if `logit_scale` is initilized as per the original implementation
483
+ if name == "logit_scale":
484
+ self.assertAlmostEqual(
485
+ param.data.item(),
486
+ np.log(1 / 0.07),
487
+ delta=1e-3,
488
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
489
+ )
490
+ else:
491
+ self.assertIn(
492
+ ((param.data.mean() * 1e9).round() / 1e9).item(),
493
+ [0.0, 1.0],
494
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
495
+ )
496
+
497
+ def _create_and_check_torchscript(self, config, inputs_dict):
498
+ if not self.test_torchscript:
499
+ self.skipTest(reason="test_torchscript is set to False")
500
+
501
+ configs_no_init = _config_zero_init(config) # To be sure we have no Nan
502
+ configs_no_init.torchscript = True
503
+ configs_no_init.return_dict = False
504
+ for model_class in self.all_model_classes:
505
+ model = model_class(config=configs_no_init).to(torch_device)
506
+ model.eval()
507
+
508
+ try:
509
+ input_ids = inputs_dict["input_ids"]
510
+ pixel_values = inputs_dict["pixel_values"] # OWLVIT needs pixel_values
511
+ traced_model = torch.jit.trace(model, (input_ids, pixel_values))
512
+ except RuntimeError:
513
+ self.fail("Couldn't trace module.")
514
+
515
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
516
+ pt_file_name = os.path.join(tmp_dir_name, "traced_model.pt")
517
+
518
+ try:
519
+ torch.jit.save(traced_model, pt_file_name)
520
+ except Exception:
521
+ self.fail("Couldn't save module.")
522
+
523
+ try:
524
+ loaded_model = torch.jit.load(pt_file_name)
525
+ except Exception:
526
+ self.fail("Couldn't load module.")
527
+
528
+ loaded_model = loaded_model.to(torch_device)
529
+ loaded_model.eval()
530
+
531
+ model_state_dict = model.state_dict()
532
+ loaded_model_state_dict = loaded_model.state_dict()
533
+
534
+ non_persistent_buffers = {}
535
+ for key in loaded_model_state_dict.keys():
536
+ if key not in model_state_dict.keys():
537
+ non_persistent_buffers[key] = loaded_model_state_dict[key]
538
+
539
+ loaded_model_state_dict = {
540
+ key: value for key, value in loaded_model_state_dict.items() if key not in non_persistent_buffers
541
+ }
542
+
543
+ self.assertEqual(set(model_state_dict.keys()), set(loaded_model_state_dict.keys()))
544
+
545
+ model_buffers = list(model.buffers())
546
+ for non_persistent_buffer in non_persistent_buffers.values():
547
+ found_buffer = False
548
+ for i, model_buffer in enumerate(model_buffers):
549
+ if torch.equal(non_persistent_buffer, model_buffer):
550
+ found_buffer = True
551
+ break
552
+
553
+ self.assertTrue(found_buffer)
554
+ model_buffers.pop(i)
555
+
556
+ models_equal = True
557
+ for layer_name, p1 in model_state_dict.items():
558
+ p2 = loaded_model_state_dict[layer_name]
559
+ if p1.data.ne(p2.data).sum() > 0:
560
+ models_equal = False
561
+
562
+ self.assertTrue(models_equal)
563
+
564
+ def test_load_vision_text_config(self):
565
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
566
+
567
+ # Save OwlViTConfig and check if we can load OwlViTVisionConfig from it
568
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
569
+ config.save_pretrained(tmp_dir_name)
570
+ vision_config = OwlViTVisionConfig.from_pretrained(tmp_dir_name)
571
+ self.assertDictEqual(config.vision_config.to_dict(), vision_config.to_dict())
572
+
573
+ # Save OwlViTConfig and check if we can load OwlViTTextConfig from it
574
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
575
+ config.save_pretrained(tmp_dir_name)
576
+ text_config = OwlViTTextConfig.from_pretrained(tmp_dir_name)
577
+ self.assertDictEqual(config.text_config.to_dict(), text_config.to_dict())
578
+
579
+ @slow
580
+ def test_model_from_pretrained(self):
581
+ model_name = "google/owlvit-base-patch32"
582
+ model = OwlViTModel.from_pretrained(model_name)
583
+ self.assertIsNotNone(model)
584
+
585
+
586
+ class OwlViTForObjectDetectionTester:
587
+ def __init__(self, parent, is_training=True):
588
+ self.parent = parent
589
+ self.text_model_tester = OwlViTTextModelTester(parent)
590
+ self.vision_model_tester = OwlViTVisionModelTester(parent)
591
+ self.is_training = is_training
592
+ self.text_config = self.text_model_tester.get_config().to_dict()
593
+ self.vision_config = self.vision_model_tester.get_config().to_dict()
594
+ self.batch_size = self.text_model_tester.batch_size # need bs for batching_equivalence test
595
+
596
+ def prepare_config_and_inputs(self):
597
+ text_config, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs()
598
+ vision_config, pixel_values = self.vision_model_tester.prepare_config_and_inputs()
599
+ config = self.get_config()
600
+ return config, pixel_values, input_ids, attention_mask
601
+
602
+ def get_config(self):
603
+ return OwlViTConfig.from_text_vision_configs(self.text_config, self.vision_config, projection_dim=64)
604
+
605
+ def create_and_check_model(self, config, pixel_values, input_ids, attention_mask):
606
+ model = OwlViTForObjectDetection(config).to(torch_device).eval()
607
+ with torch.no_grad():
608
+ result = model(
609
+ pixel_values=pixel_values,
610
+ input_ids=input_ids,
611
+ attention_mask=attention_mask,
612
+ return_dict=True,
613
+ )
614
+
615
+ pred_boxes_size = (
616
+ self.vision_model_tester.batch_size,
617
+ (self.vision_model_tester.image_size // self.vision_model_tester.patch_size) ** 2,
618
+ 4,
619
+ )
620
+ pred_logits_size = (
621
+ self.vision_model_tester.batch_size,
622
+ (self.vision_model_tester.image_size // self.vision_model_tester.patch_size) ** 2,
623
+ 4,
624
+ )
625
+ pred_class_embeds_size = (
626
+ self.vision_model_tester.batch_size,
627
+ (self.vision_model_tester.image_size // self.vision_model_tester.patch_size) ** 2,
628
+ self.text_model_tester.hidden_size,
629
+ )
630
+ self.parent.assertEqual(result.pred_boxes.shape, pred_boxes_size)
631
+ self.parent.assertEqual(result.logits.shape, pred_logits_size)
632
+ self.parent.assertEqual(result.class_embeds.shape, pred_class_embeds_size)
633
+
634
+ def prepare_config_and_inputs_for_common(self):
635
+ config_and_inputs = self.prepare_config_and_inputs()
636
+ config, pixel_values, input_ids, attention_mask = config_and_inputs
637
+ inputs_dict = {
638
+ "pixel_values": pixel_values,
639
+ "input_ids": input_ids,
640
+ "attention_mask": attention_mask,
641
+ }
642
+ return config, inputs_dict
643
+
644
+
645
+ @require_torch
646
+ class OwlViTForObjectDetectionTest(ModelTesterMixin, unittest.TestCase):
647
+ all_model_classes = (OwlViTForObjectDetection,) if is_torch_available() else ()
648
+ fx_compatible = False
649
+ test_head_masking = False
650
+ test_pruning = False
651
+ test_resize_embeddings = False
652
+ test_attention_outputs = False
653
+
654
+ def setUp(self):
655
+ self.model_tester = OwlViTForObjectDetectionTester(self)
656
+
657
+ def test_model(self):
658
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
659
+ self.model_tester.create_and_check_model(*config_and_inputs)
660
+
661
+ @unittest.skip(reason="Hidden_states is tested in individual model tests")
662
+ def test_hidden_states_output(self):
663
+ pass
664
+
665
+ @unittest.skip(reason="Inputs_embeds is tested in individual model tests")
666
+ def test_inputs_embeds(self):
667
+ pass
668
+
669
+ @unittest.skip(reason="Retain_grad is tested in individual model tests")
670
+ def test_retain_grad_hidden_states_attentions(self):
671
+ pass
672
+
673
+ @unittest.skip(reason="OwlViTModel does not have input/output embeddings")
674
+ def test_model_get_set_embeddings(self):
675
+ pass
676
+
677
+ @unittest.skip(reason="Test_initialization is tested in individual model tests")
678
+ def test_initialization(self):
679
+ pass
680
+
681
+ @unittest.skip(reason="Test_forward_signature is tested in individual model tests")
682
+ def test_forward_signature(self):
683
+ pass
684
+
685
+ @unittest.skip(reason="Test_save_load_fast_init_from_base is tested in individual model tests")
686
+ def test_save_load_fast_init_from_base(self):
687
+ pass
688
+
689
+ @unittest.skip(reason="OWL-ViT does not support training yet")
690
+ def test_training(self):
691
+ pass
692
+
693
+ @unittest.skip(reason="OWL-ViT does not support training yet")
694
+ def test_training_gradient_checkpointing(self):
695
+ pass
696
+
697
+ @unittest.skip(
698
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
699
+ )
700
+ def test_training_gradient_checkpointing_use_reentrant(self):
701
+ pass
702
+
703
+ @unittest.skip(
704
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
705
+ )
706
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
707
+ pass
708
+
709
+ def _create_and_check_torchscript(self, config, inputs_dict):
710
+ if not self.test_torchscript:
711
+ self.skipTest(reason="test_torchscript is set to False")
712
+
713
+ configs_no_init = _config_zero_init(config) # To be sure we have no Nan
714
+ configs_no_init.torchscript = True
715
+ configs_no_init.return_dict = False
716
+ for model_class in self.all_model_classes:
717
+ model = model_class(config=configs_no_init).to(torch_device)
718
+ model.eval()
719
+
720
+ try:
721
+ input_ids = inputs_dict["input_ids"]
722
+ pixel_values = inputs_dict["pixel_values"] # OWLVIT needs pixel_values
723
+ traced_model = torch.jit.trace(model, (input_ids, pixel_values))
724
+ except RuntimeError:
725
+ self.fail("Couldn't trace module.")
726
+
727
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
728
+ pt_file_name = os.path.join(tmp_dir_name, "traced_model.pt")
729
+
730
+ try:
731
+ torch.jit.save(traced_model, pt_file_name)
732
+ except Exception:
733
+ self.fail("Couldn't save module.")
734
+
735
+ try:
736
+ loaded_model = torch.jit.load(pt_file_name)
737
+ except Exception:
738
+ self.fail("Couldn't load module.")
739
+
740
+ loaded_model = loaded_model.to(torch_device)
741
+ loaded_model.eval()
742
+
743
+ model_state_dict = model.state_dict()
744
+ loaded_model_state_dict = loaded_model.state_dict()
745
+
746
+ non_persistent_buffers = {}
747
+ for key in loaded_model_state_dict.keys():
748
+ if key not in model_state_dict.keys():
749
+ non_persistent_buffers[key] = loaded_model_state_dict[key]
750
+
751
+ loaded_model_state_dict = {
752
+ key: value for key, value in loaded_model_state_dict.items() if key not in non_persistent_buffers
753
+ }
754
+
755
+ self.assertEqual(set(model_state_dict.keys()), set(loaded_model_state_dict.keys()))
756
+
757
+ model_buffers = list(model.buffers())
758
+ for non_persistent_buffer in non_persistent_buffers.values():
759
+ found_buffer = False
760
+ for i, model_buffer in enumerate(model_buffers):
761
+ if torch.equal(non_persistent_buffer, model_buffer):
762
+ found_buffer = True
763
+ break
764
+
765
+ self.assertTrue(found_buffer)
766
+ model_buffers.pop(i)
767
+
768
+ models_equal = True
769
+ for layer_name, p1 in model_state_dict.items():
770
+ p2 = loaded_model_state_dict[layer_name]
771
+ if p1.data.ne(p2.data).sum() > 0:
772
+ models_equal = False
773
+
774
+ self.assertTrue(models_equal)
775
+
776
+ @slow
777
+ def test_model_from_pretrained(self):
778
+ model_name = "google/owlvit-base-patch32"
779
+ model = OwlViTForObjectDetection.from_pretrained(model_name)
780
+ self.assertIsNotNone(model)
781
+
782
+
783
+ # We will verify our results on an image of cute cats
784
+ def prepare_img():
785
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
786
+ im = Image.open(requests.get(url, stream=True).raw)
787
+ return im
788
+
789
+
790
+ @require_vision
791
+ @require_torch
792
+ class OwlViTModelIntegrationTest(unittest.TestCase):
793
+ @slow
794
+ def test_inference(self):
795
+ model_name = "google/owlvit-base-patch32"
796
+ model = OwlViTModel.from_pretrained(model_name).to(torch_device)
797
+ processor = OwlViTProcessor.from_pretrained(model_name)
798
+
799
+ image = prepare_img()
800
+ inputs = processor(
801
+ text=[["a photo of a cat", "a photo of a dog"]],
802
+ images=image,
803
+ max_length=16,
804
+ padding="max_length",
805
+ return_tensors="pt",
806
+ ).to(torch_device)
807
+
808
+ # forward pass
809
+ with torch.no_grad():
810
+ outputs = model(**inputs)
811
+
812
+ # verify the logits
813
+ self.assertEqual(
814
+ outputs.logits_per_image.shape,
815
+ torch.Size((inputs.pixel_values.shape[0], inputs.input_ids.shape[0])),
816
+ )
817
+ self.assertEqual(
818
+ outputs.logits_per_text.shape,
819
+ torch.Size((inputs.input_ids.shape[0], inputs.pixel_values.shape[0])),
820
+ )
821
+ expected_logits = torch.tensor([[3.4613, 0.9403]], device=torch_device)
822
+ self.assertTrue(torch.allclose(outputs.logits_per_image, expected_logits, atol=1e-3))
823
+
824
+ @slow
825
+ def test_inference_interpolate_pos_encoding(self):
826
+ model_name = "google/owlvit-base-patch32"
827
+ model = OwlViTModel.from_pretrained(model_name).to(torch_device)
828
+ processor = OwlViTProcessor.from_pretrained(model_name)
829
+ processor.image_processor.size = {"height": 800, "width": 800}
830
+
831
+ image = prepare_img()
832
+ inputs = processor(
833
+ text=[["a photo of a cat", "a photo of a dog"]],
834
+ images=image,
835
+ max_length=16,
836
+ padding="max_length",
837
+ return_tensors="pt",
838
+ ).to(torch_device)
839
+
840
+ # forward pass
841
+ with torch.no_grad():
842
+ outputs = model(**inputs, interpolate_pos_encoding=True)
843
+
844
+ # verify the logits
845
+ self.assertEqual(
846
+ outputs.logits_per_image.shape,
847
+ torch.Size((inputs.pixel_values.shape[0], inputs.input_ids.shape[0])),
848
+ )
849
+ self.assertEqual(
850
+ outputs.logits_per_text.shape,
851
+ torch.Size((inputs.input_ids.shape[0], inputs.pixel_values.shape[0])),
852
+ )
853
+ expected_logits = torch.tensor([[3.6278, 0.8861]], device=torch_device)
854
+ self.assertTrue(torch.allclose(outputs.logits_per_image, expected_logits, atol=1e-3))
855
+
856
+ expected_shape = torch.Size((1, 626, 768))
857
+ self.assertEqual(outputs.vision_model_output.last_hidden_state.shape, expected_shape)
858
+
859
+ # OwlViTForObjectDetection part.
860
+ model = OwlViTForObjectDetection.from_pretrained(model_name).to(torch_device)
861
+
862
+ with torch.no_grad():
863
+ outputs = model(**inputs, interpolate_pos_encoding=True)
864
+
865
+ num_queries = int((inputs.pixel_values.shape[-1] // model.config.vision_config.patch_size) ** 2)
866
+ self.assertEqual(outputs.pred_boxes.shape, torch.Size((1, num_queries, 4)))
867
+
868
+ expected_slice_boxes = torch.tensor(
869
+ [[0.0680, 0.0422, 0.1347], [0.2071, 0.0450, 0.4146], [0.2000, 0.0418, 0.3476]]
870
+ ).to(torch_device)
871
+ self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3], expected_slice_boxes, atol=1e-4))
872
+
873
+ model = OwlViTForObjectDetection.from_pretrained(model_name).to(torch_device)
874
+ query_image = prepare_img()
875
+ inputs = processor(
876
+ images=image,
877
+ query_images=query_image,
878
+ max_length=16,
879
+ padding="max_length",
880
+ return_tensors="pt",
881
+ ).to(torch_device)
882
+
883
+ with torch.no_grad():
884
+ outputs = model.image_guided_detection(**inputs, interpolate_pos_encoding=True)
885
+
886
+ # No need to check the logits, we just check inference runs fine.
887
+ num_queries = int((inputs.pixel_values.shape[-1] / model.config.vision_config.patch_size) ** 2)
888
+ self.assertEqual(outputs.target_pred_boxes.shape, torch.Size((1, num_queries, 4)))
889
+
890
+ # Deactivate interpolate_pos_encoding on same model, and use default image size.
891
+ # Verify the dynamic change caused by the activation/deactivation of interpolate_pos_encoding of variables: (self.sqrt_num_patch_h, self.sqrt_num_patch_w), self.box_bias from (OwlViTForObjectDetection).
892
+ processor = OwlViTProcessor.from_pretrained(model_name)
893
+
894
+ image = prepare_img()
895
+ inputs = processor(
896
+ text=[["a photo of a cat", "a photo of a dog"]],
897
+ images=image,
898
+ max_length=16,
899
+ padding="max_length",
900
+ return_tensors="pt",
901
+ ).to(torch_device)
902
+
903
+ with torch.no_grad():
904
+ outputs = model(**inputs, interpolate_pos_encoding=False)
905
+
906
+ num_queries = int((inputs.pixel_values.shape[-1] // model.config.vision_config.patch_size) ** 2)
907
+ self.assertEqual(outputs.pred_boxes.shape, torch.Size((1, num_queries, 4)))
908
+
909
+ expected_default_box_bias = torch.tensor(
910
+ [
911
+ [-3.1332, -3.1332, -3.1332, -3.1332],
912
+ [-2.3968, -3.1332, -3.1332, -3.1332],
913
+ [-1.9452, -3.1332, -3.1332, -3.1332],
914
+ ]
915
+ )
916
+ self.assertTrue(torch.allclose(model.box_bias[:3, :4], expected_default_box_bias, atol=1e-4))
917
+
918
+ # Interpolate with any resolution size.
919
+ processor.image_processor.size = {"height": 1264, "width": 1024}
920
+
921
+ image = prepare_img()
922
+ inputs = processor(
923
+ text=[["a photo of a cat", "a photo of a dog"]],
924
+ images=image,
925
+ max_length=16,
926
+ padding="max_length",
927
+ return_tensors="pt",
928
+ ).to(torch_device)
929
+
930
+ with torch.no_grad():
931
+ outputs = model(**inputs, interpolate_pos_encoding=True)
932
+
933
+ num_queries = int(
934
+ (inputs.pixel_values.shape[-2] // model.config.vision_config.patch_size)
935
+ * (inputs.pixel_values.shape[-1] // model.config.vision_config.patch_size)
936
+ )
937
+ self.assertEqual(outputs.pred_boxes.shape, torch.Size((1, num_queries, 4)))
938
+ expected_slice_boxes = torch.tensor(
939
+ [[0.0499, 0.0301, 0.0983], [0.2244, 0.0365, 0.4663], [0.1387, 0.0314, 0.1859]]
940
+ ).to(torch_device)
941
+ self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3], expected_slice_boxes, atol=1e-4))
942
+
943
+ query_image = prepare_img()
944
+ inputs = processor(
945
+ images=image,
946
+ query_images=query_image,
947
+ max_length=16,
948
+ padding="max_length",
949
+ return_tensors="pt",
950
+ ).to(torch_device)
951
+
952
+ with torch.no_grad():
953
+ outputs = model.image_guided_detection(**inputs, interpolate_pos_encoding=True)
954
+
955
+ # No need to check the logits, we just check inference runs fine.
956
+ num_queries = int(
957
+ (inputs.pixel_values.shape[-2] // model.config.vision_config.patch_size)
958
+ * (inputs.pixel_values.shape[-1] // model.config.vision_config.patch_size)
959
+ )
960
+ self.assertEqual(outputs.target_pred_boxes.shape, torch.Size((1, num_queries, 4)))
961
+
962
+ @slow
963
+ def test_inference_object_detection(self):
964
+ model_name = "google/owlvit-base-patch32"
965
+ model = OwlViTForObjectDetection.from_pretrained(model_name).to(torch_device)
966
+
967
+ processor = OwlViTProcessor.from_pretrained(model_name)
968
+
969
+ image = prepare_img()
970
+ inputs = processor(
971
+ text=[["a photo of a cat", "a photo of a dog"]],
972
+ images=image,
973
+ max_length=16,
974
+ padding="max_length",
975
+ return_tensors="pt",
976
+ ).to(torch_device)
977
+
978
+ with torch.no_grad():
979
+ outputs = model(**inputs)
980
+
981
+ num_queries = int((model.config.vision_config.image_size / model.config.vision_config.patch_size) ** 2)
982
+ self.assertEqual(outputs.pred_boxes.shape, torch.Size((1, num_queries, 4)))
983
+
984
+ expected_slice_boxes = torch.tensor(
985
+ [[0.0691, 0.0445, 0.1373], [0.1592, 0.0456, 0.3192], [0.1632, 0.0423, 0.2478]]
986
+ ).to(torch_device)
987
+ self.assertTrue(torch.allclose(outputs.pred_boxes[0, :3, :3], expected_slice_boxes, atol=1e-4))
988
+
989
+ @slow
990
+ def test_inference_one_shot_object_detection(self):
991
+ model_name = "google/owlvit-base-patch32"
992
+ model = OwlViTForObjectDetection.from_pretrained(model_name).to(torch_device)
993
+
994
+ processor = OwlViTProcessor.from_pretrained(model_name)
995
+
996
+ image = prepare_img()
997
+ query_image = prepare_img()
998
+ inputs = processor(
999
+ images=image,
1000
+ query_images=query_image,
1001
+ max_length=16,
1002
+ padding="max_length",
1003
+ return_tensors="pt",
1004
+ ).to(torch_device)
1005
+
1006
+ with torch.no_grad():
1007
+ outputs = model.image_guided_detection(**inputs)
1008
+
1009
+ num_queries = int((model.config.vision_config.image_size / model.config.vision_config.patch_size) ** 2)
1010
+ self.assertEqual(outputs.target_pred_boxes.shape, torch.Size((1, num_queries, 4)))
1011
+
1012
+ expected_slice_boxes = torch.tensor(
1013
+ [[0.0691, 0.0445, 0.1373], [0.1592, 0.0456, 0.3192], [0.1632, 0.0423, 0.2478]]
1014
+ ).to(torch_device)
1015
+ self.assertTrue(torch.allclose(outputs.target_pred_boxes[0, :3, :3], expected_slice_boxes, atol=1e-4))
1016
+
1017
+ @slow
1018
+ @require_torch_accelerator
1019
+ @require_torch_fp16
1020
+ def test_inference_one_shot_object_detection_fp16(self):
1021
+ model_name = "google/owlvit-base-patch32"
1022
+ model = OwlViTForObjectDetection.from_pretrained(model_name, torch_dtype=torch.float16).to(torch_device)
1023
+
1024
+ processor = OwlViTProcessor.from_pretrained(model_name)
1025
+
1026
+ image = prepare_img()
1027
+ query_image = prepare_img()
1028
+ inputs = processor(
1029
+ images=image,
1030
+ query_images=query_image,
1031
+ max_length=16,
1032
+ padding="max_length",
1033
+ return_tensors="pt",
1034
+ ).to(torch_device)
1035
+
1036
+ with torch.no_grad():
1037
+ outputs = model.image_guided_detection(**inputs)
1038
+
1039
+ # No need to check the logits, we just check inference runs fine.
1040
+ num_queries = int((model.config.vision_config.image_size / model.config.vision_config.patch_size) ** 2)
1041
+ self.assertEqual(outputs.target_pred_boxes.shape, torch.Size((1, num_queries, 4)))
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/owlvit/test_processor_owlvit.py ADDED
@@ -0,0 +1,246 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ import json
16
+ import os
17
+ import shutil
18
+ import tempfile
19
+ import unittest
20
+
21
+ import pytest
22
+
23
+ from transformers import CLIPTokenizer, CLIPTokenizerFast
24
+ from transformers.models.clip.tokenization_clip import VOCAB_FILES_NAMES
25
+ from transformers.testing_utils import require_vision
26
+ from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available
27
+
28
+ from ...test_processing_common import ProcessorTesterMixin
29
+
30
+
31
+ if is_vision_available():
32
+ from transformers import OwlViTImageProcessor, OwlViTProcessor
33
+
34
+
35
+ @require_vision
36
+ class OwlViTProcessorTest(ProcessorTesterMixin, unittest.TestCase):
37
+ processor_class = OwlViTProcessor
38
+
39
+ def setUp(self):
40
+ self.tmpdirname = tempfile.mkdtemp()
41
+
42
+ vocab = ["", "l", "o", "w", "e", "r", "s", "t", "i", "d", "n", "lo", "l</w>", "w</w>", "r</w>", "t</w>", "low</w>", "er</w>", "lowest</w>", "newer</w>", "wider", "<unk>", "<|startoftext|>", "<|endoftext|>"] # fmt: skip
43
+ vocab_tokens = dict(zip(vocab, range(len(vocab))))
44
+ merges = ["#version: 0.2", "l o", "lo w</w>", "e r</w>", ""]
45
+ self.special_tokens_map = {"unk_token": "<unk>"}
46
+
47
+ self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"])
48
+ self.merges_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["merges_file"])
49
+ with open(self.vocab_file, "w", encoding="utf-8") as fp:
50
+ fp.write(json.dumps(vocab_tokens) + "\n")
51
+ with open(self.merges_file, "w", encoding="utf-8") as fp:
52
+ fp.write("\n".join(merges))
53
+
54
+ image_processor_map = {
55
+ "do_resize": True,
56
+ "size": 20,
57
+ "do_center_crop": True,
58
+ "crop_size": 18,
59
+ "do_normalize": True,
60
+ "image_mean": [0.48145466, 0.4578275, 0.40821073],
61
+ "image_std": [0.26862954, 0.26130258, 0.27577711],
62
+ }
63
+ self.image_processor_file = os.path.join(self.tmpdirname, IMAGE_PROCESSOR_NAME)
64
+ with open(self.image_processor_file, "w", encoding="utf-8") as fp:
65
+ json.dump(image_processor_map, fp)
66
+
67
+ def get_tokenizer(self, **kwargs):
68
+ return CLIPTokenizer.from_pretrained(self.tmpdirname, pad_token="!", **kwargs)
69
+
70
+ def get_rust_tokenizer(self, **kwargs):
71
+ return CLIPTokenizerFast.from_pretrained(self.tmpdirname, pad_token="!", **kwargs)
72
+
73
+ def get_image_processor(self, **kwargs):
74
+ return OwlViTImageProcessor.from_pretrained(self.tmpdirname, **kwargs)
75
+
76
+ def tearDown(self):
77
+ shutil.rmtree(self.tmpdirname)
78
+
79
+ def test_save_load_pretrained_default(self):
80
+ tokenizer_slow = self.get_tokenizer()
81
+ tokenizer_fast = self.get_rust_tokenizer()
82
+ image_processor = self.get_image_processor()
83
+
84
+ processor_slow = OwlViTProcessor(tokenizer=tokenizer_slow, image_processor=image_processor)
85
+ processor_slow.save_pretrained(self.tmpdirname)
86
+ processor_slow = OwlViTProcessor.from_pretrained(self.tmpdirname, use_fast=False)
87
+
88
+ processor_fast = OwlViTProcessor(tokenizer=tokenizer_fast, image_processor=image_processor)
89
+ processor_fast.save_pretrained(self.tmpdirname)
90
+ processor_fast = OwlViTProcessor.from_pretrained(self.tmpdirname)
91
+
92
+ self.assertEqual(processor_slow.tokenizer.get_vocab(), tokenizer_slow.get_vocab())
93
+ self.assertEqual(processor_fast.tokenizer.get_vocab(), tokenizer_fast.get_vocab())
94
+ self.assertEqual(tokenizer_slow.get_vocab(), tokenizer_fast.get_vocab())
95
+ self.assertIsInstance(processor_slow.tokenizer, CLIPTokenizer)
96
+ self.assertIsInstance(processor_fast.tokenizer, CLIPTokenizerFast)
97
+
98
+ self.assertEqual(processor_slow.image_processor.to_json_string(), image_processor.to_json_string())
99
+ self.assertEqual(processor_fast.image_processor.to_json_string(), image_processor.to_json_string())
100
+ self.assertIsInstance(processor_slow.image_processor, OwlViTImageProcessor)
101
+ self.assertIsInstance(processor_fast.image_processor, OwlViTImageProcessor)
102
+
103
+ def test_save_load_pretrained_additional_features(self):
104
+ processor = OwlViTProcessor(tokenizer=self.get_tokenizer(), image_processor=self.get_image_processor())
105
+ processor.save_pretrained(self.tmpdirname)
106
+
107
+ tokenizer_add_kwargs = self.get_tokenizer(bos_token="(BOS)", eos_token="(EOS)")
108
+ image_processor_add_kwargs = self.get_image_processor(do_normalize=False)
109
+
110
+ processor = OwlViTProcessor.from_pretrained(
111
+ self.tmpdirname, bos_token="(BOS)", eos_token="(EOS)", pad_token="!", do_normalize=False
112
+ )
113
+
114
+ self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab())
115
+ self.assertIsInstance(processor.tokenizer, CLIPTokenizerFast)
116
+
117
+ self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string())
118
+ self.assertIsInstance(processor.image_processor, OwlViTImageProcessor)
119
+
120
+ def test_image_processor(self):
121
+ image_processor = self.get_image_processor()
122
+ tokenizer = self.get_tokenizer()
123
+
124
+ processor = OwlViTProcessor(tokenizer=tokenizer, image_processor=image_processor)
125
+
126
+ image_input = self.prepare_image_inputs()
127
+
128
+ input_image_proc = image_processor(image_input, return_tensors="np")
129
+ input_processor = processor(images=image_input, return_tensors="np")
130
+
131
+ for key in input_image_proc.keys():
132
+ self.assertAlmostEqual(input_image_proc[key].sum(), input_processor[key].sum(), delta=1e-2)
133
+
134
+ def test_tokenizer(self):
135
+ image_processor = self.get_image_processor()
136
+ tokenizer = self.get_tokenizer()
137
+
138
+ processor = OwlViTProcessor(tokenizer=tokenizer, image_processor=image_processor)
139
+
140
+ input_str = "lower newer"
141
+
142
+ encoded_processor = processor(text=input_str, return_tensors="np")
143
+
144
+ encoded_tok = tokenizer(input_str, return_tensors="np")
145
+
146
+ for key in encoded_tok.keys():
147
+ self.assertListEqual(encoded_tok[key][0].tolist(), encoded_processor[key][0].tolist())
148
+
149
+ def test_processor(self):
150
+ image_processor = self.get_image_processor()
151
+ tokenizer = self.get_tokenizer()
152
+
153
+ processor = OwlViTProcessor(tokenizer=tokenizer, image_processor=image_processor)
154
+
155
+ input_str = "lower newer"
156
+ image_input = self.prepare_image_inputs()
157
+
158
+ inputs = processor(text=input_str, images=image_input)
159
+
160
+ self.assertListEqual(list(inputs.keys()), ["input_ids", "attention_mask", "pixel_values"])
161
+
162
+ # test if it raises when no input is passed
163
+ with pytest.raises(ValueError):
164
+ processor()
165
+
166
+ def test_processor_with_text_list(self):
167
+ model_name = "google/owlvit-base-patch32"
168
+ processor = OwlViTProcessor.from_pretrained(model_name)
169
+
170
+ input_text = ["cat", "nasa badge"]
171
+ inputs = processor(text=input_text)
172
+
173
+ seq_length = 16
174
+ self.assertListEqual(list(inputs.keys()), ["input_ids", "attention_mask"])
175
+ self.assertEqual(inputs["input_ids"].shape, (2, seq_length))
176
+
177
+ # test if it raises when no input is passed
178
+ with pytest.raises(ValueError):
179
+ processor()
180
+
181
+ def test_processor_with_nested_text_list(self):
182
+ model_name = "google/owlvit-base-patch32"
183
+ processor = OwlViTProcessor.from_pretrained(model_name)
184
+
185
+ input_texts = [["cat", "nasa badge"], ["person"]]
186
+ inputs = processor(text=input_texts)
187
+
188
+ seq_length = 16
189
+ batch_size = len(input_texts)
190
+ num_max_text_queries = max([len(texts) for texts in input_texts])
191
+
192
+ self.assertListEqual(list(inputs.keys()), ["input_ids", "attention_mask"])
193
+ self.assertEqual(inputs["input_ids"].shape, (batch_size * num_max_text_queries, seq_length))
194
+
195
+ # test if it raises when no input is passed
196
+ with pytest.raises(ValueError):
197
+ processor()
198
+
199
+ def test_processor_case(self):
200
+ model_name = "google/owlvit-base-patch32"
201
+ processor = OwlViTProcessor.from_pretrained(model_name)
202
+
203
+ input_texts = ["cat", "nasa badge"]
204
+ inputs = processor(text=input_texts)
205
+
206
+ seq_length = 16
207
+ input_ids = inputs["input_ids"]
208
+ predicted_ids = [
209
+ [49406, 2368, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
210
+ [49406, 6841, 11301, 49407, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
211
+ ]
212
+
213
+ self.assertListEqual(list(inputs.keys()), ["input_ids", "attention_mask"])
214
+ self.assertEqual(inputs["input_ids"].shape, (2, seq_length))
215
+ self.assertListEqual(list(input_ids[0]), predicted_ids[0])
216
+ self.assertListEqual(list(input_ids[1]), predicted_ids[1])
217
+
218
+ def test_processor_case2(self):
219
+ image_processor = self.get_image_processor()
220
+ tokenizer = self.get_tokenizer()
221
+
222
+ processor = OwlViTProcessor(tokenizer=tokenizer, image_processor=image_processor)
223
+
224
+ image_input = self.prepare_image_inputs()
225
+ query_input = self.prepare_image_inputs()
226
+
227
+ inputs = processor(images=image_input, query_images=query_input)
228
+
229
+ self.assertListEqual(list(inputs.keys()), ["query_pixel_values", "pixel_values"])
230
+
231
+ # test if it raises when no input is passed
232
+ with pytest.raises(ValueError):
233
+ processor()
234
+
235
+ def test_tokenizer_decode(self):
236
+ image_processor = self.get_image_processor()
237
+ tokenizer = self.get_tokenizer()
238
+
239
+ processor = OwlViTProcessor(tokenizer=tokenizer, image_processor=image_processor)
240
+
241
+ predicted_ids = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
242
+
243
+ decoded_processor = processor.batch_decode(predicted_ids)
244
+ decoded_tok = tokenizer.batch_decode(predicted_ids)
245
+
246
+ self.assertListEqual(decoded_tok, decoded_processor)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/paligemma/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/paligemma/test_modeling_paligemma.py ADDED
@@ -0,0 +1,630 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 PaliGemma model."""
16
+
17
+ import unittest
18
+
19
+ import requests
20
+
21
+ from transformers import (
22
+ PaliGemmaConfig,
23
+ PaliGemmaForConditionalGeneration,
24
+ PaliGemmaProcessor,
25
+ is_torch_available,
26
+ is_vision_available,
27
+ )
28
+ from transformers.testing_utils import (
29
+ cleanup,
30
+ require_read_token,
31
+ require_torch,
32
+ slow,
33
+ torch_device,
34
+ )
35
+
36
+ from ...generation.test_utils import GenerationTesterMixin
37
+ from ...test_configuration_common import ConfigTester
38
+ from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
39
+
40
+
41
+ if is_torch_available():
42
+ import torch
43
+
44
+
45
+ if is_vision_available():
46
+ from PIL import Image
47
+
48
+
49
+ class PaliGemmaVisionText2TextModelTester:
50
+ def __init__(
51
+ self,
52
+ parent,
53
+ ignore_index=-100,
54
+ image_token_index=0,
55
+ projector_hidden_act="gelu",
56
+ seq_length=25,
57
+ vision_feature_select_strategy="default",
58
+ vision_feature_layer=-1,
59
+ projection_dim=32,
60
+ text_config={
61
+ "model_type": "gemma",
62
+ "seq_length": 128,
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": 1,
72
+ "head_dim": 8,
73
+ "intermediate_size": 37,
74
+ "hidden_activation": "gelu_pytorch_tanh",
75
+ "hidden_dropout_prob": 0.1,
76
+ "attention_probs_dropout_prob": 0.1,
77
+ "max_position_embeddings": 512,
78
+ "type_vocab_size": 16,
79
+ "type_sequence_label_size": 2,
80
+ "initializer_range": 0.02,
81
+ "num_labels": 3,
82
+ "num_choices": 4,
83
+ "pad_token_id": 1,
84
+ },
85
+ is_training=True,
86
+ vision_config={
87
+ "use_labels": True,
88
+ "image_size": 20,
89
+ "patch_size": 5,
90
+ "num_image_tokens": 4,
91
+ "num_channels": 3,
92
+ "is_training": True,
93
+ "hidden_size": 32,
94
+ "projection_dim": 32,
95
+ "num_key_value_heads": 1,
96
+ "num_hidden_layers": 2,
97
+ "num_attention_heads": 4,
98
+ "intermediate_size": 37,
99
+ "dropout": 0.1,
100
+ "attention_dropout": 0.1,
101
+ "initializer_range": 0.02,
102
+ },
103
+ use_cache=False,
104
+ ):
105
+ self.parent = parent
106
+ self.ignore_index = ignore_index
107
+ # `image_token_index` is set to 0 to pass "resize_embeddings" test, do not modify
108
+ self.image_token_index = image_token_index
109
+ self.projector_hidden_act = projector_hidden_act
110
+ self.vision_feature_select_strategy = vision_feature_select_strategy
111
+ self.vision_feature_layer = vision_feature_layer
112
+ self.text_config = text_config
113
+ self.vision_config = vision_config
114
+ self.seq_length = seq_length
115
+ self.projection_dim = projection_dim
116
+ self.pad_token_id = text_config["pad_token_id"]
117
+
118
+ self.num_hidden_layers = text_config["num_hidden_layers"]
119
+ self.vocab_size = text_config["vocab_size"]
120
+ self.hidden_size = text_config["hidden_size"]
121
+ self.num_attention_heads = text_config["num_attention_heads"]
122
+ self.is_training = is_training
123
+
124
+ self.batch_size = 3
125
+ self.num_channels = vision_config["num_channels"]
126
+ self.image_size = vision_config["image_size"]
127
+ self.encoder_seq_length = seq_length
128
+ self.use_cache = use_cache
129
+
130
+ def get_config(self):
131
+ return PaliGemmaConfig(
132
+ text_config=self.text_config,
133
+ vision_config=self.vision_config,
134
+ ignore_index=self.ignore_index,
135
+ image_token_index=self.image_token_index,
136
+ projector_hidden_act=self.projector_hidden_act,
137
+ projection_dim=self.projection_dim,
138
+ vision_feature_select_strategy=self.vision_feature_select_strategy,
139
+ vision_feature_layer=self.vision_feature_layer,
140
+ )
141
+
142
+ def prepare_config_and_inputs(self):
143
+ pixel_values = floats_tensor(
144
+ [
145
+ self.batch_size,
146
+ self.vision_config["num_channels"],
147
+ self.vision_config["image_size"],
148
+ self.vision_config["image_size"],
149
+ ]
150
+ )
151
+ config = self.get_config()
152
+
153
+ return config, pixel_values
154
+
155
+ def prepare_config_and_inputs_for_common(self):
156
+ config_and_inputs = self.prepare_config_and_inputs()
157
+ config, pixel_values = config_and_inputs
158
+ input_ids = ids_tensor([self.batch_size, self.seq_length], config.text_config.vocab_size - 1) + 1
159
+ attention_mask = input_ids.ne(self.pad_token_id).to(torch_device)
160
+
161
+ # set the 16 first tokens to be image, and ensure that no other tokens are image tokens
162
+ # do not change this unless you modified image size or patch size
163
+ input_ids[input_ids == config.image_token_index] = self.pad_token_id
164
+ input_ids[:, :16] = config.image_token_index
165
+ inputs_dict = {
166
+ "pixel_values": pixel_values,
167
+ "input_ids": input_ids,
168
+ "attention_mask": attention_mask,
169
+ "labels": input_ids,
170
+ "token_type_ids": torch.zeros_like(input_ids),
171
+ }
172
+ return config, inputs_dict
173
+
174
+
175
+ @require_torch
176
+ class PaliGemmaForConditionalGenerationModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
177
+ """
178
+ Model tester for `PaliGemmaForConditionalGeneration`.
179
+ """
180
+
181
+ all_model_classes = (PaliGemmaForConditionalGeneration,) if is_torch_available() else ()
182
+ all_generative_model_classes = (PaliGemmaForConditionalGeneration,) if is_torch_available() else ()
183
+ pipeline_model_mapping = {"image-text-to-text": PaliGemmaForConditionalGeneration}
184
+ fx_compatible = False
185
+ test_pruning = False
186
+ test_torchscript = False
187
+ test_head_masking = False
188
+ _is_composite = True
189
+
190
+ def setUp(self):
191
+ self.model_tester = PaliGemmaVisionText2TextModelTester(self)
192
+ self.config_tester = ConfigTester(self, config_class=PaliGemmaConfig, has_text_modality=False)
193
+
194
+ # overwrite inputs_embeds tests because we need to delete "pixel values" for LVLMs
195
+ def test_inputs_embeds(self):
196
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
197
+
198
+ for model_class in self.all_model_classes:
199
+ model = model_class(config)
200
+ model.to(torch_device)
201
+ model.eval()
202
+
203
+ inputs = self._prepare_for_class(inputs_dict, model_class)
204
+
205
+ input_ids = inputs["input_ids"]
206
+ del inputs["input_ids"]
207
+ del inputs["pixel_values"]
208
+
209
+ wte = model.get_input_embeddings()
210
+ inputs["inputs_embeds"] = wte(input_ids)
211
+
212
+ with torch.no_grad():
213
+ model(**inputs)
214
+
215
+ # overwrite inputs_embeds tests because we need to delete "pixel values" for LVLMs
216
+ # while some other models require pixel_values to be present
217
+ def test_inputs_embeds_matches_input_ids(self):
218
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
219
+
220
+ for model_class in self.all_model_classes:
221
+ model = model_class(config)
222
+ model.to(torch_device)
223
+ model.eval()
224
+
225
+ inputs = self._prepare_for_class(inputs_dict, model_class)
226
+ input_ids = inputs["input_ids"]
227
+ del inputs["input_ids"]
228
+ del inputs["pixel_values"]
229
+
230
+ inputs_embeds = model.get_input_embeddings()(input_ids)
231
+
232
+ with torch.no_grad():
233
+ out_ids = model(input_ids=input_ids, **inputs)[0]
234
+ out_embeds = model(inputs_embeds=inputs_embeds, **inputs)[0]
235
+ self.assertTrue(torch.allclose(out_embeds, out_ids))
236
+
237
+ # Copied from tests.models.llava.test_modeling_llava.LlavaForConditionalGenerationModelTest.test_mismatching_num_image_tokens
238
+ def test_mismatching_num_image_tokens(self):
239
+ """
240
+ Tests that VLMs through an error with explicit message saying what is wrong
241
+ when number of images don't match number of image tokens in the text.
242
+ Also we need to test multi-image cases when one prompr has multiple image tokens.
243
+ """
244
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
245
+ for model_class in self.all_model_classes:
246
+ model = model_class(config).to(torch_device)
247
+ _ = model(**input_dict) # successfull forward with no modifications
248
+
249
+ # remove one image but leave the image token in text
250
+ input_dict["pixel_values"] = input_dict["pixel_values"][-1:, ...]
251
+ with self.assertRaises(ValueError):
252
+ _ = model(**input_dict)
253
+
254
+ # simulate multi-image case by concatenating inputs where each has exactly one image/image-token
255
+ input_ids = input_dict["input_ids"][:1]
256
+ pixel_values = input_dict["pixel_values"][:1]
257
+ input_ids = torch.cat([input_ids, input_ids], dim=0)
258
+
259
+ # one image and two image tokens raise an error
260
+ with self.assertRaises(ValueError):
261
+ _ = model(input_ids=input_ids, pixel_values=pixel_values)
262
+
263
+ # two images and two image tokens don't raise an error
264
+ pixel_values = torch.cat([pixel_values, pixel_values], dim=0)
265
+ _ = model(input_ids=input_ids, pixel_values=pixel_values)
266
+
267
+ @unittest.skip(
268
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
269
+ )
270
+ def test_training_gradient_checkpointing(self):
271
+ pass
272
+
273
+ @unittest.skip(
274
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
275
+ )
276
+ def test_training_gradient_checkpointing_use_reentrant(self):
277
+ pass
278
+
279
+ @unittest.skip(
280
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
281
+ )
282
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
283
+ pass
284
+
285
+ @unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.")
286
+ def test_cpu_offload(self):
287
+ pass
288
+
289
+ @unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.")
290
+ def test_disk_offload_bin(self):
291
+ pass
292
+
293
+ @unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.")
294
+ def test_disk_offload_safetensors(self):
295
+ pass
296
+
297
+ @unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.")
298
+ def test_model_parallelism(self):
299
+ pass
300
+
301
+ @unittest.skip(
302
+ reason="PaliGemmma's SigLip encoder uses the same initialization scheme as the Flax original implementation"
303
+ )
304
+ def test_initialization(self):
305
+ pass
306
+
307
+ # TODO extend valid outputs to include this test @Molbap
308
+ @unittest.skip(reason="PaliGemma has currently one output format.")
309
+ def test_model_outputs_equivalence(self):
310
+ pass
311
+
312
+ # TODO fix the loss = nan in the testing configuration chosen @Molbap
313
+ @unittest.skip(reason="Edge case giving loss nan values in testing configuration.")
314
+ def test_determinism(self):
315
+ pass
316
+
317
+ @unittest.skip(reason="PaliGemma does not use feedforward chunking.")
318
+ def test_feed_forward_chunking(self):
319
+ pass
320
+
321
+ @unittest.skip(reason="PaliGemma does not support low_cpu_mem_usage.")
322
+ def test_save_load_low_cpu_mem_usage(self):
323
+ pass
324
+
325
+ @unittest.skip(reason="PaliGemma does not support low_cpu_mem_usage.")
326
+ def test_save_load_low_cpu_mem_usage_checkpoints(self):
327
+ pass
328
+
329
+ @unittest.skip(reason="PaliGemma does not support low_cpu_mem_usage.")
330
+ def test_save_load_low_cpu_mem_usage_no_safetensors(self):
331
+ pass
332
+
333
+ @unittest.skip(
334
+ reason="VLMs doen't accept inputs embeds and pixel values at the same time. So if the test passed for bacbone LM, it passes for VLM also"
335
+ )
336
+ def test_generate_from_inputs_embeds_with_static_cache(self):
337
+ pass
338
+
339
+ @unittest.skip("FlashAttention only support fp16 and bf16 data type")
340
+ def test_flash_attn_2_fp32_ln(self):
341
+ pass
342
+
343
+ @unittest.skip(
344
+ "VLMs need lots of steps to prepare images/mask correctly to get pad-free inputs. Can be tested as part of LLM test"
345
+ )
346
+ def test_flash_attention_2_padding_matches_padding_free_with_position_ids(self):
347
+ pass
348
+
349
+ # TODO (joao, raushan): fix me -- the problem is in `cache_position[0] == 0`, i.e. dynamic control flow
350
+ @unittest.skip("PaliGemma is not compatible with end-to-end generation compilation")
351
+ def test_generate_compile_fullgraph(self):
352
+ pass
353
+
354
+
355
+ @slow
356
+ @require_torch
357
+ @require_read_token
358
+ class PaliGemmaForConditionalGenerationIntegrationTest(unittest.TestCase):
359
+ def setUp(self):
360
+ self.processor = PaliGemmaProcessor.from_pretrained("google/paligemma-3b-pt-224")
361
+
362
+ def tearDown(self):
363
+ cleanup(torch_device, gc_collect=True)
364
+
365
+ def test_small_model_integration_test(self):
366
+ # Let' s make sure we test the preprocessing to replace what is used
367
+ model_id = "google/paligemma-3b-pt-224"
368
+ model = PaliGemmaForConditionalGeneration.from_pretrained(model_id)
369
+ prompt = ""
370
+ image_file = (
371
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/cow_beach_1.png"
372
+ )
373
+ raw_image = Image.open(requests.get(image_file, stream=True).raw)
374
+ inputs = self.processor(images=raw_image, text=prompt, return_tensors="pt")
375
+ EXPECTED_INPUT_IDS = torch.tensor([[257152] * 256 + [2, 108]])
376
+ self.assertTrue(torch.equal(inputs["input_ids"], EXPECTED_INPUT_IDS))
377
+
378
+ output = model.generate(**inputs, max_new_tokens=20)
379
+ EXPECTED_DECODED_TEXT = "\ncow on the beach" # fmt: skip
380
+
381
+ self.assertEqual(
382
+ self.processor.decode(output[0], skip_special_tokens=True),
383
+ EXPECTED_DECODED_TEXT,
384
+ )
385
+
386
+ def test_small_model_integration_test_multiimage(self):
387
+ model_id = "google/paligemma-3b-ft-nlvr2-448" # checkpoint tuned for multiple images
388
+ model = PaliGemmaForConditionalGeneration.from_pretrained(model_id)
389
+ processor = PaliGemmaProcessor.from_pretrained(model_id)
390
+ prompt = "answer en There is no snowman in any of the images. Is this true or false?"
391
+ stop_sign_image = Image.open(
392
+ requests.get("https://www.ilankelman.org/stopsigns/australia.jpg", stream=True).raw
393
+ )
394
+ snow_image = Image.open(
395
+ requests.get(
396
+ "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg", stream=True
397
+ ).raw
398
+ )
399
+
400
+ inputs = processor(text=prompt, images=[[snow_image, snow_image]], return_tensors="pt")
401
+
402
+ output = model.generate(**inputs, max_new_tokens=20)
403
+ EXPECTED_DECODED_TEXT = "answer en There is no snowman in any of the images. Is this true or false?\nFalse"
404
+
405
+ self.assertEqual(
406
+ self.processor.decode(output[0], skip_special_tokens=True),
407
+ EXPECTED_DECODED_TEXT,
408
+ )
409
+
410
+ # try another prompt with two different image this time
411
+ prompt = "answer en There is exactly one snowman. Is this true or false?"
412
+ inputs = processor(text=prompt, images=[[snow_image, stop_sign_image]], return_tensors="pt")
413
+ output = model.generate(**inputs, max_new_tokens=20)
414
+ EXPECTED_DECODED_TEXT = "answer en There is exactly one snowman. Is this true or false?\nTrue"
415
+ self.assertEqual(
416
+ self.processor.decode(output[0], skip_special_tokens=True),
417
+ EXPECTED_DECODED_TEXT,
418
+ )
419
+
420
+ def test_small_model_integration_test_paligemma_VQA(self):
421
+ # Let' s make sure we test the preprocessing to replace what is used
422
+ model_id = "google/paligemma-3b-pt-224"
423
+ model = PaliGemmaForConditionalGeneration.from_pretrained(model_id)
424
+ prompt = "answer en Where is the cow standing?"
425
+ image_file = (
426
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/cow_beach_1.png"
427
+ )
428
+ raw_image = Image.open(requests.get(image_file, stream=True).raw)
429
+ inputs = self.processor(images=raw_image, text=prompt, return_tensors="pt").to(torch.float16)
430
+
431
+ output = model.generate(**inputs, max_new_tokens=900, do_sample=False)
432
+ EXPECTED_DECODED_TEXT = "answer en Where is the cow standing?\nbeach" # fmt: skip
433
+
434
+ self.assertEqual(
435
+ self.processor.decode(output[0], skip_special_tokens=True),
436
+ EXPECTED_DECODED_TEXT,
437
+ )
438
+
439
+ def test_small_model_integration_test_paligemma_empty_prompt(self):
440
+ # Let' s make sure we test the preprocessing to replace what is used
441
+ model_id = "google/paligemma-3b-pt-224"
442
+ model = PaliGemmaForConditionalGeneration.from_pretrained(model_id)
443
+
444
+ prompt = ""
445
+ image_file = (
446
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/cow_beach_1.png"
447
+ )
448
+ raw_image = Image.open(requests.get(image_file, stream=True).raw)
449
+ inputs = self.processor(images=raw_image, text=prompt, return_tensors="pt").to(torch.float16)
450
+
451
+ output = model.generate(**inputs, max_new_tokens=900, do_sample=False)
452
+ EXPECTED_DECODED_TEXT = "\ncow on the beach" # fmt: skip
453
+
454
+ self.assertEqual(
455
+ self.processor.decode(output[0], skip_special_tokens=True),
456
+ EXPECTED_DECODED_TEXT,
457
+ )
458
+
459
+ def test_small_model_integration_test_paligemma_batched(self):
460
+ # Let' s make sure we test the preprocessing to replace what is used
461
+ model_id = "google/paligemma-3b-pt-224"
462
+
463
+ model = PaliGemmaForConditionalGeneration.from_pretrained(model_id)
464
+
465
+ prompts = [
466
+ "answer en Where is the cow standing?",
467
+ "",
468
+ ]
469
+ image1 = Image.open(
470
+ requests.get(
471
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/cow_beach_1.png",
472
+ stream=True,
473
+ ).raw
474
+ )
475
+ image2 = image1
476
+
477
+ inputs = self.processor(images=[image1, image2], text=prompts, return_tensors="pt", padding=True)
478
+
479
+ output = model.generate(**inputs, max_new_tokens=20)
480
+
481
+ EXPECTED_DECODED_TEXT = ["answer en Where is the cow standing?\nbeach", "\ncow on the beach"] # fmt: skip
482
+
483
+ self.assertEqual(self.processor.batch_decode(output, skip_special_tokens=True), EXPECTED_DECODED_TEXT)
484
+
485
+ def test_small_model_integration_test_paligemma_batched_bf16(self):
486
+ # Let' s make sure we test the preprocessing to replace what is used
487
+ model_id = "google/paligemma-3b-pt-224"
488
+ model = PaliGemmaForConditionalGeneration.from_pretrained(
489
+ model_id, revision="bfloat16", torch_dtype=torch.bfloat16
490
+ ).to(torch_device)
491
+ # The first batch is longer in terms of text, the second will be padded.
492
+ prompts = [
493
+ "answer en Where is the cow standing?",
494
+ "",
495
+ ]
496
+ image1 = Image.open(
497
+ requests.get(
498
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/cow_beach_1.png",
499
+ stream=True,
500
+ ).raw
501
+ )
502
+ image2 = image1
503
+
504
+ inputs = (
505
+ self.processor(images=[image1, image2], text=prompts, return_tensors="pt", padding=True)
506
+ .to(torch.bfloat16)
507
+ .to(torch_device)
508
+ )
509
+ output = model.generate(**inputs, max_new_tokens=20)
510
+
511
+ EXPECTED_DECODED_TEXT = ["answer en Where is the cow standing?\nbeach", "\ncow on the beach"] # fmt: skip
512
+ self.assertEqual(self.processor.batch_decode(output, skip_special_tokens=True), EXPECTED_DECODED_TEXT)
513
+
514
+ def test_small_model_integration_test_paligemma_batched_f16(self):
515
+ # Let' s make sure we test the preprocessing to replace what is used
516
+ model_id = "google/paligemma-3b-pt-224"
517
+ model = PaliGemmaForConditionalGeneration.from_pretrained(
518
+ model_id, revision="float16", torch_dtype=torch.float16
519
+ ).to(torch_device)
520
+ # The first batch is longer in terms of text, the second will be padded.
521
+ prompts = [
522
+ "answer en Where is the cow standing?",
523
+ "",
524
+ ]
525
+ image1 = Image.open(
526
+ requests.get(
527
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/cow_beach_1.png",
528
+ stream=True,
529
+ ).raw
530
+ )
531
+ image2 = image1
532
+
533
+ inputs = (
534
+ self.processor(images=[image1, image2], text=prompts, return_tensors="pt", padding=True)
535
+ .to(torch.float16)
536
+ .to(torch_device)
537
+ )
538
+
539
+ output = model.generate(**inputs, max_new_tokens=20)
540
+
541
+ EXPECTED_DECODED_TEXT = ["answer en Where is the cow standing?\nbeach", "\ncow on the beach"] # fmt: skip
542
+ self.assertEqual(self.processor.batch_decode(output, skip_special_tokens=True), EXPECTED_DECODED_TEXT)
543
+
544
+ def test_integration_detection_bug(self):
545
+ # this is a reproducer of https://github.com/huggingface/transformers/issues/31425 where not enough context
546
+ # impacted negatively segmentation generations.
547
+ model_id = "google/paligemma-3b-pt-224"
548
+ model = PaliGemmaForConditionalGeneration.from_pretrained(
549
+ model_id, revision="bfloat16", torch_dtype=torch.bfloat16
550
+ ).to(torch_device)
551
+ prompt = ("detect shoe",)
552
+
553
+ image = Image.open(
554
+ requests.get(
555
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/shoe.png",
556
+ stream=True,
557
+ ).raw
558
+ )
559
+
560
+ inputs = self.processor(images=image, text=prompt, return_tensors="pt").to(torch.bfloat16).to(torch_device)
561
+
562
+ output = model.generate(**inputs, max_new_tokens=20)
563
+
564
+ EXPECTED_DECODED_TEXT = "detect shoe\n<loc0051><loc0309><loc0708><loc0646> shoe" # fmt: skip
565
+ self.assertEqual(self.processor.decode(output[0], skip_special_tokens=True), EXPECTED_DECODED_TEXT)
566
+
567
+ def test_paligemma_index_error_bug(self):
568
+ # This is a reproducer of https://github.com/huggingface/transformers/pull/28032 and makes sure it does not happen anymore
569
+ # Please refer to that PR, or specifically https://github.com/huggingface/transformers/pull/28032#issuecomment-1860650043 for
570
+ # more details
571
+ model_id = "google/paligemma-3b-pt-224"
572
+ model = PaliGemmaForConditionalGeneration.from_pretrained(model_id)
573
+
574
+ # Simulate a super long prompt
575
+ prompt = "\n" * 200
576
+ image_file = (
577
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/cow_beach_1.png"
578
+ )
579
+
580
+ raw_image = Image.open(requests.get(image_file, stream=True).raw)
581
+ inputs = self.processor(
582
+ images=raw_image,
583
+ text=prompt,
584
+ return_tensors="pt",
585
+ ).to(torch.float16)
586
+
587
+ # Make sure that `generate` works
588
+ _ = model.generate(**inputs, max_new_tokens=20)
589
+
590
+ def test_paligemma_finetuning_with_suffixes_bf16(self):
591
+ # this is a supplementary test to ensure paligemma fine-tuning that relies on token_type_ids is robust to future changes
592
+ model_id = "google/paligemma-3b-pt-224"
593
+ model = PaliGemmaForConditionalGeneration.from_pretrained(
594
+ model_id, revision="bfloat16", torch_dtype=torch.bfloat16
595
+ ).to(torch_device)
596
+ # The first batch is longer in terms of text, the second will be padded.
597
+ prompts = [
598
+ "answer en Where is the cow standing?",
599
+ "",
600
+ ]
601
+
602
+ suffixes = ["beach", "cow standing on the beach"]
603
+ image1 = Image.open(
604
+ requests.get(
605
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/cow_beach_1.png",
606
+ stream=True,
607
+ ).raw
608
+ )
609
+ image2 = image1
610
+
611
+ inputs = (
612
+ self.processor(images=[image1, image2], text=prompts, suffix=suffixes, return_tensors="pt", padding=True)
613
+ .to(torch.bfloat16)
614
+ .to(torch_device)
615
+ )
616
+
617
+ expected_labels = torch.tensor(
618
+ [266 * [-100] + [54901, 1], 262 * [-100] + [14706, 9980, 611, 573, 8318, 1]]
619
+ ).to(torch_device)
620
+
621
+ assert torch.equal(inputs["labels"], expected_labels)
622
+
623
+ expected_token_type_ids = torch.tensor([266 * [0] + 2 * [1], 262 * [0] + 6 * [1]]).to(torch_device)
624
+
625
+ assert torch.equal(inputs["token_type_ids"], expected_token_type_ids)
626
+
627
+ output = model(**inputs)
628
+
629
+ # check that loss does not error out
630
+ _ = output.loss
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/paligemma/test_processor_paligemma.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 GemmaTokenizer, PaliGemmaProcessor
20
+ from transformers.testing_utils import get_tests_dir, require_torch, require_vision
21
+ from transformers.utils import is_vision_available
22
+
23
+ from ...test_processing_common import ProcessorTesterMixin
24
+
25
+
26
+ if is_vision_available():
27
+ from transformers import SiglipImageProcessor
28
+
29
+ SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model")
30
+
31
+
32
+ @require_vision
33
+ class PaliGemmaProcessorTest(ProcessorTesterMixin, unittest.TestCase):
34
+ processor_class = PaliGemmaProcessor
35
+
36
+ def setUp(self):
37
+ self.tmpdirname = tempfile.mkdtemp()
38
+ image_processor = SiglipImageProcessor.from_pretrained("google/siglip-so400m-patch14-384")
39
+ image_processor.image_seq_length = 0
40
+ tokenizer = GemmaTokenizer(SAMPLE_VOCAB, keep_accents=True)
41
+ processor = PaliGemmaProcessor(image_processor=image_processor, tokenizer=tokenizer)
42
+ processor.save_pretrained(self.tmpdirname)
43
+
44
+ def tearDown(self):
45
+ shutil.rmtree(self.tmpdirname)
46
+
47
+ @require_torch
48
+ @require_vision
49
+ def test_image_seq_length(self):
50
+ input_str = "lower newer"
51
+ image_input = self.prepare_image_inputs()
52
+ image_processor = self.get_component("image_processor")
53
+ tokenizer = self.get_component("tokenizer", max_length=112, padding="max_length")
54
+ image_processor.image_seq_length = 14
55
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
56
+ inputs = processor(
57
+ text=input_str, images=image_input, return_tensors="pt", max_length=112, padding="max_length"
58
+ )
59
+ self.assertEqual(len(inputs["input_ids"][0]), 112 + 14)
60
+
61
+ def test_text_with_image_tokens(self):
62
+ image_processor = self.get_component("image_processor")
63
+ tokenizer = self.get_component("tokenizer")
64
+
65
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
66
+ text_multi_images = "<image><image>Dummy text!"
67
+ text_single_image = "<image>Dummy text!"
68
+ text_no_image = "Dummy text!"
69
+
70
+ image = self.prepare_image_inputs()
71
+
72
+ out_noimage = processor(text=text_no_image, images=image, return_tensors="np")
73
+ out_singlimage = processor(text=text_single_image, images=image, return_tensors="np")
74
+ for k in out_noimage:
75
+ self.assertTrue(out_noimage[k].tolist() == out_singlimage[k].tolist())
76
+
77
+ out_multiimages = processor(text=text_multi_images, images=[image, image], return_tensors="np")
78
+ out_noimage = processor(text=text_no_image, images=[[image, image]], return_tensors="np")
79
+
80
+ # We can't be sure what is users intention, whether user want "one text + two images" or user forgot to add the second text
81
+ with self.assertRaises(ValueError):
82
+ out_noimage = processor(text=text_no_image, images=[image, image], return_tensors="np")
83
+
84
+ for k in out_noimage:
85
+ self.assertTrue(out_noimage[k].tolist() == out_multiimages[k].tolist())
86
+
87
+ text_batched = ["Dummy text!", "Dummy text!"]
88
+ text_batched_with_image = ["<image>Dummy text!", "<image>Dummy text!"]
89
+ out_images = processor(text=text_batched_with_image, images=[image, image], return_tensors="np")
90
+ out_noimage_nested = processor(text=text_batched, images=[[image], [image]], return_tensors="np")
91
+ out_noimage = processor(text=text_batched, images=[image, image], return_tensors="np")
92
+ for k in out_noimage:
93
+ self.assertTrue(out_noimage[k].tolist() == out_images[k].tolist() == out_noimage_nested[k].tolist())
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/patchtsmixer/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/patchtsmixer/test_modeling_patchtsmixer.py ADDED
@@ -0,0 +1,1118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 IBM and HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Testing suite for the PyTorch PatchTSMixer model."""
16
+
17
+ import inspect
18
+ import itertools
19
+ import random
20
+ import tempfile
21
+ import unittest
22
+ from typing import Dict, List, Optional, Tuple, Union
23
+
24
+ import numpy as np
25
+ from huggingface_hub import hf_hub_download
26
+ from parameterized import parameterized
27
+
28
+ from transformers import is_torch_available
29
+ from transformers.models.auto import get_values
30
+ from transformers.testing_utils import is_flaky, require_torch, slow, torch_device
31
+
32
+ from ...test_configuration_common import ConfigTester
33
+ from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
34
+ from ...test_pipeline_mixin import PipelineTesterMixin
35
+
36
+
37
+ TOLERANCE = 1e-4
38
+
39
+ if is_torch_available():
40
+ import torch
41
+
42
+ from transformers import (
43
+ MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING,
44
+ MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING,
45
+ PatchTSMixerConfig,
46
+ PatchTSMixerForPrediction,
47
+ PatchTSMixerForPretraining,
48
+ PatchTSMixerForRegression,
49
+ PatchTSMixerForTimeSeriesClassification,
50
+ PatchTSMixerModel,
51
+ )
52
+ from transformers.models.patchtsmixer.modeling_patchtsmixer import (
53
+ PatchTSMixerEncoder,
54
+ PatchTSMixerForPredictionHead,
55
+ PatchTSMixerForPredictionOutput,
56
+ PatchTSMixerForRegressionOutput,
57
+ PatchTSMixerForTimeSeriesClassificationOutput,
58
+ PatchTSMixerLinearHead,
59
+ PatchTSMixerPretrainHead,
60
+ )
61
+
62
+
63
+ @require_torch
64
+ class PatchTSMixerModelTester:
65
+ def __init__(
66
+ self,
67
+ context_length: int = 32,
68
+ patch_length: int = 8,
69
+ num_input_channels: int = 3,
70
+ patch_stride: int = 8,
71
+ # d_model: int = 128,
72
+ hidden_size: int = 8,
73
+ # num_layers: int = 8,
74
+ num_hidden_layers: int = 2,
75
+ expansion_factor: int = 2,
76
+ dropout: float = 0.5,
77
+ mode: str = "common_channel",
78
+ gated_attn: bool = True,
79
+ norm_mlp="LayerNorm",
80
+ swin_hier: int = 0,
81
+ # masking related
82
+ mask_type: str = "forecast",
83
+ random_mask_ratio=0.5,
84
+ mask_patches: list = [2, 3],
85
+ forecast_mask_ratios: list = [1, 1],
86
+ mask_value=0,
87
+ masked_loss: bool = False,
88
+ mask_mode: str = "mask_before_encoder",
89
+ channel_consistent_masking: bool = True,
90
+ scaling: Optional[Union[str, bool]] = "std",
91
+ # Head related
92
+ head_dropout: float = 0.2,
93
+ # forecast related
94
+ prediction_length: int = 16,
95
+ out_channels: int = None,
96
+ # Classification/regression related
97
+ # num_labels: int = 3,
98
+ num_targets: int = 3,
99
+ output_range: list = None,
100
+ head_aggregation: str = None,
101
+ # Trainer related
102
+ batch_size=13,
103
+ is_training=True,
104
+ seed_number=42,
105
+ post_init=True,
106
+ num_parallel_samples=4,
107
+ ):
108
+ self.num_input_channels = num_input_channels
109
+ self.context_length = context_length
110
+ self.patch_length = patch_length
111
+ self.patch_stride = patch_stride
112
+ # self.d_model = d_model
113
+ self.hidden_size = hidden_size
114
+ self.expansion_factor = expansion_factor
115
+ # self.num_layers = num_layers
116
+ self.num_hidden_layers = num_hidden_layers
117
+ self.dropout = dropout
118
+ self.mode = mode
119
+ self.gated_attn = gated_attn
120
+ self.norm_mlp = norm_mlp
121
+ self.swin_hier = swin_hier
122
+ self.scaling = scaling
123
+ self.head_dropout = head_dropout
124
+ # masking related
125
+ self.mask_type = mask_type
126
+ self.random_mask_ratio = random_mask_ratio
127
+ self.mask_patches = mask_patches
128
+ self.forecast_mask_ratios = forecast_mask_ratios
129
+ self.mask_value = mask_value
130
+ self.channel_consistent_masking = channel_consistent_masking
131
+ self.mask_mode = mask_mode
132
+ self.masked_loss = masked_loss
133
+ # patching related
134
+ self.patch_last = True
135
+ # forecast related
136
+ self.prediction_length = prediction_length
137
+ self.out_channels = out_channels
138
+ # classification/regression related
139
+ # self.num_labels = num_labels
140
+ self.num_targets = num_targets
141
+ self.output_range = output_range
142
+ self.head_aggregation = head_aggregation
143
+ # Trainer related
144
+ self.batch_size = batch_size
145
+ self.is_training = is_training
146
+ self.seed_number = seed_number
147
+ self.post_init = post_init
148
+ self.num_parallel_samples = num_parallel_samples
149
+
150
+ def get_config(self):
151
+ config_ = PatchTSMixerConfig(
152
+ num_input_channels=self.num_input_channels,
153
+ context_length=self.context_length,
154
+ patch_length=self.patch_length,
155
+ patch_stride=self.patch_stride,
156
+ # d_model = self.d_model,
157
+ d_model=self.hidden_size,
158
+ expansion_factor=self.expansion_factor,
159
+ # num_layers = self.num_layers,
160
+ num_layers=self.num_hidden_layers,
161
+ dropout=self.dropout,
162
+ mode=self.mode,
163
+ gated_attn=self.gated_attn,
164
+ norm_mlp=self.norm_mlp,
165
+ swin_hier=self.swin_hier,
166
+ scaling=self.scaling,
167
+ head_dropout=self.head_dropout,
168
+ mask_type=self.mask_type,
169
+ random_mask_ratio=self.random_mask_ratio,
170
+ mask_patches=self.mask_patches,
171
+ forecast_mask_ratios=self.forecast_mask_ratios,
172
+ mask_value=self.mask_value,
173
+ channel_consistent_masking=self.channel_consistent_masking,
174
+ mask_mode=self.mask_mode,
175
+ masked_loss=self.masked_loss,
176
+ prediction_length=self.prediction_length,
177
+ out_channels=self.out_channels,
178
+ # num_labels=self.num_labels,
179
+ num_targets=self.num_targets,
180
+ output_range=self.output_range,
181
+ head_aggregation=self.head_aggregation,
182
+ post_init=self.post_init,
183
+ )
184
+ self.num_patches = config_.num_patches
185
+ return config_
186
+
187
+ def prepare_patchtsmixer_inputs_dict(self, config):
188
+ _past_length = config.context_length
189
+ # bs, n_vars, num_patch, patch_length
190
+
191
+ # [bs x context_length x n_vars]
192
+ past_values = floats_tensor([self.batch_size, _past_length, self.num_input_channels])
193
+
194
+ inputs_dict = {
195
+ "past_values": past_values,
196
+ }
197
+ return inputs_dict
198
+
199
+ def prepare_config_and_inputs(self):
200
+ config = self.get_config()
201
+ inputs_dict = self.prepare_patchtsmixer_inputs_dict(config)
202
+ return config, inputs_dict
203
+
204
+ def prepare_config_and_inputs_for_common(self):
205
+ config, inputs_dict = self.prepare_config_and_inputs()
206
+ return config, inputs_dict
207
+
208
+
209
+ @require_torch
210
+ class PatchTSMixerModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
211
+ all_model_classes = (
212
+ (
213
+ PatchTSMixerModel,
214
+ PatchTSMixerForPrediction,
215
+ PatchTSMixerForPretraining,
216
+ PatchTSMixerForTimeSeriesClassification,
217
+ PatchTSMixerForRegression,
218
+ )
219
+ if is_torch_available()
220
+ else ()
221
+ )
222
+ all_generative_model_classes = (
223
+ (PatchTSMixerForPrediction, PatchTSMixerForPretraining) if is_torch_available() else ()
224
+ )
225
+ pipeline_model_mapping = {"feature-extraction": PatchTSMixerModel} if is_torch_available() else {}
226
+ is_encoder_decoder = False
227
+ test_pruning = False
228
+ test_head_masking = False
229
+ test_missing_keys = False
230
+ test_torchscript = False
231
+ test_inputs_embeds = False
232
+
233
+ test_resize_embeddings = True
234
+ test_resize_position_embeddings = False
235
+ test_mismatched_shapes = True
236
+ test_model_parallel = False
237
+ has_attentions = False
238
+
239
+ def setUp(self):
240
+ self.model_tester = PatchTSMixerModelTester()
241
+ self.config_tester = ConfigTester(
242
+ self,
243
+ config_class=PatchTSMixerConfig,
244
+ has_text_modality=False,
245
+ prediction_length=self.model_tester.prediction_length,
246
+ common_properties=["hidden_size", "expansion_factor", "num_hidden_layers"],
247
+ )
248
+
249
+ def test_config(self):
250
+ self.config_tester.run_common_tests()
251
+
252
+ def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
253
+ inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
254
+
255
+ if model_class == PatchTSMixerForPrediction:
256
+ rng = random.Random(self.model_tester.seed_number)
257
+ labels = floats_tensor(
258
+ [
259
+ self.model_tester.batch_size,
260
+ self.model_tester.prediction_length,
261
+ self.model_tester.num_input_channels,
262
+ ],
263
+ rng=rng,
264
+ )
265
+ inputs_dict["future_values"] = labels
266
+ elif model_class in get_values(MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING):
267
+ rng = random.Random(self.model_tester.seed_number)
268
+ labels = ids_tensor([self.model_tester.batch_size], self.model_tester.num_targets, rng=rng)
269
+ inputs_dict["target_values"] = labels
270
+ elif model_class in get_values(MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING):
271
+ rng = random.Random(self.model_tester.seed_number)
272
+ labels = floats_tensor([self.model_tester.batch_size, self.model_tester.num_targets], rng=rng)
273
+ inputs_dict["target_values"] = labels
274
+
275
+ inputs_dict["output_hidden_states"] = True
276
+ return inputs_dict
277
+
278
+ def test_save_load_strict(self):
279
+ config, _ = self.model_tester.prepare_config_and_inputs()
280
+ for model_class in self.all_model_classes:
281
+ model = model_class(config)
282
+
283
+ with tempfile.TemporaryDirectory() as tmpdirname:
284
+ model.save_pretrained(tmpdirname)
285
+ model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True)
286
+ self.assertEqual(info["missing_keys"], [])
287
+
288
+ def test_hidden_states_output(self):
289
+ def check_hidden_states_output(inputs_dict, config, model_class):
290
+ model = model_class(config)
291
+ model.to(torch_device)
292
+ model.eval()
293
+
294
+ with torch.no_grad():
295
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
296
+
297
+ hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
298
+
299
+ expected_num_layers = getattr(
300
+ self.model_tester,
301
+ "expected_num_hidden_layers",
302
+ self.model_tester.num_hidden_layers,
303
+ )
304
+ self.assertEqual(len(hidden_states), expected_num_layers)
305
+
306
+ expected_hidden_size = self.model_tester.hidden_size
307
+ self.assertEqual(hidden_states[0].shape[-1], expected_hidden_size)
308
+
309
+ num_patch = self.model_tester.num_patches
310
+ self.assertListEqual(
311
+ list(hidden_states[0].shape[-2:]),
312
+ [num_patch, self.model_tester.hidden_size],
313
+ )
314
+
315
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
316
+
317
+ for model_class in self.all_model_classes:
318
+ check_hidden_states_output(inputs_dict, config, model_class)
319
+
320
+ @unittest.skip(reason="No tokens embeddings")
321
+ def test_resize_tokens_embeddings(self):
322
+ pass
323
+
324
+ def test_model_outputs_equivalence(self):
325
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
326
+
327
+ def set_nan_tensor_to_zero(t):
328
+ t[t != t] = 0
329
+ return t
330
+
331
+ def check_equivalence(model, tuple_inputs, dict_inputs, additional_kwargs={}):
332
+ with torch.no_grad():
333
+ tuple_output = model(**tuple_inputs, return_dict=False, **additional_kwargs)
334
+ output_ = model(**dict_inputs, return_dict=True, **additional_kwargs)
335
+ attributes_ = vars(output_)
336
+ dict_output = tuple(attributes_.values())
337
+
338
+ def recursive_check(tuple_object, dict_object):
339
+ if isinstance(tuple_object, (List, Tuple)):
340
+ for tuple_iterable_value, dict_iterable_value in zip(tuple_object, dict_object):
341
+ recursive_check(tuple_iterable_value, dict_iterable_value)
342
+ elif isinstance(tuple_object, Dict):
343
+ for tuple_iterable_value, dict_iterable_value in zip(
344
+ tuple_object.values(), dict_object.values()
345
+ ):
346
+ recursive_check(tuple_iterable_value, dict_iterable_value)
347
+ elif tuple_object is None:
348
+ return
349
+ else:
350
+ self.assertTrue(
351
+ torch.allclose(
352
+ set_nan_tensor_to_zero(tuple_object),
353
+ set_nan_tensor_to_zero(dict_object),
354
+ atol=1e-5,
355
+ ),
356
+ msg=(
357
+ "Tuple and dict output are not equal. Difference:"
358
+ f" {torch.max(torch.abs(tuple_object - dict_object))}. Tuple has `nan`:"
359
+ f" {torch.isnan(tuple_object).any()} and `inf`: {torch.isinf(tuple_object)}. Dict has"
360
+ f" `nan`: {torch.isnan(dict_object).any()} and `inf`: {torch.isinf(dict_object)}."
361
+ ),
362
+ )
363
+
364
+ recursive_check(tuple_output, dict_output)
365
+
366
+ for model_class in self.all_model_classes:
367
+ print(model_class)
368
+ model = model_class(config)
369
+ model.to(torch_device)
370
+ model.eval()
371
+
372
+ tuple_inputs = self._prepare_for_class(inputs_dict, model_class)
373
+ dict_inputs = self._prepare_for_class(inputs_dict, model_class)
374
+
375
+ check_equivalence(model, tuple_inputs, dict_inputs)
376
+
377
+ tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
378
+ dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
379
+ check_equivalence(model, tuple_inputs, dict_inputs)
380
+
381
+ tuple_inputs = self._prepare_for_class(inputs_dict, model_class)
382
+ dict_inputs = self._prepare_for_class(inputs_dict, model_class)
383
+ tuple_inputs.update({"output_hidden_states": False})
384
+ dict_inputs.update({"output_hidden_states": False})
385
+ check_equivalence(model, tuple_inputs, dict_inputs)
386
+
387
+ tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
388
+ dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
389
+ tuple_inputs.update({"output_hidden_states": False})
390
+ dict_inputs.update({"output_hidden_states": False})
391
+ check_equivalence(
392
+ model,
393
+ tuple_inputs,
394
+ dict_inputs,
395
+ )
396
+
397
+ def test_model_main_input_name(self):
398
+ model_signature = inspect.signature(getattr(PatchTSMixerModel, "forward"))
399
+ # The main input is the name of the argument after `self`
400
+ observed_main_input_name = list(model_signature.parameters.keys())[1]
401
+ self.assertEqual(PatchTSMixerModel.main_input_name, observed_main_input_name)
402
+
403
+ def test_forward_signature(self):
404
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
405
+
406
+ for model_class in self.all_model_classes:
407
+ model = model_class(config)
408
+ signature = inspect.signature(model.forward)
409
+ # signature.parameters is an OrderedDict => so arg_names order is deterministic
410
+ arg_names = [*signature.parameters.keys()]
411
+
412
+ if model_class == PatchTSMixerForPretraining:
413
+ expected_arg_names = [
414
+ "past_values",
415
+ "observed_mask",
416
+ "output_hidden_states",
417
+ "return_loss",
418
+ ]
419
+ elif model_class == PatchTSMixerModel:
420
+ expected_arg_names = [
421
+ "past_values",
422
+ "observed_mask",
423
+ "output_hidden_states",
424
+ ]
425
+ elif model_class in get_values(MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING) or model_class in get_values(
426
+ MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING
427
+ ):
428
+ expected_arg_names = [
429
+ "past_values",
430
+ "target_values",
431
+ "output_hidden_states",
432
+ "return_loss",
433
+ ]
434
+ else:
435
+ # PatchTSMixerForPrediction
436
+ expected_arg_names = [
437
+ "past_values",
438
+ "observed_mask",
439
+ "future_values",
440
+ "output_hidden_states",
441
+ "return_loss",
442
+ ]
443
+
444
+ self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names)
445
+
446
+ @is_flaky()
447
+ def test_retain_grad_hidden_states_attentions(self):
448
+ super().test_retain_grad_hidden_states_attentions()
449
+
450
+ @unittest.skip(reason="Model does not have input embeddings")
451
+ def test_model_get_set_embeddings(self):
452
+ pass
453
+
454
+
455
+ def prepare_batch(repo_id="ibm/patchtsmixer-etth1-test-data", file="pretrain_batch.pt"):
456
+ # TODO: Make repo public
457
+ file = hf_hub_download(repo_id=repo_id, filename=file, repo_type="dataset")
458
+ batch = torch.load(file, map_location=torch_device)
459
+ return batch
460
+
461
+
462
+ @require_torch
463
+ @slow
464
+ class PatchTSMixerModelIntegrationTests(unittest.TestCase):
465
+ def test_pretrain_head(self):
466
+ model = PatchTSMixerForPretraining.from_pretrained("ibm/patchtsmixer-etth1-pretrain").to(torch_device)
467
+ batch = prepare_batch()
468
+
469
+ torch.manual_seed(0)
470
+ with torch.no_grad():
471
+ output = model(past_values=batch["past_values"].to(torch_device)).prediction_outputs
472
+ num_patch = (
473
+ max(model.config.context_length, model.config.patch_length) - model.config.patch_length
474
+ ) // model.config.patch_stride + 1
475
+ expected_shape = torch.Size(
476
+ [
477
+ 64,
478
+ model.config.num_input_channels,
479
+ num_patch,
480
+ model.config.patch_length,
481
+ ]
482
+ )
483
+ self.assertEqual(output.shape, expected_shape)
484
+
485
+ expected_slice = torch.tensor([[[[-0.9106]],[[1.5326]],[[-0.8245]],[[0.7439]],[[-0.7830]],[[2.6256]],[[-0.6485]],]],device=torch_device) # fmt: skip
486
+ self.assertTrue(torch.allclose(output[0, :7, :1, :1], expected_slice, atol=TOLERANCE))
487
+
488
+ def test_forecasting_head(self):
489
+ model = PatchTSMixerForPrediction.from_pretrained("ibm/patchtsmixer-etth1-forecasting").to(torch_device)
490
+ batch = prepare_batch(file="forecast_batch.pt")
491
+
492
+ model.eval()
493
+ torch.manual_seed(0)
494
+ with torch.no_grad():
495
+ output = model(
496
+ past_values=batch["past_values"].to(torch_device),
497
+ future_values=batch["future_values"].to(torch_device),
498
+ ).prediction_outputs
499
+
500
+ expected_shape = torch.Size([64, model.config.prediction_length, model.config.num_input_channels])
501
+ self.assertEqual(output.shape, expected_shape)
502
+
503
+ expected_slice = torch.tensor(
504
+ [[0.2471, 0.5036, 0.3596, 0.5401, -0.0985, 0.3423, -0.8439]],
505
+ device=torch_device,
506
+ )
507
+ self.assertTrue(torch.allclose(output[0, :1, :7], expected_slice, atol=TOLERANCE))
508
+
509
+ def test_prediction_generation(self):
510
+ model = PatchTSMixerForPrediction.from_pretrained("ibm/patchtsmixer-etth1-generate").to(torch_device)
511
+ batch = prepare_batch(file="forecast_batch.pt")
512
+ print(batch["past_values"])
513
+
514
+ torch.manual_seed(0)
515
+ model.eval()
516
+ with torch.no_grad():
517
+ outputs = model.generate(past_values=batch["past_values"].to(torch_device))
518
+ expected_shape = torch.Size((64, 1, model.config.prediction_length, model.config.num_input_channels))
519
+
520
+ self.assertEqual(outputs.sequences.shape, expected_shape)
521
+
522
+ expected_slice = torch.tensor(
523
+ [[0.4308, -0.4731, 1.3512, -0.1038, -0.4655, 1.1279, -0.7179]],
524
+ device=torch_device,
525
+ )
526
+
527
+ mean_prediction = outputs.sequences.mean(dim=1)
528
+
529
+ self.assertTrue(torch.allclose(mean_prediction[0, -1:], expected_slice, atol=TOLERANCE))
530
+
531
+
532
+ @require_torch
533
+ class PatchTSMixerFunctionalTests(unittest.TestCase):
534
+ @classmethod
535
+ def setUpClass(cls):
536
+ """Setup method: Called once before test-cases execution"""
537
+ cls.params = {}
538
+ cls.params.update(
539
+ context_length=32,
540
+ patch_length=8,
541
+ num_input_channels=3,
542
+ patch_stride=8,
543
+ d_model=4,
544
+ expansion_factor=2,
545
+ num_layers=3,
546
+ dropout=0.2,
547
+ mode="common_channel", # common_channel, mix_channel
548
+ gated_attn=True,
549
+ norm_mlp="LayerNorm",
550
+ mask_type="random",
551
+ random_mask_ratio=0.5,
552
+ mask_patches=[2, 3],
553
+ forecast_mask_ratios=[1, 1],
554
+ mask_value=0,
555
+ masked_loss=True,
556
+ channel_consistent_masking=True,
557
+ head_dropout=0.2,
558
+ prediction_length=64,
559
+ out_channels=None,
560
+ # num_labels=3,
561
+ num_targets=3,
562
+ output_range=None,
563
+ head_aggregation=None,
564
+ scaling="std",
565
+ use_positional_encoding=False,
566
+ positional_encoding="sincos",
567
+ self_attn=False,
568
+ self_attn_heads=1,
569
+ num_parallel_samples=4,
570
+ )
571
+
572
+ cls.num_patches = (
573
+ max(cls.params["context_length"], cls.params["patch_length"]) - cls.params["patch_length"]
574
+ ) // cls.params["patch_stride"] + 1
575
+
576
+ # batch_size = 32
577
+ batch_size = 2
578
+
579
+ int(cls.params["prediction_length"] / cls.params["patch_length"])
580
+
581
+ cls.data = torch.rand(
582
+ batch_size,
583
+ cls.params["context_length"],
584
+ cls.params["num_input_channels"],
585
+ )
586
+
587
+ cls.enc_data = torch.rand(
588
+ batch_size,
589
+ cls.params["num_input_channels"],
590
+ cls.num_patches,
591
+ cls.params["patch_length"],
592
+ )
593
+
594
+ cls.enc_output = torch.rand(
595
+ batch_size,
596
+ cls.params["num_input_channels"],
597
+ cls.num_patches,
598
+ cls.params["d_model"],
599
+ )
600
+
601
+ cls.flat_enc_output = torch.rand(
602
+ batch_size,
603
+ cls.num_patches,
604
+ cls.params["d_model"],
605
+ )
606
+
607
+ cls.correct_pred_output = torch.rand(
608
+ batch_size,
609
+ cls.params["prediction_length"],
610
+ cls.params["num_input_channels"],
611
+ )
612
+ cls.correct_regression_output = torch.rand(batch_size, cls.params["num_targets"])
613
+
614
+ cls.correct_pretrain_output = torch.rand(
615
+ batch_size,
616
+ cls.params["num_input_channels"],
617
+ cls.num_patches,
618
+ cls.params["patch_length"],
619
+ )
620
+
621
+ cls.correct_forecast_output = torch.rand(
622
+ batch_size,
623
+ cls.params["prediction_length"],
624
+ cls.params["num_input_channels"],
625
+ )
626
+
627
+ cls.correct_sel_forecast_output = torch.rand(batch_size, cls.params["prediction_length"], 2)
628
+
629
+ cls.correct_classification_output = torch.rand(
630
+ batch_size,
631
+ cls.params["num_targets"],
632
+ )
633
+
634
+ cls.correct_classification_classes = torch.randint(0, cls.params["num_targets"], (batch_size,))
635
+
636
+ def test_patchtsmixer_encoder(self):
637
+ config = PatchTSMixerConfig(**self.__class__.params)
638
+ enc = PatchTSMixerEncoder(config)
639
+ output = enc(self.__class__.enc_data)
640
+ self.assertEqual(output.last_hidden_state.shape, self.__class__.enc_output.shape)
641
+
642
+ def test_patchmodel(self):
643
+ config = PatchTSMixerConfig(**self.__class__.params)
644
+ mdl = PatchTSMixerModel(config)
645
+ output = mdl(self.__class__.data)
646
+ self.assertEqual(output.last_hidden_state.shape, self.__class__.enc_output.shape)
647
+ self.assertEqual(output.patch_input.shape, self.__class__.enc_data.shape)
648
+
649
+ def test_pretrainhead(self):
650
+ config = PatchTSMixerConfig(**self.__class__.params)
651
+ head = PatchTSMixerPretrainHead(
652
+ config=config,
653
+ )
654
+ output = head(self.__class__.enc_output)
655
+
656
+ self.assertEqual(output.shape, self.__class__.correct_pretrain_output.shape)
657
+
658
+ def test_pretrain_full(self):
659
+ config = PatchTSMixerConfig(**self.__class__.params)
660
+ mdl = PatchTSMixerForPretraining(config)
661
+ output = mdl(self.__class__.data)
662
+ self.assertEqual(
663
+ output.prediction_outputs.shape,
664
+ self.__class__.correct_pretrain_output.shape,
665
+ )
666
+ self.assertEqual(output.last_hidden_state.shape, self.__class__.enc_output.shape)
667
+ self.assertEqual(output.loss.item() < np.inf, True)
668
+
669
+ def test_pretrain_full_with_return_dict(self):
670
+ config = PatchTSMixerConfig(**self.__class__.params)
671
+ mdl = PatchTSMixerForPretraining(config)
672
+ output = mdl(self.__class__.data, return_dict=False)
673
+ self.assertEqual(output[1].shape, self.__class__.correct_pretrain_output.shape)
674
+ self.assertEqual(output[2].shape, self.__class__.enc_output.shape)
675
+ self.assertEqual(output[0].item() < np.inf, True)
676
+
677
+ def test_forecast_head(self):
678
+ config = PatchTSMixerConfig(**self.__class__.params)
679
+ head = PatchTSMixerForPredictionHead(
680
+ config=config,
681
+ )
682
+ # output = head(self.__class__.enc_output, raw_data = self.__class__.correct_pretrain_output)
683
+ output = head(self.__class__.enc_output)
684
+
685
+ self.assertEqual(output.shape, self.__class__.correct_forecast_output.shape)
686
+
687
+ def check_module(
688
+ self,
689
+ task,
690
+ params=None,
691
+ output_hidden_states=True,
692
+ ):
693
+ config = PatchTSMixerConfig(**params)
694
+ if task == "forecast":
695
+ mdl = PatchTSMixerForPrediction(config)
696
+ target_input = self.__class__.correct_forecast_output
697
+ if config.prediction_channel_indices is not None:
698
+ target_output = self.__class__.correct_sel_forecast_output
699
+ else:
700
+ target_output = target_input
701
+ ref_samples = target_output.unsqueeze(1).expand(-1, config.num_parallel_samples, -1, -1)
702
+ ground_truth_arg = "future_values"
703
+ output_predictions_arg = "prediction_outputs"
704
+ elif task == "classification":
705
+ mdl = PatchTSMixerForTimeSeriesClassification(config)
706
+ target_input = self.__class__.correct_classification_classes
707
+ target_output = self.__class__.correct_classification_output
708
+ ground_truth_arg = "target_values"
709
+ output_predictions_arg = "prediction_outputs"
710
+ elif task == "regression":
711
+ mdl = PatchTSMixerForRegression(config)
712
+ target_input = self.__class__.correct_regression_output
713
+ target_output = self.__class__.correct_regression_output
714
+ ref_samples = target_output.unsqueeze(1).expand(-1, config.num_parallel_samples, -1)
715
+ ground_truth_arg = "target_values"
716
+ output_predictions_arg = "regression_outputs"
717
+ elif task == "pretrain":
718
+ mdl = PatchTSMixerForPretraining(config)
719
+ target_input = None
720
+ target_output = self.__class__.correct_pretrain_output
721
+ ground_truth_arg = None
722
+ output_predictions_arg = "prediction_outputs"
723
+ else:
724
+ print("invalid task")
725
+
726
+ enc_output = self.__class__.enc_output
727
+
728
+ if target_input is None:
729
+ output = mdl(self.__class__.data, output_hidden_states=output_hidden_states)
730
+ else:
731
+ output = mdl(
732
+ self.__class__.data,
733
+ **{
734
+ ground_truth_arg: target_input,
735
+ "output_hidden_states": output_hidden_states,
736
+ },
737
+ )
738
+
739
+ prediction_outputs = getattr(output, output_predictions_arg)
740
+ if isinstance(prediction_outputs, tuple):
741
+ for t in prediction_outputs:
742
+ self.assertEqual(t.shape, target_output.shape)
743
+ else:
744
+ self.assertEqual(prediction_outputs.shape, target_output.shape)
745
+
746
+ self.assertEqual(output.last_hidden_state.shape, enc_output.shape)
747
+
748
+ if output_hidden_states is True:
749
+ self.assertEqual(len(output.hidden_states), params["num_layers"])
750
+
751
+ else:
752
+ self.assertEqual(output.hidden_states, None)
753
+
754
+ self.assertEqual(output.loss.item() < np.inf, True)
755
+
756
+ if config.loss == "nll" and task in ["forecast", "regression"]:
757
+ samples = mdl.generate(self.__class__.data)
758
+ self.assertEqual(samples.sequences.shape, ref_samples.shape)
759
+
760
+ @parameterized.expand(
761
+ list(
762
+ itertools.product(
763
+ ["common_channel", "mix_channel"],
764
+ [True, False],
765
+ [True, False, "mean", "std"],
766
+ [True, False],
767
+ [None, [0, 2]],
768
+ ["mse", "nll"],
769
+ )
770
+ )
771
+ )
772
+ def test_forecast(self, mode, self_attn, scaling, gated_attn, prediction_channel_indices, loss):
773
+ params = self.__class__.params.copy()
774
+ params.update(
775
+ mode=mode,
776
+ self_attn=self_attn,
777
+ scaling=scaling,
778
+ prediction_channel_indices=prediction_channel_indices,
779
+ gated_attn=gated_attn,
780
+ loss=loss,
781
+ )
782
+
783
+ self.check_module(task="forecast", params=params)
784
+
785
+ @parameterized.expand(
786
+ list(
787
+ itertools.product(
788
+ ["common_channel", "mix_channel"],
789
+ [True, False],
790
+ [True, False, "mean", "std"],
791
+ [True, False],
792
+ ["max_pool", "avg_pool"],
793
+ )
794
+ )
795
+ )
796
+ def test_classification(self, mode, self_attn, scaling, gated_attn, head_aggregation):
797
+ params = self.__class__.params.copy()
798
+ params.update(
799
+ mode=mode,
800
+ self_attn=self_attn,
801
+ scaling=scaling,
802
+ head_aggregation=head_aggregation,
803
+ gated_attn=gated_attn,
804
+ )
805
+
806
+ self.check_module(task="classification", params=params)
807
+
808
+ @parameterized.expand(
809
+ list(
810
+ itertools.product(
811
+ ["common_channel", "mix_channel"],
812
+ [True, False],
813
+ [True, False, "mean", "std"],
814
+ [True, False],
815
+ ["max_pool", "avg_pool"],
816
+ ["mse", "nll"],
817
+ )
818
+ )
819
+ )
820
+ def test_regression(self, mode, self_attn, scaling, gated_attn, head_aggregation, loss):
821
+ params = self.__class__.params.copy()
822
+ params.update(
823
+ mode=mode,
824
+ self_attn=self_attn,
825
+ scaling=scaling,
826
+ head_aggregation=head_aggregation,
827
+ gated_attn=gated_attn,
828
+ loss=loss,
829
+ )
830
+
831
+ self.check_module(task="regression", params=params)
832
+
833
+ @parameterized.expand(
834
+ list(
835
+ itertools.product(
836
+ ["common_channel", "mix_channel"],
837
+ [True, False],
838
+ [True, False, "mean", "std"],
839
+ [True, False],
840
+ ["random", "forecast"],
841
+ [True, False],
842
+ [True, False],
843
+ )
844
+ )
845
+ )
846
+ def test_pretrain(
847
+ self,
848
+ mode,
849
+ self_attn,
850
+ scaling,
851
+ gated_attn,
852
+ mask_type,
853
+ masked_loss,
854
+ channel_consistent_masking,
855
+ ):
856
+ params = self.__class__.params.copy()
857
+ params.update(
858
+ mode=mode,
859
+ self_attn=self_attn,
860
+ scaling=scaling,
861
+ gated_attn=gated_attn,
862
+ mask_type=mask_type,
863
+ masked_loss=masked_loss,
864
+ channel_consistent_masking=channel_consistent_masking,
865
+ )
866
+
867
+ self.check_module(task="pretrain", params=params)
868
+
869
+ def forecast_full_module(self, params=None, output_hidden_states=False, return_dict=None):
870
+ config = PatchTSMixerConfig(**params)
871
+ mdl = PatchTSMixerForPrediction(config)
872
+
873
+ target_val = self.__class__.correct_forecast_output
874
+
875
+ if config.prediction_channel_indices is not None:
876
+ target_val = self.__class__.correct_sel_forecast_output
877
+
878
+ enc_output = self.__class__.enc_output
879
+
880
+ output = mdl(
881
+ self.__class__.data,
882
+ future_values=self.__class__.correct_forecast_output,
883
+ output_hidden_states=output_hidden_states,
884
+ return_dict=return_dict,
885
+ )
886
+
887
+ if isinstance(output, tuple):
888
+ output = PatchTSMixerForPredictionOutput(*output)
889
+
890
+ if config.loss == "mse":
891
+ self.assertEqual(output.prediction_outputs.shape, target_val.shape)
892
+
893
+ self.assertEqual(output.last_hidden_state.shape, enc_output.shape)
894
+
895
+ if output_hidden_states is True:
896
+ self.assertEqual(len(output.hidden_states), params["num_layers"])
897
+
898
+ else:
899
+ self.assertEqual(output.hidden_states, None)
900
+
901
+ self.assertEqual(output.loss.item() < np.inf, True)
902
+
903
+ if config.loss == "nll":
904
+ samples = mdl.generate(self.__class__.data)
905
+ ref_samples = target_val.unsqueeze(1).expand(-1, params["num_parallel_samples"], -1, -1)
906
+ self.assertEqual(samples.sequences.shape, ref_samples.shape)
907
+
908
+ def test_forecast_full(self):
909
+ self.check_module(task="forecast", params=self.__class__.params, output_hidden_states=True)
910
+ # self.forecast_full_module(self.__class__.params, output_hidden_states = True)
911
+
912
+ def test_forecast_full_2(self):
913
+ params = self.__class__.params.copy()
914
+ params.update(
915
+ mode="mix_channel",
916
+ )
917
+ self.forecast_full_module(params, output_hidden_states=True)
918
+
919
+ def test_forecast_full_2_with_return_dict(self):
920
+ params = self.__class__.params.copy()
921
+ params.update(
922
+ mode="mix_channel",
923
+ )
924
+ self.forecast_full_module(params, output_hidden_states=True, return_dict=False)
925
+
926
+ def test_forecast_full_3(self):
927
+ params = self.__class__.params.copy()
928
+ params.update(
929
+ mode="mix_channel",
930
+ )
931
+ self.forecast_full_module(params, output_hidden_states=True)
932
+
933
+ def test_forecast_full_5(self):
934
+ params = self.__class__.params.copy()
935
+ params.update(
936
+ self_attn=True,
937
+ use_positional_encoding=True,
938
+ positional_encoding="sincos",
939
+ )
940
+ self.forecast_full_module(params, output_hidden_states=True)
941
+
942
+ def test_forecast_full_4(self):
943
+ params = self.__class__.params.copy()
944
+ params.update(
945
+ mode="mix_channel",
946
+ prediction_channel_indices=[0, 2],
947
+ )
948
+ self.forecast_full_module(params)
949
+
950
+ def test_forecast_full_distributional(self):
951
+ params = self.__class__.params.copy()
952
+ params.update(
953
+ mode="mix_channel",
954
+ prediction_channel_indices=[0, 2],
955
+ loss="nll",
956
+ distribution_output="normal",
957
+ )
958
+
959
+ self.forecast_full_module(params)
960
+
961
+ def test_forecast_full_distributional_2(self):
962
+ params = self.__class__.params.copy()
963
+ params.update(
964
+ mode="mix_channel",
965
+ prediction_channel_indices=[0, 2],
966
+ loss="nll",
967
+ # distribution_output = "normal",
968
+ )
969
+ self.forecast_full_module(params)
970
+
971
+ def test_forecast_full_distributional_3(self):
972
+ params = self.__class__.params.copy()
973
+ params.update(
974
+ mode="mix_channel",
975
+ # prediction_channel_indices=[0, 2],
976
+ loss="nll",
977
+ distribution_output="normal",
978
+ )
979
+ self.forecast_full_module(params)
980
+
981
+ def test_forecast_full_distributional_4(self):
982
+ params = self.__class__.params.copy()
983
+ params.update(
984
+ mode="mix_channel",
985
+ # prediction_channel_indices=[0, 2],
986
+ loss="nll",
987
+ distribution_output="normal",
988
+ )
989
+ self.forecast_full_module(params)
990
+
991
+ def test_classification_head(self):
992
+ config = PatchTSMixerConfig(**self.__class__.params)
993
+ head = PatchTSMixerLinearHead(
994
+ config=config,
995
+ )
996
+ # output = head(self.__class__.enc_output, raw_data = self.__class__.correct_pretrain_output)
997
+ output = head(self.__class__.enc_output)
998
+
999
+ self.assertEqual(output.shape, self.__class__.correct_classification_output.shape)
1000
+
1001
+ def test_classification_full(self):
1002
+ config = PatchTSMixerConfig(**self.__class__.params)
1003
+ mdl = PatchTSMixerForTimeSeriesClassification(config)
1004
+ output = mdl(
1005
+ self.__class__.data,
1006
+ target_values=self.__class__.correct_classification_classes,
1007
+ )
1008
+ self.assertEqual(
1009
+ output.prediction_outputs.shape,
1010
+ self.__class__.correct_classification_output.shape,
1011
+ )
1012
+ self.assertEqual(output.last_hidden_state.shape, self.__class__.enc_output.shape)
1013
+ self.assertEqual(output.loss.item() < np.inf, True)
1014
+
1015
+ def test_classification_full_with_return_dict(self):
1016
+ config = PatchTSMixerConfig(**self.__class__.params)
1017
+ mdl = PatchTSMixerForTimeSeriesClassification(config)
1018
+ output = mdl(
1019
+ self.__class__.data,
1020
+ target_values=self.__class__.correct_classification_classes,
1021
+ return_dict=False,
1022
+ )
1023
+ if isinstance(output, tuple):
1024
+ output = PatchTSMixerForTimeSeriesClassificationOutput(*output)
1025
+ self.assertEqual(
1026
+ output.prediction_outputs.shape,
1027
+ self.__class__.correct_classification_output.shape,
1028
+ )
1029
+ self.assertEqual(output.last_hidden_state.shape, self.__class__.enc_output.shape)
1030
+ self.assertEqual(output.loss.item() < np.inf, True)
1031
+
1032
+ def test_regression_head(self):
1033
+ config = PatchTSMixerConfig(**self.__class__.params)
1034
+ head = PatchTSMixerLinearHead(
1035
+ config=config,
1036
+ )
1037
+ output = head(self.__class__.enc_output)
1038
+ self.assertEqual(output.shape, self.__class__.correct_regression_output.shape)
1039
+
1040
+ def test_regression_full(self):
1041
+ config = PatchTSMixerConfig(**self.__class__.params)
1042
+ mdl = PatchTSMixerForRegression(config)
1043
+ output = mdl(self.__class__.data, target_values=self.__class__.correct_regression_output)
1044
+ self.assertEqual(
1045
+ output.regression_outputs.shape,
1046
+ self.__class__.correct_regression_output.shape,
1047
+ )
1048
+ self.assertEqual(output.last_hidden_state.shape, self.__class__.enc_output.shape)
1049
+ self.assertEqual(output.loss.item() < np.inf, True)
1050
+
1051
+ def test_regression_full_with_return_dict(self):
1052
+ config = PatchTSMixerConfig(**self.__class__.params)
1053
+ mdl = PatchTSMixerForRegression(config)
1054
+ output = mdl(
1055
+ self.__class__.data,
1056
+ target_values=self.__class__.correct_regression_output,
1057
+ return_dict=False,
1058
+ )
1059
+ if isinstance(output, tuple):
1060
+ output = PatchTSMixerForRegressionOutput(*output)
1061
+ self.assertEqual(
1062
+ output.regression_outputs.shape,
1063
+ self.__class__.correct_regression_output.shape,
1064
+ )
1065
+ self.assertEqual(output.last_hidden_state.shape, self.__class__.enc_output.shape)
1066
+ self.assertEqual(output.loss.item() < np.inf, True)
1067
+
1068
+ def test_regression_full_distribute(self):
1069
+ params = self.__class__.params.copy()
1070
+ params.update(loss="nll", distribution_output="normal")
1071
+
1072
+ config = PatchTSMixerConfig(**params)
1073
+
1074
+ mdl = PatchTSMixerForRegression(config)
1075
+ output = mdl(self.__class__.data, target_values=self.__class__.correct_regression_output)
1076
+ self.assertEqual(
1077
+ output.regression_outputs[0].shape,
1078
+ self.__class__.correct_regression_output.shape,
1079
+ )
1080
+ self.assertEqual(
1081
+ output.regression_outputs[1].shape,
1082
+ self.__class__.correct_regression_output.shape,
1083
+ )
1084
+ self.assertEqual(output.last_hidden_state.shape, self.__class__.enc_output.shape)
1085
+ self.assertEqual(output.loss.item() < np.inf, True)
1086
+
1087
+ if config.loss == "nll":
1088
+ samples = mdl.generate(self.__class__.data)
1089
+ ref_samples = self.__class__.correct_regression_output.unsqueeze(1).expand(
1090
+ -1, params["num_parallel_samples"], -1
1091
+ )
1092
+ self.assertEqual(samples.sequences.shape, ref_samples.shape)
1093
+
1094
+ def test_regression_full_distribute_2(self):
1095
+ params = self.__class__.params.copy()
1096
+ params.update(loss="nll", distribution_output="student_t")
1097
+
1098
+ config = PatchTSMixerConfig(**params)
1099
+
1100
+ mdl = PatchTSMixerForRegression(config)
1101
+ output = mdl(self.__class__.data, target_values=self.__class__.correct_regression_output)
1102
+ self.assertEqual(
1103
+ output.regression_outputs[0].shape,
1104
+ self.__class__.correct_regression_output.shape,
1105
+ )
1106
+ self.assertEqual(
1107
+ output.regression_outputs[1].shape,
1108
+ self.__class__.correct_regression_output.shape,
1109
+ )
1110
+ self.assertEqual(output.last_hidden_state.shape, self.__class__.enc_output.shape)
1111
+ self.assertEqual(output.loss.item() < np.inf, True)
1112
+
1113
+ if config.loss == "nll":
1114
+ samples = mdl.generate(self.__class__.data)
1115
+ ref_samples = self.__class__.correct_regression_output.unsqueeze(1).expand(
1116
+ -1, params["num_parallel_samples"], -1
1117
+ )
1118
+ self.assertEqual(samples.sequences.shape, ref_samples.shape)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/patchtst/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/patchtst/test_modeling_patchtst.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 PatchTST model."""
16
+
17
+ import inspect
18
+ import random
19
+ import tempfile
20
+ import unittest
21
+
22
+ from huggingface_hub import hf_hub_download
23
+
24
+ from transformers import is_torch_available
25
+ from transformers.models.auto import get_values
26
+ from transformers.testing_utils import is_flaky, require_torch, slow, torch_device
27
+
28
+ from ...test_configuration_common import ConfigTester
29
+ from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
30
+ from ...test_pipeline_mixin import PipelineTesterMixin
31
+
32
+
33
+ TOLERANCE = 1e-4
34
+
35
+ if is_torch_available():
36
+ import torch
37
+
38
+ from transformers import (
39
+ MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING,
40
+ MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING,
41
+ PatchTSTConfig,
42
+ PatchTSTForClassification,
43
+ PatchTSTForPrediction,
44
+ PatchTSTForPretraining,
45
+ PatchTSTForRegression,
46
+ PatchTSTModel,
47
+ )
48
+
49
+
50
+ @require_torch
51
+ class PatchTSTModelTester:
52
+ def __init__(
53
+ self,
54
+ parent,
55
+ batch_size=13,
56
+ prediction_length=7,
57
+ context_length=14,
58
+ patch_length=5,
59
+ patch_stride=5,
60
+ num_input_channels=1,
61
+ num_time_features=1,
62
+ is_training=True,
63
+ hidden_size=16,
64
+ num_hidden_layers=2,
65
+ num_attention_heads=4,
66
+ intermediate_size=4,
67
+ hidden_act="gelu",
68
+ hidden_dropout_prob=0.1,
69
+ attention_probs_dropout_prob=0.1,
70
+ distil=False,
71
+ seed=42,
72
+ num_targets=2,
73
+ mask_type="random",
74
+ random_mask_ratio=0,
75
+ ):
76
+ self.parent = parent
77
+ self.batch_size = batch_size
78
+ self.prediction_length = prediction_length
79
+ self.context_length = context_length
80
+ self.patch_length = patch_length
81
+ self.patch_stride = patch_stride
82
+ self.num_input_channels = num_input_channels
83
+ self.num_time_features = num_time_features
84
+ self.is_training = is_training
85
+ self.hidden_size = hidden_size
86
+ self.num_hidden_layers = num_hidden_layers
87
+ self.num_attention_heads = num_attention_heads
88
+ self.intermediate_size = intermediate_size
89
+ self.hidden_act = hidden_act
90
+ self.hidden_dropout_prob = hidden_dropout_prob
91
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
92
+ self.mask_type = mask_type
93
+ self.random_mask_ratio = random_mask_ratio
94
+
95
+ self.seed = seed
96
+ self.num_targets = num_targets
97
+ self.distil = distil
98
+ self.num_patches = (max(self.context_length, self.patch_length) - self.patch_length) // self.patch_stride + 1
99
+ # define seq_length so that it can pass the test_attention_outputs
100
+ self.seq_length = self.num_patches
101
+
102
+ def get_config(self):
103
+ return PatchTSTConfig(
104
+ prediction_length=self.prediction_length,
105
+ patch_length=self.patch_length,
106
+ patch_stride=self.patch_stride,
107
+ num_input_channels=self.num_input_channels,
108
+ d_model=self.hidden_size,
109
+ num_hidden_layers=self.num_hidden_layers,
110
+ num_attention_heads=self.num_attention_heads,
111
+ ffn_dim=self.intermediate_size,
112
+ dropout=self.hidden_dropout_prob,
113
+ attention_dropout=self.attention_probs_dropout_prob,
114
+ context_length=self.context_length,
115
+ activation_function=self.hidden_act,
116
+ seed=self.seed,
117
+ num_targets=self.num_targets,
118
+ mask_type=self.mask_type,
119
+ random_mask_ratio=self.random_mask_ratio,
120
+ )
121
+
122
+ def prepare_patchtst_inputs_dict(self, config):
123
+ _past_length = config.context_length
124
+ # bs, num_input_channels, num_patch, patch_len
125
+
126
+ # [bs x seq_len x num_input_channels]
127
+ past_values = floats_tensor([self.batch_size, _past_length, self.num_input_channels])
128
+
129
+ future_values = floats_tensor([self.batch_size, config.prediction_length, self.num_input_channels])
130
+
131
+ inputs_dict = {
132
+ "past_values": past_values,
133
+ "future_values": future_values,
134
+ }
135
+ return inputs_dict
136
+
137
+ def prepare_config_and_inputs(self):
138
+ config = self.get_config()
139
+ inputs_dict = self.prepare_patchtst_inputs_dict(config)
140
+ return config, inputs_dict
141
+
142
+ def prepare_config_and_inputs_for_common(self):
143
+ config, inputs_dict = self.prepare_config_and_inputs()
144
+ return config, inputs_dict
145
+
146
+
147
+ @require_torch
148
+ class PatchTSTModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
149
+ all_model_classes = (
150
+ (
151
+ PatchTSTModel,
152
+ PatchTSTForPrediction,
153
+ PatchTSTForPretraining,
154
+ PatchTSTForClassification,
155
+ PatchTSTForRegression,
156
+ )
157
+ if is_torch_available()
158
+ else ()
159
+ )
160
+
161
+ pipeline_model_mapping = {"feature-extraction": PatchTSTModel} if is_torch_available() else {}
162
+ is_encoder_decoder = False
163
+ test_pruning = False
164
+ test_head_masking = False
165
+ test_missing_keys = True
166
+ test_torchscript = False
167
+ test_inputs_embeds = False
168
+
169
+ test_resize_embeddings = True
170
+ test_resize_position_embeddings = False
171
+ test_mismatched_shapes = True
172
+ test_model_parallel = False
173
+ has_attentions = True
174
+
175
+ def setUp(self):
176
+ self.model_tester = PatchTSTModelTester(self)
177
+ self.config_tester = ConfigTester(
178
+ self,
179
+ config_class=PatchTSTConfig,
180
+ has_text_modality=False,
181
+ prediction_length=self.model_tester.prediction_length,
182
+ )
183
+
184
+ def test_config(self):
185
+ self.config_tester.run_common_tests()
186
+
187
+ def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
188
+ inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
189
+
190
+ # if PatchTSTForPretraining
191
+ if model_class == PatchTSTForPretraining:
192
+ inputs_dict.pop("future_values")
193
+ # else if classification model:
194
+ elif model_class in get_values(MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING):
195
+ rng = random.Random(self.model_tester.seed)
196
+ labels = ids_tensor([self.model_tester.batch_size], self.model_tester.num_targets, rng=rng)
197
+ inputs_dict["target_values"] = labels
198
+ inputs_dict.pop("future_values")
199
+ elif model_class in get_values(MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING):
200
+ rng = random.Random(self.model_tester.seed)
201
+ target_values = floats_tensor([self.model_tester.batch_size, self.model_tester.num_targets], rng=rng)
202
+ inputs_dict["target_values"] = target_values
203
+ inputs_dict.pop("future_values")
204
+ return inputs_dict
205
+
206
+ def test_save_load_strict(self):
207
+ config, _ = self.model_tester.prepare_config_and_inputs()
208
+ for model_class in self.all_model_classes:
209
+ model = model_class(config)
210
+
211
+ with tempfile.TemporaryDirectory() as tmpdirname:
212
+ model.save_pretrained(tmpdirname)
213
+ model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True)
214
+ self.assertEqual(info["missing_keys"], [])
215
+
216
+ def test_hidden_states_output(self):
217
+ def check_hidden_states_output(inputs_dict, config, model_class):
218
+ model = model_class(config)
219
+ model.to(torch_device)
220
+ model.eval()
221
+
222
+ with torch.no_grad():
223
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
224
+
225
+ hidden_states = outputs.hidden_states
226
+
227
+ expected_num_layers = getattr(
228
+ self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers
229
+ )
230
+ self.assertEqual(len(hidden_states), expected_num_layers)
231
+
232
+ num_patch = self.model_tester.num_patches
233
+ self.assertListEqual(
234
+ list(hidden_states[0].shape[-2:]),
235
+ [num_patch, self.model_tester.hidden_size],
236
+ )
237
+
238
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
239
+
240
+ for model_class in self.all_model_classes:
241
+ inputs_dict["output_hidden_states"] = True
242
+ check_hidden_states_output(inputs_dict, config, model_class)
243
+
244
+ # check that output_hidden_states also work using config
245
+ del inputs_dict["output_hidden_states"]
246
+ config.output_hidden_states = True
247
+
248
+ check_hidden_states_output(inputs_dict, config, model_class)
249
+
250
+ @unittest.skip(reason="we have no tokens embeddings")
251
+ def test_resize_tokens_embeddings(self):
252
+ pass
253
+
254
+ def test_model_main_input_name(self):
255
+ model_signature = inspect.signature(getattr(PatchTSTModel, "forward"))
256
+ # The main input is the name of the argument after `self`
257
+ observed_main_input_name = list(model_signature.parameters.keys())[1]
258
+ self.assertEqual(PatchTSTModel.main_input_name, observed_main_input_name)
259
+
260
+ def test_forward_signature(self):
261
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
262
+
263
+ for model_class in self.all_model_classes:
264
+ model = model_class(config)
265
+ signature = inspect.signature(model.forward)
266
+ # signature.parameters is an OrderedDict => so arg_names order is deterministic
267
+ arg_names = [*signature.parameters.keys()]
268
+
269
+ if model_class == PatchTSTForPretraining:
270
+ expected_arg_names = [
271
+ "past_values",
272
+ "past_observed_mask",
273
+ ]
274
+ elif model_class in get_values(MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING) or model_class in get_values(
275
+ MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING
276
+ ):
277
+ expected_arg_names = ["past_values", "target_values", "past_observed_mask"]
278
+ else:
279
+ expected_arg_names = [
280
+ "past_values",
281
+ "past_observed_mask",
282
+ "future_values",
283
+ ]
284
+
285
+ expected_arg_names.extend(
286
+ [
287
+ "output_hidden_states",
288
+ "output_attentions",
289
+ "return_dict",
290
+ ]
291
+ )
292
+
293
+ self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names)
294
+
295
+ @is_flaky()
296
+ def test_retain_grad_hidden_states_attentions(self):
297
+ super().test_retain_grad_hidden_states_attentions()
298
+
299
+ @unittest.skip(reason="Model does not have input embeddings")
300
+ def test_model_get_set_embeddings(self):
301
+ pass
302
+
303
+
304
+ def prepare_batch(repo_id="hf-internal-testing/etth1-hourly-batch", file="train-batch.pt"):
305
+ file = hf_hub_download(repo_id=repo_id, filename=file, repo_type="dataset")
306
+ batch = torch.load(file, map_location=torch_device)
307
+ return batch
308
+
309
+
310
+ # Note: Pretrained model is not yet downloadable.
311
+ @require_torch
312
+ @slow
313
+ class PatchTSTModelIntegrationTests(unittest.TestCase):
314
+ # Publishing of pretrained weights are under internal review. Pretrained model is not yet downloadable.
315
+ def test_pretrain_head(self):
316
+ model = PatchTSTForPretraining.from_pretrained("namctin/patchtst_etth1_pretrain").to(torch_device)
317
+ batch = prepare_batch()
318
+
319
+ torch.manual_seed(0)
320
+ with torch.no_grad():
321
+ output = model(past_values=batch["past_values"].to(torch_device)).prediction_output
322
+ num_patch = (
323
+ max(model.config.context_length, model.config.patch_length) - model.config.patch_length
324
+ ) // model.config.patch_stride + 1
325
+ expected_shape = torch.Size([64, model.config.num_input_channels, num_patch, model.config.patch_length])
326
+ self.assertEqual(output.shape, expected_shape)
327
+
328
+ expected_slice = torch.tensor(
329
+ [[[-0.0173]], [[-1.0379]], [[-0.1030]], [[0.3642]], [[0.1601]], [[-1.3136]], [[0.8780]]],
330
+ device=torch_device,
331
+ )
332
+ self.assertTrue(torch.allclose(output[0, :7, :1, :1], expected_slice, atol=TOLERANCE))
333
+
334
+ # Publishing of pretrained weights are under internal review. Pretrained model is not yet downloadable.
335
+ def test_prediction_head(self):
336
+ model = PatchTSTForPrediction.from_pretrained("namctin/patchtst_etth1_forecast").to(torch_device)
337
+ batch = prepare_batch(file="test-batch.pt")
338
+
339
+ torch.manual_seed(0)
340
+ with torch.no_grad():
341
+ output = model(
342
+ past_values=batch["past_values"].to(torch_device),
343
+ future_values=batch["future_values"].to(torch_device),
344
+ ).prediction_outputs
345
+ expected_shape = torch.Size([64, model.config.prediction_length, model.config.num_input_channels])
346
+ self.assertEqual(output.shape, expected_shape)
347
+
348
+ expected_slice = torch.tensor(
349
+ [[0.5142, 0.6928, 0.6118, 0.5724, -0.3735, -0.1336, -0.7124]],
350
+ device=torch_device,
351
+ )
352
+ self.assertTrue(torch.allclose(output[0, :1, :7], expected_slice, atol=TOLERANCE))
353
+
354
+ def test_prediction_generation(self):
355
+ model = PatchTSTForPrediction.from_pretrained("namctin/patchtst_etth1_forecast").to(torch_device)
356
+ batch = prepare_batch(file="test-batch.pt")
357
+
358
+ torch.manual_seed(0)
359
+ with torch.no_grad():
360
+ outputs = model.generate(past_values=batch["past_values"].to(torch_device))
361
+ expected_shape = torch.Size((64, 1, model.config.prediction_length, model.config.num_input_channels))
362
+
363
+ self.assertEqual(outputs.sequences.shape, expected_shape)
364
+
365
+ expected_slice = torch.tensor(
366
+ [[0.4075, 0.3716, 0.4786, 0.2842, -0.3107, -0.0569, -0.7489]],
367
+ device=torch_device,
368
+ )
369
+ mean_prediction = outputs.sequences.mean(dim=1)
370
+ self.assertTrue(torch.allclose(mean_prediction[0, -1:], expected_slice, atol=TOLERANCE))
371
+
372
+ def test_regression_generation(self):
373
+ model = PatchTSTForRegression.from_pretrained("ibm/patchtst-etth1-regression-distribution").to(torch_device)
374
+ batch = prepare_batch(repo_id="ibm/patchtst-etth1-test-data", file="regression_distribution_batch.pt")
375
+
376
+ torch.manual_seed(0)
377
+ model.eval()
378
+ with torch.no_grad():
379
+ outputs = model.generate(past_values=batch["past_values"].to(torch_device))
380
+ expected_shape = torch.Size((64, model.config.num_parallel_samples, model.config.num_targets))
381
+ self.assertEqual(outputs.sequences.shape, expected_shape)
382
+
383
+ expected_slice = torch.tensor(
384
+ [[-0.08046409], [-0.06570087], [-0.28218266], [-0.20636195], [-0.11787311]],
385
+ device=torch_device,
386
+ )
387
+ mean_prediction = outputs.sequences.mean(dim=1)
388
+ self.assertTrue(torch.allclose(mean_prediction[-5:], expected_slice, rtol=TOLERANCE))
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pegasus/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pegasus/test_modeling_flax_pegasus.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+
17
+ import unittest
18
+
19
+ from transformers import PegasusConfig, PegasusTokenizer, is_flax_available
20
+ from transformers.testing_utils import require_flax, slow
21
+
22
+ from ...test_configuration_common import ConfigTester
23
+ from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor
24
+
25
+
26
+ if is_flax_available():
27
+ import os
28
+
29
+ # The slow tests are often failing with OOM error on GPU
30
+ # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
31
+ # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
32
+ os.environ["XLA_PYTHON_CLIENT_ALLOCATOR"] = "platform"
33
+ import jax
34
+ import jax.numpy as jnp
35
+ import numpy as np
36
+
37
+ from transformers import FlaxPegasusForConditionalGeneration, FlaxPegasusModel
38
+
39
+
40
+ @require_flax
41
+ class FlaxPegasusModelTester:
42
+ config_cls = PegasusConfig
43
+ config_updates = {}
44
+ hidden_act = "gelu"
45
+
46
+ def __init__(
47
+ self,
48
+ parent,
49
+ batch_size=13,
50
+ seq_length=7,
51
+ is_training=True,
52
+ use_labels=False,
53
+ vocab_size=99,
54
+ hidden_size=32,
55
+ num_hidden_layers=2,
56
+ num_attention_heads=4,
57
+ intermediate_size=37,
58
+ hidden_dropout_prob=0.1,
59
+ attention_probs_dropout_prob=0.1,
60
+ max_position_embeddings=20,
61
+ eos_token_id=2,
62
+ pad_token_id=1,
63
+ bos_token_id=0,
64
+ ):
65
+ self.parent = parent
66
+ self.batch_size = batch_size
67
+ self.seq_length = seq_length
68
+ self.is_training = is_training
69
+ self.use_labels = use_labels
70
+ self.vocab_size = vocab_size
71
+ self.hidden_size = hidden_size
72
+ self.num_hidden_layers = num_hidden_layers
73
+ self.num_attention_heads = num_attention_heads
74
+ self.intermediate_size = intermediate_size
75
+
76
+ self.hidden_dropout_prob = hidden_dropout_prob
77
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
78
+ self.max_position_embeddings = max_position_embeddings
79
+ self.eos_token_id = eos_token_id
80
+ self.pad_token_id = pad_token_id
81
+ self.bos_token_id = bos_token_id
82
+
83
+ def prepare_config_and_inputs_for_common(self):
84
+ input_ids = ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size).clip(3, self.vocab_size)
85
+ eos_tensor = np.expand_dims(np.array([self.eos_token_id] * self.batch_size), 1)
86
+ input_ids = np.concatenate([input_ids, eos_tensor], axis=1)
87
+
88
+ decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
89
+
90
+ config = self.config_cls(
91
+ vocab_size=self.vocab_size,
92
+ d_model=self.hidden_size,
93
+ encoder_layers=self.num_hidden_layers,
94
+ decoder_layers=self.num_hidden_layers,
95
+ encoder_attention_heads=self.num_attention_heads,
96
+ decoder_attention_heads=self.num_attention_heads,
97
+ encoder_ffn_dim=self.intermediate_size,
98
+ decoder_ffn_dim=self.intermediate_size,
99
+ dropout=self.hidden_dropout_prob,
100
+ attention_dropout=self.attention_probs_dropout_prob,
101
+ max_position_embeddings=self.max_position_embeddings,
102
+ eos_token_ids=[2],
103
+ bos_token_id=self.bos_token_id,
104
+ pad_token_id=self.pad_token_id,
105
+ decoder_start_token_id=self.pad_token_id,
106
+ **self.config_updates,
107
+ )
108
+ inputs_dict = prepare_pegasus_inputs_dict(config, input_ids, decoder_input_ids)
109
+ return config, inputs_dict
110
+
111
+ def check_use_cache_forward(self, model_class_name, config, inputs_dict):
112
+ max_decoder_length = 20
113
+ model = model_class_name(config)
114
+
115
+ encoder_outputs = model.encode(inputs_dict["input_ids"])
116
+
117
+ decoder_input_ids, decoder_attention_mask = (
118
+ inputs_dict["decoder_input_ids"],
119
+ inputs_dict["decoder_attention_mask"],
120
+ )
121
+
122
+ past_key_values = model.init_cache(decoder_input_ids.shape[0], max_decoder_length, encoder_outputs)
123
+ decoder_attention_mask = jnp.ones((decoder_input_ids.shape[0], max_decoder_length), dtype="i4")
124
+
125
+ decoder_position_ids = jnp.broadcast_to(
126
+ jnp.arange(decoder_input_ids.shape[-1] - 1)[None, :],
127
+ (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1),
128
+ )
129
+ outputs_cache = model.decode(
130
+ decoder_input_ids[:, :-1],
131
+ encoder_outputs,
132
+ decoder_attention_mask=decoder_attention_mask,
133
+ past_key_values=past_key_values,
134
+ decoder_position_ids=decoder_position_ids,
135
+ )
136
+
137
+ decoder_position_ids = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]], dtype="i4")
138
+ outputs_cache_next = model.decode(
139
+ decoder_input_ids[:, -1:],
140
+ encoder_outputs,
141
+ decoder_attention_mask=decoder_attention_mask,
142
+ past_key_values=outputs_cache.past_key_values,
143
+ decoder_position_ids=decoder_position_ids,
144
+ )
145
+
146
+ outputs = model.decode(decoder_input_ids, encoder_outputs)
147
+
148
+ diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
149
+ self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}")
150
+
151
+ def check_use_cache_forward_with_attn_mask(self, model_class_name, config, inputs_dict):
152
+ max_decoder_length = 20
153
+ model = model_class_name(config)
154
+
155
+ encoder_outputs = model.encode(inputs_dict["input_ids"])
156
+
157
+ decoder_input_ids, decoder_attention_mask = (
158
+ inputs_dict["decoder_input_ids"],
159
+ inputs_dict["decoder_attention_mask"],
160
+ )
161
+
162
+ decoder_attention_mask_cache = jnp.concatenate(
163
+ [
164
+ decoder_attention_mask,
165
+ jnp.zeros((decoder_attention_mask.shape[0], max_decoder_length - decoder_attention_mask.shape[1])),
166
+ ],
167
+ axis=-1,
168
+ )
169
+
170
+ past_key_values = model.init_cache(decoder_input_ids.shape[0], max_decoder_length, encoder_outputs)
171
+ decoder_position_ids = jnp.broadcast_to(
172
+ jnp.arange(decoder_input_ids.shape[-1] - 1)[None, :],
173
+ (decoder_input_ids.shape[0], decoder_input_ids.shape[-1] - 1),
174
+ )
175
+
176
+ outputs_cache = model.decode(
177
+ decoder_input_ids[:, :-1],
178
+ encoder_outputs,
179
+ decoder_attention_mask=decoder_attention_mask_cache,
180
+ past_key_values=past_key_values,
181
+ decoder_position_ids=decoder_position_ids,
182
+ )
183
+ decoder_position_ids = jnp.array(decoder_input_ids.shape[0] * [[decoder_input_ids.shape[-1] - 1]], dtype="i4")
184
+ outputs_cache_next = model.decode(
185
+ decoder_input_ids[:, -1:],
186
+ encoder_outputs,
187
+ past_key_values=outputs_cache.past_key_values,
188
+ decoder_attention_mask=decoder_attention_mask_cache,
189
+ decoder_position_ids=decoder_position_ids,
190
+ )
191
+
192
+ outputs = model.decode(decoder_input_ids, encoder_outputs, decoder_attention_mask=decoder_attention_mask)
193
+
194
+ diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
195
+ self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}")
196
+
197
+
198
+ def prepare_pegasus_inputs_dict(
199
+ config,
200
+ input_ids,
201
+ decoder_input_ids,
202
+ attention_mask=None,
203
+ decoder_attention_mask=None,
204
+ ):
205
+ if attention_mask is None:
206
+ attention_mask = np.not_equal(input_ids, config.pad_token_id).astype(np.int8)
207
+ if decoder_attention_mask is None:
208
+ decoder_attention_mask = np.concatenate(
209
+ [
210
+ np.ones(decoder_input_ids[:, :1].shape, dtype=np.int8),
211
+ np.not_equal(decoder_input_ids[:, 1:], config.pad_token_id).astype(np.int8),
212
+ ],
213
+ axis=-1,
214
+ )
215
+ return {
216
+ "input_ids": input_ids,
217
+ "decoder_input_ids": decoder_input_ids,
218
+ "attention_mask": attention_mask,
219
+ "decoder_attention_mask": decoder_attention_mask,
220
+ }
221
+
222
+
223
+ @require_flax
224
+ class FlaxPegasusModelTest(FlaxModelTesterMixin, unittest.TestCase):
225
+ all_model_classes = (
226
+ (
227
+ FlaxPegasusForConditionalGeneration,
228
+ FlaxPegasusModel,
229
+ )
230
+ if is_flax_available()
231
+ else ()
232
+ )
233
+ all_generative_model_classes = (FlaxPegasusForConditionalGeneration,) if is_flax_available() else ()
234
+ is_encoder_decoder = True
235
+ test_pruning = False
236
+ test_head_masking = False
237
+ test_onnx = False
238
+
239
+ def setUp(self):
240
+ self.model_tester = FlaxPegasusModelTester(self)
241
+ self.config_tester = ConfigTester(self, config_class=PegasusConfig)
242
+
243
+ def test_config(self):
244
+ self.config_tester.run_common_tests()
245
+
246
+ def test_use_cache_forward(self):
247
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
248
+ for model_class in self.all_model_classes:
249
+ self.model_tester.check_use_cache_forward(model_class, config, inputs_dict)
250
+
251
+ def test_use_cache_forward_with_attn_mask(self):
252
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
253
+ for model_class in self.all_model_classes:
254
+ self.model_tester.check_use_cache_forward_with_attn_mask(model_class, config, inputs_dict)
255
+
256
+ def test_encode(self):
257
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
258
+
259
+ for model_class in self.all_model_classes:
260
+ with self.subTest(model_class.__name__):
261
+ prepared_inputs_dict = self._prepare_for_class(inputs_dict, model_class)
262
+ model = model_class(config)
263
+
264
+ @jax.jit
265
+ def encode_jitted(input_ids, attention_mask=None, **kwargs):
266
+ return model.encode(input_ids=input_ids, attention_mask=attention_mask)
267
+
268
+ with self.subTest("JIT Enabled"):
269
+ jitted_outputs = encode_jitted(**prepared_inputs_dict).to_tuple()
270
+
271
+ with self.subTest("JIT Disabled"):
272
+ with jax.disable_jit():
273
+ outputs = encode_jitted(**prepared_inputs_dict).to_tuple()
274
+
275
+ self.assertEqual(len(outputs), len(jitted_outputs))
276
+ for jitted_output, output in zip(jitted_outputs, outputs):
277
+ self.assertEqual(jitted_output.shape, output.shape)
278
+
279
+ def test_decode(self):
280
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
281
+
282
+ for model_class in self.all_model_classes:
283
+ with self.subTest(model_class.__name__):
284
+ model = model_class(config)
285
+ encoder_outputs = model.encode(inputs_dict["input_ids"], inputs_dict["attention_mask"])
286
+
287
+ prepared_inputs_dict = {
288
+ "decoder_input_ids": inputs_dict["decoder_input_ids"],
289
+ "decoder_attention_mask": inputs_dict["decoder_attention_mask"],
290
+ "encoder_outputs": encoder_outputs,
291
+ }
292
+
293
+ @jax.jit
294
+ def decode_jitted(decoder_input_ids, decoder_attention_mask, encoder_outputs):
295
+ return model.decode(
296
+ decoder_input_ids=decoder_input_ids,
297
+ decoder_attention_mask=decoder_attention_mask,
298
+ encoder_outputs=encoder_outputs,
299
+ )
300
+
301
+ with self.subTest("JIT Enabled"):
302
+ jitted_outputs = decode_jitted(**prepared_inputs_dict).to_tuple()
303
+
304
+ with self.subTest("JIT Disabled"):
305
+ with jax.disable_jit():
306
+ outputs = decode_jitted(**prepared_inputs_dict).to_tuple()
307
+
308
+ self.assertEqual(len(outputs), len(jitted_outputs))
309
+ for jitted_output, output in zip(jitted_outputs, outputs):
310
+ self.assertEqual(jitted_output.shape, output.shape)
311
+
312
+ @slow
313
+ def test_model_from_pretrained(self):
314
+ for model_class_name in self.all_model_classes:
315
+ model = model_class_name.from_pretrained("google/pegasus-large", from_pt=True)
316
+ input_ids = np.ones((1, 1))
317
+ outputs = model(input_ids)
318
+ self.assertIsNotNone(outputs)
319
+
320
+ @slow
321
+ def test_pegasus_xsum_summary(self):
322
+ model = FlaxPegasusForConditionalGeneration.from_pretrained("google/pegasus-xsum")
323
+ tokenizer = PegasusTokenizer.from_pretrained("google/pegasus-xsum")
324
+
325
+ src_text = [
326
+ """ PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.""",
327
+ """ The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning 'Oh I think you're nominated'", said Dappy."And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around."At the end of the day we're grateful to be where we are in our careers."If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" """,
328
+ ]
329
+
330
+ tgt_text = [
331
+ "California's largest electricity provider has turned off power to hundreds of thousands of customers.",
332
+ "Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.",
333
+ ]
334
+
335
+ inputs = tokenizer(src_text, return_tensors="np", truncation=True, max_length=512, padding=True)
336
+ translated_tokens = model.generate(**inputs, num_beams=2).sequences
337
+ decoded = tokenizer.batch_decode(translated_tokens, skip_special_tokens=True)
338
+ assert tgt_text == decoded
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pegasus/test_modeling_pegasus.py ADDED
@@ -0,0 +1,589 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 PEGASUS model."""
16
+
17
+ import tempfile
18
+ import unittest
19
+
20
+ from transformers import PegasusConfig, is_torch_available
21
+ from transformers.testing_utils import (
22
+ require_sentencepiece,
23
+ require_tokenizers,
24
+ require_torch,
25
+ require_torch_fp16,
26
+ slow,
27
+ torch_device,
28
+ )
29
+ from transformers.utils import cached_property
30
+
31
+ from ...generation.test_utils import GenerationTesterMixin
32
+ from ...test_configuration_common import ConfigTester
33
+ from ...test_modeling_common import ModelTesterMixin, ids_tensor
34
+ from ...test_pipeline_mixin import PipelineTesterMixin
35
+ from ..mbart.test_modeling_mbart import AbstractSeq2SeqIntegrationTest
36
+
37
+
38
+ if is_torch_available():
39
+ import torch
40
+
41
+ from transformers import AutoModelForSeq2SeqLM, PegasusForConditionalGeneration, PegasusModel
42
+ from transformers.models.pegasus.modeling_pegasus import PegasusDecoder, PegasusEncoder, PegasusForCausalLM
43
+
44
+
45
+ def prepare_pegasus_inputs_dict(
46
+ config,
47
+ input_ids,
48
+ decoder_input_ids,
49
+ attention_mask=None,
50
+ decoder_attention_mask=None,
51
+ head_mask=None,
52
+ decoder_head_mask=None,
53
+ cross_attn_head_mask=None,
54
+ ):
55
+ if attention_mask is None:
56
+ attention_mask = input_ids.ne(config.pad_token_id)
57
+ if decoder_attention_mask is None:
58
+ decoder_attention_mask = decoder_input_ids.ne(config.pad_token_id)
59
+ if head_mask is None:
60
+ head_mask = torch.ones(config.encoder_layers, config.encoder_attention_heads, device=torch_device)
61
+ if decoder_head_mask is None:
62
+ decoder_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads, device=torch_device)
63
+ if cross_attn_head_mask is None:
64
+ cross_attn_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads, device=torch_device)
65
+ return {
66
+ "input_ids": input_ids,
67
+ "decoder_input_ids": decoder_input_ids,
68
+ "attention_mask": attention_mask,
69
+ "decoder_attention_mask": attention_mask,
70
+ "head_mask": head_mask,
71
+ "decoder_head_mask": decoder_head_mask,
72
+ "cross_attn_head_mask": cross_attn_head_mask,
73
+ }
74
+
75
+
76
+ class PegasusModelTester:
77
+ def __init__(
78
+ self,
79
+ parent,
80
+ batch_size=13,
81
+ seq_length=7,
82
+ is_training=True,
83
+ use_labels=False,
84
+ vocab_size=99,
85
+ hidden_size=16,
86
+ num_hidden_layers=2,
87
+ num_attention_heads=4,
88
+ intermediate_size=4,
89
+ hidden_act="gelu",
90
+ hidden_dropout_prob=0.1,
91
+ attention_probs_dropout_prob=0.1,
92
+ max_position_embeddings=20,
93
+ eos_token_id=2,
94
+ pad_token_id=1,
95
+ bos_token_id=0,
96
+ ):
97
+ self.parent = parent
98
+ self.batch_size = batch_size
99
+ self.seq_length = seq_length
100
+ self.is_training = is_training
101
+ self.use_labels = use_labels
102
+ self.vocab_size = vocab_size
103
+ self.hidden_size = hidden_size
104
+ self.num_hidden_layers = num_hidden_layers
105
+ self.num_attention_heads = num_attention_heads
106
+ self.intermediate_size = intermediate_size
107
+ self.hidden_act = hidden_act
108
+ self.hidden_dropout_prob = hidden_dropout_prob
109
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
110
+ self.max_position_embeddings = max_position_embeddings
111
+ self.eos_token_id = eos_token_id
112
+ self.pad_token_id = pad_token_id
113
+ self.bos_token_id = bos_token_id
114
+
115
+ def prepare_config_and_inputs(self):
116
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
117
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size).clamp(
118
+ 3,
119
+ )
120
+ input_ids[:, -1] = self.eos_token_id # Eos Token
121
+
122
+ decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
123
+
124
+ config = self.get_config()
125
+ inputs_dict = prepare_pegasus_inputs_dict(config, input_ids, decoder_input_ids)
126
+ return config, inputs_dict
127
+
128
+ def get_pipeline_config(self):
129
+ return PegasusConfig(
130
+ vocab_size=200,
131
+ d_model=self.hidden_size,
132
+ encoder_layers=self.num_hidden_layers,
133
+ decoder_layers=self.num_hidden_layers,
134
+ encoder_attention_heads=self.num_attention_heads,
135
+ decoder_attention_heads=self.num_attention_heads,
136
+ encoder_ffn_dim=self.intermediate_size,
137
+ decoder_ffn_dim=self.intermediate_size,
138
+ dropout=self.hidden_dropout_prob,
139
+ attention_dropout=self.attention_probs_dropout_prob,
140
+ max_position_embeddings=200,
141
+ eos_token_id=self.eos_token_id,
142
+ bos_token_id=self.bos_token_id,
143
+ pad_token_id=self.pad_token_id,
144
+ )
145
+
146
+ def get_config(self):
147
+ return PegasusConfig(
148
+ vocab_size=self.vocab_size,
149
+ d_model=self.hidden_size,
150
+ encoder_layers=self.num_hidden_layers,
151
+ decoder_layers=self.num_hidden_layers,
152
+ encoder_attention_heads=self.num_attention_heads,
153
+ decoder_attention_heads=self.num_attention_heads,
154
+ encoder_ffn_dim=self.intermediate_size,
155
+ decoder_ffn_dim=self.intermediate_size,
156
+ dropout=self.hidden_dropout_prob,
157
+ attention_dropout=self.attention_probs_dropout_prob,
158
+ max_position_embeddings=self.max_position_embeddings,
159
+ eos_token_id=self.eos_token_id,
160
+ bos_token_id=self.bos_token_id,
161
+ pad_token_id=self.pad_token_id,
162
+ )
163
+
164
+ def prepare_config_and_inputs_for_common(self):
165
+ config, inputs_dict = self.prepare_config_and_inputs()
166
+ return config, inputs_dict
167
+
168
+ def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict):
169
+ model = PegasusModel(config=config).get_decoder().to(torch_device).eval()
170
+ input_ids = inputs_dict["input_ids"]
171
+ attention_mask = inputs_dict["attention_mask"]
172
+ head_mask = inputs_dict["head_mask"]
173
+
174
+ # first forward pass
175
+ outputs = model(input_ids, attention_mask=attention_mask, head_mask=head_mask, use_cache=True)
176
+
177
+ output, past_key_values = outputs.to_tuple()
178
+
179
+ # create hypothetical multiple next token and extent to next_input_ids
180
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
181
+ next_attn_mask = ids_tensor((self.batch_size, 3), 2)
182
+
183
+ # append to next input_ids and
184
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
185
+ next_attention_mask = torch.cat([attention_mask, next_attn_mask], dim=-1)
186
+
187
+ output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"]
188
+ output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[
189
+ "last_hidden_state"
190
+ ]
191
+
192
+ # select random slice
193
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
194
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
195
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
196
+
197
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
198
+
199
+ # test that outputs are equal for slice
200
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
201
+
202
+ def check_encoder_decoder_model_standalone(self, config, inputs_dict):
203
+ model = PegasusModel(config=config).to(torch_device).eval()
204
+ outputs = model(**inputs_dict)
205
+
206
+ encoder_last_hidden_state = outputs.encoder_last_hidden_state
207
+ last_hidden_state = outputs.last_hidden_state
208
+
209
+ with tempfile.TemporaryDirectory() as tmpdirname:
210
+ encoder = model.get_encoder()
211
+ encoder.save_pretrained(tmpdirname)
212
+ encoder = PegasusEncoder.from_pretrained(tmpdirname).to(torch_device)
213
+
214
+ encoder_last_hidden_state_2 = encoder(inputs_dict["input_ids"], attention_mask=inputs_dict["attention_mask"])[
215
+ 0
216
+ ]
217
+
218
+ self.parent.assertTrue((encoder_last_hidden_state_2 - encoder_last_hidden_state).abs().max().item() < 1e-3)
219
+
220
+ with tempfile.TemporaryDirectory() as tmpdirname:
221
+ decoder = model.get_decoder()
222
+ decoder.save_pretrained(tmpdirname)
223
+ decoder = PegasusDecoder.from_pretrained(tmpdirname).to(torch_device)
224
+
225
+ last_hidden_state_2 = decoder(
226
+ input_ids=inputs_dict["decoder_input_ids"],
227
+ attention_mask=inputs_dict["decoder_attention_mask"],
228
+ encoder_hidden_states=encoder_last_hidden_state,
229
+ encoder_attention_mask=inputs_dict["attention_mask"],
230
+ )[0]
231
+
232
+ self.parent.assertTrue((last_hidden_state_2 - last_hidden_state).abs().max().item() < 1e-3)
233
+
234
+
235
+ @require_torch
236
+ class PegasusModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
237
+ all_model_classes = (PegasusModel, PegasusForConditionalGeneration) if is_torch_available() else ()
238
+ all_generative_model_classes = (PegasusForConditionalGeneration,) if is_torch_available() else ()
239
+ pipeline_model_mapping = (
240
+ {
241
+ "feature-extraction": PegasusModel,
242
+ "summarization": PegasusForConditionalGeneration,
243
+ "text-generation": PegasusForCausalLM,
244
+ "text2text-generation": PegasusForConditionalGeneration,
245
+ "translation": PegasusForConditionalGeneration,
246
+ }
247
+ if is_torch_available()
248
+ else {}
249
+ )
250
+ is_encoder_decoder = True
251
+ fx_compatible = True
252
+ test_resize_position_embeddings = True
253
+ test_pruning = False
254
+ test_missing_keys = False
255
+
256
+ def setUp(self):
257
+ self.model_tester = PegasusModelTester(self)
258
+ self.config_tester = ConfigTester(self, config_class=PegasusConfig)
259
+
260
+ def test_config(self):
261
+ self.config_tester.run_common_tests()
262
+
263
+ def test_save_load_strict(self):
264
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
265
+ for model_class in self.all_model_classes:
266
+ model = model_class(config)
267
+
268
+ with tempfile.TemporaryDirectory() as tmpdirname:
269
+ model.save_pretrained(tmpdirname)
270
+ model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True)
271
+ self.assertEqual(info["missing_keys"], [])
272
+
273
+ def test_decoder_model_past_with_large_inputs(self):
274
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
275
+ self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
276
+
277
+ def test_encoder_decoder_model_standalone(self):
278
+ config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common()
279
+ self.model_tester.check_encoder_decoder_model_standalone(*config_and_inputs)
280
+
281
+ @require_torch_fp16
282
+ def test_generate_fp16(self):
283
+ config, input_dict = self.model_tester.prepare_config_and_inputs()
284
+ input_ids = input_dict["input_ids"]
285
+ attention_mask = input_ids.ne(1).to(torch_device)
286
+ model = PegasusForConditionalGeneration(config).eval().to(torch_device)
287
+ model.half()
288
+ model.generate(input_ids, attention_mask=attention_mask)
289
+ model.generate(num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3)
290
+
291
+ @unittest.skip(
292
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
293
+ )
294
+ def test_training_gradient_checkpointing(self):
295
+ pass
296
+
297
+ @unittest.skip(
298
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
299
+ )
300
+ def test_training_gradient_checkpointing_use_reentrant(self):
301
+ pass
302
+
303
+ @unittest.skip(
304
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
305
+ )
306
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
307
+ pass
308
+
309
+
310
+ def assert_tensors_close(a, b, atol=1e-12, prefix=""):
311
+ """If tensors have different shapes, different values or a and b are not both tensors, raise a nice Assertion error."""
312
+ if a is None and b is None:
313
+ return True
314
+ try:
315
+ if torch.allclose(a, b, atol=atol):
316
+ return True
317
+ raise
318
+ except Exception:
319
+ pct_different = (torch.gt((a - b).abs(), atol)).float().mean().item()
320
+ if a.numel() > 100:
321
+ msg = f"tensor values are {pct_different:.1%} percent different."
322
+ else:
323
+ msg = f"{a} != {b}"
324
+ if prefix:
325
+ msg = prefix + ": " + msg
326
+ raise AssertionError(msg)
327
+
328
+
329
+ def _long_tensor(tok_lst):
330
+ return torch.tensor(tok_lst, dtype=torch.long, device=torch_device)
331
+
332
+
333
+ @require_torch
334
+ @require_sentencepiece
335
+ @require_tokenizers
336
+ class PegasusXSUMIntegrationTest(AbstractSeq2SeqIntegrationTest):
337
+ checkpoint_name = "google/pegasus-xsum"
338
+ src_text = [
339
+ """ PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.""",
340
+ """ The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning 'Oh I think you're nominated'", said Dappy."And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around."At the end of the day we're grateful to be where we are in our careers."If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" """,
341
+ ]
342
+
343
+ tgt_text = [
344
+ "California's largest electricity provider has turned off power to hundreds of thousands of customers.",
345
+ "Pop group N-Dubz have revealed they were surprised to get four nominations for this year's Mobo Awards.",
346
+ ]
347
+
348
+ @cached_property
349
+ def model(self):
350
+ return AutoModelForSeq2SeqLM.from_pretrained(self.checkpoint_name).to(torch_device)
351
+
352
+ @slow
353
+ @require_torch_fp16
354
+ def test_pegasus_xsum_summary(self):
355
+ assert self.tokenizer.model_max_length == 512
356
+ inputs = self.tokenizer(self.src_text, return_tensors="pt", truncation=True, max_length=512, padding=True).to(
357
+ torch_device
358
+ )
359
+ assert inputs.input_ids.shape == (2, 421)
360
+ translated_tokens = self.model.generate(**inputs, num_beams=2)
361
+ decoded = self.tokenizer.batch_decode(translated_tokens, skip_special_tokens=True)
362
+ assert self.tgt_text == decoded
363
+
364
+ self.model.half()
365
+ translated_tokens_fp16 = self.model.generate(**inputs, max_length=10)
366
+ decoded_fp16 = self.tokenizer.batch_decode(translated_tokens_fp16, skip_special_tokens=True)
367
+ assert decoded_fp16 == [
368
+ "California's largest electricity provider has begun",
369
+ "N-Dubz have revealed they were",
370
+ ]
371
+
372
+
373
+ class PegasusStandaloneDecoderModelTester:
374
+ def __init__(
375
+ self,
376
+ parent,
377
+ vocab_size=99,
378
+ batch_size=13,
379
+ d_model=16,
380
+ decoder_seq_length=7,
381
+ is_training=True,
382
+ is_decoder=True,
383
+ use_attention_mask=True,
384
+ use_cache=False,
385
+ use_labels=True,
386
+ decoder_start_token_id=2,
387
+ decoder_ffn_dim=32,
388
+ decoder_layers=2,
389
+ encoder_attention_heads=4,
390
+ decoder_attention_heads=4,
391
+ max_position_embeddings=30,
392
+ is_encoder_decoder=False,
393
+ pad_token_id=0,
394
+ bos_token_id=1,
395
+ eos_token_id=2,
396
+ scope=None,
397
+ ):
398
+ self.parent = parent
399
+ self.batch_size = batch_size
400
+ self.decoder_seq_length = decoder_seq_length
401
+ # For common tests
402
+ self.seq_length = self.decoder_seq_length
403
+ self.is_training = is_training
404
+ self.use_attention_mask = use_attention_mask
405
+ self.use_labels = use_labels
406
+
407
+ self.vocab_size = vocab_size
408
+ self.d_model = d_model
409
+ self.hidden_size = d_model
410
+ self.num_hidden_layers = decoder_layers
411
+ self.decoder_layers = decoder_layers
412
+ self.decoder_ffn_dim = decoder_ffn_dim
413
+ self.encoder_attention_heads = encoder_attention_heads
414
+ self.decoder_attention_heads = decoder_attention_heads
415
+ self.num_attention_heads = decoder_attention_heads
416
+ self.eos_token_id = eos_token_id
417
+ self.bos_token_id = bos_token_id
418
+ self.pad_token_id = pad_token_id
419
+ self.decoder_start_token_id = decoder_start_token_id
420
+ self.use_cache = use_cache
421
+ self.max_position_embeddings = max_position_embeddings
422
+ self.is_encoder_decoder = is_encoder_decoder
423
+
424
+ self.scope = None
425
+ self.decoder_key_length = decoder_seq_length
426
+ self.base_model_out_len = 2
427
+ self.decoder_attention_idx = 1
428
+
429
+ def prepare_config_and_inputs(self):
430
+ input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)
431
+
432
+ attention_mask = None
433
+ if self.use_attention_mask:
434
+ attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2)
435
+
436
+ lm_labels = None
437
+ if self.use_labels:
438
+ lm_labels = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)
439
+
440
+ config = PegasusConfig(
441
+ vocab_size=self.vocab_size,
442
+ d_model=self.d_model,
443
+ decoder_layers=self.decoder_layers,
444
+ decoder_ffn_dim=self.decoder_ffn_dim,
445
+ encoder_attention_heads=self.encoder_attention_heads,
446
+ decoder_attention_heads=self.decoder_attention_heads,
447
+ eos_token_id=self.eos_token_id,
448
+ bos_token_id=self.bos_token_id,
449
+ use_cache=self.use_cache,
450
+ pad_token_id=self.pad_token_id,
451
+ decoder_start_token_id=self.decoder_start_token_id,
452
+ max_position_embeddings=self.max_position_embeddings,
453
+ is_encoder_decoder=self.is_encoder_decoder,
454
+ )
455
+
456
+ return (
457
+ config,
458
+ input_ids,
459
+ attention_mask,
460
+ lm_labels,
461
+ )
462
+
463
+ def create_and_check_decoder_model_past(
464
+ self,
465
+ config,
466
+ input_ids,
467
+ attention_mask,
468
+ lm_labels,
469
+ ):
470
+ config.use_cache = True
471
+ model = PegasusDecoder(config=config).to(torch_device).eval()
472
+ # first forward pass
473
+ outputs = model(input_ids, use_cache=True)
474
+ outputs_use_cache_conf = model(input_ids)
475
+ outputs_no_past = model(input_ids, use_cache=False)
476
+
477
+ self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))
478
+ self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)
479
+
480
+ past_key_values = outputs["past_key_values"]
481
+
482
+ # create hypothetical next token and extent to next_input_ids
483
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
484
+
485
+ # append to next input_ids and
486
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
487
+
488
+ output_from_no_past = model(next_input_ids)["last_hidden_state"]
489
+ output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"]
490
+
491
+ # select random slice
492
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
493
+ output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
494
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
495
+
496
+ # test that outputs are equal for slice
497
+ assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)
498
+
499
+ def create_and_check_decoder_model_attention_mask_past(
500
+ self,
501
+ config,
502
+ input_ids,
503
+ attention_mask,
504
+ lm_labels,
505
+ ):
506
+ model = PegasusDecoder(config=config).to(torch_device).eval()
507
+
508
+ # create attention mask
509
+ attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
510
+
511
+ half_seq_length = input_ids.shape[-1] // 2
512
+ attn_mask[:, half_seq_length:] = 0
513
+
514
+ # first forward pass
515
+ past_key_values = model(input_ids, attention_mask=attn_mask, use_cache=True)["past_key_values"]
516
+
517
+ # create hypothetical next token and extent to next_input_ids
518
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
519
+
520
+ # change a random masked slice from input_ids
521
+ random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1
522
+ random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1)
523
+ input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens
524
+
525
+ # append to next input_ids and attn_mask
526
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
527
+ attn_mask = torch.cat(
528
+ [attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)],
529
+ dim=1,
530
+ )
531
+
532
+ # get two different outputs
533
+ output_from_no_past = model(next_input_ids, attention_mask=attn_mask)["last_hidden_state"]
534
+ output_from_past = model(next_tokens, attention_mask=attn_mask, past_key_values=past_key_values)[
535
+ "last_hidden_state"
536
+ ]
537
+
538
+ # select random slice
539
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
540
+ output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
541
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
542
+
543
+ # test that outputs are equal for slice
544
+ assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)
545
+
546
+ def prepare_config_and_inputs_for_common(self):
547
+ config_and_inputs = self.prepare_config_and_inputs()
548
+ (
549
+ config,
550
+ input_ids,
551
+ attention_mask,
552
+ lm_labels,
553
+ ) = config_and_inputs
554
+
555
+ inputs_dict = {
556
+ "input_ids": input_ids,
557
+ "attention_mask": attention_mask,
558
+ }
559
+ return config, inputs_dict
560
+
561
+
562
+ @require_torch
563
+ class PegasusStandaloneDecoderModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
564
+ all_model_classes = (PegasusDecoder, PegasusForCausalLM) if is_torch_available() else ()
565
+ all_generative_model_classes = (PegasusForCausalLM,) if is_torch_available() else ()
566
+ test_resize_position_embeddings = True
567
+ test_pruning = False
568
+ is_encoder_decoder = False
569
+
570
+ def setUp(
571
+ self,
572
+ ):
573
+ self.model_tester = PegasusStandaloneDecoderModelTester(self, is_training=False)
574
+ self.config_tester = ConfigTester(self, config_class=PegasusConfig)
575
+
576
+ def test_config(self):
577
+ self.config_tester.run_common_tests()
578
+
579
+ def test_decoder_model_past(self):
580
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
581
+ self.model_tester.create_and_check_decoder_model_past(*config_and_inputs)
582
+
583
+ def test_decoder_model_attn_mask_past(self):
584
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
585
+ self.model_tester.create_and_check_decoder_model_attention_mask_past(*config_and_inputs)
586
+
587
+ @unittest.skip(reason="Decoder cannot keep gradients")
588
+ def test_retain_grad_hidden_states_attentions(self):
589
+ return
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pegasus/test_modeling_tf_pegasus.py ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from __future__ import annotations
17
+
18
+ import unittest
19
+
20
+ from transformers import AutoTokenizer, PegasusConfig, is_tf_available
21
+ from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
22
+ from transformers.utils import cached_property
23
+
24
+ from ...test_configuration_common import ConfigTester
25
+ from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
26
+ from ...test_pipeline_mixin import PipelineTesterMixin
27
+
28
+
29
+ if is_tf_available():
30
+ import tensorflow as tf
31
+
32
+ from transformers import TFAutoModelForSeq2SeqLM, TFPegasusForConditionalGeneration, TFPegasusModel
33
+
34
+
35
+ @require_tf
36
+ class TFPegasusModelTester:
37
+ config_cls = PegasusConfig
38
+ config_updates = {}
39
+ hidden_act = "gelu"
40
+
41
+ def __init__(
42
+ self,
43
+ parent,
44
+ batch_size=13,
45
+ seq_length=7,
46
+ is_training=True,
47
+ use_labels=False,
48
+ vocab_size=99,
49
+ hidden_size=32,
50
+ num_hidden_layers=2,
51
+ num_attention_heads=4,
52
+ intermediate_size=37,
53
+ hidden_dropout_prob=0.1,
54
+ attention_probs_dropout_prob=0.1,
55
+ max_position_embeddings=40,
56
+ eos_token_id=2,
57
+ pad_token_id=1,
58
+ bos_token_id=0,
59
+ ):
60
+ self.parent = parent
61
+ self.batch_size = batch_size
62
+ self.seq_length = seq_length
63
+ self.is_training = is_training
64
+ self.use_labels = use_labels
65
+ self.vocab_size = vocab_size
66
+ self.hidden_size = hidden_size
67
+ self.num_hidden_layers = num_hidden_layers
68
+ self.num_attention_heads = num_attention_heads
69
+ self.intermediate_size = intermediate_size
70
+
71
+ self.hidden_dropout_prob = hidden_dropout_prob
72
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
73
+ self.max_position_embeddings = max_position_embeddings
74
+ self.eos_token_id = eos_token_id
75
+ self.pad_token_id = pad_token_id
76
+ self.bos_token_id = bos_token_id
77
+
78
+ def prepare_config_and_inputs_for_common(self):
79
+ input_ids = ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size)
80
+ eos_tensor = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size), 1)
81
+ input_ids = tf.concat([input_ids, eos_tensor], axis=1)
82
+
83
+ decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
84
+
85
+ config = self.config_cls(
86
+ vocab_size=self.vocab_size,
87
+ d_model=self.hidden_size,
88
+ encoder_layers=self.num_hidden_layers,
89
+ decoder_layers=self.num_hidden_layers,
90
+ encoder_attention_heads=self.num_attention_heads,
91
+ decoder_attention_heads=self.num_attention_heads,
92
+ encoder_ffn_dim=self.intermediate_size,
93
+ decoder_ffn_dim=self.intermediate_size,
94
+ dropout=self.hidden_dropout_prob,
95
+ attention_dropout=self.attention_probs_dropout_prob,
96
+ max_position_embeddings=self.max_position_embeddings,
97
+ eos_token_ids=[2],
98
+ bos_token_id=self.bos_token_id,
99
+ pad_token_id=self.pad_token_id,
100
+ decoder_start_token_id=self.pad_token_id,
101
+ **self.config_updates,
102
+ )
103
+ inputs_dict = prepare_pegasus_inputs_dict(config, input_ids, decoder_input_ids)
104
+ return config, inputs_dict
105
+
106
+ def check_decoder_model_past_large_inputs(self, config, inputs_dict):
107
+ model = TFPegasusModel(config=config).get_decoder()
108
+ input_ids = inputs_dict["input_ids"]
109
+
110
+ input_ids = input_ids[:1, :]
111
+ attention_mask = inputs_dict["attention_mask"][:1, :]
112
+ head_mask = inputs_dict["head_mask"]
113
+ self.batch_size = 1
114
+
115
+ # first forward pass
116
+ outputs = model(input_ids, attention_mask=attention_mask, head_mask=head_mask, use_cache=True)
117
+
118
+ output, past_key_values = outputs.to_tuple()
119
+
120
+ # create hypothetical next token and extent to next_input_ids
121
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
122
+ next_attn_mask = tf.cast(ids_tensor((self.batch_size, 3), 2), tf.int8)
123
+
124
+ # append to next input_ids and
125
+ next_input_ids = tf.concat([input_ids, next_tokens], axis=-1)
126
+ next_attention_mask = tf.concat([attention_mask, next_attn_mask], axis=-1)
127
+
128
+ output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)[0]
129
+ output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[0]
130
+
131
+ self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1])
132
+
133
+ # select random slice
134
+ random_slice_idx = int(ids_tensor((1,), output_from_past.shape[-1]))
135
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx]
136
+ output_from_past_slice = output_from_past[:, :, random_slice_idx]
137
+
138
+ # test that outputs are equal for slice
139
+ tf.debugging.assert_near(output_from_past_slice, output_from_no_past_slice, rtol=1e-3)
140
+
141
+
142
+ def prepare_pegasus_inputs_dict(
143
+ config,
144
+ input_ids,
145
+ decoder_input_ids,
146
+ attention_mask=None,
147
+ decoder_attention_mask=None,
148
+ head_mask=None,
149
+ decoder_head_mask=None,
150
+ cross_attn_head_mask=None,
151
+ ):
152
+ if attention_mask is None:
153
+ attention_mask = tf.cast(tf.math.not_equal(input_ids, config.pad_token_id), tf.int8)
154
+ if decoder_attention_mask is None:
155
+ decoder_attention_mask = tf.concat(
156
+ [
157
+ tf.ones(decoder_input_ids[:, :1].shape, dtype=tf.int8),
158
+ tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:], config.pad_token_id), tf.int8),
159
+ ],
160
+ axis=-1,
161
+ )
162
+ if head_mask is None:
163
+ head_mask = tf.ones((config.encoder_layers, config.encoder_attention_heads))
164
+ if decoder_head_mask is None:
165
+ decoder_head_mask = tf.ones((config.decoder_layers, config.decoder_attention_heads))
166
+ if cross_attn_head_mask is None:
167
+ cross_attn_head_mask = tf.ones((config.decoder_layers, config.decoder_attention_heads))
168
+ return {
169
+ "input_ids": input_ids,
170
+ "decoder_input_ids": decoder_input_ids,
171
+ "attention_mask": attention_mask,
172
+ "decoder_attention_mask": decoder_attention_mask,
173
+ "head_mask": head_mask,
174
+ "decoder_head_mask": decoder_head_mask,
175
+ "cross_attn_head_mask": cross_attn_head_mask,
176
+ }
177
+
178
+
179
+ @require_tf
180
+ class TFPegasusModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
181
+ all_model_classes = (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else ()
182
+ all_generative_model_classes = (TFPegasusForConditionalGeneration,) if is_tf_available() else ()
183
+ pipeline_model_mapping = (
184
+ {
185
+ "feature-extraction": TFPegasusModel,
186
+ "summarization": TFPegasusForConditionalGeneration,
187
+ "text2text-generation": TFPegasusForConditionalGeneration,
188
+ "translation": TFPegasusForConditionalGeneration,
189
+ }
190
+ if is_tf_available()
191
+ else {}
192
+ )
193
+ is_encoder_decoder = True
194
+ test_pruning = False
195
+ test_onnx = False
196
+
197
+ def setUp(self):
198
+ self.model_tester = TFPegasusModelTester(self)
199
+ self.config_tester = ConfigTester(self, config_class=PegasusConfig)
200
+
201
+ def test_config(self):
202
+ self.config_tester.run_common_tests()
203
+
204
+ def test_decoder_model_past_large_inputs(self):
205
+ config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common()
206
+ self.model_tester.check_decoder_model_past_large_inputs(*config_and_inputs)
207
+
208
+
209
+ @require_sentencepiece
210
+ @require_tokenizers
211
+ @require_tf
212
+ class TFPegasusIntegrationTests(unittest.TestCase):
213
+ src_text = [
214
+ """ PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.""",
215
+ """ The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning 'Oh I think you're nominated'", said Dappy."And I was like 'Oh yeah, which one?' And now we've got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it's best of us to come down and mingle with everyone and say hello to the cameras. And now we find we've got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn't be too disappointed if they didn't win this time around."At the end of the day we're grateful to be where we are in our careers."If it don't happen then it don't happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a re-working of The Killers' All These Things That I've Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year's Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" """,
216
+ ]
217
+ expected_text = [
218
+ "California's largest electricity provider has cut power to hundreds of thousands of customers in an effort to"
219
+ " reduce the risk of wildfires.",
220
+ 'N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.',
221
+ ] # differs slightly from pytorch, likely due to numerical differences in linear layers
222
+ model_name = "google/pegasus-xsum"
223
+
224
+ @cached_property
225
+ def tokenizer(self):
226
+ return AutoTokenizer.from_pretrained(self.model_name)
227
+
228
+ @cached_property
229
+ def model(self):
230
+ model = TFAutoModelForSeq2SeqLM.from_pretrained(self.model_name)
231
+ return model
232
+
233
+ def _assert_generated_batch_equal_expected(self, **tokenizer_kwargs):
234
+ generated_words = self.translate_src_text(**tokenizer_kwargs)
235
+ assert self.expected_text == generated_words
236
+
237
+ def translate_src_text(self, **tokenizer_kwargs):
238
+ model_inputs = self.tokenizer(self.src_text, **tokenizer_kwargs, padding=True, return_tensors="tf")
239
+ generated_ids = self.model.generate(
240
+ model_inputs.input_ids,
241
+ attention_mask=model_inputs.attention_mask,
242
+ num_beams=2,
243
+ use_cache=True,
244
+ )
245
+ generated_words = self.tokenizer.batch_decode(generated_ids.numpy(), skip_special_tokens=True)
246
+ return generated_words
247
+
248
+ @slow
249
+ def test_batch_generation(self):
250
+ self._assert_generated_batch_equal_expected()
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pegasus/test_tokenization_pegasus.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import unittest
16
+
17
+ from transformers import PegasusTokenizer, PegasusTokenizerFast
18
+ from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow
19
+ from transformers.utils import cached_property
20
+
21
+ from ...test_tokenization_common import TokenizerTesterMixin
22
+
23
+
24
+ SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece_no_bos.model")
25
+
26
+
27
+ @require_sentencepiece
28
+ @require_tokenizers
29
+ class PegasusTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
30
+ from_pretrained_id = "google/pegasus-xsum"
31
+ tokenizer_class = PegasusTokenizer
32
+ rust_tokenizer_class = PegasusTokenizerFast
33
+ test_rust_tokenizer = True
34
+ test_sentencepiece = True
35
+
36
+ def setUp(self):
37
+ super().setUp()
38
+
39
+ # We have a SentencePiece fixture for testing
40
+ tokenizer = PegasusTokenizer(SAMPLE_VOCAB)
41
+ tokenizer.save_pretrained(self.tmpdirname)
42
+
43
+ @cached_property
44
+ def _large_tokenizer(self):
45
+ return PegasusTokenizer.from_pretrained("google/pegasus-large")
46
+
47
+ def get_tokenizer(self, **kwargs) -> PegasusTokenizer:
48
+ return PegasusTokenizer.from_pretrained(self.tmpdirname, **kwargs)
49
+
50
+ def get_input_output_texts(self, tokenizer):
51
+ return ("This is a test", "This is a test")
52
+
53
+ def test_convert_token_and_id(self):
54
+ """Test ``_convert_token_to_id`` and ``_convert_id_to_token``."""
55
+ token = "</s>"
56
+ token_id = 1
57
+
58
+ self.assertEqual(self.get_tokenizer().convert_tokens_to_ids(token), token_id)
59
+ self.assertEqual(self.get_tokenizer().convert_ids_to_tokens(token_id), token)
60
+
61
+ def test_get_vocab(self):
62
+ vocab_keys = list(self.get_tokenizer().get_vocab().keys())
63
+
64
+ self.assertEqual(vocab_keys[0], "<pad>")
65
+ self.assertEqual(vocab_keys[1], "</s>")
66
+ self.assertEqual(vocab_keys[104], "<unk_102>")
67
+ self.assertEqual(len(vocab_keys), 1_103)
68
+
69
+ def test_vocab_size(self):
70
+ self.assertEqual(self.get_tokenizer().vocab_size, 1_103)
71
+
72
+ def test_mask_tokens_rust_pegasus(self):
73
+ rust_tokenizer = self.rust_tokenizer_class.from_pretrained(self.tmpdirname)
74
+ py_tokenizer = self.tokenizer_class.from_pretrained(self.tmpdirname)
75
+ raw_input_str = (
76
+ "Let's see which <unk> is the better <unk_token_11> one <mask_1> It seems like this <mask_2> was important"
77
+ " </s> <pad> <pad> <pad>"
78
+ )
79
+ rust_ids = rust_tokenizer([raw_input_str], return_tensors=None, add_special_tokens=False).input_ids[0]
80
+ py_ids = py_tokenizer([raw_input_str], return_tensors=None, add_special_tokens=False).input_ids[0]
81
+ self.assertListEqual(py_ids, rust_ids)
82
+
83
+ def test_large_mask_tokens(self):
84
+ tokenizer = self._large_tokenizer
85
+ # <mask_1> masks whole sentence while <mask_2> masks single word
86
+ raw_input_str = "<mask_1> To ensure a <mask_2> flow of bank resolutions."
87
+ desired_result = [2, 413, 615, 114, 3, 1971, 113, 1679, 10710, 107, 1]
88
+ ids = tokenizer([raw_input_str], return_tensors=None).input_ids[0]
89
+ self.assertListEqual(desired_result, ids)
90
+
91
+ def test_large_tokenizer_settings(self):
92
+ tokenizer = self._large_tokenizer
93
+ # The tracebacks for the following asserts are **better** without messages or self.assertEqual
94
+ assert tokenizer.vocab_size == 96103
95
+ assert tokenizer.pad_token_id == 0
96
+ assert tokenizer.eos_token_id == 1
97
+ assert tokenizer.offset == 103
98
+ assert tokenizer.unk_token_id == tokenizer.offset + 2 == 105
99
+ assert tokenizer.unk_token == "<unk>"
100
+ assert tokenizer.model_max_length == 1024
101
+ raw_input_str = "To ensure a smooth flow of bank resolutions."
102
+ desired_result = [413, 615, 114, 2291, 1971, 113, 1679, 10710, 107, 1]
103
+ ids = tokenizer([raw_input_str], return_tensors=None).input_ids[0]
104
+ self.assertListEqual(desired_result, ids)
105
+ assert tokenizer.convert_ids_to_tokens([0, 1, 2, 3]) == ["<pad>", "</s>", "<mask_1>", "<mask_2>"]
106
+
107
+ @require_torch
108
+ def test_large_seq2seq_truncation(self):
109
+ src_texts = ["This is going to be way too long." * 150, "short example"]
110
+ tgt_texts = ["not super long but more than 5 tokens", "tiny"]
111
+ batch = self._large_tokenizer(src_texts, padding=True, truncation=True, return_tensors="pt")
112
+ targets = self._large_tokenizer(
113
+ text_target=tgt_texts, max_length=5, padding=True, truncation=True, return_tensors="pt"
114
+ )
115
+
116
+ assert batch.input_ids.shape == (2, 1024)
117
+ assert batch.attention_mask.shape == (2, 1024)
118
+ assert targets["input_ids"].shape == (2, 5)
119
+ assert len(batch) == 2 # input_ids, attention_mask.
120
+
121
+ @slow
122
+ def test_tokenizer_integration(self):
123
+ expected_encoding = {'input_ids': [[38979, 143, 18485, 606, 130, 26669, 87686, 121, 54189, 1129, 111, 26669, 87686, 121, 9114, 14787, 121, 13249, 158, 592, 956, 121, 14621, 31576, 143, 62613, 108, 9688, 930, 43430, 11562, 62613, 304, 108, 11443, 897, 108, 9314, 17415, 63399, 108, 11443, 7614, 18316, 118, 4284, 7148, 12430, 143, 1400, 25703, 158, 111, 4284, 7148, 11772, 143, 21297, 1064, 158, 122, 204, 3506, 1754, 1133, 14787, 1581, 115, 33224, 4482, 111, 1355, 110, 29173, 317, 50833, 108, 20147, 94665, 111, 77198, 107, 1], [110, 62613, 117, 638, 112, 1133, 121, 20098, 1355, 79050, 13872, 135, 1596, 53541, 1352, 141, 13039, 5542, 124, 302, 518, 111, 268, 2956, 115, 149, 4427, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [139, 1235, 2799, 18289, 17780, 204, 109, 9474, 1296, 107, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], '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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # fmt: skip
124
+
125
+ self.tokenizer_integration_test_util(
126
+ expected_encoding=expected_encoding,
127
+ model_name="google/bigbird-pegasus-large-arxiv",
128
+ revision="ba85d0851d708441f91440d509690f1ab6353415",
129
+ )
130
+
131
+
132
+ @require_sentencepiece
133
+ @require_tokenizers
134
+ class BigBirdPegasusTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
135
+ from_pretrained_id = "google/pegasus-xsum"
136
+ tokenizer_class = PegasusTokenizer
137
+ rust_tokenizer_class = PegasusTokenizerFast
138
+ test_rust_tokenizer = True
139
+ test_sentencepiece = True
140
+
141
+ def setUp(self):
142
+ super().setUp()
143
+
144
+ # We have a SentencePiece fixture for testing
145
+ tokenizer = PegasusTokenizer(SAMPLE_VOCAB, offset=0, mask_token_sent=None, mask_token="[MASK]")
146
+ tokenizer.save_pretrained(self.tmpdirname)
147
+
148
+ @cached_property
149
+ def _large_tokenizer(self):
150
+ return PegasusTokenizer.from_pretrained("google/bigbird-pegasus-large-arxiv")
151
+
152
+ def get_tokenizer(self, **kwargs) -> PegasusTokenizer:
153
+ return PegasusTokenizer.from_pretrained(self.tmpdirname, **kwargs)
154
+
155
+ def get_input_output_texts(self, tokenizer):
156
+ return ("This is a test", "This is a test")
157
+
158
+ def test_mask_tokens_rust_pegasus(self):
159
+ rust_tokenizer = self.rust_tokenizer_class.from_pretrained(self.tmpdirname)
160
+ py_tokenizer = self.tokenizer_class.from_pretrained(self.tmpdirname)
161
+ raw_input_str = (
162
+ "Let's see which <unk> is the better <unk_token> one [MASK] It seems like this [MASK] was important </s>"
163
+ " <pad> <pad> <pad>"
164
+ )
165
+ rust_ids = rust_tokenizer([raw_input_str], return_tensors=None, add_special_tokens=False).input_ids[0]
166
+ py_ids = py_tokenizer([raw_input_str], return_tensors=None, add_special_tokens=False).input_ids[0]
167
+ self.assertListEqual(py_ids, rust_ids)
168
+
169
+ @require_torch
170
+ def test_large_seq2seq_truncation(self):
171
+ src_texts = ["This is going to be way too long." * 1000, "short example"]
172
+ tgt_texts = ["not super long but more than 5 tokens", "tiny"]
173
+ batch = self._large_tokenizer(src_texts, padding=True, truncation=True, return_tensors="pt")
174
+ targets = self._large_tokenizer(
175
+ text_target=tgt_texts, max_length=5, padding=True, truncation=True, return_tensors="pt"
176
+ )
177
+
178
+ assert batch.input_ids.shape == (2, 4096)
179
+ assert batch.attention_mask.shape == (2, 4096)
180
+ assert targets["input_ids"].shape == (2, 5)
181
+ assert len(batch) == 2 # input_ids, attention_mask.
182
+
183
+ def test_equivalence_to_orig_tokenizer(self):
184
+ """
185
+ To run with original TF tokenizer:
186
+
187
+ !wget https://github.com/google-research/bigbird/raw/master/bigbird/vocab/pegasus.model
188
+ !pip install tensorflow-text
189
+
190
+ import tensorflow.compat.v2 as tf
191
+ import tensorflow_text as tft
192
+
193
+ VOCAB_FILE = "./pegasus.model"
194
+
195
+ tf.enable_v2_behavior()
196
+
197
+ test_str = "This is an example string that is used to test the original TF implementation against the HF implementation"
198
+ tokenizer = tft.SentencepieceTokenizer(model=tf.io.gfile.GFile(VOCAB_FILE, "rb").read())
199
+
200
+ tokenizer.tokenize(test_str)
201
+ """
202
+
203
+ test_str = (
204
+ "This is an example string that is used to test the original TF implementation against the HF"
205
+ " implementation"
206
+ )
207
+
208
+ token_ids = self._large_tokenizer(test_str).input_ids
209
+
210
+ self.assertListEqual(
211
+ token_ids,
212
+ [182, 117, 142, 587, 4211, 120, 117, 263, 112, 804, 109, 856, 25016, 3137, 464, 109, 26955, 3137, 1],
213
+ )
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pegasus_x/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pegasus_x/test_modeling_pegasus_x.py ADDED
@@ -0,0 +1,877 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 PEGASUS-X model."""
16
+
17
+ import copy
18
+ import math
19
+ import tempfile
20
+ import unittest
21
+
22
+ from transformers import is_torch_available
23
+ from transformers.testing_utils import (
24
+ require_sentencepiece,
25
+ require_tokenizers,
26
+ require_torch,
27
+ require_torch_fp16,
28
+ slow,
29
+ torch_device,
30
+ )
31
+ from transformers.utils import cached_property
32
+
33
+ from ...generation.test_utils import GenerationTesterMixin
34
+ from ...test_configuration_common import ConfigTester
35
+ from ...test_modeling_common import ModelTesterMixin, ids_tensor
36
+ from ...test_pipeline_mixin import PipelineTesterMixin
37
+
38
+
39
+ if is_torch_available():
40
+ import torch
41
+
42
+ from transformers import PegasusTokenizer, PegasusXConfig, PegasusXForConditionalGeneration, PegasusXModel
43
+ from transformers.models.pegasus_x.modeling_pegasus_x import PegasusXDecoder, PegasusXEncoder
44
+
45
+
46
+ def prepare_pegasus_x_inputs_dict(
47
+ config,
48
+ input_ids,
49
+ decoder_input_ids,
50
+ attention_mask=None,
51
+ decoder_attention_mask=None,
52
+ ):
53
+ if attention_mask is None:
54
+ attention_mask = input_ids.ne(config.pad_token_id)
55
+ if decoder_attention_mask is None:
56
+ decoder_attention_mask = decoder_input_ids.ne(config.pad_token_id)
57
+ return {
58
+ "input_ids": input_ids,
59
+ "decoder_input_ids": decoder_input_ids,
60
+ "attention_mask": attention_mask,
61
+ "decoder_attention_mask": attention_mask,
62
+ }
63
+
64
+
65
+ @require_torch
66
+ class PegasusXModelTester:
67
+ def __init__(
68
+ self,
69
+ parent,
70
+ batch_size=13,
71
+ seq_length=7,
72
+ is_training=True,
73
+ use_labels=False,
74
+ vocab_size=99,
75
+ hidden_size=16,
76
+ num_hidden_layers=2,
77
+ num_attention_heads=4,
78
+ intermediate_size=4,
79
+ hidden_act="gelu",
80
+ hidden_dropout_prob=0.1,
81
+ attention_probs_dropout_prob=0.1,
82
+ max_position_embeddings=20,
83
+ eos_token_id=2,
84
+ pad_token_id=1,
85
+ bos_token_id=0,
86
+ ):
87
+ self.parent = parent
88
+ self.batch_size = batch_size
89
+ self.seq_length = seq_length
90
+ self.is_training = is_training
91
+ self.use_labels = use_labels
92
+ self.vocab_size = vocab_size
93
+ self.hidden_size = hidden_size
94
+ self.num_hidden_layers = num_hidden_layers
95
+ self.num_attention_heads = num_attention_heads
96
+ self.intermediate_size = intermediate_size
97
+ self.hidden_act = hidden_act
98
+ self.hidden_dropout_prob = hidden_dropout_prob
99
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
100
+ self.max_position_embeddings = max_position_embeddings
101
+ self.eos_token_id = eos_token_id
102
+ self.pad_token_id = pad_token_id
103
+ self.bos_token_id = bos_token_id
104
+
105
+ def prepare_config_and_inputs(self):
106
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size).clamp(
107
+ 3,
108
+ )
109
+ input_ids[:, -1] = self.eos_token_id # Eos Token
110
+
111
+ decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
112
+
113
+ config = PegasusXConfig(
114
+ vocab_size=self.vocab_size,
115
+ d_model=self.hidden_size,
116
+ encoder_layers=self.num_hidden_layers,
117
+ decoder_layers=self.num_hidden_layers,
118
+ encoder_attention_heads=self.num_attention_heads,
119
+ decoder_attention_heads=self.num_attention_heads,
120
+ encoder_ffn_dim=self.intermediate_size,
121
+ decoder_ffn_dim=self.intermediate_size,
122
+ dropout=self.hidden_dropout_prob,
123
+ attention_dropout=self.attention_probs_dropout_prob,
124
+ max_position_embeddings=self.max_position_embeddings,
125
+ eos_token_id=self.eos_token_id,
126
+ bos_token_id=self.bos_token_id,
127
+ pad_token_id=self.pad_token_id,
128
+ stagger_local_blocks=False,
129
+ )
130
+ inputs_dict = prepare_pegasus_x_inputs_dict(config, input_ids, decoder_input_ids)
131
+ return config, inputs_dict
132
+
133
+ def prepare_config_and_inputs_for_common(self):
134
+ config, inputs_dict = self.prepare_config_and_inputs()
135
+ return config, inputs_dict
136
+
137
+ def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict):
138
+ model = PegasusXModel(config=config).get_decoder().to(torch_device).eval()
139
+ input_ids = inputs_dict["input_ids"]
140
+ attention_mask = inputs_dict["attention_mask"]
141
+
142
+ # first forward pass
143
+ outputs = model(input_ids, attention_mask=attention_mask, use_cache=True)
144
+
145
+ output, past_key_values = outputs.to_tuple()
146
+
147
+ # create hypothetical multiple next token and extent to next_input_ids
148
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
149
+ next_attn_mask = ids_tensor((self.batch_size, 3), 2)
150
+
151
+ # append to next input_ids and
152
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
153
+ next_attention_mask = torch.cat([attention_mask, next_attn_mask], dim=-1)
154
+
155
+ output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"]
156
+ output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[
157
+ "last_hidden_state"
158
+ ]
159
+
160
+ # select random slice
161
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
162
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
163
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
164
+
165
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
166
+
167
+ # test that outputs are equal for slice
168
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-2))
169
+
170
+ def check_encoder_decoder_model_standalone(self, config, inputs_dict):
171
+ model = PegasusXModel(config=config).to(torch_device).eval()
172
+ outputs = model(**inputs_dict)
173
+
174
+ encoder_last_hidden_state = outputs.encoder_last_hidden_state
175
+ last_hidden_state = outputs.last_hidden_state
176
+
177
+ with tempfile.TemporaryDirectory() as tmpdirname:
178
+ encoder = model.get_encoder()
179
+ encoder.save_pretrained(tmpdirname)
180
+ encoder = PegasusXEncoder.from_pretrained(tmpdirname).to(torch_device)
181
+
182
+ encoder_last_hidden_state_2 = encoder(inputs_dict["input_ids"], attention_mask=inputs_dict["attention_mask"])[
183
+ 0
184
+ ]
185
+
186
+ self.parent.assertTrue((encoder_last_hidden_state_2 - encoder_last_hidden_state).abs().max().item() < 1e-3)
187
+
188
+ with tempfile.TemporaryDirectory() as tmpdirname:
189
+ decoder = model.get_decoder()
190
+ decoder.save_pretrained(tmpdirname)
191
+ decoder = PegasusXDecoder.from_pretrained(tmpdirname).to(torch_device)
192
+
193
+ last_hidden_state_2 = decoder(
194
+ input_ids=inputs_dict["decoder_input_ids"],
195
+ attention_mask=inputs_dict["decoder_attention_mask"],
196
+ encoder_hidden_states=encoder_last_hidden_state,
197
+ encoder_attention_mask=inputs_dict["attention_mask"],
198
+ )[0]
199
+
200
+ self.parent.assertTrue((last_hidden_state_2 - last_hidden_state).abs().max().item() < 1e-3)
201
+
202
+
203
+ @require_torch
204
+ class PegasusXModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
205
+ all_model_classes = (PegasusXModel, PegasusXForConditionalGeneration) if is_torch_available() else ()
206
+ all_generative_model_classes = (PegasusXForConditionalGeneration,) if is_torch_available() else ()
207
+ pipeline_model_mapping = (
208
+ {
209
+ "feature-extraction": PegasusXModel,
210
+ "summarization": PegasusXForConditionalGeneration,
211
+ "text2text-generation": PegasusXForConditionalGeneration,
212
+ "translation": PegasusXForConditionalGeneration,
213
+ }
214
+ if is_torch_available()
215
+ else {}
216
+ )
217
+ is_encoder_decoder = True
218
+ test_pruning = False
219
+ test_head_masking = False
220
+ test_missing_keys = False
221
+
222
+ def setUp(self):
223
+ self.model_tester = PegasusXModelTester(self)
224
+ self.config_tester = ConfigTester(self, config_class=PegasusXConfig)
225
+
226
+ @unittest.skip(
227
+ "`PegasusXGlobalLocalAttention` returns attentions as dictionary - not compatible with torchscript "
228
+ )
229
+ def test_torchscript_output_attentions(self):
230
+ pass
231
+
232
+ def test_config(self):
233
+ self.config_tester.run_common_tests()
234
+
235
+ def test_save_load_strict(self):
236
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
237
+ for model_class in self.all_model_classes:
238
+ model = model_class(config)
239
+
240
+ with tempfile.TemporaryDirectory() as tmpdirname:
241
+ model.save_pretrained(tmpdirname)
242
+ model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True)
243
+ self.assertEqual(info["missing_keys"], [])
244
+
245
+ def test_decoder_model_past_with_large_inputs(self):
246
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
247
+ self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
248
+
249
+ def test_encoder_decoder_model_standalone(self):
250
+ config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common()
251
+ self.model_tester.check_encoder_decoder_model_standalone(*config_and_inputs)
252
+
253
+ def test_inputs_embeds(self):
254
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
255
+
256
+ for model_class in (PegasusXModel, PegasusXForConditionalGeneration):
257
+ model = model_class(config)
258
+ model.to(torch_device)
259
+ model.eval()
260
+
261
+ inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class))
262
+
263
+ if not self.is_encoder_decoder:
264
+ input_ids = inputs["input_ids"]
265
+ del inputs["input_ids"]
266
+ else:
267
+ encoder_input_ids = inputs["input_ids"]
268
+ decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids)
269
+ del inputs["input_ids"]
270
+ inputs.pop("decoder_input_ids", None)
271
+
272
+ wte = model.get_input_embeddings()
273
+ if not self.is_encoder_decoder:
274
+ inputs["inputs_embeds"] = wte(input_ids)
275
+ else:
276
+ inputs["inputs_embeds"] = wte(encoder_input_ids)
277
+ inputs["decoder_inputs_embeds"] = wte(decoder_input_ids)
278
+
279
+ with torch.no_grad():
280
+ model(**inputs)[0]
281
+
282
+ @require_torch_fp16
283
+ def test_generate_fp16(self):
284
+ config, input_dict = self.model_tester.prepare_config_and_inputs()
285
+ input_ids = input_dict["input_ids"]
286
+ attention_mask = input_ids.ne(1).to(torch_device)
287
+ model = PegasusXForConditionalGeneration(config).eval().to(torch_device)
288
+ model.half()
289
+ model.generate(input_ids, attention_mask=attention_mask)
290
+ model.generate(num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3)
291
+
292
+ def test_attention_outputs(self):
293
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
294
+ config.return_dict = True
295
+
296
+ seq_len = getattr(self.model_tester, "seq_length", None)
297
+ decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len)
298
+ encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len)
299
+ decoder_key_length = getattr(self.model_tester, "decoder_key_length", decoder_seq_length)
300
+ encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length)
301
+ chunk_length = getattr(self.model_tester, "chunk_length", None)
302
+ if chunk_length is not None and hasattr(self.model_tester, "num_hashes"):
303
+ encoder_seq_length = encoder_seq_length * self.model_tester.num_hashes
304
+
305
+ for model_class in self.all_model_classes:
306
+ inputs_dict["output_attentions"] = True
307
+ inputs_dict["output_hidden_states"] = False
308
+ config.return_dict = True
309
+ model = model_class(config)
310
+ model.to(torch_device)
311
+ model.eval()
312
+ with torch.no_grad():
313
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
314
+ attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
315
+ self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
316
+
317
+ # check that output_attentions also work using config
318
+ del inputs_dict["output_attentions"]
319
+ config.output_attentions = True
320
+ model = model_class(config)
321
+ model.to(torch_device)
322
+ model.eval()
323
+ with torch.no_grad():
324
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
325
+ attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
326
+ self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
327
+
328
+ self.assertListEqual(
329
+ list(attentions[0]["local"].shape[-4:]),
330
+ [
331
+ self.model_tester.num_attention_heads,
332
+ math.ceil(encoder_seq_length / model.config.block_size),
333
+ model.config.block_size,
334
+ model.config.block_size + model.config.num_global_tokens,
335
+ ],
336
+ )
337
+ out_len = len(outputs)
338
+
339
+ if self.is_encoder_decoder:
340
+ correct_outlen = 5
341
+
342
+ # loss is at first position
343
+ if "labels" in inputs_dict:
344
+ correct_outlen += 1 # loss is added to beginning
345
+ if "past_key_values" in outputs:
346
+ correct_outlen += 1 # past_key_values have been returned
347
+
348
+ self.assertEqual(out_len, correct_outlen)
349
+
350
+ # decoder attentions
351
+ decoder_attentions = outputs.decoder_attentions
352
+ self.assertIsInstance(decoder_attentions, (list, tuple))
353
+ self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers)
354
+ self.assertListEqual(
355
+ list(decoder_attentions[0].shape[-3:]),
356
+ [self.model_tester.num_attention_heads, decoder_seq_length, decoder_key_length],
357
+ )
358
+
359
+ # cross attentions
360
+ cross_attentions = outputs.cross_attentions
361
+ self.assertIsInstance(cross_attentions, (list, tuple))
362
+ self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers)
363
+ self.assertListEqual(
364
+ list(cross_attentions[0].shape[-3:]),
365
+ [
366
+ self.model_tester.num_attention_heads,
367
+ decoder_seq_length,
368
+ encoder_key_length,
369
+ ],
370
+ )
371
+
372
+ # Check attention is always last and order is fine
373
+ inputs_dict["output_attentions"] = True
374
+ inputs_dict["output_hidden_states"] = True
375
+ model = model_class(config)
376
+ model.to(torch_device)
377
+ model.eval()
378
+ with torch.no_grad():
379
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
380
+
381
+ if hasattr(self.model_tester, "num_hidden_states_types"):
382
+ added_hidden_states = self.model_tester.num_hidden_states_types
383
+ elif self.is_encoder_decoder:
384
+ added_hidden_states = 2
385
+ else:
386
+ added_hidden_states = 1
387
+ self.assertEqual(out_len + added_hidden_states, len(outputs))
388
+
389
+ self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
390
+
391
+ self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers)
392
+ self.assertListEqual(
393
+ list(self_attentions[0]["local"].shape[-4:]),
394
+ [
395
+ self.model_tester.num_attention_heads,
396
+ math.ceil(encoder_seq_length / model.config.block_size),
397
+ model.config.block_size,
398
+ model.config.block_size + model.config.num_global_tokens,
399
+ ],
400
+ )
401
+
402
+ def _check_encoder_attention_for_generate(self, attentions, batch_size, config, seq_length):
403
+ encoder_expected_shape = (
404
+ batch_size,
405
+ config.num_attention_heads,
406
+ math.ceil(seq_length / config.block_size),
407
+ config.block_size,
408
+ config.block_size + config.num_global_tokens,
409
+ )
410
+ self.assertIsInstance(attentions, tuple)
411
+ self.assertListEqual(
412
+ [layer_attentions["local"].shape for layer_attentions in attentions],
413
+ [encoder_expected_shape] * len(attentions),
414
+ )
415
+
416
+ def _check_encoder_hidden_states_for_generate(self, hidden_states, batch_size, config, seq_length):
417
+ encoder_expected_shape = (batch_size, self.round_up(seq_length, config.block_size), config.hidden_size)
418
+ self.assertIsInstance(hidden_states, tuple)
419
+ # Only the last layer will have the hidden states truncated back to token level
420
+ self.assertListEqual(
421
+ [layer_hidden_states.shape for layer_hidden_states in hidden_states[:-1]],
422
+ [encoder_expected_shape] * (len(hidden_states) - 1),
423
+ )
424
+ # Only the last layer will have the hidden states truncated back to token level
425
+ self.assertEqual(
426
+ hidden_states[-1][0].shape,
427
+ (batch_size, seq_length, config.hidden_size),
428
+ )
429
+
430
+ def test_hidden_states_output(self):
431
+ def _check_hidden_states_output(inputs_dict, config, model_class):
432
+ model = model_class(config)
433
+ model.to(torch_device)
434
+ model.eval()
435
+
436
+ with torch.no_grad():
437
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
438
+
439
+ hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
440
+
441
+ expected_num_layers = getattr(
442
+ self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1
443
+ )
444
+ self.assertEqual(len(hidden_states), expected_num_layers)
445
+
446
+ if hasattr(self.model_tester, "encoder_seq_length"):
447
+ seq_length = self.model_tester.encoder_seq_length
448
+ if hasattr(self.model_tester, "chunk_length") and self.model_tester.chunk_length > 1:
449
+ seq_length = seq_length * self.model_tester.chunk_length
450
+ else:
451
+ seq_length = self.model_tester.seq_length
452
+
453
+ self.assertListEqual(
454
+ list(hidden_states[0].shape[-2:]),
455
+ [self.round_up(seq_length, config.block_size), self.model_tester.hidden_size],
456
+ )
457
+
458
+ if config.is_encoder_decoder:
459
+ hidden_states = outputs.decoder_hidden_states
460
+
461
+ self.assertIsInstance(hidden_states, (list, tuple))
462
+ self.assertEqual(len(hidden_states), expected_num_layers)
463
+ seq_len = getattr(self.model_tester, "seq_length", None)
464
+ decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len)
465
+
466
+ self.assertListEqual(
467
+ list(hidden_states[0].shape[-2:]),
468
+ [decoder_seq_length, self.model_tester.hidden_size],
469
+ )
470
+
471
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
472
+
473
+ for model_class in self.all_model_classes:
474
+ inputs_dict["output_hidden_states"] = True
475
+ _check_hidden_states_output(inputs_dict, config, model_class)
476
+
477
+ # check that output_hidden_states also work using config
478
+ del inputs_dict["output_hidden_states"]
479
+ config.output_hidden_states = True
480
+
481
+ _check_hidden_states_output(inputs_dict, config, model_class)
482
+
483
+ def test_retain_grad_hidden_states_attentions(self):
484
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
485
+ config.output_hidden_states = True
486
+ config.output_attentions = self.has_attentions
487
+
488
+ # no need to test all models as different heads yield the same functionality
489
+ model_class = self.all_model_classes[0]
490
+ model = model_class(config)
491
+ model.to(torch_device)
492
+
493
+ inputs = self._prepare_for_class(inputs_dict, model_class)
494
+
495
+ outputs = model(**inputs)
496
+
497
+ output = outputs[0]
498
+
499
+ if config.is_encoder_decoder:
500
+ # Seq2Seq models
501
+ encoder_hidden_states = outputs.encoder_hidden_states[0]
502
+ encoder_hidden_states.retain_grad()
503
+
504
+ decoder_hidden_states = outputs.decoder_hidden_states[0]
505
+ decoder_hidden_states.retain_grad()
506
+
507
+ if self.has_attentions:
508
+ encoder_attentions = outputs.encoder_attentions[0]
509
+ encoder_attentions["local"].retain_grad()
510
+ encoder_attentions["global"].retain_grad()
511
+
512
+ decoder_attentions = outputs.decoder_attentions[0]
513
+ decoder_attentions.retain_grad()
514
+
515
+ cross_attentions = outputs.cross_attentions[0]
516
+ cross_attentions.retain_grad()
517
+
518
+ output.flatten()[0].backward(retain_graph=True)
519
+
520
+ self.assertIsNotNone(encoder_hidden_states.grad)
521
+ self.assertIsNotNone(decoder_hidden_states.grad)
522
+
523
+ if self.has_attentions:
524
+ self.assertIsNotNone(encoder_attentions["local"].grad)
525
+ self.assertIsNotNone(encoder_attentions["global"].grad)
526
+ self.assertIsNotNone(decoder_attentions.grad)
527
+ self.assertIsNotNone(cross_attentions.grad)
528
+ else:
529
+ # Encoder-/Decoder-only models
530
+ hidden_states = outputs.hidden_states[0]
531
+ hidden_states.retain_grad()
532
+
533
+ if self.has_attentions:
534
+ attentions = outputs.attentions[0]
535
+ attentions.retain_grad()
536
+
537
+ output.flatten()[0].backward(retain_graph=True)
538
+
539
+ self.assertIsNotNone(hidden_states.grad)
540
+
541
+ if self.has_attentions:
542
+ self.assertIsNotNone(attentions.grad)
543
+
544
+ @classmethod
545
+ def round_up(cls, n, k):
546
+ return math.ceil(n / k) * k
547
+
548
+
549
+ def assert_tensors_close(a, b, atol=1e-12, prefix=""):
550
+ """If tensors have different shapes, different values or a and b are not both tensors, raise a nice Assertion error."""
551
+ if a is None and b is None:
552
+ return True
553
+ try:
554
+ if torch.allclose(a, b, atol=atol):
555
+ return True
556
+ raise
557
+ except Exception:
558
+ pct_different = (torch.gt((a - b).abs(), atol)).float().mean().item()
559
+ if a.numel() > 100:
560
+ msg = f"tensor values are {pct_different:.1%} percent different."
561
+ else:
562
+ msg = f"{a} != {b}"
563
+ if prefix:
564
+ msg = prefix + ": " + msg
565
+ raise AssertionError(msg)
566
+
567
+
568
+ def _long_tensor(tok_lst):
569
+ return torch.tensor(tok_lst, dtype=torch.long, device=torch_device)
570
+
571
+
572
+ TOLERANCE = 1e-4
573
+
574
+
575
+ @require_torch
576
+ @require_sentencepiece
577
+ @require_tokenizers
578
+ @slow
579
+ class PegasusXModelIntegrationTests(unittest.TestCase):
580
+ @cached_property
581
+ def default_tokenizer(self):
582
+ return PegasusTokenizer.from_pretrained("google/pegasus-x-base")
583
+
584
+ def test_inference_no_head(self):
585
+ model = PegasusXModel.from_pretrained("google/pegasus-x-base").to(torch_device)
586
+ input_ids = _long_tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
587
+ decoder_input_ids = _long_tensor([[2, 0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588]])
588
+ inputs_dict = prepare_pegasus_x_inputs_dict(model.config, input_ids, decoder_input_ids)
589
+ with torch.no_grad():
590
+ output = model(**inputs_dict)[0]
591
+ expected_shape = torch.Size((1, 11, 768))
592
+ self.assertEqual(output.shape, expected_shape)
593
+ # change to expected output here
594
+ expected_slice = torch.tensor(
595
+ [[0.0702, -0.1552, 0.1192], [0.0836, -0.1848, 0.1304], [0.0673, -0.1686, 0.1045]], device=torch_device
596
+ )
597
+
598
+ self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=TOLERANCE))
599
+
600
+ def test_inference_head(self):
601
+ model = PegasusXForConditionalGeneration.from_pretrained("google/pegasus-x-base").to(torch_device)
602
+
603
+ # change to intended input
604
+ input_ids = _long_tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
605
+ decoder_input_ids = _long_tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
606
+ inputs_dict = prepare_pegasus_x_inputs_dict(model.config, input_ids, decoder_input_ids)
607
+ with torch.no_grad():
608
+ output = model(**inputs_dict)[0]
609
+ expected_shape = torch.Size((1, 11, model.config.vocab_size))
610
+ self.assertEqual(output.shape, expected_shape)
611
+ # change to expected output here
612
+ expected_slice = torch.tensor(
613
+ [[0.0, 9.5705185, 1.5897303], [0.0, 9.833374, 1.5828674], [0.0, 10.429961, 1.5643371]], device=torch_device
614
+ )
615
+ self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=TOLERANCE))
616
+
617
+ def test_seq_to_seq_generation(self):
618
+ hf = PegasusXForConditionalGeneration.from_pretrained("google/pegasus-x-base-arxiv").to(torch_device)
619
+ tok = PegasusTokenizer.from_pretrained("google/pegasus-x-base")
620
+
621
+ batch_input = [
622
+ "While large pretrained Transformer models have proven highly capable at tackling natural language tasks,"
623
+ " handling long sequence inputs continues to be a significant challenge. One such task is long input"
624
+ " summarization, where inputs are longer than the maximum input context of most pretrained models. Through"
625
+ " an extensive set of experiments, we investigate what model architectural changes and pretraining"
626
+ " paradigms can most efficiently adapt a pretrained Transformer for long input summarization. We find that"
627
+ " a staggered, block-local Transformer with global encoder tokens strikes a good balance of performance"
628
+ " and efficiency, and that an additional pretraining phase on long sequences meaningfully improves"
629
+ " downstream summarization performance. Based on our findings, we introduce PEGASUS-X, an extension of the"
630
+ " PEGASUS model with additional long input pretraining to handle inputs of up to 16K tokens. PEGASUS-X"
631
+ " achieves strong performance on long input summarization tasks comparable with much larger models while"
632
+ " adding few additional parameters and not requiring model parallelism to train."
633
+ ]
634
+
635
+ # The below article tests that we don't add any hypotheses outside of the top n_beams
636
+ dct = tok.batch_encode_plus(
637
+ batch_input,
638
+ max_length=512,
639
+ padding="max_length",
640
+ truncation_strategy="only_first",
641
+ truncation=True,
642
+ return_tensors="pt",
643
+ )
644
+
645
+ hypotheses_batch = hf.generate(
646
+ input_ids=dct["input_ids"].to(torch_device),
647
+ attention_mask=dct["attention_mask"].to(torch_device),
648
+ num_beams=2,
649
+ max_length=32,
650
+ )
651
+
652
+ EXPECTED = [
653
+ "we investigate the performance of a new pretrained model for long input summarization. <n> the model is a"
654
+ " superposition of two well -"
655
+ ]
656
+
657
+ generated = tok.batch_decode(
658
+ hypotheses_batch.tolist(), clean_up_tokenization_spaces=True, skip_special_tokens=True
659
+ )
660
+ assert generated == EXPECTED
661
+
662
+
663
+ class PegasusXStandaloneDecoderModelTester:
664
+ def __init__(
665
+ self,
666
+ parent,
667
+ vocab_size=99,
668
+ batch_size=13,
669
+ d_model=16,
670
+ decoder_seq_length=7,
671
+ is_training=True,
672
+ is_decoder=True,
673
+ use_attention_mask=True,
674
+ use_cache=False,
675
+ use_labels=True,
676
+ decoder_start_token_id=2,
677
+ decoder_ffn_dim=32,
678
+ decoder_layers=2,
679
+ encoder_attention_heads=4,
680
+ decoder_attention_heads=4,
681
+ max_position_embeddings=30,
682
+ is_encoder_decoder=False,
683
+ pad_token_id=0,
684
+ bos_token_id=1,
685
+ eos_token_id=2,
686
+ scope=None,
687
+ ):
688
+ self.parent = parent
689
+ self.batch_size = batch_size
690
+ self.decoder_seq_length = decoder_seq_length
691
+ # For common tests
692
+ self.seq_length = self.decoder_seq_length
693
+ self.is_training = is_training
694
+ self.use_attention_mask = use_attention_mask
695
+ self.use_labels = use_labels
696
+
697
+ self.vocab_size = vocab_size
698
+ self.d_model = d_model
699
+ self.hidden_size = d_model
700
+ self.num_hidden_layers = decoder_layers
701
+ self.decoder_layers = decoder_layers
702
+ self.decoder_ffn_dim = decoder_ffn_dim
703
+ self.encoder_attention_heads = encoder_attention_heads
704
+ self.decoder_attention_heads = decoder_attention_heads
705
+ self.num_attention_heads = decoder_attention_heads
706
+ self.eos_token_id = eos_token_id
707
+ self.bos_token_id = bos_token_id
708
+ self.pad_token_id = pad_token_id
709
+ self.decoder_start_token_id = decoder_start_token_id
710
+ self.use_cache = use_cache
711
+ self.max_position_embeddings = max_position_embeddings
712
+ self.is_encoder_decoder = is_encoder_decoder
713
+
714
+ self.scope = None
715
+ self.decoder_key_length = decoder_seq_length
716
+ self.base_model_out_len = 2
717
+ self.decoder_attention_idx = 1
718
+
719
+ def prepare_config_and_inputs(self):
720
+ input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)
721
+
722
+ attention_mask = None
723
+ if self.use_attention_mask:
724
+ attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2)
725
+
726
+ lm_labels = None
727
+ if self.use_labels:
728
+ lm_labels = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)
729
+
730
+ config = PegasusXConfig(
731
+ vocab_size=self.vocab_size,
732
+ d_model=self.d_model,
733
+ decoder_layers=self.decoder_layers,
734
+ decoder_ffn_dim=self.decoder_ffn_dim,
735
+ encoder_attention_heads=self.encoder_attention_heads,
736
+ decoder_attention_heads=self.decoder_attention_heads,
737
+ eos_token_id=self.eos_token_id,
738
+ bos_token_id=self.bos_token_id,
739
+ use_cache=self.use_cache,
740
+ pad_token_id=self.pad_token_id,
741
+ decoder_start_token_id=self.decoder_start_token_id,
742
+ max_position_embeddings=self.max_position_embeddings,
743
+ is_encoder_decoder=self.is_encoder_decoder,
744
+ )
745
+
746
+ return (
747
+ config,
748
+ input_ids,
749
+ attention_mask,
750
+ lm_labels,
751
+ )
752
+
753
+ def create_and_check_decoder_model_past(
754
+ self,
755
+ config,
756
+ input_ids,
757
+ attention_mask,
758
+ lm_labels,
759
+ ):
760
+ config.use_cache = True
761
+ model = PegasusXDecoder(config=config).to(torch_device).eval()
762
+ # first forward pass
763
+ outputs = model(input_ids, use_cache=True)
764
+ outputs_use_cache_conf = model(input_ids)
765
+ outputs_no_past = model(input_ids, use_cache=False)
766
+
767
+ self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))
768
+ self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)
769
+
770
+ past_key_values = outputs["past_key_values"]
771
+
772
+ # create hypothetical next token and extent to next_input_ids
773
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
774
+
775
+ # append to next input_ids and
776
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
777
+
778
+ output_from_no_past = model(next_input_ids)["last_hidden_state"]
779
+ output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"]
780
+
781
+ # select random slice
782
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
783
+ output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
784
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
785
+
786
+ # test that outputs are equal for slice
787
+ assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3)
788
+
789
+ def create_and_check_decoder_model_attention_mask_past(
790
+ self,
791
+ config,
792
+ input_ids,
793
+ attention_mask,
794
+ lm_labels,
795
+ ):
796
+ model = PegasusXDecoder(config=config).to(torch_device).eval()
797
+
798
+ # create attention mask
799
+ attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
800
+
801
+ half_seq_length = input_ids.shape[-1] // 2
802
+ attn_mask[:, half_seq_length:] = 0
803
+
804
+ # first forward pass
805
+ past_key_values = model(input_ids, attention_mask=attn_mask, use_cache=True)["past_key_values"]
806
+
807
+ # create hypothetical next token and extent to next_input_ids
808
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
809
+
810
+ # change a random masked slice from input_ids
811
+ random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1
812
+ random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1)
813
+ input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens
814
+
815
+ # append to next input_ids and attn_mask
816
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
817
+ attn_mask = torch.cat(
818
+ [attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)],
819
+ dim=1,
820
+ )
821
+
822
+ # get two different outputs
823
+ output_from_no_past = model(next_input_ids)["last_hidden_state"]
824
+ output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"]
825
+
826
+ # select random slice
827
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
828
+ output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
829
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
830
+
831
+ # test that outputs are equal for slice
832
+ assert torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-2)
833
+
834
+ def prepare_config_and_inputs_for_common(self):
835
+ config_and_inputs = self.prepare_config_and_inputs()
836
+ (
837
+ config,
838
+ input_ids,
839
+ attention_mask,
840
+ lm_labels,
841
+ ) = config_and_inputs
842
+
843
+ inputs_dict = {
844
+ "input_ids": input_ids,
845
+ "attention_mask": attention_mask,
846
+ }
847
+ return config, inputs_dict
848
+
849
+
850
+ @require_torch
851
+ class PegasusXStandaloneDecoderModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
852
+ all_model_classes = (PegasusXDecoder,) if is_torch_available() else ()
853
+ all_generative_model_classes = ()
854
+ test_pruning = False
855
+ is_encoder_decoder = False
856
+ test_head_masking = False
857
+
858
+ def setUp(
859
+ self,
860
+ ):
861
+ self.model_tester = PegasusXStandaloneDecoderModelTester(self, is_training=False)
862
+ self.config_tester = ConfigTester(self, config_class=PegasusXConfig)
863
+
864
+ def test_config(self):
865
+ self.config_tester.run_common_tests()
866
+
867
+ def test_decoder_model_past(self):
868
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
869
+ self.model_tester.create_and_check_decoder_model_past(*config_and_inputs)
870
+
871
+ def test_decoder_model_attn_mask_past(self):
872
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
873
+ self.model_tester.create_and_check_decoder_model_attention_mask_past(*config_and_inputs)
874
+
875
+ @unittest.skip(reason="Decoder cannot keep gradients")
876
+ def test_retain_grad_hidden_states_attentions(self):
877
+ return
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/perceiver/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/perceiver/test_modeling_perceiver.py ADDED
@@ -0,0 +1,1053 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Perceiver model."""
16
+
17
+ import copy
18
+ import inspect
19
+ import math
20
+ import tempfile
21
+ import unittest
22
+ import warnings
23
+ from typing import Dict, List, Tuple
24
+
25
+ import numpy as np
26
+ from datasets import load_dataset
27
+
28
+ from transformers import PerceiverConfig
29
+ from transformers.testing_utils import (
30
+ IS_ROCM_SYSTEM,
31
+ require_torch,
32
+ require_torch_multi_gpu,
33
+ require_vision,
34
+ slow,
35
+ torch_device,
36
+ )
37
+ from transformers.utils import is_torch_available, is_vision_available
38
+
39
+ from ...test_configuration_common import ConfigTester
40
+ from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
41
+ from ...test_pipeline_mixin import PipelineTesterMixin
42
+
43
+
44
+ if is_torch_available():
45
+ import torch
46
+ from torch import nn
47
+
48
+ from transformers import (
49
+ PerceiverForImageClassificationConvProcessing,
50
+ PerceiverForImageClassificationFourier,
51
+ PerceiverForImageClassificationLearned,
52
+ PerceiverForMaskedLM,
53
+ PerceiverForMultimodalAutoencoding,
54
+ PerceiverForOpticalFlow,
55
+ PerceiverForSequenceClassification,
56
+ PerceiverModel,
57
+ PerceiverTokenizer,
58
+ )
59
+ from transformers.models.auto.modeling_auto import (
60
+ MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES,
61
+ MODEL_FOR_MASKED_LM_MAPPING_NAMES,
62
+ MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES,
63
+ MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES,
64
+ MODEL_MAPPING_NAMES,
65
+ )
66
+
67
+
68
+ if is_vision_available():
69
+ from PIL import Image
70
+
71
+ from transformers import PerceiverImageProcessor
72
+
73
+
74
+ class PerceiverModelTester:
75
+ def __init__(
76
+ self,
77
+ parent,
78
+ batch_size=13,
79
+ seq_length=7,
80
+ num_channels=3,
81
+ image_size=32,
82
+ train_size=[20, 20],
83
+ num_frames=5,
84
+ audio_samples_per_frame=200,
85
+ samples_per_patch=20,
86
+ nchunks=20,
87
+ num_latents=10,
88
+ d_latents=20,
89
+ d_model=64,
90
+ num_blocks=1,
91
+ num_self_attends_per_block=2,
92
+ num_self_attention_heads=1,
93
+ num_cross_attention_heads=1,
94
+ self_attention_widening_factor=4,
95
+ cross_attention_widening_factor=4,
96
+ is_training=True,
97
+ use_input_mask=True,
98
+ use_labels=True,
99
+ vocab_size=99,
100
+ hidden_act="gelu",
101
+ attention_probs_dropout_prob=0.1,
102
+ initializer_range=0.02,
103
+ max_position_embeddings=7,
104
+ num_labels=3,
105
+ scope=None,
106
+ ):
107
+ self.parent = parent
108
+ self.batch_size = batch_size
109
+ self.seq_length = seq_length
110
+ self.num_channels = num_channels
111
+ self.image_size = image_size
112
+ self.train_size = train_size
113
+ self.num_frames = num_frames
114
+ self.audio_samples_per_frame = audio_samples_per_frame
115
+ self.samples_per_patch = samples_per_patch
116
+ self.nchunks = nchunks
117
+ self.num_latents = num_latents
118
+ self.d_latents = d_latents
119
+ self.d_model = d_model
120
+ self.num_blocks = num_blocks
121
+ self.num_self_attends_per_block = num_self_attends_per_block
122
+ self.num_self_attention_heads = num_self_attention_heads
123
+ self.num_cross_attention_heads = num_cross_attention_heads
124
+ self.self_attention_widening_factor = self_attention_widening_factor
125
+ self.cross_attention_widening_factor = cross_attention_widening_factor
126
+ self.is_training = is_training
127
+ self.use_input_mask = use_input_mask
128
+ self.use_labels = use_labels
129
+ self.vocab_size = vocab_size
130
+ self.hidden_act = hidden_act
131
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
132
+ self.max_position_embeddings = max_position_embeddings
133
+ self.initializer_range = initializer_range
134
+ self.num_labels = num_labels
135
+ self.scope = scope
136
+ # set subsampling for multimodal model (take first chunk)
137
+ image_chunk_size = np.prod((self.num_frames, self.image_size, self.image_size)) // self.nchunks
138
+ audio_chunk_size = self.num_frames * self.audio_samples_per_frame // self.samples_per_patch // self.nchunks
139
+ self.subsampling = {
140
+ "image": torch.arange(0, image_chunk_size),
141
+ "audio": torch.arange(0, audio_chunk_size),
142
+ "label": None,
143
+ }
144
+
145
+ def prepare_config_and_inputs(self, model_class=None):
146
+ config = self.get_config()
147
+
148
+ input_mask = None
149
+ sequence_labels = None
150
+ token_labels = None
151
+ if self.use_labels:
152
+ sequence_labels = ids_tensor([self.batch_size], self.num_labels)
153
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
154
+
155
+ if model_class is None or model_class.__name__ == "PerceiverModel":
156
+ inputs = floats_tensor([self.batch_size, self.seq_length, config.d_model], scale=1.0)
157
+ return config, inputs, input_mask, sequence_labels, token_labels
158
+ elif model_class.__name__ in ["PerceiverForMaskedLM", "PerceiverForSequenceClassification"]:
159
+ inputs = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
160
+ # input mask is only relevant for text inputs
161
+ if self.use_input_mask:
162
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
163
+ elif model_class.__name__ == "PerceiverForImageClassificationLearned":
164
+ inputs = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
165
+ elif model_class.__name__ == "PerceiverForImageClassificationFourier":
166
+ inputs = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
167
+ elif model_class.__name__ == "PerceiverForImageClassificationConvProcessing":
168
+ inputs = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
169
+ elif model_class.__name__ == "PerceiverForOpticalFlow":
170
+ inputs = floats_tensor([self.batch_size, 2, 27, self.train_size[0], self.train_size[1]])
171
+ elif model_class.__name__ == "PerceiverForMultimodalAutoencoding":
172
+ images = torch.randn(
173
+ (self.batch_size, self.num_frames, self.num_channels, self.image_size, self.image_size),
174
+ device=torch_device,
175
+ )
176
+ audio = torch.randn(
177
+ (self.batch_size, self.num_frames * self.audio_samples_per_frame, 1), device=torch_device
178
+ )
179
+ inputs = {
180
+ "image": images,
181
+ "audio": audio,
182
+ "label": torch.zeros((self.batch_size, self.num_labels), device=torch_device),
183
+ }
184
+ else:
185
+ raise ValueError(f"Model class {model_class} not supported")
186
+
187
+ return config, inputs, input_mask, sequence_labels, token_labels
188
+
189
+ def get_config(self):
190
+ return PerceiverConfig(
191
+ num_latents=self.num_latents,
192
+ d_latents=self.d_latents,
193
+ d_model=self.d_model,
194
+ qk_channels=self.d_latents,
195
+ v_channels=self.d_latents,
196
+ num_blocks=self.num_blocks,
197
+ num_self_attends_per_block=self.num_self_attends_per_block,
198
+ num_self_attention_heads=self.num_self_attention_heads,
199
+ num_cross_attention_heads=self.num_cross_attention_heads,
200
+ self_attention_widening_factor=self.self_attention_widening_factor,
201
+ cross_attention_widening_factor=self.cross_attention_widening_factor,
202
+ vocab_size=self.vocab_size,
203
+ hidden_act=self.hidden_act,
204
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
205
+ initializer_range=self.initializer_range,
206
+ max_position_embeddings=self.max_position_embeddings,
207
+ image_size=self.image_size,
208
+ train_size=self.train_size,
209
+ num_frames=self.num_frames,
210
+ audio_samples_per_frame=self.audio_samples_per_frame,
211
+ samples_per_patch=self.samples_per_patch,
212
+ num_labels=self.num_labels,
213
+ output_num_channels=32,
214
+ _label_trainable_num_channels=16,
215
+ )
216
+
217
+ def get_pipeline_config(self):
218
+ config = self.get_config()
219
+ # Byte level vocab
220
+ config.vocab_size = 261
221
+ config.max_position_embeddings = 40
222
+ return config
223
+
224
+ def create_and_check_for_masked_lm(self, config, inputs, input_mask, sequence_labels, token_labels):
225
+ model = PerceiverForMaskedLM(config=config)
226
+ model.to(torch_device)
227
+ model.eval()
228
+ result = model(inputs, attention_mask=input_mask, labels=token_labels)
229
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
230
+
231
+ def create_and_check_for_sequence_classification(self, config, inputs, input_mask, sequence_labels, token_labels):
232
+ model = PerceiverForSequenceClassification(config=config)
233
+ model.to(torch_device)
234
+ model.eval()
235
+ result = model(inputs, attention_mask=input_mask, labels=sequence_labels)
236
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
237
+
238
+ def create_and_check_for_image_classification_learned(
239
+ self, config, inputs, input_mask, sequence_labels, token_labels
240
+ ):
241
+ model = PerceiverForImageClassificationLearned(config=config)
242
+ model.to(torch_device)
243
+ model.eval()
244
+ result = model(inputs, attention_mask=input_mask, labels=sequence_labels)
245
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
246
+
247
+ def create_and_check_for_image_classification_fourier(
248
+ self, config, inputs, input_mask, sequence_labels, token_labels
249
+ ):
250
+ model = PerceiverForImageClassificationFourier(config=config)
251
+ model.to(torch_device)
252
+ model.eval()
253
+ result = model(inputs, attention_mask=input_mask, labels=sequence_labels)
254
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
255
+
256
+ def create_and_check_for_image_classification_conv(
257
+ self, config, inputs, input_mask, sequence_labels, token_labels
258
+ ):
259
+ model = PerceiverForImageClassificationConvProcessing(config=config)
260
+ model.to(torch_device)
261
+ model.eval()
262
+ result = model(inputs, attention_mask=input_mask, labels=sequence_labels)
263
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
264
+
265
+ def prepare_config_and_inputs_for_common(self):
266
+ config_and_inputs = self.prepare_config_and_inputs()
267
+ config, inputs, input_mask, sequence_labels, token_labels = config_and_inputs
268
+ inputs_dict = {"inputs": inputs, "attention_mask": input_mask}
269
+ return config, inputs_dict
270
+
271
+ def prepare_config_and_inputs_for_model_class(self, model_class):
272
+ config_and_inputs = self.prepare_config_and_inputs(model_class)
273
+ config, inputs, input_mask, sequence_labels, token_labels = config_and_inputs
274
+ inputs_dict = {"inputs": inputs, "attention_mask": input_mask}
275
+
276
+ return config, inputs_dict
277
+
278
+
279
+ @require_torch
280
+ class PerceiverModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
281
+ all_model_classes = (
282
+ (
283
+ PerceiverModel,
284
+ PerceiverForMaskedLM,
285
+ PerceiverForImageClassificationLearned,
286
+ PerceiverForImageClassificationConvProcessing,
287
+ PerceiverForImageClassificationFourier,
288
+ PerceiverForOpticalFlow,
289
+ PerceiverForMultimodalAutoencoding,
290
+ PerceiverForSequenceClassification,
291
+ )
292
+ if is_torch_available()
293
+ else ()
294
+ )
295
+ pipeline_model_mapping = (
296
+ {
297
+ "feature-extraction": PerceiverModel,
298
+ "fill-mask": PerceiverForMaskedLM,
299
+ "image-classification": (
300
+ PerceiverForImageClassificationConvProcessing,
301
+ PerceiverForImageClassificationFourier,
302
+ PerceiverForImageClassificationLearned,
303
+ ),
304
+ "text-classification": PerceiverForSequenceClassification,
305
+ "zero-shot": PerceiverForSequenceClassification,
306
+ }
307
+ if is_torch_available()
308
+ else {}
309
+ )
310
+ test_pruning = False
311
+ test_head_masking = False
312
+ test_torchscript = False
313
+
314
+ maxDiff = None
315
+
316
+ def setUp(self):
317
+ self.model_tester = PerceiverModelTester(self)
318
+ self.config_tester = ConfigTester(
319
+ self,
320
+ config_class=PerceiverConfig,
321
+ hidden_size=37,
322
+ common_properties=["d_model", "num_self_attention_heads", "num_cross_attention_heads"],
323
+ )
324
+
325
+ def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
326
+ inputs_dict = copy.deepcopy(inputs_dict)
327
+
328
+ if model_class.__name__ == "PerceiverForMultimodalAutoencoding":
329
+ inputs_dict["subsampled_output_points"] = self.model_tester.subsampling
330
+
331
+ if return_labels:
332
+ if model_class.__name__ in [
333
+ *MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES.values(),
334
+ "PerceiverForImageClassificationLearned",
335
+ "PerceiverForImageClassificationFourier",
336
+ "PerceiverForImageClassificationConvProcessing",
337
+ *MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES.values(),
338
+ ]:
339
+ inputs_dict["labels"] = torch.zeros(
340
+ self.model_tester.batch_size, dtype=torch.long, device=torch_device
341
+ )
342
+ elif model_class.__name__ in [
343
+ *MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES.values(),
344
+ *MODEL_FOR_MASKED_LM_MAPPING_NAMES.values(),
345
+ ]:
346
+ inputs_dict["labels"] = torch.zeros(
347
+ (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device
348
+ )
349
+ return inputs_dict
350
+
351
+ def test_config(self):
352
+ self.config_tester.run_common_tests()
353
+
354
+ def test_for_masked_lm(self):
355
+ config_and_inputs = self.model_tester.prepare_config_and_inputs(model_class=PerceiverForMaskedLM)
356
+ self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
357
+
358
+ def test_for_sequence_classification(self):
359
+ config_and_inputs = self.model_tester.prepare_config_and_inputs(model_class=PerceiverForSequenceClassification)
360
+ self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs)
361
+
362
+ def test_for_image_classification_learned(self):
363
+ config_and_inputs = self.model_tester.prepare_config_and_inputs(
364
+ model_class=PerceiverForImageClassificationLearned
365
+ )
366
+ self.model_tester.create_and_check_for_image_classification_learned(*config_and_inputs)
367
+
368
+ def test_for_image_classification_fourier(self):
369
+ config_and_inputs = self.model_tester.prepare_config_and_inputs(
370
+ model_class=PerceiverForImageClassificationFourier
371
+ )
372
+ self.model_tester.create_and_check_for_image_classification_fourier(*config_and_inputs)
373
+
374
+ def test_for_image_classification_conv(self):
375
+ config_and_inputs = self.model_tester.prepare_config_and_inputs(
376
+ model_class=PerceiverForImageClassificationConvProcessing
377
+ )
378
+ self.model_tester.create_and_check_for_image_classification_conv(*config_and_inputs)
379
+
380
+ def test_model_get_set_embeddings(self):
381
+ for model_class in self.all_model_classes:
382
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_model_class(model_class)
383
+ model = model_class(config)
384
+ # we overwrite this, as the embeddings of Perceiver are an instance of nn.Parameter
385
+ # and Perceiver doesn't support get_output_embeddings
386
+ self.assertIsInstance(model.get_input_embeddings(), (nn.Parameter))
387
+
388
+ def test_training(self):
389
+ if not self.model_tester.is_training:
390
+ self.skipTest(reason="model_tester.is_training is set to False")
391
+
392
+ for model_class in self.all_model_classes:
393
+ if model_class.__name__ in [
394
+ *MODEL_MAPPING_NAMES.values(),
395
+ "PerceiverForOpticalFlow",
396
+ "PerceiverForMultimodalAutoencoding",
397
+ ]:
398
+ continue
399
+
400
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_model_class(model_class)
401
+ config.return_dict = True
402
+
403
+ model = model_class(config)
404
+ model.to(torch_device)
405
+ model.train()
406
+ inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
407
+ loss = model(**inputs).loss
408
+ loss.backward()
409
+
410
+ def test_forward_signature(self):
411
+ for model_class in self.all_model_classes:
412
+ config, _ = self.model_tester.prepare_config_and_inputs_for_model_class(model_class)
413
+
414
+ model = model_class(config)
415
+ signature = inspect.signature(model.forward)
416
+ # signature.parameters is an OrderedDict => so arg_names order is deterministic
417
+ arg_names = [*signature.parameters.keys()]
418
+
419
+ expected_arg_names = ["inputs"]
420
+ self.assertListEqual(arg_names[:1], expected_arg_names)
421
+
422
+ def test_determinism(self):
423
+ for model_class in self.all_model_classes:
424
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_model_class(model_class)
425
+
426
+ model = model_class(config)
427
+ model.to(torch_device)
428
+ model.eval()
429
+ with torch.no_grad():
430
+ inputs_dict = self._prepare_for_class(inputs_dict, model_class)
431
+ first = model(**inputs_dict)[0]
432
+ second = model(**inputs_dict)[0]
433
+
434
+ if model_class.__name__ == "PerceiverForMultimodalAutoencoding":
435
+ # model outputs a dictionary with logits per modality, let's verify each modality
436
+ for modality in first.keys():
437
+ out_1 = first[modality].cpu().numpy()
438
+ out_2 = second[modality].cpu().numpy()
439
+ out_1 = out_1[~np.isnan(out_1)]
440
+ out_2 = out_2[~np.isnan(out_2)]
441
+ max_diff = np.amax(np.abs(out_1 - out_2))
442
+ self.assertLessEqual(max_diff, 1e-5)
443
+ else:
444
+ out_1 = first.cpu().numpy()
445
+ out_2 = second.cpu().numpy()
446
+ out_1 = out_1[~np.isnan(out_1)]
447
+ out_2 = out_2[~np.isnan(out_2)]
448
+ max_diff = np.amax(np.abs(out_1 - out_2))
449
+ self.assertLessEqual(max_diff, 1e-5)
450
+
451
+ def test_attention_outputs(self):
452
+ seq_len = getattr(self.model_tester, "num_latents", None)
453
+
454
+ for model_class in self.all_model_classes:
455
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_model_class(model_class)
456
+ config.return_dict = True
457
+
458
+ inputs_dict["output_attentions"] = True
459
+ inputs_dict["output_hidden_states"] = False
460
+ config.return_dict = True
461
+ model = model_class(config)
462
+ model.to(torch_device)
463
+ model.eval()
464
+ with torch.no_grad():
465
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
466
+ self_attentions = outputs.attentions
467
+ cross_attentions = outputs.cross_attentions
468
+
469
+ # check expected number of attentions depending on model class
470
+ expected_num_self_attentions = self.model_tester.num_blocks * self.model_tester.num_self_attends_per_block
471
+ if model.__class__.__name__ == "PerceiverModel":
472
+ # we expect to have 2 cross-attentions, namely one in the PerceiverEncoder, and one in PerceiverBasicDecoder
473
+ expected_num_cross_attentions = 1
474
+ else:
475
+ # we expect to have 2 cross-attentions, namely one in the PerceiverEncoder, and one in PerceiverBasicDecoder
476
+ expected_num_cross_attentions = 2
477
+ self.assertEqual(len(self_attentions), expected_num_self_attentions)
478
+ self.assertEqual(len(cross_attentions), expected_num_cross_attentions)
479
+
480
+ # check that output_attentions also work using config
481
+ del inputs_dict["output_attentions"]
482
+ config.output_attentions = True
483
+ model = model_class(config)
484
+ model.to(torch_device)
485
+ model.eval()
486
+ with torch.no_grad():
487
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
488
+ self_attentions = outputs.attentions
489
+ cross_attentions = outputs.cross_attentions
490
+ self.assertEqual(len(self_attentions), expected_num_self_attentions)
491
+ self.assertEqual(len(cross_attentions), expected_num_cross_attentions)
492
+
493
+ self.assertListEqual(
494
+ list(self_attentions[0].shape[-3:]),
495
+ [self.model_tester.num_self_attention_heads, seq_len, seq_len],
496
+ )
497
+ out_len = len(outputs)
498
+
499
+ # Check attention is always last and order is fine
500
+ inputs_dict["output_attentions"] = True
501
+ inputs_dict["output_hidden_states"] = True
502
+ model = model_class(config)
503
+ model.to(torch_device)
504
+ model.eval()
505
+ with torch.no_grad():
506
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
507
+
508
+ self.assertEqual(out_len + 1, len(outputs))
509
+
510
+ self_attentions = outputs.attentions
511
+
512
+ self.assertEqual(len(self_attentions), expected_num_self_attentions)
513
+ self.assertListEqual(
514
+ list(self_attentions[0].shape[-3:]),
515
+ [self.model_tester.num_self_attention_heads, seq_len, seq_len],
516
+ )
517
+
518
+ def test_hidden_states_output(self):
519
+ def check_hidden_states_output(inputs_dict, config, model_class):
520
+ model = model_class(config)
521
+ model.to(torch_device)
522
+ model.eval()
523
+
524
+ with torch.no_grad():
525
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
526
+
527
+ hidden_states = outputs.hidden_states
528
+
529
+ expected_num_layers = self.model_tester.num_blocks * self.model_tester.num_self_attends_per_block + 1
530
+ self.assertEqual(len(hidden_states), expected_num_layers)
531
+
532
+ seq_length = self.model_tester.num_latents
533
+
534
+ self.assertListEqual(
535
+ list(hidden_states[0].shape[-2:]),
536
+ [seq_length, self.model_tester.d_latents],
537
+ )
538
+
539
+ for model_class in self.all_model_classes:
540
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_model_class(model_class)
541
+
542
+ inputs_dict["output_hidden_states"] = True
543
+ check_hidden_states_output(inputs_dict, config, model_class)
544
+
545
+ # check that output_hidden_states also work using config
546
+ del inputs_dict["output_hidden_states"]
547
+ config.output_hidden_states = True
548
+
549
+ check_hidden_states_output(inputs_dict, config, model_class)
550
+
551
+ def test_model_outputs_equivalence(self):
552
+ def set_nan_tensor_to_zero(t):
553
+ t[t != t] = 0
554
+ return t
555
+
556
+ def check_equivalence(model, tuple_inputs, dict_inputs, additional_kwargs={}):
557
+ with torch.no_grad():
558
+ tuple_output = model(**tuple_inputs, return_dict=False, **additional_kwargs)
559
+ dict_output = model(**dict_inputs, return_dict=True, **additional_kwargs).to_tuple()
560
+
561
+ def recursive_check(tuple_object, dict_object):
562
+ if isinstance(tuple_object, (List, Tuple)):
563
+ for tuple_iterable_value, dict_iterable_value in zip(tuple_object, dict_object):
564
+ recursive_check(tuple_iterable_value, dict_iterable_value)
565
+ elif isinstance(tuple_object, Dict):
566
+ for tuple_iterable_value, dict_iterable_value in zip(
567
+ tuple_object.values(), dict_object.values()
568
+ ):
569
+ recursive_check(tuple_iterable_value, dict_iterable_value)
570
+ elif tuple_object is None:
571
+ return
572
+ else:
573
+ self.assertTrue(
574
+ torch.allclose(
575
+ set_nan_tensor_to_zero(tuple_object), set_nan_tensor_to_zero(dict_object), atol=1e-5
576
+ ),
577
+ msg=(
578
+ "Tuple and dict output are not equal. Difference:"
579
+ f" {torch.max(torch.abs(tuple_object - dict_object))}. Tuple has `nan`:"
580
+ f" {torch.isnan(tuple_object).any()} and `inf`: {torch.isinf(tuple_object)}. Dict has"
581
+ f" `nan`: {torch.isnan(dict_object).any()} and `inf`: {torch.isinf(dict_object)}."
582
+ ),
583
+ )
584
+
585
+ recursive_check(tuple_output, dict_output)
586
+
587
+ for model_class in self.all_model_classes:
588
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_model_class(model_class)
589
+
590
+ model = model_class(config)
591
+ model.to(torch_device)
592
+ model.eval()
593
+
594
+ tuple_inputs = self._prepare_for_class(inputs_dict, model_class)
595
+ dict_inputs = self._prepare_for_class(inputs_dict, model_class)
596
+ check_equivalence(model, tuple_inputs, dict_inputs)
597
+
598
+ if model_class.__name__ not in ["PerceiverForOpticalFlow", "PerceiverForMultimodalAutoencoding"]:
599
+ # optical flow + multimodal models don't support training for now
600
+ tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
601
+ dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
602
+ check_equivalence(model, tuple_inputs, dict_inputs)
603
+
604
+ tuple_inputs = self._prepare_for_class(inputs_dict, model_class)
605
+ dict_inputs = self._prepare_for_class(inputs_dict, model_class)
606
+
607
+ check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True})
608
+
609
+ tuple_inputs = self._prepare_for_class(inputs_dict, model_class)
610
+ dict_inputs = self._prepare_for_class(inputs_dict, model_class)
611
+ check_equivalence(model, tuple_inputs, dict_inputs, {"output_attentions": True})
612
+
613
+ if model_class.__name__ not in ["PerceiverForOpticalFlow", "PerceiverForMultimodalAutoencoding"]:
614
+ # optical flow + multimodal models don't support training for now
615
+ tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
616
+ dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
617
+ check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True})
618
+
619
+ if model_class.__name__ not in ["PerceiverForOpticalFlow", "PerceiverForMultimodalAutoencoding"]:
620
+ # optical flow + multimodal models don't support training for now
621
+ tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
622
+ dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
623
+ check_equivalence(model, tuple_inputs, dict_inputs, {"output_attentions": True})
624
+
625
+ if model_class.__name__ not in ["PerceiverForOpticalFlow", "PerceiverForMultimodalAutoencoding"]:
626
+ # optical flow + multimodal models don't support training for now
627
+ tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
628
+ dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
629
+ check_equivalence(
630
+ model, tuple_inputs, dict_inputs, {"output_hidden_states": True, "output_attentions": True}
631
+ )
632
+
633
+ def test_retain_grad_hidden_states_attentions(self):
634
+ # no need to test all models as different heads yield the same functionality
635
+ model_class = PerceiverForMaskedLM
636
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_model_class(model_class)
637
+ config.output_hidden_states = True
638
+ config.output_attentions = True
639
+
640
+ model = model_class(config)
641
+ model.to(torch_device)
642
+
643
+ inputs = self._prepare_for_class(inputs_dict, model_class)
644
+
645
+ outputs = model(**inputs)
646
+
647
+ output = outputs[0]
648
+
649
+ # Encoder-only model
650
+ hidden_states = outputs.hidden_states[0]
651
+ attentions = outputs.attentions[0]
652
+
653
+ hidden_states.retain_grad()
654
+ attentions.retain_grad()
655
+
656
+ output.flatten()[0].backward(retain_graph=True)
657
+
658
+ self.assertIsNotNone(hidden_states.grad)
659
+ self.assertIsNotNone(attentions.grad)
660
+
661
+ def test_feed_forward_chunking(self):
662
+ for model_class in self.all_model_classes:
663
+ original_config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_model_class(model_class)
664
+ torch.manual_seed(0)
665
+ config = copy.deepcopy(original_config)
666
+ model = model_class(config)
667
+ model.to(torch_device)
668
+ model.eval()
669
+
670
+ hidden_states_no_chunk = model(**self._prepare_for_class(inputs_dict, model_class))[0]
671
+
672
+ torch.manual_seed(0)
673
+ config.chunk_size_feed_forward = 1
674
+ model = model_class(config)
675
+ model.to(torch_device)
676
+ model.eval()
677
+
678
+ hidden_states_with_chunk = model(**self._prepare_for_class(inputs_dict, model_class))[0]
679
+ if model_class.__name__ == "PerceiverForMultimodalAutoencoding":
680
+ # model outputs a dictionary with logits for each modality
681
+ for modality in hidden_states_no_chunk.keys():
682
+ self.assertTrue(
683
+ torch.allclose(hidden_states_no_chunk[modality], hidden_states_with_chunk[modality], atol=1e-3)
684
+ )
685
+ else:
686
+ self.assertTrue(torch.allclose(hidden_states_no_chunk, hidden_states_with_chunk, atol=1e-3))
687
+
688
+ def test_save_load(self):
689
+ for model_class in self.all_model_classes:
690
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_model_class(model_class)
691
+
692
+ model = model_class(config)
693
+ model.to(torch_device)
694
+ model.eval()
695
+ with torch.no_grad():
696
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
697
+
698
+ if model_class.__name__ == "PerceiverForMultimodalAutoencoding":
699
+ for modality in outputs[0].keys():
700
+ out_2 = outputs[0][modality].cpu().numpy()
701
+ out_2[np.isnan(out_2)] = 0
702
+
703
+ with tempfile.TemporaryDirectory() as tmpdirname:
704
+ model.save_pretrained(tmpdirname)
705
+ model = model_class.from_pretrained(tmpdirname)
706
+ model.to(torch_device)
707
+ with torch.no_grad():
708
+ after_outputs = model(**self._prepare_for_class(inputs_dict, model_class))
709
+
710
+ # Make sure we don't have nans
711
+ out_1 = after_outputs[0][modality].cpu().numpy()
712
+ out_1[np.isnan(out_1)] = 0
713
+ max_diff = np.amax(np.abs(out_1 - out_2))
714
+ self.assertLessEqual(max_diff, 1e-5)
715
+
716
+ else:
717
+ out_2 = outputs[0].cpu().numpy()
718
+ out_2[np.isnan(out_2)] = 0
719
+
720
+ with tempfile.TemporaryDirectory() as tmpdirname:
721
+ model.save_pretrained(tmpdirname)
722
+ model = model_class.from_pretrained(tmpdirname)
723
+ model.to(torch_device)
724
+ with torch.no_grad():
725
+ after_outputs = model(**self._prepare_for_class(inputs_dict, model_class))
726
+
727
+ # Make sure we don't have nans
728
+ out_1 = after_outputs[0].cpu().numpy()
729
+ out_1[np.isnan(out_1)] = 0
730
+ max_diff = np.amax(np.abs(out_1 - out_2))
731
+ self.assertLessEqual(max_diff, 1e-5)
732
+
733
+ def test_correct_missing_keys(self):
734
+ if not self.test_missing_keys:
735
+ self.skipTest(reason="test_missing_keys is set to False")
736
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
737
+
738
+ for model_class in self.all_model_classes:
739
+ # most Perceiver models don't have a typical head like is the case with BERT
740
+ if model_class.__name__ in [
741
+ "PerceiverForOpticalFlow",
742
+ "PerceiverForMultimodalAutoencoding",
743
+ *MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES.values(),
744
+ "PerceiverForImageClassificationLearned",
745
+ "PerceiverForImageClassificationFourier",
746
+ "PerceiverForImageClassificationConvProcessing",
747
+ *MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES.values(),
748
+ ]:
749
+ continue
750
+
751
+ model = model_class(config)
752
+ base_model_prefix = model.base_model_prefix
753
+
754
+ if hasattr(model, base_model_prefix):
755
+ with tempfile.TemporaryDirectory() as temp_dir_name:
756
+ model.base_model.save_pretrained(temp_dir_name)
757
+ model, loading_info = model_class.from_pretrained(temp_dir_name, output_loading_info=True)
758
+ with self.subTest(msg=f"Missing keys for {model.__class__.__name__}"):
759
+ self.assertGreater(len(loading_info["missing_keys"]), 0)
760
+
761
+ def test_problem_types(self):
762
+ problem_types = [
763
+ {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float},
764
+ {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long},
765
+ {"title": "regression", "num_labels": 1, "dtype": torch.float},
766
+ ]
767
+
768
+ for model_class in self.all_model_classes:
769
+ if model_class.__name__ not in MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES.values():
770
+ continue
771
+
772
+ config, inputs, input_mask, _, _ = self.model_tester.prepare_config_and_inputs(model_class=model_class)
773
+ inputs_dict = {"inputs": inputs, "attention_mask": input_mask}
774
+
775
+ for problem_type in problem_types:
776
+ with self.subTest(msg=f"Testing {model_class} with {problem_type['title']}"):
777
+ config.problem_type = problem_type["title"]
778
+ config.num_labels = problem_type["num_labels"]
779
+
780
+ model = model_class(config)
781
+ model.to(torch_device)
782
+ model.train()
783
+
784
+ inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
785
+
786
+ if problem_type["num_labels"] > 1:
787
+ inputs["labels"] = inputs["labels"].unsqueeze(1).repeat(1, problem_type["num_labels"])
788
+
789
+ inputs["labels"] = inputs["labels"].to(problem_type["dtype"])
790
+
791
+ # This tests that we do not trigger the warning form PyTorch "Using a target size that is different
792
+ # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure
793
+ # they have the same size." which is a symptom something in wrong for the regression problem.
794
+ # See https://github.com/huggingface/transformers/issues/11780
795
+ with warnings.catch_warnings(record=True) as warning_list:
796
+ loss = model(**inputs).loss
797
+ for w in warning_list:
798
+ if "Using a target size that is different to the input size" in str(w.message):
799
+ raise ValueError(
800
+ f"Something is going wrong in the regression problem: intercepted {w.message}"
801
+ )
802
+
803
+ loss.backward()
804
+
805
+ @require_torch_multi_gpu
806
+ @unittest.skip(
807
+ reason=(
808
+ "Perceiver does not work with data parallel (DP) because of a bug in PyTorch:"
809
+ " https://github.com/pytorch/pytorch/issues/36035"
810
+ )
811
+ )
812
+ def test_multi_gpu_data_parallel_forward(self):
813
+ pass
814
+
815
+ @unittest.skip(reason="Perceiver models don't have a typical head like is the case with BERT")
816
+ def test_save_load_fast_init_from_base(self):
817
+ pass
818
+
819
+ @unittest.skip(reason="Perceiver models don't have a typical head like is the case with BERT")
820
+ def test_save_load_fast_init_to_base(self):
821
+ pass
822
+
823
+ @unittest.skip(reason="Perceiver doesn't support resize_token_embeddings")
824
+ def test_resize_tokens_embeddings(self):
825
+ pass
826
+
827
+ @unittest.skip(reason="Perceiver doesn't support resize_token_embeddings")
828
+ def test_resize_embeddings_untied(self):
829
+ pass
830
+
831
+ @unittest.skip(reason="Perceiver doesn't support inputs_embeds")
832
+ def test_inputs_embeds(self):
833
+ pass
834
+
835
+ @unittest.skip(reason="Perceiver doesn't support the AutoModel API")
836
+ def test_load_with_mismatched_shapes(self):
837
+ pass
838
+
839
+ @slow
840
+ def test_model_from_pretrained(self):
841
+ model_name = "deepmind/language-perceiver"
842
+ model = PerceiverModel.from_pretrained(model_name)
843
+ self.assertIsNotNone(model)
844
+
845
+
846
+ # We will verify our results on an image of cute cats
847
+ def prepare_img():
848
+ image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
849
+ return image
850
+
851
+
852
+ # Helper functions for optical flow integration test
853
+ def prepare_optical_flow_images():
854
+ dataset = load_dataset("hf-internal-testing/fixtures_sintel", split="test", trust_remote_code=True)
855
+ image1 = Image.open(dataset[0]["file"]).convert("RGB")
856
+ image2 = Image.open(dataset[0]["file"]).convert("RGB")
857
+
858
+ return image1, image2
859
+
860
+
861
+ def normalize(img):
862
+ return img / 255.0 * 2 - 1
863
+
864
+
865
+ def extract_image_patches(x, kernel, stride=1, dilation=1):
866
+ # Do TF 'SAME' Padding
867
+ b, c, h, w = x.shape
868
+ h2 = math.ceil(h / stride)
869
+ w2 = math.ceil(w / stride)
870
+ pad_row = (h2 - 1) * stride + (kernel - 1) * dilation + 1 - h
871
+ pad_col = (w2 - 1) * stride + (kernel - 1) * dilation + 1 - w
872
+ x = torch.nn.functional.pad(x, (pad_row // 2, pad_row - pad_row // 2, pad_col // 2, pad_col - pad_col // 2))
873
+
874
+ # Extract patches
875
+ patches = x.unfold(2, kernel, stride).unfold(3, kernel, stride)
876
+ patches = patches.permute(0, 4, 5, 1, 2, 3).contiguous()
877
+
878
+ return patches.view(b, -1, patches.shape[-2], patches.shape[-1])
879
+
880
+
881
+ @require_torch
882
+ @require_vision
883
+ class PerceiverModelIntegrationTest(unittest.TestCase):
884
+ @slow
885
+ def test_inference_masked_lm(self):
886
+ tokenizer = PerceiverTokenizer.from_pretrained("deepmind/language-perceiver")
887
+ model = PerceiverForMaskedLM.from_pretrained("deepmind/language-perceiver")
888
+ model.to(torch_device)
889
+
890
+ # prepare inputs
891
+ text = "This is an incomplete sentence where some words are missing."
892
+ encoding = tokenizer(text, padding="max_length", return_tensors="pt")
893
+
894
+ # mask " missing.".
895
+ encoding.input_ids[0, 52:61] = tokenizer.mask_token_id
896
+ inputs, input_mask = encoding.input_ids.to(torch_device), encoding.attention_mask.to(torch_device)
897
+
898
+ # forward pass
899
+ with torch.no_grad():
900
+ outputs = model(inputs=inputs, attention_mask=input_mask)
901
+ logits = outputs.logits
902
+
903
+ # verify logits
904
+ expected_shape = torch.Size((1, tokenizer.model_max_length, len(tokenizer)))
905
+ self.assertEqual(logits.shape, expected_shape)
906
+
907
+ expected_slice = torch.tensor(
908
+ [[-10.8609, -10.7651, -10.9187], [-12.1689, -11.9389, -12.1479], [-12.1518, -11.9707, -12.2073]],
909
+ device=torch_device,
910
+ )
911
+
912
+ self.assertTrue(torch.allclose(logits[0, :3, :3], expected_slice, atol=1e-4))
913
+
914
+ expected_greedy_predictions = [38, 115, 111, 121, 121, 111, 116, 109, 52]
915
+ masked_tokens_predictions = logits[0, 52:61].argmax(dim=-1).tolist()
916
+ self.assertListEqual(expected_greedy_predictions, masked_tokens_predictions)
917
+
918
+ @slow
919
+ def test_inference_image_classification(self):
920
+ image_processor = PerceiverImageProcessor()
921
+ model = PerceiverForImageClassificationLearned.from_pretrained("deepmind/vision-perceiver-learned")
922
+ model.to(torch_device)
923
+
924
+ # prepare inputs
925
+ image = prepare_img()
926
+ inputs = image_processor(image, return_tensors="pt").pixel_values.to(torch_device)
927
+ input_mask = None
928
+
929
+ # forward pass
930
+ with torch.no_grad():
931
+ outputs = model(inputs=inputs, attention_mask=input_mask)
932
+ logits = outputs.logits
933
+
934
+ # verify logits
935
+ expected_shape = torch.Size((1, model.config.num_labels))
936
+ self.assertEqual(logits.shape, expected_shape)
937
+
938
+ expected_slice = torch.tensor([-1.1652, -0.1992, -0.7520], device=torch_device)
939
+
940
+ atol = 1e-3 if IS_ROCM_SYSTEM else 1e-4
941
+ self.assertTrue(torch.allclose(logits[0, :3], expected_slice, atol=atol))
942
+
943
+ @slow
944
+ def test_inference_image_classification_fourier(self):
945
+ image_processor = PerceiverImageProcessor()
946
+ model = PerceiverForImageClassificationFourier.from_pretrained("deepmind/vision-perceiver-fourier")
947
+ model.to(torch_device)
948
+
949
+ # prepare inputs
950
+ image = prepare_img()
951
+ inputs = image_processor(image, return_tensors="pt").pixel_values.to(torch_device)
952
+ input_mask = None
953
+
954
+ # forward pass
955
+ with torch.no_grad():
956
+ outputs = model(inputs=inputs, attention_mask=input_mask)
957
+ logits = outputs.logits
958
+
959
+ # verify logits
960
+ expected_shape = torch.Size((1, model.config.num_labels))
961
+ self.assertEqual(logits.shape, expected_shape)
962
+
963
+ expected_slice = torch.tensor([-1.1295, -0.2832, 0.3226], device=torch_device)
964
+
965
+ self.assertTrue(torch.allclose(logits[0, :3], expected_slice, atol=1e-4))
966
+
967
+ @slow
968
+ def test_inference_image_classification_conv(self):
969
+ image_processor = PerceiverImageProcessor()
970
+ model = PerceiverForImageClassificationConvProcessing.from_pretrained("deepmind/vision-perceiver-conv")
971
+ model.to(torch_device)
972
+
973
+ # prepare inputs
974
+ image = prepare_img()
975
+ inputs = image_processor(image, return_tensors="pt").pixel_values.to(torch_device)
976
+ input_mask = None
977
+
978
+ # forward pass
979
+ with torch.no_grad():
980
+ outputs = model(inputs=inputs, attention_mask=input_mask)
981
+ logits = outputs.logits
982
+
983
+ # verify logits
984
+ expected_shape = torch.Size((1, model.config.num_labels))
985
+ self.assertEqual(logits.shape, expected_shape)
986
+
987
+ expected_slice = torch.tensor([-1.1186, 0.0554, 0.0897], device=torch_device)
988
+
989
+ self.assertTrue(torch.allclose(logits[0, :3], expected_slice, atol=1e-4))
990
+
991
+ @slow
992
+ def test_inference_optical_flow(self):
993
+ model = PerceiverForOpticalFlow.from_pretrained("deepmind/optical-flow-perceiver")
994
+ model.to(torch_device)
995
+
996
+ # prepare inputs
997
+ image1, image2 = prepare_optical_flow_images()
998
+ img1 = normalize(np.array(image1))
999
+ img2 = normalize(np.array(image1))
1000
+
1001
+ # stack images
1002
+ img1 = torch.tensor(np.moveaxis(img1, -1, 0))
1003
+ img2 = torch.tensor(np.moveaxis(img2, -1, 0))
1004
+ images = torch.stack([img1, img2], dim=0)
1005
+
1006
+ # extract 3x3 patches
1007
+ patch_size = model.config.train_size
1008
+
1009
+ inputs = images[..., : patch_size[0], : patch_size[1]].unsqueeze(0)
1010
+ batch_size, _, C, H, W = inputs.shape
1011
+ patches = extract_image_patches(inputs.view(batch_size * 2, C, H, W), kernel=3)
1012
+ _, C, H, W = patches.shape
1013
+ patches = patches.view(batch_size, -1, C, H, W).float()
1014
+
1015
+ # forward pass
1016
+ with torch.no_grad():
1017
+ outputs = model(inputs=patches.to(torch_device))
1018
+ logits = outputs.logits
1019
+
1020
+ # verify logits
1021
+ expected_shape = torch.Size((1, 368, 496, 2))
1022
+ self.assertEqual(logits.shape, expected_shape)
1023
+
1024
+ expected_slice = torch.tensor(
1025
+ [
1026
+ [[0.0025, -0.0050], [0.0025, -0.0049], [0.0025, -0.0048]],
1027
+ [[0.0026, -0.0049], [0.0026, -0.0048], [0.0026, -0.0047]],
1028
+ [[0.0026, -0.0049], [0.0026, -0.0048], [0.0026, -0.0046]],
1029
+ ],
1030
+ device=torch_device,
1031
+ )
1032
+
1033
+ self.assertTrue(torch.allclose(logits[0, :3, :3, :3], expected_slice, atol=1e-4))
1034
+
1035
+ @slow
1036
+ def test_inference_interpolate_pos_encoding(self):
1037
+ image_processor = PerceiverImageProcessor(size={"height": 384, "width": 384})
1038
+ model = PerceiverForImageClassificationLearned.from_pretrained("deepmind/vision-perceiver-learned")
1039
+ model.to(torch_device)
1040
+
1041
+ # prepare inputs
1042
+ image = prepare_img()
1043
+ inputs = image_processor(image, return_tensors="pt").pixel_values.to(torch_device)
1044
+ input_mask = None
1045
+
1046
+ # forward pass
1047
+ with torch.no_grad():
1048
+ outputs = model(inputs=inputs, attention_mask=input_mask, interpolate_pos_encoding=True)
1049
+ logits = outputs.logits
1050
+
1051
+ # verify logits
1052
+ expected_shape = torch.Size((1, model.config.num_labels))
1053
+ self.assertEqual(logits.shape, expected_shape)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/perceiver/test_tokenization_perceiver.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2021 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import json
17
+ import os
18
+ import re
19
+ import shutil
20
+ import tempfile
21
+ import unittest
22
+ from typing import Tuple
23
+
24
+ from transformers import AddedToken, BatchEncoding, PerceiverTokenizer
25
+ from transformers.utils import cached_property, is_tf_available, is_torch_available
26
+
27
+ from ...test_tokenization_common import TokenizerTesterMixin
28
+
29
+
30
+ if is_torch_available():
31
+ FRAMEWORK = "pt"
32
+ elif is_tf_available():
33
+ FRAMEWORK = "tf"
34
+ else:
35
+ FRAMEWORK = "jax"
36
+
37
+
38
+ class PerceiverTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
39
+ from_pretrained_id = "deepmind/language-perceiver"
40
+ tokenizer_class = PerceiverTokenizer
41
+ test_rust_tokenizer = False
42
+
43
+ def setUp(self):
44
+ super().setUp()
45
+ tokenizer = PerceiverTokenizer()
46
+ tokenizer.save_pretrained(self.tmpdirname)
47
+
48
+ @cached_property
49
+ def perceiver_tokenizer(self):
50
+ return PerceiverTokenizer.from_pretrained("deepmind/language-perceiver")
51
+
52
+ def get_tokenizer(self, **kwargs) -> PerceiverTokenizer:
53
+ return self.tokenizer_class.from_pretrained(self.tmpdirname, **kwargs)
54
+
55
+ def get_clean_sequence(self, tokenizer, with_prefix_space=False, max_length=20, min_length=5) -> Tuple[str, list]:
56
+ # XXX The default common tokenizer tests assume that every ID is decodable on its own.
57
+ # This assumption is invalid for Perceiver because single bytes might not be
58
+ # valid utf-8 (byte 128 for instance).
59
+ # Here we're overriding the smallest possible method to provide
60
+ # a clean sequence without making the same assumption.
61
+
62
+ toks = []
63
+ for i in range(len(tokenizer)):
64
+ try:
65
+ tok = tokenizer.decode([i], clean_up_tokenization_spaces=False)
66
+ except UnicodeDecodeError:
67
+ pass
68
+ toks.append((i, tok))
69
+
70
+ toks = list(filter(lambda t: re.match(r"^[ a-zA-Z]+$", t[1]), toks))
71
+ toks = list(filter(lambda t: [t[0]] == tokenizer.encode(t[1], add_special_tokens=False), toks))
72
+ if max_length is not None and len(toks) > max_length:
73
+ toks = toks[:max_length]
74
+ if min_length is not None and len(toks) < min_length and len(toks) > 0:
75
+ while len(toks) < min_length:
76
+ toks = toks + toks
77
+ # toks_str = [t[1] for t in toks]
78
+ toks_ids = [t[0] for t in toks]
79
+
80
+ # Ensure consistency
81
+ output_txt = tokenizer.decode(toks_ids, clean_up_tokenization_spaces=False)
82
+ if " " not in output_txt and len(toks_ids) > 1:
83
+ output_txt = (
84
+ tokenizer.decode([toks_ids[0]], clean_up_tokenization_spaces=False)
85
+ + " "
86
+ + tokenizer.decode(toks_ids[1:], clean_up_tokenization_spaces=False)
87
+ )
88
+ if with_prefix_space:
89
+ output_txt = " " + output_txt
90
+ output_ids = tokenizer.encode(output_txt, add_special_tokens=False)
91
+ return output_txt, output_ids
92
+
93
+ def test_multibytes_char(self):
94
+ tokenizer = self.perceiver_tokenizer
95
+ src_text = "Unicode €."
96
+ encoded = tokenizer(src_text)
97
+ encoded_ids = [4, 91, 116, 111, 105, 117, 106, 107, 38, 232, 136, 178, 52, 5]
98
+ self.assertEqual(encoded["input_ids"], encoded_ids)
99
+
100
+ # decoding
101
+ decoded = tokenizer.decode(encoded_ids)
102
+ self.assertEqual(decoded, "[CLS]Unicode €.[SEP]")
103
+
104
+ encoded = tokenizer("e è é ê ë")
105
+ encoded_ids = [4, 107, 38, 201, 174, 38, 201, 175, 38, 201, 176, 38, 201, 177, 5]
106
+ self.assertEqual(encoded["input_ids"], encoded_ids)
107
+ # decoding
108
+ decoded = tokenizer.decode(encoded_ids)
109
+ self.assertEqual(decoded, "[CLS]e è é ê ë[SEP]")
110
+
111
+ # encode/decode, but with `encode` instead of `__call__`
112
+ self.assertEqual(tokenizer.decode(tokenizer.encode("e è é ê ë")), "[CLS]e è é ê ë[SEP]")
113
+
114
+ def test_prepare_batch_integration(self):
115
+ tokenizer = self.perceiver_tokenizer
116
+ src_text = ["A long paragraph for summarization.", "Another paragraph for summarization."]
117
+ expected_src_tokens = [4, 71, 38, 114, 117, 116, 109, 38, 118, 103, 120, 103, 109, 120, 103, 118, 110, 38, 108, 117, 120, 38, 121, 123, 115, 115, 103, 120, 111, 128, 103, 122, 111, 117, 116, 52, 5, 0] # fmt: skip
118
+ batch = tokenizer(src_text, padding=True, return_tensors=FRAMEWORK)
119
+ self.assertIsInstance(batch, BatchEncoding)
120
+
121
+ if FRAMEWORK != "jax":
122
+ result = list(batch.input_ids.numpy()[0])
123
+ else:
124
+ result = list(batch.input_ids.tolist()[0])
125
+
126
+ self.assertListEqual(expected_src_tokens, result)
127
+
128
+ self.assertEqual((2, 38), batch.input_ids.shape)
129
+ self.assertEqual((2, 38), batch.attention_mask.shape)
130
+
131
+ def test_empty_target_text(self):
132
+ tokenizer = self.perceiver_tokenizer
133
+ src_text = ["A long paragraph for summarization.", "Another paragraph for summarization."]
134
+ batch = tokenizer(src_text, padding=True, return_tensors=FRAMEWORK)
135
+ # check if input_ids are returned and no decoder_input_ids
136
+ self.assertIn("input_ids", batch)
137
+ self.assertIn("attention_mask", batch)
138
+ self.assertNotIn("decoder_input_ids", batch)
139
+ self.assertNotIn("decoder_attention_mask", batch)
140
+
141
+ def test_max_length_integration(self):
142
+ tokenizer = self.perceiver_tokenizer
143
+ tgt_text = [
144
+ "Summary of the text.",
145
+ "Another summary.",
146
+ ]
147
+ targets = tokenizer(
148
+ text_target=tgt_text, max_length=32, padding="max_length", truncation=True, return_tensors=FRAMEWORK
149
+ )
150
+ self.assertEqual(32, targets["input_ids"].shape[1])
151
+
152
+ # cannot use default save_and_load_tokenizer test method because tokenizer has no vocab
153
+ def test_save_and_load_tokenizer(self):
154
+ # safety check on max_len default value so we are sure the test works
155
+ tokenizers = self.get_tokenizers()
156
+ for tokenizer in tokenizers:
157
+ with self.subTest(f"{tokenizer.__class__.__name__}"):
158
+ self.assertNotEqual(tokenizer.model_max_length, 42)
159
+
160
+ # Now let's start the test
161
+ tokenizers = self.get_tokenizers()
162
+ for tokenizer in tokenizers:
163
+ with self.subTest(f"{tokenizer.__class__.__name__}"):
164
+ # Isolate this from the other tests because we save additional tokens/etc
165
+ tmpdirname = tempfile.mkdtemp()
166
+
167
+ sample_text = " He is very happy, UNwant\u00e9d,running"
168
+ before_tokens = tokenizer.encode(sample_text, add_special_tokens=False)
169
+ tokenizer.save_pretrained(tmpdirname)
170
+
171
+ after_tokenizer = tokenizer.__class__.from_pretrained(tmpdirname)
172
+ after_tokens = after_tokenizer.encode(sample_text, add_special_tokens=False)
173
+ self.assertListEqual(before_tokens, after_tokens)
174
+
175
+ shutil.rmtree(tmpdirname)
176
+
177
+ tokenizers = self.get_tokenizers(model_max_length=42)
178
+ for tokenizer in tokenizers:
179
+ with self.subTest(f"{tokenizer.__class__.__name__}"):
180
+ # Isolate this from the other tests because we save additional tokens/etc
181
+ tmpdirname = tempfile.mkdtemp()
182
+
183
+ sample_text = " He is very happy, UNwant\u00e9d,running"
184
+ tokenizer.add_tokens(["bim", "bambam"])
185
+ additional_special_tokens = tokenizer.additional_special_tokens
186
+ additional_special_tokens.append("new_additional_special_token")
187
+ tokenizer.add_special_tokens(
188
+ {"additional_special_tokens": additional_special_tokens}, replace_additional_special_tokens=False
189
+ )
190
+ before_tokens = tokenizer.encode(sample_text, add_special_tokens=False)
191
+ tokenizer.save_pretrained(tmpdirname)
192
+
193
+ after_tokenizer = tokenizer.__class__.from_pretrained(tmpdirname)
194
+ after_tokens = after_tokenizer.encode(sample_text, add_special_tokens=False)
195
+ self.assertListEqual(before_tokens, after_tokens)
196
+ self.assertIn("new_additional_special_token", after_tokenizer.additional_special_tokens)
197
+ self.assertEqual(after_tokenizer.model_max_length, 42)
198
+
199
+ tokenizer = tokenizer.__class__.from_pretrained(tmpdirname, model_max_length=43)
200
+ self.assertEqual(tokenizer.model_max_length, 43)
201
+
202
+ shutil.rmtree(tmpdirname)
203
+
204
+ # There is a conflict between the default value of extra_ids and adding a new special token through additional_special_tokens
205
+ # We need to add the extra_ids in the list of the arg additional_special_tokens
206
+ def test_special_tokens_initialization_with_non_empty_additional_special_tokens(self):
207
+ tokenizer_list = []
208
+ if self.test_slow_tokenizer:
209
+ tokenizer_list.append((self.tokenizer_class, self.get_tokenizer()))
210
+
211
+ if self.test_rust_tokenizer:
212
+ tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer()))
213
+
214
+ for tokenizer_class, tokenizer_utils in tokenizer_list:
215
+ with tempfile.TemporaryDirectory() as tmp_dir:
216
+ tokenizer_utils.save_pretrained(tmp_dir)
217
+
218
+ with open(os.path.join(tmp_dir, "special_tokens_map.json"), encoding="utf-8") as json_file:
219
+ special_tokens_map = json.load(json_file)
220
+
221
+ with open(os.path.join(tmp_dir, "tokenizer_config.json"), encoding="utf-8") as json_file:
222
+ tokenizer_config = json.load(json_file)
223
+
224
+ added_tokens_extra_ids = [f"<extra_id_{i}>" for i in range(125)]
225
+
226
+ special_tokens_map["additional_special_tokens"] = added_tokens_extra_ids + [
227
+ "an_additional_special_token"
228
+ ]
229
+ tokenizer_config["additional_special_tokens"] = added_tokens_extra_ids + [
230
+ "an_additional_special_token"
231
+ ]
232
+
233
+ with open(os.path.join(tmp_dir, "special_tokens_map.json"), "w", encoding="utf-8") as outfile:
234
+ json.dump(special_tokens_map, outfile)
235
+ with open(os.path.join(tmp_dir, "tokenizer_config.json"), "w", encoding="utf-8") as outfile:
236
+ json.dump(tokenizer_config, outfile)
237
+
238
+ # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes
239
+ # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and
240
+ # "special_tokens_map.json" files
241
+ tokenizer_without_change_in_init = tokenizer_class.from_pretrained(
242
+ tmp_dir,
243
+ )
244
+ self.assertIn(
245
+ "an_additional_special_token", tokenizer_without_change_in_init.additional_special_tokens
246
+ )
247
+ self.assertEqual(
248
+ ["an_additional_special_token"],
249
+ tokenizer_without_change_in_init.convert_ids_to_tokens(
250
+ tokenizer_without_change_in_init.convert_tokens_to_ids(["an_additional_special_token"])
251
+ ),
252
+ )
253
+
254
+ # Now we test that we can change the value of additional_special_tokens in the from_pretrained
255
+ new_added_tokens = added_tokens_extra_ids + [AddedToken("a_new_additional_special_token", lstrip=True)]
256
+ tokenizer = tokenizer_class.from_pretrained(
257
+ tmp_dir,
258
+ additional_special_tokens=new_added_tokens,
259
+ )
260
+
261
+ self.assertIn("a_new_additional_special_token", tokenizer.additional_special_tokens)
262
+ self.assertEqual(
263
+ ["a_new_additional_special_token"],
264
+ tokenizer.convert_ids_to_tokens(
265
+ tokenizer.convert_tokens_to_ids(["a_new_additional_special_token"])
266
+ ),
267
+ )
268
+
269
+ def test_decode_invalid_byte_id(self):
270
+ tokenizer = self.perceiver_tokenizer
271
+ self.assertEqual(tokenizer.decode([178]), "�")
272
+
273
+ @unittest.skip(reason="tokenizer does not have vocabulary")
274
+ def test_get_vocab(self):
275
+ pass
276
+
277
+ @unittest.skip(reason="inputs cannot be pretokenized")
278
+ def test_pretokenized_inputs(self):
279
+ # inputs cannot be pretokenized since ids depend on whole input string and not just on single characters
280
+ pass
281
+
282
+ @unittest.skip(reason="vocab does not exist")
283
+ def test_conversion_reversible(self):
284
+ pass
285
+
286
+ def test_convert_tokens_to_string_format(self):
287
+ # The default common tokenizer tests uses invalid tokens for Perceiver that can only accept one-character
288
+ # strings and special added tokens as tokens
289
+ tokenizers = self.get_tokenizers(fast=True, do_lower_case=True)
290
+ for tokenizer in tokenizers:
291
+ with self.subTest(f"{tokenizer.__class__.__name__}"):
292
+ tokens = ["[CLS]", "t", "h", "i", "s", " ", "i", "s", " ", "a", " ", "t", "e", "s", "t", "[SEP]"]
293
+ string = tokenizer.convert_tokens_to_string(tokens)
294
+
295
+ self.assertIsInstance(string, str)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/persimmon/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/persimmon/test_modeling_persimmon.py ADDED
@@ -0,0 +1,519 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Persimmon model."""
16
+
17
+ import gc
18
+ import unittest
19
+
20
+ from parameterized import parameterized
21
+
22
+ from transformers import PersimmonConfig, is_torch_available, set_seed
23
+ from transformers.testing_utils import (
24
+ backend_empty_cache,
25
+ require_bitsandbytes,
26
+ require_torch,
27
+ require_torch_accelerator,
28
+ require_torch_fp16,
29
+ slow,
30
+ torch_device,
31
+ )
32
+
33
+ from ...generation.test_utils import GenerationTesterMixin
34
+ from ...test_configuration_common import ConfigTester
35
+ from ...test_modeling_common import ModelTesterMixin, ids_tensor
36
+ from ...test_pipeline_mixin import PipelineTesterMixin
37
+
38
+
39
+ if is_torch_available():
40
+ import torch
41
+
42
+ from transformers import (
43
+ AutoTokenizer,
44
+ PersimmonForCausalLM,
45
+ PersimmonForSequenceClassification,
46
+ PersimmonForTokenClassification,
47
+ PersimmonModel,
48
+ )
49
+ from transformers.models.persimmon.modeling_persimmon import PersimmonRotaryEmbedding
50
+
51
+
52
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTester with Llama->Persimmon
53
+ class PersimmonModelTester:
54
+ def __init__(
55
+ self,
56
+ parent,
57
+ batch_size=13,
58
+ seq_length=7,
59
+ is_training=True,
60
+ use_input_mask=True,
61
+ use_token_type_ids=False,
62
+ use_labels=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
+ pad_token_id=0,
78
+ scope=None,
79
+ ):
80
+ self.parent = parent
81
+ self.batch_size = batch_size
82
+ self.seq_length = seq_length
83
+ self.is_training = is_training
84
+ self.use_input_mask = use_input_mask
85
+ self.use_token_type_ids = use_token_type_ids
86
+ self.use_labels = use_labels
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.pad_token_id = pad_token_id
102
+ self.scope = scope
103
+
104
+ def prepare_config_and_inputs(self):
105
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
106
+
107
+ input_mask = None
108
+ if self.use_input_mask:
109
+ input_mask = torch.tril(torch.ones_like(input_ids).to(torch_device))
110
+
111
+ token_type_ids = None
112
+ if self.use_token_type_ids:
113
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
114
+
115
+ sequence_labels = None
116
+ token_labels = None
117
+ choice_labels = None
118
+ if self.use_labels:
119
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
120
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
121
+ choice_labels = ids_tensor([self.batch_size], self.num_choices)
122
+
123
+ config = self.get_config()
124
+
125
+ return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
126
+
127
+ def get_config(self):
128
+ return PersimmonConfig(
129
+ vocab_size=self.vocab_size,
130
+ hidden_size=self.hidden_size,
131
+ num_hidden_layers=self.num_hidden_layers,
132
+ num_attention_heads=self.num_attention_heads,
133
+ intermediate_size=self.intermediate_size,
134
+ hidden_act=self.hidden_act,
135
+ hidden_dropout_prob=self.hidden_dropout_prob,
136
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
137
+ max_position_embeddings=self.max_position_embeddings,
138
+ type_vocab_size=self.type_vocab_size,
139
+ is_decoder=False,
140
+ initializer_range=self.initializer_range,
141
+ pad_token_id=self.pad_token_id,
142
+ )
143
+
144
+ def create_and_check_model(
145
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
146
+ ):
147
+ model = PersimmonModel(config=config)
148
+ model.to(torch_device)
149
+ model.eval()
150
+ result = model(input_ids, attention_mask=input_mask)
151
+ result = model(input_ids)
152
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
153
+
154
+ def create_and_check_model_as_decoder(
155
+ self,
156
+ config,
157
+ input_ids,
158
+ token_type_ids,
159
+ input_mask,
160
+ sequence_labels,
161
+ token_labels,
162
+ choice_labels,
163
+ encoder_hidden_states,
164
+ encoder_attention_mask,
165
+ ):
166
+ config.add_cross_attention = True
167
+ model = PersimmonModel(config)
168
+ model.to(torch_device)
169
+ model.eval()
170
+ result = model(
171
+ input_ids,
172
+ attention_mask=input_mask,
173
+ encoder_hidden_states=encoder_hidden_states,
174
+ encoder_attention_mask=encoder_attention_mask,
175
+ )
176
+ result = model(
177
+ input_ids,
178
+ attention_mask=input_mask,
179
+ encoder_hidden_states=encoder_hidden_states,
180
+ )
181
+ result = model(input_ids, attention_mask=input_mask)
182
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
183
+
184
+ def create_and_check_for_causal_lm(
185
+ self,
186
+ config,
187
+ input_ids,
188
+ token_type_ids,
189
+ input_mask,
190
+ sequence_labels,
191
+ token_labels,
192
+ choice_labels,
193
+ encoder_hidden_states,
194
+ encoder_attention_mask,
195
+ ):
196
+ model = PersimmonForCausalLM(config=config)
197
+ model.to(torch_device)
198
+ model.eval()
199
+ result = model(input_ids, attention_mask=input_mask, labels=token_labels)
200
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
201
+
202
+ def create_and_check_decoder_model_past_large_inputs(
203
+ self,
204
+ config,
205
+ input_ids,
206
+ token_type_ids,
207
+ input_mask,
208
+ sequence_labels,
209
+ token_labels,
210
+ choice_labels,
211
+ encoder_hidden_states,
212
+ encoder_attention_mask,
213
+ ):
214
+ config.is_decoder = True
215
+ config.add_cross_attention = True
216
+ model = PersimmonForCausalLM(config=config)
217
+ model.to(torch_device)
218
+ model.eval()
219
+
220
+ # first forward pass
221
+ outputs = model(
222
+ input_ids,
223
+ attention_mask=input_mask,
224
+ encoder_hidden_states=encoder_hidden_states,
225
+ encoder_attention_mask=encoder_attention_mask,
226
+ use_cache=True,
227
+ )
228
+ past_key_values = outputs.past_key_values
229
+
230
+ # create hypothetical multiple next token and extent to next_input_ids
231
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
232
+ next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
233
+
234
+ # append to next input_ids and
235
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
236
+ next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
237
+
238
+ output_from_no_past = model(
239
+ next_input_ids,
240
+ attention_mask=next_attention_mask,
241
+ encoder_hidden_states=encoder_hidden_states,
242
+ encoder_attention_mask=encoder_attention_mask,
243
+ output_hidden_states=True,
244
+ )["hidden_states"][0]
245
+ output_from_past = model(
246
+ next_tokens,
247
+ attention_mask=next_attention_mask,
248
+ encoder_hidden_states=encoder_hidden_states,
249
+ encoder_attention_mask=encoder_attention_mask,
250
+ past_key_values=past_key_values,
251
+ output_hidden_states=True,
252
+ )["hidden_states"][0]
253
+
254
+ # select random slice
255
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
256
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
257
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
258
+
259
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
260
+
261
+ # test that outputs are equal for slice
262
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
263
+
264
+ def prepare_config_and_inputs_for_common(self):
265
+ config_and_inputs = self.prepare_config_and_inputs()
266
+ (
267
+ config,
268
+ input_ids,
269
+ token_type_ids,
270
+ input_mask,
271
+ sequence_labels,
272
+ token_labels,
273
+ choice_labels,
274
+ ) = config_and_inputs
275
+ inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
276
+ return config, inputs_dict
277
+
278
+
279
+ @require_torch
280
+ class PersimmonModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
281
+ all_model_classes = (
282
+ (PersimmonModel, PersimmonForCausalLM, PersimmonForSequenceClassification, PersimmonForTokenClassification)
283
+ if is_torch_available()
284
+ else ()
285
+ )
286
+ pipeline_model_mapping = (
287
+ {
288
+ "feature-extraction": PersimmonModel,
289
+ "text-classification": PersimmonForSequenceClassification,
290
+ "token-classification": PersimmonForTokenClassification,
291
+ # TODO (ydshieh): check why these two fail. Fix them or skip them in a better way.
292
+ # "text-generation": PersimmonForCausalLM,
293
+ # "zero-shot": PersimmonForSequenceClassification,
294
+ }
295
+ if is_torch_available()
296
+ else {}
297
+ )
298
+
299
+ all_generative_model_classes = (PersimmonForCausalLM,) if is_torch_available() else ()
300
+ test_headmasking = False
301
+ test_pruning = False
302
+
303
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.setUp with Llama->Persimmon
304
+ def setUp(self):
305
+ self.model_tester = PersimmonModelTester(self)
306
+ self.config_tester = ConfigTester(self, config_class=PersimmonConfig, hidden_size=37)
307
+
308
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_config
309
+ def test_config(self):
310
+ self.config_tester.run_common_tests()
311
+
312
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_model
313
+ def test_model(self):
314
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
315
+ self.model_tester.create_and_check_model(*config_and_inputs)
316
+
317
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_model_various_embeddings
318
+ def test_model_various_embeddings(self):
319
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
320
+ for type in ["absolute", "relative_key", "relative_key_query"]:
321
+ config_and_inputs[0].position_embedding_type = type
322
+ self.model_tester.create_and_check_model(*config_and_inputs)
323
+
324
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_llama_sequence_classification_model with Llama->Persimmon,llama->persimmon
325
+ def test_persimmon_sequence_classification_model(self):
326
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
327
+ config.num_labels = 3
328
+ input_ids = input_dict["input_ids"]
329
+ attention_mask = input_ids.ne(1).to(torch_device)
330
+ sequence_labels = ids_tensor([self.model_tester.batch_size], self.model_tester.type_sequence_label_size)
331
+ model = PersimmonForSequenceClassification(config)
332
+ model.to(torch_device)
333
+ model.eval()
334
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
335
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
336
+
337
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_llama_sequence_classification_model_for_single_label with Llama->Persimmon,llama->persimmon
338
+ def test_persimmon_sequence_classification_model_for_single_label(self):
339
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
340
+ config.num_labels = 3
341
+ config.problem_type = "single_label_classification"
342
+ input_ids = input_dict["input_ids"]
343
+ attention_mask = input_ids.ne(1).to(torch_device)
344
+ sequence_labels = ids_tensor([self.model_tester.batch_size], self.model_tester.type_sequence_label_size)
345
+ model = PersimmonForSequenceClassification(config)
346
+ model.to(torch_device)
347
+ model.eval()
348
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
349
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
350
+
351
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_llama_sequence_classification_model_for_multi_label with Llama->Persimmon,llama->persimmon
352
+ def test_persimmon_sequence_classification_model_for_multi_label(self):
353
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
354
+ config.num_labels = 3
355
+ config.problem_type = "multi_label_classification"
356
+ input_ids = input_dict["input_ids"]
357
+ attention_mask = input_ids.ne(1).to(torch_device)
358
+ sequence_labels = ids_tensor(
359
+ [self.model_tester.batch_size, config.num_labels], self.model_tester.type_sequence_label_size
360
+ ).to(torch.float)
361
+ model = PersimmonForSequenceClassification(config)
362
+ model.to(torch_device)
363
+ model.eval()
364
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
365
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
366
+
367
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_llama_token_classification_model with Llama->Persimmon,llama->persimmon
368
+ def test_persimmon_token_classification_model(self):
369
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
370
+ config.num_labels = 3
371
+ input_ids = input_dict["input_ids"]
372
+ attention_mask = input_ids.ne(1).to(torch_device)
373
+ token_labels = ids_tensor([self.model_tester.batch_size, self.model_tester.seq_length], config.num_labels)
374
+ model = PersimmonForTokenClassification(config=config)
375
+ model.to(torch_device)
376
+ model.eval()
377
+ result = model(input_ids, attention_mask=attention_mask, labels=token_labels)
378
+ self.assertEqual(
379
+ result.logits.shape,
380
+ (self.model_tester.batch_size, self.model_tester.seq_length, self.model_tester.num_labels),
381
+ )
382
+
383
+ @unittest.skip(reason="Persimmon buffers include complex numbers, which breaks this test")
384
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_save_load_fast_init_from_base
385
+ def test_save_load_fast_init_from_base(self):
386
+ pass
387
+
388
+ @parameterized.expand([("linear",), ("dynamic",)])
389
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_model_rope_scaling_from_config with Llama->Persimmon
390
+ def test_model_rope_scaling_from_config(self, scaling_type):
391
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
392
+ short_input = ids_tensor([1, 10], config.vocab_size)
393
+ long_input = ids_tensor([1, int(config.max_position_embeddings * 1.5)], config.vocab_size)
394
+
395
+ set_seed(42) # Fixed seed at init time so the two models get the same random weights
396
+ original_model = PersimmonModel(config)
397
+ original_model.to(torch_device)
398
+ original_model.eval()
399
+ original_short_output = original_model(short_input).last_hidden_state
400
+ original_long_output = original_model(long_input).last_hidden_state
401
+
402
+ set_seed(42) # Fixed seed at init time so the two models get the same random weights
403
+ config.rope_scaling = {"type": scaling_type, "factor": 10.0}
404
+ scaled_model = PersimmonModel(config)
405
+ scaled_model.to(torch_device)
406
+ scaled_model.eval()
407
+ scaled_short_output = scaled_model(short_input).last_hidden_state
408
+ scaled_long_output = scaled_model(long_input).last_hidden_state
409
+
410
+ # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
411
+ # maximum sequence length, so the outputs for the short input should match.
412
+ if scaling_type == "dynamic":
413
+ self.assertTrue(torch.allclose(original_short_output, scaled_short_output, atol=1e-5))
414
+ else:
415
+ self.assertFalse(torch.allclose(original_short_output, scaled_short_output, atol=1e-5))
416
+
417
+ # The output should be different for long inputs
418
+ self.assertFalse(torch.allclose(original_long_output, scaled_long_output, atol=1e-5))
419
+
420
+ # Copied from tests.models.gpt_neox.test_modeling_gpt_neox.GPTNeoXModelTest.test_model_rope_scaling with GPTNeoX->Persimmon
421
+ def test_model_rope_scaling(self):
422
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
423
+ scaling_factor = 10
424
+ short_input_length = 10
425
+ long_input_length = int(config.max_position_embeddings * 1.5)
426
+
427
+ # Inputs
428
+ x = torch.randn(1, dtype=torch.float32, device=torch_device) # used exlusively to get the dtype and the device
429
+ position_ids_short = torch.arange(short_input_length, dtype=torch.long, device=torch_device)
430
+ position_ids_short = position_ids_short.unsqueeze(0)
431
+ position_ids_long = torch.arange(long_input_length, dtype=torch.long, device=torch_device)
432
+ position_ids_long = position_ids_long.unsqueeze(0)
433
+
434
+ # Sanity check original RoPE
435
+ original_rope = PersimmonRotaryEmbedding(config).to(torch_device)
436
+ original_cos_short, original_sin_short = original_rope(x, position_ids_short)
437
+ original_cos_long, original_sin_long = original_rope(x, position_ids_long)
438
+ torch.testing.assert_close(original_cos_short, original_cos_long[:, :short_input_length, :])
439
+ torch.testing.assert_close(original_sin_short, original_sin_long[:, :short_input_length, :])
440
+
441
+ # Sanity check linear RoPE scaling
442
+ # New position "x" should match original position with index "x/scaling_factor"
443
+ config.rope_scaling = {"type": "linear", "factor": scaling_factor}
444
+ linear_scaling_rope = PersimmonRotaryEmbedding(config).to(torch_device)
445
+ linear_cos_short, linear_sin_short = linear_scaling_rope(x, position_ids_short)
446
+ linear_cos_long, linear_sin_long = linear_scaling_rope(x, position_ids_long)
447
+ torch.testing.assert_close(linear_cos_short, linear_cos_long[:, :short_input_length, :])
448
+ torch.testing.assert_close(linear_sin_short, linear_sin_long[:, :short_input_length, :])
449
+ for new_position in range(0, long_input_length, scaling_factor):
450
+ original_position = int(new_position // scaling_factor)
451
+ torch.testing.assert_close(linear_cos_long[:, new_position, :], original_cos_long[:, original_position, :])
452
+ torch.testing.assert_close(linear_sin_long[:, new_position, :], original_sin_long[:, original_position, :])
453
+
454
+ # Sanity check Dynamic NTK RoPE scaling
455
+ # Scaling should only be observed after a long input is fed. We can observe that the frequencies increase
456
+ # with scaling_factor (or that `inv_freq` decreases)
457
+ config.rope_scaling = {"type": "dynamic", "factor": scaling_factor}
458
+ ntk_scaling_rope = PersimmonRotaryEmbedding(config).to(torch_device)
459
+ ntk_cos_short, ntk_sin_short = ntk_scaling_rope(x, position_ids_short)
460
+ ntk_cos_long, ntk_sin_long = ntk_scaling_rope(x, position_ids_long)
461
+ torch.testing.assert_close(ntk_cos_short, original_cos_short)
462
+ torch.testing.assert_close(ntk_sin_short, original_sin_short)
463
+ with self.assertRaises(AssertionError):
464
+ torch.testing.assert_close(ntk_cos_long, original_cos_long)
465
+ with self.assertRaises(AssertionError):
466
+ torch.testing.assert_close(ntk_sin_long, original_sin_long)
467
+ self.assertTrue((ntk_scaling_rope.inv_freq <= original_rope.inv_freq).all())
468
+
469
+
470
+ @require_torch
471
+ class PersimmonIntegrationTest(unittest.TestCase):
472
+ @slow
473
+ @require_torch_accelerator
474
+ @require_bitsandbytes
475
+ def test_model_8b_chat_logits(self):
476
+ input_ids = [1, 306, 4658, 278, 6593, 310, 2834, 338]
477
+ model = PersimmonForCausalLM.from_pretrained(
478
+ "adept/persimmon-8b-chat", load_in_8bit=True, device_map={"": 0}, torch_dtype=torch.float16
479
+ )
480
+ out = model(torch.tensor([input_ids], device=torch_device)).logits.float()
481
+
482
+ EXPECTED_MEAN = torch.tensor(
483
+ [[-11.4726, -11.1495, -11.2694, -11.2223, -10.9452, -11.0663, -11.0031, -11.1028]]
484
+ )
485
+ # change dtype to `torch.float32` before calling `mean` to avoid `nan` values
486
+ torch.testing.assert_close(out.cpu().to(torch.float32).mean(-1), EXPECTED_MEAN, atol=1e-4, rtol=1e-4)
487
+ # fmt: off
488
+ EXPECTED_SLICE = torch.tensor(
489
+ [-16.9062, -16.9062, -16.9062, -16.9062, -16.8906, -16.9062, -16.9531, -16.9062, -16.9062, -16.9062, -16.9531, -16.9062, -16.9531, -16.9062, -16.9062, -16.9062, -16.9062, -16.9062, -16.9531, -16.9062, -16.9062, -16.9062, -16.9062, -16.9062, -16.9062, -16.9531, -16.9062, -16.9531, -16.9062, -16.9062],
490
+ dtype=torch.float16
491
+ )
492
+ # fmt: on
493
+ torch.testing.assert_close(out.cpu()[0, 0, :30], EXPECTED_SLICE, atol=1e-5, rtol=1e-5)
494
+
495
+ backend_empty_cache(torch_device)
496
+ del model
497
+ gc.collect()
498
+
499
+ @slow
500
+ @require_torch_accelerator
501
+ @require_torch_fp16
502
+ @require_bitsandbytes
503
+ def test_model_8b_chat_greedy_generation(self):
504
+ EXPECTED_TEXT_COMPLETION = """human: Simply put, the theory of relativity states that?\n\nadept: The theory of relativity states that the laws of physics are the same for all observers, regardless of their relative motion."""
505
+ prompt = "human: Simply put, the theory of relativity states that?\n\nadept:"
506
+ tokenizer = AutoTokenizer.from_pretrained("adept/persimmon-8b-chat", use_fast=False)
507
+ input_ids = tokenizer.encode(prompt, return_tensors="pt").to(torch_device)
508
+ model = PersimmonForCausalLM.from_pretrained(
509
+ "adept/persimmon-8b-chat", load_in_8bit=True, device_map={"": 0}, torch_dtype=torch.float16
510
+ )
511
+
512
+ # greedy generation outputs
513
+ generated_ids = model.generate(input_ids, max_new_tokens=64)
514
+ text = tokenizer.decode(generated_ids[0], skip_special_tokens=True)
515
+ self.assertEqual(EXPECTED_TEXT_COMPLETION, text)
516
+
517
+ backend_empty_cache(torch_device)
518
+ del model
519
+ gc.collect()
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/phi/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/phi/test_modeling_phi.py ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 Microsoft 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
+
16
+ """Testing suite for the PyTorch Phi model."""
17
+
18
+ import unittest
19
+
20
+ from parameterized import parameterized
21
+
22
+ from transformers import PhiConfig, is_torch_available, set_seed
23
+ from transformers.testing_utils import (
24
+ require_torch,
25
+ slow,
26
+ torch_device,
27
+ )
28
+
29
+ from ...generation.test_utils import GenerationTesterMixin
30
+ from ...test_configuration_common import ConfigTester
31
+ from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
32
+ from ...test_pipeline_mixin import PipelineTesterMixin
33
+
34
+
35
+ if is_torch_available():
36
+ import torch
37
+
38
+ from transformers import (
39
+ AutoTokenizer,
40
+ PhiForCausalLM,
41
+ PhiForSequenceClassification,
42
+ PhiForTokenClassification,
43
+ PhiModel,
44
+ )
45
+ from transformers.models.phi.modeling_phi import PhiRotaryEmbedding
46
+
47
+
48
+ class PhiModelTester:
49
+ def __init__(
50
+ self,
51
+ parent,
52
+ batch_size=13,
53
+ seq_length=7,
54
+ is_training=True,
55
+ use_input_mask=True,
56
+ use_token_type_ids=False,
57
+ use_labels=True,
58
+ vocab_size=99,
59
+ hidden_size=32,
60
+ num_hidden_layers=2,
61
+ num_attention_heads=4,
62
+ intermediate_size=37,
63
+ hidden_act="gelu",
64
+ hidden_dropout_prob=0.1,
65
+ attention_probs_dropout_prob=0.1,
66
+ max_position_embeddings=512,
67
+ type_vocab_size=16,
68
+ type_sequence_label_size=2,
69
+ initializer_range=0.02,
70
+ num_labels=3,
71
+ num_choices=4,
72
+ pad_token_id=0,
73
+ scope=None,
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.hidden_size = hidden_size
84
+ self.num_hidden_layers = num_hidden_layers
85
+ self.num_attention_heads = num_attention_heads
86
+ self.intermediate_size = intermediate_size
87
+ self.hidden_act = hidden_act
88
+ self.hidden_dropout_prob = hidden_dropout_prob
89
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
90
+ self.max_position_embeddings = max_position_embeddings
91
+ self.type_vocab_size = type_vocab_size
92
+ self.type_sequence_label_size = type_sequence_label_size
93
+ self.initializer_range = initializer_range
94
+ self.num_labels = num_labels
95
+ self.num_choices = num_choices
96
+ self.pad_token_id = pad_token_id
97
+ self.scope = scope
98
+
99
+ def prepare_config_and_inputs(self):
100
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
101
+
102
+ input_mask = None
103
+ if self.use_input_mask:
104
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
105
+
106
+ token_type_ids = None
107
+ if self.use_token_type_ids:
108
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
109
+
110
+ sequence_labels = None
111
+ token_labels = None
112
+ choice_labels = None
113
+ if self.use_labels:
114
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
115
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
116
+ choice_labels = ids_tensor([self.batch_size], self.num_choices)
117
+
118
+ config = self.get_config()
119
+
120
+ return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
121
+
122
+ def get_config(self):
123
+ return PhiConfig(
124
+ vocab_size=self.vocab_size,
125
+ hidden_size=self.hidden_size,
126
+ num_hidden_layers=self.num_hidden_layers,
127
+ num_attention_heads=self.num_attention_heads,
128
+ intermediate_size=self.intermediate_size,
129
+ hidden_act=self.hidden_act,
130
+ hidden_dropout_prob=self.hidden_dropout_prob,
131
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
132
+ max_position_embeddings=self.max_position_embeddings,
133
+ type_vocab_size=self.type_vocab_size,
134
+ is_decoder=False,
135
+ initializer_range=self.initializer_range,
136
+ pad_token_id=self.pad_token_id,
137
+ )
138
+
139
+ def create_and_check_model(
140
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
141
+ ):
142
+ model = PhiModel(config=config)
143
+ model.to(torch_device)
144
+ model.eval()
145
+ result = model(input_ids, attention_mask=input_mask)
146
+ result = model(input_ids)
147
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
148
+
149
+ def create_and_check_model_as_decoder(
150
+ self,
151
+ config,
152
+ input_ids,
153
+ token_type_ids,
154
+ input_mask,
155
+ sequence_labels,
156
+ token_labels,
157
+ choice_labels,
158
+ encoder_hidden_states,
159
+ encoder_attention_mask,
160
+ ):
161
+ config.add_cross_attention = True
162
+ model = PhiModel(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
+ token_type_ids,
184
+ input_mask,
185
+ sequence_labels,
186
+ token_labels,
187
+ choice_labels,
188
+ encoder_hidden_states,
189
+ encoder_attention_mask,
190
+ ):
191
+ model = PhiForCausalLM(config=config)
192
+ model.to(torch_device)
193
+ model.eval()
194
+ result = model(input_ids, attention_mask=input_mask, labels=token_labels)
195
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
196
+
197
+ def create_and_check_decoder_model_past_large_inputs(
198
+ self,
199
+ config,
200
+ input_ids,
201
+ token_type_ids,
202
+ input_mask,
203
+ sequence_labels,
204
+ token_labels,
205
+ choice_labels,
206
+ encoder_hidden_states,
207
+ encoder_attention_mask,
208
+ ):
209
+ config.is_decoder = True
210
+ config.add_cross_attention = True
211
+ model = PhiForCausalLM(config=config)
212
+ model.to(torch_device)
213
+ model.eval()
214
+
215
+ # first forward pass
216
+ outputs = model(
217
+ input_ids,
218
+ attention_mask=input_mask,
219
+ encoder_hidden_states=encoder_hidden_states,
220
+ encoder_attention_mask=encoder_attention_mask,
221
+ use_cache=True,
222
+ )
223
+ past_key_values = outputs.past_key_values
224
+
225
+ # create hypothetical multiple next token and extent to next_input_ids
226
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
227
+ next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
228
+
229
+ # append to next input_ids and
230
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
231
+ next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
232
+
233
+ output_from_no_past = model(
234
+ next_input_ids,
235
+ attention_mask=next_attention_mask,
236
+ encoder_hidden_states=encoder_hidden_states,
237
+ encoder_attention_mask=encoder_attention_mask,
238
+ output_hidden_states=True,
239
+ )["hidden_states"][0]
240
+ output_from_past = model(
241
+ next_tokens,
242
+ attention_mask=next_attention_mask,
243
+ encoder_hidden_states=encoder_hidden_states,
244
+ encoder_attention_mask=encoder_attention_mask,
245
+ past_key_values=past_key_values,
246
+ output_hidden_states=True,
247
+ )["hidden_states"][0]
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[:, -3:, random_slice_idx].detach()
252
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
253
+
254
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
255
+
256
+ # test that outputs are equal for slice
257
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
258
+
259
+ def prepare_config_and_inputs_for_common(self):
260
+ config_and_inputs = self.prepare_config_and_inputs()
261
+ (
262
+ config,
263
+ input_ids,
264
+ token_type_ids,
265
+ input_mask,
266
+ sequence_labels,
267
+ token_labels,
268
+ choice_labels,
269
+ ) = config_and_inputs
270
+ inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
271
+ return config, inputs_dict
272
+
273
+
274
+ @require_torch
275
+ class PhiModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
276
+ all_model_classes = (
277
+ (PhiModel, PhiForCausalLM, PhiForSequenceClassification, PhiForTokenClassification)
278
+ if is_torch_available()
279
+ else ()
280
+ )
281
+ all_generative_model_classes = (PhiForCausalLM,) if is_torch_available() else ()
282
+ pipeline_model_mapping = (
283
+ {
284
+ "feature-extraction": PhiModel,
285
+ "text-classification": PhiForSequenceClassification,
286
+ "text-generation": PhiForCausalLM,
287
+ "token-classification": PhiForTokenClassification,
288
+ "zero-shot": PhiForSequenceClassification,
289
+ }
290
+ if is_torch_available()
291
+ else {}
292
+ )
293
+
294
+ test_headmasking = False
295
+ test_pruning = False
296
+
297
+ # TODO (ydshieh): Check this. See https://app.circleci.com/pipelines/github/huggingface/transformers/79292/workflows/fa2ba644-8953-44a6-8f67-ccd69ca6a476/jobs/1012905
298
+ def is_pipeline_test_to_skip(
299
+ self,
300
+ pipeline_test_case_name,
301
+ config_class,
302
+ model_architecture,
303
+ tokenizer_name,
304
+ image_processor_name,
305
+ feature_extractor_name,
306
+ processor_name,
307
+ ):
308
+ return True
309
+
310
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.setUp with Llama->Phi
311
+ def setUp(self):
312
+ self.model_tester = PhiModelTester(self)
313
+ self.config_tester = ConfigTester(self, config_class=PhiConfig, hidden_size=37)
314
+
315
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_config
316
+ def test_config(self):
317
+ self.config_tester.run_common_tests()
318
+
319
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_model
320
+ def test_model(self):
321
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
322
+ self.model_tester.create_and_check_model(*config_and_inputs)
323
+
324
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_llama_sequence_classification_model with Llama->Phi,llama->phi
325
+ def test_phi_sequence_classification_model(self):
326
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
327
+ config.num_labels = 3
328
+ input_ids = input_dict["input_ids"]
329
+ attention_mask = input_ids.ne(1).to(torch_device)
330
+ sequence_labels = ids_tensor([self.model_tester.batch_size], self.model_tester.type_sequence_label_size)
331
+ model = PhiForSequenceClassification(config)
332
+ model.to(torch_device)
333
+ model.eval()
334
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
335
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
336
+
337
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_llama_sequence_classification_model_for_single_label with Llama->Phi,llama->phi
338
+ def test_phi_sequence_classification_model_for_single_label(self):
339
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
340
+ config.num_labels = 3
341
+ config.problem_type = "single_label_classification"
342
+ input_ids = input_dict["input_ids"]
343
+ attention_mask = input_ids.ne(1).to(torch_device)
344
+ sequence_labels = ids_tensor([self.model_tester.batch_size], self.model_tester.type_sequence_label_size)
345
+ model = PhiForSequenceClassification(config)
346
+ model.to(torch_device)
347
+ model.eval()
348
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
349
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
350
+
351
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_llama_sequence_classification_model_for_multi_label with Llama->Phi,llama->phi
352
+ def test_phi_sequence_classification_model_for_multi_label(self):
353
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
354
+ config.num_labels = 3
355
+ config.problem_type = "multi_label_classification"
356
+ input_ids = input_dict["input_ids"]
357
+ attention_mask = input_ids.ne(1).to(torch_device)
358
+ sequence_labels = ids_tensor(
359
+ [self.model_tester.batch_size, config.num_labels], self.model_tester.type_sequence_label_size
360
+ ).to(torch.float)
361
+ model = PhiForSequenceClassification(config)
362
+ model.to(torch_device)
363
+ model.eval()
364
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
365
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
366
+
367
+ @parameterized.expand([("linear",), ("dynamic",)])
368
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_model_rope_scaling_from_config with Llama->Phi
369
+ def test_model_rope_scaling_from_config(self, scaling_type):
370
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
371
+ short_input = ids_tensor([1, 10], config.vocab_size)
372
+ long_input = ids_tensor([1, int(config.max_position_embeddings * 1.5)], config.vocab_size)
373
+
374
+ set_seed(42) # Fixed seed at init time so the two models get the same random weights
375
+ original_model = PhiModel(config)
376
+ original_model.to(torch_device)
377
+ original_model.eval()
378
+ original_short_output = original_model(short_input).last_hidden_state
379
+ original_long_output = original_model(long_input).last_hidden_state
380
+
381
+ set_seed(42) # Fixed seed at init time so the two models get the same random weights
382
+ config.rope_scaling = {"type": scaling_type, "factor": 10.0}
383
+ scaled_model = PhiModel(config)
384
+ scaled_model.to(torch_device)
385
+ scaled_model.eval()
386
+ scaled_short_output = scaled_model(short_input).last_hidden_state
387
+ scaled_long_output = scaled_model(long_input).last_hidden_state
388
+
389
+ # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
390
+ # maximum sequence length, so the outputs for the short input should match.
391
+ if scaling_type == "dynamic":
392
+ self.assertTrue(torch.allclose(original_short_output, scaled_short_output, atol=1e-5))
393
+ else:
394
+ self.assertFalse(torch.allclose(original_short_output, scaled_short_output, atol=1e-5))
395
+
396
+ # The output should be different for long inputs
397
+ self.assertFalse(torch.allclose(original_long_output, scaled_long_output, atol=1e-5))
398
+
399
+ # Copied from tests.models.gpt_neox.test_modeling_gpt_neox.GPTNeoXModelTest.test_model_rope_scaling with GPTNeoX->Phi
400
+ def test_model_rope_scaling(self):
401
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
402
+ scaling_factor = 10
403
+ short_input_length = 10
404
+ long_input_length = int(config.max_position_embeddings * 1.5)
405
+
406
+ # Inputs
407
+ x = torch.randn(1, dtype=torch.float32, device=torch_device) # used exlusively to get the dtype and the device
408
+ position_ids_short = torch.arange(short_input_length, dtype=torch.long, device=torch_device)
409
+ position_ids_short = position_ids_short.unsqueeze(0)
410
+ position_ids_long = torch.arange(long_input_length, dtype=torch.long, device=torch_device)
411
+ position_ids_long = position_ids_long.unsqueeze(0)
412
+
413
+ # Sanity check original RoPE
414
+ original_rope = PhiRotaryEmbedding(config).to(torch_device)
415
+ original_cos_short, original_sin_short = original_rope(x, position_ids_short)
416
+ original_cos_long, original_sin_long = original_rope(x, position_ids_long)
417
+ torch.testing.assert_close(original_cos_short, original_cos_long[:, :short_input_length, :])
418
+ torch.testing.assert_close(original_sin_short, original_sin_long[:, :short_input_length, :])
419
+
420
+ # Sanity check linear RoPE scaling
421
+ # New position "x" should match original position with index "x/scaling_factor"
422
+ config.rope_scaling = {"type": "linear", "factor": scaling_factor}
423
+ linear_scaling_rope = PhiRotaryEmbedding(config).to(torch_device)
424
+ linear_cos_short, linear_sin_short = linear_scaling_rope(x, position_ids_short)
425
+ linear_cos_long, linear_sin_long = linear_scaling_rope(x, position_ids_long)
426
+ torch.testing.assert_close(linear_cos_short, linear_cos_long[:, :short_input_length, :])
427
+ torch.testing.assert_close(linear_sin_short, linear_sin_long[:, :short_input_length, :])
428
+ for new_position in range(0, long_input_length, scaling_factor):
429
+ original_position = int(new_position // scaling_factor)
430
+ torch.testing.assert_close(linear_cos_long[:, new_position, :], original_cos_long[:, original_position, :])
431
+ torch.testing.assert_close(linear_sin_long[:, new_position, :], original_sin_long[:, original_position, :])
432
+
433
+ # Sanity check Dynamic NTK RoPE scaling
434
+ # Scaling should only be observed after a long input is fed. We can observe that the frequencies increase
435
+ # with scaling_factor (or that `inv_freq` decreases)
436
+ config.rope_scaling = {"type": "dynamic", "factor": scaling_factor}
437
+ ntk_scaling_rope = PhiRotaryEmbedding(config).to(torch_device)
438
+ ntk_cos_short, ntk_sin_short = ntk_scaling_rope(x, position_ids_short)
439
+ ntk_cos_long, ntk_sin_long = ntk_scaling_rope(x, position_ids_long)
440
+ torch.testing.assert_close(ntk_cos_short, original_cos_short)
441
+ torch.testing.assert_close(ntk_sin_short, original_sin_short)
442
+ with self.assertRaises(AssertionError):
443
+ torch.testing.assert_close(ntk_cos_long, original_cos_long)
444
+ with self.assertRaises(AssertionError):
445
+ torch.testing.assert_close(ntk_sin_long, original_sin_long)
446
+ self.assertTrue((ntk_scaling_rope.inv_freq <= original_rope.inv_freq).all())
447
+
448
+
449
+ @slow
450
+ @require_torch
451
+ class PhiIntegrationTest(unittest.TestCase):
452
+ def test_model_phi_1_logits(self):
453
+ input_ids = {
454
+ "input_ids": torch.tensor(
455
+ [[1212, 318, 281, 1672, 2643, 290, 428, 318, 257, 1332]], dtype=torch.long, device=torch_device
456
+ )
457
+ }
458
+
459
+ model = PhiForCausalLM.from_pretrained("microsoft/phi-1").to(torch_device)
460
+ model.eval()
461
+
462
+ output = model(**input_ids).logits
463
+
464
+ EXPECTED_OUTPUT = torch.tensor([[2.2671, 6.7684, -2.0107, -1.2440, -1.5335, -2.3828, 6.9186, 6.4245, 3.1548, 0.9998, 0.0760, 4.4653, 4.9857, 4.2956, 1.2308, -1.4178, 0.1361, 0.5191, -0.5699, -2.2201, -3.0750, -3.9600, -4.5936, -3.7394, -2.7777, 6.1874, -0.4148, -1.5684, -0.5967, 0.2395], [1.7004, 4.0383, 0.0546, 0.4530, -0.3619, -0.9021, 1.8355, 1.3587, 1.2406, 2.5775, -0.8834, 5.1910, 4.2565, 4.1406, 3.0752, -0.9099, 1.1595, 0.0264, 0.3243, -1.1803, -1.3945, -2.1406, -3.9939, -1.4438, -2.9546, 3.9204, 1.0851, -1.0598, -1.7819, -0.4827]]).to(torch_device) # fmt: skip
465
+
466
+ self.assertTrue(torch.allclose(EXPECTED_OUTPUT, output[0, :2, :30], atol=1e-4, rtol=1e-4))
467
+
468
+ def test_model_phi_1_5_logits(self):
469
+ input_ids = {
470
+ "input_ids": torch.tensor(
471
+ [[1212, 318, 281, 1672, 2643, 290, 428, 318, 257, 1332]], dtype=torch.long, device=torch_device
472
+ )
473
+ }
474
+
475
+ model = PhiForCausalLM.from_pretrained("microsoft/phi-1_5").to(torch_device)
476
+ model.eval()
477
+
478
+ output = model(**input_ids).logits
479
+
480
+ EXPECTED_OUTPUT = torch.tensor([[12.2922, 13.3507, 8.6963, 9.1355, 9.3502, 9.2667, 14.2027, 13.1363, 13.5446, 11.1337, 9.9279, 16.7195, 13.0768, 14.9141, 11.9965, 8.0233, 10.3129, 10.6118, 10.0204, 9.3827, 8.8344, 8.2806, 8.0153, 8.0540, 7.0964, 16.5743, 11.1256, 9.6987, 11.4770, 10.5440], [12.3323, 14.6050, 8.9986, 8.1580, 9.5654, 6.6728, 12.5966, 12.6662, 12.2784, 11.7522, 8.2039, 16.3102, 11.2203, 13.6088, 12.0125, 9.1021, 9.8216, 10.0987, 9.0926, 8.4260, 8.8009, 7.6547, 6.8075, 7.7881, 7.4501, 15.7451, 10.5053, 8.3129, 10.0027, 9.2612]]).to(torch_device) # fmt: skip
481
+
482
+ self.assertTrue(torch.allclose(EXPECTED_OUTPUT, output[0, :2, :30], atol=1e-4, rtol=1e-4))
483
+
484
+ def test_model_phi_2_logits(self):
485
+ input_ids = {
486
+ "input_ids": torch.tensor(
487
+ [[1212, 318, 281, 1672, 2643, 290, 428, 318, 257, 1332]], dtype=torch.long, device=torch_device
488
+ )
489
+ }
490
+
491
+ model = PhiForCausalLM.from_pretrained("microsoft/phi-2").to(torch_device)
492
+ model.eval()
493
+
494
+ output = model(**input_ids).logits
495
+
496
+ EXPECTED_OUTPUT = torch.tensor([[6.4830, 6.1644, 3.4055, 2.2848, 5.4654, 2.8360, 5.5975, 5.5391, 7.3101, 4.2498, 2.5913, 10.3885, 6.4359, 8.7982, 5.6534, 0.5150, 2.7498, 3.1930, 2.4334, 1.7781, 1.5613, 1.3067, 0.8291, 0.5633, 0.6522, 9.8191, 5.5771, 2.7987, 4.2845, 3.7030], [6.0642, 7.8242, 3.4634, 1.9259, 4.3169, 2.0913, 6.0446, 3.6804, 6.6736, 4.0727, 2.1791, 11.4139, 5.6795, 7.5652, 6.2039, 2.7174, 4.3266, 3.6930, 2.8058, 2.6721, 2.3047, 2.0848, 2.0972, 2.0441, 1.3160, 9.2085, 4.5557, 3.0296, 2.6045, 2.4059]]).to(torch_device) # fmt: skip
497
+
498
+ self.assertTrue(torch.allclose(EXPECTED_OUTPUT, output[0, :2, :30], atol=1e-3, rtol=1e-3))
499
+
500
+ def test_phi_2_generation(self):
501
+ model = PhiForCausalLM.from_pretrained("microsoft/phi-2")
502
+ tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-2")
503
+
504
+ inputs = tokenizer(
505
+ "Can you help me write a formal email to a potential business partner proposing a joint venture?",
506
+ return_tensors="pt",
507
+ return_attention_mask=False,
508
+ )
509
+
510
+ outputs = model.generate(**inputs, max_new_tokens=30)
511
+ output_text = tokenizer.batch_decode(outputs)
512
+
513
+ EXPECTED_OUTPUT = [
514
+ "Can you help me write a formal email to a potential business partner proposing a joint venture?\nInput: Company A: ABC Inc.\nCompany B: XYZ Ltd.\nJoint Venture: A new online platform for e-commerce"
515
+ ]
516
+
517
+ self.assertListEqual(output_text, EXPECTED_OUTPUT)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/phi3/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/phi3/test_modeling_phi3.py ADDED
@@ -0,0 +1,707 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft 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
+
16
+ """Testing suite for the PyTorch Phi-3 model."""
17
+
18
+ import unittest
19
+ from typing import List
20
+
21
+ from parameterized import parameterized
22
+
23
+ from transformers import Phi3Config, StaticCache, is_torch_available, set_seed
24
+ from transformers.testing_utils import (
25
+ require_torch,
26
+ slow,
27
+ torch_device,
28
+ )
29
+
30
+ from ...generation.test_utils import GenerationTesterMixin
31
+ from ...test_configuration_common import ConfigTester
32
+ from ...test_modeling_common import ModelTesterMixin, ids_tensor
33
+ from ...test_pipeline_mixin import PipelineTesterMixin
34
+
35
+
36
+ if is_torch_available():
37
+ import torch
38
+
39
+ from transformers import (
40
+ AutoTokenizer,
41
+ Phi3ForCausalLM,
42
+ Phi3ForSequenceClassification,
43
+ Phi3ForTokenClassification,
44
+ Phi3Model,
45
+ )
46
+
47
+ end_of_text_token = 32000
48
+
49
+ class Phi3MiniWithStaticCache(torch.nn.Module):
50
+ def __init__(self, model: Phi3ForCausalLM, batch_size: int, max_seq_len: int):
51
+ super().__init__()
52
+ self.model = model
53
+ self.cache = StaticCache(
54
+ config=model.config,
55
+ batch_size=batch_size,
56
+ max_cache_len=max_seq_len,
57
+ device=self.model.device,
58
+ dtype=self.model.dtype,
59
+ )
60
+
61
+ def forward(
62
+ self,
63
+ input_ids: torch.LongTensor = None,
64
+ ) -> torch.FloatTensor:
65
+ return self.model.forward(
66
+ input_ids=input_ids,
67
+ use_cache=True,
68
+ return_dict=True,
69
+ past_key_values=self.cache,
70
+ ).logits
71
+
72
+ @staticmethod
73
+ def generate(model: Phi3ForCausalLM, prompt_tokens: torch.LongTensor, max_seq_len: int) -> List[int]:
74
+ model = Phi3MiniWithStaticCache(model, 1, max_seq_len + prompt_tokens.shape[-1])
75
+
76
+ response_tokens = []
77
+
78
+ for input_pos in range(prompt_tokens.shape[-1]):
79
+ result = model.forward(
80
+ input_ids=prompt_tokens[:, input_pos : input_pos + 1],
81
+ )
82
+ response_tokens.append(prompt_tokens[0][input_pos].item())
83
+
84
+ current_token = torch.argmax(result[:, -1, :], dim=-1).item()
85
+ response_tokens.append(current_token)
86
+
87
+ while current_token != end_of_text_token and len(response_tokens) < max_seq_len:
88
+ result = model.forward(
89
+ input_ids=torch.tensor([[current_token]], dtype=torch.long),
90
+ )
91
+ current_token = torch.argmax(result[:, -1, :], dim=-1).item()
92
+ response_tokens.append(current_token)
93
+
94
+ return response_tokens
95
+
96
+
97
+ class Phi3ModelTester:
98
+ def __init__(
99
+ self,
100
+ parent,
101
+ batch_size=13,
102
+ seq_length=7,
103
+ is_training=True,
104
+ use_input_mask=True,
105
+ use_token_type_ids=False,
106
+ use_labels=True,
107
+ vocab_size=99,
108
+ hidden_size=32,
109
+ num_hidden_layers=2,
110
+ num_attention_heads=4,
111
+ intermediate_size=37,
112
+ hidden_act="gelu",
113
+ hidden_dropout_prob=0.1,
114
+ attention_probs_dropout_prob=0.1,
115
+ max_position_embeddings=512,
116
+ type_vocab_size=16,
117
+ type_sequence_label_size=2,
118
+ initializer_range=0.02,
119
+ num_labels=3,
120
+ num_choices=4,
121
+ pad_token_id=0,
122
+ scope=None,
123
+ ):
124
+ self.parent = parent
125
+ self.batch_size = batch_size
126
+ self.seq_length = seq_length
127
+ self.is_training = is_training
128
+ self.use_input_mask = use_input_mask
129
+ self.use_token_type_ids = use_token_type_ids
130
+ self.use_labels = use_labels
131
+ self.vocab_size = vocab_size
132
+ self.hidden_size = hidden_size
133
+ self.num_hidden_layers = num_hidden_layers
134
+ self.num_attention_heads = num_attention_heads
135
+ self.intermediate_size = intermediate_size
136
+ self.hidden_act = hidden_act
137
+ self.hidden_dropout_prob = hidden_dropout_prob
138
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
139
+ self.max_position_embeddings = max_position_embeddings
140
+ self.type_vocab_size = type_vocab_size
141
+ self.type_sequence_label_size = type_sequence_label_size
142
+ self.initializer_range = initializer_range
143
+ self.num_labels = num_labels
144
+ self.num_choices = num_choices
145
+ self.pad_token_id = pad_token_id
146
+ self.scope = scope
147
+
148
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTester.prepare_config_and_inputs
149
+ def prepare_config_and_inputs(self):
150
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
151
+
152
+ input_mask = None
153
+ if self.use_input_mask:
154
+ input_mask = torch.tril(torch.ones_like(input_ids).to(torch_device))
155
+
156
+ token_type_ids = None
157
+ if self.use_token_type_ids:
158
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
159
+
160
+ sequence_labels = None
161
+ token_labels = None
162
+ choice_labels = None
163
+ if self.use_labels:
164
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
165
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
166
+ choice_labels = ids_tensor([self.batch_size], self.num_choices)
167
+
168
+ config = self.get_config()
169
+
170
+ return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
171
+
172
+ def get_config(self):
173
+ return Phi3Config(
174
+ vocab_size=self.vocab_size,
175
+ hidden_size=self.hidden_size,
176
+ num_hidden_layers=self.num_hidden_layers,
177
+ num_attention_heads=self.num_attention_heads,
178
+ intermediate_size=self.intermediate_size,
179
+ hidden_act=self.hidden_act,
180
+ hidden_dropout_prob=self.hidden_dropout_prob,
181
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
182
+ max_position_embeddings=self.max_position_embeddings,
183
+ type_vocab_size=self.type_vocab_size,
184
+ is_decoder=False,
185
+ initializer_range=self.initializer_range,
186
+ pad_token_id=self.pad_token_id,
187
+ )
188
+
189
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTester.create_and_check_model with Llama->Phi3
190
+ def create_and_check_model(
191
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
192
+ ):
193
+ model = Phi3Model(config=config)
194
+ model.to(torch_device)
195
+ model.eval()
196
+ result = model(input_ids, attention_mask=input_mask)
197
+ result = model(input_ids)
198
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
199
+
200
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTester.create_and_check_model_as_decoder with Llama->Phi3
201
+ def create_and_check_model_as_decoder(
202
+ self,
203
+ config,
204
+ input_ids,
205
+ token_type_ids,
206
+ input_mask,
207
+ sequence_labels,
208
+ token_labels,
209
+ choice_labels,
210
+ encoder_hidden_states,
211
+ encoder_attention_mask,
212
+ ):
213
+ config.add_cross_attention = True
214
+ model = Phi3Model(config)
215
+ model.to(torch_device)
216
+ model.eval()
217
+ result = model(
218
+ input_ids,
219
+ attention_mask=input_mask,
220
+ encoder_hidden_states=encoder_hidden_states,
221
+ encoder_attention_mask=encoder_attention_mask,
222
+ )
223
+ result = model(
224
+ input_ids,
225
+ attention_mask=input_mask,
226
+ encoder_hidden_states=encoder_hidden_states,
227
+ )
228
+ result = model(input_ids, attention_mask=input_mask)
229
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
230
+
231
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTester.create_and_check_for_causal_lm with Llama->Phi3
232
+ def create_and_check_for_causal_lm(
233
+ self,
234
+ config,
235
+ input_ids,
236
+ token_type_ids,
237
+ input_mask,
238
+ sequence_labels,
239
+ token_labels,
240
+ choice_labels,
241
+ encoder_hidden_states,
242
+ encoder_attention_mask,
243
+ ):
244
+ model = Phi3ForCausalLM(config=config)
245
+ model.to(torch_device)
246
+ model.eval()
247
+ result = model(input_ids, attention_mask=input_mask, labels=token_labels)
248
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
249
+
250
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTester.create_and_check_decoder_model_past_large_inputs with Llama->Phi3
251
+ def create_and_check_decoder_model_past_large_inputs(
252
+ self,
253
+ config,
254
+ input_ids,
255
+ token_type_ids,
256
+ input_mask,
257
+ sequence_labels,
258
+ token_labels,
259
+ choice_labels,
260
+ encoder_hidden_states,
261
+ encoder_attention_mask,
262
+ ):
263
+ config.is_decoder = True
264
+ config.add_cross_attention = True
265
+ model = Phi3ForCausalLM(config=config)
266
+ model.to(torch_device)
267
+ model.eval()
268
+
269
+ # first forward pass
270
+ outputs = model(
271
+ input_ids,
272
+ attention_mask=input_mask,
273
+ encoder_hidden_states=encoder_hidden_states,
274
+ encoder_attention_mask=encoder_attention_mask,
275
+ use_cache=True,
276
+ )
277
+ past_key_values = outputs.past_key_values
278
+
279
+ # create hypothetical multiple next token and extent to next_input_ids
280
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
281
+ next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
282
+
283
+ # append to next input_ids and
284
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
285
+ next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
286
+
287
+ output_from_no_past = model(
288
+ next_input_ids,
289
+ attention_mask=next_attention_mask,
290
+ encoder_hidden_states=encoder_hidden_states,
291
+ encoder_attention_mask=encoder_attention_mask,
292
+ output_hidden_states=True,
293
+ )["hidden_states"][0]
294
+ output_from_past = model(
295
+ next_tokens,
296
+ attention_mask=next_attention_mask,
297
+ encoder_hidden_states=encoder_hidden_states,
298
+ encoder_attention_mask=encoder_attention_mask,
299
+ past_key_values=past_key_values,
300
+ output_hidden_states=True,
301
+ )["hidden_states"][0]
302
+
303
+ # select random slice
304
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
305
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
306
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
307
+
308
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
309
+
310
+ # test that outputs are equal for slice
311
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
312
+
313
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTester.prepare_config_and_inputs_for_common
314
+ def prepare_config_and_inputs_for_common(self):
315
+ config_and_inputs = self.prepare_config_and_inputs()
316
+ (
317
+ config,
318
+ input_ids,
319
+ token_type_ids,
320
+ input_mask,
321
+ sequence_labels,
322
+ token_labels,
323
+ choice_labels,
324
+ ) = config_and_inputs
325
+ inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
326
+ return config, inputs_dict
327
+
328
+
329
+ @require_torch
330
+ class Phi3ModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
331
+ all_model_classes = (
332
+ (Phi3Model, Phi3ForCausalLM, Phi3ForSequenceClassification, Phi3ForTokenClassification)
333
+ if is_torch_available()
334
+ else ()
335
+ )
336
+ all_generative_model_classes = (Phi3ForCausalLM,) if is_torch_available() else ()
337
+ pipeline_model_mapping = (
338
+ {
339
+ "feature-extraction": Phi3Model,
340
+ "text-classification": Phi3ForSequenceClassification,
341
+ "text-generation": Phi3ForCausalLM,
342
+ "token-classification": Phi3ForTokenClassification,
343
+ "zero-shot": Phi3ForSequenceClassification,
344
+ }
345
+ if is_torch_available()
346
+ else {}
347
+ )
348
+
349
+ test_headmasking = False
350
+ test_pruning = False
351
+
352
+ # TODO (ydshieh): Check this. See https://app.circleci.com/pipelines/github/huggingface/transformers/79292/workflows/fa2ba644-8953-44a6-8f67-ccd69ca6a476/jobs/1012905
353
+ def is_pipeline_test_to_skip(
354
+ self,
355
+ pipeline_test_case_name,
356
+ config_class,
357
+ model_architecture,
358
+ tokenizer_name,
359
+ image_processor_name,
360
+ feature_extractor_name,
361
+ processor_name,
362
+ ):
363
+ return True
364
+
365
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.setUp with Llama->Phi3
366
+ def setUp(self):
367
+ self.model_tester = Phi3ModelTester(self)
368
+ self.config_tester = ConfigTester(self, config_class=Phi3Config, hidden_size=37)
369
+
370
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_config
371
+ def test_config(self):
372
+ self.config_tester.run_common_tests()
373
+
374
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_model
375
+ def test_model(self):
376
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
377
+ self.model_tester.create_and_check_model(*config_and_inputs)
378
+
379
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_llama_sequence_classification_model with Llama->Phi3,llama->phi3
380
+ def test_phi3_sequence_classification_model(self):
381
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
382
+ config.num_labels = 3
383
+ input_ids = input_dict["input_ids"]
384
+ attention_mask = input_ids.ne(1).to(torch_device)
385
+ sequence_labels = ids_tensor([self.model_tester.batch_size], self.model_tester.type_sequence_label_size)
386
+ model = Phi3ForSequenceClassification(config)
387
+ model.to(torch_device)
388
+ model.eval()
389
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
390
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
391
+
392
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_llama_sequence_classification_model_for_single_label with Llama->Phi3,llama->phi3
393
+ def test_phi3_sequence_classification_model_for_single_label(self):
394
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
395
+ config.num_labels = 3
396
+ config.problem_type = "single_label_classification"
397
+ input_ids = input_dict["input_ids"]
398
+ attention_mask = input_ids.ne(1).to(torch_device)
399
+ sequence_labels = ids_tensor([self.model_tester.batch_size], self.model_tester.type_sequence_label_size)
400
+ model = Phi3ForSequenceClassification(config)
401
+ model.to(torch_device)
402
+ model.eval()
403
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
404
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
405
+
406
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_llama_sequence_classification_model_for_multi_label with Llama->Phi3,llama->phi3
407
+ def test_phi3_sequence_classification_model_for_multi_label(self):
408
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
409
+ config.num_labels = 3
410
+ config.problem_type = "multi_label_classification"
411
+ input_ids = input_dict["input_ids"]
412
+ attention_mask = input_ids.ne(1).to(torch_device)
413
+ sequence_labels = ids_tensor(
414
+ [self.model_tester.batch_size, config.num_labels], self.model_tester.type_sequence_label_size
415
+ ).to(torch.float)
416
+ model = Phi3ForSequenceClassification(config)
417
+ model.to(torch_device)
418
+ model.eval()
419
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
420
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
421
+
422
+ @parameterized.expand([("longrope",)])
423
+ def test_model_rope_scaling_from_config(self, scaling_type):
424
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
425
+ short_input = ids_tensor([1, 10], config.vocab_size)
426
+ long_input = ids_tensor([1, int(config.max_position_embeddings * 1.5)], config.vocab_size)
427
+
428
+ set_seed(42) # Fixed seed at init time so the two models get the same random weights
429
+ original_model = Phi3Model(config)
430
+ original_model.to(torch_device)
431
+ original_model.eval()
432
+ original_short_output = original_model(short_input).last_hidden_state
433
+ original_long_output = original_model(long_input).last_hidden_state
434
+
435
+ set_seed(42) # Fixed seed at init time so the two models get the same random weights
436
+ n_factors = config.hidden_size // config.num_attention_heads // 2
437
+ config.rope_scaling = {
438
+ "type": scaling_type,
439
+ "short_factor": [5.0 for _ in range(n_factors)],
440
+ "long_factor": [5.0 for _ in range(n_factors)],
441
+ }
442
+ scaled_model = Phi3Model(config)
443
+ scaled_model.to(torch_device)
444
+ scaled_model.eval()
445
+ scaled_short_output = scaled_model(short_input).last_hidden_state
446
+ scaled_long_output = scaled_model(long_input).last_hidden_state
447
+
448
+ # Scaling changes the RoPE embeddings, both for the short and long outputs
449
+ self.assertFalse(torch.allclose(original_short_output, scaled_short_output, atol=1e-5))
450
+ self.assertFalse(torch.allclose(original_long_output, scaled_long_output, atol=1e-5))
451
+
452
+ @parameterized.expand([("longrope",)])
453
+ def test_model_rope_scaling_short_long_factor(self, scaling_type):
454
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
455
+ n_factors = config.hidden_size // config.num_key_value_heads // 2
456
+ config.rope_scaling = {
457
+ "type": scaling_type,
458
+ "short_factor": [3.0 for _ in range(n_factors)],
459
+ "long_factor": [5.0 for _ in range(n_factors)],
460
+ }
461
+ input_tensor = ids_tensor([1, 4090], config.vocab_size)
462
+ model = Phi3ForCausalLM(config)
463
+ model.to(torch_device)
464
+ model.eval()
465
+ generation_args_short = {
466
+ "max_length": config.original_max_position_embeddings,
467
+ "temperature": 0.0,
468
+ "use_cache": True,
469
+ "do_sample": False,
470
+ "return_dict_in_generate": True,
471
+ }
472
+ output_with_short_factor = model.generate(input_tensor, **generation_args_short)
473
+ keys_with_short_factor = output_with_short_factor.past_key_values[0][0]
474
+ generation_args_long = {
475
+ "max_length": config.original_max_position_embeddings + 5,
476
+ "temperature": 0.0,
477
+ "use_cache": True,
478
+ "do_sample": False,
479
+ "return_dict_in_generate": True,
480
+ "output_logits": True,
481
+ }
482
+ output_with_long_factor = model.generate(input_tensor, **generation_args_long)
483
+ keys_with_long_factor = output_with_long_factor.past_key_values[0][0]
484
+ last_token_logits = output_with_long_factor.logits[-1][-1]
485
+ regenerated_last_token_logits = model(output_with_long_factor.sequences[:, :-1]).logits[0][-1]
486
+ keys_with_long_factor = keys_with_long_factor[:, :, : config.original_max_position_embeddings - 1, :]
487
+
488
+ # KV cache is re-computed after reaching the (`config.original_max_position_embeddings`+1)th token position
489
+ self.assertFalse(torch.allclose(keys_with_short_factor, keys_with_long_factor, atol=1e-2, rtol=1e-2))
490
+ # Last token generated using long factor
491
+ self.assertTrue(torch.allclose(last_token_logits, regenerated_last_token_logits, atol=1e-2, rtol=1e-2))
492
+
493
+
494
+ @slow
495
+ @require_torch
496
+ class Phi3IntegrationTest(unittest.TestCase):
497
+ def test_model_phi3_mini_4k_instruct_logits(self):
498
+ input_ids = {
499
+ "input_ids": torch.tensor(
500
+ [[1212, 318, 281, 1672, 2643, 290, 428, 318, 257, 1332]], dtype=torch.long, device=torch_device
501
+ )
502
+ }
503
+
504
+ model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct").to(torch_device)
505
+ model.eval()
506
+
507
+ output = model(**input_ids).logits
508
+
509
+ EXPECTED_OUTPUT = torch.tensor([[ 0.9979, -1.9449, -2.5613, -2.2110, -0.9323, -2.2726, -3.2468, -2.0122,-1.0021, -1.2764, -1.0876, -1.2358, 3.9385, 6.2152, -0.3695, -2.3285,-1.2907, -1.8238, -1.9941, -2.2098, -0.6923, -1.6793, -1.1660, -2.0469,-0.7369, -1.4101, -1.4091, -3.1694, -1.8383, -1.1952],[ 3.0525, 1.9178, 3.7016, 0.9263, 0.3397, 1.9584, 2.1347, 0.3482, 1.3773, 0.2153, 0.2798, 0.8360, 9.0936, 11.4944, -0.3575, -0.9442,-0.1246, 1.3869, 0.9846, 1.7243, 0.9150, 1.0823, 0.4313, 1.5742, 0.2566, -0.1401, -1.3019, 0.4967, 0.6941, 0.7214]]).to(torch_device) # fmt: skip
510
+
511
+ self.assertTrue(torch.allclose(EXPECTED_OUTPUT, output[0, :2, :30], atol=1e-4, rtol=1e-4))
512
+
513
+ def test_phi3_mini_4k_instruct_generation(self):
514
+ model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
515
+ tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
516
+
517
+ messages = [
518
+ {
519
+ "role": "system",
520
+ "content": "You are a helpful digital assistant. Please provide safe, ethical and accurate information to the user.",
521
+ },
522
+ {"role": "user", "content": "Can you provide ways to eat combinations of bananas and dragonfruits?"},
523
+ ]
524
+ inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt")
525
+
526
+ outputs = model.generate(inputs, max_new_tokens=32)
527
+ output_text = tokenizer.batch_decode(outputs)
528
+
529
+ EXPECTED_OUTPUT = [
530
+ "<|system|> You are a helpful digital assistant. Please provide safe, ethical and accurate information to the user.<|end|><|user|> Can you provide ways to eat combinations of bananas and dragonfruits?<|end|><|assistant|> Certainly! Bananas and dragonfruits can be combined in various delicious ways. Here are some ideas for incorporating these fruits into your"
531
+ ]
532
+
533
+ self.assertListEqual(output_text, EXPECTED_OUTPUT)
534
+
535
+ def test_phi3_mini_4k_instruct_with_static_cache(self):
536
+ model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-4k-instruct")
537
+ tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-4k-instruct")
538
+
539
+ messages = [
540
+ {
541
+ "role": "system",
542
+ "content": "You are a helpful digital assistant. Please provide safe, ethical and accurate information to the user.",
543
+ },
544
+ {"role": "user", "content": "Can you provide ways to eat combinations of bananas and dragonfruits?"},
545
+ ]
546
+ inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt")
547
+
548
+ response_tokens = Phi3MiniWithStaticCache.generate(model, inputs, 64)
549
+
550
+ output_text = tokenizer.batch_decode(torch.tensor([response_tokens], dtype=torch.long, device=torch_device))
551
+
552
+ EXPECTED_OUTPUT = [
553
+ "<|system|> You are a helpful digital assistant. Please provide safe, ethical and accurate information to the user.<|end|><|user|> Can you provide ways to eat combinations of bananas and dragonfruits?<|end|><|assistant|> Certainly! Bananas and dragonfruits can be combined in various delicious ways. Here are some"
554
+ ]
555
+
556
+ self.assertListEqual(output_text, EXPECTED_OUTPUT)
557
+
558
+ def test_model_phi3_mini_128k_instruct_logits(self):
559
+ input_ids = {
560
+ "input_ids": torch.tensor(
561
+ [[1212, 318, 281, 1672, 2643, 290, 428, 318, 257, 1332]], dtype=torch.long, device=torch_device
562
+ )
563
+ }
564
+
565
+ model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-128k-instruct").to(torch_device)
566
+ model.eval()
567
+
568
+ output = model(**input_ids).logits
569
+
570
+ EXPECTED_OUTPUT = torch.tensor([[ 1.8478, -0.5709, -1.6792, -1.2133, -0.7809, -0.8817, -2.0969, -1.1191,-0.7731, -1.0483, -0.5961, -1.3067, 3.1325, 6.9442, -0.4803, -0.9154,-1.3085, -1.0822, -1.1433, -0.7660, -0.8531, -0.9150, -0.6179, -1.6153,-0.2239, -1.3207, -1.1187, -2.4795, -1.4733, -0.4931],[ 3.5839, 2.4722, 3.7130, 1.2032, 0.7356, 2.7777, 2.5256, 0.9157, 1.6431, 0.3533, 0.5100, 1.3512, 8.9873, 10.9815, 0.3530, 0.1473, 0.2051, 1.8553, 1.5988, 2.2268, 1.1897, 1.2829, 0.7894, 1.8895, 0.7666, 0.4122, -0.9316, 0.9936, 1.2722, 0.8263]]).to(torch_device) # fmt: skip
571
+
572
+ self.assertTrue(torch.allclose(EXPECTED_OUTPUT, output[0, :2, :30], atol=1e-4, rtol=1e-4))
573
+
574
+ def test_phi3_mini_128k_instruct_generation(self):
575
+ model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-128k-instruct")
576
+ tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-128k-instruct")
577
+
578
+ messages = [
579
+ {
580
+ "role": "system",
581
+ "content": "You are a helpful digital assistant. Please provide safe, ethical and accurate information to the user.",
582
+ },
583
+ {"role": "user", "content": "Can you provide ways to eat combinations of bananas and dragonfruits?"},
584
+ ]
585
+ inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt")
586
+
587
+ outputs = model.generate(inputs, max_new_tokens=32)
588
+ output_text = tokenizer.batch_decode(outputs)
589
+
590
+ EXPECTED_OUTPUT = [
591
+ "<|system|> You are a helpful digital assistant. Please provide safe, ethical and accurate information to the user.<|end|><|user|> Can you provide ways to eat combinations of bananas and dragonfruits?<|end|><|assistant|> Certainly! Bananas and dragonfruits can be combined in various delicious and nutritious ways. Here are some creative and healthy"
592
+ ]
593
+
594
+ self.assertListEqual(output_text, EXPECTED_OUTPUT)
595
+
596
+ def test_phi3_mini_128k_instruct_with_static_cache(self):
597
+ model = Phi3ForCausalLM.from_pretrained("microsoft/phi-3-mini-128k-instruct")
598
+ tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-3-mini-128k-instruct")
599
+
600
+ messages = [
601
+ {
602
+ "role": "system",
603
+ "content": "You are a helpful digital assistant. Please provide safe, ethical and accurate information to the user.",
604
+ },
605
+ {"role": "user", "content": "Can you provide ways to eat combinations of bananas and dragonfruits?"},
606
+ ]
607
+ inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt")
608
+
609
+ response_tokens = Phi3MiniWithStaticCache.generate(model, inputs, 64)
610
+
611
+ output_text = tokenizer.batch_decode(torch.tensor([response_tokens], dtype=torch.long, device=torch_device))
612
+
613
+ EXPECTED_OUTPUT = [
614
+ "<|system|> You are a helpful digital assistant. Please provide safe, ethical and accurate information to the user.<|end|><|user|> Can you provide ways to eat combinations of bananas and dragonfruits?<|end|><|assistant|> Certainly! Bananas and dragonfruits can be combined in various delicious and nutritious ways"
615
+ ]
616
+
617
+ self.assertListEqual(output_text, EXPECTED_OUTPUT)
618
+
619
+ def test_phi3_mini_4k_sliding_window(self):
620
+ """
621
+ This tests that Phi3 doesn't deteriorate in quality for long context generations. Since Phi3 has
622
+ sliding window attention, the test is tailored so that (context + max_new_tokens > sliding_window).
623
+ See #33586 for more
624
+ """
625
+ model = Phi3ForCausalLM.from_pretrained(
626
+ "microsoft/Phi-3-mini-4k-instruct", device_map=torch_device, torch_dtype=torch.bfloat16
627
+ )
628
+ tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-4k-instruct")
629
+
630
+ input_text = """
631
+ <|user|>
632
+ Tell me about Paris, France.<|end|>
633
+ <|assistant|>
634
+ Paris, the capital city of France, is renowned for its rich history, iconic landmarks, and vibrant culture. Known as "The City of Light," Paris is situated in the north-central part of the country along the Seine River.
635
+
636
+ Here are some key aspects of Paris:
637
+
638
+ 1. Landmarks: Paris is home to numerous famous landmarks, including the Eiffel Tower, the Louvre Museum, Notre-Dame Cathedral, and the Champs-Élysées. The Eiffel Tower, built in 1889, is an iconic symbol of Paris and attracts millions of tourists each year. The Louvre Museum, the world's largest art museum, houses thousands of works of art, including the Mona Lisa and the Venus de Milo.
639
+
640
+ 2. History: Paris has a rich history dating back to the 3rd century BC, when it was founded by a Celtic tribe called the Parisii. Over the centuries, the city has been influenced by various cultures, including the Romans, the Franks, and the Normans. The French Revolution in the late 18th century marked a significant turning point in Paris's history, leading to the establishment of the modern French Republic.
641
+
642
+ 3. Culture: Paris is a global center for art, fashion, gastronomy, and culture. The city is home to numerous museums, including the Centre Pompidou, Musée d'Orsay, and Musée Rodin. Paris is also known for its fashion industry, with many famous designers having their origins in the city. The city's cuisine is also highly regarded, with a focus on fresh ingredients, and a wide variety of dishes, including French classics like coq au vin, boeuf bourguignon, and crêpes.
643
+
644
+ 4. Architecture: Parisian architecture is characterized by its diverse styles, ranging from Gothic and Romanesque to Art Nouveau and Art Deco. The city's famous Haussmannian buildings, designed by Baron Haussmann in the mid-19th century, are known for their uniform facades, wrought-iron balconies, and large windows.
645
+
646
+ 5. Transportation: Paris has an extensive public transportation system, including the Paris Métro, RER (suburban trains), and buses. The city's iconic yellow taxis are also a popular mode of transportation.
647
+
648
+ 6. Language: The official language of Paris is French, and the city's residents are known for their charm and politeness.
649
+
650
+ 7. Festivals and Events: Paris hosts numerous festivals and events throughout the year, including the annual Bastille Day celebrations, the Paris Fashion Week, and the famous annual New Year's Eve fireworks on the Eiffel Tower.
651
+
652
+ 8. Geography: Paris is located in the north-central part of France, with the Seine River running through the city. The city's geography is characterized by rolling hills and picturesque parks, such as the Bois de Boulogne and the Jardin des Tuileries.
653
+
654
+ 9. Population: As of 2021, Paris has an estimated population of around 2.2 million residents, with the metropolitan area housing over 12 million people.
655
+
656
+ In summary, Paris is a city steeped in history, culture, and art, with a unique blend of architectural styles and a vibrant atmosphere that continues to captivate millions of visitors each year.<|end|>
657
+ <|user|>
658
+ Please give me a list of 5 architectural landmarks in Paris, France.<|end|>
659
+ <|assistant|>
660
+ 1. Eiffel Tower: Designed by Gustave Eiffel and completed in 1889, the Eiffel Tower is an iconic symbol of Paris and France. Standing at 324 meters tall, it was the tallest man-made structure in the world until the completion of the Chrysler Building in New York in 1930. The Eiffel Tower is made of wrought iron and offers visitors stunning views of the city from its three levels.
661
+
662
+ 2. Notre-Dame Cathedral: Located on the Île de la Cité, Notre-Dame Cathedral is a masterpiece of French Gothic architecture. Construction began in the 12th century and continued for over 200 years, with the cathedral's completion in the 14th century. The cathedral is famous for its intricate facade, stained-glass windows, and the iconic gargoyles and chimeras.
663
+
664
+ 3. Louvre Museum: Originally built as a fortress in the 12th century, the Louvre Museum is now the world's largest art museum and a historic monument in Paris. The museum's most famous landmark is the iconic glass pyramid entrance, designed by architect I. M. Pei in the 1980s. The Louvre houses over 380,000 works of art, including the Mona Lisa and the Venus de Milo.
665
+
666
+ 4. Sacré-Cœur Basilica: The Sacré-Cœur Basilica, also known as the Basilique du Sacré-Cœur, is a Roman Catholic church and minor basilica located at the summit of the butte Montmartre, the highest point in Paris. The basilica was designed by Paul Abadie and dedicated in 1914. Its white domes and lavender-colored travertine stone make it a distinctive landmark in the Paris skyline.
667
+
668
+ 5. Arc de Triomphe: The Arc de Triomphe is a monumental structure located at the western end of the Champs-Élysées. Commissioned by Napoleon in 1806, the Arc was designed by Jean-François-Thérèse Chalgrin and completed in 1836. The monument honors those who fought and died for France during the French Revolutionary and Napoleonic Wars. The Arc features sculptural reliefs and inscriptions, and its façade is adorned with the names of 357 generals and 660 soldiers.
669
+
670
+ These five architectural landmarks showcase the diverse styles and historical periods of Paris, from Gothic to Neoclassical, and from the 19th to the 20th centuries. Each landmark has its unique features and contributes to the city's rich architectural heritage.<|end|>
671
+ <|user|>
672
+ Please give me a list of 10 famous items displayed in the Louvre Museum. Thanks!<|end|>
673
+ <|assistant|>
674
+ 1. Mona Lisa: The Mona Lisa, painted by Leonardo da Vinci in the early 16th century, is arguably the most famous painting in the world. The portrait is known for its enigmatic smile and masterful use of sfumato, a technique that creates a soft, hazy effect.
675
+
676
+ 2. Venus de Milo: This ancient Greek statue, believed to have been created around 130-100 BC, is a masterpiece of Hellenistic sculpture. The Venus de Milo is renowned for its graceful beauty and the mystery surrounding its missing arms.
677
+
678
+ 3. Winged Victory of Samothrace: This Hellenistic sculpture, dating back to the 2nd century BC, depicts the Greek goddess Nike, the personification of victory. The sculpture is celebrated for its dynamic movement and intricate details.
679
+
680
+ 4. Liberty Leading the People: This iconic painting by Eugène Delacroix, created in 1830, commemorates the July Revolution in France. The artwork depicts a woman personifying Liberty leading a group of revolutionaries over the bodies of the fallen.
681
+
682
+ 5. The Wedding at Cana: A 1516 painting by Veronese, The Wedding at Cana is a large-scale work that depicts the biblical story of Jesus turning water into wine at a wedding feast. The painting is known for its vibrant colors and intricate details.
683
+
684
+ 6. The Raft of the Medusa: This 1819 painting by Théodore Géricault is a powerful depiction of the aftermath of the shipwreck of the French frigate Méduse. The painting is famous for its dramatic composition and emotional intensity.
685
+
686
+ 7. The Coronation of Napoleon: This 1805 painting by Jacques-Louis David portrays the coronation of Napoleon Bonaparte as Emperor of the French. The artwork is a masterpiece of neoclassical style and captures the pomp and ceremony of the event.
687
+
688
+ 8. The Death of Socrates: A 1914 painting by Pablo Picasso, The Death of Socrates depicts the moment when the ancient Greek philosopher Socrates drinks the poison hemlock, as ordered by the Athenian government. The painting is a powerful expression of the existential themes associated with Socrates' death.
689
+
690
+ 9. The Turkish Bath: A 1887 painting by Puvis de Chavannes, The Turkish Bath is a large-scale work that depicts a scene of relaxation and leisity in a traditional Turkish bath. The painting is known for its subdued color palette and serene atmosphere.
691
+
692
+ 10. The Wedding at Cana: A 1901 painting by Giovanni Boldini, The Wedding at Cana is a lively depiction of a festive Italian wedding. The painting is characterized by Boldini's signature flamboyant style and his ability to capture the essence of the subjects with a sense of movement and energy.
693
+
694
+ These 10 famous items in the Louvre Museum showcase a diverse range of artistic styles and periods, from ancient Greek and Roman sculptures to Renaissance and 19th-century paintings. The collection at the Louvre is one of the world's largest and most important museums, housing over 800,000 works of art, and these famous items are just a small selection of the museum's vast collection.<|end|>
695
+ <|user|>
696
+ Please give me a list of 10 famous French dishes.<|end|>
697
+ <|assistant|>
698
+ """
699
+
700
+ inputs = tokenizer(input_text, return_tensors="pt").to(device=torch_device)
701
+ outputs = model.generate(**inputs, max_new_tokens=100)
702
+ output_text = tokenizer.batch_decode(outputs[:, inputs.input_ids.shape[1] :], skip_special_tokens=True)
703
+ EXPECTED_OUTPUT = [
704
+ '1. Coq au Vin: Coq au Vin is a classic French dish that translates to "rooster in wine." The dish consists of chicken braised with wine, lardons, mushrooms, and garlic. It is a hearty and flavorful dish that is often served with potatoes or rice.\n\n 2. Boeuf Bourguignon: Boeuf Bourguignon is a traditional French beef stew that'
705
+ ]
706
+
707
+ self.assertListEqual(output_text, EXPECTED_OUTPUT)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/phimoe/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/phimoe/test_modeling_phimoe.py ADDED
@@ -0,0 +1,566 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 Microsoft 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
+
16
+ """Testing suite for the PyTorch PhiMoE model."""
17
+
18
+ import unittest
19
+ from typing import List
20
+
21
+ from parameterized import parameterized
22
+
23
+ from transformers import PhimoeConfig, StaticCache, is_torch_available, set_seed
24
+ from transformers.testing_utils import (
25
+ require_torch,
26
+ slow,
27
+ torch_device,
28
+ )
29
+
30
+ from ...generation.test_utils import GenerationTesterMixin
31
+ from ...test_configuration_common import ConfigTester
32
+ from ...test_modeling_common import ModelTesterMixin, ids_tensor
33
+ from ...test_pipeline_mixin import PipelineTesterMixin
34
+
35
+
36
+ if is_torch_available():
37
+ import torch
38
+
39
+ from transformers import (
40
+ AutoTokenizer,
41
+ PhimoeForCausalLM,
42
+ PhimoeForSequenceClassification,
43
+ PhimoeModel,
44
+ )
45
+
46
+ end_of_text_token = 32000
47
+
48
+ class PhimoeMiniWithStaticCache(torch.nn.Module):
49
+ def __init__(self, model: PhimoeForCausalLM, batch_size: int, max_seq_len: int):
50
+ super().__init__()
51
+ self.model = model
52
+ self.cache = StaticCache(
53
+ config=model.config,
54
+ batch_size=batch_size,
55
+ max_cache_len=max_seq_len,
56
+ device=self.model.device,
57
+ dtype=self.model.dtype,
58
+ )
59
+
60
+ def forward(
61
+ self,
62
+ input_ids: torch.LongTensor = None,
63
+ ) -> torch.FloatTensor:
64
+ return self.model.forward(
65
+ input_ids=input_ids,
66
+ use_cache=True,
67
+ return_dict=True,
68
+ past_key_values=self.cache,
69
+ ).logits
70
+
71
+ @staticmethod
72
+ def generate(model: PhimoeForCausalLM, prompt_tokens: torch.LongTensor, max_seq_len: int) -> List[int]:
73
+ model = PhimoeMiniWithStaticCache(model, 1, max_seq_len + prompt_tokens.shape[-1])
74
+
75
+ response_tokens = []
76
+
77
+ for input_pos in range(prompt_tokens.shape[-1]):
78
+ result = model.forward(
79
+ input_ids=prompt_tokens[:, input_pos : input_pos + 1],
80
+ )
81
+ response_tokens.append(prompt_tokens[0][input_pos].item())
82
+
83
+ current_token = torch.argmax(result[:, -1, :], dim=-1).item()
84
+ response_tokens.append(current_token)
85
+
86
+ while current_token != end_of_text_token and len(response_tokens) < max_seq_len:
87
+ result = model.forward(
88
+ input_ids=torch.tensor([[current_token]], dtype=torch.long),
89
+ )
90
+ current_token = torch.argmax(result[:, -1, :], dim=-1).item()
91
+ response_tokens.append(current_token)
92
+
93
+ return response_tokens
94
+
95
+
96
+ class PhimoeModelTester:
97
+ def __init__(
98
+ self,
99
+ parent,
100
+ batch_size=13,
101
+ seq_length=7,
102
+ is_training=True,
103
+ use_input_mask=True,
104
+ use_token_type_ids=False,
105
+ use_labels=True,
106
+ vocab_size=99,
107
+ hidden_size=32,
108
+ num_hidden_layers=2,
109
+ num_attention_heads=4,
110
+ num_key_value_heads=4,
111
+ intermediate_size=37,
112
+ hidden_act="gelu",
113
+ hidden_dropout_prob=0.1,
114
+ attention_probs_dropout_prob=0.1,
115
+ max_position_embeddings=131072,
116
+ type_vocab_size=16,
117
+ type_sequence_label_size=2,
118
+ initializer_range=0.02,
119
+ num_labels=3,
120
+ num_choices=4,
121
+ pad_token_id=0,
122
+ scope=None,
123
+ original_max_position_embeddings=4096,
124
+ ):
125
+ self.parent = parent
126
+ self.batch_size = batch_size
127
+ self.seq_length = seq_length
128
+ self.is_training = is_training
129
+ self.use_input_mask = use_input_mask
130
+ self.use_token_type_ids = use_token_type_ids
131
+ self.use_labels = use_labels
132
+ self.vocab_size = vocab_size
133
+ self.hidden_size = hidden_size
134
+ self.num_hidden_layers = num_hidden_layers
135
+ self.num_attention_heads = num_attention_heads
136
+ self.num_key_value_heads = num_key_value_heads
137
+ self.intermediate_size = intermediate_size
138
+ self.hidden_act = hidden_act
139
+ self.hidden_dropout_prob = hidden_dropout_prob
140
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
141
+ self.max_position_embeddings = max_position_embeddings
142
+ self.type_vocab_size = type_vocab_size
143
+ self.type_sequence_label_size = type_sequence_label_size
144
+ self.initializer_range = initializer_range
145
+ self.num_labels = num_labels
146
+ self.num_choices = num_choices
147
+ self.pad_token_id = pad_token_id
148
+ self.scope = scope
149
+ self.original_max_position_embeddings = original_max_position_embeddings
150
+
151
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTester.prepare_config_and_inputs
152
+ def prepare_config_and_inputs(self):
153
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
154
+
155
+ input_mask = None
156
+ if self.use_input_mask:
157
+ input_mask = torch.tril(torch.ones_like(input_ids).to(torch_device))
158
+
159
+ token_type_ids = None
160
+ if self.use_token_type_ids:
161
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
162
+
163
+ sequence_labels = None
164
+ token_labels = None
165
+ choice_labels = None
166
+ if self.use_labels:
167
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
168
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
169
+ choice_labels = ids_tensor([self.batch_size], self.num_choices)
170
+
171
+ config = self.get_config()
172
+
173
+ return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
174
+
175
+ def get_config(self):
176
+ return PhimoeConfig(
177
+ vocab_size=self.vocab_size,
178
+ hidden_size=self.hidden_size,
179
+ num_hidden_layers=self.num_hidden_layers,
180
+ num_attention_heads=self.num_attention_heads,
181
+ num_key_value_heads=self.num_key_value_heads,
182
+ intermediate_size=self.intermediate_size,
183
+ hidden_act=self.hidden_act,
184
+ hidden_dropout_prob=self.hidden_dropout_prob,
185
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
186
+ max_position_embeddings=self.max_position_embeddings,
187
+ type_vocab_size=self.type_vocab_size,
188
+ is_decoder=False,
189
+ initializer_range=self.initializer_range,
190
+ pad_token_id=self.pad_token_id,
191
+ num_experts_per_tok=2,
192
+ num_local_experts=2,
193
+ original_max_position_embeddings=self.original_max_position_embeddings,
194
+ )
195
+
196
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTester.create_and_check_model with Llama->Phimoe
197
+ def create_and_check_model(
198
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
199
+ ):
200
+ model = PhimoeModel(config=config)
201
+ model.to(torch_device)
202
+ model.eval()
203
+ result = model(input_ids, attention_mask=input_mask)
204
+ result = model(input_ids)
205
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
206
+
207
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTester.create_and_check_model_as_decoder with Llama->Phimoe
208
+ def create_and_check_model_as_decoder(
209
+ self,
210
+ config,
211
+ input_ids,
212
+ token_type_ids,
213
+ input_mask,
214
+ sequence_labels,
215
+ token_labels,
216
+ choice_labels,
217
+ encoder_hidden_states,
218
+ encoder_attention_mask,
219
+ ):
220
+ config.add_cross_attention = True
221
+ model = PhimoeModel(config)
222
+ model.to(torch_device)
223
+ model.eval()
224
+ result = model(
225
+ input_ids,
226
+ attention_mask=input_mask,
227
+ encoder_hidden_states=encoder_hidden_states,
228
+ encoder_attention_mask=encoder_attention_mask,
229
+ )
230
+ result = model(
231
+ input_ids,
232
+ attention_mask=input_mask,
233
+ encoder_hidden_states=encoder_hidden_states,
234
+ )
235
+ result = model(input_ids, attention_mask=input_mask)
236
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
237
+
238
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTester.create_and_check_for_causal_lm with Llama->Phimoe
239
+ def create_and_check_for_causal_lm(
240
+ self,
241
+ config,
242
+ input_ids,
243
+ token_type_ids,
244
+ input_mask,
245
+ sequence_labels,
246
+ token_labels,
247
+ choice_labels,
248
+ encoder_hidden_states,
249
+ encoder_attention_mask,
250
+ ):
251
+ model = PhimoeForCausalLM(config=config)
252
+ model.to(torch_device)
253
+ model.eval()
254
+ result = model(input_ids, attention_mask=input_mask, labels=token_labels)
255
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
256
+
257
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTester.create_and_check_decoder_model_past_large_inputs with Llama->Phimoe
258
+ def create_and_check_decoder_model_past_large_inputs(
259
+ self,
260
+ config,
261
+ input_ids,
262
+ token_type_ids,
263
+ input_mask,
264
+ sequence_labels,
265
+ token_labels,
266
+ choice_labels,
267
+ encoder_hidden_states,
268
+ encoder_attention_mask,
269
+ ):
270
+ config.is_decoder = True
271
+ config.add_cross_attention = True
272
+ model = PhimoeForCausalLM(config=config)
273
+ model.to(torch_device)
274
+ model.eval()
275
+
276
+ # first forward pass
277
+ outputs = model(
278
+ input_ids,
279
+ attention_mask=input_mask,
280
+ encoder_hidden_states=encoder_hidden_states,
281
+ encoder_attention_mask=encoder_attention_mask,
282
+ use_cache=True,
283
+ )
284
+ past_key_values = outputs.past_key_values
285
+
286
+ # create hypothetical multiple next token and extent to next_input_ids
287
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
288
+ next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
289
+
290
+ # append to next input_ids and
291
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
292
+ next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
293
+
294
+ output_from_no_past = model(
295
+ next_input_ids,
296
+ attention_mask=next_attention_mask,
297
+ encoder_hidden_states=encoder_hidden_states,
298
+ encoder_attention_mask=encoder_attention_mask,
299
+ output_hidden_states=True,
300
+ )["hidden_states"][0]
301
+ output_from_past = model(
302
+ next_tokens,
303
+ attention_mask=next_attention_mask,
304
+ encoder_hidden_states=encoder_hidden_states,
305
+ encoder_attention_mask=encoder_attention_mask,
306
+ past_key_values=past_key_values,
307
+ output_hidden_states=True,
308
+ )["hidden_states"][0]
309
+
310
+ # select random slice
311
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
312
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
313
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
314
+
315
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
316
+
317
+ # test that outputs are equal for slice
318
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
319
+
320
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTester.prepare_config_and_inputs_for_common
321
+ def prepare_config_and_inputs_for_common(self):
322
+ config_and_inputs = self.prepare_config_and_inputs()
323
+ (
324
+ config,
325
+ input_ids,
326
+ token_type_ids,
327
+ input_mask,
328
+ sequence_labels,
329
+ token_labels,
330
+ choice_labels,
331
+ ) = config_and_inputs
332
+ inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
333
+ return config, inputs_dict
334
+
335
+
336
+ @require_torch
337
+ class PhimoeModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
338
+ all_model_classes = (
339
+ (PhimoeModel, PhimoeForCausalLM, PhimoeForSequenceClassification) if is_torch_available() else ()
340
+ )
341
+ all_generative_model_classes = (PhimoeForCausalLM,) if is_torch_available() else ()
342
+ pipeline_model_mapping = (
343
+ {
344
+ "feature-extraction": PhimoeModel,
345
+ "text-classification": PhimoeForSequenceClassification,
346
+ "text-generation": PhimoeForCausalLM,
347
+ "zero-shot": PhimoeForSequenceClassification,
348
+ }
349
+ if is_torch_available()
350
+ else {}
351
+ )
352
+
353
+ test_headmasking = False
354
+ test_pruning = False
355
+
356
+ # TODO (ydshieh): Check this. See https://app.circleci.com/pipelines/github/huggingface/transformers/79292/workflows/fa2ba644-8953-44a6-8f67-ccd69ca6a476/jobs/1012905
357
+ def is_pipeline_test_to_skip(
358
+ self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name
359
+ ):
360
+ return True
361
+
362
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.setUp with Llama->Phimoe
363
+ def setUp(self):
364
+ self.model_tester = PhimoeModelTester(self)
365
+ self.config_tester = ConfigTester(self, config_class=PhimoeConfig, hidden_size=37)
366
+
367
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_config
368
+ def test_config(self):
369
+ self.config_tester.run_common_tests()
370
+
371
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_model
372
+ def test_model(self):
373
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
374
+ self.model_tester.create_and_check_model(*config_and_inputs)
375
+
376
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_llama_sequence_classification_model with Llama->Phimoe,llama->phimoe
377
+ def test_phimoe_sequence_classification_model(self):
378
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
379
+ config.num_labels = 3
380
+ input_ids = input_dict["input_ids"]
381
+ attention_mask = input_ids.ne(1).to(torch_device)
382
+ sequence_labels = ids_tensor([self.model_tester.batch_size], self.model_tester.type_sequence_label_size)
383
+ model = PhimoeForSequenceClassification(config)
384
+ model.to(torch_device)
385
+ model.eval()
386
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
387
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
388
+
389
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_llama_sequence_classification_model_for_single_label with Llama->Phimoe,llama->phimoe
390
+ def test_phimoe_sequence_classification_model_for_single_label(self):
391
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
392
+ config.num_labels = 3
393
+ config.problem_type = "single_label_classification"
394
+ input_ids = input_dict["input_ids"]
395
+ attention_mask = input_ids.ne(1).to(torch_device)
396
+ sequence_labels = ids_tensor([self.model_tester.batch_size], self.model_tester.type_sequence_label_size)
397
+ model = PhimoeForSequenceClassification(config)
398
+ model.to(torch_device)
399
+ model.eval()
400
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
401
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
402
+
403
+ # Copied from tests.models.llama.test_modeling_llama.LlamaModelTest.test_llama_sequence_classification_model_for_multi_label with Llama->Phimoe,llama->phimoe
404
+ def test_phimoe_sequence_classification_model_for_multi_label(self):
405
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
406
+ config.num_labels = 3
407
+ config.problem_type = "multi_label_classification"
408
+ input_ids = input_dict["input_ids"]
409
+ attention_mask = input_ids.ne(1).to(torch_device)
410
+ sequence_labels = ids_tensor(
411
+ [self.model_tester.batch_size, config.num_labels], self.model_tester.type_sequence_label_size
412
+ ).to(torch.float)
413
+ model = PhimoeForSequenceClassification(config)
414
+ model.to(torch_device)
415
+ model.eval()
416
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
417
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
418
+
419
+ @parameterized.expand([("longrope",)])
420
+ def test_model_rope_scaling_from_config(self, scaling_type):
421
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
422
+ short_input = ids_tensor([1, 10], config.vocab_size)
423
+ long_input = ids_tensor([1, int(config.original_max_position_embeddings * 1.5)], config.vocab_size)
424
+
425
+ set_seed(42) # Fixed seed at init time so the two models get the same random weights
426
+ original_model = PhimoeModel(config)
427
+ original_model.to(torch_device)
428
+ original_model.eval()
429
+ original_short_output = original_model(short_input).last_hidden_state
430
+ original_long_output = original_model(long_input).last_hidden_state
431
+
432
+ set_seed(42) # Fixed seed at init time so the two models get the same random weights
433
+ n_factors = config.hidden_size // config.num_attention_heads // 2
434
+ config.rope_scaling = {
435
+ "type": scaling_type,
436
+ "short_factor": [3.0 for _ in range(n_factors)],
437
+ "long_factor": [5.0 for _ in range(n_factors)],
438
+ "short_mscale": 1.243163121016122,
439
+ "long_mscale": 1.243163121016122,
440
+ "original_max_position_embeddings": 4096,
441
+ }
442
+ scaled_model = PhimoeModel(config)
443
+ scaled_model.to(torch_device)
444
+ scaled_model.eval()
445
+ scaled_short_output = scaled_model(short_input).last_hidden_state
446
+ scaled_long_output = scaled_model(long_input).last_hidden_state
447
+
448
+ # Scaling changes the RoPE embeddings, both for the short and long outputs
449
+ self.assertFalse(torch.allclose(original_short_output, scaled_short_output, atol=1e-5))
450
+ self.assertFalse(torch.allclose(original_long_output, scaled_long_output, atol=1e-5))
451
+
452
+ @parameterized.expand([("longrope",)])
453
+ def test_model_rope_scaling_short_long_factor(self, scaling_type):
454
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
455
+ n_factors = config.hidden_size // config.num_key_value_heads // 2
456
+ config.rope_scaling = {
457
+ "type": scaling_type,
458
+ "short_factor": [3.0 for _ in range(n_factors)],
459
+ "long_factor": [5.0 for _ in range(n_factors)],
460
+ "short_mscale": 1.243163121016122,
461
+ "long_mscale": 1.243163121016122,
462
+ "original_max_position_embeddings": 4096,
463
+ }
464
+ input_tensor = ids_tensor([1, 4090], config.vocab_size)
465
+ model = PhimoeForCausalLM(config)
466
+ model.to(torch_device)
467
+ model.eval()
468
+ generation_args_short = {
469
+ "max_length": config.original_max_position_embeddings,
470
+ "temperature": 0.0,
471
+ "use_cache": True,
472
+ "do_sample": False,
473
+ "return_dict_in_generate": True,
474
+ }
475
+ output_with_short_factor = model.generate(input_tensor, **generation_args_short)
476
+ keys_with_short_factor = output_with_short_factor.past_key_values[0][0]
477
+ generation_args_long = {
478
+ "max_length": config.original_max_position_embeddings + 5,
479
+ "temperature": 0.0,
480
+ "use_cache": True,
481
+ "do_sample": False,
482
+ "return_dict_in_generate": True,
483
+ "output_logits": True,
484
+ }
485
+ output_with_long_factor = model.generate(input_tensor, **generation_args_long)
486
+ keys_with_long_factor = output_with_long_factor.past_key_values[0][0]
487
+ last_token_logits = output_with_long_factor.logits[-1][-1]
488
+ regenerated_last_token_logits = model(output_with_long_factor.sequences[:, :-1]).logits[0][-1]
489
+ keys_with_long_factor = keys_with_long_factor[:, :, : config.original_max_position_embeddings - 1, :]
490
+
491
+ # KV cache is re-computed after reaching the (`config.original_max_position_embeddings`+1)th token position
492
+ self.assertFalse(torch.allclose(keys_with_short_factor, keys_with_long_factor, atol=1e-3, rtol=1e-3))
493
+ # Last token generated using long factor
494
+ self.assertTrue(torch.allclose(last_token_logits, regenerated_last_token_logits, atol=1e-2, rtol=1e-2))
495
+
496
+
497
+ @slow
498
+ @require_torch
499
+ class PhimoeIntegrationTest(unittest.TestCase):
500
+ def test_model_phimoe_instruct_logits(self):
501
+ input_ids = {
502
+ "input_ids": torch.tensor(
503
+ [[1212, 318, 281, 1672, 2643, 290, 428, 318, 257, 1332]], dtype=torch.long, device=torch_device
504
+ )
505
+ }
506
+
507
+ model = PhimoeForCausalLM.from_pretrained("microsoft/Phi-3.5-MoE-instruct").to(torch_device)
508
+ model.eval()
509
+
510
+ output = model(**input_ids).logits
511
+
512
+ EXPECTED_OUTPUT = torch.tensor([[-3.5312, -2.5000, -1.2734, 0.3555, -0.7578, -0.4727, 0.5977, -0.4316,
513
+ 0.2256, -1.2188, -1.6797, 0.9961, 3.7656, 11.3125, -1.3828, -4.8438,
514
+ -5.7500, -1.9375, 0.7227, -0.3438, -0.2100, -0.4277, -0.0444, -0.5352,
515
+ -0.6406, -0.1016, -0.4258, -1.0234, 0.4297, -0.6250],
516
+ [-0.9883, 0.1455, -0.4902, 2.3594, 0.7031, 3.1406, 0.4375, 0.2559,
517
+ 0.6172, -2.1094, -1.3359, 2.5938, 4.9062, 10.8125, -0.1094, 1.5781,
518
+ -4.9375, 0.7148, -0.0972, 1.7656, -0.0801, 0.2217, 0.1875, -0.4629,
519
+ 1.5781, 0.3535, 0.0874, 0.6836, -0.0518, -1.2969]]).to(torch_device) # fmt: skip
520
+
521
+ self.assertTrue(torch.allclose(EXPECTED_OUTPUT, output[0, :2, :30], atol=1e-4, rtol=1e-4))
522
+
523
+ def test_phimoe_instruct_generation(self):
524
+ model = PhimoeForCausalLM.from_pretrained("microsoft/Phi-3.5-MoE-instruct")
525
+ tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3.5-MoE-instruct")
526
+
527
+ messages = [
528
+ {
529
+ "role": "system",
530
+ "content": "You are a helpful digital assistant. Please provide safe, ethical and accurate information to the user.",
531
+ },
532
+ {"role": "user", "content": "Can you provide ways to eat combinations of bananas and dragonfruits?"},
533
+ ]
534
+ inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt")
535
+
536
+ outputs = model.generate(inputs, max_new_tokens=32)
537
+ output_text = tokenizer.batch_decode(outputs)
538
+
539
+ EXPECTED_OUTPUT = [
540
+ "<|system|> You are a helpful digital assistant. Please provide safe, ethical and accurate information to the user.<|end|><|user|> Can you provide ways to eat combinations of bananas and dragonfruits?<|end|><|assistant|> Certainly! Bananas and dragonfruits are both delicious and nutritious fruits that can be combined in various ways to create tast"
541
+ ]
542
+
543
+ self.assertListEqual(output_text, EXPECTED_OUTPUT)
544
+
545
+ def test_phimoe_instruct_with_static_cache(self):
546
+ model = PhimoeForCausalLM.from_pretrained("microsoft/Phi-3.5-MoE-instruct")
547
+ tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3.5-MoE-instruct")
548
+
549
+ messages = [
550
+ {
551
+ "role": "system",
552
+ "content": "You are a helpful digital assistant. Please provide safe, ethical and accurate information to the user.",
553
+ },
554
+ {"role": "user", "content": "Can you provide ways to eat combinations of bananas and dragonfruits?"},
555
+ ]
556
+ inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_tensors="pt")
557
+
558
+ response_tokens = PhimoeMiniWithStaticCache.generate(model, inputs, 64)
559
+
560
+ output_text = tokenizer.batch_decode(torch.tensor([response_tokens], dtype=torch.long, device=torch_device))
561
+
562
+ EXPECTED_OUTPUT = [
563
+ "<|system|> You are a helpful digital assistant. Please provide safe, ethical and accurate information to the user.<|end|><|user|> Can you provide ways to eat combinations of bananas and dragonfruits?<|end|><|assistant|> Certainly! Bananas and dragonfruits are both delicious and nutritious fruits that can"
564
+ ]
565
+
566
+ self.assertListEqual(output_text, EXPECTED_OUTPUT)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/phobert/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/phobert/test_tokenization_phobert.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2018 Salesforce and HuggingFace Inc. team.
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 os
17
+ import unittest
18
+
19
+ from transformers.models.phobert.tokenization_phobert import VOCAB_FILES_NAMES, PhobertTokenizer
20
+
21
+ from ...test_tokenization_common import TokenizerTesterMixin
22
+
23
+
24
+ class PhobertTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
25
+ from_pretrained_id = "vinai/phobert-base"
26
+ tokenizer_class = PhobertTokenizer
27
+ test_rust_tokenizer = False
28
+
29
+ def setUp(self):
30
+ super().setUp()
31
+
32
+ # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
33
+ vocab = ["T@@", "i", "I", "R@@", "r", "e@@"]
34
+ vocab_tokens = dict(zip(vocab, range(len(vocab))))
35
+ merges = ["#version: 0.2", "l à</w>"]
36
+ self.special_tokens_map = {"unk_token": "<unk>"}
37
+
38
+ self.vocab_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["vocab_file"])
39
+ self.merges_file = os.path.join(self.tmpdirname, VOCAB_FILES_NAMES["merges_file"])
40
+
41
+ with open(self.vocab_file, "w", encoding="utf-8") as fp:
42
+ for token in vocab_tokens:
43
+ fp.write(f"{token} {vocab_tokens[token]}\n")
44
+ with open(self.merges_file, "w", encoding="utf-8") as fp:
45
+ fp.write("\n".join(merges))
46
+
47
+ def get_tokenizer(self, **kwargs):
48
+ kwargs.update(self.special_tokens_map)
49
+ return PhobertTokenizer.from_pretrained(self.tmpdirname, **kwargs)
50
+
51
+ def get_input_output_texts(self, tokenizer):
52
+ input_text = "Tôi là VinAI Research"
53
+ output_text = "T<unk> i <unk> <unk> <unk> <unk> <unk> <unk> I Re<unk> e<unk> <unk> <unk> <unk>"
54
+ return input_text, output_text
55
+
56
+ def test_full_tokenizer(self):
57
+ tokenizer = PhobertTokenizer(self.vocab_file, self.merges_file, **self.special_tokens_map)
58
+ text = "Tôi là VinAI Research"
59
+ bpe_tokens = "T@@ ô@@ i l@@ à V@@ i@@ n@@ A@@ I R@@ e@@ s@@ e@@ a@@ r@@ c@@ h".split()
60
+ tokens = tokenizer.tokenize(text)
61
+ print(tokens)
62
+ self.assertListEqual(tokens, bpe_tokens)
63
+
64
+ input_tokens = tokens + [tokenizer.unk_token]
65
+
66
+ input_bpe_tokens = [4, 3, 5, 3, 3, 3, 3, 3, 3, 6, 7, 9, 3, 9, 3, 3, 3, 3, 3]
67
+ self.assertListEqual(tokenizer.convert_tokens_to_ids(input_tokens), input_bpe_tokens)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pix2struct/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pix2struct/test_image_processing_pix2struct.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 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
+ import requests
21
+
22
+ from transformers.testing_utils import require_torch, require_vision
23
+ from transformers.utils import is_torch_available, is_vision_available
24
+
25
+ from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs
26
+
27
+
28
+ if is_torch_available():
29
+ import torch
30
+
31
+ if is_vision_available():
32
+ from PIL import Image
33
+
34
+ from transformers import Pix2StructImageProcessor
35
+
36
+
37
+ class Pix2StructImageProcessingTester:
38
+ def __init__(
39
+ self,
40
+ parent,
41
+ batch_size=7,
42
+ num_channels=3,
43
+ image_size=18,
44
+ min_resolution=30,
45
+ max_resolution=400,
46
+ size=None,
47
+ do_normalize=True,
48
+ do_convert_rgb=True,
49
+ patch_size=None,
50
+ ):
51
+ size = size if size is not None else {"height": 20, "width": 20}
52
+ self.parent = parent
53
+ self.batch_size = batch_size
54
+ self.num_channels = num_channels
55
+ self.image_size = image_size
56
+ self.min_resolution = min_resolution
57
+ self.max_resolution = max_resolution
58
+ self.size = size
59
+ self.do_normalize = do_normalize
60
+ self.do_convert_rgb = do_convert_rgb
61
+ self.max_patches = [512, 1024, 2048, 4096]
62
+ self.patch_size = patch_size if patch_size is not None else {"height": 16, "width": 16}
63
+
64
+ def prepare_image_processor_dict(self):
65
+ return {"do_normalize": self.do_normalize, "do_convert_rgb": self.do_convert_rgb}
66
+
67
+ def prepare_dummy_image(self):
68
+ img_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg"
69
+ raw_image = Image.open(requests.get(img_url, stream=True).raw).convert("RGB")
70
+ return raw_image
71
+
72
+ def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
73
+ return prepare_image_inputs(
74
+ batch_size=self.batch_size,
75
+ num_channels=self.num_channels,
76
+ min_resolution=self.min_resolution,
77
+ max_resolution=self.max_resolution,
78
+ equal_resolution=equal_resolution,
79
+ numpify=numpify,
80
+ torchify=torchify,
81
+ )
82
+
83
+
84
+ @require_torch
85
+ @require_vision
86
+ class Pix2StructImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
87
+ image_processing_class = Pix2StructImageProcessor if is_vision_available() else None
88
+
89
+ def setUp(self):
90
+ super().setUp()
91
+ self.image_processor_tester = Pix2StructImageProcessingTester(self)
92
+
93
+ @property
94
+ def image_processor_dict(self):
95
+ return self.image_processor_tester.prepare_image_processor_dict()
96
+
97
+ def test_image_processor_properties(self):
98
+ image_processor = self.image_processing_class(**self.image_processor_dict)
99
+ self.assertTrue(hasattr(image_processor, "do_normalize"))
100
+ self.assertTrue(hasattr(image_processor, "do_convert_rgb"))
101
+
102
+ def test_expected_patches(self):
103
+ dummy_image = self.image_processor_tester.prepare_dummy_image()
104
+
105
+ image_processor = self.image_processing_class(**self.image_processor_dict)
106
+ max_patch = 2048
107
+
108
+ inputs = image_processor(dummy_image, return_tensors="pt", max_patches=max_patch)
109
+ self.assertTrue(torch.allclose(inputs.flattened_patches.mean(), torch.tensor(0.0606), atol=1e-3, rtol=1e-3))
110
+
111
+ def test_call_pil(self):
112
+ # Initialize image_processor
113
+ image_processor = self.image_processing_class(**self.image_processor_dict)
114
+ # create random PIL images
115
+ image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False)
116
+ for image in image_inputs:
117
+ self.assertIsInstance(image, Image.Image)
118
+
119
+ # Test not batched input
120
+ expected_hidden_dim = (
121
+ (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"])
122
+ * self.image_processor_tester.num_channels
123
+ ) + 2
124
+
125
+ for max_patch in self.image_processor_tester.max_patches:
126
+ # Test not batched input
127
+ encoded_images = image_processor(
128
+ image_inputs[0], return_tensors="pt", max_patches=max_patch
129
+ ).flattened_patches
130
+ self.assertEqual(
131
+ encoded_images.shape,
132
+ (1, max_patch, expected_hidden_dim),
133
+ )
134
+
135
+ # Test batched
136
+ encoded_images = image_processor(
137
+ image_inputs, return_tensors="pt", max_patches=max_patch
138
+ ).flattened_patches
139
+ self.assertEqual(
140
+ encoded_images.shape,
141
+ (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim),
142
+ )
143
+
144
+ def test_call_vqa(self):
145
+ # Initialize image_processor
146
+ image_processor = self.image_processing_class(**self.image_processor_dict)
147
+ # create random PIL images
148
+ image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False)
149
+ for image in image_inputs:
150
+ self.assertIsInstance(image, Image.Image)
151
+
152
+ # Test not batched input
153
+ expected_hidden_dim = (
154
+ (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"])
155
+ * self.image_processor_tester.num_channels
156
+ ) + 2
157
+
158
+ image_processor.is_vqa = True
159
+
160
+ for max_patch in self.image_processor_tester.max_patches:
161
+ # Test not batched input
162
+ with self.assertRaises(ValueError):
163
+ encoded_images = image_processor(
164
+ image_inputs[0], return_tensors="pt", max_patches=max_patch
165
+ ).flattened_patches
166
+
167
+ dummy_text = "Hello"
168
+
169
+ encoded_images = image_processor(
170
+ image_inputs[0], return_tensors="pt", max_patches=max_patch, header_text=dummy_text
171
+ ).flattened_patches
172
+ self.assertEqual(
173
+ encoded_images.shape,
174
+ (1, max_patch, expected_hidden_dim),
175
+ )
176
+
177
+ # Test batched
178
+ encoded_images = image_processor(
179
+ image_inputs, return_tensors="pt", max_patches=max_patch, header_text=dummy_text
180
+ ).flattened_patches
181
+ self.assertEqual(
182
+ encoded_images.shape,
183
+ (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim),
184
+ )
185
+
186
+ def test_call_numpy(self):
187
+ # Initialize image_processor
188
+ image_processor = self.image_processing_class(**self.image_processor_dict)
189
+ # create random numpy tensors
190
+ image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True)
191
+ for image in image_inputs:
192
+ self.assertIsInstance(image, np.ndarray)
193
+
194
+ expected_hidden_dim = (
195
+ (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"])
196
+ * self.image_processor_tester.num_channels
197
+ ) + 2
198
+
199
+ for max_patch in self.image_processor_tester.max_patches:
200
+ # Test not batched input
201
+ encoded_images = image_processor(
202
+ image_inputs[0], return_tensors="pt", max_patches=max_patch
203
+ ).flattened_patches
204
+ self.assertEqual(
205
+ encoded_images.shape,
206
+ (1, max_patch, expected_hidden_dim),
207
+ )
208
+
209
+ # Test batched
210
+ encoded_images = image_processor(
211
+ image_inputs, return_tensors="pt", max_patches=max_patch
212
+ ).flattened_patches
213
+ self.assertEqual(
214
+ encoded_images.shape,
215
+ (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim),
216
+ )
217
+
218
+ def test_call_numpy_4_channels(self):
219
+ # Initialize image_processor
220
+ image_processor = self.image_processing_class(**self.image_processor_dict)
221
+ # create random numpy tensors
222
+ self.image_processor_tester.num_channels = 4
223
+ image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True)
224
+ for image in image_inputs:
225
+ self.assertIsInstance(image, np.ndarray)
226
+
227
+ expected_hidden_dim = (
228
+ (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"])
229
+ * self.image_processor_tester.num_channels
230
+ ) + 2
231
+
232
+ for max_patch in self.image_processor_tester.max_patches:
233
+ # Test not batched input
234
+ encoded_images = image_processor(
235
+ image_inputs[0], return_tensors="pt", max_patches=max_patch, input_data_format="channels_last"
236
+ ).flattened_patches
237
+ self.assertEqual(
238
+ encoded_images.shape,
239
+ (1, max_patch, expected_hidden_dim),
240
+ )
241
+
242
+ # Test batched
243
+ encoded_images = image_processor(
244
+ image_inputs, return_tensors="pt", max_patches=max_patch, input_data_format="channels_last"
245
+ ).flattened_patches
246
+ self.assertEqual(
247
+ encoded_images.shape,
248
+ (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim),
249
+ )
250
+ self.image_processor_tester.num_channels = 3
251
+
252
+ def test_call_pytorch(self):
253
+ # Initialize image_processor
254
+ image_processor = self.image_processing_class(**self.image_processor_dict)
255
+ # create random PyTorch tensors
256
+ image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True)
257
+ for image in image_inputs:
258
+ self.assertIsInstance(image, torch.Tensor)
259
+
260
+ # Test not batched input
261
+ expected_hidden_dim = (
262
+ (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"])
263
+ * self.image_processor_tester.num_channels
264
+ ) + 2
265
+
266
+ for max_patch in self.image_processor_tester.max_patches:
267
+ # Test not batched input
268
+ encoded_images = image_processor(
269
+ image_inputs[0], return_tensors="pt", max_patches=max_patch
270
+ ).flattened_patches
271
+ self.assertEqual(
272
+ encoded_images.shape,
273
+ (1, max_patch, expected_hidden_dim),
274
+ )
275
+
276
+ # Test batched
277
+ encoded_images = image_processor(
278
+ image_inputs, return_tensors="pt", max_patches=max_patch
279
+ ).flattened_patches
280
+ self.assertEqual(
281
+ encoded_images.shape,
282
+ (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim),
283
+ )
284
+
285
+
286
+ @require_torch
287
+ @require_vision
288
+ class Pix2StructImageProcessingTestFourChannels(ImageProcessingTestMixin, unittest.TestCase):
289
+ image_processing_class = Pix2StructImageProcessor if is_vision_available() else None
290
+
291
+ def setUp(self):
292
+ super().setUp()
293
+ self.image_processor_tester = Pix2StructImageProcessingTester(self, num_channels=4)
294
+ self.expected_encoded_image_num_channels = 3
295
+
296
+ @property
297
+ def image_processor_dict(self):
298
+ return self.image_processor_tester.prepare_image_processor_dict()
299
+
300
+ def test_image_processor_properties(self):
301
+ image_processor = self.image_processing_class(**self.image_processor_dict)
302
+ self.assertTrue(hasattr(image_processor, "do_normalize"))
303
+ self.assertTrue(hasattr(image_processor, "do_convert_rgb"))
304
+
305
+ def test_call_pil(self):
306
+ # Initialize image_processor
307
+ image_processor = self.image_processing_class(**self.image_processor_dict)
308
+ # create random PIL images
309
+ image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False)
310
+ for image in image_inputs:
311
+ self.assertIsInstance(image, Image.Image)
312
+
313
+ # Test not batched input
314
+ expected_hidden_dim = (
315
+ (self.image_processor_tester.patch_size["height"] * self.image_processor_tester.patch_size["width"])
316
+ * (self.image_processor_tester.num_channels - 1)
317
+ ) + 2
318
+
319
+ for max_patch in self.image_processor_tester.max_patches:
320
+ # Test not batched input
321
+ encoded_images = image_processor(
322
+ image_inputs[0], return_tensors="pt", max_patches=max_patch
323
+ ).flattened_patches
324
+ self.assertEqual(
325
+ encoded_images.shape,
326
+ (1, max_patch, expected_hidden_dim),
327
+ )
328
+
329
+ # Test batched
330
+ encoded_images = image_processor(
331
+ image_inputs, return_tensors="pt", max_patches=max_patch
332
+ ).flattened_patches
333
+ self.assertEqual(
334
+ encoded_images.shape,
335
+ (self.image_processor_tester.batch_size, max_patch, expected_hidden_dim),
336
+ )
337
+
338
+ @unittest.skip(reason="Pix2StructImageProcessor does not support 4 channels yet") # FIXME Amy
339
+ def test_call_numpy(self):
340
+ return super().test_call_numpy()
341
+
342
+ @unittest.skip(reason="Pix2StructImageProcessor does not support 4 channels yet") # FIXME Amy
343
+ def test_call_pytorch(self):
344
+ return super().test_call_torch()
345
+
346
+ @unittest.skip(
347
+ reason="Pix2StructImageProcessor does treat numpy and PIL 4 channel images consistently"
348
+ ) # FIXME Amy
349
+ def test_call_numpy_4_channels(self):
350
+ return super().test_call_torch()
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pix2struct/test_modeling_pix2struct.py ADDED
@@ -0,0 +1,895 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Pix2Struct model."""
16
+
17
+ import copy
18
+ import inspect
19
+ import os
20
+ import tempfile
21
+ import unittest
22
+
23
+ import numpy as np
24
+ import requests
25
+
26
+ from transformers import Pix2StructConfig, Pix2StructTextConfig, Pix2StructVisionConfig
27
+ from transformers.testing_utils import require_torch, require_vision, slow, torch_device
28
+ from transformers.utils import is_torch_available, is_vision_available
29
+
30
+ from ...generation.test_utils import GenerationTesterMixin
31
+ from ...test_configuration_common import ConfigTester
32
+ from ...test_modeling_common import (
33
+ ModelTesterMixin,
34
+ _config_zero_init,
35
+ floats_tensor,
36
+ ids_tensor,
37
+ random_attention_mask,
38
+ )
39
+ from ...test_pipeline_mixin import PipelineTesterMixin
40
+
41
+
42
+ if is_torch_available():
43
+ import torch
44
+ from torch import nn
45
+
46
+ from transformers import (
47
+ Pix2StructForConditionalGeneration,
48
+ Pix2StructProcessor,
49
+ Pix2StructTextModel,
50
+ Pix2StructVisionModel,
51
+ )
52
+
53
+
54
+ if is_vision_available():
55
+ from PIL import Image
56
+
57
+
58
+ class Pix2StructVisionModelTester:
59
+ def __init__(
60
+ self,
61
+ parent,
62
+ batch_size=12,
63
+ image_size=30,
64
+ patch_size=2,
65
+ num_channels=3,
66
+ is_training=True,
67
+ hidden_size=12,
68
+ patch_embed_hidden_size=12,
69
+ projection_dim=32,
70
+ max_patches=64,
71
+ num_hidden_layers=2,
72
+ num_attention_heads=4,
73
+ intermediate_size=37,
74
+ dropout=0.1,
75
+ attention_dropout=0.1,
76
+ initializer_range=1e-10,
77
+ scope=None,
78
+ ):
79
+ self.parent = parent
80
+ self.batch_size = batch_size
81
+ self.image_size = image_size
82
+ self.patch_embed_hidden_size = patch_embed_hidden_size
83
+ self.patch_size = patch_size
84
+ self.num_channels = num_channels
85
+ self.is_training = is_training
86
+ self.hidden_size = hidden_size
87
+ self.max_patches = max_patches
88
+ self.seq_length = self.max_patches
89
+ self.patch_proj_dim = ((patch_size**2) * num_channels) + 2
90
+
91
+ self.projection_dim = projection_dim
92
+ self.num_hidden_layers = num_hidden_layers
93
+ self.num_attention_heads = num_attention_heads
94
+ self.intermediate_size = intermediate_size
95
+ self.dropout = dropout
96
+ self.attention_dropout = attention_dropout
97
+ self.initializer_range = initializer_range
98
+ self.scope = scope
99
+
100
+ def prepare_config_and_inputs(self):
101
+ flattened_patches = floats_tensor([self.batch_size, self.max_patches, self.patch_proj_dim])
102
+ config = self.get_config()
103
+
104
+ return config, flattened_patches
105
+
106
+ def get_config(self):
107
+ return Pix2StructVisionConfig(
108
+ image_size=self.image_size,
109
+ patch_size=self.patch_size,
110
+ num_channels=self.num_channels,
111
+ hidden_size=self.hidden_size,
112
+ projection_dim=self.projection_dim,
113
+ num_hidden_layers=self.num_hidden_layers,
114
+ num_attention_heads=self.num_attention_heads,
115
+ intermediate_size=self.intermediate_size,
116
+ dropout=self.dropout,
117
+ attention_dropout=self.attention_dropout,
118
+ initializer_range=self.initializer_range,
119
+ patch_embed_hidden_size=self.patch_embed_hidden_size,
120
+ )
121
+
122
+ def create_and_check_model(self, config, flattened_patches):
123
+ model = Pix2StructVisionModel(config=config)
124
+ model.to(torch_device)
125
+ model.eval()
126
+ with torch.no_grad():
127
+ result = model(flattened_patches)
128
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
129
+
130
+ def prepare_config_and_inputs_for_common(self):
131
+ config_and_inputs = self.prepare_config_and_inputs()
132
+ config, flattened_patches = config_and_inputs
133
+ inputs_dict = {
134
+ "flattened_patches": flattened_patches,
135
+ "attention_mask": torch.randint(0, 2, (self.batch_size, self.max_patches)),
136
+ }
137
+ return config, inputs_dict
138
+
139
+
140
+ @require_torch
141
+ class Pix2StructVisionModelTest(ModelTesterMixin, unittest.TestCase):
142
+ """
143
+ Here we also overwrite some of the tests of test_modeling_common.py, as Pix2Struct does not use input_ids, inputs_embeds,
144
+ attention_mask and seq_length.
145
+ """
146
+
147
+ all_model_classes = (Pix2StructVisionModel,) if is_torch_available() else ()
148
+ fx_compatible = False
149
+ test_pruning = False
150
+ test_resize_embeddings = False
151
+ test_head_masking = False
152
+
153
+ def setUp(self):
154
+ self.model_tester = Pix2StructVisionModelTester(self)
155
+ self.config_tester = ConfigTester(
156
+ self, config_class=Pix2StructVisionConfig, has_text_modality=False, hidden_size=37
157
+ )
158
+
159
+ def test_config(self):
160
+ self.config_tester.run_common_tests()
161
+
162
+ @unittest.skip(reason="Pix2StructVision does not use inputs_embeds")
163
+ def test_inputs_embeds(self):
164
+ pass
165
+
166
+ def test_model_get_set_embeddings(self):
167
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
168
+
169
+ for model_class in self.all_model_classes:
170
+ model = model_class(config)
171
+ self.assertIsInstance(model.get_input_embeddings(), (nn.Module))
172
+ x = model.get_output_embeddings()
173
+ self.assertTrue(x is None or isinstance(x, nn.Linear))
174
+
175
+ def test_forward_signature(self):
176
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
177
+
178
+ for model_class in self.all_model_classes:
179
+ model = model_class(config)
180
+ signature = inspect.signature(model.forward)
181
+ # signature.parameters is an OrderedDict => so arg_names order is deterministic
182
+ arg_names = [*signature.parameters.keys()]
183
+
184
+ expected_arg_names = ["flattened_patches"]
185
+ self.assertListEqual(arg_names[:1], expected_arg_names)
186
+
187
+ def test_model(self):
188
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
189
+ self.model_tester.create_and_check_model(*config_and_inputs)
190
+
191
+ @unittest.skip(reason="Training is tested directly on `Pix2StructTextImageModelTest`")
192
+ def test_training(self):
193
+ pass
194
+
195
+ @unittest.skip(reason="Training is tested directly on `Pix2StructTextImageModelTest`")
196
+ def test_training_gradient_checkpointing(self):
197
+ pass
198
+
199
+ @unittest.skip(
200
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
201
+ )
202
+ def test_training_gradient_checkpointing_use_reentrant(self):
203
+ pass
204
+
205
+ @unittest.skip(
206
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
207
+ )
208
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
209
+ pass
210
+
211
+ @unittest.skip(reason="Training is tested directly on `Pix2StructTextImageModelTest`")
212
+ def test_retain_grad_hidden_states_attentions(self):
213
+ pass
214
+
215
+ @unittest.skip(reason="Pix2StructVisionModel has no base class and is not available in MODEL_MAPPING")
216
+ def test_save_load_fast_init_from_base(self):
217
+ pass
218
+
219
+ @unittest.skip(reason="Pix2StructVisionModel has no base class and is not available in MODEL_MAPPING")
220
+ def test_save_load_fast_init_to_base(self):
221
+ pass
222
+
223
+ @slow
224
+ def test_model_from_pretrained(self):
225
+ model_name = "google/pix2struct-textcaps-base"
226
+ model = Pix2StructVisionModel.from_pretrained(model_name)
227
+ self.assertIsNotNone(model)
228
+
229
+
230
+ class Pix2StructTextModelTester:
231
+ def __init__(
232
+ self,
233
+ parent,
234
+ batch_size=12,
235
+ seq_length=7,
236
+ is_training=True,
237
+ use_input_mask=True,
238
+ use_labels=True,
239
+ vocab_size=99,
240
+ hidden_size=12,
241
+ projection_dim=32,
242
+ num_hidden_layers=2,
243
+ num_attention_heads=4,
244
+ intermediate_size=37,
245
+ dropout=0.1,
246
+ attention_dropout=0.1,
247
+ max_position_embeddings=512,
248
+ initializer_range=0.02,
249
+ bos_token_id=0,
250
+ scope=None,
251
+ ):
252
+ self.parent = parent
253
+ self.batch_size = batch_size
254
+ self.seq_length = seq_length
255
+ self.is_training = is_training
256
+ self.use_input_mask = use_input_mask
257
+ self.use_labels = use_labels
258
+ self.d_kv = hidden_size // num_attention_heads
259
+ self.vocab_size = vocab_size
260
+ self.hidden_size = hidden_size
261
+ self.projection_dim = projection_dim
262
+ self.num_hidden_layers = num_hidden_layers
263
+ self.num_attention_heads = num_attention_heads
264
+ self.intermediate_size = intermediate_size
265
+ self.dropout = dropout
266
+ self.attention_dropout = attention_dropout
267
+ self.max_position_embeddings = max_position_embeddings
268
+ self.initializer_range = initializer_range
269
+ self.scope = scope
270
+ self.bos_token_id = bos_token_id
271
+
272
+ def prepare_config_and_inputs(self):
273
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
274
+
275
+ input_mask = None
276
+ if self.use_input_mask:
277
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
278
+
279
+ if input_mask is not None:
280
+ batch_size, seq_length = input_mask.shape
281
+ rnd_start_indices = np.random.randint(1, seq_length - 1, size=(batch_size,))
282
+ for batch_idx, start_index in enumerate(rnd_start_indices):
283
+ input_mask[batch_idx, :start_index] = 1
284
+ input_mask[batch_idx, start_index:] = 0
285
+
286
+ config = self.get_config()
287
+
288
+ return config, input_ids, input_mask
289
+
290
+ def get_config(self):
291
+ return Pix2StructTextConfig(
292
+ vocab_size=self.vocab_size,
293
+ hidden_size=self.hidden_size,
294
+ projection_dim=self.projection_dim,
295
+ num_hidden_layers=self.num_hidden_layers,
296
+ num_attention_heads=self.num_attention_heads,
297
+ intermediate_size=self.intermediate_size,
298
+ dropout=self.dropout,
299
+ attention_dropout=self.attention_dropout,
300
+ max_position_embeddings=self.max_position_embeddings,
301
+ initializer_range=self.initializer_range,
302
+ bos_token_id=self.bos_token_id,
303
+ d_kv=self.d_kv,
304
+ )
305
+
306
+ def create_and_check_model(self, config, input_ids, input_mask):
307
+ model = Pix2StructTextModel(config=config)
308
+ model.to(torch_device)
309
+ model.eval()
310
+ with torch.no_grad():
311
+ result = model(input_ids, attention_mask=input_mask)
312
+ result = model(input_ids)
313
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
314
+
315
+ def prepare_config_and_inputs_for_common(self):
316
+ config_and_inputs = self.prepare_config_and_inputs()
317
+ config, input_ids, input_mask = config_and_inputs
318
+ inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
319
+ return config, inputs_dict
320
+
321
+
322
+ @require_torch
323
+ class Pix2StructTextModelTest(ModelTesterMixin, unittest.TestCase):
324
+ all_model_classes = (Pix2StructTextModel,) if is_torch_available() else ()
325
+ fx_compatible = False
326
+ test_pruning = False
327
+ test_head_masking = False
328
+
329
+ def setUp(self):
330
+ self.model_tester = Pix2StructTextModelTester(self)
331
+ self.config_tester = ConfigTester(self, config_class=Pix2StructTextConfig, hidden_size=37)
332
+
333
+ def test_config(self):
334
+ self.config_tester.run_common_tests()
335
+
336
+ def test_model(self):
337
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
338
+ self.model_tester.create_and_check_model(*config_and_inputs)
339
+
340
+ @unittest.skip(reason="Training is tested directly on `Pix2StructTextImageModelTest`")
341
+ def test_training(self):
342
+ pass
343
+
344
+ @unittest.skip(reason="Training is tested directly on `Pix2StructTextImageModelTest`")
345
+ def test_training_gradient_checkpointing(self):
346
+ pass
347
+
348
+ @unittest.skip(
349
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
350
+ )
351
+ def test_training_gradient_checkpointing_use_reentrant(self):
352
+ pass
353
+
354
+ @unittest.skip(
355
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
356
+ )
357
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
358
+ pass
359
+
360
+ @unittest.skip(reason="Pix2Struct does not use inputs_embeds")
361
+ def test_inputs_embeds(self):
362
+ pass
363
+
364
+ @unittest.skip(reason="Pix2StructTextModel has no base class and is not available in MODEL_MAPPING")
365
+ def test_save_load_fast_init_from_base(self):
366
+ pass
367
+
368
+ @unittest.skip(reason="Pix2StructTextModel has no base class and is not available in MODEL_MAPPING")
369
+ def test_save_load_fast_init_to_base(self):
370
+ pass
371
+
372
+ @slow
373
+ def test_model_from_pretrained(self):
374
+ model_name = "google/pix2struct-textcaps-base"
375
+ model = Pix2StructTextModel.from_pretrained(model_name)
376
+ self.assertIsNotNone(model)
377
+
378
+
379
+ class Pix2StructModelTester:
380
+ def __init__(self, parent, text_kwargs=None, vision_kwargs=None, is_training=True):
381
+ if text_kwargs is None:
382
+ text_kwargs = {}
383
+ if vision_kwargs is None:
384
+ vision_kwargs = {}
385
+
386
+ self.parent = parent
387
+ self.text_model_tester = Pix2StructTextModelTester(parent, **text_kwargs)
388
+ self.vision_model_tester = Pix2StructVisionModelTester(parent, **vision_kwargs)
389
+ self.batch_size = self.text_model_tester.batch_size # need bs for batching_equivalence test
390
+ self.seq_length = self.text_model_tester.seq_length # need seq_length for common tests
391
+ self.is_training = is_training
392
+ self.max_patches = self.vision_model_tester.max_patches
393
+
394
+ def prepare_config_and_inputs(self):
395
+ text_config, input_ids, attention_mask = self.text_model_tester.prepare_config_and_inputs()
396
+ vision_config, flattened_patches = self.vision_model_tester.prepare_config_and_inputs()
397
+
398
+ config = self.get_config(text_config, vision_config)
399
+
400
+ return config, input_ids, attention_mask, flattened_patches
401
+
402
+ def get_config(self, text_config, vision_config):
403
+ return Pix2StructConfig.from_text_vision_configs(text_config, vision_config, projection_dim=64)
404
+
405
+ def prepare_config_and_inputs_for_common(self):
406
+ config_and_inputs = self.prepare_config_and_inputs()
407
+ config, input_ids, decoder_attention_mask, flattened_patches = config_and_inputs
408
+
409
+ attention_mask = (flattened_patches.sum(dim=-1) != 0).float()
410
+
411
+ inputs_dict = {
412
+ "decoder_input_ids": input_ids,
413
+ "labels": input_ids,
414
+ "decoder_attention_mask": decoder_attention_mask,
415
+ "flattened_patches": flattened_patches,
416
+ "attention_mask": attention_mask,
417
+ }
418
+ return config, inputs_dict
419
+
420
+
421
+ @require_torch
422
+ class Pix2StructModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
423
+ all_model_classes = (Pix2StructForConditionalGeneration,) if is_torch_available() else ()
424
+ all_generative_model_classes = (Pix2StructForConditionalGeneration,) if is_torch_available() else {}
425
+ pipeline_model_mapping = (
426
+ {"image-to-text": Pix2StructForConditionalGeneration, "image-text-to-text": Pix2StructForConditionalGeneration}
427
+ if is_torch_available()
428
+ else {}
429
+ )
430
+ fx_compatible = False
431
+ test_head_masking = False
432
+ test_pruning = False
433
+ test_resize_embeddings = True
434
+ test_attention_outputs = False
435
+ test_torchscript = False
436
+
437
+ def setUp(self):
438
+ self.model_tester = Pix2StructModelTester(self)
439
+
440
+ def test_model(self):
441
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
442
+ for model_class in self.all_model_classes:
443
+ model = model_class(config).to(torch_device)
444
+
445
+ output = model(**input_dict)
446
+ self.assertEqual(
447
+ output[1].shape,
448
+ (
449
+ self.model_tester.vision_model_tester.batch_size,
450
+ self.model_tester.text_model_tester.seq_length,
451
+ self.model_tester.text_model_tester.vocab_size,
452
+ ),
453
+ )
454
+
455
+ def test_generative_model(self):
456
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
457
+ for model_class in self.all_generative_model_classes:
458
+ model = model_class(config).eval().to(torch_device)
459
+
460
+ output = model.generate(**input_dict, use_cache=False, min_new_tokens=10, max_new_tokens=10)
461
+ output_use_cache = model.generate(**input_dict, use_cache=True, min_new_tokens=10, max_new_tokens=10)
462
+
463
+ torch.testing.assert_close(output, output_use_cache)
464
+
465
+ @unittest.skip(reason="Hidden_states is tested in individual model tests")
466
+ def test_hidden_states_output(self):
467
+ pass
468
+
469
+ @unittest.skip(reason="Inputs_embeds is tested in individual model tests")
470
+ def test_inputs_embeds(self):
471
+ pass
472
+
473
+ @unittest.skip(reason="Retain_grad is tested in individual model tests")
474
+ def test_retain_grad_hidden_states_attentions(self):
475
+ pass
476
+
477
+ @unittest.skip(reason="Pix2StructModel does not have input/output embeddings")
478
+ def test_model_get_set_embeddings(self):
479
+ pass
480
+
481
+ def test_forward_signature(self):
482
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
483
+
484
+ for model_class in self.all_model_classes:
485
+ model = model_class(config)
486
+ signature = inspect.signature(model.forward)
487
+ # signature.parameters is an OrderedDict => so arg_names order is deterministic
488
+ arg_names = [*signature.parameters.keys()]
489
+
490
+ expected_arg_names = [
491
+ "flattened_patches",
492
+ "attention_mask",
493
+ "decoder_input_ids",
494
+ "decoder_attention_mask",
495
+ "head_mask",
496
+ "decoder_head_mask",
497
+ "cross_attn_head_mask",
498
+ "encoder_outputs",
499
+ "past_key_values",
500
+ "labels",
501
+ "decoder_inputs_embeds",
502
+ "use_cache",
503
+ ]
504
+
505
+ self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names)
506
+
507
+ def test_training(self):
508
+ if not self.model_tester.is_training:
509
+ self.skipTest(reason="model_tester.is_training is set to False")
510
+
511
+ for model_class in self.all_model_classes[:-1]:
512
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
513
+ config.return_dict = True
514
+
515
+ model = model_class(config)
516
+ model.to(torch_device)
517
+ model.train()
518
+ inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
519
+
520
+ # hardcode labels to be the same as input_ids
521
+ inputs["labels"] = inputs["input_ids"]
522
+
523
+ loss = model(**inputs).loss
524
+ loss.backward()
525
+
526
+ def test_training_gradient_checkpointing(self):
527
+ if not self.model_tester.is_training:
528
+ self.skipTest(reason="model_tester.is_training is set to False")
529
+
530
+ for model_class in self.all_model_classes[:-1]:
531
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
532
+ config.use_cache = False
533
+ config.return_dict = True
534
+
535
+ model = model_class(config)
536
+ model.to(torch_device)
537
+ model.gradient_checkpointing_enable()
538
+ model.train()
539
+ inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
540
+
541
+ # hardcode labels to be the same as input_ids
542
+ inputs["labels"] = inputs["input_ids"]
543
+
544
+ loss = model(**inputs).loss
545
+ loss.backward()
546
+
547
+ # override as the `logit_scale` parameter initilization is different for Pix2Struct
548
+ def test_initialization(self):
549
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
550
+
551
+ configs_no_init = _config_zero_init(config)
552
+ for model_class in self.all_model_classes:
553
+ model = model_class(config=configs_no_init)
554
+ for name, param in model.named_parameters():
555
+ if param.requires_grad:
556
+ # check if `logit_scale` is initilized as per the original implementation
557
+ if name == "logit_scale":
558
+ self.assertAlmostEqual(
559
+ param.data.item(),
560
+ np.log(1 / 0.07),
561
+ delta=1e-3,
562
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
563
+ )
564
+ else:
565
+ self.assertIn(
566
+ ((param.data.mean() * 1e9).round() / 1e9).item(),
567
+ [0.0, 1.0],
568
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
569
+ )
570
+
571
+ # overwrite because `vocab_size` is not an attribute of `Pix2StructConfig` but rather `Pix2StructTextConfig`
572
+ def test_resize_tokens_embeddings(self):
573
+ original_config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
574
+ if not self.test_resize_embeddings:
575
+ self.skipTest(reason="test_resize_embeddings is set to False")
576
+
577
+ for model_class in self.all_model_classes:
578
+ config = copy.deepcopy(original_config)
579
+ model = model_class(config)
580
+ model.to(torch_device)
581
+
582
+ if self.model_tester.is_training is False:
583
+ model.eval()
584
+
585
+ model_vocab_size = config.text_config.vocab_size
586
+ # Retrieve the embeddings and clone theme
587
+ model_embed = model.resize_token_embeddings(model_vocab_size)
588
+ cloned_embeddings = model_embed.weight.clone()
589
+
590
+ # Check that resizing the token embeddings with a larger vocab size increases the model's vocab size
591
+ model_embed = model.resize_token_embeddings(model_vocab_size + 10)
592
+ self.assertEqual(model.config.text_config.vocab_size, model_vocab_size + 10)
593
+ # Check that it actually resizes the embeddings matrix
594
+ self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] + 10)
595
+ # Check that the model can still do a forward pass successfully (every parameter should be resized)
596
+ model(**self._prepare_for_class(inputs_dict, model_class))
597
+
598
+ # Check that resizing the token embeddings with a smaller vocab size decreases the model's vocab size
599
+ model_embed = model.resize_token_embeddings(model_vocab_size - 15)
600
+ self.assertEqual(model.config.text_config.vocab_size, model_vocab_size - 15)
601
+ # Check that it actually resizes the embeddings matrix
602
+ self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] - 15)
603
+
604
+ # Check that the model can still do a forward pass successfully (every parameter should be resized)
605
+ # Decoder input ids should be clamped to the maximum size of the vocabulary
606
+ if "decoder_input_ids" in inputs_dict:
607
+ inputs_dict["decoder_input_ids"].clamp_(max=model_vocab_size - 15 - 1)
608
+ model(**self._prepare_for_class(inputs_dict, model_class))
609
+
610
+ # Check that adding and removing tokens has not modified the first part of the embedding matrix.
611
+ models_equal = True
612
+ for p1, p2 in zip(cloned_embeddings, model_embed.weight):
613
+ if p1.data.ne(p2.data).sum() > 0:
614
+ models_equal = False
615
+
616
+ self.assertTrue(models_equal)
617
+
618
+ # overwrite because `vocab_size` is not an attribute of `Pix2StructConfig` but rather `Pix2StructTextConfig`
619
+ def test_resize_embeddings_untied(self):
620
+ original_config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
621
+ if not self.test_resize_embeddings:
622
+ self.skipTest(reason="test_resize_embeddings is set to False")
623
+
624
+ original_config.tie_word_embeddings = False
625
+
626
+ # if model cannot untied embeddings -> leave test
627
+ if original_config.tie_word_embeddings:
628
+ self.skipTest(reason="Model cannot untie embeddings")
629
+
630
+ for model_class in self.all_model_classes:
631
+ config = copy.deepcopy(original_config)
632
+ model = model_class(config).to(torch_device)
633
+
634
+ # if no output embeddings -> leave test
635
+ if model.get_output_embeddings() is None:
636
+ continue
637
+
638
+ # Check that resizing the token embeddings with a larger vocab size increases the model's vocab size
639
+ model_vocab_size = config.text_config.vocab_size
640
+ model.resize_token_embeddings(model_vocab_size + 10)
641
+ self.assertEqual(model.config.text_config.vocab_size, model_vocab_size + 10)
642
+ output_embeds = model.get_output_embeddings()
643
+ self.assertEqual(output_embeds.weight.shape[0], model_vocab_size + 10)
644
+ # Check bias if present
645
+ if output_embeds.bias is not None:
646
+ self.assertEqual(output_embeds.bias.shape[0], model_vocab_size + 10)
647
+ # Check that the model can still do a forward pass successfully (every parameter should be resized)
648
+ model(**self._prepare_for_class(inputs_dict, model_class))
649
+
650
+ # Check that resizing the token embeddings with a smaller vocab size decreases the model's vocab size
651
+ model.resize_token_embeddings(model_vocab_size - 15)
652
+ self.assertEqual(model.config.text_config.vocab_size, model_vocab_size - 15)
653
+ # Check that it actually resizes the embeddings matrix
654
+ output_embeds = model.get_output_embeddings()
655
+ self.assertEqual(output_embeds.weight.shape[0], model_vocab_size - 15)
656
+ # Check bias if present
657
+ if output_embeds.bias is not None:
658
+ self.assertEqual(output_embeds.bias.shape[0], model_vocab_size - 15)
659
+ # Check that the model can still do a forward pass successfully (every parameter should be resized)
660
+ # Decoder input ids should be clamped to the maximum size of the vocabulary
661
+ if "decoder_input_ids" in inputs_dict:
662
+ inputs_dict["decoder_input_ids"].clamp_(max=model_vocab_size - 15 - 1)
663
+ # Check that the model can still do a forward pass successfully (every parameter should be resized)
664
+ model(**self._prepare_for_class(inputs_dict, model_class))
665
+
666
+ @unittest.skip(reason="Pix2Struct doesn't use tied weights")
667
+ def test_tied_model_weights_key_ignore(self):
668
+ pass
669
+
670
+ def _create_and_check_torchscript(self, config, inputs_dict):
671
+ if not self.test_torchscript:
672
+ self.skipTest(reason="test_torchscript is set to False")
673
+
674
+ configs_no_init = _config_zero_init(config) # To be sure we have no Nan
675
+ configs_no_init.torchscript = True
676
+ configs_no_init.return_dict = False
677
+ for model_class in self.all_model_classes:
678
+ model = model_class(config=configs_no_init)
679
+ model.to(torch_device)
680
+ model.eval()
681
+
682
+ try:
683
+ input_ids = inputs_dict["input_ids"]
684
+ flattened_patches = inputs_dict["flattened_patches"] # Pix2Struct needs flattened_patches
685
+ traced_model = torch.jit.trace(model, (input_ids, flattened_patches))
686
+ except RuntimeError:
687
+ self.fail("Couldn't trace module.")
688
+
689
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
690
+ pt_file_name = os.path.join(tmp_dir_name, "traced_model.pt")
691
+
692
+ try:
693
+ torch.jit.save(traced_model, pt_file_name)
694
+ except Exception:
695
+ self.fail("Couldn't save module.")
696
+
697
+ try:
698
+ loaded_model = torch.jit.load(pt_file_name)
699
+ except Exception:
700
+ self.fail("Couldn't load module.")
701
+
702
+ model.to(torch_device)
703
+ model.eval()
704
+
705
+ loaded_model.to(torch_device)
706
+ loaded_model.eval()
707
+
708
+ model_state_dict = model.state_dict()
709
+ loaded_model_state_dict = loaded_model.state_dict()
710
+
711
+ non_persistent_buffers = {}
712
+ for key in loaded_model_state_dict.keys():
713
+ if key not in model_state_dict.keys():
714
+ non_persistent_buffers[key] = loaded_model_state_dict[key]
715
+
716
+ loaded_model_state_dict = {
717
+ key: value for key, value in loaded_model_state_dict.items() if key not in non_persistent_buffers
718
+ }
719
+
720
+ self.assertEqual(set(model_state_dict.keys()), set(loaded_model_state_dict.keys()))
721
+
722
+ model_buffers = list(model.buffers())
723
+ for non_persistent_buffer in non_persistent_buffers.values():
724
+ found_buffer = False
725
+ for i, model_buffer in enumerate(model_buffers):
726
+ if torch.equal(non_persistent_buffer, model_buffer):
727
+ found_buffer = True
728
+ break
729
+
730
+ self.assertTrue(found_buffer)
731
+ model_buffers.pop(i)
732
+
733
+ models_equal = True
734
+ for layer_name, p1 in model_state_dict.items():
735
+ p2 = loaded_model_state_dict[layer_name]
736
+ if p1.data.ne(p2.data).sum() > 0:
737
+ models_equal = False
738
+
739
+ self.assertTrue(models_equal)
740
+
741
+ def test_load_vision_text_config(self):
742
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
743
+
744
+ # Save Pix2StructConfig and check if we can load Pix2StructVisionConfig from it
745
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
746
+ config.save_pretrained(tmp_dir_name)
747
+ vision_config = Pix2StructVisionConfig.from_pretrained(tmp_dir_name)
748
+ self.assertDictEqual(config.vision_config.to_dict(), vision_config.to_dict())
749
+
750
+ # Save Pix2StructConfig and check if we can load Pix2StructTextConfig from it
751
+ with tempfile.TemporaryDirectory() as tmp_dir_name:
752
+ config.save_pretrained(tmp_dir_name)
753
+ text_config = Pix2StructTextConfig.from_pretrained(tmp_dir_name)
754
+ self.assertDictEqual(config.text_config.to_dict(), text_config.to_dict())
755
+
756
+ def _check_encoder_attention_for_generate(self, attentions, batch_size, config, seq_length):
757
+ # overwrite because # pix2struct seq length depends on image inputs
758
+ seq_length = self.model_tester.max_patches
759
+ encoder_expected_shape = (batch_size, config.num_attention_heads, seq_length, seq_length)
760
+ self.assertIsInstance(attentions, tuple)
761
+ self.assertListEqual(
762
+ [layer_attentions.shape for layer_attentions in attentions],
763
+ [encoder_expected_shape] * len(attentions),
764
+ )
765
+
766
+ def _check_encoder_hidden_states_for_generate(self, hidden_states, batch_size, config, seq_length):
767
+ # overwrite because # pix2struct seq length depends on image inputs
768
+ seq_length = self.model_tester.max_patches
769
+ encoder_expected_shape = (batch_size, seq_length, config.hidden_size)
770
+ self.assertIsInstance(hidden_states, tuple)
771
+ self.assertListEqual(
772
+ [layer_hidden_states.shape for layer_hidden_states in hidden_states],
773
+ [encoder_expected_shape] * len(hidden_states),
774
+ )
775
+
776
+
777
+ # We will verify our results on an image of a stop sign
778
+ def prepare_img():
779
+ url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/australia.jpg"
780
+ im = Image.open(requests.get(url, stream=True).raw)
781
+ return im
782
+
783
+
784
+ @require_vision
785
+ @require_torch
786
+ @slow
787
+ class Pix2StructIntegrationTest(unittest.TestCase):
788
+ def test_inference_image_captioning(self):
789
+ model = Pix2StructForConditionalGeneration.from_pretrained("google/pix2struct-textcaps-base").to(torch_device)
790
+ processor = Pix2StructProcessor.from_pretrained("google/pix2struct-textcaps-base")
791
+ image = prepare_img()
792
+
793
+ # image only
794
+ inputs = processor(images=image, return_tensors="pt").to(torch_device)
795
+
796
+ predictions = model.generate(**inputs)
797
+
798
+ self.assertEqual(
799
+ processor.decode(predictions[0], skip_special_tokens=True), "A stop sign is on a street corner."
800
+ )
801
+
802
+ def test_batched_inference_image_captioning(self):
803
+ model = Pix2StructForConditionalGeneration.from_pretrained("google/pix2struct-textcaps-base").to(torch_device)
804
+ processor = Pix2StructProcessor.from_pretrained("google/pix2struct-textcaps-base")
805
+ image_1 = prepare_img()
806
+
807
+ second_url = (
808
+ "https://www.connollycove.com/wp-content/uploads/2019/06/temple-bar-dublin-world-famous-irish-pub.jpg"
809
+ )
810
+ image_2 = Image.open(requests.get(second_url, stream=True).raw)
811
+
812
+ # image only
813
+ inputs = processor(images=[image_1, image_2], return_tensors="pt").to(torch_device)
814
+
815
+ predictions = model.generate(**inputs)
816
+
817
+ self.assertEqual(
818
+ processor.decode(predictions[0], skip_special_tokens=True), "A stop sign is on a street corner."
819
+ )
820
+
821
+ self.assertEqual(
822
+ processor.decode(predictions[1], skip_special_tokens=True),
823
+ "A row of books including The Temple Bar and Guiness.",
824
+ )
825
+
826
+ def test_batched_inference_image_captioning_conditioned(self):
827
+ model = Pix2StructForConditionalGeneration.from_pretrained("google/pix2struct-textcaps-base").to(torch_device)
828
+ processor = Pix2StructProcessor.from_pretrained("google/pix2struct-textcaps-base")
829
+ image_1 = prepare_img()
830
+
831
+ second_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/temple-bar-dublin-world-famous-irish-pub.jpg"
832
+ image_2 = Image.open(requests.get(second_url, stream=True).raw)
833
+ texts = ["A picture of", "An photography of"]
834
+
835
+ # image only
836
+ inputs = processor(images=[image_1, image_2], text=texts, return_tensors="pt", add_special_tokens=False).to(
837
+ torch_device
838
+ )
839
+
840
+ predictions = model.generate(**inputs)
841
+
842
+ self.assertEqual(
843
+ processor.decode(predictions[0], skip_special_tokens=True),
844
+ "A picture of a stop sign with a red stop sign",
845
+ )
846
+
847
+ self.assertEqual(
848
+ processor.decode(predictions[1], skip_special_tokens=True),
849
+ "An photography of the Temple Bar and other places in the city.",
850
+ )
851
+
852
+ def test_vqa_model(self):
853
+ model_id = "google/pix2struct-ai2d-base"
854
+
855
+ image_url = "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg"
856
+ image = Image.open(requests.get(image_url, stream=True).raw)
857
+
858
+ model = Pix2StructForConditionalGeneration.from_pretrained(model_id, torch_dtype=torch.bfloat16).to(
859
+ torch_device
860
+ )
861
+ processor = Pix2StructProcessor.from_pretrained(model_id)
862
+
863
+ # image only
864
+ text = "What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud"
865
+
866
+ inputs = processor(images=image, return_tensors="pt", text=text).to(torch_device, torch.bfloat16)
867
+
868
+ predictions = model.generate(**inputs)
869
+ self.assertEqual(processor.decode(predictions[0], skip_special_tokens=True), "ash cloud")
870
+
871
+ def test_vqa_model_batched(self):
872
+ model_id = "google/pix2struct-ai2d-base"
873
+
874
+ image_urls = [
875
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo.jpg",
876
+ "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/tasks/ai2d-demo-2.png",
877
+ ]
878
+
879
+ images = [Image.open(requests.get(image_url, stream=True).raw) for image_url in image_urls]
880
+
881
+ texts = [
882
+ "What does the label 15 represent? (1) lava (2) core (3) tunnel (4) ash cloud",
883
+ "What is the producer in the diagram? (1) Phytoplankton (2) Zooplankton (3) Large fish (4) Small fish",
884
+ ]
885
+
886
+ model = Pix2StructForConditionalGeneration.from_pretrained(model_id, torch_dtype=torch.bfloat16).to(
887
+ torch_device
888
+ )
889
+ processor = Pix2StructProcessor.from_pretrained(model_id)
890
+
891
+ inputs = processor(images=images, return_tensors="pt", text=texts).to(torch_device, torch.bfloat16)
892
+
893
+ predictions = model.generate(**inputs)
894
+ self.assertEqual(processor.decode(predictions[0], skip_special_tokens=True), "ash cloud")
895
+ self.assertEqual(processor.decode(predictions[1], skip_special_tokens=True), "Phytoplankton")
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pix2struct/test_processor_pix2struct.py ADDED
@@ -0,0 +1,329 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import shutil
15
+ import tempfile
16
+ import unittest
17
+
18
+ import pytest
19
+
20
+ from transformers.testing_utils import require_torch, require_vision
21
+ from transformers.utils import is_vision_available
22
+
23
+ from ...test_processing_common import ProcessorTesterMixin
24
+
25
+
26
+ if is_vision_available():
27
+ from transformers import (
28
+ AutoProcessor,
29
+ Pix2StructImageProcessor,
30
+ Pix2StructProcessor,
31
+ PreTrainedTokenizerFast,
32
+ T5Tokenizer,
33
+ )
34
+
35
+
36
+ @require_vision
37
+ @require_torch
38
+ class Pix2StructProcessorTest(ProcessorTesterMixin, unittest.TestCase):
39
+ processor_class = Pix2StructProcessor
40
+ text_input_name = "decoder_input_ids"
41
+ images_input_name = "flattened_patches"
42
+
43
+ def setUp(self):
44
+ self.tmpdirname = tempfile.mkdtemp()
45
+
46
+ image_processor = Pix2StructImageProcessor()
47
+ tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small")
48
+
49
+ processor = Pix2StructProcessor(image_processor, tokenizer)
50
+
51
+ processor.save_pretrained(self.tmpdirname)
52
+
53
+ def get_tokenizer(self, **kwargs):
54
+ return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).tokenizer
55
+
56
+ def get_image_processor(self, **kwargs):
57
+ return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).image_processor
58
+
59
+ def tearDown(self):
60
+ shutil.rmtree(self.tmpdirname)
61
+
62
+ def test_save_load_pretrained_additional_features(self):
63
+ processor = Pix2StructProcessor(tokenizer=self.get_tokenizer(), image_processor=self.get_image_processor())
64
+ processor.save_pretrained(self.tmpdirname)
65
+
66
+ tokenizer_add_kwargs = self.get_tokenizer(bos_token="(BOS)", eos_token="(EOS)")
67
+ image_processor_add_kwargs = self.get_image_processor(do_normalize=False, padding_value=1.0)
68
+
69
+ processor = Pix2StructProcessor.from_pretrained(
70
+ self.tmpdirname, bos_token="(BOS)", eos_token="(EOS)", do_normalize=False, padding_value=1.0
71
+ )
72
+
73
+ self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab())
74
+ self.assertIsInstance(processor.tokenizer, PreTrainedTokenizerFast)
75
+
76
+ self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string())
77
+ self.assertIsInstance(processor.image_processor, Pix2StructImageProcessor)
78
+
79
+ def test_image_processor(self):
80
+ image_processor = self.get_image_processor()
81
+ tokenizer = self.get_tokenizer()
82
+
83
+ processor = Pix2StructProcessor(tokenizer=tokenizer, image_processor=image_processor)
84
+
85
+ image_input = self.prepare_image_inputs()
86
+
87
+ input_feat_extract = image_processor(image_input, return_tensors="np")
88
+ input_processor = processor(images=image_input, return_tensors="np")
89
+
90
+ for key in input_feat_extract.keys():
91
+ self.assertAlmostEqual(input_feat_extract[key].sum(), input_processor[key].sum(), delta=1e-2)
92
+
93
+ def test_tokenizer(self):
94
+ image_processor = self.get_image_processor()
95
+ tokenizer = self.get_tokenizer()
96
+
97
+ processor = Pix2StructProcessor(tokenizer=tokenizer, image_processor=image_processor)
98
+
99
+ input_str = self.prepare_text_inputs()
100
+
101
+ encoded_processor = processor(text=input_str)
102
+
103
+ encoded_tok = tokenizer(input_str, return_token_type_ids=False, add_special_tokens=True)
104
+
105
+ for key in encoded_tok.keys():
106
+ self.assertListEqual(encoded_tok[key], encoded_processor[key])
107
+
108
+ def test_processor(self):
109
+ image_processor = self.get_image_processor()
110
+ tokenizer = self.get_tokenizer()
111
+
112
+ processor = Pix2StructProcessor(tokenizer=tokenizer, image_processor=image_processor)
113
+
114
+ input_str = self.prepare_text_inputs()
115
+ image_input = self.prepare_image_inputs()
116
+
117
+ inputs = processor(text=input_str, images=image_input)
118
+
119
+ self.assertListEqual(
120
+ list(inputs.keys()), ["flattened_patches", "attention_mask", "decoder_attention_mask", "decoder_input_ids"]
121
+ )
122
+
123
+ # test if it raises when no input is passed
124
+ with pytest.raises(ValueError):
125
+ processor()
126
+
127
+ def test_processor_max_patches(self):
128
+ image_processor = self.get_image_processor()
129
+ tokenizer = self.get_tokenizer()
130
+
131
+ processor = Pix2StructProcessor(tokenizer=tokenizer, image_processor=image_processor)
132
+
133
+ input_str = self.prepare_text_inputs()
134
+ image_input = self.prepare_image_inputs()
135
+
136
+ inputs = processor(text=input_str, images=image_input)
137
+
138
+ max_patches = [512, 1024, 2048, 4096]
139
+ expected_hidden_size = [770, 770, 770, 770]
140
+ # with text
141
+ for i, max_patch in enumerate(max_patches):
142
+ inputs = processor(text=input_str, images=image_input, max_patches=max_patch)
143
+ self.assertEqual(inputs["flattened_patches"][0].shape[0], max_patch)
144
+ self.assertEqual(inputs["flattened_patches"][0].shape[1], expected_hidden_size[i])
145
+
146
+ # without text input
147
+ for i, max_patch in enumerate(max_patches):
148
+ inputs = processor(images=image_input, max_patches=max_patch)
149
+ self.assertEqual(inputs["flattened_patches"][0].shape[0], max_patch)
150
+ self.assertEqual(inputs["flattened_patches"][0].shape[1], expected_hidden_size[i])
151
+
152
+ def test_tokenizer_decode(self):
153
+ image_processor = self.get_image_processor()
154
+ tokenizer = self.get_tokenizer()
155
+
156
+ processor = Pix2StructProcessor(tokenizer=tokenizer, image_processor=image_processor)
157
+
158
+ predicted_ids = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
159
+
160
+ decoded_processor = processor.batch_decode(predicted_ids)
161
+ decoded_tok = tokenizer.batch_decode(predicted_ids)
162
+
163
+ self.assertListEqual(decoded_tok, decoded_processor)
164
+
165
+ def test_model_input_names(self):
166
+ image_processor = self.get_image_processor()
167
+ tokenizer = self.get_tokenizer()
168
+
169
+ processor = Pix2StructProcessor(tokenizer=tokenizer, image_processor=image_processor)
170
+
171
+ input_str = self.prepare_text_inputs()
172
+ image_input = self.prepare_image_inputs()
173
+
174
+ inputs = processor(text=input_str, images=image_input)
175
+
176
+ # For now the processor supports only ["flattened_patches", "input_ids", "attention_mask", "decoder_attention_mask"]
177
+ self.assertListEqual(
178
+ list(inputs.keys()), ["flattened_patches", "attention_mask", "decoder_attention_mask", "decoder_input_ids"]
179
+ )
180
+
181
+ inputs = processor(text=input_str)
182
+
183
+ # For now the processor supports only ["flattened_patches", "input_ids", "attention_mask", "decoder_attention_mask"]
184
+ self.assertListEqual(list(inputs.keys()), ["input_ids", "attention_mask"])
185
+
186
+ @require_torch
187
+ @require_vision
188
+ def test_image_processor_defaults_preserved_by_image_kwargs(self):
189
+ # Rewrite as pix2struct processor return "flattened_patches" and not "pixel_values"
190
+ if "image_processor" not in self.processor_class.attributes:
191
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
192
+ image_processor = self.get_component("image_processor", max_patches=1024, patch_size={"height": 8, "width": 8})
193
+ tokenizer = self.get_component("tokenizer", max_length=117, padding="max_length")
194
+
195
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
196
+ self.skip_processor_without_typed_kwargs(processor)
197
+
198
+ input_str = self.prepare_text_inputs()
199
+ image_input = self.prepare_image_inputs()
200
+
201
+ inputs = processor(text=input_str, images=image_input)
202
+ self.assertEqual(len(inputs["flattened_patches"][0][0]), 194)
203
+
204
+ @require_torch
205
+ @require_vision
206
+ def test_kwargs_overrides_default_image_processor_kwargs(self):
207
+ # Rewrite as pix2struct processor return "flattened_patches" and not "pixel_values"
208
+ if "image_processor" not in self.processor_class.attributes:
209
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
210
+ image_processor = self.get_component("image_processor", max_patches=4096)
211
+ tokenizer = self.get_component("tokenizer", max_length=117, padding="max_length")
212
+
213
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
214
+ self.skip_processor_without_typed_kwargs(processor)
215
+
216
+ input_str = self.prepare_text_inputs()
217
+ image_input = self.prepare_image_inputs()
218
+
219
+ inputs = processor(text=input_str, images=image_input, max_patches=1024)
220
+ self.assertEqual(len(inputs["flattened_patches"][0]), 1024)
221
+
222
+ @require_torch
223
+ @require_vision
224
+ def test_unstructured_kwargs(self):
225
+ # Rewrite as pix2struct processor return "decoder_input_ids" and not "input_ids"
226
+ if "image_processor" not in self.processor_class.attributes:
227
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
228
+ image_processor = self.get_component("image_processor")
229
+ tokenizer = self.get_component("tokenizer")
230
+
231
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
232
+ self.skip_processor_without_typed_kwargs(processor)
233
+
234
+ input_str = self.prepare_text_inputs()
235
+ image_input = self.prepare_image_inputs()
236
+ inputs = processor(
237
+ text=input_str,
238
+ images=image_input,
239
+ return_tensors="pt",
240
+ max_patches=1024,
241
+ padding="max_length",
242
+ max_length=76,
243
+ )
244
+
245
+ self.assertEqual(inputs["flattened_patches"].shape[1], 1024)
246
+ self.assertEqual(len(inputs["decoder_input_ids"][0]), 76)
247
+
248
+ @require_torch
249
+ @require_vision
250
+ def test_unstructured_kwargs_batched(self):
251
+ # Rewrite as pix2struct processor return "decoder_input_ids" and not "input_ids"
252
+ if "image_processor" not in self.processor_class.attributes:
253
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
254
+ image_processor = self.get_component("image_processor")
255
+ tokenizer = self.get_component("tokenizer")
256
+
257
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
258
+ self.skip_processor_without_typed_kwargs(processor)
259
+
260
+ input_str = self.prepare_text_inputs(batch_size=2)
261
+ image_input = self.prepare_image_inputs(batch_size=2)
262
+ inputs = processor(
263
+ text=input_str,
264
+ images=image_input,
265
+ return_tensors="pt",
266
+ max_patches=1024,
267
+ padding="longest",
268
+ max_length=76,
269
+ )
270
+
271
+ self.assertEqual(inputs["flattened_patches"].shape[1], 1024)
272
+
273
+ self.assertEqual(len(inputs["decoder_input_ids"][0]), 5)
274
+
275
+ @require_torch
276
+ @require_vision
277
+ def test_structured_kwargs_nested(self):
278
+ # Rewrite as pix2struct processor return "decoder_input_ids" and not "input_ids"
279
+ if "image_processor" not in self.processor_class.attributes:
280
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
281
+ image_processor = self.get_component("image_processor")
282
+ tokenizer = self.get_component("tokenizer")
283
+
284
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
285
+ self.skip_processor_without_typed_kwargs(processor)
286
+
287
+ input_str = self.prepare_text_inputs()
288
+ image_input = self.prepare_image_inputs()
289
+
290
+ # Define the kwargs for each modality
291
+ all_kwargs = {
292
+ "common_kwargs": {"return_tensors": "pt"},
293
+ "images_kwargs": {"max_patches": 1024},
294
+ "text_kwargs": {"padding": "max_length", "max_length": 76},
295
+ }
296
+
297
+ inputs = processor(text=input_str, images=image_input, **all_kwargs)
298
+ self.skip_processor_without_typed_kwargs(processor)
299
+
300
+ self.assertEqual(inputs["flattened_patches"].shape[1], 1024)
301
+
302
+ self.assertEqual(len(inputs["decoder_input_ids"][0]), 76)
303
+
304
+ @require_torch
305
+ @require_vision
306
+ def test_structured_kwargs_nested_from_dict(self):
307
+ # Rewrite as pix2struct processor return "decoder_input_ids" and not "input_ids"
308
+ if "image_processor" not in self.processor_class.attributes:
309
+ self.skipTest(f"image_processor attribute not present in {self.processor_class}")
310
+
311
+ image_processor = self.get_component("image_processor")
312
+ tokenizer = self.get_component("tokenizer")
313
+
314
+ processor = self.processor_class(tokenizer=tokenizer, image_processor=image_processor)
315
+ self.skip_processor_without_typed_kwargs(processor)
316
+ input_str = self.prepare_text_inputs()
317
+ image_input = self.prepare_image_inputs()
318
+
319
+ # Define the kwargs for each modality
320
+ all_kwargs = {
321
+ "common_kwargs": {"return_tensors": "pt"},
322
+ "images_kwargs": {"max_patches": 1024},
323
+ "text_kwargs": {"padding": "max_length", "max_length": 76},
324
+ }
325
+
326
+ inputs = processor(text=input_str, images=image_input, **all_kwargs)
327
+ self.assertEqual(inputs["flattened_patches"].shape[1], 1024)
328
+
329
+ self.assertEqual(len(inputs["decoder_input_ids"][0]), 76)
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pixtral/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pixtral/test_image_processing_pixtral.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 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 random
17
+ import time
18
+ import unittest
19
+
20
+ import numpy as np
21
+ import requests
22
+ from packaging import version
23
+
24
+ from transformers.testing_utils import (
25
+ require_torch,
26
+ require_torch_gpu,
27
+ require_vision,
28
+ slow,
29
+ torch_device,
30
+ )
31
+ from transformers.utils import is_torch_available, is_torchvision_available, is_vision_available
32
+
33
+ from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs
34
+
35
+
36
+ if is_torch_available():
37
+ import torch
38
+
39
+ if is_vision_available():
40
+ from PIL import Image
41
+
42
+ from transformers import PixtralImageProcessor
43
+
44
+ if is_torchvision_available():
45
+ from transformers import PixtralImageProcessorFast
46
+
47
+
48
+ class PixtralImageProcessingTester:
49
+ def __init__(
50
+ self,
51
+ parent,
52
+ batch_size=7,
53
+ num_channels=3,
54
+ image_size=18,
55
+ max_num_images_per_sample=3,
56
+ min_resolution=30,
57
+ max_resolution=400,
58
+ do_resize=True,
59
+ size=None,
60
+ patch_size=None,
61
+ do_normalize=True,
62
+ image_mean=[0.48145466, 0.4578275, 0.40821073],
63
+ image_std=[0.26862954, 0.26130258, 0.27577711],
64
+ do_convert_rgb=True,
65
+ ):
66
+ super().__init__()
67
+ size = size if size is not None else {"longest_edge": 24}
68
+ patch_size = patch_size if patch_size is not None else {"height": 8, "width": 8}
69
+ self.parent = parent
70
+ self.batch_size = batch_size
71
+ self.num_channels = num_channels
72
+ self.image_size = image_size
73
+ self.max_num_images_per_sample = max_num_images_per_sample
74
+ self.min_resolution = min_resolution
75
+ self.max_resolution = max_resolution
76
+ self.do_resize = do_resize
77
+ self.size = size
78
+ self.patch_size = patch_size
79
+ self.do_normalize = do_normalize
80
+ self.image_mean = image_mean
81
+ self.image_std = image_std
82
+ self.do_convert_rgb = do_convert_rgb
83
+
84
+ def prepare_image_processor_dict(self):
85
+ return {
86
+ "do_resize": self.do_resize,
87
+ "size": self.size,
88
+ "patch_size": self.patch_size,
89
+ "do_normalize": self.do_normalize,
90
+ "image_mean": self.image_mean,
91
+ "image_std": self.image_std,
92
+ "do_convert_rgb": self.do_convert_rgb,
93
+ }
94
+
95
+ def expected_output_image_shape(self, image):
96
+ if isinstance(image, Image.Image):
97
+ width, height = image.size
98
+ elif isinstance(image, np.ndarray):
99
+ height, width = image.shape[:2]
100
+ elif isinstance(image, torch.Tensor):
101
+ height, width = image.shape[-2:]
102
+
103
+ max_height = max_width = self.size.get("longest_edge")
104
+
105
+ ratio = max(height / max_height, width / max_width)
106
+ if ratio > 1:
107
+ height = int(np.ceil(height / ratio))
108
+ width = int(np.ceil(width / ratio))
109
+
110
+ patch_height, patch_width = self.patch_size["height"], self.patch_size["width"]
111
+ num_height_tokens = (height - 1) // patch_height + 1
112
+ num_width_tokens = (width - 1) // patch_width + 1
113
+
114
+ height = num_height_tokens * patch_height
115
+ width = num_width_tokens * patch_width
116
+
117
+ return self.num_channels, height, width
118
+
119
+ def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
120
+ # Use prepare_image_inputs to make a list of list of single images
121
+
122
+ images_list = []
123
+ for _ in range(self.batch_size):
124
+ images = []
125
+ for _ in range(random.randint(1, self.max_num_images_per_sample)):
126
+ img = prepare_image_inputs(
127
+ batch_size=1,
128
+ num_channels=self.num_channels,
129
+ min_resolution=self.min_resolution,
130
+ max_resolution=self.max_resolution,
131
+ equal_resolution=equal_resolution,
132
+ numpify=numpify,
133
+ torchify=torchify,
134
+ )[0]
135
+ images.append(img)
136
+ images_list.append(images)
137
+ return images_list
138
+
139
+
140
+ @require_torch
141
+ @require_vision
142
+ class PixtralImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
143
+ image_processing_class = PixtralImageProcessor if is_vision_available() else None
144
+ fast_image_processing_class = PixtralImageProcessorFast if is_torchvision_available() else None
145
+
146
+ def setUp(self):
147
+ super().setUp()
148
+ self.image_processor_tester = PixtralImageProcessingTester(self)
149
+
150
+ @property
151
+ def image_processor_dict(self):
152
+ return self.image_processor_tester.prepare_image_processor_dict()
153
+
154
+ def test_image_processor_properties(self):
155
+ for image_processing_class in self.image_processor_list:
156
+ image_processing = image_processing_class(**self.image_processor_dict)
157
+ self.assertTrue(hasattr(image_processing, "do_resize"))
158
+ self.assertTrue(hasattr(image_processing, "size"))
159
+ self.assertTrue(hasattr(image_processing, "patch_size"))
160
+ self.assertTrue(hasattr(image_processing, "do_rescale"))
161
+ self.assertTrue(hasattr(image_processing, "rescale_factor"))
162
+ self.assertTrue(hasattr(image_processing, "do_normalize"))
163
+ self.assertTrue(hasattr(image_processing, "image_mean"))
164
+ self.assertTrue(hasattr(image_processing, "image_std"))
165
+ self.assertTrue(hasattr(image_processing, "do_convert_rgb"))
166
+
167
+ # The following tests are overriden as PixtralImageProcessor can return images of different sizes
168
+ # and thus doesn't support returning batched tensors
169
+
170
+ def test_call_pil(self):
171
+ for image_processing_class in self.image_processor_list:
172
+ # Initialize image_processing
173
+ image_processing = image_processing_class(**self.image_processor_dict)
174
+ # create random PIL images
175
+ image_inputs_list = self.image_processor_tester.prepare_image_inputs()
176
+ for image_inputs in image_inputs_list:
177
+ for image in image_inputs:
178
+ self.assertIsInstance(image, Image.Image)
179
+
180
+ # Test not batched input
181
+ encoded_images = image_processing(image_inputs_list[0][0], return_tensors="pt").pixel_values
182
+ expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(
183
+ image_inputs_list[0][0]
184
+ )
185
+ self.assertEqual(tuple(encoded_images[0][0].shape), expected_output_image_shape)
186
+
187
+ # Test batched
188
+ batch_encoded_images = image_processing(image_inputs_list, return_tensors="pt").pixel_values
189
+ for encoded_images, images in zip(batch_encoded_images, image_inputs_list):
190
+ for encoded_image, image in zip(encoded_images, images):
191
+ expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image)
192
+ self.assertEqual(tuple(encoded_image.shape), expected_output_image_shape)
193
+
194
+ def test_call_numpy(self):
195
+ for image_processing_class in self.image_processor_list:
196
+ # Initialize image_processing
197
+ image_processing = image_processing_class(**self.image_processor_dict)
198
+ # create random numpy tensors
199
+ image_inputs_list = self.image_processor_tester.prepare_image_inputs(numpify=True)
200
+ for image_inputs in image_inputs_list:
201
+ for image in image_inputs:
202
+ self.assertIsInstance(image, np.ndarray)
203
+
204
+ # Test not batched input
205
+ encoded_images = image_processing(image_inputs_list[0][0], return_tensors="pt").pixel_values
206
+ expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(
207
+ image_inputs_list[0][0]
208
+ )
209
+ self.assertEqual(tuple(encoded_images[0][0].shape), expected_output_image_shape)
210
+
211
+ # Test batched
212
+ batch_encoded_images = image_processing(image_inputs_list, return_tensors="pt").pixel_values
213
+ for encoded_images, images in zip(batch_encoded_images, image_inputs_list):
214
+ for encoded_image, image in zip(encoded_images, images):
215
+ expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image)
216
+ self.assertEqual(tuple(encoded_image.shape), expected_output_image_shape)
217
+
218
+ def test_call_pytorch(self):
219
+ for image_processing_class in self.image_processor_list:
220
+ # Initialize image_processing
221
+ image_processing = image_processing_class(**self.image_processor_dict)
222
+ # create random PyTorch tensors
223
+ image_inputs_list = self.image_processor_tester.prepare_image_inputs(torchify=True)
224
+ for image_inputs in image_inputs_list:
225
+ for image in image_inputs:
226
+ self.assertIsInstance(image, torch.Tensor)
227
+
228
+ # Test not batched input
229
+ encoded_images = image_processing(image_inputs_list[0][0], return_tensors="pt").pixel_values
230
+ expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(
231
+ image_inputs_list[0][0]
232
+ )
233
+ self.assertEqual(tuple(encoded_images[0][0].shape), expected_output_image_shape)
234
+
235
+ # Test batched
236
+ batch_encoded_images = image_processing(image_inputs_list, return_tensors="pt").pixel_values
237
+ for encoded_images, images in zip(batch_encoded_images, image_inputs_list):
238
+ for encoded_image, image in zip(encoded_images, images):
239
+ expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image)
240
+ self.assertEqual(tuple(encoded_image.shape), expected_output_image_shape)
241
+
242
+ @require_vision
243
+ @require_torch
244
+ def test_fast_is_faster_than_slow(self):
245
+ if not self.test_slow_image_processor or not self.test_fast_image_processor:
246
+ self.skipTest(reason="Skipping speed test")
247
+
248
+ if self.image_processing_class is None or self.fast_image_processing_class is None:
249
+ self.skipTest(reason="Skipping speed test as one of the image processors is not defined")
250
+
251
+ def measure_time(image_processor, image):
252
+ start = time.time()
253
+ _ = image_processor(image, return_tensors="pt")
254
+ return time.time() - start
255
+
256
+ image_inputs_list = self.image_processor_tester.prepare_image_inputs(torchify=True)
257
+ image_processor_slow = self.image_processing_class(**self.image_processor_dict)
258
+ image_processor_fast = self.fast_image_processing_class(**self.image_processor_dict)
259
+
260
+ fast_time = measure_time(image_processor_fast, image_inputs_list)
261
+ slow_time = measure_time(image_processor_slow, image_inputs_list)
262
+
263
+ self.assertLessEqual(fast_time, slow_time)
264
+
265
+ @require_vision
266
+ @require_torch
267
+ def test_slow_fast_equivalence(self):
268
+ dummy_image = Image.open(
269
+ requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw
270
+ )
271
+
272
+ if not self.test_slow_image_processor or not self.test_fast_image_processor:
273
+ self.skipTest(reason="Skipping slow/fast equivalence test")
274
+
275
+ if self.image_processing_class is None or self.fast_image_processing_class is None:
276
+ self.skipTest(reason="Skipping slow/fast equivalence test as one of the image processors is not defined")
277
+
278
+ image_processor_slow = self.image_processing_class(**self.image_processor_dict)
279
+ image_processor_fast = self.fast_image_processing_class(**self.image_processor_dict)
280
+
281
+ encoding_slow = image_processor_slow(dummy_image, return_tensors="pt")
282
+ encoding_fast = image_processor_fast(dummy_image, return_tensors="pt")
283
+
284
+ self.assertTrue(torch.allclose(encoding_slow.pixel_values[0][0], encoding_fast.pixel_values[0][0], atol=1e-2))
285
+
286
+ @slow
287
+ @require_torch_gpu
288
+ @require_vision
289
+ def test_can_compile_fast_image_processor(self):
290
+ if self.fast_image_processing_class is None:
291
+ self.skipTest("Skipping compilation test as fast image processor is not defined")
292
+ if version.parse(torch.__version__) < version.parse("2.3"):
293
+ self.skipTest(reason="This test requires torch >= 2.3 to run.")
294
+
295
+ torch.compiler.reset()
296
+ input_image = torch.randint(0, 255, (3, 224, 224), dtype=torch.uint8)
297
+ image_processor = self.fast_image_processing_class(**self.image_processor_dict)
298
+ output_eager = image_processor(input_image, device=torch_device, return_tensors="pt")
299
+
300
+ image_processor = torch.compile(image_processor, mode="reduce-overhead")
301
+ output_compiled = image_processor(input_image, device=torch_device, return_tensors="pt")
302
+
303
+ self.assertTrue(torch.allclose(output_eager.pixel_values[0][0], output_compiled.pixel_values[0][0], atol=1e-4))
304
+
305
+ @unittest.skip(reason="PixtralImageProcessor doesn't treat 4 channel PIL and numpy consistently yet") # FIXME Amy
306
+ def test_call_numpy_4_channels(self):
307
+ pass
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pixtral/test_modeling_pixtral.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Pixtral model."""
16
+
17
+ import unittest
18
+
19
+ from transformers import (
20
+ PixtralVisionConfig,
21
+ PixtralVisionModel,
22
+ is_torch_available,
23
+ is_vision_available,
24
+ )
25
+ from transformers.testing_utils import (
26
+ require_torch,
27
+ torch_device,
28
+ )
29
+
30
+ from ...test_configuration_common import ConfigTester
31
+ from ...test_modeling_common import ModelTesterMixin, floats_tensor
32
+
33
+
34
+ if is_torch_available():
35
+ import torch
36
+
37
+
38
+ if is_vision_available():
39
+ pass
40
+
41
+
42
+ class PixtralVisionModelTester:
43
+ def __init__(
44
+ self,
45
+ parent,
46
+ batch_size=12,
47
+ image_size=30,
48
+ patch_size=2,
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 PixtralVisionConfig(
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 = PixtralVisionModel(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
+ self.parent.assertEqual(result.pooler_output.shape, (self.batch_size, self.hidden_size))
114
+
115
+ def create_and_check_model_with_projection(self, config, pixel_values):
116
+ model = PixtralVisionModel(config=config)
117
+ model.to(torch_device)
118
+ model.eval()
119
+ with torch.no_grad():
120
+ result = model(pixel_values)
121
+ # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
122
+ image_size = (self.image_size, self.image_size)
123
+ patch_size = (self.patch_size, self.patch_size)
124
+ num_patches = (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
125
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, num_patches + 1, self.hidden_size))
126
+ self.parent.assertEqual(result.image_embeds.shape, (self.batch_size, self.projection_dim))
127
+
128
+ def prepare_config_and_inputs_for_common(self):
129
+ config_and_inputs = self.prepare_config_and_inputs()
130
+ config, pixel_values = config_and_inputs
131
+ inputs_dict = {"pixel_values": pixel_values}
132
+ return config, inputs_dict
133
+
134
+
135
+ @require_torch
136
+ class PixtralVisionModelModelTest(ModelTesterMixin, unittest.TestCase):
137
+ """
138
+ Model tester for `PixtralVisionModel`.
139
+ """
140
+
141
+ all_model_classes = (PixtralVisionModel,) if is_torch_available() else ()
142
+ test_pruning = False
143
+ test_head_masking = False
144
+ test_torchscript = False
145
+
146
+ def setUp(self):
147
+ self.model_tester = PixtralVisionModelTester(self)
148
+ self.config_tester = ConfigTester(self, config_class=PixtralVisionConfig, has_text_modality=False)
149
+
150
+ @unittest.skip("model does not support input embeds")
151
+ def test_inputs_embeds(self):
152
+ pass
153
+
154
+ @unittest.skip("model does not support input embeds")
155
+ def test_inputs_embeds_matches_input_ids(self):
156
+ pass
157
+
158
+ @unittest.skip(
159
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
160
+ )
161
+ def test_training_gradient_checkpointing(self):
162
+ pass
163
+
164
+ @unittest.skip(
165
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
166
+ )
167
+ def test_training_gradient_checkpointing_use_reentrant(self):
168
+ pass
169
+
170
+ @unittest.skip(
171
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
172
+ )
173
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
174
+ pass
175
+
176
+ @unittest.skip(reason="Compile not yet supported because in Pixtral models")
177
+ def test_sdpa_can_compile_dynamic(self):
178
+ pass
179
+
180
+ @unittest.skip(reason="Compile not yet supported because in Pixtral models")
181
+ def test_sdpa_can_dispatch_on_flash(self):
182
+ pass
183
+
184
+ @unittest.skip(reason="Not supported yet")
185
+ def test_attention_outputs(self):
186
+ pass
187
+
188
+ @unittest.skip(reason="Not supported yet")
189
+ def test_cpu_offload(self):
190
+ pass
191
+
192
+ @unittest.skip(reason="Not supported yet")
193
+ def test_batching_equivalence(self):
194
+ pass
195
+
196
+ @unittest.skip(reason="Not supported yet")
197
+ def test_disk_offload_bin(self):
198
+ pass
199
+
200
+ @unittest.skip(reason="Not supported yet")
201
+ def test_retain_grad_hidden_states_attentions(self):
202
+ pass
203
+
204
+ @unittest.skip(reason="Not supported yet")
205
+ def test_multi_gpu_data_parallel_forward(self):
206
+ pass
207
+
208
+ @unittest.skip(reason="Not supported yet")
209
+ def test_model_parallelism(self):
210
+ pass
211
+
212
+ @unittest.skip(reason="Not supported yet")
213
+ def test_model_outputs_equivalence(self):
214
+ pass
215
+
216
+ @unittest.skip(reason="Not supported yet")
217
+ def test_save_load(self):
218
+ pass
219
+
220
+ @unittest.skip(reason="Not supported yet")
221
+ def test_model_get_set_embeddings(self):
222
+ pass
223
+
224
+ @unittest.skip(reason="Not supported yet")
225
+ def test_resize_tokens_embeddings(self):
226
+ pass
227
+
228
+ @unittest.skip(reason="Not supported yet")
229
+ def test_model_main_input_name(self):
230
+ pass
231
+
232
+ @unittest.skip(reason="Not supported yet")
233
+ def test_initialization(self):
234
+ pass
235
+
236
+ @unittest.skip(reason="Not supported yet")
237
+ def test_hidden_states_output(self):
238
+ pass
239
+
240
+ @unittest.skip(reason="Not supported yet")
241
+ def test_gradient_checkpointing_backward_compatibility(self):
242
+ pass
243
+
244
+ @unittest.skip(reason="Not supported yet")
245
+ def test_feed_forward_chunking(self):
246
+ pass
247
+
248
+ @unittest.skip(reason="Not supported yet")
249
+ def test_disk_offload_safetensors(self):
250
+ pass
251
+
252
+ @unittest.skip(reason="Not supported yet")
253
+ def test_determinism(self):
254
+ pass
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/pixtral/test_processor_pixtral.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 shutil
15
+ import tempfile
16
+ import unittest
17
+ from typing import Optional
18
+
19
+ import requests
20
+ import torch
21
+
22
+ from transformers.testing_utils import require_vision
23
+ from transformers.utils import is_vision_available
24
+
25
+ from ...test_processing_common import ProcessorTesterMixin
26
+
27
+
28
+ if is_vision_available():
29
+ from PIL import Image
30
+
31
+ from transformers import AutoTokenizer, PixtralImageProcessor, PixtralProcessor
32
+
33
+
34
+ @require_vision
35
+ class PixtralProcessorTest(ProcessorTesterMixin, unittest.TestCase):
36
+ processor_class = PixtralProcessor
37
+
38
+ @classmethod
39
+ def setUpClass(cls):
40
+ cls.url_0 = "https://www.ilankelman.org/stopsigns/australia.jpg"
41
+ cls.image_0 = Image.open(requests.get(cls.url_0, stream=True).raw)
42
+ cls.url_1 = "http://images.cocodataset.org/val2017/000000039769.jpg"
43
+ cls.image_1 = Image.open(requests.get(cls.url_1, stream=True).raw)
44
+ cls.url_2 = "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg"
45
+ cls.image_2 = Image.open(requests.get(cls.url_2, stream=True).raw)
46
+
47
+ def setUp(self):
48
+ self.tmpdirname = tempfile.mkdtemp()
49
+
50
+ # FIXME - just load the processor directly from the checkpoint
51
+ tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/pixtral-12b")
52
+ image_processor = PixtralImageProcessor()
53
+ processor = PixtralProcessor(tokenizer=tokenizer, image_processor=image_processor)
54
+ processor.save_pretrained(self.tmpdirname)
55
+
56
+ def tearDown(self):
57
+ shutil.rmtree(self.tmpdirname)
58
+
59
+ @unittest.skip("No chat template was set for this model (yet)")
60
+ def test_chat_template(self):
61
+ processor = self.processor_class.from_pretrained(self.tmpdirname)
62
+ expected_prompt = "USER: [IMG]\nWhat is shown in this image? ASSISTANT:"
63
+
64
+ messages = [
65
+ {
66
+ "role": "user",
67
+ "content": [
68
+ {"type": "image"},
69
+ {"type": "text", "text": "What is shown in this image?"},
70
+ ],
71
+ },
72
+ ]
73
+ formatted_prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
74
+ self.assertEqual(expected_prompt, formatted_prompt)
75
+
76
+ @unittest.skip("No chat template was set for this model (yet)")
77
+ def test_image_token_filling(self):
78
+ processor = self.processor_class.from_pretrained(self.tmpdirname)
79
+ # Important to check with non square image
80
+ image = torch.randint(0, 2, (3, 500, 316))
81
+ expected_image_tokens = 1526
82
+ image_token_index = 32000
83
+
84
+ messages = [
85
+ {
86
+ "role": "user",
87
+ "content": [
88
+ {"type": "image"},
89
+ {"type": "text", "text": "What is shown in this image?"},
90
+ ],
91
+ },
92
+ ]
93
+ inputs = processor(
94
+ text=[processor.apply_chat_template(messages)],
95
+ images=[image],
96
+ return_tensors="pt",
97
+ )
98
+ image_tokens = (inputs["input_ids"] == image_token_index).sum().item()
99
+ self.assertEqual(expected_image_tokens, image_tokens)
100
+
101
+ def test_processor_with_single_image(self):
102
+ processor = self.processor_class.from_pretrained(self.tmpdirname)
103
+ prompt_string = "USER: [IMG]\nWhat's the content of the image? ASSISTANT:"
104
+
105
+ # Make small for checking image token expansion
106
+ processor.image_processor.size = {"longest_edge": 30}
107
+ processor.image_processor.patch_size = {"height": 2, "width": 2}
108
+
109
+ # Test passing in an image
110
+ inputs_image = processor(text=prompt_string, images=self.image_0, return_tensors="pt")
111
+ self.assertIn("input_ids", inputs_image)
112
+ self.assertTrue(len(inputs_image["input_ids"]) == 1)
113
+ self.assertIsInstance(inputs_image["input_ids"], torch.Tensor)
114
+ self.assertIsInstance(inputs_image["pixel_values"], list)
115
+ self.assertTrue(len(inputs_image["pixel_values"]) == 1)
116
+ self.assertIsInstance(inputs_image["pixel_values"][0], list)
117
+ self.assertTrue(len(inputs_image["pixel_values"][0]) == 1)
118
+ self.assertIsInstance(inputs_image["pixel_values"][0][0], torch.Tensor)
119
+
120
+ # fmt: off
121
+ input_ids = inputs_image["input_ids"]
122
+ self.assertEqual(
123
+ input_ids[0].tolist(),
124
+ # Equivalent to "USER: [IMG][IMG][IMG_BREAK][IMG][IMG][IMG_END]\nWhat's the content of the image? ASSISTANT:"
125
+ [21510, 1058, 1032, 10, 10, 12, 10, 10, 13, 1010, 7493, 1681, 1278, 4701, 1307, 1278, 3937, 1063, 1349, 4290, 16002, 41150, 1058]
126
+ )
127
+ # fmt: on
128
+
129
+ # Test passing in a url
130
+ inputs_url = processor(text=prompt_string, images=self.url_0, return_tensors="pt")
131
+ self.assertIn("input_ids", inputs_url)
132
+ self.assertTrue(len(inputs_url["input_ids"]) == 1)
133
+ self.assertIsInstance(inputs_url["input_ids"], torch.Tensor)
134
+ self.assertIsInstance(inputs_url["pixel_values"], list)
135
+ self.assertTrue(len(inputs_url["pixel_values"]) == 1)
136
+ self.assertIsInstance(inputs_url["pixel_values"][0], list)
137
+ self.assertTrue(len(inputs_url["pixel_values"][0]) == 1)
138
+ self.assertIsInstance(inputs_url["pixel_values"][0][0], torch.Tensor)
139
+
140
+ # fmt: off
141
+ input_ids = inputs_url["input_ids"]
142
+ self.assertEqual(
143
+ input_ids[0].tolist(),
144
+ # Equivalent to "USER: [IMG][IMG][IMG_BREAK][IMG][IMG][IMG_END]\nWhat's the content of the image? ASSISTANT:"
145
+ [21510, 1058, 1032, 10, 10, 12, 10, 10, 13, 1010, 7493, 1681, 1278, 4701, 1307, 1278, 3937, 1063, 1349, 4290, 16002, 41150, 1058]
146
+ )
147
+ # fmt: on
148
+
149
+ def test_processor_with_multiple_images_single_list(self):
150
+ processor = self.processor_class.from_pretrained(self.tmpdirname)
151
+ prompt_string = "USER: [IMG][IMG]\nWhat's the difference between these two images? ASSISTANT:"
152
+
153
+ # Make small for checking image token expansion
154
+ processor.image_processor.size = {"longest_edge": 30}
155
+ processor.image_processor.patch_size = {"height": 2, "width": 2}
156
+
157
+ # Test passing in an image
158
+ inputs_image = processor(text=prompt_string, images=[self.image_0, self.image_1], return_tensors="pt")
159
+ self.assertIn("input_ids", inputs_image)
160
+ self.assertTrue(len(inputs_image["input_ids"]) == 1)
161
+ self.assertIsInstance(inputs_image["input_ids"], torch.Tensor)
162
+ self.assertIsInstance(inputs_image["pixel_values"], list)
163
+ self.assertTrue(len(inputs_image["pixel_values"]) == 1)
164
+ self.assertIsInstance(inputs_image["pixel_values"][0], list)
165
+ self.assertTrue(len(inputs_image["pixel_values"][0]) == 2)
166
+ self.assertIsInstance(inputs_image["pixel_values"][0][0], torch.Tensor)
167
+
168
+ # fmt: off
169
+ input_ids = inputs_image["input_ids"]
170
+ self.assertEqual(
171
+ input_ids[0].tolist(),
172
+ # Equivalent to ["USER: [IMG][IMG][IMG_BREAK][IMG][IMG][IMG_END][IMG][IMG][IMG_BREAK][IMG][IMG][IMG_END]\nWhat's the difference between these two images? ASSISTANT:"]
173
+ [21510, 1058, 1032, 10, 10, 12, 10, 10, 13, 10, 10, 12, 10, 10, 13, 1010, 7493, 1681, 1278, 6592, 2396, 2576, 2295, 8061, 1063, 1349, 4290, 16002, 41150, 1058]
174
+ )
175
+ # fmt: on
176
+
177
+ # Test passing in a url
178
+ inputs_url = processor(text=prompt_string, images=[self.url_0, self.url_1], return_tensors="pt")
179
+ self.assertIn("input_ids", inputs_url)
180
+ self.assertTrue(len(inputs_url["input_ids"]) == 1)
181
+ self.assertIsInstance(inputs_url["input_ids"], torch.Tensor)
182
+ self.assertIsInstance(inputs_url["pixel_values"], list)
183
+ self.assertTrue(len(inputs_url["pixel_values"]) == 1)
184
+ self.assertIsInstance(inputs_url["pixel_values"][0], list)
185
+ self.assertTrue(len(inputs_url["pixel_values"][0]) == 2)
186
+ self.assertIsInstance(inputs_url["pixel_values"][0][0], torch.Tensor)
187
+ # fmt: off
188
+ input_ids = inputs_url["input_ids"]
189
+ self.assertEqual(
190
+ input_ids[0].tolist(),
191
+ # Equivalent to ["USER: [IMG][IMG][IMG_BREAK][IMG][IMG][IMG_END][IMG][IMG][IMG_BREAK][IMG][IMG][IMG_END]\nWhat's the difference between these two images? ASSISTANT:"]
192
+ [21510, 1058, 1032, 10, 10, 12, 10, 10, 13, 10, 10, 12, 10, 10, 13, 1010, 7493, 1681, 1278, 6592, 2396, 2576, 2295, 8061, 1063, 1349, 4290, 16002, 41150, 1058]
193
+ )
194
+ # fmt: on
195
+
196
+ def test_processor_with_multiple_images_multiple_lists(self):
197
+ processor = self.processor_class.from_pretrained(self.tmpdirname)
198
+ prompt_string = [
199
+ "USER: [IMG][IMG]\nWhat's the difference between these two images? ASSISTANT:",
200
+ "USER: [IMG]\nWhat's the content of the image? ASSISTANT:",
201
+ ]
202
+ processor.tokenizer.pad_token = "</s>"
203
+ image_inputs = [[self.image_0, self.image_1], [self.image_2]]
204
+
205
+ # Make small for checking image token expansion
206
+ processor.image_processor.size = {"longest_edge": 30}
207
+ processor.image_processor.patch_size = {"height": 2, "width": 2}
208
+
209
+ # Test passing in an image
210
+ inputs_image = processor(text=prompt_string, images=image_inputs, return_tensors="pt", padding=True)
211
+ self.assertIn("input_ids", inputs_image)
212
+ self.assertTrue(len(inputs_image["input_ids"]) == 2)
213
+ self.assertIsInstance(inputs_image["input_ids"], torch.Tensor)
214
+ self.assertIsInstance(inputs_image["pixel_values"], list)
215
+ self.assertTrue(len(inputs_image["pixel_values"]) == 2)
216
+ self.assertIsInstance(inputs_image["pixel_values"][0], list)
217
+ self.assertTrue(len(inputs_image["pixel_values"][0]) == 2)
218
+ self.assertIsInstance(inputs_image["pixel_values"][0][0], torch.Tensor)
219
+
220
+ # fmt: off
221
+ input_ids = inputs_image["input_ids"]
222
+ self.assertEqual(
223
+ input_ids[0].tolist(),
224
+ # Equivalent to ["USER: [IMG][IMG][IMG_BREAK][IMG][IMG][IMG_END][IMG][IMG][IMG_BREAK][IMG][IMG][IMG_END]\nWhat's the difference between these two images? ASSISTANT:"]
225
+ [21510, 1058, 1032, 10, 10, 12, 10, 10, 13, 10, 10, 12, 10, 10, 13, 1010, 7493, 1681, 1278, 6592, 2396, 2576, 2295, 8061, 1063, 1349, 4290, 16002, 41150, 1058]
226
+ )
227
+ # fmt: on
228
+
229
+ # Test passing in a url
230
+ inputs_url = processor(text=prompt_string, images=image_inputs, return_tensors="pt", padding=True)
231
+ self.assertIn("input_ids", inputs_url)
232
+ self.assertTrue(len(inputs_url["input_ids"]) == 2)
233
+ self.assertIsInstance(inputs_url["input_ids"], torch.Tensor)
234
+ self.assertIsInstance(inputs_url["pixel_values"], list)
235
+ self.assertTrue(len(inputs_url["pixel_values"]) == 2)
236
+ self.assertIsInstance(inputs_url["pixel_values"][0], list)
237
+ self.assertTrue(len(inputs_url["pixel_values"][0]) == 2)
238
+ self.assertIsInstance(inputs_url["pixel_values"][0][0], torch.Tensor)
239
+
240
+ # fmt: off
241
+ input_ids = inputs_url["input_ids"]
242
+ self.assertEqual(
243
+ input_ids[0].tolist(),
244
+ # Equivalent to ["USER: [IMG][IMG][IMG_BREAK][IMG][IMG][IMG_END][IMG][IMG][IMG_BREAK][IMG][IMG][IMG_END]\nWhat's the difference between these two images? ASSISTANT:"]
245
+ [21510, 1058, 1032, 10, 10, 12, 10, 10, 13, 10, 10, 12, 10, 10, 13, 1010, 7493, 1681, 1278, 6592, 2396, 2576, 2295, 8061, 1063, 1349, 4290, 16002, 41150, 1058]
246
+ )
247
+ # fmt: on
248
+
249
+ def test_processor_returns_full_length_batches(self):
250
+ # to avoid https://github.com/huggingface/transformers/issues/34204
251
+ processor = self.processor_class.from_pretrained(self.tmpdirname)
252
+ prompt_string = [
253
+ "USER: [IMG]\nWhat's the content of the image? ASSISTANT:",
254
+ ] * 5
255
+ processor.tokenizer.pad_token = "</s>"
256
+ image_inputs = [self.image_0] * 5
257
+
258
+ # Make small for checking image token expansion
259
+ processor.image_processor.size = {"longest_edge": 30}
260
+ processor.image_processor.patch_size = {"height": 2, "width": 2}
261
+
262
+ # Test passing in an image
263
+ inputs_image = processor(text=prompt_string, images=image_inputs, return_tensors="pt", padding=True)
264
+ self.assertIn("input_ids", inputs_image)
265
+ self.assertTrue(len(inputs_image["input_ids"]) == 5)
266
+ self.assertTrue(len(inputs_image["pixel_values"]) == 5)
267
+
268
+ # Override as PixtralProcessor needs nested images to work properly with batched inputs
269
+ @require_vision
270
+ def prepare_image_inputs(self, batch_size: Optional[int] = None):
271
+ """This function prepares a list of PIL images for testing"""
272
+ if batch_size is None:
273
+ return super().prepare_image_inputs()
274
+ if batch_size < 1:
275
+ raise ValueError("batch_size must be greater than 0")
276
+ return [[super().prepare_image_inputs()]] * batch_size
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/plbart/__init__.py ADDED
File without changes
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/plbart/test_modeling_plbart.py ADDED
@@ -0,0 +1,682 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 PLBART model."""
16
+
17
+ import copy
18
+ import tempfile
19
+ import unittest
20
+
21
+ from transformers import PLBartConfig, is_torch_available
22
+ from transformers.testing_utils import (
23
+ require_sentencepiece,
24
+ require_tokenizers,
25
+ require_torch,
26
+ require_torch_fp16,
27
+ slow,
28
+ torch_device,
29
+ )
30
+ from transformers.utils import cached_property
31
+
32
+ from ...generation.test_utils import GenerationTesterMixin
33
+ from ...test_configuration_common import ConfigTester
34
+ from ...test_modeling_common import ModelTesterMixin, ids_tensor
35
+ from ...test_pipeline_mixin import PipelineTesterMixin
36
+
37
+
38
+ if is_torch_available():
39
+ import torch
40
+
41
+ from transformers import (
42
+ AutoTokenizer,
43
+ PLBartForCausalLM,
44
+ PLBartForConditionalGeneration,
45
+ PLBartForSequenceClassification,
46
+ PLBartModel,
47
+ )
48
+ from transformers.models.plbart.modeling_plbart import PLBartDecoder, PLBartEncoder
49
+
50
+
51
+ def prepare_plbart_inputs_dict(
52
+ config,
53
+ input_ids,
54
+ decoder_input_ids,
55
+ attention_mask=None,
56
+ decoder_attention_mask=None,
57
+ head_mask=None,
58
+ decoder_head_mask=None,
59
+ cross_attn_head_mask=None,
60
+ ):
61
+ if attention_mask is None:
62
+ attention_mask = input_ids.ne(config.pad_token_id)
63
+ if decoder_attention_mask is None:
64
+ decoder_attention_mask = decoder_input_ids.ne(config.pad_token_id)
65
+ if head_mask is None:
66
+ head_mask = torch.ones(config.encoder_layers, config.encoder_attention_heads, device=torch_device)
67
+ if decoder_head_mask is None:
68
+ decoder_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads, device=torch_device)
69
+ if cross_attn_head_mask is None:
70
+ cross_attn_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads, device=torch_device)
71
+ return {
72
+ "input_ids": input_ids,
73
+ "decoder_input_ids": decoder_input_ids,
74
+ "attention_mask": attention_mask,
75
+ "decoder_attention_mask": attention_mask,
76
+ "head_mask": head_mask,
77
+ "decoder_head_mask": decoder_head_mask,
78
+ "cross_attn_head_mask": cross_attn_head_mask,
79
+ }
80
+
81
+
82
+ class PLBartModelTester:
83
+ def __init__(
84
+ self,
85
+ parent,
86
+ batch_size=13,
87
+ seq_length=7,
88
+ is_training=True,
89
+ use_labels=False,
90
+ vocab_size=99,
91
+ hidden_size=16,
92
+ num_hidden_layers=2,
93
+ num_attention_heads=4,
94
+ intermediate_size=4,
95
+ hidden_act="gelu",
96
+ hidden_dropout_prob=0.1,
97
+ attention_probs_dropout_prob=0.1,
98
+ max_position_embeddings=100,
99
+ eos_token_id=2,
100
+ pad_token_id=1,
101
+ bos_token_id=0,
102
+ ):
103
+ self.parent = parent
104
+ self.batch_size = batch_size
105
+ self.seq_length = seq_length
106
+ self.is_training = is_training
107
+ self.use_labels = use_labels
108
+ self.vocab_size = vocab_size
109
+ self.hidden_size = hidden_size
110
+ self.num_hidden_layers = num_hidden_layers
111
+ self.num_attention_heads = num_attention_heads
112
+ self.intermediate_size = intermediate_size
113
+ self.hidden_act = hidden_act
114
+ self.hidden_dropout_prob = hidden_dropout_prob
115
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
116
+ self.max_position_embeddings = max_position_embeddings
117
+ self.eos_token_id = eos_token_id
118
+ self.pad_token_id = pad_token_id
119
+ self.bos_token_id = bos_token_id
120
+
121
+ def prepare_config_and_inputs(self):
122
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
123
+ input_ids = input_ids.clamp(3)
124
+ input_ids[:, -1] = self.eos_token_id # Eos Token
125
+
126
+ decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
127
+
128
+ config = self.get_config()
129
+ inputs_dict = prepare_plbart_inputs_dict(config, input_ids, decoder_input_ids)
130
+ return config, inputs_dict
131
+
132
+ def get_config(self):
133
+ return PLBartConfig(
134
+ vocab_size=self.vocab_size,
135
+ d_model=self.hidden_size,
136
+ encoder_layers=self.num_hidden_layers,
137
+ decoder_layers=self.num_hidden_layers,
138
+ encoder_attention_heads=self.num_attention_heads,
139
+ decoder_attention_heads=self.num_attention_heads,
140
+ encoder_ffn_dim=self.intermediate_size,
141
+ decoder_ffn_dim=self.intermediate_size,
142
+ dropout=self.hidden_dropout_prob,
143
+ attention_dropout=self.attention_probs_dropout_prob,
144
+ max_position_embeddings=self.max_position_embeddings,
145
+ eos_token_id=self.eos_token_id,
146
+ bos_token_id=self.bos_token_id,
147
+ pad_token_id=self.pad_token_id,
148
+ )
149
+
150
+ def prepare_config_and_inputs_for_common(self):
151
+ config, inputs_dict = self.prepare_config_and_inputs()
152
+ return config, inputs_dict
153
+
154
+ def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict):
155
+ model = PLBartModel(config=config).get_decoder().to(torch_device).eval()
156
+ input_ids = inputs_dict["input_ids"]
157
+ attention_mask = inputs_dict["attention_mask"]
158
+ head_mask = inputs_dict["head_mask"]
159
+
160
+ # first forward pass
161
+ outputs = model(input_ids, attention_mask=attention_mask, head_mask=head_mask, use_cache=True)
162
+
163
+ output, past_key_values = outputs.to_tuple()
164
+
165
+ # create hypothetical multiple next token and extent to next_input_ids
166
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
167
+ next_attn_mask = ids_tensor((self.batch_size, 3), 2)
168
+
169
+ # append to next input_ids and
170
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
171
+ next_attention_mask = torch.cat([attention_mask, next_attn_mask], dim=-1)
172
+
173
+ output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"]
174
+ output_with_past_key_values = model(
175
+ next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values
176
+ )
177
+ output_from_past = output_with_past_key_values["last_hidden_state"]
178
+
179
+ # select random slice
180
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
181
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
182
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
183
+
184
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
185
+
186
+ # test that outputs are equal for slice
187
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
188
+
189
+ def check_encoder_decoder_model_standalone(self, config, inputs_dict):
190
+ model = PLBartModel(config=config).to(torch_device).eval()
191
+ outputs = model(**inputs_dict)
192
+
193
+ encoder_last_hidden_state = outputs.encoder_last_hidden_state
194
+ last_hidden_state = outputs.last_hidden_state
195
+
196
+ with tempfile.TemporaryDirectory() as tmpdirname:
197
+ encoder = model.get_encoder()
198
+ encoder.save_pretrained(tmpdirname)
199
+ encoder = PLBartEncoder.from_pretrained(tmpdirname).to(torch_device)
200
+
201
+ encoder_last_hidden_state_2 = encoder(inputs_dict["input_ids"], attention_mask=inputs_dict["attention_mask"])[
202
+ 0
203
+ ]
204
+
205
+ self.parent.assertTrue((encoder_last_hidden_state_2 - encoder_last_hidden_state).abs().max().item() < 1e-3)
206
+
207
+ with tempfile.TemporaryDirectory() as tmpdirname:
208
+ decoder = model.get_decoder()
209
+ decoder.save_pretrained(tmpdirname)
210
+ decoder = PLBartDecoder.from_pretrained(tmpdirname).to(torch_device)
211
+
212
+ last_hidden_state_2 = decoder(
213
+ input_ids=inputs_dict["decoder_input_ids"],
214
+ attention_mask=inputs_dict["decoder_attention_mask"],
215
+ encoder_hidden_states=encoder_last_hidden_state,
216
+ encoder_attention_mask=inputs_dict["attention_mask"],
217
+ )[0]
218
+
219
+ self.parent.assertTrue((last_hidden_state_2 - last_hidden_state).abs().max().item() < 1e-3)
220
+
221
+
222
+ @require_torch
223
+ class PLBartModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
224
+ all_model_classes = (
225
+ (PLBartModel, PLBartForConditionalGeneration, PLBartForSequenceClassification) if is_torch_available() else ()
226
+ )
227
+ all_generative_model_classes = (PLBartForConditionalGeneration,) if is_torch_available() else ()
228
+ pipeline_model_mapping = (
229
+ {
230
+ "feature-extraction": PLBartModel,
231
+ "summarization": PLBartForConditionalGeneration,
232
+ "text-classification": PLBartForSequenceClassification,
233
+ "text-generation": PLBartForCausalLM,
234
+ "text2text-generation": PLBartForConditionalGeneration,
235
+ "translation": PLBartForConditionalGeneration,
236
+ "zero-shot": PLBartForSequenceClassification,
237
+ }
238
+ if is_torch_available()
239
+ else {}
240
+ )
241
+ is_encoder_decoder = True
242
+ fx_compatible = False # Fix me Michael
243
+ test_pruning = False
244
+ test_missing_keys = False
245
+
246
+ # TODO: Fix the failed tests
247
+ def is_pipeline_test_to_skip(
248
+ self,
249
+ pipeline_test_case_name,
250
+ config_class,
251
+ model_architecture,
252
+ tokenizer_name,
253
+ image_processor_name,
254
+ feature_extractor_name,
255
+ processor_name,
256
+ ):
257
+ if pipeline_test_case_name == "TranslationPipelineTests":
258
+ # Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`.
259
+ # `PLBartConfig` was never used in pipeline tests: cannot create a simple tokenizer.
260
+ return True
261
+
262
+ return False
263
+
264
+ def setUp(self):
265
+ self.model_tester = PLBartModelTester(self)
266
+ self.config_tester = ConfigTester(self, config_class=PLBartConfig)
267
+
268
+ def test_config(self):
269
+ self.config_tester.run_common_tests()
270
+
271
+ def test_save_load_strict(self):
272
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
273
+ for model_class in self.all_model_classes:
274
+ model = model_class(config)
275
+
276
+ with tempfile.TemporaryDirectory() as tmpdirname:
277
+ model.save_pretrained(tmpdirname)
278
+ model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True)
279
+ self.assertEqual(info["missing_keys"], [])
280
+
281
+ def test_decoder_model_past_with_large_inputs(self):
282
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
283
+ self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
284
+
285
+ def test_encoder_decoder_model_standalone(self):
286
+ config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common()
287
+ self.model_tester.check_encoder_decoder_model_standalone(*config_and_inputs)
288
+
289
+ # PLBartForSequenceClassification does not support inputs_embeds
290
+ def test_inputs_embeds(self):
291
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
292
+
293
+ for model_class in (PLBartModel, PLBartForConditionalGeneration):
294
+ model = model_class(config)
295
+ model.to(torch_device)
296
+ model.eval()
297
+
298
+ inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class))
299
+
300
+ if not self.is_encoder_decoder:
301
+ input_ids = inputs["input_ids"]
302
+ del inputs["input_ids"]
303
+ else:
304
+ encoder_input_ids = inputs["input_ids"]
305
+ decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids)
306
+ del inputs["input_ids"]
307
+ inputs.pop("decoder_input_ids", None)
308
+
309
+ wte = model.get_input_embeddings()
310
+ if not self.is_encoder_decoder:
311
+ inputs["inputs_embeds"] = wte(input_ids)
312
+ else:
313
+ inputs["inputs_embeds"] = wte(encoder_input_ids)
314
+ inputs["decoder_inputs_embeds"] = wte(decoder_input_ids)
315
+
316
+ with torch.no_grad():
317
+ model(**inputs)[0]
318
+
319
+ @require_torch_fp16
320
+ def test_generate_fp16(self):
321
+ config, input_dict = self.model_tester.prepare_config_and_inputs()
322
+ input_ids = input_dict["input_ids"]
323
+ attention_mask = input_ids.ne(1).to(torch_device)
324
+ model = PLBartForConditionalGeneration(config).eval().to(torch_device)
325
+ model.half()
326
+ model.generate(input_ids, attention_mask=attention_mask)
327
+ model.generate(num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3)
328
+
329
+ @unittest.skip(reason="Failing since #26752")
330
+ def test_sample_generate(self):
331
+ pass
332
+
333
+ @unittest.skip(
334
+ reason="This architecure has tied weights by default and there is no way to remove it, check: https://github.com/huggingface/transformers/pull/31771#issuecomment-2210915245"
335
+ )
336
+ def test_load_save_without_tied_weights(self):
337
+ pass
338
+
339
+
340
+ def assert_tensors_close(a, b, atol=1e-12, prefix=""):
341
+ """If tensors have different shapes, different values or a and b are not both tensors, raise a nice Assertion error."""
342
+ if a is None and b is None:
343
+ return True
344
+ try:
345
+ if torch.allclose(a, b, atol=atol):
346
+ return True
347
+ raise
348
+ except Exception:
349
+ pct_different = (torch.gt((a - b).abs(), atol)).float().mean().item()
350
+ if a.numel() > 100:
351
+ msg = f"tensor values are {pct_different:.1%} percent different."
352
+ else:
353
+ msg = f"{a} != {b}"
354
+ if prefix:
355
+ msg = prefix + ": " + msg
356
+ raise AssertionError(msg)
357
+
358
+
359
+ def _long_tensor(tok_lst):
360
+ return torch.tensor(tok_lst, dtype=torch.long, device=torch_device)
361
+
362
+
363
+ @require_torch
364
+ @require_sentencepiece
365
+ @require_tokenizers
366
+ class AbstractSeq2SeqIntegrationTest(unittest.TestCase):
367
+ maxDiff = 1000 # longer string compare tracebacks
368
+ checkpoint_name = None
369
+
370
+ @classmethod
371
+ def setUpClass(cls):
372
+ cls.tokenizer = AutoTokenizer.from_pretrained(cls.checkpoint_name, use_fast=False)
373
+ return cls
374
+
375
+ @cached_property
376
+ def model(self):
377
+ """Only load the model if needed."""
378
+ model = PLBartForConditionalGeneration.from_pretrained(self.checkpoint_name).to(torch_device)
379
+ if "cuda" in torch_device:
380
+ model = model.half()
381
+ return model
382
+
383
+
384
+ @require_torch
385
+ @require_sentencepiece
386
+ @require_tokenizers
387
+ class PLBartJavaCsIntegrationTest(AbstractSeq2SeqIntegrationTest):
388
+ checkpoint_name = "uclanlp/plbart-java-cs"
389
+ src_text = [
390
+ "public int maximum(int a, int b, int c){return Math.max(a, Math.max(b, c));}",
391
+ "public int product(int a, int b, int c){return a*b*c;}",
392
+ ]
393
+ tgt_text = [
394
+ "public int maximum(int a, int b, int c){return Math.Max(",
395
+ "public int Product(int a, int b, int c){return a * b *",
396
+ ]
397
+
398
+ @slow
399
+ def test_java_cs_generate_one(self):
400
+ batch = self.tokenizer(
401
+ ["public int maximum(int a, int b, int c){return Math.max(a, Math.max(b, c));}"], return_tensors="pt"
402
+ )
403
+ batch = batch.to(torch_device)
404
+ translated_tokens = self.model.generate(**batch)
405
+ decoded = self.tokenizer.batch_decode(translated_tokens, skip_special_tokens=True)
406
+ self.assertEqual(self.tgt_text[0], decoded[0])
407
+ # self.assertEqual(self.tgt_text[1], decoded[1])
408
+
409
+ @slow
410
+ def test_java_cs_generate_batch(self):
411
+ batch = self.tokenizer(self.src_text, return_tensors="pt", padding=True, truncation=True)
412
+ batch = batch.to(torch_device)
413
+ translated_tokens = self.model.generate(**batch)
414
+ decoded = self.tokenizer.batch_decode(translated_tokens, skip_special_tokens=True)
415
+ assert self.tgt_text == decoded
416
+
417
+ def test_plbart_java_cs_config(self):
418
+ plbart_models = ["uclanlp/plbart-java-cs"]
419
+ expected = {"scale_embedding": True}
420
+ for name in plbart_models:
421
+ config = PLBartConfig.from_pretrained(name)
422
+ for k, v in expected.items():
423
+ try:
424
+ self.assertEqual(v, getattr(config, k))
425
+ except AssertionError as e:
426
+ e.args += (name, k)
427
+ raise
428
+
429
+ def test_plbart_fast_forward(self):
430
+ config = PLBartConfig(
431
+ vocab_size=99,
432
+ d_model=24,
433
+ encoder_layers=2,
434
+ decoder_layers=2,
435
+ encoder_attention_heads=2,
436
+ decoder_attention_heads=2,
437
+ encoder_ffn_dim=32,
438
+ decoder_ffn_dim=32,
439
+ max_position_embeddings=48,
440
+ add_final_layer_norm=True,
441
+ )
442
+ lm_model = PLBartForConditionalGeneration(config).to(torch_device)
443
+ context = torch.tensor(
444
+ [[71, 82, 18, 33, 46, 91, 2], [68, 34, 26, 58, 30, 2, 1]], device=torch_device, dtype=torch.long
445
+ )
446
+ summary = torch.tensor([[82, 71, 82, 18, 2], [58, 68, 2, 1, 1]], device=torch_device, dtype=torch.long)
447
+ result = lm_model(input_ids=context, decoder_input_ids=summary, labels=summary)
448
+ expected_shape = (*summary.shape, config.vocab_size)
449
+ self.assertEqual(result.logits.shape, expected_shape)
450
+
451
+
452
+ @require_torch
453
+ @require_sentencepiece
454
+ @require_tokenizers
455
+ class PLBartBaseIntegrationTest(AbstractSeq2SeqIntegrationTest):
456
+ checkpoint_name = "uclanlp/plbart-base"
457
+ src_text = ["Is 0 the first Fibonacci number ?", "Find the sum of all prime numbers ."]
458
+ tgt_text = ["0 the first Fibonacci number?", "the sum of all prime numbers.......... the the"]
459
+
460
+ def test_base_generate(self):
461
+ inputs = self.tokenizer([self.src_text[0]], return_tensors="pt").to(torch_device)
462
+ src_lan = self.tokenizer._convert_lang_code_special_format("en_XX")
463
+ translated_tokens = self.model.generate(
464
+ input_ids=inputs["input_ids"].to(torch_device),
465
+ decoder_start_token_id=self.tokenizer.lang_code_to_id[src_lan],
466
+ )
467
+ decoded = self.tokenizer.batch_decode(translated_tokens, skip_special_tokens=True)
468
+ self.assertEqual(self.tgt_text[0], decoded[0])
469
+
470
+ @slow
471
+ def test_fill_mask(self):
472
+ inputs = self.tokenizer(["Is 0 the <mask> Fibonacci <mask> ?"], return_tensors="pt").to(torch_device)
473
+ src_lan = self.tokenizer._convert_lang_code_special_format("en_XX")
474
+ outputs = self.model.generate(
475
+ inputs["input_ids"], decoder_start_token_id=self.tokenizer.lang_code_to_id[src_lan], num_beams=1
476
+ )
477
+ prediction: str = self.tokenizer.batch_decode(
478
+ outputs, clean_up_tokenization_spaces=True, skip_special_tokens=True
479
+ )[0]
480
+ self.assertEqual(prediction, "0 0 the 0 the 0 the 0 the 0 the 0 the 0 the 0 the")
481
+
482
+
483
+ class PLBartStandaloneDecoderModelTester:
484
+ def __init__(
485
+ self,
486
+ parent,
487
+ vocab_size=99,
488
+ batch_size=13,
489
+ d_model=16,
490
+ decoder_seq_length=7,
491
+ is_training=True,
492
+ is_decoder=True,
493
+ use_attention_mask=True,
494
+ use_cache=False,
495
+ use_labels=True,
496
+ decoder_start_token_id=2,
497
+ decoder_ffn_dim=32,
498
+ decoder_layers=2,
499
+ encoder_attention_heads=4,
500
+ decoder_attention_heads=4,
501
+ max_position_embeddings=30,
502
+ is_encoder_decoder=False,
503
+ pad_token_id=0,
504
+ bos_token_id=1,
505
+ eos_token_id=2,
506
+ scope=None,
507
+ ):
508
+ self.parent = parent
509
+ self.batch_size = batch_size
510
+ self.decoder_seq_length = decoder_seq_length
511
+ # For common tests
512
+ self.seq_length = self.decoder_seq_length
513
+ self.is_training = is_training
514
+ self.use_attention_mask = use_attention_mask
515
+ self.use_labels = use_labels
516
+
517
+ self.vocab_size = vocab_size
518
+ self.d_model = d_model
519
+ self.hidden_size = d_model
520
+ self.num_hidden_layers = decoder_layers
521
+ self.decoder_layers = decoder_layers
522
+ self.decoder_ffn_dim = decoder_ffn_dim
523
+ self.encoder_attention_heads = encoder_attention_heads
524
+ self.decoder_attention_heads = decoder_attention_heads
525
+ self.num_attention_heads = decoder_attention_heads
526
+ self.eos_token_id = eos_token_id
527
+ self.bos_token_id = bos_token_id
528
+ self.pad_token_id = pad_token_id
529
+ self.decoder_start_token_id = decoder_start_token_id
530
+ self.use_cache = use_cache
531
+ self.max_position_embeddings = max_position_embeddings
532
+ self.is_encoder_decoder = is_encoder_decoder
533
+
534
+ self.scope = None
535
+ self.decoder_key_length = decoder_seq_length
536
+ self.base_model_out_len = 2
537
+ self.decoder_attention_idx = 1
538
+
539
+ def prepare_config_and_inputs(self):
540
+ input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)
541
+
542
+ attention_mask = None
543
+ if self.use_attention_mask:
544
+ attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2)
545
+
546
+ lm_labels = None
547
+ if self.use_labels:
548
+ lm_labels = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)
549
+
550
+ config = PLBartConfig(
551
+ vocab_size=self.vocab_size,
552
+ d_model=self.d_model,
553
+ decoder_layers=self.decoder_layers,
554
+ decoder_ffn_dim=self.decoder_ffn_dim,
555
+ encoder_attention_heads=self.encoder_attention_heads,
556
+ decoder_attention_heads=self.decoder_attention_heads,
557
+ eos_token_id=self.eos_token_id,
558
+ bos_token_id=self.bos_token_id,
559
+ use_cache=self.use_cache,
560
+ pad_token_id=self.pad_token_id,
561
+ decoder_start_token_id=self.decoder_start_token_id,
562
+ max_position_embeddings=self.max_position_embeddings,
563
+ is_encoder_decoder=self.is_encoder_decoder,
564
+ )
565
+
566
+ return (config, input_ids, attention_mask, lm_labels)
567
+
568
+ def create_and_check_decoder_model_past(
569
+ self,
570
+ config,
571
+ input_ids,
572
+ attention_mask,
573
+ lm_labels,
574
+ ):
575
+ config.use_cache = True
576
+ model = PLBartDecoder(config=config).to(torch_device).eval()
577
+ # first forward pass
578
+ outputs = model(input_ids, use_cache=True)
579
+ outputs_use_cache_conf = model(input_ids)
580
+ outputs_no_past = model(input_ids, use_cache=False)
581
+
582
+ self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))
583
+ self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)
584
+
585
+ past_key_values = outputs["past_key_values"]
586
+
587
+ # create hypothetical next token and extent to next_input_ids
588
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
589
+
590
+ # append to next input_ids and
591
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
592
+
593
+ output_from_no_past = model(next_input_ids)["last_hidden_state"]
594
+ output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"]
595
+
596
+ # select random slice
597
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
598
+ output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
599
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
600
+
601
+ # test that outputs are equal for slice
602
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
603
+
604
+ def create_and_check_decoder_model_attention_mask_past(
605
+ self,
606
+ config,
607
+ input_ids,
608
+ attention_mask,
609
+ lm_labels,
610
+ ):
611
+ model = PLBartDecoder(config=config).to(torch_device).eval()
612
+
613
+ # create attention mask
614
+ attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
615
+
616
+ half_seq_length = input_ids.shape[-1] // 2
617
+ attn_mask[:, half_seq_length:] = 0
618
+
619
+ # first forward pass
620
+ past_key_values = model(input_ids, attention_mask=attn_mask, use_cache=True)["past_key_values"]
621
+
622
+ # create hypothetical next token and extent to next_input_ids
623
+ next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
624
+
625
+ # change a random masked slice from input_ids
626
+ random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1
627
+ random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1)
628
+ input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens
629
+
630
+ # append to next input_ids and attn_mask
631
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
632
+ attn_mask = torch.cat(
633
+ [attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)],
634
+ dim=1,
635
+ )
636
+
637
+ # get two different outputs
638
+ output_from_no_past = model(next_input_ids, attention_mask=attn_mask)["last_hidden_state"]
639
+ output_from_past = model(next_tokens, attention_mask=attn_mask, past_key_values=past_key_values)[
640
+ "last_hidden_state"
641
+ ]
642
+
643
+ # select random slice
644
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
645
+ output_from_no_past_slice = output_from_no_past[:, next_input_ids.shape[-1] - 1, random_slice_idx].detach()
646
+ output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
647
+
648
+ # test that outputs are equal for slice
649
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
650
+
651
+ def prepare_config_and_inputs_for_common(self):
652
+ config_and_inputs = self.prepare_config_and_inputs()
653
+ (config, input_ids, attention_mask, lm_labels) = config_and_inputs
654
+ inputs_dict = {"input_ids": input_ids, "attention_mask": attention_mask}
655
+ return config, inputs_dict
656
+
657
+
658
+ @require_torch
659
+ class PLBartStandaloneDecoderModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
660
+ all_model_classes = (PLBartDecoder, PLBartForCausalLM) if is_torch_available() else ()
661
+ all_generative_model_classes = (PLBartForCausalLM,) if is_torch_available() else ()
662
+ test_pruning = False
663
+ is_encoder_decoder = False
664
+
665
+ def setUp(self):
666
+ self.model_tester = PLBartStandaloneDecoderModelTester(self, is_training=False)
667
+ self.config_tester = ConfigTester(self, config_class=PLBartConfig)
668
+
669
+ def test_config(self):
670
+ self.config_tester.run_common_tests()
671
+
672
+ def test_decoder_model_past(self):
673
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
674
+ self.model_tester.create_and_check_decoder_model_past(*config_and_inputs)
675
+
676
+ def test_decoder_model_attn_mask_past(self):
677
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
678
+ self.model_tester.create_and_check_decoder_model_attention_mask_past(*config_and_inputs)
679
+
680
+ @unittest.skip(reason="Decoder cannot keep gradients")
681
+ def test_retain_grad_hidden_states_attentions(self):
682
+ return
tasks/tasksmith-5dd11b34cce1/tests/source/tests/models/plbart/test_tokenization_plbart.py ADDED
@@ -0,0 +1,376 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
15
+ import tempfile
16
+ import unittest
17
+
18
+ from transformers import SPIECE_UNDERLINE, BatchEncoding, PLBartTokenizer, is_torch_available
19
+ from transformers.testing_utils import (
20
+ get_tests_dir,
21
+ nested_simplify,
22
+ require_sentencepiece,
23
+ require_tokenizers,
24
+ require_torch,
25
+ )
26
+
27
+ from ...test_tokenization_common import TokenizerTesterMixin
28
+
29
+
30
+ SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model")
31
+
32
+
33
+ if is_torch_available():
34
+ from transformers.models.plbart.modeling_plbart import shift_tokens_right
35
+
36
+ EN_CODE = 50003
37
+ PYTHON_CODE = 50002
38
+
39
+
40
+ @require_sentencepiece
41
+ @require_tokenizers
42
+ class PLBartTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
43
+ from_pretrained_id = "uclanlp/plbart-base"
44
+ tokenizer_class = PLBartTokenizer
45
+ rust_tokenizer_class = None
46
+ test_rust_tokenizer = False
47
+
48
+ def setUp(self):
49
+ super().setUp()
50
+
51
+ # We have a SentencePiece fixture for testing
52
+ tokenizer = PLBartTokenizer(SAMPLE_VOCAB, language_codes="base", keep_accents=True)
53
+ tokenizer.save_pretrained(self.tmpdirname)
54
+
55
+ def test_full_base_tokenizer(self):
56
+ tokenizer = PLBartTokenizer(SAMPLE_VOCAB, language_codes="base", keep_accents=True)
57
+
58
+ tokens = tokenizer.tokenize("This is a test")
59
+ self.assertListEqual(tokens, ["▁This", "▁is", "▁a", "▁t", "est"])
60
+
61
+ self.assertListEqual(
62
+ tokenizer.convert_tokens_to_ids(tokens),
63
+ [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]],
64
+ )
65
+
66
+ tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.")
67
+ self.assertListEqual(
68
+ tokens,
69
+ [
70
+ SPIECE_UNDERLINE + "I",
71
+ SPIECE_UNDERLINE + "was",
72
+ SPIECE_UNDERLINE + "b",
73
+ "or",
74
+ "n",
75
+ SPIECE_UNDERLINE + "in",
76
+ SPIECE_UNDERLINE + "",
77
+ "9",
78
+ "2",
79
+ "0",
80
+ "0",
81
+ "0",
82
+ ",",
83
+ SPIECE_UNDERLINE + "and",
84
+ SPIECE_UNDERLINE + "this",
85
+ SPIECE_UNDERLINE + "is",
86
+ SPIECE_UNDERLINE + "f",
87
+ "al",
88
+ "s",
89
+ "é",
90
+ ".",
91
+ ],
92
+ )
93
+ ids = tokenizer.convert_tokens_to_ids(tokens)
94
+ self.assertListEqual(
95
+ ids,
96
+ [
97
+ value + tokenizer.fairseq_offset
98
+ for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4]
99
+ ],
100
+ )
101
+
102
+ back_tokens = tokenizer.convert_ids_to_tokens(ids)
103
+ self.assertListEqual(
104
+ back_tokens,
105
+ [
106
+ SPIECE_UNDERLINE + "I",
107
+ SPIECE_UNDERLINE + "was",
108
+ SPIECE_UNDERLINE + "b",
109
+ "or",
110
+ "n",
111
+ SPIECE_UNDERLINE + "in",
112
+ SPIECE_UNDERLINE + "",
113
+ "<unk>",
114
+ "2",
115
+ "0",
116
+ "0",
117
+ "0",
118
+ ",",
119
+ SPIECE_UNDERLINE + "and",
120
+ SPIECE_UNDERLINE + "this",
121
+ SPIECE_UNDERLINE + "is",
122
+ SPIECE_UNDERLINE + "f",
123
+ "al",
124
+ "s",
125
+ "<unk>",
126
+ ".",
127
+ ],
128
+ )
129
+
130
+ end = tokenizer.vocab_size
131
+ language_tokens = [tokenizer.convert_ids_to_tokens(x) for x in range(end - 4, end)]
132
+
133
+ self.assertListEqual(language_tokens, ["__java__", "__python__", "__en_XX__", "<mask>"])
134
+
135
+ code = "java.lang.Exception, python.lang.Exception, javascript, php, ruby, go"
136
+ input_ids = tokenizer(code).input_ids
137
+ self.assertEqual(
138
+ tokenizer.decode(input_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False),
139
+ code,
140
+ )
141
+
142
+ def test_full_multi_tokenizer(self):
143
+ tokenizer = PLBartTokenizer(SAMPLE_VOCAB, language_codes="multi", keep_accents=True)
144
+
145
+ tokens = tokenizer.tokenize("This is a test")
146
+ self.assertListEqual(tokens, ["▁This", "▁is", "▁a", "▁t", "est"])
147
+
148
+ self.assertListEqual(
149
+ tokenizer.convert_tokens_to_ids(tokens),
150
+ [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]],
151
+ )
152
+
153
+ tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.")
154
+ self.assertListEqual(
155
+ tokens,
156
+ [
157
+ SPIECE_UNDERLINE + "I",
158
+ SPIECE_UNDERLINE + "was",
159
+ SPIECE_UNDERLINE + "b",
160
+ "or",
161
+ "n",
162
+ SPIECE_UNDERLINE + "in",
163
+ SPIECE_UNDERLINE + "",
164
+ "9",
165
+ "2",
166
+ "0",
167
+ "0",
168
+ "0",
169
+ ",",
170
+ SPIECE_UNDERLINE + "and",
171
+ SPIECE_UNDERLINE + "this",
172
+ SPIECE_UNDERLINE + "is",
173
+ SPIECE_UNDERLINE + "f",
174
+ "al",
175
+ "s",
176
+ "é",
177
+ ".",
178
+ ],
179
+ )
180
+ ids = tokenizer.convert_tokens_to_ids(tokens)
181
+ self.assertListEqual(
182
+ ids,
183
+ [
184
+ value + tokenizer.fairseq_offset
185
+ for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4]
186
+ ],
187
+ )
188
+
189
+ back_tokens = tokenizer.convert_ids_to_tokens(ids)
190
+ self.assertListEqual(
191
+ back_tokens,
192
+ [
193
+ SPIECE_UNDERLINE + "I",
194
+ SPIECE_UNDERLINE + "was",
195
+ SPIECE_UNDERLINE + "b",
196
+ "or",
197
+ "n",
198
+ SPIECE_UNDERLINE + "in",
199
+ SPIECE_UNDERLINE + "",
200
+ "<unk>",
201
+ "2",
202
+ "0",
203
+ "0",
204
+ "0",
205
+ ",",
206
+ SPIECE_UNDERLINE + "and",
207
+ SPIECE_UNDERLINE + "this",
208
+ SPIECE_UNDERLINE + "is",
209
+ SPIECE_UNDERLINE + "f",
210
+ "al",
211
+ "s",
212
+ "<unk>",
213
+ ".",
214
+ ],
215
+ )
216
+ end = tokenizer.vocab_size
217
+ language_tokens = [tokenizer.convert_ids_to_tokens(x) for x in range(end - 7, end)]
218
+
219
+ self.assertListEqual(
220
+ language_tokens, ["__java__", "__python__", "__en_XX__", "__javascript__", "__php__", "__ruby__", "__go__"]
221
+ )
222
+ code = "java.lang.Exception, python.lang.Exception, javascript, php, ruby, go"
223
+ input_ids = tokenizer(code).input_ids
224
+ self.assertEqual(
225
+ tokenizer.decode(input_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False),
226
+ code,
227
+ )
228
+
229
+
230
+ @require_torch
231
+ @require_sentencepiece
232
+ @require_tokenizers
233
+ class PLBartPythonEnIntegrationTest(unittest.TestCase):
234
+ checkpoint_name = "uclanlp/plbart-python-en_XX"
235
+ src_text = [
236
+ "def maximum(a,b,c):NEW_LINE_INDENTreturn max([a,b,c])",
237
+ "def sum(a,b,c):NEW_LINE_INDENTreturn sum([a,b,c])",
238
+ ]
239
+ tgt_text = [
240
+ "Returns the maximum value of a b c.",
241
+ "Sums the values of a b c.",
242
+ ]
243
+ expected_src_tokens = [
244
+ 134,
245
+ 5452,
246
+ 33460,
247
+ 33441,
248
+ 33463,
249
+ 33465,
250
+ 33463,
251
+ 33449,
252
+ 988,
253
+ 20,
254
+ 33456,
255
+ 19,
256
+ 33456,
257
+ 771,
258
+ 39,
259
+ 4258,
260
+ 889,
261
+ 3318,
262
+ 33441,
263
+ 33463,
264
+ 33465,
265
+ 33463,
266
+ 33449,
267
+ 2471,
268
+ 2,
269
+ PYTHON_CODE,
270
+ ]
271
+
272
+ @classmethod
273
+ def setUpClass(cls):
274
+ cls.tokenizer: PLBartTokenizer = PLBartTokenizer.from_pretrained(
275
+ cls.checkpoint_name, language_codes="base", src_lang="python", tgt_lang="en_XX"
276
+ )
277
+ cls.pad_token_id = 1
278
+ return cls
279
+
280
+ def check_language_codes(self):
281
+ self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["__java__"], 50001)
282
+ self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["__python__"], 50002)
283
+ self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["__en_XX__"], 50003)
284
+
285
+ def test_python_en_tokenizer_batch_encode_plus(self):
286
+ ids = self.tokenizer.batch_encode_plus(self.src_text).input_ids[0]
287
+ self.assertListEqual(self.expected_src_tokens, ids)
288
+
289
+ def test_python_en_tokenizer_decode_ignores_language_codes(self):
290
+ self.assertIn(PYTHON_CODE, self.tokenizer.all_special_ids)
291
+ generated_ids = [EN_CODE, 9037, 33442, 57, 752, 153, 14, 56, 18, 9, 2]
292
+ result = self.tokenizer.decode(generated_ids, skip_special_tokens=True)
293
+ expected_english = self.tokenizer.decode(generated_ids[1:], skip_special_tokens=True)
294
+ self.assertEqual(result, expected_english)
295
+ self.assertNotIn(self.tokenizer.eos_token, result)
296
+
297
+ def test_python_en_tokenizer_truncation(self):
298
+ src_text = ["def sum(a,b,c):NEW_LINE_INDENTreturn sum([a,b,c])" * 20]
299
+ self.assertIsInstance(src_text[0], str)
300
+ desired_max_length = 10
301
+ ids = self.tokenizer(src_text, max_length=desired_max_length, truncation=True).input_ids[0]
302
+ self.assertEqual(ids[-2], 2)
303
+ self.assertEqual(ids[-1], PYTHON_CODE)
304
+ self.assertEqual(len(ids), desired_max_length)
305
+
306
+ def test_mask_token(self):
307
+ self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["<mask>", "__java__"]), [50004, 50001])
308
+
309
+ def test_special_tokens_unaffacted_by_save_load(self):
310
+ tmpdirname = tempfile.mkdtemp()
311
+ original_special_tokens = self.tokenizer.fairseq_tokens_to_ids
312
+ self.tokenizer.save_pretrained(tmpdirname)
313
+ new_tok = PLBartTokenizer.from_pretrained(tmpdirname)
314
+ self.assertDictEqual(new_tok.fairseq_tokens_to_ids, original_special_tokens)
315
+
316
+ @require_torch
317
+ def test_batch_fairseq_parity(self):
318
+ batch = self.tokenizer(self.src_text, text_target=self.tgt_text, padding=True, return_tensors="pt")
319
+ batch["decoder_input_ids"] = shift_tokens_right(batch["labels"], self.tokenizer.pad_token_id)
320
+
321
+ # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4
322
+ self.assertEqual(batch.input_ids[1][-2:].tolist(), [2, PYTHON_CODE])
323
+ self.assertEqual(batch.decoder_input_ids[1][0], EN_CODE)
324
+ self.assertEqual(batch.decoder_input_ids[1][-1], 2)
325
+ self.assertEqual(batch.labels[1][-2:].tolist(), [2, EN_CODE])
326
+
327
+ @require_torch
328
+ def test_python_en_tokenizer_prepare_batch(self):
329
+ batch = self.tokenizer(
330
+ self.src_text,
331
+ text_target=self.tgt_text,
332
+ padding=True,
333
+ truncation=True,
334
+ max_length=len(self.expected_src_tokens),
335
+ return_tensors="pt",
336
+ )
337
+ batch["decoder_input_ids"] = shift_tokens_right(batch["labels"], self.tokenizer.pad_token_id)
338
+
339
+ self.assertIsInstance(batch, BatchEncoding)
340
+
341
+ self.assertEqual((2, 26), batch.input_ids.shape)
342
+ self.assertEqual((2, 26), batch.attention_mask.shape)
343
+ result = batch.input_ids.tolist()[0]
344
+ self.assertListEqual(self.expected_src_tokens, result)
345
+ self.assertEqual(2, batch.decoder_input_ids[0, -1]) # EOS
346
+ # Test that special tokens are reset
347
+ self.assertEqual(self.tokenizer.prefix_tokens, [])
348
+ self.assertEqual(self.tokenizer.suffix_tokens, [self.tokenizer.eos_token_id, PYTHON_CODE])
349
+
350
+ def test_seq2seq_max_length(self):
351
+ batch = self.tokenizer(self.src_text, padding=True, truncation=True, max_length=3, return_tensors="pt")
352
+ targets = self.tokenizer(
353
+ text_target=self.tgt_text, padding=True, truncation=True, max_length=10, return_tensors="pt"
354
+ )
355
+ labels = targets["input_ids"]
356
+ batch["decoder_input_ids"] = shift_tokens_right(labels, self.tokenizer.pad_token_id)
357
+
358
+ self.assertEqual(batch.input_ids.shape[1], 3)
359
+ self.assertEqual(batch.decoder_input_ids.shape[1], 10)
360
+
361
+ @require_torch
362
+ def test_tokenizer_translation(self):
363
+ inputs = self.tokenizer._build_translation_inputs(
364
+ "A test", return_tensors="pt", src_lang="en_XX", tgt_lang="java"
365
+ )
366
+
367
+ self.assertEqual(
368
+ nested_simplify(inputs),
369
+ {
370
+ # A, test, EOS, en_XX
371
+ "input_ids": [[150, 242, 2, 50003]],
372
+ "attention_mask": [[1, 1, 1, 1]],
373
+ # java
374
+ "forced_bos_token_id": 50001,
375
+ },
376
+ )