AdithyaSK HF Staff commited on
Commit
769035a
·
verified ·
1 Parent(s): 1182e06

Stage Harbor release files 91501-92000

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-e0f68dd4420c/tests/source/tests/models/myt5/__init__.py +0 -0
  2. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/myt5/test_tokenization_myt5.py +188 -0
  3. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/nemotron/__init__.py +0 -0
  4. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/nemotron/test_modeling_nemotron.py +236 -0
  5. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/nllb/__init__.py +0 -0
  6. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/nllb/test_tokenization_nllb.py +468 -0
  7. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/nllb_moe/__init__.py +0 -0
  8. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/nllb_moe/test_modeling_nllb_moe.py +579 -0
  9. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/nougat/__init__.py +0 -0
  10. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/nougat/test_image_processing_nougat.py +195 -0
  11. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/nougat/test_tokenization_nougat.py +197 -0
  12. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/nystromformer/__init__.py +0 -0
  13. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/nystromformer/test_modeling_nystromformer.py +323 -0
  14. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/olmo/__init__.py +0 -0
  15. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/olmo/test_modeling_olmo.py +505 -0
  16. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/olmo2/__init__.py +0 -0
  17. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/olmo2/test_modeling_olmo2.py +467 -0
  18. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/olmoe/__init__.py +0 -0
  19. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/olmoe/test_modeling_olmoe.py +432 -0
  20. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/omdet_turbo/__init__.py +0 -0
  21. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/omdet_turbo/test_modeling_omdet_turbo.py +912 -0
  22. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/omdet_turbo/test_processor_omdet_turbo.py +202 -0
  23. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/oneformer/__init__.py +0 -0
  24. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/oneformer/test_image_processing_oneformer.py +368 -0
  25. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/oneformer/test_modeling_oneformer.py +630 -0
  26. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/oneformer/test_processor_oneformer.py +799 -0
  27. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/openai/__init__.py +0 -0
  28. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/openai/test_modeling_openai.py +312 -0
  29. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/openai/test_modeling_tf_openai.py +297 -0
  30. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/openai/test_tokenization_openai.py +145 -0
  31. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/opt/__init__.py +0 -0
  32. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/opt/test_modeling_flax_opt.py +404 -0
  33. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/opt/test_modeling_opt.py +580 -0
  34. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/opt/test_modeling_tf_opt.py +406 -0
  35. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/owlv2/__init__.py +0 -0
  36. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/owlv2/test_image_processing_owlv2.py +173 -0
  37. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/owlv2/test_modeling_owlv2.py +1071 -0
  38. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/owlv2/test_processor_owlv2.py +38 -0
  39. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/owlvit/__init__.py +0 -0
  40. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/owlvit/test_image_processing_owlvit.py +120 -0
  41. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/owlvit/test_modeling_owlvit.py +1057 -0
  42. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/owlvit/test_processor_owlvit.py +261 -0
  43. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/paligemma/__init__.py +0 -0
  44. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/paligemma/test_modeling_paligemma.py +670 -0
  45. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/paligemma/test_processor_paligemma.py +93 -0
  46. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/paligemma2/__init__.py +0 -0
  47. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/paligemma2/test_modeling_paligemma2.py +388 -0
  48. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/patchtsmixer/__init__.py +0 -0
  49. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/patchtsmixer/test_modeling_patchtsmixer.py +1115 -0
  50. tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/patchtst/__init__.py +0 -0
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/myt5/__init__.py ADDED
File without changes
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/myt5/test_tokenization_myt5.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ import binascii
16
+ import unittest
17
+
18
+ from transformers import MyT5Tokenizer
19
+ from transformers.utils import is_tf_available, is_torch_available
20
+
21
+ from ...test_tokenization_common import TokenizerTesterMixin
22
+
23
+
24
+ if is_torch_available():
25
+ FRAMEWORK = "pt"
26
+ elif is_tf_available():
27
+ FRAMEWORK = "tf"
28
+ else:
29
+ FRAMEWORK = "jax"
30
+
31
+
32
+ def bytes_to_hex(bline: bytes, sep: str = " ") -> str:
33
+ return str(binascii.hexlify(bline, sep), "utf-8")
34
+
35
+
36
+ def str_to_hex(line: str, sep: str = " ") -> str:
37
+ return bytes_to_hex(bytes(line, "utf-8"), sep)
38
+
39
+
40
+ class TestByteRewriter(unittest.TestCase):
41
+ def setUp(self) -> None:
42
+ self.tokenizer = MyT5Tokenizer.from_pretrained("Tomlim/myt5-base")
43
+
44
+ def test_simple_decompose(self):
45
+ decompose_rewriter = self.tokenizer.decompose_rewriter
46
+
47
+ # test rewriting
48
+ in_str = "Hello WorlD"
49
+ out_str = "hAello wAorldA"
50
+
51
+ in_hex = str_to_hex(in_str).split(" ")
52
+ out_hex = str_to_hex(out_str).split(" ")
53
+
54
+ self.assertEqual(decompose_rewriter.rewrite_bytes(in_hex), out_hex)
55
+
56
+ def test_simple_decompose_reversible(self):
57
+ decompose_rewriter = self.tokenizer.decompose_rewriter
58
+
59
+ in_str = "Hello WorlD"
60
+ out_str = "Hello WorlD"
61
+
62
+ in_hex = str_to_hex(in_str).split(" ")
63
+ out_hex = str_to_hex(out_str).split(" ")
64
+
65
+ self.assertEqual(
66
+ decompose_rewriter.rewrite_bytes(decompose_rewriter.rewrite_bytes(in_hex), reverse=True), out_hex
67
+ )
68
+
69
+ def test_simple_decompose_non_latin(self):
70
+ decompose_rewriter = self.tokenizer.decompose_rewriter
71
+
72
+ in_str = "你好世界 Hello WorlD"
73
+ out_str = "你好世界 hAello wAorldA"
74
+
75
+ in_hex = str_to_hex(in_str).split(" ")
76
+ out_hex = str_to_hex(out_str).split(" ")
77
+
78
+ self.assertEqual(decompose_rewriter.rewrite_bytes(in_hex), out_hex)
79
+
80
+ def test_unrecognized_byte(self):
81
+ decompose_rewriter = self.tokenizer.decompose_rewriter
82
+
83
+ in_hex = ["00", "01", "xx", "03", "61"]
84
+ out_hex = ["00", "01", "xx", "03", "61"]
85
+
86
+ self.assertEqual(decompose_rewriter.rewrite_bytes(in_hex), out_hex)
87
+
88
+
89
+ class MyT5TokenizationTest(TokenizerTesterMixin, unittest.TestCase):
90
+ tokenizer_class = MyT5Tokenizer
91
+ test_rust_tokenizer = False
92
+
93
+ def setUp(self):
94
+ super().setUp()
95
+
96
+ def get_tokenizer(self, **kwargs) -> MyT5Tokenizer:
97
+ return self.tokenizer_class.from_pretrained("Tomlim/myt5-base", **kwargs)
98
+
99
+ @unittest.skip(reason="inputs cannot be pretokenized as ids depend on whole input string")
100
+ def test_pretokenized_inputs(self):
101
+ pass
102
+
103
+ def test_convert_tokens_to_string_format(self):
104
+ tokenizer = self.get_tokenizer()
105
+ with self.subTest(f"{tokenizer.__class__.__name__}"):
106
+ tokens = ["52", "85", "91", "9f", "6f", "20", "52", "85", "9f", "90", "</s>"]
107
+ string = tokenizer.convert_tokens_to_string(tokens)
108
+
109
+ self.assertIsInstance(string, str)
110
+
111
+ def test_simple_tokenize(self):
112
+ tokenizer = self.get_tokenizer()
113
+
114
+ in_str = "Hello World"
115
+ out_tokens = ["52", "85", "91", "9f", "6f", "20", "52", "85", "9f", "90"]
116
+
117
+ self.assertEqual(tokenizer.tokenize(in_str), out_tokens)
118
+
119
+ in_pl_str = "Witaj świecie"
120
+ out_tokens = ["77", "41", "69", "74", "61", "6a", "20", "4b", "a5", "97", "63", "69", "65"]
121
+
122
+ self.assertEqual(tokenizer.tokenize(in_pl_str), out_tokens)
123
+
124
+ in_jp_str = "こんにちは世界"
125
+ out_tokens = ["58", "80", "91", "a1", "e4", "b8", "96", "e7", "95", "8c"]
126
+
127
+ self.assertEqual(tokenizer.tokenize(in_jp_str), out_tokens)
128
+
129
+ def test_batch_tokenize(self):
130
+ tokenizer = self.get_tokenizer()
131
+
132
+ in_batch = ["Hello World", "Witaj świecie", "こんにちは世界"]
133
+
134
+ out_tokens = [
135
+ ["52", "85", "91", "9f", "6f", "20", "52", "85", "9f", "90", "</s>"],
136
+ ["77", "41", "69", "74", "61", "6a", "20", "4b", "a5", "97", "63", "69", "65", "</s>"],
137
+ ["58", "80", "91", "a1", "e4", "b8", "96", "e7", "95", "8c", "</s>"],
138
+ ]
139
+
140
+ self.assertListEqual(
141
+ [tokenizer.convert_ids_to_tokens(ids) for ids in tokenizer(in_batch)["input_ids"]], out_tokens
142
+ )
143
+
144
+ def test_special_bytes(self):
145
+ tokenizer = self.get_tokenizer()
146
+
147
+ in_str_special = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09"
148
+ out_tokens = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09"]
149
+
150
+ self.assertEqual(tokenizer.tokenize(in_str_special), out_tokens)
151
+
152
+ in_str_mixed = "\x00Hello\x01 World\x02"
153
+ out_tokens = ["00", "52", "85", "91", "9f", "6f", "01", "20", "52", "85", "9f", "90", "02"]
154
+
155
+ self.assertEqual(tokenizer.tokenize(in_str_mixed), out_tokens)
156
+
157
+ def test_special_tokens(self):
158
+ tokenizer = self.get_tokenizer()
159
+
160
+ in_str_special = "<unk></s><pad>"
161
+ out_tokens = ["<unk>", "</s>", "<pad>"]
162
+
163
+ self.assertEqual(tokenizer.tokenize(in_str_special), out_tokens)
164
+
165
+ in_str_not_special = "<s>"
166
+ out_tokens = ["3c", "73", "3e"]
167
+
168
+ self.assertEqual(tokenizer.tokenize(in_str_not_special), out_tokens)
169
+
170
+ in_str_mixed = "<s>Hello World</s>"
171
+ out_tokens = ["3c", "73", "3e", "52", "85", "91", "9f", "6f", "20", "52", "85", "9f", "90", "</s>"]
172
+
173
+ self.assertEqual(tokenizer.tokenize(in_str_mixed), out_tokens)
174
+
175
+ def test_token_ids_conversion(self):
176
+ tokenizer = self.get_tokenizer()
177
+
178
+ tokens_range = [f"{x:02x}" for x in range(256)]
179
+ indices_range = list(range(3, 256 + 3))
180
+
181
+ self.assertListEqual(tokenizer.convert_tokens_to_ids(tokens_range), indices_range)
182
+ self.assertListEqual(tokenizer.convert_ids_to_tokens(indices_range), tokens_range)
183
+
184
+ special_tokens = ["<pad>", "</s>", "<unk>"]
185
+ special_indices = [0, 1, 2]
186
+
187
+ self.assertListEqual(tokenizer.convert_tokens_to_ids(special_tokens), special_indices)
188
+ self.assertListEqual(tokenizer.convert_ids_to_tokens(special_indices), special_tokens)
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/nemotron/__init__.py ADDED
File without changes
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/nemotron/test_modeling_nemotron.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 HuggingFace Inc. team. All rights reserved.
3
+ # Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+ """Testing suite for the PyTorch Nemotron model."""
17
+
18
+ import tempfile
19
+ import unittest
20
+
21
+ import pytest
22
+
23
+ from transformers import NemotronConfig, is_torch_available
24
+ from transformers.testing_utils import (
25
+ is_flaky,
26
+ require_flash_attn,
27
+ require_read_token,
28
+ require_torch,
29
+ require_torch_accelerator,
30
+ require_torch_gpu,
31
+ require_torch_sdpa,
32
+ slow,
33
+ torch_device,
34
+ )
35
+
36
+ from ...models.gemma.test_modeling_gemma import GemmaModelTest, GemmaModelTester
37
+ from ...test_configuration_common import ConfigTester
38
+
39
+
40
+ if is_torch_available():
41
+ import torch
42
+
43
+ from transformers import (
44
+ AutoTokenizer,
45
+ NemotronForCausalLM,
46
+ NemotronForQuestionAnswering,
47
+ NemotronForSequenceClassification,
48
+ NemotronForTokenClassification,
49
+ NemotronModel,
50
+ )
51
+
52
+
53
+ class NemotronModelTester(GemmaModelTester):
54
+ if is_torch_available():
55
+ config_class = NemotronConfig
56
+ model_class = NemotronModel
57
+ for_causal_lm_class = NemotronForCausalLM
58
+ for_sequence_class = NemotronForSequenceClassification
59
+ for_token_class = NemotronForTokenClassification
60
+
61
+
62
+ @require_torch
63
+ class NemotronModelTest(GemmaModelTest):
64
+ # Need to use `0.8` instead of `0.9` for `test_cpu_offload`
65
+ # This is because we are hitting edge cases with the causal_mask buffer
66
+ model_split_percents = [0.5, 0.7, 0.8]
67
+ all_model_classes = (
68
+ (
69
+ NemotronModel,
70
+ NemotronForCausalLM,
71
+ NemotronForSequenceClassification,
72
+ NemotronForQuestionAnswering,
73
+ NemotronForTokenClassification,
74
+ )
75
+ if is_torch_available()
76
+ else ()
77
+ )
78
+ pipeline_model_mapping = (
79
+ {
80
+ "feature-extraction": NemotronModel,
81
+ "text-classification": NemotronForSequenceClassification,
82
+ "text-generation": NemotronForCausalLM,
83
+ "zero-shot": NemotronForSequenceClassification,
84
+ "question-answering": NemotronForQuestionAnswering,
85
+ "token-classification": NemotronForTokenClassification,
86
+ }
87
+ if is_torch_available()
88
+ else {}
89
+ )
90
+ test_headmasking = False
91
+ test_pruning = False
92
+ fx_compatible = False
93
+
94
+ # used in `test_torch_compile_for_training`
95
+ _torch_compile_train_cls = NemotronForCausalLM if is_torch_available() else None
96
+
97
+ def setUp(self):
98
+ self.model_tester = NemotronModelTester(self)
99
+ self.config_tester = ConfigTester(self, config_class=NemotronConfig, hidden_size=37)
100
+
101
+ @unittest.skip("Eager and SDPA do not produce the same outputs, thus this test fails")
102
+ def test_model_outputs_equivalence(self, **kwargs):
103
+ pass
104
+
105
+ @require_torch_sdpa
106
+ @require_torch_accelerator
107
+ @slow
108
+ def test_sdpa_equivalence(self):
109
+ for model_class in self.all_model_classes:
110
+ if not model_class._supports_sdpa:
111
+ self.skipTest(reason="Model does not support SDPA")
112
+
113
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
114
+ model = model_class(config)
115
+
116
+ with tempfile.TemporaryDirectory() as tmpdirname:
117
+ model.save_pretrained(tmpdirname)
118
+ model_sdpa = model_class.from_pretrained(
119
+ tmpdirname, torch_dtype=torch.float16, attn_implementation="sdpa"
120
+ )
121
+ model_sdpa.to(torch_device)
122
+
123
+ model = model_class.from_pretrained(tmpdirname, torch_dtype=torch.float16, attn_implementation="eager")
124
+ model.to(torch_device)
125
+
126
+ dummy_input = inputs_dict[model_class.main_input_name]
127
+ dummy_input = dummy_input.to(torch_device)
128
+ outputs = model(dummy_input, output_hidden_states=True)
129
+ outputs_sdpa = model_sdpa(dummy_input, output_hidden_states=True)
130
+
131
+ logits = outputs.hidden_states[-1]
132
+ logits_sdpa = outputs_sdpa.hidden_states[-1]
133
+
134
+ # nemotron sdpa needs a high tolerance
135
+ assert torch.allclose(logits_sdpa, logits, atol=1e-2)
136
+
137
+ @require_flash_attn
138
+ @require_torch_gpu
139
+ @pytest.mark.flash_attn_test
140
+ @is_flaky()
141
+ @slow
142
+ def test_flash_attn_2_equivalence(self):
143
+ for model_class in self.all_model_classes:
144
+ if not model_class._supports_flash_attn_2:
145
+ self.skipTest(reason="Model does not support Flash Attention 2")
146
+
147
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
148
+ model = model_class(config)
149
+
150
+ with tempfile.TemporaryDirectory() as tmpdirname:
151
+ model.save_pretrained(tmpdirname)
152
+ model_fa = model_class.from_pretrained(
153
+ tmpdirname, torch_dtype=torch.float16, attn_implementation="flash_attention_2"
154
+ )
155
+ model_fa.to(torch_device)
156
+
157
+ model = model_class.from_pretrained(tmpdirname, torch_dtype=torch.float16, attn_implementation="eager")
158
+ model.to(torch_device)
159
+
160
+ dummy_input = inputs_dict[model_class.main_input_name]
161
+ dummy_input = dummy_input.to(torch_device)
162
+ outputs = model(dummy_input, output_hidden_states=True)
163
+ outputs_fa = model_fa(dummy_input, output_hidden_states=True)
164
+
165
+ logits = outputs.hidden_states[-1]
166
+ logits_fa = outputs_fa.hidden_states[-1]
167
+
168
+ # nemotron flash attention 2 needs a high tolerance
169
+ assert torch.allclose(logits_fa, logits, atol=1e-2)
170
+
171
+
172
+ @require_torch_gpu
173
+ class NemotronIntegrationTest(unittest.TestCase):
174
+ # This variable is used to determine which CUDA device are we using for our runners (A10 or T4)
175
+ # Depending on the hardware we get different logits / generations
176
+ cuda_compute_capability_major_version = None
177
+
178
+ @classmethod
179
+ def setUpClass(cls):
180
+ if is_torch_available() and torch.cuda.is_available():
181
+ # 8 is for A100 / A10 and 7 for T4
182
+ cls.cuda_compute_capability_major_version = torch.cuda.get_device_capability()[0]
183
+
184
+ @slow
185
+ @require_read_token
186
+ def test_nemotron_8b_generation_sdpa(self):
187
+ text = ["What is the largest planet in solar system?"]
188
+ EXPECTED_TEXT = [
189
+ "What is the largest planet in solar system?\nAnswer: Jupiter\n\nWhat is the answer",
190
+ ]
191
+ model_id = "thhaus/nemotron3-8b"
192
+ model = NemotronForCausalLM.from_pretrained(
193
+ model_id, torch_dtype=torch.float16, device_map="auto", attn_implementation="sdpa"
194
+ )
195
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
196
+ inputs = tokenizer(text, return_tensors="pt").to(torch_device)
197
+
198
+ output = model.generate(**inputs, do_sample=False)
199
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=True)
200
+ self.assertEqual(EXPECTED_TEXT, output_text)
201
+
202
+ @slow
203
+ @require_read_token
204
+ def test_nemotron_8b_generation_eager(self):
205
+ text = ["What is the largest planet in solar system?"]
206
+ EXPECTED_TEXT = [
207
+ "What is the largest planet in solar system?\nAnswer: Jupiter\n\nWhat is the answer",
208
+ ]
209
+ model_id = "thhaus/nemotron3-8b"
210
+ model = NemotronForCausalLM.from_pretrained(
211
+ model_id, torch_dtype=torch.float16, device_map="auto", attn_implementation="eager"
212
+ )
213
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
214
+ inputs = tokenizer(text, return_tensors="pt").to(torch_device)
215
+
216
+ output = model.generate(**inputs, do_sample=False)
217
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=True)
218
+ self.assertEqual(EXPECTED_TEXT, output_text)
219
+
220
+ @slow
221
+ @require_read_token
222
+ def test_nemotron_8b_generation_fa2(self):
223
+ text = ["What is the largest planet in solar system?"]
224
+ EXPECTED_TEXT = [
225
+ "What is the largest planet in solar system?\nAnswer: Jupiter\n\nWhat is the answer",
226
+ ]
227
+ model_id = "thhaus/nemotron3-8b"
228
+ model = NemotronForCausalLM.from_pretrained(
229
+ model_id, torch_dtype=torch.float16, device_map="auto", attn_implementation="flash_attention_2"
230
+ )
231
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
232
+ inputs = tokenizer(text, return_tensors="pt").to(torch_device)
233
+
234
+ output = model.generate(**inputs, do_sample=False)
235
+ output_text = tokenizer.batch_decode(output, skip_special_tokens=True)
236
+ self.assertEqual(EXPECTED_TEXT, output_text)
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/nllb/__init__.py ADDED
File without changes
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/nllb/test_tokenization_nllb.py ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 shutil
16
+ import tempfile
17
+ import unittest
18
+
19
+ from transformers import (
20
+ SPIECE_UNDERLINE,
21
+ AddedToken,
22
+ BatchEncoding,
23
+ NllbTokenizer,
24
+ NllbTokenizerFast,
25
+ is_torch_available,
26
+ )
27
+ from transformers.models.nllb.tokenization_nllb import FAIRSEQ_LANGUAGE_CODES
28
+ from transformers.testing_utils import (
29
+ get_tests_dir,
30
+ nested_simplify,
31
+ require_sentencepiece,
32
+ require_tokenizers,
33
+ require_torch,
34
+ )
35
+
36
+ from ...test_tokenization_common import TokenizerTesterMixin
37
+
38
+
39
+ SAMPLE_VOCAB = get_tests_dir("fixtures/test_sentencepiece.model")
40
+
41
+
42
+ if is_torch_available():
43
+ from transformers.models.m2m_100.modeling_m2m_100 import shift_tokens_right
44
+
45
+ EN_CODE = 256047
46
+ RO_CODE = 256145
47
+
48
+
49
+ @require_sentencepiece
50
+ @require_tokenizers
51
+ class NllbTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
52
+ from_pretrained_id = "facebook/nllb-200-distilled-600M"
53
+ tokenizer_class = NllbTokenizer
54
+ rust_tokenizer_class = NllbTokenizerFast
55
+ test_rust_tokenizer = True
56
+ test_sentencepiece = True
57
+ from_pretrained_kwargs = {}
58
+
59
+ def setUp(self):
60
+ super().setUp()
61
+
62
+ # We have a SentencePiece fixture for testing
63
+ tokenizer = NllbTokenizer(SAMPLE_VOCAB, keep_accents=True)
64
+ tokenizer.save_pretrained(self.tmpdirname)
65
+
66
+ def test_full_tokenizer(self):
67
+ tokenizer = NllbTokenizer(SAMPLE_VOCAB, keep_accents=True)
68
+
69
+ tokens = tokenizer.tokenize("This is a test")
70
+ self.assertListEqual(tokens, ["▁This", "▁is", "▁a", "▁t", "est"])
71
+
72
+ self.assertListEqual(
73
+ tokenizer.convert_tokens_to_ids(tokens),
74
+ [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]],
75
+ )
76
+
77
+ tokens = tokenizer.tokenize("I was born in 92000, and this is falsé.")
78
+ self.assertListEqual(
79
+ tokens,
80
+ [
81
+ SPIECE_UNDERLINE + "I",
82
+ SPIECE_UNDERLINE + "was",
83
+ SPIECE_UNDERLINE + "b",
84
+ "or",
85
+ "n",
86
+ SPIECE_UNDERLINE + "in",
87
+ SPIECE_UNDERLINE + "",
88
+ "9",
89
+ "2",
90
+ "0",
91
+ "0",
92
+ "0",
93
+ ",",
94
+ SPIECE_UNDERLINE + "and",
95
+ SPIECE_UNDERLINE + "this",
96
+ SPIECE_UNDERLINE + "is",
97
+ SPIECE_UNDERLINE + "f",
98
+ "al",
99
+ "s",
100
+ "é",
101
+ ".",
102
+ ],
103
+ )
104
+ ids = tokenizer.convert_tokens_to_ids(tokens)
105
+ self.assertListEqual(
106
+ ids,
107
+ [
108
+ value + tokenizer.fairseq_offset
109
+ for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4]
110
+ ],
111
+ )
112
+
113
+ back_tokens = tokenizer.convert_ids_to_tokens(ids)
114
+ self.assertListEqual(
115
+ back_tokens,
116
+ [
117
+ SPIECE_UNDERLINE + "I",
118
+ SPIECE_UNDERLINE + "was",
119
+ SPIECE_UNDERLINE + "b",
120
+ "or",
121
+ "n",
122
+ SPIECE_UNDERLINE + "in",
123
+ SPIECE_UNDERLINE + "",
124
+ "<unk>",
125
+ "2",
126
+ "0",
127
+ "0",
128
+ "0",
129
+ ",",
130
+ SPIECE_UNDERLINE + "and",
131
+ SPIECE_UNDERLINE + "this",
132
+ SPIECE_UNDERLINE + "is",
133
+ SPIECE_UNDERLINE + "f",
134
+ "al",
135
+ "s",
136
+ "<unk>",
137
+ ".",
138
+ ],
139
+ )
140
+
141
+ # overwrite from test_tokenization_common to speed up test
142
+ def test_save_pretrained(self):
143
+ self.tokenizers_list[0] = (self.rust_tokenizer_class, "hf-internal-testing/tiny-random-nllb", {})
144
+ for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
145
+ with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
146
+ tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
147
+ tokenizer_p = self.tokenizer_class.from_pretrained(pretrained_name, **kwargs)
148
+
149
+ tmpdirname2 = tempfile.mkdtemp()
150
+
151
+ tokenizer_r_files = tokenizer_r.save_pretrained(tmpdirname2)
152
+ tokenizer_p_files = tokenizer_p.save_pretrained(tmpdirname2)
153
+
154
+ # Checks it save with the same files + the tokenizer.json file for the fast one
155
+ self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files))
156
+ tokenizer_r_files = tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f)
157
+ self.assertSequenceEqual(tokenizer_r_files, tokenizer_p_files)
158
+
159
+ # Checks everything loads correctly in the same way
160
+ tokenizer_rp = tokenizer_r.from_pretrained(tmpdirname2)
161
+ tokenizer_pp = tokenizer_p.from_pretrained(tmpdirname2)
162
+
163
+ # Check special tokens are set accordingly on Rust and Python
164
+ for key in tokenizer_pp.special_tokens_map:
165
+ self.assertTrue(hasattr(tokenizer_rp, key))
166
+
167
+ shutil.rmtree(tmpdirname2)
168
+
169
+ # Save tokenizer rust, legacy_format=True
170
+ tmpdirname2 = tempfile.mkdtemp()
171
+
172
+ tokenizer_r_files = tokenizer_r.save_pretrained(tmpdirname2, legacy_format=True)
173
+ tokenizer_p_files = tokenizer_p.save_pretrained(tmpdirname2)
174
+
175
+ # Checks it save with the same files
176
+ self.assertSequenceEqual(tokenizer_r_files, tokenizer_p_files)
177
+
178
+ # Checks everything loads correctly in the same way
179
+ tokenizer_rp = tokenizer_r.from_pretrained(tmpdirname2)
180
+ tokenizer_pp = tokenizer_p.from_pretrained(tmpdirname2)
181
+
182
+ # Check special tokens are set accordingly on Rust and Python
183
+ for key in tokenizer_pp.special_tokens_map:
184
+ self.assertTrue(hasattr(tokenizer_rp, key))
185
+
186
+ shutil.rmtree(tmpdirname2)
187
+
188
+ # Save tokenizer rust, legacy_format=False
189
+ tmpdirname2 = tempfile.mkdtemp()
190
+
191
+ tokenizer_r_files = tokenizer_r.save_pretrained(tmpdirname2, legacy_format=False)
192
+ tokenizer_p_files = tokenizer_p.save_pretrained(tmpdirname2)
193
+
194
+ # Checks it saved the tokenizer.json file
195
+ self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files))
196
+
197
+ # Checks everything loads correctly in the same way
198
+ tokenizer_rp = tokenizer_r.from_pretrained(tmpdirname2)
199
+ tokenizer_pp = tokenizer_p.from_pretrained(tmpdirname2)
200
+
201
+ # Check special tokens are set accordingly on Rust and Python
202
+ for key in tokenizer_pp.special_tokens_map:
203
+ self.assertTrue(hasattr(tokenizer_rp, key))
204
+
205
+ shutil.rmtree(tmpdirname2)
206
+
207
+ @require_torch
208
+ def test_prepare_seq2seq_batch(self):
209
+ if not self.test_seq2seq:
210
+ self.skipTest(reason="test_seq2seq is set to False")
211
+
212
+ tokenizers = self.get_tokenizers()
213
+ for tokenizer in tokenizers:
214
+ with self.subTest(f"{tokenizer.__class__.__name__}"):
215
+ # Longer text that will definitely require truncation.
216
+ src_text = [
217
+ " UN Chief Says There Is No Military Solution in Syria",
218
+ " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for"
219
+ " Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons"
220
+ " will only worsen the violence and misery for millions of people.",
221
+ ]
222
+ tgt_text = [
223
+ "Şeful ONU declară că nu există o soluţie militară în Siria",
224
+ "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al"
225
+ ' Rusiei pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi'
226
+ " că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.",
227
+ ]
228
+ try:
229
+ batch = tokenizer.prepare_seq2seq_batch(
230
+ src_texts=src_text,
231
+ tgt_texts=tgt_text,
232
+ max_length=3,
233
+ max_target_length=10,
234
+ return_tensors="pt",
235
+ src_lang="eng_Latn",
236
+ tgt_lang="ron_Latn",
237
+ )
238
+ except NotImplementedError:
239
+ self.skipTest(reason="Encountered NotImplementedError when calling prepare_seq2seq_batch")
240
+ self.assertEqual(batch.input_ids.shape[1], 3)
241
+ self.assertEqual(batch.labels.shape[1], 10)
242
+ # max_target_length will default to max_length if not specified
243
+ batch = tokenizer.prepare_seq2seq_batch(
244
+ src_text, tgt_texts=tgt_text, max_length=3, return_tensors="pt"
245
+ )
246
+ self.assertEqual(batch.input_ids.shape[1], 3)
247
+ self.assertEqual(batch.labels.shape[1], 3)
248
+
249
+ batch_encoder_only = tokenizer.prepare_seq2seq_batch(
250
+ src_texts=src_text, max_length=3, max_target_length=10, return_tensors="pt"
251
+ )
252
+ self.assertEqual(batch_encoder_only.input_ids.shape[1], 3)
253
+ self.assertEqual(batch_encoder_only.attention_mask.shape[1], 3)
254
+ self.assertNotIn("decoder_input_ids", batch_encoder_only)
255
+
256
+ @unittest.skip(reason="Unfortunately way too slow to build a BPE with SentencePiece.")
257
+ def test_save_slow_from_fast_and_reload_fast(self):
258
+ pass
259
+
260
+ def test_special_tokens_initialization(self):
261
+ for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
262
+ with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
263
+ added_tokens = [AddedToken("<special>", lstrip=True)]
264
+
265
+ tokenizer_r = self.rust_tokenizer_class.from_pretrained(
266
+ pretrained_name, additional_special_tokens=added_tokens, **kwargs
267
+ )
268
+ r_output = tokenizer_r.encode("Hey this is a <special> token")
269
+
270
+ special_token_id = tokenizer_r.encode("<special>", add_special_tokens=False)[0]
271
+
272
+ self.assertTrue(special_token_id in r_output)
273
+
274
+ if self.test_slow_tokenizer:
275
+ tokenizer_cr = self.rust_tokenizer_class.from_pretrained(
276
+ pretrained_name,
277
+ additional_special_tokens=added_tokens,
278
+ **kwargs, # , from_slow=True <- unfortunately too slow to convert
279
+ )
280
+ tokenizer_p = self.tokenizer_class.from_pretrained(
281
+ pretrained_name, additional_special_tokens=added_tokens, **kwargs
282
+ )
283
+
284
+ p_output = tokenizer_p.encode("Hey this is a <special> token")
285
+
286
+ cr_output = tokenizer_cr.encode("Hey this is a <special> token")
287
+
288
+ self.assertEqual(p_output, r_output)
289
+ self.assertEqual(cr_output, r_output)
290
+ self.assertTrue(special_token_id in p_output)
291
+ self.assertTrue(special_token_id in cr_output)
292
+
293
+ @unittest.skip(reason="Need to fix this after #26538")
294
+ def test_training_new_tokenizer(self):
295
+ pass
296
+
297
+ def test_new_language_codes(self):
298
+ code1, code2 = "myv_Cyrl", "myv_Latn"
299
+ new_codes = FAIRSEQ_LANGUAGE_CODES + [code1, code2]
300
+ # here I create a tokenizer with the default behaviour
301
+ tok1 = NllbTokenizer.from_pretrained("facebook/nllb-200-distilled-600M")
302
+ # here I enhance the model's vocabulary with two new language codes
303
+ tok2 = NllbTokenizer.from_pretrained("facebook/nllb-200-distilled-600M", additional_special_tokens=new_codes)
304
+
305
+ # testing that the new codes can work
306
+ self.assertEqual(len(tok2), len(tok1) + 2)
307
+ tok2.tgt_lang = code1
308
+ tok2.src_lang = code2
309
+
310
+ self.assertEqual(tok2("šumbrat!").input_ids[0], tok2.convert_tokens_to_ids(code2))
311
+ with tempfile.TemporaryDirectory() as tempdir:
312
+ # testing that saving and loading the tokenizer preserves the new behaviour
313
+ tok2.save_pretrained(tempdir)
314
+ tok3 = NllbTokenizer.from_pretrained(tempdir)
315
+ self.assertEqual(tok2.get_vocab(), tok3.get_vocab())
316
+ tok3.src_lang = code2
317
+ self.assertEqual(tok3("šumbrat!").input_ids[0], tok3.convert_tokens_to_ids(code2))
318
+
319
+ # testing that saving and loading the tokenizer preserves the new behaviour
320
+ tok2.save_pretrained(tempdir)
321
+ tok3 = NllbTokenizer(f"{tempdir}/sentencepiece.bpe.model", additional_special_tokens=None)
322
+ self.assertEqual(len(tok3), 256204) # legacy
323
+ tok4 = NllbTokenizer(f"{tempdir}/sentencepiece.bpe.model", additional_special_tokens=[])
324
+ self.assertEqual(len(tok4), 256002)
325
+ tok5 = NllbTokenizer(f"{tempdir}/sentencepiece.bpe.model", additional_special_tokens=[code1, code2])
326
+ self.assertEqual(len(tok5), 256004)
327
+
328
+
329
+ @require_torch
330
+ @require_sentencepiece
331
+ @require_tokenizers
332
+ class NllbDistilledIntegrationTest(unittest.TestCase):
333
+ checkpoint_name = "facebook/nllb-200-distilled-600M"
334
+ src_text = [
335
+ " UN Chief Says There Is No Military Solution in Syria",
336
+ """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.""",
337
+ ]
338
+ tgt_text = [
339
+ "Şeful ONU declară că nu există o soluţie militară în Siria",
340
+ "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei"
341
+ ' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor'
342
+ " face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.",
343
+ ]
344
+ expected_src_tokens = [
345
+ 256047,
346
+ 16297,
347
+ 134408,
348
+ 8165,
349
+ 248066,
350
+ 14734,
351
+ 950,
352
+ 1135,
353
+ 105721,
354
+ 3573,
355
+ 83,
356
+ 27352,
357
+ 108,
358
+ 49486,
359
+ 2,
360
+ ]
361
+
362
+ @classmethod
363
+ def setUpClass(cls):
364
+ cls.tokenizer: NllbTokenizer = NllbTokenizer.from_pretrained(
365
+ cls.checkpoint_name, src_lang="eng_Latn", tgt_lang="ron_Latn"
366
+ )
367
+ cls.pad_token_id = 1
368
+ return cls
369
+
370
+ def test_enro_tokenizer_batch_encode_plus(self):
371
+ ids = self.tokenizer.batch_encode_plus(self.src_text).input_ids[0]
372
+ self.assertListEqual(self.expected_src_tokens, ids)
373
+
374
+ def test_enro_tokenizer_decode_ignores_language_codes(self):
375
+ self.assertIn(RO_CODE, self.tokenizer.all_special_ids)
376
+ generated_ids = [RO_CODE, 4254, 98068, 112923, 39072, 3909, 713, 102767, 26, 17314, 35642, 14683, 33118, 2022, 66987, 2, 256047] # fmt: skip
377
+
378
+ result = self.tokenizer.decode(generated_ids, skip_special_tokens=True)
379
+ expected_romanian = self.tokenizer.decode(generated_ids[1:], skip_special_tokens=True)
380
+ self.assertEqual(result, expected_romanian)
381
+ self.assertNotIn(self.tokenizer.eos_token, result)
382
+
383
+ def test_enro_tokenizer_truncation(self):
384
+ src_text = ["this is gunna be a long sentence " * 20]
385
+ assert isinstance(src_text[0], str)
386
+ desired_max_length = 10
387
+ ids = self.tokenizer(src_text, max_length=desired_max_length, truncation=True).input_ids[0]
388
+ self.assertEqual(ids[-1], 2)
389
+ self.assertEqual(ids[0], EN_CODE)
390
+ self.assertEqual(len(ids), desired_max_length)
391
+
392
+ def test_mask_token(self):
393
+ self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["<mask>", "ar_AR"]), [256203, 3])
394
+
395
+ @require_torch
396
+ def test_enro_tokenizer_prepare_batch(self):
397
+ batch = self.tokenizer(
398
+ self.src_text,
399
+ text_target=self.tgt_text,
400
+ padding=True,
401
+ truncation=True,
402
+ max_length=len(self.expected_src_tokens),
403
+ return_tensors="pt",
404
+ )
405
+ batch["decoder_input_ids"] = shift_tokens_right(
406
+ batch["labels"], self.tokenizer.pad_token_id, self.tokenizer.convert_tokens_to_ids("ron_Latn")
407
+ )
408
+
409
+ self.assertIsInstance(batch, BatchEncoding)
410
+
411
+ self.assertEqual((2, 15), batch.input_ids.shape)
412
+ self.assertEqual((2, 15), batch.attention_mask.shape)
413
+ result = batch.input_ids.tolist()[0]
414
+ self.assertListEqual(self.expected_src_tokens, result)
415
+ self.assertEqual(RO_CODE, batch.decoder_input_ids[0, 0]) # EOS
416
+ # Test that special tokens are reset
417
+ self.assertEqual(self.tokenizer.prefix_tokens, [EN_CODE])
418
+ self.assertEqual(self.tokenizer.suffix_tokens, [self.tokenizer.eos_token_id])
419
+
420
+ def test_seq2seq_max_length(self):
421
+ batch = self.tokenizer(self.src_text, padding=True, truncation=True, max_length=3, return_tensors="pt")
422
+ targets = self.tokenizer(
423
+ text_target=self.tgt_text, padding=True, truncation=True, max_length=10, return_tensors="pt"
424
+ )
425
+ labels = targets["input_ids"]
426
+ batch["decoder_input_ids"] = shift_tokens_right(
427
+ labels,
428
+ self.tokenizer.pad_token_id,
429
+ decoder_start_token_id=self.tokenizer.convert_tokens_to_ids(self.tokenizer.tgt_lang),
430
+ )
431
+
432
+ self.assertEqual(batch.input_ids.shape[1], 3)
433
+ self.assertEqual(batch.decoder_input_ids.shape[1], 10)
434
+
435
+ @require_torch
436
+ def test_tokenizer_translation(self):
437
+ inputs = self.tokenizer._build_translation_inputs(
438
+ "A test", return_tensors="pt", src_lang="eng_Latn", tgt_lang="fra_Latn"
439
+ )
440
+
441
+ self.assertEqual(
442
+ nested_simplify(inputs),
443
+ {
444
+ # A, test, EOS, en_XX
445
+ "input_ids": [[256047, 70, 7356, 2]],
446
+ "attention_mask": [[1, 1, 1, 1]],
447
+ # ar_AR
448
+ "forced_bos_token_id": 256057,
449
+ },
450
+ )
451
+
452
+ @require_torch
453
+ def test_legacy_behaviour(self):
454
+ self.tokenizer.legacy_behaviour = True
455
+ inputs = self.tokenizer(
456
+ "UN Chief says there is no military solution in Syria", src_lang="eng_Latn", tgt_lang="fra_Latn"
457
+ )
458
+ self.assertEqual(
459
+ inputs.input_ids, [16297, 134408, 25653, 6370, 248, 254, 103929, 94995, 108, 49486, 2, 256047]
460
+ )
461
+
462
+ self.tokenizer.legacy_behaviour = False
463
+ inputs = self.tokenizer(
464
+ "UN Chief says there is no military solution in Syria", src_lang="eng_Latn", tgt_lang="fra_Latn"
465
+ )
466
+ self.assertEqual(
467
+ inputs.input_ids, [256047, 16297, 134408, 25653, 6370, 248, 254, 103929, 94995, 108, 49486, 2]
468
+ )
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/nllb_moe/__init__.py ADDED
File without changes
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/nllb_moe/test_modeling_nllb_moe.py ADDED
@@ -0,0 +1,579 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 NLLB-MoE model."""
16
+
17
+ import copy
18
+ import tempfile
19
+ import unittest
20
+
21
+ from transformers import NllbMoeConfig, is_torch_available, set_seed
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 NllbMoeForConditionalGeneration, NllbMoeModel, NllbTokenizer
42
+ from transformers.models.nllb_moe.modeling_nllb_moe import NllbMoeDecoder, NllbMoeEncoder, NllbMoeTop2Router
43
+
44
+
45
+ class NllbMoeModelTester:
46
+ def __init__(
47
+ self,
48
+ parent,
49
+ batch_size=13,
50
+ seq_length=7,
51
+ is_training=True,
52
+ use_labels=False,
53
+ vocab_size=99,
54
+ hidden_size=16,
55
+ num_hidden_layers=2,
56
+ num_attention_heads=4,
57
+ intermediate_size=4,
58
+ hidden_act="relu",
59
+ hidden_dropout_prob=0.1,
60
+ attention_probs_dropout_prob=0.1,
61
+ encoder_layerdrop=0.0,
62
+ decoder_layerdrop=0.0,
63
+ max_position_embeddings=20,
64
+ eos_token_id=2,
65
+ pad_token_id=1,
66
+ bos_token_id=0,
67
+ num_experts=4,
68
+ encoder_sparse_step=2,
69
+ decoder_sparse_step=1,
70
+ expert_capacity=100,
71
+ router_jitter_noise=0.0,
72
+ ):
73
+ self.parent = parent
74
+ self.batch_size = batch_size
75
+ self.seq_length = seq_length
76
+ self.is_training = is_training
77
+ self.use_labels = use_labels
78
+ self.vocab_size = vocab_size
79
+ self.hidden_size = hidden_size
80
+ self.num_hidden_layers = num_hidden_layers
81
+ self.num_attention_heads = num_attention_heads
82
+ self.intermediate_size = intermediate_size
83
+ self.hidden_act = hidden_act
84
+ self.hidden_dropout_prob = hidden_dropout_prob
85
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
86
+ self.encoder_layerdrop = encoder_layerdrop
87
+ self.decoder_layerdrop = decoder_layerdrop
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.encoder_sparse_step = encoder_sparse_step
93
+ self.decoder_sparse_step = decoder_sparse_step
94
+ self.expert_capacity = expert_capacity
95
+ self.router_jitter_noise = router_jitter_noise
96
+ self.num_experts = num_experts
97
+
98
+ def prepare_nllb_moe_inputs_dict(
99
+ self,
100
+ config,
101
+ input_ids,
102
+ decoder_input_ids,
103
+ attention_mask=None,
104
+ decoder_attention_mask=None,
105
+ head_mask=None,
106
+ decoder_head_mask=None,
107
+ cross_attn_head_mask=None,
108
+ ):
109
+ if attention_mask is None:
110
+ attention_mask = input_ids.ne(config.pad_token_id)
111
+ if decoder_attention_mask is None:
112
+ decoder_attention_mask = decoder_input_ids.ne(config.pad_token_id)
113
+ if head_mask is None:
114
+ head_mask = torch.ones(config.encoder_layers, config.encoder_attention_heads, device=torch_device)
115
+ if decoder_head_mask is None:
116
+ decoder_head_mask = torch.ones(config.decoder_layers, config.decoder_attention_heads, device=torch_device)
117
+ if cross_attn_head_mask is None:
118
+ cross_attn_head_mask = torch.ones(
119
+ config.decoder_layers, config.decoder_attention_heads, device=torch_device
120
+ )
121
+ return {
122
+ "input_ids": input_ids,
123
+ "decoder_input_ids": decoder_input_ids,
124
+ "attention_mask": attention_mask,
125
+ "decoder_attention_mask": attention_mask,
126
+ "head_mask": head_mask,
127
+ "decoder_head_mask": decoder_head_mask,
128
+ "cross_attn_head_mask": cross_attn_head_mask,
129
+ }
130
+
131
+ def prepare_config_and_inputs(self):
132
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
133
+ input_ids[:, -1] = self.eos_token_id # Eos Token
134
+ decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
135
+
136
+ # we need to clamp the input ids here to avoid having pad token in between
137
+ # this is because for NllbMoe the position_ids are prepared such that
138
+ # all pad tokens have pos id = 2 and rest are between 2..seq_length
139
+ # and the seq_length here is seq_length - num_pad_tokens
140
+ # but when using past, there is no way of knowing if the past input ids had
141
+ # pad tokens in them, which results in incorrect seq_lenth and which in turn results in
142
+ # position_ids being off by num_pad_tokens in past input
143
+ input_ids = input_ids.clamp(self.pad_token_id + 1)
144
+ decoder_input_ids = decoder_input_ids.clamp(self.pad_token_id + 1)
145
+
146
+ config = self.get_config()
147
+ inputs_dict = self.prepare_nllb_moe_inputs_dict(config, input_ids, decoder_input_ids)
148
+ return config, inputs_dict
149
+
150
+ def get_config(self):
151
+ return NllbMoeConfig(
152
+ vocab_size=self.vocab_size,
153
+ d_model=self.hidden_size,
154
+ encoder_layers=self.num_hidden_layers,
155
+ decoder_layers=self.num_hidden_layers,
156
+ encoder_attention_heads=self.num_attention_heads,
157
+ decoder_attention_heads=self.num_attention_heads,
158
+ encoder_ffn_dim=self.intermediate_size,
159
+ decoder_ffn_dim=self.intermediate_size,
160
+ dropout=self.hidden_dropout_prob,
161
+ attention_dropout=self.attention_probs_dropout_prob,
162
+ encoder_layerdrop=self.encoder_layerdrop,
163
+ decoder_layerdrop=self.decoder_layerdrop,
164
+ max_position_embeddings=self.max_position_embeddings,
165
+ eos_token_id=self.eos_token_id,
166
+ bos_token_id=self.bos_token_id,
167
+ pad_token_id=self.pad_token_id,
168
+ expert_capacity=self.expert_capacity,
169
+ router_jitter_noise=self.router_jitter_noise,
170
+ decoder_sparse_step=self.decoder_sparse_step,
171
+ encoder_sparse_step=self.encoder_sparse_step,
172
+ num_experts=self.num_experts,
173
+ )
174
+
175
+ def prepare_config_and_inputs_for_common(self):
176
+ config, inputs_dict = self.prepare_config_and_inputs()
177
+ return config, inputs_dict
178
+
179
+ @require_torch
180
+ def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict):
181
+ model = NllbMoeModel(config=config).get_decoder().to(torch_device).eval()
182
+ input_ids = inputs_dict["input_ids"]
183
+ attention_mask = inputs_dict["attention_mask"]
184
+ head_mask = inputs_dict["head_mask"]
185
+
186
+ # first forward pass
187
+ outputs = model(input_ids, attention_mask=attention_mask, head_mask=head_mask, use_cache=True)
188
+
189
+ output, past_key_values = outputs.to_tuple()
190
+
191
+ # create hypothetical multiple next token and extent to next_input_ids
192
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
193
+ next_attn_mask = ids_tensor((self.batch_size, 3), 2)
194
+
195
+ # append to next input_ids and
196
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
197
+ next_attention_mask = torch.cat([attention_mask, next_attn_mask], dim=-1)
198
+
199
+ output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"]
200
+ output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[
201
+ "last_hidden_state"
202
+ ]
203
+
204
+ # select random slice
205
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
206
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
207
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
208
+
209
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
210
+
211
+ # test that outputs are equal for slice
212
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
213
+
214
+ def check_encoder_decoder_model_standalone(self, config, inputs_dict):
215
+ model = NllbMoeModel(config=config).to(torch_device).eval()
216
+ outputs = model(**inputs_dict)
217
+
218
+ encoder_last_hidden_state = outputs.encoder_last_hidden_state
219
+ last_hidden_state = outputs.last_hidden_state
220
+
221
+ with tempfile.TemporaryDirectory() as tmpdirname:
222
+ encoder = model.get_encoder()
223
+ encoder.save_pretrained(tmpdirname)
224
+ encoder = NllbMoeEncoder.from_pretrained(tmpdirname).to(torch_device)
225
+
226
+ encoder_last_hidden_state_2 = encoder(inputs_dict["input_ids"], attention_mask=inputs_dict["attention_mask"])[
227
+ 0
228
+ ]
229
+
230
+ self.parent.assertTrue((encoder_last_hidden_state_2 - encoder_last_hidden_state).abs().max().item() < 1e-3)
231
+
232
+ with tempfile.TemporaryDirectory() as tmpdirname:
233
+ decoder = model.get_decoder()
234
+ decoder.save_pretrained(tmpdirname)
235
+ decoder = NllbMoeDecoder.from_pretrained(tmpdirname).to(torch_device)
236
+
237
+ last_hidden_state_2 = decoder(
238
+ input_ids=inputs_dict["decoder_input_ids"],
239
+ attention_mask=inputs_dict["decoder_attention_mask"],
240
+ encoder_hidden_states=encoder_last_hidden_state,
241
+ encoder_attention_mask=inputs_dict["attention_mask"],
242
+ )[0]
243
+
244
+ self.parent.assertTrue((last_hidden_state_2 - last_hidden_state).abs().max().item() < 1e-3)
245
+
246
+
247
+ @require_torch
248
+ class NllbMoeModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
249
+ all_model_classes = (NllbMoeModel, NllbMoeForConditionalGeneration) if is_torch_available() else ()
250
+ pipeline_model_mapping = (
251
+ {
252
+ "feature-extraction": NllbMoeModel,
253
+ "summarization": NllbMoeForConditionalGeneration,
254
+ "text2text-generation": NllbMoeForConditionalGeneration,
255
+ "translation": NllbMoeForConditionalGeneration,
256
+ }
257
+ if is_torch_available()
258
+ else {}
259
+ )
260
+ is_encoder_decoder = True
261
+ fx_compatible = False
262
+ test_pruning = False
263
+ test_missing_keys = True
264
+ test_torchscript = False
265
+
266
+ # TODO: Fix the failed tests when this model gets more usage
267
+ def is_pipeline_test_to_skip(
268
+ self,
269
+ pipeline_test_case_name,
270
+ config_class,
271
+ model_architecture,
272
+ tokenizer_name,
273
+ image_processor_name,
274
+ feature_extractor_name,
275
+ processor_name,
276
+ ):
277
+ # Saving the slow tokenizer after saving the fast tokenizer causes the loading of the later hanging forever.
278
+ return True
279
+
280
+ def setUp(self):
281
+ self.model_tester = NllbMoeModelTester(self)
282
+ self.config_tester = ConfigTester(self, config_class=NllbMoeConfig)
283
+
284
+ def test_config(self):
285
+ self.config_tester.run_common_tests()
286
+
287
+ def test_save_load_strict(self):
288
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
289
+ for model_class in self.all_model_classes:
290
+ model = model_class(config)
291
+
292
+ with tempfile.TemporaryDirectory() as tmpdirname:
293
+ model.save_pretrained(tmpdirname)
294
+ model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True)
295
+ self.assertEqual(info["missing_keys"], [])
296
+
297
+ def test_decoder_model_past_with_large_inputs(self):
298
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
299
+ config.decoder_sparse_step = 0
300
+ self.model_tester.create_and_check_decoder_model_past_large_inputs(config, inputs_dict)
301
+
302
+ def test_encoder_decoder_model_standalone(self):
303
+ config_and_inputs = self.model_tester.prepare_config_and_inputs_for_common()
304
+ self.model_tester.check_encoder_decoder_model_standalone(*config_and_inputs)
305
+
306
+ def test_inputs_embeds(self):
307
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
308
+
309
+ for model_class in (NllbMoeModel, NllbMoeForConditionalGeneration):
310
+ model = model_class(config)
311
+ model.to(torch_device)
312
+ model.eval()
313
+
314
+ inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class))
315
+
316
+ if not self.is_encoder_decoder:
317
+ input_ids = inputs["input_ids"]
318
+ del inputs["input_ids"]
319
+ else:
320
+ encoder_input_ids = inputs["input_ids"]
321
+ decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids)
322
+ del inputs["input_ids"]
323
+ inputs.pop("decoder_input_ids", None)
324
+
325
+ wte = model.get_input_embeddings()
326
+ if not self.is_encoder_decoder:
327
+ inputs["inputs_embeds"] = wte(input_ids)
328
+ else:
329
+ inputs["inputs_embeds"] = wte(encoder_input_ids)
330
+ inputs["decoder_inputs_embeds"] = wte(decoder_input_ids)
331
+
332
+ with torch.no_grad():
333
+ model(**inputs)[0]
334
+
335
+ @require_torch_fp16
336
+ def test_generate_fp16(self):
337
+ config, input_dict = self.model_tester.prepare_config_and_inputs()
338
+ input_ids = input_dict["input_ids"]
339
+ attention_mask = input_ids.ne(1).to(torch_device)
340
+ model = NllbMoeForConditionalGeneration(config).eval().to(torch_device)
341
+ model.half()
342
+ model.generate(input_ids, attention_mask=attention_mask)
343
+ model.generate(num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3)
344
+
345
+ def test_get_loss(self):
346
+ config, input_dict = self.model_tester.prepare_config_and_inputs()
347
+ input_dict["output_router_logits"] = True
348
+ input_dict["labels"] = input_dict["input_ids"]
349
+ model = NllbMoeForConditionalGeneration(config).eval().to(torch_device)
350
+ out = model(**input_dict)
351
+ self.assertIsNotNone(out.loss)
352
+ self.assertIsNotNone(model(**input_dict)["encoder_router_logits"][1])
353
+ self.assertIsNotNone(model(**input_dict)["decoder_router_logits"][0])
354
+
355
+ @unittest.skip(
356
+ 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"
357
+ )
358
+ def test_load_save_without_tied_weights(self):
359
+ pass
360
+
361
+
362
+ @require_torch
363
+ @require_sentencepiece
364
+ @require_tokenizers
365
+ @slow
366
+ class NllbMoeModelIntegrationTests(unittest.TestCase):
367
+ @require_torch
368
+ @cached_property
369
+ def model_inputs(self):
370
+ return {
371
+ "input_ids": torch.LongTensor(
372
+ [
373
+ [28768, 248, 6399, 9, 65972, 452, 1925, 629, 123543, 248075, 2, 256047],
374
+ [117, 7027, 7195, 202, 44778, 248075, 2, 256047, 1, 1, 1, 1],
375
+ ]
376
+ ),
377
+ "attention_mask": torch.Tensor(
378
+ [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0]]
379
+ ),
380
+ "decoder_input_ids": torch.LongTensor([[2, 256057], [2, 256057]]),
381
+ }
382
+
383
+ @cached_property
384
+ def tokenizer(self):
385
+ return NllbTokenizer.from_pretrained("hf-internal-testing/random-nllb-moe-2-experts")
386
+
387
+ @cached_property
388
+ def big_model(self):
389
+ return NllbMoeForConditionalGeneration.from_pretrained("facebook/nllb-moe-54b")
390
+
391
+ def inference_no_head(self):
392
+ model = NllbMoeModel.from_pretrained("hf-internal-testing/random-nllb-moe-2-experts").eval()
393
+ with torch.no_grad():
394
+ output = model(**self.model_inputs)
395
+ # fmt: off
396
+ EXPECTED_ENCODER_STATE = torch.Tensor([ 0.3920, -0.1974, -0.0279, 0.3463, -0.8306, -1.0629, -0.4643, 2.0563, 1.1123, 0.3566, -0.9291, -0.3840, -0.2527, -0.9858, 1.5185, -1.1346, 0.0323, -0.9103, -0.3647, -0.4462, -0.9720, -0.3541, 0.1777, -0.4647, 1.6970, -0.9062, 0.2727, -1.0737, 0.8785, 0.4324])
397
+ EXPECTED_DECODER_STATE = torch.Tensor([-6.0425e-02, -2.0015e-01, 6.0575e-02, -8.6366e-01, -1.1310e+00, 6.8369e-01, 7.5615e-01, 7.3555e-01, 2.3071e-01, 1.5954e+00, -7.0728e-01, -2.2647e-01, -1.3292e+00, 4.8246e-01, -6.9153e-01, -1.8199e-02, -7.3664e-01, 1.5902e-03, 1.0760e-01, 1.0298e-01, -9.3933e-01, -4.6567e-01, 8.0417e-01, 1.5243e+00, 5.5844e-01, -9.9239e-02, 1.4885e+00, 7.1527e-02, -5.2612e-01, 9.4435e-02])
398
+ # fmt: on
399
+
400
+ torch.testing.assert_close(
401
+ output.encoder_last_hidden_state[1, 0, :30], EXPECTED_ENCODER_STATE, rtol=6e-3, atol=9e-3
402
+ )
403
+ torch.testing.assert_close(output.last_hidden_state[1, 0, :30], EXPECTED_DECODER_STATE, rtol=6e-3, atol=9e-3)
404
+
405
+ def test_inference_logits(self):
406
+ r"""
407
+ Logits testing to check implementation consistency between `fairseq` implementation
408
+ and `transformers` implementation of NLLB-MoE transformers. We only check the logits
409
+ of the second sample of the batch, as it is padded.
410
+ """
411
+ model = NllbMoeForConditionalGeneration.from_pretrained("hf-internal-testing/random-nllb-moe-2-experts").eval()
412
+ with torch.no_grad():
413
+ output = model(**self.model_inputs)
414
+
415
+ EXPECTED_LOGTIS = torch.Tensor([-0.3059, 0.0000, 9.3029, 0.6456, -0.9148, 1.7836, 0.6478, 0.9438, -0.5272, -0.6617, -1.2717, 0.4564, 0.1345, -0.2301, -1.0140, 1.1427, -1.5535, 0.1337, 0.2082, -0.8112, -0.3842, -0.3377, 0.1256, 0.6450, -0.0452, 0.0219, 1.4274, -0.4991, -0.2063, -0.4409,]) # fmt: skip
416
+ torch.testing.assert_close(output.logits[1, 0, :30], EXPECTED_LOGTIS, rtol=6e-3, atol=9e-3)
417
+
418
+ @unittest.skip(reason="This requires 300GB of RAM")
419
+ def test_large_logits(self):
420
+ model = self.big_model
421
+ with torch.no_grad():
422
+ output = model(**self.model_inputs)
423
+
424
+ # fmt: off
425
+ EXPECTED_ENCODER_STATE = torch.Tensor([ 0.1696, -0.0059, 0.0489, 0.0479, -0.4222, -0.2178, -0.1372, -0.0860, -0.4249, -0.0081, -0.1186, 0.6678, 0.0160, 0.4140, 0.1799, 0.0672, -0.4941, 0.0173, -0.0740, 0.0845, -0.2197, 0.4465, 0.2268, -0.1752, -0.0562, 0.1033, -0.0869, -0.5490, 0.0582, 0.2165])
426
+ EXPECTED_DECODER_STATE = torch.Tensor([ 0.0374, -0.1055, -0.1060, -0.1711, -0.0540, -0.1183, -0.0779, 0.0610, -0.0279, -0.0848, 0.0222, 0.0372, -0.0298, -0.0861, -0.0354, -0.0103, 0.0538, -0.0148, -0.0105, 0.0224, 0.0629, -0.0291, -0.0671, 0.0173, -0.0066, -0.0245, -0.0499, 0.0760, -0.0067, 0.0086])
427
+ EXPECTED_LOGTIS = torch.Tensor([ 0.3834, 0.2057, 4.5399, 0.8301, 0.4810, 0.9325, 0.9928, 0.9574, 0.5517, 0.9156, 0.2698, 0.6728, 0.7121, 0.3080, 0.4693, 0.5756, 1.0407, 0.2219, 0.3714, 0.5699, 0.5547, 0.8472, 0.3178, 0.1286, 0.1791, 0.9391, 0.5153, -0.2146, 0.1689, 0.6816])
428
+ # fmt: on
429
+
430
+ torch.testing.assert_close(
431
+ output.encoder_last_hidden_state[1, 0, :30], EXPECTED_ENCODER_STATE, rtol=6e-3, atol=9e-3
432
+ )
433
+ torch.testing.assert_close(output.last_hidden_state[1, 0, :30], EXPECTED_DECODER_STATE, rtol=6e-3, atol=9e-3)
434
+ torch.testing.assert_close(output.logits[1, 0, :30], EXPECTED_LOGTIS, rtol=6e-3, atol=9e-3)
435
+
436
+ @unittest.skip(reason="This requires 300GB of RAM")
437
+ def test_seq_to_seq_generation(self):
438
+ model = self.big_model
439
+ tokenizer = NllbTokenizer.from_pretrained("facebook/nllb-moe-54b")
440
+
441
+ # first 6 samples of load_dataset("facebook/flores", "eng_Latn-fra_Latn"), devtest. Truth are very similar to the fairseq translation files
442
+ FIRST_6_FLORES_200 = [
443
+ 'We now have 4-month-old mice that are non-diabetic that used to be diabetic," he added.',
444
+ "Dr. Ehud Ur, professor of medicine at Dalhousie University in Halifax, Nova Scotia and chair of the clinical and scientific division of the Canadian Diabetes Association cautioned that the research is still in its early days.",
445
+ "Like some other experts, he is skeptical about whether diabetes can be cured, noting that these findings have no relevance to people who already have Type 1 diabetes.",
446
+ "On Monday, Sara Danius, permanent secretary of the Nobel Committee for Literature at the Swedish Academy, publicly announced during a radio program on Sveriges Radio in Sweden the committee, unable to reach Bob Dylan directly about winning the 2016 Nobel Prize in Literature, had abandoned its efforts to reach him.",
447
+ 'Danius said, "Right now we are doing nothing. I have called and sent emails to his closest collaborator and received very friendly replies. For now, that is certainly enough."',
448
+ "Previously, Ring's CEO, Jamie Siminoff, remarked the company started when his doorbell wasn't audible from his shop in his garage.",
449
+ ]
450
+ inputs = tokenizer(FIRST_6_FLORES_200, padding=True, return_tensors="pt").to(torch_device)
451
+ batch_translation = model.generate(**inputs, forced_bos_token_id=tokenizer.lang_code_to_id["fra_Latn"])
452
+
453
+ EXPECTED_FAIRSEQ_TRANSLATION = [
454
+ '"Nous avons maintenant des souris de 4 mois non diabétiques qui étaient diabétiques", a-t-il ajouté.',
455
+ "Le docteur Ehud Ur, professeur de médecine à l'université Dalhousie, à Halifax, en Nouvelle-Écosse, et président de la division clinique et scientifique de l'Association canadienne du diabète, prévient que la recherche n'en est qu'à ses débuts.",
456
+ "Comme d'autres spécialistes, il est sceptique quant à la guérison du diabète.",
457
+ "Lundi, Sara Danius, secrétaire permanente du Comité Nobel de littérature à l'Académie suédoise, a annoncé publiquement lors d'une émission de radio sur Sveriges Radio en Suède que le comité, incapable de joindre Bob Dylan directement pour lui annoncer le prix Nobel de littérature 2016, avait abandonné ses efforts pour le joindre.",
458
+ "Danius a déclaré: \"Pour l'instant, nous ne faisons rien. J'ai appelé et envoyé des courriels à son plus proche collaborateur et j'ai reçu des réponses très amicales. Pour l'instant, c'est certainement suffisant\".",
459
+ "Auparavant, le PDG de Ring, Jamie Siminoff, a fait remarquer que la société avait commencé lorsque sa sonnette n'était pas audible depuis son magasin dans son garage.",
460
+ ]
461
+
462
+ translation = tokenizer.batch_decode(
463
+ batch_translation.tolist(), clean_up_tokenization_spaces=True, skip_special_tokens=True
464
+ )
465
+ assert translation == EXPECTED_FAIRSEQ_TRANSLATION
466
+
467
+
468
+ @require_torch
469
+ class NllbMoeRouterTest(unittest.TestCase):
470
+ r"""
471
+ Switch Transformers has different blocks from classic transformer based models.
472
+ The Swift MLP contains a Router class, that has to be tested to check if it is correctly implemented
473
+
474
+ Original implementation of the routers here:
475
+
476
+ """
477
+
478
+ config = NllbMoeConfig(
479
+ num_experts=4,
480
+ hidden_size=32,
481
+ d_ff=16,
482
+ expert_capacity=4,
483
+ )
484
+ batch_size = 2
485
+ sequence_length = 20
486
+
487
+ def test_top_2_routing(self):
488
+ # test routing with minimal reproduction
489
+ mask = torch.ones((self.batch_size, self.sequence_length), dtype=torch.bool)
490
+ mask[0][0] = False
491
+ mask[1][0] = False
492
+ mask = mask.reshape(-1)
493
+ set_seed(0)
494
+ hidden_states = torch.rand((self.batch_size, self.sequence_length, self.config.hidden_size))
495
+ classfier = torch.nn.Linear(self.config.hidden_size, self.config.num_experts)
496
+ hf_router = NllbMoeTop2Router(self.config)
497
+
498
+ _, _, hidden_dim = hidden_states.shape
499
+ logits = classfier(hidden_states.reshape((self.batch_size * self.sequence_length), hidden_dim))
500
+ top_1_mask, router_probs = hf_router.route_tokens(logits, padding_mask=mask)
501
+ torch.argmax(top_1_mask, dim=-1)
502
+ router_mask = router_probs.bool()
503
+ set_seed(0)
504
+ experts = [
505
+ torch.nn.Linear(hidden_dim, hidden_dim),
506
+ torch.nn.Linear(hidden_dim, hidden_dim),
507
+ torch.nn.Linear(hidden_dim, hidden_dim),
508
+ torch.nn.Linear(hidden_dim, hidden_dim),
509
+ ]
510
+ hidden_states = hidden_states.reshape((self.batch_size * self.sequence_length), hidden_dim)
511
+ masked_hidden_states = torch.einsum("bm,be->ebm", hidden_states, router_mask)
512
+ for idx, expert in enumerate(experts):
513
+ token_indices = router_mask[:, idx]
514
+ combining_weights = router_probs[token_indices, idx]
515
+ expert_output = expert(masked_hidden_states[idx, token_indices])
516
+ expert_output *= 1 - self.config.moe_token_dropout
517
+ masked_hidden_states[idx, token_indices] = torch.einsum("b,be->be", combining_weights, expert_output)
518
+ hidden_states = masked_hidden_states.sum(dim=0).reshape(self.batch_size, self.sequence_length, hidden_dim)
519
+
520
+ EXPECTED_MEAN_FAIRSEQ_HIDDEN_STATES = torch.Tensor([[ 7.0340e-04, 2.7997e-03, -1.3351e-02, -7.6705e-03, -3.5089e-03,3.9773e-03, 7.4593e-03, 1.2566e-02, 3.5860e-03, -2.7448e-02,-1.3731e-02, -1.0534e-02, -1.3606e-02, -1.5048e-02, -2.8914e-03,-5.0371e-03, -1.3963e-03, 6.0076e-03, -1.1380e-02, -1.4620e-02, 5.2401e-03, 8.4660e-04, -1.5319e-03, -1.6735e-02, 1.1302e-02, 3.6119e-03, 4.6084e-03, -1.3458e-02, 7.7792e-05, 1.4312e-02, 4.9107e-03, -5.0936e-03], [-4.4538e-03, 3.1026e-03, 1.4121e-04, -4.8121e-03, -5.6279e-03, 7.2493e-03, 3.9769e-03, 1.1114e-02, -1.5666e-03, -2.3477e-02, 8.7268e-03, 1.3446e-02, -2.8845e-05, -1.7287e-02, 8.7619e-03, -4.5316e-03, -1.2164e-02, 5.7461e-03, -4.5861e-03, -9.3907e-03, 2.9808e-02, 8.9206e-04, -7.6232e-04, -1.4173e-02, 3.0208e-03, 1.5310e-02, 9.7717e-03, 3.1014e-03, 7.8042e-03, 8.0197e-03, 3.4784e-03, -7.1728e-03]]) # fmt: skip
521
+ torch.testing.assert_close(hidden_states.mean(1), EXPECTED_MEAN_FAIRSEQ_HIDDEN_STATES, atol=1e-4, rtol=1e-4)
522
+
523
+ def test_batch_prioritized_routing(self):
524
+ set_seed(0)
525
+ config = NllbMoeConfig(
526
+ num_experts=4, hidden_size=32, d_ff=16, expert_capacity=4, second_expert_policy="random"
527
+ )
528
+ mask = torch.zeros((self.batch_size * self.sequence_length), dtype=torch.bool)
529
+ logits = torch.rand((self.batch_size * self.sequence_length, 4))
530
+ config.batch_prioritized_routing = True
531
+ router = NllbMoeTop2Router(config)
532
+ top_1_mask, _ = router.route_tokens(logits, padding_mask=mask)
533
+ # check that the routing is batch first. One of the last token is routed while expert capacity is very small
534
+ # this means that it had a greater probability of being routed
535
+ assert top_1_mask[-1, 0] == 1
536
+
537
+ def test_second_expert_policy(self):
538
+ config = NllbMoeConfig(
539
+ num_experts=4,
540
+ hidden_size=32,
541
+ d_ff=16,
542
+ expert_capacity=40,
543
+ )
544
+ set_seed(0)
545
+ mask = torch.zeros((self.batch_size * self.sequence_length), dtype=torch.bool)
546
+ logits = torch.rand((self.batch_size * self.sequence_length, 4))
547
+
548
+ set_seed(0)
549
+ config.second_expert_policy = "random"
550
+ router = NllbMoeTop2Router(config)
551
+ top_1_mask, router_probs = router.route_tokens(logits, padding_mask=mask)
552
+
553
+ set_seed(0)
554
+ config.second_expert_policy = "sampling"
555
+ router = NllbMoeTop2Router(config)
556
+ top_1_mask_sp, router_probs_sp = router.route_tokens(logits, padding_mask=mask)
557
+
558
+ set_seed(0)
559
+ config.second_expert_policy = "all"
560
+ router = NllbMoeTop2Router(config)
561
+ top_1_mask_all, router_probs_all = router.route_tokens(logits, padding_mask=mask)
562
+
563
+ # fmt: off
564
+ EXPECTED_ROUTER_ALL = torch.tensor([[0.3902, 0.0000, 0.0000, 0.6098], [0.0000, 0.0000, 0.7770, 0.2230], [0.0000, 0.0000, 0.2726, 0.7274], [0.4221, 0.0000, 0.5779, 0.0000], [0.0000, 0.0000, 0.7810, 0.2190], [0.5518, 0.4482, 0.0000, 0.0000], [0.0000, 0.4060, 0.5940, 0.0000], [0.7340, 0.0000, 0.0000, 0.2660], [0.4778, 0.5222, 0.0000, 0.0000], [0.0000, 0.3984, 0.0000, 0.6016], [0.0000, 0.0548, 0.9452, 0.0000], [0.6796, 0.0000, 0.0000, 0.3204], [0.0700, 0.0000, 0.9300, 0.0000], [0.1854, 0.0000, 0.8146, 0.0000], [0.6775, 0.3225, 0.0000, 0.0000], [0.0000, 0.0000, 0.5027, 0.4973], [0.0000, 0.6577, 0.0000, 0.3423], [0.0000, 0.7767, 0.0000, 0.2233], [0.1944, 0.8056, 0.0000, 0.0000], [0.0000, 0.3073, 0.0000, 0.6927], [0.0000, 0.5655, 0.4345, 0.0000], [0.5791, 0.0000, 0.0000, 0.4209], [0.0440, 0.0000, 0.9560, 0.0000], [0.0083, 0.9917, 0.0000, 0.0000], [0.0000, 0.8395, 0.0000, 0.1605], [0.0000, 0.1458, 0.0000, 0.8542], [0.0000, 0.8534, 0.1466, 0.0000], [0.4938, 0.0000, 0.0000, 0.5062], [0.1329, 0.8671, 0.0000, 0.0000], [0.3058, 0.0000, 0.6942, 0.0000], [0.4458, 0.0000, 0.0000, 0.5542], [0.9053, 0.0947, 0.0000, 0.0000], [0.0000, 0.7563, 0.2437, 0.0000], [0.0000, 0.0000, 0.4096, 0.5904], [0.4551, 0.0000, 0.0000, 0.5449], [0.8502, 0.1498, 0.0000, 0.0000], [0.0000, 0.6312, 0.3688, 0.0000], [0.8920, 0.0000, 0.0000, 0.1080], [0.1913, 0.0000, 0.0000, 0.8087], [0.2491, 0.7509, 0.0000, 0.0000]])
565
+ EXPECTED_ROUTER_SP = torch.tensor([[0.0000, 0.6539, 0.0000, 0.3461], [0.0000, 0.0000, 0.3998, 0.6002], [0.0000, 0.5574, 0.0000, 0.4426], [0.0000, 0.0000, 0.4441, 0.5559], [0.0000, 0.6545, 0.3455, 0.0000], [0.4419, 0.5581, 0.0000, 0.0000], [0.0000, 0.4014, 0.5986, 0.0000], [0.3215, 0.0000, 0.0000, 0.6785], [0.4765, 0.5235, 0.0000, 0.0000], [0.0000, 0.5467, 0.0000, 0.4533], [0.0000, 0.4156, 0.5844, 0.0000], [0.3370, 0.0000, 0.6630, 0.0000], [0.0000, 0.0000, 0.4558, 0.5442], [0.4659, 0.0000, 0.5341, 0.0000], [0.6179, 0.3821, 0.0000, 0.0000], [0.6277, 0.0000, 0.3723, 0.0000], [0.5836, 0.4164, 0.0000, 0.0000], [0.0000, 0.6600, 0.0000, 0.3400], [0.0000, 0.4933, 0.0000, 0.5067], [0.6016, 0.0000, 0.0000, 0.3984], [0.0000, 0.5160, 0.4840, 0.0000], [0.5799, 0.0000, 0.0000, 0.4201], [0.0000, 0.0000, 0.4826, 0.5174], [0.5426, 0.4574, 0.0000, 0.0000], [0.5362, 0.4638, 0.0000, 0.0000], [0.6448, 0.0000, 0.0000, 0.3552], [0.0000, 0.5909, 0.4091, 0.0000], [0.4196, 0.0000, 0.0000, 0.5804], [0.3191, 0.6809, 0.0000, 0.0000], [0.0000, 0.0000, 0.4886, 0.5114], [0.4899, 0.0000, 0.0000, 0.5101], [0.4123, 0.0000, 0.5877, 0.0000], [0.0000, 0.3736, 0.0000, 0.6264], [0.0000, 0.0000, 0.6009, 0.3991], [0.4246, 0.0000, 0.0000, 0.5754], [0.4997, 0.0000, 0.5003, 0.0000], [0.0000, 0.3595, 0.6405, 0.0000], [0.5433, 0.0000, 0.0000, 0.4567], [0.0000, 0.6806, 0.0000, 0.3194], [0.6689, 0.3311, 0.0000, 0.0000]])
566
+ EXPECTED_ROUTER = torch.tensor([[0.4324, 0.5676, 0.0000, 0.0000], [0.0000, 0.4348, 0.0000, 0.5652], [0.4559, 0.5441, 0.0000, 0.0000], [0.0000, 0.0000, 0.0000, 1.0000], [0.4744, 0.5256, 0.0000, 0.0000], [0.0000, 0.5103, 0.0000, 0.4897], [0.0000, 0.0000, 1.0000, 0.0000], [0.0000, 0.0000, 0.0000, 1.0000], [0.0000, 1.0000, 0.0000, 0.0000], [0.0000, 0.5467, 0.0000, 0.4533], [0.0000, 0.0000, 1.0000, 0.0000], [0.0000, 0.0000, 1.0000, 0.0000], [0.0000, 0.0000, 0.0000, 1.0000], [0.0000, 0.0000, 1.0000, 0.0000], [1.0000, 0.0000, 0.0000, 0.0000], [0.5063, 0.4937, 0.0000, 0.0000], [0.5396, 0.0000, 0.0000, 0.4604], [0.4576, 0.5424, 0.0000, 0.0000], [0.0000, 0.0000, 0.0000, 1.0000], [0.5134, 0.0000, 0.4866, 0.0000], [0.0000, 0.5160, 0.4840, 0.0000], [0.5439, 0.0000, 0.4561, 0.0000], [0.4849, 0.0000, 0.0000, 0.5151], [0.5426, 0.4574, 0.0000, 0.0000], [0.5362, 0.4638, 0.0000, 0.0000], [1.0000, 0.0000, 0.0000, 0.0000], [0.0000, 1.0000, 0.0000, 0.0000], [0.0000, 0.4448, 0.0000, 0.5552], [0.0000, 1.0000, 0.0000, 0.0000], [0.0000, 0.0000, 0.4886, 0.5114], [0.4899, 0.0000, 0.0000, 0.5101], [0.0000, 0.0000, 0.5296, 0.4704], [0.0000, 0.0000, 0.4469, 0.5531], [0.0000, 0.4053, 0.5947, 0.0000], [0.0000, 0.0000, 0.4460, 0.5540], [0.4997, 0.0000, 0.5003, 0.0000], [0.0000, 0.0000, 0.5851, 0.4149], [1.0000, 0.0000, 0.0000, 0.0000], [0.0000, 0.5010, 0.4990, 0.0000], [1.0000, 0.0000, 0.0000, 0.0000]])
567
+
568
+ EXPECTED_TOP_1_ALL = torch.LongTensor([[0, 0, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 0, 1, 0], [1, 0, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0], [0, 0, 1, 0], [0, 0, 1, 0], [1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 1, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0]])
569
+ EXPECTED_TOP_1_SP = torch.LongTensor([[0, 1, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1], [0, 1, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 1, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 0, 1], [0, 1, 0, 0], [0, 0, 0, 1], [0, 0, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 0, 0, 1], [0, 0, 1, 0], [0, 0, 1, 0], [1, 0, 0, 0], [0, 1, 0, 0], [1, 0, 0, 0]])
570
+ # `sampling` and `random` do not affect the mask of the top_1 router
571
+ # fmt: on
572
+
573
+ torch.testing.assert_close(router_probs_all, EXPECTED_ROUTER_ALL, rtol=1e-4, atol=1e-4)
574
+ torch.testing.assert_close(router_probs_sp, EXPECTED_ROUTER_SP, rtol=1e-4, atol=1e-4)
575
+ torch.testing.assert_close(router_probs, EXPECTED_ROUTER, rtol=1e-4, atol=1e-4)
576
+
577
+ torch.testing.assert_close(top_1_mask_all, EXPECTED_TOP_1_ALL, rtol=1e-4, atol=1e-4)
578
+ torch.testing.assert_close(top_1_mask_sp, EXPECTED_TOP_1_SP, rtol=1e-4, atol=1e-4)
579
+ torch.testing.assert_close(top_1_mask, EXPECTED_TOP_1_SP, rtol=1e-4, atol=1e-4)
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/nougat/__init__.py ADDED
File without changes
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/nougat/test_image_processing_nougat.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from huggingface_hub import hf_hub_download
21
+
22
+ from transformers.testing_utils import require_torch, require_vision
23
+ from transformers.utils import cached_property, 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 NougatImageProcessor
35
+
36
+
37
+ class NougatImageProcessingTester:
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
+ do_crop_margin=True,
47
+ do_resize=True,
48
+ size=None,
49
+ do_thumbnail=True,
50
+ do_align_long_axis: bool = False,
51
+ do_pad=True,
52
+ do_normalize: bool = True,
53
+ image_mean=[0.5, 0.5, 0.5],
54
+ image_std=[0.5, 0.5, 0.5],
55
+ ):
56
+ size = size if size is not None else {"height": 20, "width": 20}
57
+ self.parent = parent
58
+ self.batch_size = batch_size
59
+ self.num_channels = num_channels
60
+ self.image_size = image_size
61
+ self.min_resolution = min_resolution
62
+ self.max_resolution = max_resolution
63
+ self.do_crop_margin = do_crop_margin
64
+ self.do_resize = do_resize
65
+ self.size = size
66
+ self.do_thumbnail = do_thumbnail
67
+ self.do_align_long_axis = do_align_long_axis
68
+ self.do_pad = do_pad
69
+ self.do_normalize = do_normalize
70
+ self.image_mean = image_mean
71
+ self.image_std = image_std
72
+
73
+ def prepare_image_processor_dict(self):
74
+ return {
75
+ "do_crop_margin": self.do_crop_margin,
76
+ "do_resize": self.do_resize,
77
+ "size": self.size,
78
+ "do_thumbnail": self.do_thumbnail,
79
+ "do_align_long_axis": self.do_align_long_axis,
80
+ "do_pad": self.do_pad,
81
+ "do_normalize": self.do_normalize,
82
+ "image_mean": self.image_mean,
83
+ "image_std": self.image_std,
84
+ }
85
+
86
+ def expected_output_image_shape(self, images):
87
+ return self.num_channels, self.size["height"], self.size["width"]
88
+
89
+ def prepare_dummy_image(self):
90
+ filepath = hf_hub_download(
91
+ repo_id="hf-internal-testing/fixtures_docvqa", filename="nougat_pdf.png", repo_type="dataset"
92
+ )
93
+ image = Image.open(filepath).convert("RGB")
94
+ return image
95
+
96
+ def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
97
+ return prepare_image_inputs(
98
+ batch_size=self.batch_size,
99
+ num_channels=self.num_channels,
100
+ min_resolution=self.min_resolution,
101
+ max_resolution=self.max_resolution,
102
+ equal_resolution=equal_resolution,
103
+ numpify=numpify,
104
+ torchify=torchify,
105
+ )
106
+
107
+
108
+ @require_torch
109
+ @require_vision
110
+ class NougatImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
111
+ image_processing_class = NougatImageProcessor if is_vision_available() else None
112
+
113
+ def setUp(self):
114
+ super().setUp()
115
+ self.image_processor_tester = NougatImageProcessingTester(self)
116
+
117
+ @property
118
+ def image_processor_dict(self):
119
+ return self.image_processor_tester.prepare_image_processor_dict()
120
+
121
+ @cached_property
122
+ def image_processor(self):
123
+ return self.image_processing_class(**self.image_processor_dict)
124
+
125
+ def test_image_processor_properties(self):
126
+ image_processing = self.image_processing_class(**self.image_processor_dict)
127
+ self.assertTrue(hasattr(image_processing, "do_resize"))
128
+ self.assertTrue(hasattr(image_processing, "size"))
129
+ self.assertTrue(hasattr(image_processing, "do_normalize"))
130
+ self.assertTrue(hasattr(image_processing, "image_mean"))
131
+ self.assertTrue(hasattr(image_processing, "image_std"))
132
+
133
+ def test_image_processor_from_dict_with_kwargs(self):
134
+ image_processor = self.image_processing_class.from_dict(self.image_processor_dict)
135
+ self.assertEqual(image_processor.size, {"height": 20, "width": 20})
136
+
137
+ image_processor = self.image_processing_class.from_dict(self.image_processor_dict, size=42)
138
+ self.assertEqual(image_processor.size, {"height": 42, "width": 42})
139
+
140
+ def test_expected_output(self):
141
+ dummy_image = self.image_processor_tester.prepare_dummy_image()
142
+ image_processor = self.image_processor
143
+ inputs = image_processor(dummy_image, return_tensors="pt")
144
+ torch.testing.assert_close(inputs["pixel_values"].mean(), torch.tensor(0.4906), rtol=1e-3, atol=1e-3)
145
+
146
+ def test_crop_margin_all_white(self):
147
+ image = np.uint8(np.ones((100, 100, 3)) * 255)
148
+ image_processor = self.image_processor
149
+ cropped_image = image_processor.crop_margin(image)
150
+ self.assertTrue(np.array_equal(image, cropped_image))
151
+
152
+ def test_crop_margin_centered_black_square(self):
153
+ image = np.ones((100, 100, 3), dtype=np.uint8) * 255
154
+ image[45:55, 45:55, :] = 0
155
+ image_processor = self.image_processor
156
+ cropped_image = image_processor.crop_margin(image)
157
+ expected_cropped = image[45:55, 45:55, :]
158
+ self.assertTrue(np.array_equal(expected_cropped, cropped_image))
159
+
160
+ def test_align_long_axis_no_rotation(self):
161
+ image = np.uint8(np.ones((100, 200, 3)) * 255)
162
+ image_processor = self.image_processor
163
+ size = {"height": 200, "width": 300}
164
+ aligned_image = image_processor.align_long_axis(image, size)
165
+ self.assertEqual(image.shape, aligned_image.shape)
166
+
167
+ def test_align_long_axis_with_rotation(self):
168
+ image = np.uint8(np.ones((200, 100, 3)) * 255)
169
+ image_processor = self.image_processor
170
+ size = {"height": 300, "width": 200}
171
+ aligned_image = image_processor.align_long_axis(image, size)
172
+ self.assertEqual((200, 100, 3), aligned_image.shape)
173
+
174
+ def test_align_long_axis_data_format(self):
175
+ image = np.uint8(np.ones((100, 200, 3)) * 255)
176
+ data_format = "channels_first"
177
+ size = {"height": 200, "width": 300}
178
+ image_processor = self.image_processor
179
+ aligned_image = image_processor.align_long_axis(image, size, data_format=data_format)
180
+ self.assertEqual((3, 100, 200), aligned_image.shape)
181
+
182
+ def prepare_dummy_np_image(self):
183
+ filepath = hf_hub_download(
184
+ repo_id="hf-internal-testing/fixtures_docvqa", filename="nougat_pdf.png", repo_type="dataset"
185
+ )
186
+ image = Image.open(filepath).convert("RGB")
187
+ return np.array(image)
188
+
189
+ def test_crop_margin_equality_cv2_python(self):
190
+ image = self.prepare_dummy_np_image()
191
+ image_processor = self.image_processor
192
+ image_cropped_python = image_processor.crop_margin(image)
193
+
194
+ self.assertEqual(image_cropped_python.shape, (850, 685, 3))
195
+ self.assertEqual(image_cropped_python.mean(), 237.43881150708458)
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/nougat/test_tokenization_nougat.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import unittest
17
+
18
+ from transformers import NougatTokenizerFast
19
+ from transformers.models.nougat.tokenization_nougat_fast import markdown_compatible, normalize_list_like_lines
20
+ from transformers.testing_utils import require_levenshtein, require_nltk, require_tokenizers
21
+
22
+ from ...test_tokenization_common import TokenizerTesterMixin
23
+
24
+
25
+ @require_tokenizers
26
+ class NougatTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
27
+ from_pretrained_id = "facebook/nougat-base"
28
+ slow_tokenizer_class = None
29
+ rust_tokenizer_class = NougatTokenizerFast
30
+ tokenizer_class = NougatTokenizerFast
31
+ test_rust_tokenizer = True
32
+ test_slow_tokenizer = False
33
+ from_pretrained_vocab_key = "tokenizer_file"
34
+ special_tokens_map = {"bos_token": "<s>", "eos_token": "</s>", "unk_token": "<unk>", "pad_token": "<pad>"}
35
+
36
+ def setUp(self):
37
+ super().setUp()
38
+ tokenizer = NougatTokenizerFast.from_pretrained("facebook/nougat-base")
39
+ tokenizer.save_pretrained(self.tmpdirname)
40
+
41
+ def get_rust_tokenizer(self, **kwargs):
42
+ kwargs.update(self.special_tokens_map)
43
+ return NougatTokenizerFast.from_pretrained(self.tmpdirname, **kwargs)
44
+
45
+ def test_padding(self, max_length=6):
46
+ for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
47
+ with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"):
48
+ tokenizer_r = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs)
49
+ # Simple input
50
+ sentence1 = "This is a simple input"
51
+ sentence2 = ["This is a simple input 1", "This is a simple input 2"]
52
+ pair1 = ("This is a simple input", "This is a pair")
53
+ pair2 = [
54
+ ("This is a simple input 1", "This is a simple input 2"),
55
+ ("This is a simple pair 1", "This is a simple pair 2"),
56
+ ]
57
+
58
+ # Simple input tests
59
+ try:
60
+ tokenizer_r.encode(sentence1, max_length=max_length)
61
+ tokenizer_r.encode_plus(sentence1, max_length=max_length)
62
+
63
+ tokenizer_r.batch_encode_plus(sentence2, max_length=max_length)
64
+ tokenizer_r.encode(pair1, max_length=max_length)
65
+ tokenizer_r.batch_encode_plus(pair2, max_length=max_length)
66
+ except ValueError:
67
+ self.fail("Nougat Tokenizer should be able to deal with padding")
68
+
69
+ tokenizer_r.pad_token = None # Hotfixing padding = None
70
+ self.assertRaises(
71
+ ValueError, tokenizer_r.encode, sentence1, max_length=max_length, padding="max_length"
72
+ )
73
+
74
+ # Simple input
75
+ self.assertRaises(
76
+ ValueError, tokenizer_r.encode_plus, sentence1, max_length=max_length, padding="max_length"
77
+ )
78
+
79
+ # Simple input
80
+ self.assertRaises(
81
+ ValueError,
82
+ tokenizer_r.batch_encode_plus,
83
+ sentence2,
84
+ max_length=max_length,
85
+ padding="max_length",
86
+ )
87
+
88
+ # Pair input
89
+ self.assertRaises(ValueError, tokenizer_r.encode, pair1, max_length=max_length, padding="max_length")
90
+
91
+ # Pair input
92
+ self.assertRaises(
93
+ ValueError, tokenizer_r.encode_plus, pair1, max_length=max_length, padding="max_length"
94
+ )
95
+
96
+ # Pair input
97
+ self.assertRaises(
98
+ ValueError,
99
+ tokenizer_r.batch_encode_plus,
100
+ pair2,
101
+ max_length=max_length,
102
+ padding="max_length",
103
+ )
104
+
105
+ @unittest.skip(reason="NougatTokenizerFast does not have tokenizer_file in its signature")
106
+ def test_rust_tokenizer_signature(self):
107
+ pass
108
+
109
+ @unittest.skip(reason="NougatTokenizerFast does not support pretokenized inputs")
110
+ def test_pretokenized_inputs(self):
111
+ pass
112
+
113
+ @unittest.skip(reason="NougatTokenizerFast directly inherits from PreTrainedTokenizerFast")
114
+ def test_prepare_for_model(self):
115
+ pass
116
+
117
+ @unittest.skip(reason="This needs a slow tokenizer. Nougat does not have one!")
118
+ def test_encode_decode_with_spaces(self):
119
+ pass
120
+
121
+
122
+ class MarkdownCompatibleTest(unittest.TestCase):
123
+ def test_equation_tag(self):
124
+ input_text = "(3.2) \\[Equation Text\\]"
125
+ excepted_output = "\\[Equation Text \\tag{3.2}\\]"
126
+ self.assertEqual(markdown_compatible(input_text), excepted_output)
127
+
128
+ def test_equation_tag_letters(self):
129
+ input_text = "(18a) \\[Equation Text\\]"
130
+ excepted_output = "\\[Equation Text \\tag{18a}\\]"
131
+ self.assertEqual(markdown_compatible(input_text), excepted_output)
132
+
133
+ def test_bold_formatting(self):
134
+ input_text = r"This is \bm{bold} text."
135
+ expected_output = r"This is \mathbf{bold} text."
136
+ self.assertEqual(markdown_compatible(input_text), expected_output)
137
+
138
+ def test_url_conversion(self):
139
+ input_text = "Visit my website at https://www.example.com"
140
+ expected_output = "Visit my website at [https://www.example.com](https://www.example.com)"
141
+ self.assertEqual(markdown_compatible(input_text), expected_output)
142
+
143
+ def test_algorithm_code_block(self):
144
+ input_text = "```python\nprint('Hello, world!')\n```"
145
+ expected_output = "```\npython\nprint('Hello, world!')\n```"
146
+ self.assertEqual(markdown_compatible(input_text), expected_output)
147
+
148
+ def test_escape_characters(self):
149
+ input_text = r"Escaped characters like \n should not be \\[affected\\]"
150
+ expected_output = r"Escaped characters like \n should not be \\[affected\\]"
151
+ self.assertEqual(markdown_compatible(input_text), expected_output)
152
+
153
+ def test_nested_tags(self):
154
+ input_text = r"This is a super nested \bm{\bm{\bm{\bm{\bm{bold}}}}} tag."
155
+ expected_output = r"This is a super nested \mathbf{\mathbf{\mathbf{\mathbf{\mathbf{bold}}}}} tag."
156
+ self.assertEqual(markdown_compatible(input_text), expected_output)
157
+
158
+
159
+ class TestNormalizeListLikeLines(unittest.TestCase):
160
+ def test_two_level_lines(self):
161
+ input_str = "* Item 1 * Item 2"
162
+ expected_output = "* Item 1\n* Item 2\n"
163
+ self.assertEqual(normalize_list_like_lines(input_str), expected_output)
164
+
165
+ def test_three_level_lines(self):
166
+ input_str = "- I. Item 1 - II. Item 2 - III. Item 3"
167
+ expected_output = "- I. Item 1\n- II. Item 2\n- III. Item 3\n"
168
+ self.assertEqual(normalize_list_like_lines(input_str), expected_output)
169
+
170
+ def test_nested_lines(self):
171
+ input_str = "- I. Item 1 - I.1 Sub-item 1 - I.1.1 Sub-sub-item 1 - II. Item 2"
172
+ expected_output = "- I. Item 1\n\t- I.1 Sub-item 1\n\t\t- I.1.1 Sub-sub-item 1\n- II. Item 2\n"
173
+ self.assertEqual(normalize_list_like_lines(input_str), expected_output)
174
+
175
+
176
+ @require_tokenizers
177
+ class NougatPostProcessingTest(unittest.TestCase):
178
+ def setUp(self):
179
+ super().setUp()
180
+ self.tokenizer = NougatTokenizerFast.from_pretrained("facebook/nougat-base")
181
+
182
+ def test_correct_tables_basic(self):
183
+ input_str = "\\begin{table} \\begin{tabular}{l l} & \\ \\end{tabular} \\end{table}"
184
+ expected_output = "\\begin{table}\n\\begin{tabular}{l l} & \\ \\end{tabular}\n\\end{table}"
185
+ self.assertEqual(self.tokenizer.correct_tables(input_str), expected_output)
186
+
187
+ def test_correct_tables_high_count(self):
188
+ input_str = "\\begin{tabular}" * 20
189
+ expected_output = ""
190
+ self.assertEqual(self.tokenizer.correct_tables(input_str), expected_output)
191
+
192
+ @require_levenshtein
193
+ @require_nltk
194
+ def test_postprocess_as_nougat_no_markdown(self):
195
+ input_str = "# Nougat: Neural Optical Understanding for Academic Documents\n\n Lukas Blecher\n\nCorrespondence to: lblecher@meta.com\n\nGuillem Cucurull\n\nThomas Scialom\n\nRobert Stojnic\n\nMeta AI\n\nThe paper reports 8.1M papers but the authors recently updated the numbers on the GitHub page https://github.com/allenai/s2orc\n\n###### Abstract\n\nScientific knowledge is predominantly stored in books and scientific journals, often in the form of PDFs. However, the PDF format leads to a loss of semantic information, particularly for mathematical expressions. We propose Nougat (**N**eural **O**ptical **U**nderstanding for **A**cademic Documents), a Visual Transformer model that performs an _Optical Character Recognition_ (OCR) task for processing scientific documents into a markup language, and demonstrate the effectiveness of our model on a new dataset of scientific documents. The proposed approach offers a promising solution to enhance the accessibility of scientific knowledge in the digital age, by bridging the gap between human-readable documents and machine-readable text. We release the models and code to accelerate future work on scientific text recognition.\n\n## 1 Introduction\n\nThe majority of scientific knowledge is stored in books or published in scientific journals, most commonly in the Portable Document Format (PDF). Next to HTML, PDFs are the second most prominent data format on the internet, making up 2.4% of common crawl [1]. However, the information stored in these files is very difficult to extract into any other formats. This is especially true for highly specialized documents, such as scientific research papers, where the semantic information of mathematical expressions is lost.\n\nExisting Optical Character Recognition (OCR) engines, such as Tesseract OCR [2], excel at detecting and classifying individual characters and words in an image, but fail to understand the relationship between them due to their line-by-line approach. This means that they treat superscripts and subscripts in the same way as the surrounding text, which is a significant drawback for mathematical expressions. In mathematical notations like fractions, exponents, and matrices, relative positions of characters are crucial.\n\nConverting academic research papers into machine-readable text also enables accessibility and searchability of science as a whole. The information of millions of academic papers can not be fully accessed because they are locked behind an unreadable format. Existing corpora, such as the S2ORC dataset [3], capture the text of 12M2 papers using GROBID [4], but are missing meaningful representations of the mathematical equations.\n\nFootnote 2: The paper reports 8.1M papers but the authors recently updated the numbers on the GitHub page https://github.com/allenai/s2orc\n\nTo this end, we introduce Nougat, a transformer based model that can convert images of document pages to formatted markup text.\n\nThe primary contributions in this paper are\n\n* Release of a pre-trained model capable of converting a PDF to a lightweight markup language. We release the code and the model on GitHub3 Footnote 3: https://github.com/facebookresearch/nougat\n* We introduce a pipeline to create dataset for pairing PDFs to source code\n* Our method is only dependent on the image of a page, allowing access to scanned papers and books" # noqa: E231
196
+ expected_output = "\n\n# Nougat: Neural Optical Understanding for Academic Documents\n\n Lukas Blecher\n\nCorrespondence to: lblecher@meta.com\n\nGuillem Cucurull\n\nThomas Scialom\n\nRobert Stojnic\n\nMeta AI\n\nThe paper reports 8.1M papers but the authors recently updated the numbers on the GitHub page https://github.com/allenai/s2orc\n\n###### Abstract\n\nScientific knowledge is predominantly stored in books and scientific journals, often in the form of PDFs. However, the PDF format leads to a loss of semantic information, particularly for mathematical expressions. We propose Nougat (**N**eural **O**ptical **U**nderstanding for **A**cademic Documents), a Visual Transformer model that performs an _Optical Character Recognition_ (OCR) task for processing scientific documents into a markup language, and demonstrate the effectiveness of our model on a new dataset of scientific documents. The proposed approach offers a promising solution to enhance the accessibility of scientific knowledge in the digital age, by bridging the gap between human-readable documents and machine-readable text. We release the models and code to accelerate future work on scientific text recognition.\n\n## 1 Introduction\n\nThe majority of scientific knowledge is stored in books or published in scientific journals, most commonly in the Portable Document Format (PDF). Next to HTML, PDFs are the second most prominent data format on the internet, making up 2.4% of common crawl [1]. However, the information stored in these files is very difficult to extract into any other formats. This is especially true for highly specialized documents, such as scientific research papers, where the semantic information of mathematical expressions is lost.\n\nExisting Optical Character Recognition (OCR) engines, such as Tesseract OCR [2], excel at detecting and classifying individual characters and words in an image, but fail to understand the relationship between them due to their line-by-line approach. This means that they treat superscripts and subscripts in the same way as the surrounding text, which is a significant drawback for mathematical expressions. In mathematical notations like fractions, exponents, and matrices, relative positions of characters are crucial.\n\nConverting academic research papers into machine-readable text also enables accessibility and searchability of science as a whole. The information of millions of academic papers can not be fully accessed because they are locked behind an unreadable format. Existing corpora, such as the S2ORC dataset [3], capture the text of 12M2 papers using GROBID [4], but are missing meaningful representations of the mathematical equations.\n\nFootnote 2: The paper reports 8.1M papers but the authors recently updated the numbers on the GitHub page https://github.com/allenai/s2orc\n\nTo this end, we introduce Nougat, a transformer based model that can convert images of document pages to formatted markup text.\n\nThe primary contributions in this paper are\n\n* Release of a pre-trained model capable of converting a PDF to a lightweight markup language. We release the code and the model on GitHub3 Footnote 3: https://github.com/facebookresearch/nougat\n* We introduce a pipeline to create dataset for pairing PDFs to source code\n* Our method is only dependent on the image of a page, allowing access to scanned papers and books" # noqa: E231
197
+ self.assertEqual(self.tokenizer.post_process_single(input_str, fix_markdown=False), expected_output)
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/nystromformer/__init__.py ADDED
File without changes
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/nystromformer/test_modeling_nystromformer.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 Nystromformer model."""
16
+
17
+ import unittest
18
+
19
+ from transformers import AutoTokenizer, NystromformerConfig, is_torch_available
20
+ from transformers.testing_utils import require_torch, slow, torch_device
21
+
22
+ from ...test_configuration_common import ConfigTester
23
+ from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
24
+ from ...test_pipeline_mixin import PipelineTesterMixin
25
+
26
+
27
+ if is_torch_available():
28
+ import torch
29
+
30
+ from transformers import (
31
+ NystromformerForMaskedLM,
32
+ NystromformerForMultipleChoice,
33
+ NystromformerForQuestionAnswering,
34
+ NystromformerForSequenceClassification,
35
+ NystromformerForTokenClassification,
36
+ NystromformerModel,
37
+ )
38
+
39
+
40
+ class NystromformerModelTester:
41
+ def __init__(
42
+ self,
43
+ parent,
44
+ batch_size=13,
45
+ seq_length=7,
46
+ is_training=True,
47
+ use_input_mask=True,
48
+ use_token_type_ids=True,
49
+ use_labels=True,
50
+ vocab_size=99,
51
+ hidden_size=32,
52
+ num_hidden_layers=2,
53
+ num_attention_heads=4,
54
+ intermediate_size=37,
55
+ hidden_act="gelu",
56
+ hidden_dropout_prob=0.1,
57
+ attention_probs_dropout_prob=0.1,
58
+ max_position_embeddings=512,
59
+ type_vocab_size=16,
60
+ type_sequence_label_size=2,
61
+ initializer_range=0.02,
62
+ num_labels=3,
63
+ num_choices=4,
64
+ scope=None,
65
+ ):
66
+ self.parent = parent
67
+ self.batch_size = batch_size
68
+ self.seq_length = seq_length
69
+ self.is_training = is_training
70
+ self.use_input_mask = use_input_mask
71
+ self.use_token_type_ids = use_token_type_ids
72
+ self.use_labels = use_labels
73
+ self.vocab_size = vocab_size
74
+ self.hidden_size = hidden_size
75
+ self.num_hidden_layers = num_hidden_layers
76
+ self.num_attention_heads = num_attention_heads
77
+ self.intermediate_size = intermediate_size
78
+ self.hidden_act = hidden_act
79
+ self.hidden_dropout_prob = hidden_dropout_prob
80
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
81
+ self.max_position_embeddings = max_position_embeddings
82
+ self.type_vocab_size = type_vocab_size
83
+ self.type_sequence_label_size = type_sequence_label_size
84
+ self.initializer_range = initializer_range
85
+ self.num_labels = num_labels
86
+ self.num_choices = num_choices
87
+ self.scope = scope
88
+
89
+ def prepare_config_and_inputs(self):
90
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
91
+
92
+ input_mask = None
93
+ if self.use_input_mask:
94
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
95
+
96
+ token_type_ids = None
97
+ if self.use_token_type_ids:
98
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
99
+
100
+ sequence_labels = None
101
+ token_labels = None
102
+ choice_labels = None
103
+ if self.use_labels:
104
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
105
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
106
+ choice_labels = ids_tensor([self.batch_size], self.num_choices)
107
+
108
+ config = self.get_config()
109
+
110
+ return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
111
+
112
+ def get_config(self):
113
+ return NystromformerConfig(
114
+ vocab_size=self.vocab_size,
115
+ hidden_size=self.hidden_size,
116
+ num_hidden_layers=self.num_hidden_layers,
117
+ num_attention_heads=self.num_attention_heads,
118
+ intermediate_size=self.intermediate_size,
119
+ hidden_act=self.hidden_act,
120
+ hidden_dropout_prob=self.hidden_dropout_prob,
121
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
122
+ max_position_embeddings=self.max_position_embeddings,
123
+ type_vocab_size=self.type_vocab_size,
124
+ is_decoder=False,
125
+ initializer_range=self.initializer_range,
126
+ )
127
+
128
+ def create_and_check_model(
129
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
130
+ ):
131
+ model = NystromformerModel(config=config)
132
+ model.to(torch_device)
133
+ model.eval()
134
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
135
+ result = model(input_ids, token_type_ids=token_type_ids)
136
+ result = model(input_ids)
137
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
138
+
139
+ def create_and_check_for_masked_lm(
140
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
141
+ ):
142
+ model = NystromformerForMaskedLM(config=config)
143
+ model.to(torch_device)
144
+ model.eval()
145
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
146
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
147
+
148
+ def create_and_check_for_question_answering(
149
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
150
+ ):
151
+ model = NystromformerForQuestionAnswering(config=config)
152
+ model.to(torch_device)
153
+ model.eval()
154
+ result = model(
155
+ input_ids,
156
+ attention_mask=input_mask,
157
+ token_type_ids=token_type_ids,
158
+ start_positions=sequence_labels,
159
+ end_positions=sequence_labels,
160
+ )
161
+ self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
162
+ self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
163
+
164
+ def create_and_check_for_sequence_classification(
165
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
166
+ ):
167
+ config.num_labels = self.num_labels
168
+ model = NystromformerForSequenceClassification(config)
169
+ model.to(torch_device)
170
+ model.eval()
171
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels)
172
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
173
+
174
+ def create_and_check_for_token_classification(
175
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
176
+ ):
177
+ config.num_labels = self.num_labels
178
+ model = NystromformerForTokenClassification(config=config)
179
+ model.to(torch_device)
180
+ model.eval()
181
+ result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=token_labels)
182
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
183
+
184
+ def create_and_check_for_multiple_choice(
185
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
186
+ ):
187
+ config.num_choices = self.num_choices
188
+ model = NystromformerForMultipleChoice(config=config)
189
+ model.to(torch_device)
190
+ model.eval()
191
+ multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
192
+ multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
193
+ multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
194
+ result = model(
195
+ multiple_choice_inputs_ids,
196
+ attention_mask=multiple_choice_input_mask,
197
+ token_type_ids=multiple_choice_token_type_ids,
198
+ labels=choice_labels,
199
+ )
200
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
201
+
202
+ def prepare_config_and_inputs_for_common(self):
203
+ config_and_inputs = self.prepare_config_and_inputs()
204
+ (
205
+ config,
206
+ input_ids,
207
+ token_type_ids,
208
+ input_mask,
209
+ sequence_labels,
210
+ token_labels,
211
+ choice_labels,
212
+ ) = config_and_inputs
213
+ inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
214
+ return config, inputs_dict
215
+
216
+
217
+ @require_torch
218
+ class NystromformerModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
219
+ all_model_classes = (
220
+ (
221
+ NystromformerModel,
222
+ NystromformerForMaskedLM,
223
+ NystromformerForMultipleChoice,
224
+ NystromformerForQuestionAnswering,
225
+ NystromformerForSequenceClassification,
226
+ NystromformerForTokenClassification,
227
+ )
228
+ if is_torch_available()
229
+ else ()
230
+ )
231
+ pipeline_model_mapping = (
232
+ {
233
+ "feature-extraction": NystromformerModel,
234
+ "fill-mask": NystromformerForMaskedLM,
235
+ "question-answering": NystromformerForQuestionAnswering,
236
+ "text-classification": NystromformerForSequenceClassification,
237
+ "token-classification": NystromformerForTokenClassification,
238
+ "zero-shot": NystromformerForSequenceClassification,
239
+ }
240
+ if is_torch_available()
241
+ else {}
242
+ )
243
+ test_pruning = False
244
+ test_headmasking = False
245
+
246
+ def setUp(self):
247
+ self.model_tester = NystromformerModelTester(self)
248
+ self.config_tester = ConfigTester(self, config_class=NystromformerConfig, hidden_size=37)
249
+
250
+ def test_config(self):
251
+ self.config_tester.run_common_tests()
252
+
253
+ def test_model(self):
254
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
255
+ self.model_tester.create_and_check_model(*config_and_inputs)
256
+
257
+ def test_model_various_embeddings(self):
258
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
259
+ for type in ["absolute", "relative_key", "relative_key_query"]:
260
+ config_and_inputs[0].position_embedding_type = type
261
+ self.model_tester.create_and_check_model(*config_and_inputs)
262
+
263
+ def test_for_masked_lm(self):
264
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
265
+ self.model_tester.create_and_check_for_masked_lm(*config_and_inputs)
266
+
267
+ def test_for_multiple_choice(self):
268
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
269
+ self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
270
+
271
+ def test_for_question_answering(self):
272
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
273
+ self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
274
+
275
+ def test_for_sequence_classification(self):
276
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
277
+ self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs)
278
+
279
+ def test_for_token_classification(self):
280
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
281
+ self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
282
+
283
+ @slow
284
+ def test_model_from_pretrained(self):
285
+ model_name = "uw-madison/nystromformer-512"
286
+ model = NystromformerModel.from_pretrained(model_name)
287
+ self.assertIsNotNone(model)
288
+
289
+
290
+ @require_torch
291
+ class NystromformerModelIntegrationTest(unittest.TestCase):
292
+ @slow
293
+ def test_inference_no_head(self):
294
+ model = NystromformerModel.from_pretrained("uw-madison/nystromformer-512")
295
+ input_ids = torch.tensor([[0, 1, 2, 3, 4, 5]])
296
+
297
+ with torch.no_grad():
298
+ output = model(input_ids)[0]
299
+
300
+ expected_shape = torch.Size((1, 6, 768))
301
+ self.assertEqual(output.shape, expected_shape)
302
+
303
+ expected_slice = torch.tensor(
304
+ [[[-0.4532, -0.0936, 0.5137], [-0.2676, 0.0628, 0.6186], [-0.3629, -0.1726, 0.4716]]]
305
+ )
306
+
307
+ torch.testing.assert_close(output[:, :3, :3], expected_slice, rtol=1e-4, atol=1e-4)
308
+
309
+ @slow
310
+ def test_masked_lm_end_to_end(self):
311
+ sentence = "the [MASK] of Belgium is Brussels"
312
+
313
+ tokenizer = AutoTokenizer.from_pretrained("uw-madison/nystromformer-512")
314
+ model = NystromformerForMaskedLM.from_pretrained("uw-madison/nystromformer-512")
315
+
316
+ encoding = tokenizer(sentence, return_tensors="pt")
317
+
318
+ with torch.no_grad():
319
+ token_logits = model(encoding.input_ids).logits
320
+
321
+ prediction = token_logits[:, 2, :].argmax(-1)[0]
322
+
323
+ self.assertEqual(tokenizer.decode(prediction), "capital")
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/olmo/__init__.py ADDED
File without changes
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/olmo/test_modeling_olmo.py ADDED
@@ -0,0 +1,505 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 OLMo model."""
16
+
17
+ import unittest
18
+
19
+ from packaging import version
20
+ from parameterized import parameterized
21
+
22
+ from transformers import OlmoConfig, is_torch_available, set_seed
23
+ from transformers.generation.configuration_utils import GenerationConfig
24
+ from transformers.models.auto.tokenization_auto import AutoTokenizer
25
+ from transformers.models.gpt_neox.tokenization_gpt_neox_fast import GPTNeoXTokenizerFast
26
+ from transformers.testing_utils import (
27
+ require_tokenizers,
28
+ require_torch,
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
+ OlmoForCausalLM,
44
+ OlmoModel,
45
+ )
46
+
47
+
48
+ class OlmoModelTester:
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="silu",
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 = torch.tril(torch.ones_like(input_ids).to(torch_device))
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 OlmoConfig(
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 = OlmoModel(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 = OlmoModel(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 = OlmoForCausalLM(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 = OlmoForCausalLM(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 OlmoModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
276
+ all_model_classes = (OlmoModel, OlmoForCausalLM) if is_torch_available() else ()
277
+ pipeline_model_mapping = (
278
+ {
279
+ "feature-extraction": OlmoModel,
280
+ "text-generation": OlmoForCausalLM,
281
+ }
282
+ if is_torch_available()
283
+ else {}
284
+ )
285
+ test_pruning = False
286
+ fx_compatible = False
287
+
288
+ # Need to use `0.8` instead of `0.9` for `test_cpu_offload`
289
+ # This is because we are hitting edge cases with the causal_mask buffer
290
+ model_split_percents = [0.5, 0.7, 0.8]
291
+
292
+ def setUp(self):
293
+ self.model_tester = OlmoModelTester(self)
294
+ self.config_tester = ConfigTester(self, config_class=OlmoConfig, hidden_size=37)
295
+
296
+ def test_config(self):
297
+ self.config_tester.run_common_tests()
298
+
299
+ def test_model(self):
300
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
301
+ self.model_tester.create_and_check_model(*config_and_inputs)
302
+
303
+ @unittest.skip(reason="OLMo does not support head pruning.")
304
+ def test_headmasking(self):
305
+ pass
306
+
307
+ def test_model_various_embeddings(self):
308
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
309
+ for type in ["absolute", "relative_key", "relative_key_query"]:
310
+ config_and_inputs[0].position_embedding_type = type
311
+ self.model_tester.create_and_check_model(*config_and_inputs)
312
+
313
+ @unittest.skip(reason="OLMo buffers include complex numbers, which breaks this test")
314
+ def test_save_load_fast_init_from_base(self):
315
+ pass
316
+
317
+ @parameterized.expand([("linear",), ("dynamic",)])
318
+ def test_model_rope_scaling(self, scaling_type):
319
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
320
+ short_input = ids_tensor([1, 10], config.vocab_size)
321
+ long_input = ids_tensor([1, int(config.max_position_embeddings * 1.5)], config.vocab_size)
322
+
323
+ set_seed(42) # Fixed seed at init time so the two models get the same random weights
324
+ original_model = OlmoModel(config)
325
+ original_model.to(torch_device)
326
+ original_model.eval()
327
+ original_short_output = original_model(short_input).last_hidden_state
328
+ original_long_output = original_model(long_input).last_hidden_state
329
+
330
+ set_seed(42) # Fixed seed at init time so the two models get the same random weights
331
+ config.rope_scaling = {"type": scaling_type, "factor": 10.0}
332
+ scaled_model = OlmoModel(config)
333
+ scaled_model.to(torch_device)
334
+ scaled_model.eval()
335
+ scaled_short_output = scaled_model(short_input).last_hidden_state
336
+ scaled_long_output = scaled_model(long_input).last_hidden_state
337
+
338
+ # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
339
+ # maximum sequence length, so the outputs for the short input should match.
340
+ if scaling_type == "dynamic":
341
+ torch.testing.assert_close(original_short_output, scaled_short_output, rtol=1e-5, atol=1e-5)
342
+ else:
343
+ self.assertFalse(torch.allclose(original_short_output, scaled_short_output, atol=1e-5))
344
+
345
+ # The output should be different for long inputs
346
+ self.assertFalse(torch.allclose(original_long_output, scaled_long_output, atol=1e-5))
347
+
348
+
349
+ @require_torch
350
+ class OlmoIntegrationTest(unittest.TestCase):
351
+ @slow
352
+ def test_model_1b_logits(self):
353
+ input_ids = [[1, 306, 4658, 278, 6593, 310, 2834, 338]]
354
+ model = OlmoForCausalLM.from_pretrained("allenai/OLMo-1B-hf", device_map="auto")
355
+ out = model(torch.tensor(input_ids)).logits.float()
356
+ # Expected mean on dim = -1
357
+ EXPECTED_MEAN = torch.tensor([[2.2869, 0.3315, 0.9876, 1.4146, 1.8804, 2.0430, 1.7055, 1.2065]])
358
+ torch.testing.assert_close(out.mean(-1), EXPECTED_MEAN, rtol=1e-2, atol=1e-2)
359
+ # slicing logits[0, 0, 0:30]
360
+ EXPECTED_SLICE = torch.tensor([2.5551, -1.1230, 11.0510, 12.4977, 7.9651, 7.2342, 6.1885, 7.8340, 9.9847, 12.6695, 12.2345, 10.7970, 8.4749, 14.2483, 12.9588, 13.9233, 11.0496, 5.5749, 7.4466, 7.7914, 6.8440, 5.8951, 4.8180, 4.1935, 4.5216, 4.7256, 3.9553, 12.2870, 12.4990, 8.1591]) # fmt: skip
361
+ torch.testing.assert_close(out[0, 0, :30], EXPECTED_SLICE, rtol=1e-2, atol=1e-2)
362
+
363
+ @slow
364
+ def test_model_7b_logits(self):
365
+ input_ids = [[1, 306, 4658, 278, 6593, 310, 2834, 338]]
366
+ model = OlmoForCausalLM.from_pretrained("allenai/OLMo-7B-hf", device_map="auto")
367
+ out = model(torch.tensor(input_ids)).logits.float()
368
+ # Expected mean on dim = -1
369
+ EXPECTED_MEAN = torch.tensor([[0.0271, 0.0249, -0.0578, -0.0870, 0.0167, 0.0710, 0.1002, 0.0677]])
370
+ torch.testing.assert_close(out.mean(-1), EXPECTED_MEAN, rtol=1e-2, atol=1e-2)
371
+ # slicing logits[0, 0, 0:30]
372
+ EXPECTED_SLICE = torch.tensor([-1.7433, -1.6685, 7.4941, 6.1506, 0.1364, -0.1127, 1.3224, 4.5458, 4.2068, 5.8296, 7.4723, 2.7925, 3.1245, 10.8872, 10.0758, 10.6717, 7.0945, 1.2398, 3.6766, 4.2365, 2.5655, 2.2222, 1.7418, 0.5223, 0.7753, 1.0938, 0.6723, 6.2522, 6.2264, 1.8105]) # fmt: skip
373
+ torch.testing.assert_close(out[0, 0, :30], EXPECTED_SLICE, rtol=1e-2, atol=1e-2)
374
+
375
+ @slow
376
+ def test_model_7b_twin_2t_logits(self):
377
+ input_ids = [[1, 306, 4658, 278, 6593, 310, 2834, 338]]
378
+ model = OlmoForCausalLM.from_pretrained("allenai/OLMo-7B-Twin-2T-hf", device_map="auto")
379
+ out = model(torch.tensor(input_ids)).logits.float()
380
+ # Expected mean on dim = -1
381
+ EXPECTED_MEAN = torch.tensor([[-0.3636, -0.3825, -0.4800, -0.3696, -0.8388, -0.9737, -0.9849, -0.8356]])
382
+ torch.testing.assert_close(out.mean(-1), EXPECTED_MEAN, rtol=1e-2, atol=1e-2)
383
+ # slicing logits[0, 0, 0:30]
384
+ EXPECTED_SLICE = torch.tensor([-2.0833, -1.9234, 8.7312, 7.8049, 1.0372, 0.8941, 3.1548, 1.8502, 5.5511, 5.5793, 8.1166, 4.5906, 1.8691, 11.6377, 8.9858, 11.6447, 7.4549, 1.4725, 2.8399, 2.7568, 1.4011, 1.6958, 0.5572, 0.5231, 0.3068, 0.5364, 0.6769, 7.9636, 8.2379, 1.7950]) # fmt: skip
385
+ torch.testing.assert_close(out[0, 0, :30], EXPECTED_SLICE, rtol=1e-2, atol=1e-2)
386
+
387
+ @slow
388
+ def test_model_7b_greedy_generation(self):
389
+ EXPECTED_TEXT_COMPLETION = """Simply put, the theory of relativity states that \nthe speed of light is the same for all observers.\n\nThe theory of relativity is a theory of physics that describes the \nmovement of objects in space and time.\n\nThe theory of relativity is a theory of physics that describes the \nmovement of objects in space and time.\n\n"""
390
+ prompt = "Simply put, the theory of relativity states that "
391
+ tokenizer = AutoTokenizer.from_pretrained("allenai/OLMo-7B-hf", device_map="auto")
392
+ input_ids = tokenizer.encode(prompt, return_tensors="pt")
393
+ model = OlmoForCausalLM.from_pretrained("allenai/OLMo-7B-hf", device_map="auto")
394
+
395
+ # greedy generation outputs
396
+ generated_ids = model.generate(input_ids, max_new_tokens=64, top_p=None, temperature=1, do_sample=False)
397
+ text = tokenizer.decode(generated_ids[0], skip_special_tokens=True)
398
+ self.assertEqual(EXPECTED_TEXT_COMPLETION, text)
399
+
400
+ @require_tokenizers
401
+ def test_fast_special_tokens(self):
402
+ fast_tokenizer = GPTNeoXTokenizerFast.from_pretrained("allenai/OLMo-1B-hf")
403
+
404
+ original_add_eos_token = fast_tokenizer.add_eos_token
405
+
406
+ fast_tokenizer.add_eos_token = False
407
+ fast = fast_tokenizer.encode("A sample test")
408
+ self.assertEqual(fast, [34, 3410, 1071])
409
+
410
+ fast_tokenizer.add_eos_token = True
411
+ fast = fast_tokenizer.encode("A sample test")
412
+ self.assertEqual(fast, [34, 3410, 1071, 50279])
413
+
414
+ fast_tokenizer.add_eos_token = original_add_eos_token
415
+
416
+ @require_tokenizers
417
+ def test_simple_encode_decode(self):
418
+ rust_tokenizer = GPTNeoXTokenizerFast.from_pretrained("allenai/OLMo-1B-hf")
419
+
420
+ self.assertEqual(rust_tokenizer.encode("This is a test"), [1552, 310, 247, 1071])
421
+ self.assertEqual(rust_tokenizer.decode([1552, 310, 247, 1071], skip_special_tokens=True), "This is a test")
422
+
423
+ # bytefallback showcase
424
+ self.assertEqual(rust_tokenizer.encode("生活的真谛是"), [20025, 46549, 5225, 48561, 33656, 238, 12105]) # fmt: skip
425
+ self.assertEqual(
426
+ rust_tokenizer.decode([20025, 46549, 5225, 48561, 33656, 238, 12105], skip_special_tokens=True),
427
+ "生活的真谛是",
428
+ )
429
+
430
+ # Inner spaces showcase
431
+ self.assertEqual(rust_tokenizer.encode("Hi Hello"), [12764, 50276, 12092])
432
+ self.assertEqual(rust_tokenizer.decode([12764, 50276, 12092], skip_special_tokens=True), "Hi Hello")
433
+
434
+ self.assertEqual(rust_tokenizer.encode("Hi Hello"), [12764, 50275, 12092])
435
+ self.assertEqual(rust_tokenizer.decode([12764, 50275, 12092], skip_special_tokens=True), "Hi Hello")
436
+
437
+ self.assertEqual(rust_tokenizer.encode(""), [])
438
+
439
+ self.assertEqual(rust_tokenizer.encode(" "), [209])
440
+
441
+ self.assertEqual(rust_tokenizer.encode(" "), [50276])
442
+
443
+ self.assertEqual(rust_tokenizer.encode(" Hello"), [24387])
444
+
445
+ @slow
446
+ def test_export_static_cache(self):
447
+ if version.parse(torch.__version__) < version.parse("2.4.0"):
448
+ self.skipTest(reason="This test requires torch >= 2.4 to run.")
449
+
450
+ from transformers.integrations.executorch import (
451
+ TorchExportableModuleWithStaticCache,
452
+ convert_and_export_with_cache,
453
+ )
454
+
455
+ olmo_model = "allenai/OLMo-1B-hf"
456
+
457
+ tokenizer = AutoTokenizer.from_pretrained(olmo_model, pad_token="</s>", padding_side="right")
458
+ EXPECTED_TEXT_COMPLETION = [
459
+ "Simply put, the theory of relativity states that \nthe speed of light is the same in all reference frames.\n\nThe speed of light",
460
+ ]
461
+ max_generation_length = tokenizer(EXPECTED_TEXT_COMPLETION, return_tensors="pt", padding=True)[
462
+ "input_ids"
463
+ ].shape[-1]
464
+
465
+ # Load model
466
+ device = "cpu"
467
+ dtype = torch.bfloat16
468
+ cache_implementation = "static"
469
+ attn_implementation = "sdpa"
470
+ batch_size = 1
471
+ model = OlmoForCausalLM.from_pretrained(
472
+ olmo_model,
473
+ device_map=device,
474
+ torch_dtype=dtype,
475
+ attn_implementation=attn_implementation,
476
+ generation_config=GenerationConfig(
477
+ use_cache=True,
478
+ cache_implementation=cache_implementation,
479
+ max_length=max_generation_length,
480
+ cache_config={
481
+ "batch_size": batch_size,
482
+ "max_cache_len": max_generation_length,
483
+ },
484
+ ),
485
+ )
486
+
487
+ prompts = ["Simply put, the theory of relativity states that "]
488
+ prompt_tokens = tokenizer(prompts, return_tensors="pt", padding=True).to(model.device)
489
+ prompt_token_ids = prompt_tokens["input_ids"]
490
+ max_new_tokens = max_generation_length - prompt_token_ids.shape[-1]
491
+
492
+ # Static Cache + eager
493
+ eager_generated_ids = model.generate(
494
+ **prompt_tokens, max_new_tokens=max_new_tokens, do_sample=False, cache_implementation=cache_implementation
495
+ )
496
+ eager_generated_text = tokenizer.batch_decode(eager_generated_ids, skip_special_tokens=True)
497
+ self.assertEqual(EXPECTED_TEXT_COMPLETION, eager_generated_text)
498
+
499
+ # Static Cache + export
500
+ exported_program = convert_and_export_with_cache(model)
501
+ ep_generated_ids = TorchExportableModuleWithStaticCache.generate(
502
+ exported_program=exported_program, prompt_token_ids=prompt_token_ids, max_new_tokens=max_new_tokens
503
+ )
504
+ ep_generated_text = tokenizer.batch_decode(ep_generated_ids, skip_special_tokens=True)
505
+ self.assertEqual(EXPECTED_TEXT_COMPLETION, ep_generated_text)
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/olmo2/__init__.py ADDED
File without changes
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/olmo2/test_modeling_olmo2.py ADDED
@@ -0,0 +1,467 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 OLMo2 model."""
16
+
17
+ import unittest
18
+
19
+ from packaging import version
20
+ from parameterized import parameterized
21
+
22
+ from transformers import Olmo2Config, is_torch_available, set_seed
23
+ from transformers.generation.configuration_utils import GenerationConfig
24
+ from transformers.models.auto.tokenization_auto import AutoTokenizer
25
+ from transformers.testing_utils import (
26
+ require_tokenizers,
27
+ require_torch,
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
+ Olmo2ForCausalLM,
43
+ Olmo2Model,
44
+ )
45
+
46
+
47
+ class Olmo2ModelTester:
48
+ def __init__(
49
+ self,
50
+ parent,
51
+ batch_size=13,
52
+ seq_length=7,
53
+ is_training=True,
54
+ use_input_mask=True,
55
+ use_token_type_ids=False,
56
+ use_labels=True,
57
+ vocab_size=99,
58
+ hidden_size=32,
59
+ num_hidden_layers=2,
60
+ num_attention_heads=4,
61
+ intermediate_size=37,
62
+ hidden_act="silu",
63
+ hidden_dropout_prob=0.1,
64
+ attention_probs_dropout_prob=0.1,
65
+ max_position_embeddings=512,
66
+ type_vocab_size=16,
67
+ type_sequence_label_size=2,
68
+ initializer_range=0.02,
69
+ num_labels=3,
70
+ num_choices=4,
71
+ pad_token_id=0,
72
+ scope=None,
73
+ ):
74
+ self.parent = parent
75
+ self.batch_size = batch_size
76
+ self.seq_length = seq_length
77
+ self.is_training = is_training
78
+ self.use_input_mask = use_input_mask
79
+ self.use_token_type_ids = use_token_type_ids
80
+ self.use_labels = use_labels
81
+ self.vocab_size = vocab_size
82
+ self.hidden_size = hidden_size
83
+ self.num_hidden_layers = num_hidden_layers
84
+ self.num_attention_heads = num_attention_heads
85
+ self.intermediate_size = intermediate_size
86
+ self.hidden_act = hidden_act
87
+ self.hidden_dropout_prob = hidden_dropout_prob
88
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
89
+ self.max_position_embeddings = max_position_embeddings
90
+ self.type_vocab_size = type_vocab_size
91
+ self.type_sequence_label_size = type_sequence_label_size
92
+ self.initializer_range = initializer_range
93
+ self.num_labels = num_labels
94
+ self.num_choices = num_choices
95
+ self.pad_token_id = pad_token_id
96
+ self.scope = scope
97
+
98
+ def prepare_config_and_inputs(self):
99
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
100
+
101
+ input_mask = None
102
+ if self.use_input_mask:
103
+ input_mask = torch.tril(torch.ones_like(input_ids).to(torch_device))
104
+
105
+ token_type_ids = None
106
+ if self.use_token_type_ids:
107
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
108
+
109
+ sequence_labels = None
110
+ token_labels = None
111
+ choice_labels = None
112
+ if self.use_labels:
113
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
114
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
115
+ choice_labels = ids_tensor([self.batch_size], self.num_choices)
116
+
117
+ config = self.get_config()
118
+
119
+ return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
120
+
121
+ def get_config(self):
122
+ return Olmo2Config(
123
+ vocab_size=self.vocab_size,
124
+ hidden_size=self.hidden_size,
125
+ num_hidden_layers=self.num_hidden_layers,
126
+ num_attention_heads=self.num_attention_heads,
127
+ intermediate_size=self.intermediate_size,
128
+ hidden_act=self.hidden_act,
129
+ hidden_dropout_prob=self.hidden_dropout_prob,
130
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
131
+ max_position_embeddings=self.max_position_embeddings,
132
+ type_vocab_size=self.type_vocab_size,
133
+ is_decoder=False,
134
+ initializer_range=self.initializer_range,
135
+ pad_token_id=self.pad_token_id,
136
+ )
137
+
138
+ def create_and_check_model(
139
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
140
+ ):
141
+ model = Olmo2Model(config=config)
142
+ model.to(torch_device)
143
+ model.eval()
144
+ result = model(input_ids, attention_mask=input_mask)
145
+ result = model(input_ids)
146
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
147
+
148
+ def create_and_check_model_as_decoder(
149
+ self,
150
+ config,
151
+ input_ids,
152
+ token_type_ids,
153
+ input_mask,
154
+ sequence_labels,
155
+ token_labels,
156
+ choice_labels,
157
+ encoder_hidden_states,
158
+ encoder_attention_mask,
159
+ ):
160
+ config.add_cross_attention = True
161
+ model = Olmo2Model(config)
162
+ model.to(torch_device)
163
+ model.eval()
164
+ result = model(
165
+ input_ids,
166
+ attention_mask=input_mask,
167
+ encoder_hidden_states=encoder_hidden_states,
168
+ encoder_attention_mask=encoder_attention_mask,
169
+ )
170
+ result = model(
171
+ input_ids,
172
+ attention_mask=input_mask,
173
+ encoder_hidden_states=encoder_hidden_states,
174
+ )
175
+ result = model(input_ids, attention_mask=input_mask)
176
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
177
+
178
+ def create_and_check_for_causal_lm(
179
+ self,
180
+ config,
181
+ input_ids,
182
+ token_type_ids,
183
+ input_mask,
184
+ sequence_labels,
185
+ token_labels,
186
+ choice_labels,
187
+ encoder_hidden_states,
188
+ encoder_attention_mask,
189
+ ):
190
+ model = Olmo2ForCausalLM(config=config)
191
+ model.to(torch_device)
192
+ model.eval()
193
+ result = model(input_ids, attention_mask=input_mask, labels=token_labels)
194
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
195
+
196
+ def create_and_check_decoder_model_past_large_inputs(
197
+ self,
198
+ config,
199
+ input_ids,
200
+ token_type_ids,
201
+ input_mask,
202
+ sequence_labels,
203
+ token_labels,
204
+ choice_labels,
205
+ encoder_hidden_states,
206
+ encoder_attention_mask,
207
+ ):
208
+ config.is_decoder = True
209
+ config.add_cross_attention = True
210
+ model = Olmo2ForCausalLM(config=config)
211
+ model.to(torch_device)
212
+ model.eval()
213
+
214
+ # first forward pass
215
+ outputs = model(
216
+ input_ids,
217
+ attention_mask=input_mask,
218
+ encoder_hidden_states=encoder_hidden_states,
219
+ encoder_attention_mask=encoder_attention_mask,
220
+ use_cache=True,
221
+ )
222
+ past_key_values = outputs.past_key_values
223
+
224
+ # create hypothetical multiple next token and extent to next_input_ids
225
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
226
+ next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
227
+
228
+ # append to next input_ids and
229
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
230
+ next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
231
+
232
+ output_from_no_past = model(
233
+ next_input_ids,
234
+ attention_mask=next_attention_mask,
235
+ encoder_hidden_states=encoder_hidden_states,
236
+ encoder_attention_mask=encoder_attention_mask,
237
+ output_hidden_states=True,
238
+ )["hidden_states"][0]
239
+ output_from_past = model(
240
+ next_tokens,
241
+ attention_mask=next_attention_mask,
242
+ encoder_hidden_states=encoder_hidden_states,
243
+ encoder_attention_mask=encoder_attention_mask,
244
+ past_key_values=past_key_values,
245
+ output_hidden_states=True,
246
+ )["hidden_states"][0]
247
+
248
+ # select random slice
249
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
250
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
251
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
252
+
253
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
254
+
255
+ # test that outputs are equal for slice
256
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
257
+
258
+ def prepare_config_and_inputs_for_common(self):
259
+ config_and_inputs = self.prepare_config_and_inputs()
260
+ (
261
+ config,
262
+ input_ids,
263
+ token_type_ids,
264
+ input_mask,
265
+ sequence_labels,
266
+ token_labels,
267
+ choice_labels,
268
+ ) = config_and_inputs
269
+ inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
270
+ return config, inputs_dict
271
+
272
+
273
+ @require_torch
274
+ class Olmo2ModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
275
+ all_model_classes = (Olmo2Model, Olmo2ForCausalLM) if is_torch_available() else ()
276
+ pipeline_model_mapping = (
277
+ {
278
+ "feature-extraction": Olmo2Model,
279
+ "text-generation": Olmo2ForCausalLM,
280
+ }
281
+ if is_torch_available()
282
+ else {}
283
+ )
284
+ test_pruning = False
285
+ fx_compatible = False
286
+
287
+ # Need to use `0.8` instead of `0.9` for `test_cpu_offload`
288
+ # This is because we are hitting edge cases with the causal_mask buffer
289
+ model_split_percents = [0.5, 0.7, 0.8]
290
+
291
+ def setUp(self):
292
+ self.model_tester = Olmo2ModelTester(self)
293
+ self.config_tester = ConfigTester(self, config_class=Olmo2Config, hidden_size=37)
294
+
295
+ def test_config(self):
296
+ self.config_tester.run_common_tests()
297
+
298
+ def test_model(self):
299
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
300
+ self.model_tester.create_and_check_model(*config_and_inputs)
301
+
302
+ @unittest.skip(reason="OLMo2 does not support head pruning.")
303
+ def test_headmasking(self):
304
+ pass
305
+
306
+ def test_model_various_embeddings(self):
307
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
308
+ for type in ["absolute", "relative_key", "relative_key_query"]:
309
+ config_and_inputs[0].position_embedding_type = type
310
+ self.model_tester.create_and_check_model(*config_and_inputs)
311
+
312
+ @unittest.skip(reason="OLMo2 buffers include complex numbers, which breaks this test")
313
+ def test_save_load_fast_init_from_base(self):
314
+ pass
315
+
316
+ @parameterized.expand([("linear",), ("dynamic",)])
317
+ def test_model_rope_scaling(self, scaling_type):
318
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
319
+ short_input = ids_tensor([1, 10], config.vocab_size)
320
+ long_input = ids_tensor([1, int(config.max_position_embeddings * 1.5)], config.vocab_size)
321
+
322
+ set_seed(42) # Fixed seed at init time so the two models get the same random weights
323
+ original_model = Olmo2Model(config)
324
+ original_model.to(torch_device)
325
+ original_model.eval()
326
+ original_short_output = original_model(short_input).last_hidden_state
327
+ original_long_output = original_model(long_input).last_hidden_state
328
+
329
+ set_seed(42) # Fixed seed at init time so the two models get the same random weights
330
+ config.rope_scaling = {"type": scaling_type, "factor": 10.0}
331
+ scaled_model = Olmo2Model(config)
332
+ scaled_model.to(torch_device)
333
+ scaled_model.eval()
334
+ scaled_short_output = scaled_model(short_input).last_hidden_state
335
+ scaled_long_output = scaled_model(long_input).last_hidden_state
336
+
337
+ # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
338
+ # maximum sequence length, so the outputs for the short input should match.
339
+ if scaling_type == "dynamic":
340
+ torch.testing.assert_close(original_short_output, scaled_short_output, rtol=1e-5, atol=1e-5)
341
+ else:
342
+ self.assertFalse(torch.allclose(original_short_output, scaled_short_output, atol=1e-5))
343
+
344
+ # The output should be different for long inputs
345
+ self.assertFalse(torch.allclose(original_long_output, scaled_long_output, atol=1e-5))
346
+
347
+
348
+ @require_torch
349
+ class Olmo2IntegrationTest(unittest.TestCase):
350
+ @slow
351
+ def test_model_7b_logits(self):
352
+ input_ids = [[1, 306, 4658, 278, 6593, 310, 2834, 338]]
353
+ model = Olmo2ForCausalLM.from_pretrained("shanearora/OLMo2-7B-1124-hf", device_map="auto")
354
+ out = model(torch.tensor(input_ids)).logits.float()
355
+ # Expected mean on dim = -1
356
+ EXPECTED_MEAN = torch.tensor(
357
+ [[-13.0244, -13.9564, -11.8270, -11.3047, -12.3794, -12.4215, -15.6030, -12.7962]]
358
+ )
359
+ torch.testing.assert_close(out.mean(-1), EXPECTED_MEAN, rtol=1e-2, atol=1e-2)
360
+ # slicing logits[0, 0, 0:30]
361
+ EXPECTED_SLICE = torch.tensor([-5.3909, -13.9841, -13.6123, -14.5780, -13.9455, -13.2265, -13.4734, -11.9079, -9.2879, -12.6139, -11.4819, -5.9607, -11.9657, -6.3618, -11.1065, -7.3075, -6.5674, -6.7154, -7.3409, -7.9662, -8.0863, -8.1682, -8.7341, -8.7665, -8.8742, -9.7813, -8.0620, -12.5937, -7.6440, -11.3966]) # fmt: skip
362
+ torch.testing.assert_close(out[0, 0, :30], EXPECTED_SLICE, rtol=1e-2, atol=1e-2)
363
+
364
+ @slow
365
+ def test_model_7b_greedy_generation(self):
366
+ EXPECTED_TEXT_COMPLETION = """Simply put, the theory of relativity states that 1) the speed of light is constant, 2) the speed of light is the fastest speed possible, and 3) the speed of light is the same for all observers, regardless of their relative motion. The theory of relativity is based on the idea that the speed of light is constant. This means that"""
367
+ prompt = "Simply put, the theory of relativity states that "
368
+ tokenizer = AutoTokenizer.from_pretrained("shanearora/OLMo2-7B-1124-hf", device_map="auto")
369
+ model = Olmo2ForCausalLM.from_pretrained("shanearora/OLMo2-7B-1124-hf", device_map="auto")
370
+ input_ids = tokenizer.encode(prompt, return_tensors="pt").to(model.device)
371
+
372
+ # greedy generation outputs
373
+ generated_ids = model.generate(input_ids, max_new_tokens=64, top_p=None, temperature=1, do_sample=False)
374
+ text = tokenizer.decode(generated_ids[0], skip_special_tokens=True)
375
+ self.assertEqual(EXPECTED_TEXT_COMPLETION, text)
376
+
377
+ @require_tokenizers
378
+ def test_simple_encode_decode(self):
379
+ rust_tokenizer = AutoTokenizer.from_pretrained("shanearora/OLMo2-7B-1124-hf")
380
+
381
+ self.assertEqual(rust_tokenizer.encode("This is a test"), [2028, 374, 264, 1296])
382
+ self.assertEqual(rust_tokenizer.decode([2028, 374, 264, 1296], skip_special_tokens=True), "This is a test")
383
+
384
+ # bytefallback showcase
385
+ self.assertEqual(rust_tokenizer.encode("生活的真谛是"), [21990, 76706, 9554, 89151, 39013, 249, 21043]) # fmt: skip
386
+ self.assertEqual(
387
+ rust_tokenizer.decode([21990, 76706, 9554, 89151, 39013, 249, 21043], skip_special_tokens=True),
388
+ "生活的真谛是",
389
+ )
390
+
391
+ # Inner spaces showcase
392
+ self.assertEqual(rust_tokenizer.encode("Hi Hello"), [13347, 220, 22691])
393
+ self.assertEqual(rust_tokenizer.decode([13347, 220, 22691], skip_special_tokens=True), "Hi Hello")
394
+
395
+ self.assertEqual(rust_tokenizer.encode("Hi Hello"), [13347, 256, 22691])
396
+ self.assertEqual(rust_tokenizer.decode([13347, 256, 22691], skip_special_tokens=True), "Hi Hello")
397
+
398
+ self.assertEqual(rust_tokenizer.encode(""), [])
399
+
400
+ self.assertEqual(rust_tokenizer.encode(" "), [220])
401
+
402
+ self.assertEqual(rust_tokenizer.encode(" "), [256])
403
+
404
+ self.assertEqual(rust_tokenizer.encode(" Hello"), [22691])
405
+
406
+ @slow
407
+ def test_export_static_cache(self):
408
+ if version.parse(torch.__version__) < version.parse("2.4.0"):
409
+ self.skipTest(reason="This test requires torch >= 2.4 to run.")
410
+
411
+ from transformers.integrations.executorch import (
412
+ TorchExportableModuleWithStaticCache,
413
+ convert_and_export_with_cache,
414
+ )
415
+
416
+ olmo2_model = "shanearora/OLMo2-7B-1124-hf"
417
+
418
+ tokenizer = AutoTokenizer.from_pretrained(olmo2_model, pad_token="</s>", padding_side="right")
419
+ EXPECTED_TEXT_COMPLETION = [
420
+ "Simply put, the theory of relativity states that 1) the speed of light is constant, 2) the speed of light",
421
+ ]
422
+ max_generation_length = tokenizer(EXPECTED_TEXT_COMPLETION, return_tensors="pt", padding=True)[
423
+ "input_ids"
424
+ ].shape[-1]
425
+
426
+ # Load model
427
+ device = "cpu"
428
+ dtype = torch.bfloat16
429
+ cache_implementation = "static"
430
+ attn_implementation = "sdpa"
431
+ batch_size = 1
432
+ generation_config = GenerationConfig(
433
+ use_cache=True,
434
+ cache_implementation=cache_implementation,
435
+ max_length=max_generation_length,
436
+ cache_config={
437
+ "batch_size": batch_size,
438
+ "max_cache_len": max_generation_length,
439
+ },
440
+ )
441
+ model = Olmo2ForCausalLM.from_pretrained(
442
+ olmo2_model,
443
+ device_map=device,
444
+ torch_dtype=dtype,
445
+ attn_implementation=attn_implementation,
446
+ generation_config=generation_config,
447
+ )
448
+
449
+ prompts = ["Simply put, the theory of relativity states that "]
450
+ prompt_tokens = tokenizer(prompts, return_tensors="pt", padding=True).to(model.device)
451
+ prompt_token_ids = prompt_tokens["input_ids"]
452
+ max_new_tokens = max_generation_length - prompt_token_ids.shape[-1]
453
+
454
+ # Static Cache + eager
455
+ eager_generated_ids = model.generate(
456
+ **prompt_tokens, max_new_tokens=max_new_tokens, do_sample=False, cache_implementation=cache_implementation
457
+ )
458
+ eager_generated_text = tokenizer.batch_decode(eager_generated_ids, skip_special_tokens=True)
459
+ self.assertEqual(EXPECTED_TEXT_COMPLETION, eager_generated_text)
460
+
461
+ # Static Cache + export
462
+ exported_program = convert_and_export_with_cache(model)
463
+ ep_generated_ids = TorchExportableModuleWithStaticCache.generate(
464
+ exported_program=exported_program, prompt_token_ids=prompt_token_ids, max_new_tokens=max_new_tokens
465
+ )
466
+ ep_generated_text = tokenizer.batch_decode(ep_generated_ids, skip_special_tokens=True)
467
+ self.assertEqual(EXPECTED_TEXT_COMPLETION, ep_generated_text)
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/olmoe/__init__.py ADDED
File without changes
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/olmoe/test_modeling_olmoe.py ADDED
@@ -0,0 +1,432 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 OLMoE model."""
16
+
17
+ import unittest
18
+
19
+ from parameterized import parameterized
20
+
21
+ from transformers import OlmoeConfig, is_torch_available, set_seed
22
+ from transformers.models.auto.tokenization_auto import AutoTokenizer
23
+ from transformers.models.gpt_neox.tokenization_gpt_neox_fast import GPTNeoXTokenizerFast
24
+ from transformers.testing_utils import (
25
+ require_tokenizers,
26
+ require_torch,
27
+ slow,
28
+ torch_device,
29
+ )
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
+
36
+
37
+ if is_torch_available():
38
+ import torch
39
+
40
+ from transformers import (
41
+ OlmoeForCausalLM,
42
+ OlmoeModel,
43
+ )
44
+
45
+
46
+ class OlmoeModelTester:
47
+ def __init__(
48
+ self,
49
+ parent,
50
+ batch_size=13,
51
+ seq_length=7,
52
+ is_training=True,
53
+ use_input_mask=True,
54
+ use_token_type_ids=False,
55
+ use_labels=True,
56
+ vocab_size=99,
57
+ hidden_size=32,
58
+ num_hidden_layers=2,
59
+ num_attention_heads=4,
60
+ hidden_act="silu",
61
+ hidden_dropout_prob=0.1,
62
+ attention_probs_dropout_prob=0.1,
63
+ max_position_embeddings=512,
64
+ type_vocab_size=16,
65
+ type_sequence_label_size=2,
66
+ initializer_range=0.02,
67
+ num_labels=3,
68
+ num_choices=4,
69
+ pad_token_id=0,
70
+ scope=None,
71
+ num_experts_per_tok=2,
72
+ num_experts=8,
73
+ norm_topk_prob=False,
74
+ output_router_logits=False,
75
+ router_aux_loss_coef=0.001,
76
+ intermediate_size=12,
77
+ ):
78
+ self.parent = parent
79
+ self.batch_size = batch_size
80
+ self.seq_length = seq_length
81
+ self.is_training = is_training
82
+ self.use_input_mask = use_input_mask
83
+ self.use_token_type_ids = use_token_type_ids
84
+ self.use_labels = use_labels
85
+ self.vocab_size = vocab_size
86
+ self.hidden_size = hidden_size
87
+ self.num_hidden_layers = num_hidden_layers
88
+ self.num_attention_heads = num_attention_heads
89
+ self.intermediate_size = intermediate_size
90
+ self.hidden_act = hidden_act
91
+ self.hidden_dropout_prob = hidden_dropout_prob
92
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
93
+ self.max_position_embeddings = max_position_embeddings
94
+ self.type_vocab_size = type_vocab_size
95
+ self.type_sequence_label_size = type_sequence_label_size
96
+ self.initializer_range = initializer_range
97
+ self.num_labels = num_labels
98
+ self.num_choices = num_choices
99
+ self.pad_token_id = pad_token_id
100
+ self.scope = scope
101
+ self.num_experts_per_tok = num_experts_per_tok
102
+ self.num_experts = num_experts
103
+ self.norm_topk_prob = norm_topk_prob
104
+ self.output_router_logits = output_router_logits
105
+ self.router_aux_loss_coef = router_aux_loss_coef
106
+
107
+ def prepare_config_and_inputs(self):
108
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
109
+
110
+ input_mask = None
111
+ if self.use_input_mask:
112
+ input_mask = torch.tril(torch.ones_like(input_ids).to(torch_device))
113
+
114
+ token_type_ids = None
115
+ if self.use_token_type_ids:
116
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
117
+
118
+ sequence_labels = None
119
+ token_labels = None
120
+ choice_labels = None
121
+ if self.use_labels:
122
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
123
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
124
+ choice_labels = ids_tensor([self.batch_size], self.num_choices)
125
+
126
+ config = self.get_config()
127
+
128
+ return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
129
+
130
+ def get_config(self):
131
+ return OlmoeConfig(
132
+ vocab_size=self.vocab_size,
133
+ hidden_size=self.hidden_size,
134
+ num_hidden_layers=self.num_hidden_layers,
135
+ num_attention_heads=self.num_attention_heads,
136
+ intermediate_size=self.intermediate_size,
137
+ hidden_act=self.hidden_act,
138
+ hidden_dropout_prob=self.hidden_dropout_prob,
139
+ attention_probs_dropout_prob=self.attention_probs_dropout_prob,
140
+ max_position_embeddings=self.max_position_embeddings,
141
+ type_vocab_size=self.type_vocab_size,
142
+ is_decoder=False,
143
+ initializer_range=self.initializer_range,
144
+ pad_token_id=self.pad_token_id,
145
+ num_experts_per_tok=self.num_experts_per_tok,
146
+ num_experts=self.num_experts,
147
+ norm_topk_prob=self.norm_topk_prob,
148
+ output_router_logits=self.output_router_logits,
149
+ router_aux_loss_coef=self.router_aux_loss_coef,
150
+ )
151
+
152
+ def create_and_check_model(
153
+ self, config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
154
+ ):
155
+ model = OlmoeModel(config=config)
156
+ model.to(torch_device)
157
+ model.eval()
158
+ result = model(input_ids, attention_mask=input_mask)
159
+ result = model(input_ids)
160
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
161
+
162
+ def create_and_check_model_as_decoder(
163
+ self,
164
+ config,
165
+ input_ids,
166
+ token_type_ids,
167
+ input_mask,
168
+ sequence_labels,
169
+ token_labels,
170
+ choice_labels,
171
+ encoder_hidden_states,
172
+ encoder_attention_mask,
173
+ ):
174
+ config.add_cross_attention = True
175
+ model = OlmoeModel(config)
176
+ model.to(torch_device)
177
+ model.eval()
178
+ result = model(
179
+ input_ids,
180
+ attention_mask=input_mask,
181
+ encoder_hidden_states=encoder_hidden_states,
182
+ encoder_attention_mask=encoder_attention_mask,
183
+ )
184
+ result = model(
185
+ input_ids,
186
+ attention_mask=input_mask,
187
+ encoder_hidden_states=encoder_hidden_states,
188
+ )
189
+ result = model(input_ids, attention_mask=input_mask)
190
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
191
+
192
+ def create_and_check_for_causal_lm(
193
+ self,
194
+ config,
195
+ input_ids,
196
+ token_type_ids,
197
+ input_mask,
198
+ sequence_labels,
199
+ token_labels,
200
+ choice_labels,
201
+ encoder_hidden_states,
202
+ encoder_attention_mask,
203
+ ):
204
+ model = OlmoeForCausalLM(config=config)
205
+ model.to(torch_device)
206
+ model.eval()
207
+ result = model(input_ids, attention_mask=input_mask, labels=token_labels)
208
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
209
+
210
+ def create_and_check_decoder_model_past_large_inputs(
211
+ self,
212
+ config,
213
+ input_ids,
214
+ token_type_ids,
215
+ input_mask,
216
+ sequence_labels,
217
+ token_labels,
218
+ choice_labels,
219
+ encoder_hidden_states,
220
+ encoder_attention_mask,
221
+ ):
222
+ config.is_decoder = True
223
+ config.add_cross_attention = True
224
+ model = OlmoeForCausalLM(config=config)
225
+ model.to(torch_device)
226
+ model.eval()
227
+
228
+ # first forward pass
229
+ outputs = model(
230
+ input_ids,
231
+ attention_mask=input_mask,
232
+ encoder_hidden_states=encoder_hidden_states,
233
+ encoder_attention_mask=encoder_attention_mask,
234
+ use_cache=True,
235
+ )
236
+ past_key_values = outputs.past_key_values
237
+
238
+ # create hypothetical multiple next token and extent to next_input_ids
239
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
240
+ next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
241
+
242
+ # append to next input_ids and
243
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
244
+ next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
245
+
246
+ output_from_no_past = model(
247
+ next_input_ids,
248
+ attention_mask=next_attention_mask,
249
+ encoder_hidden_states=encoder_hidden_states,
250
+ encoder_attention_mask=encoder_attention_mask,
251
+ output_hidden_states=True,
252
+ )["hidden_states"][0]
253
+ output_from_past = model(
254
+ next_tokens,
255
+ attention_mask=next_attention_mask,
256
+ encoder_hidden_states=encoder_hidden_states,
257
+ encoder_attention_mask=encoder_attention_mask,
258
+ past_key_values=past_key_values,
259
+ output_hidden_states=True,
260
+ )["hidden_states"][0]
261
+
262
+ # select random slice
263
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
264
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
265
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
266
+
267
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
268
+
269
+ # test that outputs are equal for slice
270
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
271
+
272
+ def prepare_config_and_inputs_for_common(self):
273
+ config_and_inputs = self.prepare_config_and_inputs()
274
+ (
275
+ config,
276
+ input_ids,
277
+ token_type_ids,
278
+ input_mask,
279
+ sequence_labels,
280
+ token_labels,
281
+ choice_labels,
282
+ ) = config_and_inputs
283
+ inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
284
+ return config, inputs_dict
285
+
286
+
287
+ @require_torch
288
+ class OlmoeModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
289
+ all_model_classes = (OlmoeModel, OlmoeForCausalLM) if is_torch_available() else ()
290
+ pipeline_model_mapping = (
291
+ {
292
+ "feature-extraction": OlmoeModel,
293
+ "text-generation": OlmoeForCausalLM,
294
+ }
295
+ if is_torch_available()
296
+ else {}
297
+ )
298
+ test_pruning = False
299
+ fx_compatible = False
300
+
301
+ # Need to use `0.8` instead of `0.9` for `test_cpu_offload`
302
+ # This is because we are hitting edge cases with the causal_mask buffer
303
+ model_split_percents = [0.5, 0.7, 0.8]
304
+
305
+ def setUp(self):
306
+ self.model_tester = OlmoeModelTester(self)
307
+ self.config_tester = ConfigTester(self, config_class=OlmoeConfig, hidden_size=37)
308
+
309
+ def test_config(self):
310
+ self.config_tester.run_common_tests()
311
+
312
+ def test_model(self):
313
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
314
+ self.model_tester.create_and_check_model(*config_and_inputs)
315
+
316
+ @unittest.skip(reason="OLMoE does not support head pruning.")
317
+ def test_headmasking(self):
318
+ pass
319
+
320
+ def test_model_various_embeddings(self):
321
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
322
+ for type in ["absolute", "relative_key", "relative_key_query"]:
323
+ config_and_inputs[0].position_embedding_type = type
324
+ self.model_tester.create_and_check_model(*config_and_inputs)
325
+
326
+ @unittest.skip(reason="OLMoE buffers include complex numbers, which breaks this test")
327
+ def test_save_load_fast_init_from_base(self):
328
+ pass
329
+
330
+ @parameterized.expand([("linear",), ("dynamic",)])
331
+ def test_model_rope_scaling(self, scaling_type):
332
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
333
+ short_input = ids_tensor([1, 10], config.vocab_size)
334
+ long_input = ids_tensor([1, int(config.max_position_embeddings * 1.5)], config.vocab_size)
335
+
336
+ set_seed(42) # Fixed seed at init time so the two models get the same random weights
337
+ original_model = OlmoeModel(config)
338
+ original_model.to(torch_device)
339
+ original_model.eval()
340
+ original_short_output = original_model(short_input).last_hidden_state
341
+ original_long_output = original_model(long_input).last_hidden_state
342
+
343
+ set_seed(42) # Fixed seed at init time so the two models get the same random weights
344
+ config.rope_scaling = {"type": scaling_type, "factor": 10.0}
345
+ scaled_model = OlmoeModel(config)
346
+ scaled_model.to(torch_device)
347
+ scaled_model.eval()
348
+ scaled_short_output = scaled_model(short_input).last_hidden_state
349
+ scaled_long_output = scaled_model(long_input).last_hidden_state
350
+
351
+ # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
352
+ # maximum sequence length, so the outputs for the short input should match.
353
+ if scaling_type == "dynamic":
354
+ torch.testing.assert_close(original_short_output, scaled_short_output, rtol=1e-5, atol=1e-5)
355
+ else:
356
+ self.assertFalse(torch.allclose(original_short_output, scaled_short_output, atol=1e-5))
357
+
358
+ # The output should be different for long inputs
359
+ self.assertFalse(torch.allclose(original_long_output, scaled_long_output, atol=1e-5))
360
+
361
+
362
+ @require_torch
363
+ class OlmoeIntegrationTest(unittest.TestCase):
364
+ @slow
365
+ def test_model_7b_logits(self):
366
+ input_ids = [[1, 306, 4658, 278, 6593, 310, 2834, 338]]
367
+ model = OlmoeForCausalLM.from_pretrained("allenai/OLMoE-1B-7B-0924", device_map="auto")
368
+ out = model(torch.tensor(input_ids)).logits.float()
369
+ # Expected mean on dim = -1
370
+ EXPECTED_MEAN = torch.tensor([[-1.3814, -3.4450, -2.2990, -1.9542, -2.4387, -2.7941, -2.9312, -2.8309]])
371
+ torch.testing.assert_close(out.mean(-1), EXPECTED_MEAN, rtol=1e-2, atol=1e-2)
372
+ # slicing logits[0, 0, 0:30]
373
+ EXPECTED_SLICE = torch.tensor([-2.3874, -2.4076, -2.4995, 4.2278, 1.4004, -0.0252, 0.4189, -2.7560, 0.3531, 1.6678, -0.7941, -1.1818, -0.2920, 0.7131, -1.4173, 1.6723, 0.5406, 0.1345, -0.1800, 0.2304, 1.2791, 0.7489, 0.6341, -0.0151, -1.3693, -1.2532, -2.3921, 0.7376, 1.6876, 0.5483]) # fmt: skip
374
+ torch.testing.assert_close(out[0, 0, :30], EXPECTED_SLICE, rtol=1e-2, atol=1e-2)
375
+
376
+ @slow
377
+ def test_model_7b_greedy_generation(self):
378
+ EXPECTED_TEXT_COMPLETION = """Simply put, the theory of relativity states that \nthe speed of light is the same for all observers, no matter \nhow fast they are moving. This is a very counter-intuitive \nconcept, and it took Einstein a long time to come up with \nthe theory. The theory of relativity is based on two \npostulates"""
379
+ prompt = "Simply put, the theory of relativity states that "
380
+ tokenizer = AutoTokenizer.from_pretrained("allenai/OLMoE-1B-7B-0924", device_map="auto")
381
+ input_ids = tokenizer.encode(prompt, return_tensors="pt")
382
+ model = OlmoeForCausalLM.from_pretrained("allenai/OLMoE-1B-7B-0924", device_map="auto")
383
+
384
+ # greedy generation outputs
385
+ generated_ids = model.generate(input_ids, max_new_tokens=64, top_p=None, temperature=1, do_sample=False)
386
+ text = tokenizer.decode(generated_ids[0], skip_special_tokens=True)
387
+ self.assertEqual(EXPECTED_TEXT_COMPLETION, text)
388
+
389
+ @require_tokenizers
390
+ def test_fast_special_tokens(self):
391
+ fast_tokenizer = GPTNeoXTokenizerFast.from_pretrained("allenai/OLMoE-1B-7B-0924")
392
+
393
+ original_add_eos_token = fast_tokenizer.add_eos_token
394
+
395
+ fast_tokenizer.add_eos_token = False
396
+ fast = fast_tokenizer.encode("A sample test")
397
+ self.assertEqual(fast, [34, 3410, 1071])
398
+
399
+ fast_tokenizer.add_eos_token = True
400
+ fast = fast_tokenizer.encode("A sample test")
401
+ self.assertEqual(fast, [34, 3410, 1071, 50279])
402
+
403
+ fast_tokenizer.add_eos_token = original_add_eos_token
404
+
405
+ @require_tokenizers
406
+ def test_simple_encode_decode(self):
407
+ rust_tokenizer = GPTNeoXTokenizerFast.from_pretrained("allenai/OLMoE-1B-7B-0924")
408
+
409
+ self.assertEqual(rust_tokenizer.encode("This is a test"), [1552, 310, 247, 1071])
410
+ self.assertEqual(rust_tokenizer.decode([1552, 310, 247, 1071], skip_special_tokens=True), "This is a test")
411
+
412
+ # bytefallback showcase
413
+ self.assertEqual(rust_tokenizer.encode("生活的真谛是"), [20025, 46549, 5225, 48561, 33656, 238, 12105]) # fmt: skip
414
+ self.assertEqual(
415
+ rust_tokenizer.decode([20025, 46549, 5225, 48561, 33656, 238, 12105], skip_special_tokens=True),
416
+ "生活的真谛是",
417
+ )
418
+
419
+ # Inner spaces showcase
420
+ self.assertEqual(rust_tokenizer.encode("Hi Hello"), [12764, 50276, 12092])
421
+ self.assertEqual(rust_tokenizer.decode([12764, 50276, 12092], skip_special_tokens=True), "Hi Hello")
422
+
423
+ self.assertEqual(rust_tokenizer.encode("Hi Hello"), [12764, 50275, 12092])
424
+ self.assertEqual(rust_tokenizer.decode([12764, 50275, 12092], skip_special_tokens=True), "Hi Hello")
425
+
426
+ self.assertEqual(rust_tokenizer.encode(""), [])
427
+
428
+ self.assertEqual(rust_tokenizer.encode(" "), [209])
429
+
430
+ self.assertEqual(rust_tokenizer.encode(" "), [50276])
431
+
432
+ self.assertEqual(rust_tokenizer.encode(" Hello"), [24387])
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/omdet_turbo/__init__.py ADDED
File without changes
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/omdet_turbo/test_modeling_omdet_turbo.py ADDED
@@ -0,0 +1,912 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 OmDet-Turbo model."""
16
+
17
+ import copy
18
+ import unittest
19
+ from io import BytesIO
20
+
21
+ import requests
22
+
23
+ from transformers import OmDetTurboConfig, is_torch_available, is_vision_available
24
+ from transformers.feature_extraction_utils import BatchFeature
25
+ from transformers.file_utils import cached_property
26
+ from transformers.testing_utils import (
27
+ require_timm,
28
+ require_torch,
29
+ require_torch_accelerator,
30
+ require_vision,
31
+ slow,
32
+ torch_device,
33
+ )
34
+
35
+ from ...test_configuration_common import ConfigTester
36
+ from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
37
+ from ...test_pipeline_mixin import PipelineTesterMixin
38
+
39
+
40
+ if is_torch_available():
41
+ import torch
42
+ import torch.nn.functional as F
43
+
44
+ from transformers import OmDetTurboForObjectDetection
45
+
46
+
47
+ if is_vision_available():
48
+ from PIL import Image
49
+
50
+ from transformers import AutoProcessor
51
+
52
+
53
+ class OmDetTurboModelTester:
54
+ def __init__(
55
+ self,
56
+ parent,
57
+ batch_size=6,
58
+ is_training=False,
59
+ num_channels=3,
60
+ max_text_len=7,
61
+ num_classes=3,
62
+ use_timm_backbone=False,
63
+ backbone=None,
64
+ apply_layernorm_after_vision_backbone=False,
65
+ image_size=224,
66
+ text_projection_in_dim=16,
67
+ text_projection_out_dim=16,
68
+ class_embed_dim=16,
69
+ hidden_size=8,
70
+ num_hidden_layers=2,
71
+ num_attention_heads=2,
72
+ num_queries=20,
73
+ encoder_in_channels=(16, 32, 64),
74
+ encoder_dim_feedforward=32,
75
+ num_projection_layers=1,
76
+ decoder_n_points=4,
77
+ num_feature_levels=3,
78
+ ):
79
+ super().__init__()
80
+ self.parent = parent
81
+ self.batch_size = batch_size
82
+ self.is_training = is_training
83
+ self.num_channels = num_channels
84
+ self.max_text_len = max_text_len
85
+ self.num_classes = num_classes
86
+ self.use_timm_backbone = use_timm_backbone
87
+ self.backbone = backbone
88
+ self.apply_layernorm_after_vision_backbone = apply_layernorm_after_vision_backbone
89
+ self.image_size = image_size
90
+ self.text_projection_in_dim = text_projection_in_dim
91
+ self.text_projection_out_dim = text_projection_out_dim
92
+ self.class_embed_dim = class_embed_dim
93
+ self.hidden_size = hidden_size
94
+ self.num_hidden_layers = num_hidden_layers
95
+ self.num_attention_heads = num_attention_heads
96
+ self.num_queries = num_queries
97
+ self.encoder_in_channels = encoder_in_channels
98
+ self.encoder_dim_feedforward = encoder_dim_feedforward
99
+ self.num_projection_layers = num_projection_layers
100
+ self.decoder_n_points = decoder_n_points
101
+ self.num_feature_levels = num_feature_levels
102
+
103
+ self.encoder_seq_length_vision = self.image_size // 32
104
+ self.decoder_seq_length = self.num_queries
105
+
106
+ def prepare_config_and_inputs(self):
107
+ pixel_values = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
108
+
109
+ input_ids_tasks = ids_tensor([self.batch_size, self.max_text_len], self.num_classes)
110
+ input_ids_tasks = input_ids_tasks.to(torch_device)
111
+ input_ids_classes = torch.cat(
112
+ [ids_tensor([self.num_classes, self.max_text_len], self.num_classes) for _ in range(self.batch_size)]
113
+ )
114
+ input_ids_classes = input_ids_classes.to(torch_device)
115
+ attention_mask_tasks = torch.ones_like(input_ids_tasks, device=torch_device)
116
+ attention_mask_classes = torch.ones_like(input_ids_classes, device=torch_device)
117
+ classes_structure = torch.ones(self.batch_size, dtype=torch.long, device=torch_device) * self.num_classes
118
+ encoding = BatchFeature()
119
+ encoding.update(
120
+ {
121
+ "pixel_values": pixel_values,
122
+ "classes_input_ids": input_ids_classes,
123
+ "classes_attention_mask": attention_mask_classes,
124
+ "tasks_input_ids": input_ids_tasks,
125
+ "tasks_attention_mask": attention_mask_tasks,
126
+ "classes_structure": classes_structure,
127
+ }
128
+ )
129
+ config = self.get_config()
130
+ return config, encoding
131
+
132
+ def get_config(self):
133
+ text_backbone = {
134
+ "hidden_size": 16,
135
+ "num_hidden_layers": 2,
136
+ "num_attention_heads": 2,
137
+ "intermediate_size": 16,
138
+ "max_position_embeddings": 8,
139
+ "model_type": "clip_text_model",
140
+ }
141
+ backbone_config = {
142
+ "embed_dim": self.hidden_size,
143
+ "depths": (1, 1, 1, 1),
144
+ "num_heads": (1, 1, 1, 1),
145
+ "window_size": 7,
146
+ "image_size": self.image_size,
147
+ "out_indices": (2, 3, 4),
148
+ "model_type": "swin",
149
+ }
150
+
151
+ return OmDetTurboConfig(
152
+ text_config=text_backbone,
153
+ backbone_config=backbone_config,
154
+ use_timm_backbone=self.use_timm_backbone,
155
+ backbone=self.backbone,
156
+ apply_layernorm_after_vision_backbone=self.apply_layernorm_after_vision_backbone,
157
+ decoder_num_layers=self.num_hidden_layers,
158
+ image_size=self.image_size,
159
+ encoder_in_channels=self.encoder_in_channels,
160
+ num_queries=self.num_queries,
161
+ encoder_layers=self.num_hidden_layers,
162
+ encoder_projection_indices=[2] * self.num_projection_layers,
163
+ encoder_attention_heads=self.num_attention_heads,
164
+ decoder_num_heads=self.num_attention_heads,
165
+ decoder_num_points=self.decoder_n_points,
166
+ num_feature_levels=self.num_feature_levels,
167
+ encoder_dim_feedforward=self.encoder_dim_feedforward,
168
+ task_encoder_hidden_dim=self.encoder_dim_feedforward,
169
+ decoder_dim_feedforward=self.encoder_dim_feedforward,
170
+ class_embed_dim=self.class_embed_dim,
171
+ text_projection_in_dim=self.text_projection_in_dim,
172
+ text_projection_out_dim=self.text_projection_out_dim,
173
+ encoder_hidden_dim=self.hidden_size,
174
+ decoder_hidden_dim=self.hidden_size,
175
+ vision_features_channels=[self.hidden_size, self.hidden_size, self.hidden_size],
176
+ )
177
+
178
+ def prepare_config_and_inputs_for_common(self):
179
+ config, inputs_dict = self.prepare_config_and_inputs()
180
+ return config, inputs_dict
181
+
182
+ def create_and_check_object_detection_head_model(self, config, inputs_dict):
183
+ model = OmDetTurboForObjectDetection(config=config)
184
+ model.to(torch_device)
185
+ model.eval()
186
+
187
+ result = model(**inputs_dict)
188
+
189
+ self.parent.assertEqual(result.decoder_coord_logits.shape, (self.batch_size, self.num_queries, 4))
190
+ self.parent.assertEqual(
191
+ result.decoder_class_logits.shape, (self.batch_size, self.num_queries, self.num_classes)
192
+ )
193
+
194
+
195
+ @require_torch
196
+ class OmDetTurboModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
197
+ all_model_classes = (OmDetTurboForObjectDetection,) if is_torch_available() else ()
198
+ is_encoder_decoder = True
199
+ test_pruning = False
200
+ test_head_masking = False
201
+ pipeline_model_mapping = (
202
+ {"zero-shot-object-detection": OmDetTurboForObjectDetection} if is_torch_available() else {}
203
+ )
204
+
205
+ # special case for head models
206
+ def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
207
+ inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
208
+
209
+ return inputs_dict
210
+
211
+ def setUp(self):
212
+ self.model_tester = OmDetTurboModelTester(self)
213
+ self.config_tester = ConfigTester(
214
+ self,
215
+ config_class=OmDetTurboConfig,
216
+ has_text_modality=False,
217
+ common_properties=["d_model", "encoder_attention_heads", "decoder_num_heads"],
218
+ )
219
+
220
+ def test_config(self):
221
+ self.config_tester.run_common_tests()
222
+
223
+ def test_object_detection_head_model(self):
224
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
225
+ self.model_tester.create_and_check_object_detection_head_model(config, inputs_dict)
226
+
227
+ @unittest.skip(
228
+ reason="Unsupported as classes_input_ids are classes input are flattened by the processor: https://github.com/huggingface/transformers/issues/33669"
229
+ )
230
+ def test_multi_gpu_data_parallel_forward(self):
231
+ pass
232
+
233
+ @unittest.skip(reason="OmDet-Turbo does not use inputs_embeds")
234
+ def test_inputs_embeds(self):
235
+ pass
236
+
237
+ @unittest.skip(reason="OmDet-Turbo does not have 'input_ids' and 'attention_mask'")
238
+ def test_torchscript_output_attentions(self):
239
+ pass
240
+
241
+ @unittest.skip(reason="OmDet-Turbo does not have 'input_ids' and 'attention_mask'")
242
+ def test_torchscript_output_hidden_states(self):
243
+ pass
244
+
245
+ @unittest.skip(reason="OmDet-Turbo does not have 'input_ids' and 'attention_mask'")
246
+ def test_torchscript_simple(self):
247
+ pass
248
+
249
+ @unittest.skip(reason="OmDet-Turbo does not have 'input_ids' and 'attention_mask'")
250
+ def test_torchscript_output_hidden_state(self):
251
+ pass
252
+
253
+ def test_resize_tokens_embeddings(self):
254
+ # rewrite as OmDet-Turbo does not have "input_ids" and "decoder_input_ids"
255
+ (
256
+ original_config,
257
+ inputs_dict,
258
+ ) = self.model_tester.prepare_config_and_inputs_for_common()
259
+ if not self.test_resize_embeddings:
260
+ self.skipTest(reason="test_resize_embeddings is set to `False`")
261
+
262
+ for model_class in self.all_model_classes:
263
+ config = copy.deepcopy(original_config)
264
+ model = model_class(config)
265
+ model.to(torch_device)
266
+ model_embed_pre_resize = model.get_input_embeddings()
267
+ type_model_embed_pre_resize = type(model_embed_pre_resize)
268
+
269
+ if self.model_tester.is_training is False:
270
+ model.eval()
271
+
272
+ model_vocab_size = config.text_config.vocab_size if hasattr(config, "text_config") else config.vocab_size
273
+ # Retrieve the embeddings and clone theme
274
+ model_embed = model.resize_token_embeddings(model_vocab_size)
275
+ cloned_embeddings = model_embed.weight.clone()
276
+
277
+ # Check that resizing the token embeddings with a larger vocab size increases the model's vocab size
278
+ model_embed = model.resize_token_embeddings(model_vocab_size + 10)
279
+ new_model_vocab_size = (
280
+ model.config.text_config.vocab_size
281
+ if hasattr(model.config, "text_config")
282
+ else model.config.vocab_size
283
+ )
284
+ self.assertEqual(new_model_vocab_size, model_vocab_size + 10)
285
+ # Check that it actually resizes the embeddings matrix
286
+ self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] + 10)
287
+ # Check to make sure the type of embeddings returned post resizing is same as type of input
288
+ type_model_embed_post_resize = type(model_embed)
289
+ self.assertEqual(type_model_embed_pre_resize, type_model_embed_post_resize)
290
+ # Check that the model can still do a forward pass successfully (every parameter should be resized)
291
+ model(**self._prepare_for_class(inputs_dict, model_class))
292
+
293
+ # Check that resizing the token embeddings with a smaller vocab size decreases the model's vocab size
294
+ model_embed = model.resize_token_embeddings(model_vocab_size - 15)
295
+ new_model_vocab_size = (
296
+ model.config.text_config.vocab_size
297
+ if hasattr(model.config, "text_config")
298
+ else model.config.vocab_size
299
+ )
300
+ self.assertEqual(new_model_vocab_size, model_vocab_size - 15)
301
+ # Check that it actually resizes the embeddings matrix
302
+ self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] - 15)
303
+
304
+ # Check that the model can still do a forward pass successfully (every parameter should be resized)
305
+ # Input ids should be clamped to the maximum size of the vocabulary
306
+ inputs_dict["tasks_input_ids"].clamp_(max=model_vocab_size - 15 - 1)
307
+
308
+ # make sure that classes_input_ids are resized as well
309
+ if "classes_input_ids" in inputs_dict:
310
+ inputs_dict["classes_input_ids"].clamp_(max=model_vocab_size - 15 - 1)
311
+ model(**self._prepare_for_class(inputs_dict, model_class))
312
+
313
+ # Check that adding and removing tokens has not modified the first part of the embedding matrix.
314
+ models_equal = True
315
+ for p1, p2 in zip(cloned_embeddings, model_embed.weight):
316
+ if p1.data.ne(p2.data).sum() > 0:
317
+ models_equal = False
318
+
319
+ self.assertTrue(models_equal)
320
+
321
+ config = copy.deepcopy(original_config)
322
+ model = model_class(config)
323
+ model.to(torch_device)
324
+
325
+ model_vocab_size = config.text_config.vocab_size if hasattr(config, "text_config") else config.vocab_size
326
+ model.resize_token_embeddings(model_vocab_size + 10, pad_to_multiple_of=1)
327
+ new_model_vocab_size = (
328
+ model.config.text_config.vocab_size
329
+ if hasattr(model.config, "text_config")
330
+ else model.config.vocab_size
331
+ )
332
+ self.assertTrue(new_model_vocab_size + 10, model_vocab_size)
333
+
334
+ model_embed = model.resize_token_embeddings(model_vocab_size, pad_to_multiple_of=64)
335
+ new_model_vocab_size = (
336
+ model.config.text_config.vocab_size
337
+ if hasattr(model.config, "text_config")
338
+ else model.config.vocab_size
339
+ )
340
+ self.assertTrue(model_embed.weight.shape[0] // 64, 0)
341
+
342
+ self.assertTrue(model_embed.weight.shape[0], new_model_vocab_size)
343
+ self.assertTrue(new_model_vocab_size, model.vocab_size)
344
+
345
+ model_embed = model.resize_token_embeddings(model_vocab_size + 13, pad_to_multiple_of=64)
346
+ self.assertTrue(model_embed.weight.shape[0] // 64, 0)
347
+
348
+ # Check that resizing a model to a multiple of pad_to_multiple leads to a model of exactly that size
349
+ target_dimension = 128
350
+ model_embed = model.resize_token_embeddings(target_dimension, pad_to_multiple_of=64)
351
+ self.assertTrue(model_embed.weight.shape[0], target_dimension)
352
+
353
+ with self.assertRaisesRegex(
354
+ ValueError,
355
+ "Asking to pad the embedding matrix to a multiple of `1.3`, which is not and integer. Please make sure to pass an integer",
356
+ ):
357
+ model.resize_token_embeddings(model_vocab_size, pad_to_multiple_of=1.3)
358
+
359
+ # Overwrite as `init_reference_points` is not batch dependent and contains `inf` values
360
+ def test_batching_equivalence(self):
361
+ """
362
+ Tests that the model supports batching and that the output is nearly the same for the same input in
363
+ different batch sizes.
364
+ (Why "nearly the same" not "exactly the same"? Batching uses different matmul shapes, which often leads to
365
+ different results: https://github.com/huggingface/transformers/issues/25420#issuecomment-1775317535)
366
+ """
367
+
368
+ def get_tensor_equivalence_function(batched_input):
369
+ # models operating on continuous spaces have higher abs difference than LMs
370
+ # instead, we can rely on cos distance for image/speech models, similar to `diffusers`
371
+ if "input_ids" not in batched_input:
372
+ return lambda tensor1, tensor2: (
373
+ 1.0 - F.cosine_similarity(tensor1.float().flatten(), tensor2.float().flatten(), dim=0, eps=1e-38)
374
+ )
375
+ return lambda tensor1, tensor2: torch.max(torch.abs(tensor1 - tensor2))
376
+
377
+ def recursive_check(batched_object, single_row_object, model_name, key):
378
+ if isinstance(batched_object, (list, tuple)):
379
+ for batched_object_value, single_row_object_value in zip(batched_object, single_row_object):
380
+ recursive_check(batched_object_value, single_row_object_value, model_name, key)
381
+ elif isinstance(batched_object, dict):
382
+ for batched_object_value, single_row_object_value in zip(
383
+ batched_object.values(), single_row_object.values()
384
+ ):
385
+ recursive_check(batched_object_value, single_row_object_value, model_name, key)
386
+ # do not compare returned loss (0-dim tensor) / codebook ids (int) / caching objects
387
+ elif batched_object is None or not isinstance(batched_object, torch.Tensor):
388
+ return
389
+ elif batched_object.dim() == 0:
390
+ return
391
+ elif key != "init_reference_points":
392
+ # init
393
+ # indexing the first element does not always work
394
+ # e.g. models that output similarity scores of size (N, M) would need to index [0, 0]
395
+ slice_ids = [slice(0, index) for index in single_row_object.shape]
396
+ batched_row = batched_object[slice_ids]
397
+ self.assertFalse(
398
+ torch.isnan(batched_row).any(), f"Batched output has `nan` in {model_name} for key={key}"
399
+ )
400
+ self.assertFalse(
401
+ torch.isinf(batched_row).any(), f"Batched output has `inf` in {model_name} for key={key}"
402
+ )
403
+ self.assertFalse(
404
+ torch.isnan(single_row_object).any(), f"Single row output has `nan` in {model_name} for key={key}"
405
+ )
406
+ self.assertFalse(
407
+ torch.isinf(single_row_object).any(),
408
+ f"Single row output has `inf` in {model_name} for key={key}",
409
+ )
410
+ self.assertTrue(
411
+ (equivalence(batched_row, single_row_object)) <= 1e-03,
412
+ msg=(
413
+ f"Batched and Single row outputs are not equal in {model_name} for key={key}. "
414
+ f"Difference={equivalence(batched_row, single_row_object)}."
415
+ ),
416
+ )
417
+
418
+ config, batched_input = self.model_tester.prepare_config_and_inputs_for_common()
419
+ equivalence = get_tensor_equivalence_function(batched_input)
420
+
421
+ for model_class in self.all_model_classes:
422
+ config.output_hidden_states = True
423
+
424
+ model_name = model_class.__name__
425
+ if hasattr(self.model_tester, "prepare_config_and_inputs_for_model_class"):
426
+ config, batched_input = self.model_tester.prepare_config_and_inputs_for_model_class(model_class)
427
+ batched_input_prepared = self._prepare_for_class(batched_input, model_class)
428
+ model = model_class(config).to(torch_device).eval()
429
+ batch_size = self.model_tester.batch_size
430
+ single_row_input = {}
431
+ for key, value in batched_input_prepared.items():
432
+ single_batch_shape = value.shape[0] // batch_size
433
+ single_row_input[key] = value[:single_batch_shape]
434
+
435
+ with torch.no_grad():
436
+ model_batched_output = model(**batched_input_prepared)
437
+ model_row_output = model(**single_row_input)
438
+
439
+ if isinstance(model_batched_output, torch.Tensor):
440
+ model_batched_output = {"model_output": model_batched_output}
441
+ model_row_output = {"model_output": model_row_output}
442
+
443
+ for key in model_batched_output:
444
+ # DETR starts from zero-init queries to decoder, leading to cos_similarity = `nan`
445
+ if hasattr(self, "zero_init_hidden_state") and "decoder_hidden_states" in key:
446
+ model_batched_output[key] = model_batched_output[key][1:]
447
+ model_row_output[key] = model_row_output[key][1:]
448
+ if key in ("decoder_class_logits", "decoder_classes", "encoder_class_logits"):
449
+ # check if all elements are close to 0, if so skip the test as the test strugles with comparing
450
+ # tensors with all elements close to 0
451
+ if torch.allclose(
452
+ model_batched_output[key], torch.zeros_like(model_batched_output[key]), atol=1e-6
453
+ ) and torch.allclose(model_row_output[key], torch.zeros_like(model_row_output[key]), atol=1e-6):
454
+ continue
455
+
456
+ recursive_check(model_batched_output[key], model_row_output[key], model_name, key)
457
+
458
+ def test_attention_outputs(self):
459
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
460
+ config.return_dict = True
461
+
462
+ for model_class in self.all_model_classes:
463
+ inputs_dict["output_attentions"] = True
464
+ inputs_dict["output_hidden_states"] = False
465
+ config.return_dict = True
466
+ model = model_class(config)
467
+ model.to(torch_device)
468
+ model.eval()
469
+ with torch.no_grad():
470
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
471
+ attentions = outputs.encoder_attentions[-1]
472
+ self.assertEqual(len(attentions), self.model_tester.num_hidden_layers)
473
+
474
+ # check that output_attentions also work using config
475
+ del inputs_dict["output_attentions"]
476
+ config.output_attentions = True
477
+ model = model_class(config)
478
+ model.to(torch_device)
479
+ model.eval()
480
+ with torch.no_grad():
481
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
482
+ attentions = outputs.encoder_attentions[-1]
483
+ self.assertEqual(
484
+ len(attentions), self.model_tester.num_hidden_layers * self.model_tester.num_projection_layers
485
+ )
486
+ # Rest of the shape seems to depend on backbone output shapes and image size
487
+ self.assertListEqual(
488
+ list(attentions[0].shape[-3:]),
489
+ [
490
+ self.model_tester.num_attention_heads,
491
+ self.model_tester.encoder_seq_length_vision**2,
492
+ self.model_tester.encoder_seq_length_vision**2,
493
+ ],
494
+ )
495
+ # decoder attentions
496
+ decoder_attentions = outputs.decoder_attentions[0]
497
+ self.assertIsInstance(decoder_attentions, (list, tuple))
498
+ self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers)
499
+ self.assertListEqual(
500
+ list(decoder_attentions[0].shape[-3:]),
501
+ [
502
+ self.model_tester.num_attention_heads,
503
+ self.model_tester.num_queries + self.model_tester.max_text_len,
504
+ self.model_tester.num_queries + self.model_tester.max_text_len,
505
+ ],
506
+ )
507
+
508
+ # cross attentions
509
+ cross_attentions = outputs.decoder_attentions[-1]
510
+ self.assertIsInstance(cross_attentions, (list, tuple))
511
+ self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers)
512
+ self.assertListEqual(
513
+ list(cross_attentions[0].shape[-3:]),
514
+ [
515
+ self.model_tester.num_attention_heads,
516
+ self.model_tester.num_feature_levels,
517
+ self.model_tester.decoder_n_points,
518
+ ],
519
+ )
520
+
521
+ # Check attention is always last and order is fine
522
+ inputs_dict["output_attentions"] = True
523
+ inputs_dict["output_hidden_states"] = True
524
+ model = model_class(config)
525
+ model.to(torch_device)
526
+ model.eval()
527
+ with torch.no_grad():
528
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
529
+
530
+ self_attentions = outputs.encoder_attentions[-1]
531
+
532
+ self.assertEqual(
533
+ len(self_attentions), self.model_tester.num_hidden_layers * self.model_tester.num_projection_layers
534
+ )
535
+ self.assertListEqual(
536
+ list(attentions[0].shape[-3:]),
537
+ [
538
+ self.model_tester.num_attention_heads,
539
+ self.model_tester.encoder_seq_length_vision**2,
540
+ self.model_tester.encoder_seq_length_vision**2,
541
+ ],
542
+ )
543
+
544
+ # overwrite since encoder_hidden_states are 3-dim and not 2-dim
545
+ def test_hidden_states_output(self):
546
+ def check_hidden_states_output(inputs_dict, config, model_class):
547
+ model = model_class(config)
548
+ model.to(torch_device)
549
+ model.eval()
550
+
551
+ with torch.no_grad():
552
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
553
+
554
+ hidden_states = outputs.encoder_hidden_states
555
+ expected_num_layers = getattr(
556
+ self.model_tester, "expected_num_hidden_layers", self.model_tester.num_projection_layers + 1
557
+ )
558
+ self.assertEqual(len(hidden_states), expected_num_layers)
559
+
560
+ seq_len = self.model_tester.encoder_seq_length_vision
561
+
562
+ self.assertListEqual(list(hidden_states[0].shape[-3:]), [self.model_tester.hidden_size, seq_len, seq_len])
563
+
564
+ hidden_states = outputs.decoder_hidden_states
565
+ expected_num_layers = getattr(
566
+ self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1
567
+ )
568
+ self.assertIsInstance(hidden_states, (list, tuple))
569
+ self.assertEqual(len(hidden_states), expected_num_layers)
570
+ self.assertListEqual(
571
+ list(hidden_states[0].shape[-2:]),
572
+ [self.model_tester.decoder_seq_length, self.model_tester.hidden_size],
573
+ )
574
+
575
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
576
+
577
+ for model_class in self.all_model_classes:
578
+ inputs_dict["output_hidden_states"] = True
579
+ check_hidden_states_output(inputs_dict, config, model_class)
580
+
581
+ # check that output_hidden_states also work using config
582
+ del inputs_dict["output_hidden_states"]
583
+ config.output_hidden_states = True
584
+
585
+ check_hidden_states_output(inputs_dict, config, model_class)
586
+
587
+ # removed retain_grad and grad on decoder_hidden_states, as queries don't require grad
588
+ def test_retain_grad_hidden_states_attentions(self):
589
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
590
+ config.output_hidden_states = True
591
+ config.output_attentions = True
592
+
593
+ # no need to test all models as different heads yield the same functionality
594
+ model_class = self.all_model_classes[0]
595
+ model = model_class(config)
596
+ model.to(torch_device)
597
+
598
+ inputs = self._prepare_for_class(inputs_dict, model_class)
599
+
600
+ outputs = model(**inputs)
601
+
602
+ output = outputs[0]
603
+
604
+ encoder_hidden_states = outputs.encoder_hidden_states[0]
605
+ encoder_attentions = outputs.encoder_attentions[0][0]
606
+ encoder_hidden_states.retain_grad()
607
+ encoder_attentions.retain_grad()
608
+
609
+ cross_attentions = outputs.decoder_attentions[-1][0]
610
+ cross_attentions.retain_grad()
611
+
612
+ output.flatten()[0].backward(retain_graph=True)
613
+
614
+ self.assertIsNotNone(encoder_hidden_states.grad)
615
+ self.assertIsNotNone(encoder_attentions.grad)
616
+ self.assertIsNotNone(cross_attentions.grad)
617
+
618
+ def test_initialization(self):
619
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
620
+
621
+ configs_no_init = _config_zero_init(config)
622
+ for model_class in self.all_model_classes:
623
+ model = model_class(config=configs_no_init)
624
+ for name, param in model.named_parameters():
625
+ if param.requires_grad:
626
+ if (
627
+ "embeddings" in name
628
+ or ".fc" in name
629
+ or "decoder.channel_projection_layers" in name
630
+ or "query_position_head" in name
631
+ or "decoder.encoder_vision_features" in name
632
+ ):
633
+ continue
634
+ self.assertIn(
635
+ ((param.data.mean() * 1e9).round() / 1e9).item(),
636
+ [0.0, 1.0],
637
+ msg=f"Parameter {name} seems not properly initialized",
638
+ )
639
+
640
+
641
+ # We will verify our results on an image of cute cats
642
+ def prepare_img():
643
+ url = "http://images.cocodataset.org/val2017/000000039769.jpg"
644
+ image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
645
+ return image
646
+
647
+
648
+ def prepare_text():
649
+ text_labels = ["cat", "remote"]
650
+ task = "Detect {}.".format(", ".join(text_labels))
651
+ return text_labels, task
652
+
653
+
654
+ def prepare_img_batched():
655
+ url1 = "http://images.cocodataset.org/val2017/000000039769.jpg"
656
+ url2 = "http://images.cocodataset.org/train2017/000000257813.jpg"
657
+ url3 = "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg"
658
+
659
+ return [Image.open(BytesIO(requests.get(url).content)).convert("RGB") for url in [url1, url2, url3]]
660
+
661
+
662
+ def prepare_text_batched():
663
+ text_labels1 = ["cat", "remote"]
664
+ text_labels2 = ["boat"]
665
+ text_labels3 = ["statue", "trees", "torch"]
666
+
667
+ task1 = "Detect {}.".format(", ".join(text_labels1))
668
+ task2 = "Detect all the boat in the image."
669
+ task3 = "Focus on the foreground, detect statue, torch and trees."
670
+ return [text_labels1, text_labels2, text_labels3], [task1, task2, task3]
671
+
672
+
673
+ @require_timm
674
+ @require_vision
675
+ @slow
676
+ class OmDetTurboModelIntegrationTests(unittest.TestCase):
677
+ @cached_property
678
+ def default_processor(self):
679
+ return AutoProcessor.from_pretrained("omlab/omdet-turbo-swin-tiny-hf") if is_vision_available() else None
680
+
681
+ def test_inference_object_detection_head(self):
682
+ model = OmDetTurboForObjectDetection.from_pretrained("omlab/omdet-turbo-swin-tiny-hf").to(torch_device)
683
+
684
+ processor = self.default_processor
685
+ image = prepare_img()
686
+ text_labels, task = prepare_text()
687
+ encoding = processor(images=image, text=text_labels, task=task, return_tensors="pt").to(torch_device)
688
+
689
+ with torch.no_grad():
690
+ outputs = model(**encoding)
691
+
692
+ expected_shape_coord_logits = torch.Size((1, model.config.num_queries, 4))
693
+ expected_shape_class_logits = torch.Size((1, model.config.num_queries, 2))
694
+ self.assertEqual(outputs.decoder_coord_logits.shape, expected_shape_coord_logits)
695
+ self.assertEqual(outputs.decoder_class_logits.shape, expected_shape_class_logits)
696
+
697
+ expected_class_logits = torch.tensor([[[0.9427, -2.5958], [0.2105, -3.4569], [-2.6364, -4.1610]]]).to(
698
+ torch_device
699
+ )
700
+ expected_coord_logits = torch.tensor(
701
+ [[[0.2550, 0.5501, 0.4738, 0.8745], [0.7695, 0.4121, 0.4603, 0.7244], [0.7691, 0.4117, 0.4603, 0.7214]]]
702
+ ).to(torch_device)
703
+
704
+ torch.testing.assert_close(outputs.decoder_class_logits[:3, :3], expected_class_logits, rtol=1e-1, atol=1e-1)
705
+ torch.testing.assert_close(outputs.decoder_coord_logits[:3, :3], expected_coord_logits, rtol=1e-3, atol=1e-3)
706
+
707
+ # verify grounded postprocessing
708
+ results = processor.post_process_grounded_object_detection(
709
+ outputs, text_labels=[text_labels], target_sizes=[image.size[::-1]]
710
+ )[0]
711
+ expected_scores = torch.tensor([0.7675, 0.7196, 0.5634, 0.5524]).to(torch_device)
712
+ expected_slice_boxes = torch.tensor([39.8870, 70.3522, 176.7424, 118.0354]).to(torch_device)
713
+
714
+ self.assertEqual(len(results["scores"]), 4)
715
+ torch.testing.assert_close(results["scores"], expected_scores, rtol=1e-2, atol=1e-2)
716
+ torch.testing.assert_close(results["boxes"][0, :], expected_slice_boxes, rtol=1e-2, atol=1e-2)
717
+
718
+ expected_text_labels = ["remote", "cat", "remote", "cat"]
719
+ self.assertListEqual(results["text_labels"], expected_text_labels)
720
+
721
+ def test_inference_object_detection_head_fp16(self):
722
+ model = OmDetTurboForObjectDetection.from_pretrained("omlab/omdet-turbo-swin-tiny-hf").to(
723
+ torch_device, dtype=torch.float16
724
+ )
725
+
726
+ processor = self.default_processor
727
+ image = prepare_img()
728
+ text_labels, task = prepare_text()
729
+ encoding = processor(images=image, text=text_labels, task=task, return_tensors="pt").to(
730
+ torch_device, dtype=torch.float16
731
+ )
732
+
733
+ with torch.no_grad():
734
+ outputs = model(**encoding)
735
+
736
+ expected_shape_coord_logits = torch.Size((1, model.config.num_queries, 4))
737
+ expected_shape_class_logits = torch.Size((1, model.config.num_queries, 2))
738
+ self.assertEqual(outputs.decoder_coord_logits.shape, expected_shape_coord_logits)
739
+ self.assertEqual(outputs.decoder_class_logits.shape, expected_shape_class_logits)
740
+
741
+ expected_class_logits = torch.tensor([[[0.9427, -2.5958], [0.2105, -3.4569], [-2.6364, -4.1610]]]).to(
742
+ torch_device, dtype=torch.float16
743
+ )
744
+ expected_coord_logits = torch.tensor(
745
+ [[[0.2550, 0.5501, 0.4738, 0.8745], [0.7695, 0.4121, 0.4603, 0.7244], [0.7691, 0.4117, 0.4603, 0.7214]]]
746
+ ).to(torch_device, dtype=torch.float16)
747
+
748
+ torch.testing.assert_close(outputs.decoder_class_logits[:3, :3], expected_class_logits, rtol=1e-1, atol=1e-1)
749
+ torch.testing.assert_close(outputs.decoder_coord_logits[:3, :3], expected_coord_logits, rtol=1e-3, atol=1e-3)
750
+
751
+ # verify grounded postprocessing
752
+ results = processor.post_process_grounded_object_detection(
753
+ outputs, text_labels=[text_labels], target_sizes=[image.size[::-1]]
754
+ )[0]
755
+ expected_scores = torch.tensor([0.7675, 0.7196, 0.5634, 0.5524]).to(torch_device, dtype=torch.float16)
756
+ expected_slice_boxes = torch.tensor([39.8870, 70.3522, 176.7424, 118.0354]).to(
757
+ torch_device, dtype=torch.float16
758
+ )
759
+
760
+ self.assertEqual(len(results["scores"]), 4)
761
+ torch.testing.assert_close(results["scores"], expected_scores, rtol=1e-2, atol=1e-2)
762
+ torch.testing.assert_close(results["boxes"][0, :], expected_slice_boxes, rtol=1e-1, atol=1e-1)
763
+
764
+ expected_text_labels = ["remote", "cat", "remote", "cat"]
765
+ self.assertListEqual(results["text_labels"], expected_text_labels)
766
+
767
+ def test_inference_object_detection_head_no_task(self):
768
+ model = OmDetTurboForObjectDetection.from_pretrained("omlab/omdet-turbo-swin-tiny-hf").to(torch_device)
769
+
770
+ processor = self.default_processor
771
+ image = prepare_img()
772
+ text_labels, _ = prepare_text()
773
+ encoding = processor(images=image, text=text_labels, return_tensors="pt").to(torch_device)
774
+
775
+ with torch.no_grad():
776
+ outputs = model(**encoding)
777
+
778
+ expected_shape_coord_logits = torch.Size((1, model.config.num_queries, 4))
779
+ expected_shape_class_logits = torch.Size((1, model.config.num_queries, 2))
780
+ self.assertEqual(outputs.decoder_coord_logits.shape, expected_shape_coord_logits)
781
+ self.assertEqual(outputs.decoder_class_logits.shape, expected_shape_class_logits)
782
+
783
+ expected_class_logits = torch.tensor([[[0.9427, -2.5958], [0.2105, -3.4569], [-2.6364, -4.1610]]]).to(
784
+ torch_device
785
+ )
786
+ expected_coord_logits = torch.tensor(
787
+ [[[0.2550, 0.5501, 0.4738, 0.8745], [0.7695, 0.4121, 0.4603, 0.7244], [0.7691, 0.4117, 0.4603, 0.7214]]]
788
+ ).to(torch_device)
789
+
790
+ torch.testing.assert_close(outputs.decoder_class_logits[:3, :3], expected_class_logits, rtol=1e-1, atol=1e-1)
791
+ torch.testing.assert_close(outputs.decoder_coord_logits[:3, :3], expected_coord_logits, rtol=1e-3, atol=1e-3)
792
+
793
+ # verify grounded postprocessing
794
+ results = processor.post_process_grounded_object_detection(
795
+ outputs, text_labels=[text_labels], target_sizes=[image.size[::-1]]
796
+ )[0]
797
+ expected_scores = torch.tensor([0.7675, 0.7196, 0.5634, 0.5524]).to(torch_device)
798
+ expected_slice_boxes = torch.tensor([39.8870, 70.3522, 176.7424, 118.0354]).to(torch_device)
799
+
800
+ self.assertEqual(len(results["scores"]), 4)
801
+ torch.testing.assert_close(results["scores"], expected_scores, rtol=1e-2, atol=1e-2)
802
+ torch.testing.assert_close(results["boxes"][0, :], expected_slice_boxes, rtol=1e-2, atol=1e-2)
803
+
804
+ expected_text_labels = ["remote", "cat", "remote", "cat"]
805
+ self.assertListEqual(results["text_labels"], expected_text_labels)
806
+
807
+ def test_inference_object_detection_head_batched(self):
808
+ torch_device = "cpu"
809
+ model = OmDetTurboForObjectDetection.from_pretrained("omlab/omdet-turbo-swin-tiny-hf").to(torch_device)
810
+
811
+ processor = self.default_processor
812
+ images_batched = prepare_img_batched()
813
+ text_labels_batched, tasks_batched = prepare_text_batched()
814
+ encoding = processor(
815
+ images=images_batched, text=text_labels_batched, task=tasks_batched, return_tensors="pt"
816
+ ).to(torch_device)
817
+
818
+ with torch.no_grad():
819
+ outputs = model(**encoding)
820
+
821
+ expected_shape_coord_logits = torch.Size((len(images_batched), model.config.num_queries, 4))
822
+ expected_shape_class_logits = torch.Size((len(images_batched), model.config.num_queries, 3))
823
+ self.assertEqual(outputs.decoder_coord_logits.shape, expected_shape_coord_logits)
824
+ self.assertEqual(outputs.decoder_class_logits.shape, expected_shape_class_logits)
825
+
826
+ expected_class_logits = torch.tensor(
827
+ [[[0.9427, -2.5958, -7.7601]], [[-2.3408, -9.3516, -9.3516]], [[1.0740, -2.3315, -1.1885]]]
828
+ ).to(torch_device)
829
+
830
+ expected_coord_logits = torch.tensor(
831
+ [[[0.2550, 0.5501, 0.4738]], [[0.2535, 0.6006, 0.0353]], [[0.3742, 0.3337, 0.0666]]]
832
+ ).to(torch_device)
833
+
834
+ torch.testing.assert_close(
835
+ outputs.decoder_class_logits[:, :1, :3], expected_class_logits, rtol=1e-1, atol=1e-1
836
+ )
837
+ torch.testing.assert_close(
838
+ outputs.decoder_coord_logits[:, :1, :3], expected_coord_logits, rtol=1e-3, atol=1e-3
839
+ )
840
+
841
+ # verify grounded postprocessing
842
+ results = processor.post_process_grounded_object_detection(
843
+ outputs,
844
+ text_labels=text_labels_batched,
845
+ target_sizes=[image.size[::-1] for image in images_batched],
846
+ score_threshold=0.2,
847
+ )
848
+ expected_scores = torch.tensor([0.7675, 0.3016, 0.7454]).to(torch_device)
849
+ expected_slice_boxes = torch.tensor(
850
+ [
851
+ [39.8870, 70.3522, 176.7424, 118.0354],
852
+ [146.5446, 219.7132, 209.6983, 251.0456],
853
+ [545.3470, 209.9055, 651.9860, 502.1882],
854
+ ]
855
+ ).to(torch_device)
856
+
857
+ self.assertListEqual([len(result["scores"]) for result in results], [4, 4, 6])
858
+ torch.testing.assert_close(
859
+ torch.stack([result["scores"][0] for result in results]), expected_scores, rtol=1e-2, atol=1e-2
860
+ )
861
+ torch.testing.assert_close(
862
+ torch.stack([result["boxes"][0, :] for result in results]), expected_slice_boxes, rtol=1e-2, atol=1e-2
863
+ )
864
+
865
+ expected_text_labels = [
866
+ ["remote", "cat", "remote", "cat"],
867
+ ["boat", "boat", "boat", "boat"],
868
+ ["statue", "trees", "trees", "torch", "statue", "statue"],
869
+ ]
870
+ self.assertListEqual([result["text_labels"] for result in results], expected_text_labels)
871
+
872
+ @require_torch_accelerator
873
+ def test_inference_object_detection_head_equivalence_cpu_gpu(self):
874
+ processor = self.default_processor
875
+ image = prepare_img()
876
+ text_labels, task = prepare_text()
877
+ encoding = processor(images=image, text=text_labels, task=task, return_tensors="pt")
878
+ # 1. run model on CPU
879
+ model = OmDetTurboForObjectDetection.from_pretrained("omlab/omdet-turbo-swin-tiny-hf")
880
+
881
+ with torch.no_grad():
882
+ cpu_outputs = model(**encoding)
883
+
884
+ # 2. run model on GPU
885
+ model.to(torch_device)
886
+ encoding = encoding.to(torch_device)
887
+ with torch.no_grad():
888
+ gpu_outputs = model(**encoding)
889
+
890
+ # 3. assert equivalence
891
+ expected_class_logits = torch.tensor([[[0.9427, -2.5958], [0.2105, -3.4569], [-2.6364, -4.1610]]])
892
+ expected_coord_logits = torch.tensor(
893
+ [[[0.2550, 0.5501, 0.4738, 0.8745], [0.7695, 0.4121, 0.4603, 0.7244], [0.7691, 0.4117, 0.4603, 0.7214]]]
894
+ )
895
+
896
+ torch.testing.assert_close(
897
+ cpu_outputs.decoder_class_logits[:3, :3], expected_class_logits, rtol=1e-1, atol=1e-1
898
+ )
899
+ torch.testing.assert_close(
900
+ cpu_outputs.decoder_coord_logits[:3, :3], expected_coord_logits, rtol=1e-3, atol=1e-3
901
+ )
902
+
903
+ # verify grounded postprocessing
904
+ results_cpu = processor.post_process_grounded_object_detection(
905
+ cpu_outputs, text_labels=[text_labels], target_sizes=[image.size[::-1]]
906
+ )[0]
907
+ result_gpu = processor.post_process_grounded_object_detection(
908
+ gpu_outputs, text_labels=[text_labels], target_sizes=[image.size[::-1]]
909
+ )[0]
910
+
911
+ torch.testing.assert_close(results_cpu["scores"], result_gpu["scores"].cpu(), rtol=1e-2, atol=1e-2)
912
+ torch.testing.assert_close(results_cpu["boxes"][0, :], result_gpu["boxes"][0, :].cpu(), rtol=1e-2, atol=1e-2)
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/omdet_turbo/test_processor_omdet_turbo.py ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
16
+ import shutil
17
+ import tempfile
18
+ import unittest
19
+
20
+ import pytest
21
+
22
+ from transformers import AutoProcessor, CLIPTokenizerFast, OmDetTurboProcessor
23
+ from transformers.testing_utils import require_torch, require_vision
24
+ from transformers.utils import is_torch_available, is_vision_available
25
+
26
+ from ...test_processing_common import ProcessorTesterMixin
27
+
28
+
29
+ IMAGE_MEAN = [123.675, 116.28, 103.53]
30
+ IMAGE_STD = [58.395, 57.12, 57.375]
31
+
32
+ if is_torch_available():
33
+ import torch
34
+
35
+ from transformers.models.omdet_turbo.modeling_omdet_turbo import OmDetTurboObjectDetectionOutput
36
+
37
+ if is_vision_available():
38
+ from transformers import DetrImageProcessor
39
+
40
+
41
+ @require_torch
42
+ @require_vision
43
+ class OmDetTurboProcessorTest(ProcessorTesterMixin, unittest.TestCase):
44
+ processor_class = OmDetTurboProcessor
45
+ text_input_name = "classes_input_ids"
46
+
47
+ def setUp(self):
48
+ self.tmpdirname = tempfile.mkdtemp()
49
+ image_processor = DetrImageProcessor()
50
+ tokenizer = CLIPTokenizerFast.from_pretrained("openai/clip-vit-base-patch32")
51
+
52
+ processor = OmDetTurboProcessor(image_processor, tokenizer)
53
+ processor.save_pretrained(self.tmpdirname)
54
+
55
+ self.input_keys = [
56
+ "tasks_input_ids",
57
+ "tasks_attention_mask",
58
+ "classes_input_ids",
59
+ "classes_attention_mask",
60
+ "classes_structure",
61
+ "pixel_values",
62
+ "pixel_mask",
63
+ ]
64
+
65
+ self.batch_size = 5
66
+ self.num_queries = 5
67
+ self.embed_dim = 3
68
+
69
+ def get_tokenizer(self, **kwargs):
70
+ return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).tokenizer
71
+
72
+ def get_image_processor(self, **kwargs):
73
+ return AutoProcessor.from_pretrained(self.tmpdirname, **kwargs).image_processor
74
+
75
+ def tearDown(self):
76
+ shutil.rmtree(self.tmpdirname)
77
+
78
+ def get_fake_omdet_turbo_output(self):
79
+ classes = self.get_fake_omdet_turbo_classes()
80
+ classes_structure = torch.tensor([len(sublist) for sublist in classes])
81
+ torch.manual_seed(42)
82
+ return OmDetTurboObjectDetectionOutput(
83
+ decoder_coord_logits=torch.rand(self.batch_size, self.num_queries, 4),
84
+ decoder_class_logits=torch.rand(self.batch_size, self.num_queries, self.embed_dim),
85
+ classes_structure=classes_structure,
86
+ )
87
+
88
+ def get_fake_omdet_turbo_classes(self):
89
+ return [[f"class{i}_{j}" for i in range(self.num_queries)] for j in range(self.batch_size)]
90
+
91
+ def test_post_process_grounded_object_detection(self):
92
+ image_processor = self.get_image_processor()
93
+ tokenizer = self.get_tokenizer()
94
+
95
+ processor = OmDetTurboProcessor(tokenizer=tokenizer, image_processor=image_processor)
96
+
97
+ omdet_turbo_output = self.get_fake_omdet_turbo_output()
98
+ omdet_turbo_classes = self.get_fake_omdet_turbo_classes()
99
+
100
+ post_processed = processor.post_process_grounded_object_detection(
101
+ omdet_turbo_output, omdet_turbo_classes, target_sizes=[(400, 30) for _ in range(self.batch_size)]
102
+ )
103
+
104
+ self.assertEqual(len(post_processed), self.batch_size)
105
+ self.assertEqual(list(post_processed[0].keys()), ["boxes", "scores", "labels", "text_labels"])
106
+ self.assertEqual(post_processed[0]["boxes"].shape, (self.num_queries, 4))
107
+ self.assertEqual(post_processed[0]["scores"].shape, (self.num_queries,))
108
+ expected_scores = torch.tensor([0.7310, 0.6579, 0.6513, 0.6444, 0.6252])
109
+ torch.testing.assert_close(post_processed[0]["scores"], expected_scores, rtol=1e-4, atol=1e-4)
110
+
111
+ expected_box_slice = torch.tensor([14.9657, 141.2052, 30.0000, 312.9670])
112
+ torch.testing.assert_close(post_processed[0]["boxes"][0], expected_box_slice, rtol=1e-4, atol=1e-4)
113
+
114
+ def test_save_load_pretrained_additional_features(self):
115
+ processor = OmDetTurboProcessor(tokenizer=self.get_tokenizer(), image_processor=self.get_image_processor())
116
+ processor.save_pretrained(self.tmpdirname)
117
+
118
+ tokenizer_add_kwargs = self.get_tokenizer(bos_token="(BOS)", eos_token="(EOS)")
119
+ image_processor_add_kwargs = self.get_image_processor(do_normalize=False, padding_value=1.0)
120
+
121
+ processor = OmDetTurboProcessor.from_pretrained(
122
+ self.tmpdirname, bos_token="(BOS)", eos_token="(EOS)", do_normalize=False, padding_value=1.0
123
+ )
124
+
125
+ self.assertEqual(processor.tokenizer.get_vocab(), tokenizer_add_kwargs.get_vocab())
126
+ self.assertIsInstance(processor.tokenizer, CLIPTokenizerFast)
127
+
128
+ self.assertEqual(processor.image_processor.to_json_string(), image_processor_add_kwargs.to_json_string())
129
+ self.assertIsInstance(processor.image_processor, DetrImageProcessor)
130
+
131
+ def test_image_processor(self):
132
+ image_processor = self.get_image_processor()
133
+ tokenizer = self.get_tokenizer()
134
+
135
+ processor = OmDetTurboProcessor(tokenizer=tokenizer, image_processor=image_processor).image_processor
136
+
137
+ image_input = self.prepare_image_inputs()
138
+
139
+ input_image_proc = image_processor(image_input, return_tensors="np")
140
+ input_processor = processor(images=image_input, return_tensors="np")
141
+
142
+ for key in input_image_proc.keys():
143
+ self.assertAlmostEqual(input_image_proc[key].sum(), input_processor[key].sum(), delta=1e-2)
144
+
145
+ def test_tokenizer(self):
146
+ image_processor = self.get_image_processor()
147
+ tokenizer = self.get_tokenizer()
148
+
149
+ processor = OmDetTurboProcessor(tokenizer=tokenizer, image_processor=image_processor).tokenizer
150
+
151
+ input_str = "lower newer"
152
+
153
+ encoded_processor = processor(text=input_str, padding="max_length", truncation=True, max_length=77)
154
+
155
+ encoded_tok = tokenizer(input_str, padding="max_length", truncation=True, max_length=77)
156
+
157
+ for key in encoded_tok.keys():
158
+ self.assertListEqual(encoded_tok[key], encoded_processor[key])
159
+
160
+ def test_processor(self):
161
+ image_processor = self.get_image_processor()
162
+ tokenizer = self.get_tokenizer()
163
+
164
+ processor = OmDetTurboProcessor(tokenizer=tokenizer, image_processor=image_processor)
165
+
166
+ input_tasks = "task"
167
+ input_classes = ["class1", "class2"]
168
+ image_input = self.prepare_image_inputs()
169
+
170
+ input_processor = processor(images=image_input, text=input_classes, task=input_tasks, return_tensors="pt")
171
+
172
+ for key in self.input_keys:
173
+ assert torch.is_tensor(input_processor[key])
174
+ # test if it raises when no input is passed
175
+ with pytest.raises(ValueError):
176
+ processor()
177
+
178
+ def test_tokenizer_decode(self):
179
+ image_processor = self.get_image_processor()
180
+ tokenizer = self.get_tokenizer()
181
+
182
+ processor = OmDetTurboProcessor(tokenizer=tokenizer, image_processor=image_processor)
183
+
184
+ predicted_ids = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
185
+
186
+ decoded_processor = processor.batch_decode(predicted_ids)
187
+ decoded_tok = tokenizer.batch_decode(predicted_ids)
188
+
189
+ self.assertListEqual(decoded_tok, decoded_processor)
190
+
191
+ def test_model_input_names(self):
192
+ image_processor = self.get_image_processor()
193
+ tokenizer = self.get_tokenizer()
194
+
195
+ processor = OmDetTurboProcessor(tokenizer=tokenizer, image_processor=image_processor)
196
+
197
+ input_tasks = "task"
198
+ input_classes = ["class1", "class2"]
199
+ image_input = self.prepare_image_inputs()
200
+ inputs = processor(images=image_input, text=input_classes, task=input_tasks, return_tensors="pt")
201
+
202
+ self.assertListEqual(list(inputs.keys()), self.input_keys)
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/oneformer/__init__.py ADDED
File without changes
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/oneformer/test_image_processing_oneformer.py ADDED
@@ -0,0 +1,368 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 json
18
+ import os
19
+ import tempfile
20
+ import unittest
21
+
22
+ import numpy as np
23
+
24
+ from transformers.testing_utils import require_torch, require_vision
25
+ from transformers.utils import is_torch_available, is_vision_available
26
+
27
+ from ...test_image_processing_common import ImageProcessingTestMixin, prepare_image_inputs
28
+
29
+
30
+ if is_torch_available():
31
+ import torch
32
+
33
+ if is_vision_available():
34
+ from transformers import OneFormerImageProcessor
35
+ from transformers.models.oneformer.image_processing_oneformer import binary_mask_to_rle, prepare_metadata
36
+ from transformers.models.oneformer.modeling_oneformer import OneFormerForUniversalSegmentationOutput
37
+
38
+ if is_vision_available():
39
+ from PIL import Image
40
+
41
+
42
+ class OneFormerImageProcessorTester:
43
+ def __init__(
44
+ self,
45
+ parent,
46
+ batch_size=7,
47
+ num_channels=3,
48
+ min_resolution=30,
49
+ max_resolution=400,
50
+ size=None,
51
+ do_resize=True,
52
+ do_normalize=True,
53
+ image_mean=[0.5, 0.5, 0.5],
54
+ image_std=[0.5, 0.5, 0.5],
55
+ num_labels=10,
56
+ do_reduce_labels=False,
57
+ ignore_index=255,
58
+ repo_path="shi-labs/oneformer_demo",
59
+ class_info_file="ade20k_panoptic.json",
60
+ num_text=10,
61
+ ):
62
+ self.parent = parent
63
+ self.batch_size = batch_size
64
+ self.num_channels = num_channels
65
+ self.min_resolution = min_resolution
66
+ self.max_resolution = max_resolution
67
+ self.do_resize = do_resize
68
+ self.size = {"shortest_edge": 32, "longest_edge": 1333} if size is None else size
69
+ self.do_normalize = do_normalize
70
+ self.image_mean = image_mean
71
+ self.image_std = image_std
72
+ self.class_info_file = class_info_file
73
+ self.num_text = num_text
74
+ self.repo_path = repo_path
75
+
76
+ # for the post_process_functions
77
+ self.batch_size = 2
78
+ self.num_queries = 10
79
+ self.num_classes = 10
80
+ self.height = 3
81
+ self.width = 4
82
+ self.num_labels = num_labels
83
+ self.do_reduce_labels = do_reduce_labels
84
+ self.ignore_index = ignore_index
85
+
86
+ def prepare_image_processor_dict(self):
87
+ return {
88
+ "do_resize": self.do_resize,
89
+ "size": self.size,
90
+ "do_normalize": self.do_normalize,
91
+ "image_mean": self.image_mean,
92
+ "image_std": self.image_std,
93
+ "num_labels": self.num_labels,
94
+ "do_reduce_labels": self.do_reduce_labels,
95
+ "ignore_index": self.ignore_index,
96
+ "class_info_file": self.class_info_file,
97
+ "num_text": self.num_text,
98
+ }
99
+
100
+ def get_expected_values(self, image_inputs, batched=False):
101
+ """
102
+ This function computes the expected height and width when providing images to OneFormerImageProcessor,
103
+ assuming do_resize is set to True with a scalar size.
104
+ """
105
+ if not batched:
106
+ image = image_inputs[0]
107
+ if isinstance(image, Image.Image):
108
+ w, h = image.size
109
+ elif isinstance(image, np.ndarray):
110
+ h, w = image.shape[0], image.shape[1]
111
+ else:
112
+ h, w = image.shape[1], image.shape[2]
113
+ if w < h:
114
+ expected_height = int(self.size["shortest_edge"] * h / w)
115
+ expected_width = self.size["shortest_edge"]
116
+ elif w > h:
117
+ expected_height = self.size["shortest_edge"]
118
+ expected_width = int(self.size["shortest_edge"] * w / h)
119
+ else:
120
+ expected_height = self.size["shortest_edge"]
121
+ expected_width = self.size["shortest_edge"]
122
+
123
+ else:
124
+ expected_values = []
125
+ for image in image_inputs:
126
+ expected_height, expected_width = self.get_expected_values([image])
127
+ expected_values.append((expected_height, expected_width))
128
+ expected_height = max(expected_values, key=lambda item: item[0])[0]
129
+ expected_width = max(expected_values, key=lambda item: item[1])[1]
130
+
131
+ return expected_height, expected_width
132
+
133
+ def get_fake_oneformer_outputs(self):
134
+ return OneFormerForUniversalSegmentationOutput(
135
+ # +1 for null class
136
+ class_queries_logits=torch.randn((self.batch_size, self.num_queries, self.num_classes + 1)),
137
+ masks_queries_logits=torch.randn((self.batch_size, self.num_queries, self.height, self.width)),
138
+ )
139
+
140
+ def expected_output_image_shape(self, images):
141
+ height, width = self.get_expected_values(images, batched=True)
142
+ return self.num_channels, height, width
143
+
144
+ def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
145
+ return prepare_image_inputs(
146
+ batch_size=self.batch_size,
147
+ num_channels=self.num_channels,
148
+ min_resolution=self.min_resolution,
149
+ max_resolution=self.max_resolution,
150
+ equal_resolution=equal_resolution,
151
+ numpify=numpify,
152
+ torchify=torchify,
153
+ )
154
+
155
+
156
+ @require_torch
157
+ @require_vision
158
+ class OneFormerImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
159
+ image_processing_class = OneFormerImageProcessor if (is_vision_available() and is_torch_available()) else None
160
+ # only for test_image_processing_common.test_image_proc_to_json_string
161
+ image_processing_class = image_processing_class
162
+
163
+ def setUp(self):
164
+ super().setUp()
165
+ self.image_processor_tester = OneFormerImageProcessorTester(self)
166
+
167
+ @property
168
+ def image_processor_dict(self):
169
+ return self.image_processor_tester.prepare_image_processor_dict()
170
+
171
+ def test_image_proc_properties(self):
172
+ image_processor = self.image_processing_class(**self.image_processor_dict)
173
+ self.assertTrue(hasattr(image_processor, "image_mean"))
174
+ self.assertTrue(hasattr(image_processor, "image_std"))
175
+ self.assertTrue(hasattr(image_processor, "do_normalize"))
176
+ self.assertTrue(hasattr(image_processor, "do_resize"))
177
+ self.assertTrue(hasattr(image_processor, "size"))
178
+ self.assertTrue(hasattr(image_processor, "ignore_index"))
179
+ self.assertTrue(hasattr(image_processor, "class_info_file"))
180
+ self.assertTrue(hasattr(image_processor, "num_text"))
181
+ self.assertTrue(hasattr(image_processor, "repo_path"))
182
+ self.assertTrue(hasattr(image_processor, "metadata"))
183
+ self.assertTrue(hasattr(image_processor, "do_reduce_labels"))
184
+
185
+ def comm_get_image_processor_inputs(
186
+ self, with_segmentation_maps=False, is_instance_map=False, segmentation_type="np"
187
+ ):
188
+ image_processor = self.image_processing_class(**self.image_processor_dict)
189
+ # prepare image and target
190
+ num_labels = self.image_processor_tester.num_labels
191
+ annotations = None
192
+ instance_id_to_semantic_id = None
193
+ image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False)
194
+ if with_segmentation_maps:
195
+ high = num_labels
196
+ if is_instance_map:
197
+ labels_expanded = list(range(num_labels)) * 2
198
+ instance_id_to_semantic_id = dict(enumerate(labels_expanded))
199
+ annotations = [
200
+ np.random.randint(0, high * 2, (img.size[1], img.size[0])).astype(np.uint8) for img in image_inputs
201
+ ]
202
+ if segmentation_type == "pil":
203
+ annotations = [Image.fromarray(annotation) for annotation in annotations]
204
+
205
+ inputs = image_processor(
206
+ image_inputs,
207
+ ["semantic"] * len(image_inputs),
208
+ annotations,
209
+ return_tensors="pt",
210
+ instance_id_to_semantic_id=instance_id_to_semantic_id,
211
+ pad_and_return_pixel_mask=True,
212
+ )
213
+
214
+ return inputs
215
+
216
+ @unittest.skip
217
+ def test_init_without_params(self):
218
+ pass
219
+
220
+ def test_call_with_segmentation_maps(self):
221
+ def common(is_instance_map=False, segmentation_type=None):
222
+ inputs = self.comm_get_image_processor_inputs(
223
+ with_segmentation_maps=True, is_instance_map=is_instance_map, segmentation_type=segmentation_type
224
+ )
225
+
226
+ mask_labels = inputs["mask_labels"]
227
+ class_labels = inputs["class_labels"]
228
+ pixel_values = inputs["pixel_values"]
229
+ text_inputs = inputs["text_inputs"]
230
+
231
+ # check the batch_size
232
+ for mask_label, class_label, text_input in zip(mask_labels, class_labels, text_inputs):
233
+ self.assertEqual(mask_label.shape[0], class_label.shape[0])
234
+ # this ensure padding has happened
235
+ self.assertEqual(mask_label.shape[1:], pixel_values.shape[2:])
236
+ self.assertEqual(len(text_input), self.image_processor_tester.num_text)
237
+
238
+ common()
239
+ common(is_instance_map=True)
240
+ common(is_instance_map=False, segmentation_type="pil")
241
+ common(is_instance_map=True, segmentation_type="pil")
242
+
243
+ def test_binary_mask_to_rle(self):
244
+ fake_binary_mask = np.zeros((20, 50))
245
+ fake_binary_mask[0, 20:] = 1
246
+ fake_binary_mask[1, :15] = 1
247
+ fake_binary_mask[5, :10] = 1
248
+
249
+ rle = binary_mask_to_rle(fake_binary_mask)
250
+ self.assertEqual(len(rle), 4)
251
+ self.assertEqual(rle[0], 21)
252
+ self.assertEqual(rle[1], 45)
253
+
254
+ def test_post_process_semantic_segmentation(self):
255
+ fature_extractor = self.image_processing_class(
256
+ num_labels=self.image_processor_tester.num_classes,
257
+ max_seq_length=77,
258
+ task_seq_length=77,
259
+ class_info_file="ade20k_panoptic.json",
260
+ num_text=self.image_processor_tester.num_text,
261
+ repo_path="shi-labs/oneformer_demo",
262
+ )
263
+ outputs = self.image_processor_tester.get_fake_oneformer_outputs()
264
+
265
+ segmentation = fature_extractor.post_process_semantic_segmentation(outputs)
266
+
267
+ self.assertEqual(len(segmentation), self.image_processor_tester.batch_size)
268
+ self.assertEqual(
269
+ segmentation[0].shape,
270
+ (
271
+ self.image_processor_tester.height,
272
+ self.image_processor_tester.width,
273
+ ),
274
+ )
275
+
276
+ target_sizes = [(1, 4) for i in range(self.image_processor_tester.batch_size)]
277
+ segmentation = fature_extractor.post_process_semantic_segmentation(outputs, target_sizes=target_sizes)
278
+
279
+ self.assertEqual(segmentation[0].shape, target_sizes[0])
280
+
281
+ def test_post_process_instance_segmentation(self):
282
+ image_processor = self.image_processing_class(
283
+ num_labels=self.image_processor_tester.num_classes,
284
+ max_seq_length=77,
285
+ task_seq_length=77,
286
+ class_info_file="ade20k_panoptic.json",
287
+ num_text=self.image_processor_tester.num_text,
288
+ repo_path="shi-labs/oneformer_demo",
289
+ )
290
+ outputs = self.image_processor_tester.get_fake_oneformer_outputs()
291
+ segmentation = image_processor.post_process_instance_segmentation(outputs, threshold=0)
292
+
293
+ self.assertTrue(len(segmentation) == self.image_processor_tester.batch_size)
294
+ for el in segmentation:
295
+ self.assertTrue("segmentation" in el)
296
+ self.assertTrue("segments_info" in el)
297
+ self.assertEqual(type(el["segments_info"]), list)
298
+ self.assertEqual(
299
+ el["segmentation"].shape, (self.image_processor_tester.height, self.image_processor_tester.width)
300
+ )
301
+
302
+ segmentation_with_opts = image_processor.post_process_instance_segmentation(
303
+ outputs,
304
+ threshold=0,
305
+ target_sizes=[(1, 4) for _ in range(self.image_processor_tester.batch_size)],
306
+ task_type="panoptic",
307
+ )
308
+ self.assertTrue(len(segmentation_with_opts) == self.image_processor_tester.batch_size)
309
+ for el in segmentation_with_opts:
310
+ self.assertTrue("segmentation" in el)
311
+ self.assertTrue("segments_info" in el)
312
+ self.assertEqual(type(el["segments_info"]), list)
313
+ self.assertEqual(el["segmentation"].shape, (1, 4))
314
+
315
+ def test_post_process_panoptic_segmentation(self):
316
+ image_processor = self.image_processing_class(
317
+ num_labels=self.image_processor_tester.num_classes,
318
+ max_seq_length=77,
319
+ task_seq_length=77,
320
+ class_info_file="ade20k_panoptic.json",
321
+ num_text=self.image_processor_tester.num_text,
322
+ repo_path="shi-labs/oneformer_demo",
323
+ )
324
+ outputs = self.image_processor_tester.get_fake_oneformer_outputs()
325
+ segmentation = image_processor.post_process_panoptic_segmentation(outputs, threshold=0)
326
+
327
+ self.assertTrue(len(segmentation) == self.image_processor_tester.batch_size)
328
+ for el in segmentation:
329
+ self.assertTrue("segmentation" in el)
330
+ self.assertTrue("segments_info" in el)
331
+ self.assertEqual(type(el["segments_info"]), list)
332
+ self.assertEqual(
333
+ el["segmentation"].shape, (self.image_processor_tester.height, self.image_processor_tester.width)
334
+ )
335
+
336
+ def test_can_load_with_local_metadata(self):
337
+ # Create a temporary json file
338
+ class_info = {
339
+ "0": {"isthing": 0, "name": "foo"},
340
+ "1": {"isthing": 0, "name": "bar"},
341
+ "2": {"isthing": 1, "name": "baz"},
342
+ }
343
+ metadata = prepare_metadata(class_info)
344
+
345
+ with tempfile.TemporaryDirectory() as tmpdirname:
346
+ metadata_path = os.path.join(tmpdirname, "metadata.json")
347
+ with open(metadata_path, "w") as f:
348
+ json.dump(class_info, f)
349
+
350
+ config_dict = self.image_processor_dict
351
+ config_dict["class_info_file"] = metadata_path
352
+ config_dict["repo_path"] = tmpdirname
353
+ image_processor = self.image_processing_class(**config_dict)
354
+
355
+ self.assertEqual(image_processor.metadata, metadata)
356
+
357
+ def test_removed_deprecated_kwargs(self):
358
+ image_processor_dict = dict(self.image_processor_dict)
359
+ image_processor_dict.pop("do_reduce_labels", None)
360
+ image_processor_dict["reduce_labels"] = True
361
+
362
+ # test we are able to create the image processor with the deprecated kwargs
363
+ image_processor = self.image_processing_class(**image_processor_dict)
364
+ self.assertEqual(image_processor.do_reduce_labels, True)
365
+
366
+ # test we still support reduce_labels with config
367
+ image_processor = self.image_processing_class.from_dict(image_processor_dict)
368
+ self.assertEqual(image_processor.do_reduce_labels, True)
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/oneformer/test_modeling_oneformer.py ADDED
@@ -0,0 +1,630 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 OneFormer model."""
16
+
17
+ import copy
18
+ import inspect
19
+ import unittest
20
+
21
+ import numpy as np
22
+
23
+ from tests.test_modeling_common import floats_tensor
24
+ from transformers import OneFormerConfig, is_torch_available, is_vision_available
25
+ from transformers.testing_utils import (
26
+ is_flaky,
27
+ require_timm,
28
+ require_torch,
29
+ require_torch_accelerator,
30
+ require_torch_fp16,
31
+ require_torch_multi_gpu,
32
+ require_vision,
33
+ slow,
34
+ torch_device,
35
+ )
36
+ from transformers.utils import cached_property
37
+
38
+ from ...test_configuration_common import ConfigTester
39
+ from ...test_modeling_common import ModelTesterMixin
40
+ from ...test_pipeline_mixin import PipelineTesterMixin
41
+
42
+
43
+ if is_torch_available():
44
+ import torch
45
+
46
+ from transformers import OneFormerForUniversalSegmentation, OneFormerModel
47
+
48
+ if is_vision_available():
49
+ from transformers import OneFormerProcessor
50
+
51
+ if is_vision_available():
52
+ from PIL import Image
53
+
54
+
55
+ def _config_zero_init(config):
56
+ configs_no_init = copy.deepcopy(config)
57
+ for key in configs_no_init.__dict__.keys():
58
+ if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key:
59
+ setattr(configs_no_init, key, 1e-10)
60
+ return configs_no_init
61
+
62
+
63
+ class OneFormerModelTester:
64
+ def __init__(
65
+ self,
66
+ parent,
67
+ batch_size=2,
68
+ is_training=True,
69
+ vocab_size=99,
70
+ use_auxiliary_loss=False,
71
+ num_queries=10,
72
+ num_channels=3,
73
+ min_size=32 * 8,
74
+ max_size=32 * 8,
75
+ num_labels=4,
76
+ hidden_dim=64,
77
+ sequence_length=77,
78
+ n_ctx=4,
79
+ ):
80
+ self.parent = parent
81
+ self.batch_size = batch_size
82
+ self.is_training = is_training
83
+ self.vocab_size = vocab_size
84
+ self.use_auxiliary_loss = use_auxiliary_loss
85
+ self.num_queries = num_queries
86
+ self.num_channels = num_channels
87
+ self.min_size = min_size
88
+ self.max_size = max_size
89
+ self.num_labels = num_labels
90
+ self.hidden_dim = hidden_dim
91
+ self.sequence_length = sequence_length
92
+ self.n_ctx = n_ctx
93
+
94
+ def prepare_config_and_inputs(self):
95
+ pixel_values = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]).to(
96
+ torch_device
97
+ )
98
+
99
+ task_inputs = (
100
+ torch.randint(high=self.vocab_size, size=(self.batch_size, self.sequence_length)).to(torch_device).long()
101
+ )
102
+
103
+ pixel_mask = torch.ones([self.batch_size, self.min_size, self.max_size], device=torch_device)
104
+
105
+ text_inputs = (
106
+ torch.randint(
107
+ high=self.vocab_size, size=(self.batch_size, self.num_queries - self.n_ctx, self.sequence_length)
108
+ )
109
+ .to(torch_device)
110
+ .long()
111
+ )
112
+
113
+ mask_labels = (
114
+ torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size], device=torch_device) > 0.5
115
+ ).float()
116
+ class_labels = (torch.rand((self.batch_size, self.num_labels), device=torch_device) > 0.5).long()
117
+
118
+ config = self.get_config()
119
+ return config, pixel_values, task_inputs, text_inputs, pixel_mask, mask_labels, class_labels
120
+
121
+ def get_config(self):
122
+ config = OneFormerConfig(
123
+ text_encoder_vocab_size=self.vocab_size,
124
+ hidden_size=self.hidden_dim,
125
+ num_queries=self.num_queries,
126
+ num_labels=self.num_labels,
127
+ encoder_feedforward_dim=32,
128
+ dim_feedforward=64,
129
+ encoder_layers=2,
130
+ decoder_layers=2,
131
+ )
132
+
133
+ config.backbone_config.embed_dim = 16
134
+ config.backbone_config.depths = [1, 1, 1, 1]
135
+ config.backbone_config.hidden_size = 16
136
+ config.backbone_config.num_channels = self.num_channels
137
+ config.backbone_config.num_heads = [1, 1, 2, 2]
138
+ config.backbone = None
139
+
140
+ config.hidden_dim = self.hidden_dim
141
+ config.mask_dim = self.hidden_dim
142
+ config.conv_dim = self.hidden_dim
143
+
144
+ config.text_encoder_width = self.hidden_dim
145
+ config.task_seq_len = self.sequence_length
146
+ config.max_seq_len = self.sequence_length
147
+ config.text_encoder_context_length = self.sequence_length
148
+ config.text_encoder_n_ctx = self.n_ctx
149
+
150
+ return config
151
+
152
+ def prepare_config_and_inputs_for_common(self):
153
+ config, pixel_values, task_inputs, pixel_mask, _, _, _ = self.prepare_config_and_inputs()
154
+ inputs_dict = {"pixel_values": pixel_values, "pixel_mask": pixel_mask, "task_inputs": task_inputs}
155
+ return config, inputs_dict
156
+
157
+ def check_output_hidden_state(self, output, config):
158
+ encoder_hidden_states = output.encoder_hidden_states
159
+ pixel_decoder_hidden_states = output.pixel_decoder_hidden_states
160
+ transformer_decoder_hidden_states = output.transformer_decoder_hidden_states
161
+
162
+ self.parent.assertTrue(len(encoder_hidden_states), len(config.backbone_config.depths))
163
+ self.parent.assertTrue(len(pixel_decoder_hidden_states), config.encoder_layers)
164
+ self.parent.assertTrue(len(transformer_decoder_hidden_states), config.decoder_layers - 1)
165
+
166
+ def create_and_check_oneformer_model(
167
+ self, config, pixel_values, task_inputs, pixel_mask, output_hidden_states=False
168
+ ):
169
+ with torch.no_grad():
170
+ model = OneFormerModel(config=config)
171
+ model.to(torch_device)
172
+ model.eval()
173
+
174
+ output = model(pixel_values=pixel_values, task_inputs=task_inputs, pixel_mask=pixel_mask)
175
+ output = model(pixel_values, task_inputs=task_inputs, output_hidden_states=True)
176
+ # the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
177
+ # encoder and pixel decoder
178
+ self.parent.assertEqual(
179
+ output.transformer_decoder_object_queries.shape,
180
+ (self.batch_size, self.num_queries, self.hidden_dim),
181
+ )
182
+ # let's ensure the other two hidden state exists
183
+ self.parent.assertTrue(output.pixel_decoder_hidden_states is not None)
184
+ self.parent.assertTrue(output.encoder_hidden_states is not None)
185
+
186
+ if output_hidden_states:
187
+ self.check_output_hidden_state(output, config)
188
+
189
+ def create_and_check_oneformer_universal_segmentation_head_model(
190
+ self, config, pixel_values, task_inputs, text_inputs, pixel_mask, mask_labels, class_labels
191
+ ):
192
+ model = OneFormerForUniversalSegmentation(config=config)
193
+ model.to(torch_device)
194
+ model.eval()
195
+
196
+ def comm_check_on_output(result):
197
+ # let's still check that all the required stuff is there
198
+ self.parent.assertTrue(result.transformer_decoder_hidden_states is not None)
199
+ self.parent.assertTrue(result.pixel_decoder_hidden_states is not None)
200
+ self.parent.assertTrue(result.encoder_hidden_states is not None)
201
+ # okay, now we need to check the logits shape
202
+ # due to the encoder compression, masks have a //4 spatial size
203
+ self.parent.assertEqual(
204
+ result.masks_queries_logits.shape,
205
+ (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4),
206
+ )
207
+ # + 1 for null class
208
+ self.parent.assertEqual(
209
+ result.class_queries_logits.shape, (self.batch_size, self.num_queries, self.num_labels + 1)
210
+ )
211
+
212
+ with torch.no_grad():
213
+ result = model(pixel_values=pixel_values, task_inputs=task_inputs, pixel_mask=pixel_mask)
214
+ result = model(pixel_values, task_inputs)
215
+
216
+ comm_check_on_output(result)
217
+
218
+ config.is_training = True
219
+ model = OneFormerForUniversalSegmentation(config=config)
220
+ model.to(torch_device)
221
+ model.eval()
222
+
223
+ with torch.no_grad():
224
+ result = model(
225
+ pixel_values=pixel_values,
226
+ task_inputs=task_inputs,
227
+ pixel_mask=pixel_mask,
228
+ mask_labels=mask_labels,
229
+ class_labels=class_labels,
230
+ text_inputs=text_inputs,
231
+ )
232
+
233
+ comm_check_on_output(result)
234
+
235
+ self.parent.assertTrue(result.loss is not None)
236
+ self.parent.assertEqual(result.loss.shape, torch.Size([1]))
237
+
238
+
239
+ @require_torch
240
+ class OneFormerModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
241
+ all_model_classes = (OneFormerModel, OneFormerForUniversalSegmentation) if is_torch_available() else ()
242
+ pipeline_model_mapping = {"feature-extraction": OneFormerModel} if is_torch_available() else {}
243
+
244
+ is_encoder_decoder = False
245
+ test_pruning = False
246
+ test_head_masking = False
247
+ test_missing_keys = False
248
+
249
+ # TODO: Fix the failed tests when this model gets more usage
250
+ def is_pipeline_test_to_skip(
251
+ self,
252
+ pipeline_test_case_name,
253
+ config_class,
254
+ model_architecture,
255
+ tokenizer_name,
256
+ image_processor_name,
257
+ feature_extractor_name,
258
+ processor_name,
259
+ ):
260
+ if pipeline_test_case_name == "FeatureExtractionPipelineTests":
261
+ return True
262
+
263
+ return False
264
+
265
+ def setUp(self):
266
+ self.model_tester = OneFormerModelTester(self)
267
+ self.config_tester = ConfigTester(self, config_class=OneFormerConfig, has_text_modality=False)
268
+
269
+ def test_config(self):
270
+ self.config_tester.run_common_tests()
271
+
272
+ @is_flaky(
273
+ description="The `attention_mask` computed with `< 0.5` in `OneFormerTransformerDecoder.forward_prediction_heads` is sensitive to input values."
274
+ )
275
+ def test_batching_equivalence(self):
276
+ super().test_batching_equivalence()
277
+
278
+ def test_oneformer_model(self):
279
+ config, inputs = self.model_tester.prepare_config_and_inputs_for_common()
280
+ self.model_tester.create_and_check_oneformer_model(config, **inputs, output_hidden_states=False)
281
+
282
+ def test_oneformer_universal_segmentation_head_model(self):
283
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
284
+ self.model_tester.create_and_check_oneformer_universal_segmentation_head_model(*config_and_inputs)
285
+
286
+ def test_model_main_input_name(self):
287
+ for model_class in self.all_model_classes:
288
+ model_signature = inspect.signature(getattr(model_class, "forward"))
289
+ # The main input is the name of the argument after `self`
290
+ observed_main_input_name = list(model_signature.parameters.keys())[1:3]
291
+ self.assertEqual(model_class.main_input_name, observed_main_input_name)
292
+
293
+ @unittest.skip(reason="OneFormer uses two main inputs")
294
+ def test_torchscript_simple(self):
295
+ pass
296
+
297
+ @unittest.skip(reason="OneFormer uses two main inputs")
298
+ def test_torchscript_output_attentions(self):
299
+ pass
300
+
301
+ @unittest.skip(reason="OneFormer uses two main inputs")
302
+ def test_torchscript_output_hidden_state(self):
303
+ pass
304
+
305
+ @unittest.skip(reason="OneFormer does not use inputs_embeds")
306
+ def test_inputs_embeds(self):
307
+ pass
308
+
309
+ @unittest.skip(reason="OneFormer does not have a get_input_embeddings method")
310
+ def test_model_get_set_embeddings(self):
311
+ pass
312
+
313
+ @unittest.skip(reason="OneFormer is not a generative model")
314
+ def test_generate_without_input_ids(self):
315
+ pass
316
+
317
+ @unittest.skip(reason="OneFormer does not use token embeddings")
318
+ def test_resize_tokens_embeddings(self):
319
+ pass
320
+
321
+ @require_torch_multi_gpu
322
+ @unittest.skip(
323
+ reason="OneFormer has some layers using `add_module` which doesn't work well with `nn.DataParallel`"
324
+ )
325
+ def test_multi_gpu_data_parallel_forward(self):
326
+ pass
327
+
328
+ def test_forward_signature(self):
329
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
330
+
331
+ for model_class in self.all_model_classes:
332
+ model = model_class(config)
333
+ signature = inspect.signature(model.forward)
334
+ # signature.parameters is an OrderedDict => so arg_names order is deterministic
335
+ arg_names = [*signature.parameters.keys()]
336
+
337
+ expected_arg_names = ["pixel_values", "task_inputs"]
338
+ self.assertListEqual(arg_names[:2], expected_arg_names)
339
+
340
+ @slow
341
+ def test_model_from_pretrained(self):
342
+ for model_name in ["shi-labs/oneformer_ade20k_swin_tiny"]:
343
+ model = OneFormerModel.from_pretrained(model_name)
344
+ self.assertIsNotNone(model)
345
+
346
+ def test_model_with_labels(self):
347
+ size = (self.model_tester.min_size,) * 2
348
+ inputs = {
349
+ "pixel_values": torch.randn((2, 3, *size), device=torch_device),
350
+ "task_inputs": torch.randint(high=self.model_tester.vocab_size, size=(2, 77), device=torch_device).long(),
351
+ "text_inputs": torch.randint(
352
+ high=self.model_tester.vocab_size, size=(2, 6, 77), device=torch_device
353
+ ).long(),
354
+ "mask_labels": torch.randn((2, 150, *size), device=torch_device),
355
+ "class_labels": torch.zeros(2, 150, device=torch_device).long(),
356
+ }
357
+
358
+ config = self.model_tester.get_config()
359
+ config.is_training = True
360
+
361
+ model = OneFormerForUniversalSegmentation(config).to(torch_device)
362
+ outputs = model(**inputs)
363
+ self.assertTrue(outputs.loss is not None)
364
+
365
+ def test_hidden_states_output(self):
366
+ config, inputs = self.model_tester.prepare_config_and_inputs_for_common()
367
+ self.model_tester.create_and_check_oneformer_model(config, **inputs, output_hidden_states=True)
368
+
369
+ def test_attention_outputs(self):
370
+ config, inputs = self.model_tester.prepare_config_and_inputs_for_common()
371
+
372
+ for model_class in self.all_model_classes:
373
+ model = model_class(config).to(torch_device)
374
+ outputs = model(**inputs, output_attentions=True)
375
+ self.assertTrue(outputs.attentions is not None)
376
+
377
+ def test_initialization(self):
378
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
379
+ config.contrastive_temperature = 1
380
+
381
+ configs_no_init = _config_zero_init(config)
382
+ for model_class in self.all_model_classes:
383
+ model = model_class(config=configs_no_init)
384
+ for name, param in model.named_parameters():
385
+ if param.requires_grad:
386
+ self.assertIn(
387
+ ((param.data.mean() * 1e9).round() / 1e9).item(),
388
+ [0.0, 1.0],
389
+ msg=f"Parameter {name} of model {model_class} seems not properly initialized",
390
+ )
391
+
392
+ def test_training(self):
393
+ if not self.model_tester.is_training:
394
+ self.skipTest(reason="model_tester.is_training is set to False")
395
+ # only OneFormerForUniversalSegmentation has the loss
396
+ model_class = self.all_model_classes[1]
397
+ (
398
+ config,
399
+ pixel_values,
400
+ task_inputs,
401
+ text_inputs,
402
+ pixel_mask,
403
+ mask_labels,
404
+ class_labels,
405
+ ) = self.model_tester.prepare_config_and_inputs()
406
+ config.is_training = True
407
+
408
+ model = model_class(config)
409
+ model.to(torch_device)
410
+ model.train()
411
+
412
+ loss = model(
413
+ pixel_values, task_inputs, text_inputs=text_inputs, mask_labels=mask_labels, class_labels=class_labels
414
+ ).loss
415
+ loss.backward()
416
+
417
+ def test_retain_grad_hidden_states_attentions(self):
418
+ # only OneFormerForUniversalSegmentation has the loss
419
+ model_class = self.all_model_classes[1]
420
+ (
421
+ config,
422
+ pixel_values,
423
+ task_inputs,
424
+ text_inputs,
425
+ pixel_mask,
426
+ mask_labels,
427
+ class_labels,
428
+ ) = self.model_tester.prepare_config_and_inputs()
429
+ config.output_hidden_states = True
430
+ config.output_attentions = True
431
+ config.is_training = True
432
+
433
+ model = model_class(config)
434
+ model.to(torch_device)
435
+ model.train()
436
+
437
+ outputs = model(
438
+ pixel_values, task_inputs, text_inputs=text_inputs, mask_labels=mask_labels, class_labels=class_labels
439
+ )
440
+
441
+ encoder_hidden_states = outputs.encoder_hidden_states[0]
442
+ encoder_hidden_states.retain_grad()
443
+
444
+ pixel_decoder_hidden_states = outputs.pixel_decoder_hidden_states[0]
445
+ pixel_decoder_hidden_states.retain_grad()
446
+
447
+ transformer_decoder_class_predictions = outputs.transformer_decoder_class_predictions
448
+ transformer_decoder_class_predictions.retain_grad()
449
+
450
+ transformer_decoder_mask_predictions = outputs.transformer_decoder_mask_predictions
451
+ transformer_decoder_mask_predictions.retain_grad()
452
+
453
+ attentions = outputs.attentions[0][0]
454
+ attentions.retain_grad()
455
+
456
+ outputs.loss.backward(retain_graph=True)
457
+
458
+ self.assertIsNotNone(encoder_hidden_states.grad)
459
+ self.assertIsNotNone(pixel_decoder_hidden_states.grad)
460
+ self.assertIsNotNone(transformer_decoder_class_predictions.grad)
461
+ self.assertIsNotNone(transformer_decoder_mask_predictions.grad)
462
+ self.assertIsNotNone(attentions.grad)
463
+
464
+ @require_timm
465
+ def test_backbone_selection(self):
466
+ config, inputs = self.model_tester.prepare_config_and_inputs_for_common()
467
+
468
+ config.backbone_config = None
469
+ config.backbone_kwargs = {"out_indices": [1, 2, 3]}
470
+ config.use_pretrained_backbone = True
471
+
472
+ # Load a timm backbone
473
+ # We can't load transformer checkpoint with timm backbone, as we can't specify features_only and out_indices
474
+ config.backbone = "resnet18"
475
+ config.use_timm_backbone = True
476
+
477
+ for model_class in self.all_model_classes:
478
+ model = model_class(config).to(torch_device).eval()
479
+ if model.__class__.__name__ == "OneFormerModel":
480
+ self.assertEqual(model.pixel_level_module.encoder.out_indices, [1, 2, 3])
481
+ elif model.__class__.__name__ == "OneFormerForUniversalSegmentation":
482
+ self.assertEqual(model.model.pixel_level_module.encoder.out_indices, [1, 2, 3])
483
+
484
+ # Load a HF backbone
485
+ config.backbone = "microsoft/resnet-18"
486
+ config.use_timm_backbone = False
487
+
488
+ for model_class in self.all_model_classes:
489
+ model = model_class(config).to(torch_device).eval()
490
+ if model.__class__.__name__ == "OneFormerModel":
491
+ self.assertEqual(model.pixel_level_module.encoder.out_indices, [1, 2, 3])
492
+ elif model.__class__.__name__ == "OneFormerForUniversalSegmentation":
493
+ self.assertEqual(model.model.pixel_level_module.encoder.out_indices, [1, 2, 3])
494
+
495
+
496
+ TOLERANCE = 1e-4
497
+
498
+
499
+ # We will verify our results on an image of cute cats
500
+ def prepare_img():
501
+ image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
502
+ return image
503
+
504
+
505
+ @require_vision
506
+ @slow
507
+ class OneFormerModelIntegrationTest(unittest.TestCase):
508
+ @cached_property
509
+ def model_checkpoints(self):
510
+ return "shi-labs/oneformer_ade20k_swin_tiny"
511
+
512
+ @cached_property
513
+ def default_processor(self):
514
+ return OneFormerProcessor.from_pretrained(self.model_checkpoints) if is_vision_available() else None
515
+
516
+ def test_inference_no_head(self):
517
+ model = OneFormerModel.from_pretrained(self.model_checkpoints).to(torch_device)
518
+ processor = self.default_processor
519
+ image = prepare_img()
520
+ inputs = processor(image, ["semantic"], return_tensors="pt").to(torch_device)
521
+ inputs_shape = inputs["pixel_values"].shape
522
+ # check size
523
+ self.assertEqual(inputs_shape, (1, 3, 512, 682))
524
+
525
+ task_inputs_shape = inputs["task_inputs"].shape
526
+ # check size
527
+ self.assertEqual(task_inputs_shape, (1, 77))
528
+
529
+ with torch.no_grad():
530
+ outputs = model(**inputs)
531
+
532
+ expected_slice_hidden_state = torch.tensor(
533
+ [[0.2723, 0.8280, 0.6026], [1.2699, 1.1257, 1.1444], [1.1344, 0.6153, 0.4177]]
534
+ ).to(torch_device)
535
+ self.assertTrue(
536
+ torch.allclose(
537
+ outputs.encoder_hidden_states[-1][0, 0, :3, :3], expected_slice_hidden_state, atol=TOLERANCE
538
+ )
539
+ )
540
+
541
+ expected_slice_hidden_state = torch.tensor(
542
+ [[1.0581, 1.2276, 1.2003], [1.1903, 1.2925, 1.2862], [1.158, 1.2559, 1.3216]]
543
+ ).to(torch_device)
544
+ self.assertTrue(
545
+ torch.allclose(
546
+ outputs.pixel_decoder_hidden_states[0][0, 0, :3, :3], expected_slice_hidden_state, atol=TOLERANCE
547
+ )
548
+ )
549
+
550
+ expected_slice_hidden_state = torch.tensor(
551
+ [[3.0668, -1.1833, -5.1103], [3.344, -3.362, -5.1101], [2.6017, -4.3613, -4.1444]]
552
+ ).to(torch_device)
553
+ self.assertTrue(
554
+ torch.allclose(
555
+ outputs.transformer_decoder_class_predictions[0, :3, :3], expected_slice_hidden_state, atol=TOLERANCE
556
+ )
557
+ )
558
+
559
+ def test_inference_universal_segmentation_head(self):
560
+ model = OneFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints).to(torch_device).eval()
561
+ processor = self.default_processor
562
+ image = prepare_img()
563
+ inputs = processor(image, ["semantic"], return_tensors="pt").to(torch_device)
564
+ inputs_shape = inputs["pixel_values"].shape
565
+ # check size
566
+ self.assertEqual(inputs_shape, (1, 3, 512, 682))
567
+
568
+ with torch.no_grad():
569
+ outputs = model(**inputs)
570
+
571
+ # masks_queries_logits
572
+ masks_queries_logits = outputs.masks_queries_logits
573
+ self.assertEqual(
574
+ masks_queries_logits.shape,
575
+ (1, model.config.num_queries, inputs_shape[-2] // 4, (inputs_shape[-1] + 2) // 4),
576
+ )
577
+ expected_slice = [[[3.1848, 4.2141, 4.1993], [2.9000, 3.5721, 3.6603], [2.5358, 3.0883, 3.6168]]]
578
+ expected_slice = torch.tensor(expected_slice).to(torch_device)
579
+ torch.testing.assert_close(masks_queries_logits[0, 0, :3, :3], expected_slice, rtol=TOLERANCE, atol=TOLERANCE)
580
+ # class_queries_logits
581
+ class_queries_logits = outputs.class_queries_logits
582
+ self.assertEqual(
583
+ class_queries_logits.shape,
584
+ (1, model.config.num_queries, model.config.num_labels + 1),
585
+ )
586
+ expected_slice = torch.tensor(
587
+ [[3.0668, -1.1833, -5.1103], [3.3440, -3.3620, -5.1101], [2.6017, -4.3613, -4.1444]]
588
+ ).to(torch_device)
589
+ torch.testing.assert_close(class_queries_logits[0, :3, :3], expected_slice, rtol=TOLERANCE, atol=TOLERANCE)
590
+
591
+ @require_torch_accelerator
592
+ @require_torch_fp16
593
+ def test_inference_fp16(self):
594
+ model = (
595
+ OneFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints)
596
+ .to(torch_device, dtype=torch.float16)
597
+ .eval()
598
+ )
599
+ processor = self.default_processor
600
+ image = prepare_img()
601
+ inputs = processor(image, ["semantic"], return_tensors="pt").to(torch_device, dtype=torch.float16)
602
+
603
+ with torch.no_grad():
604
+ _ = model(**inputs)
605
+
606
+ def test_with_segmentation_maps_and_loss(self):
607
+ dummy_model = OneFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints)
608
+ processor = self.default_processor
609
+ processor.image_processor.num_text = dummy_model.config.num_queries - dummy_model.config.text_encoder_n_ctx
610
+ dummy_model.config.is_training = True
611
+ model = OneFormerForUniversalSegmentation(dummy_model.config).to(torch_device).eval()
612
+ del dummy_model
613
+
614
+ inputs = processor(
615
+ [np.zeros((3, 512, 640)), np.zeros((3, 512, 640))],
616
+ ["semantic", "semantic"],
617
+ segmentation_maps=[np.zeros((384, 384)).astype(np.float32), np.zeros((384, 384)).astype(np.float32)],
618
+ return_tensors="pt",
619
+ )
620
+
621
+ inputs["pixel_values"] = inputs["pixel_values"].to(torch_device)
622
+ inputs["task_inputs"] = inputs["task_inputs"].to(torch_device)
623
+ inputs["text_inputs"] = inputs["text_inputs"].to(torch_device)
624
+ inputs["mask_labels"] = [el.to(torch_device) for el in inputs["mask_labels"]]
625
+ inputs["class_labels"] = [el.to(torch_device) for el in inputs["class_labels"]]
626
+
627
+ with torch.no_grad():
628
+ outputs = model(**inputs)
629
+
630
+ self.assertTrue(outputs.loss is not None)
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/oneformer/test_processor_oneformer.py ADDED
@@ -0,0 +1,799 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 json
18
+ import os
19
+ import tempfile
20
+ import unittest
21
+
22
+ import numpy as np
23
+ from datasets import load_dataset
24
+ from huggingface_hub import hf_hub_download
25
+
26
+ from transformers.testing_utils import check_json_file_has_correct_format, require_torch, require_vision
27
+ from transformers.utils import is_torch_available, is_vision_available
28
+
29
+ from ...test_image_processing_common import prepare_image_inputs
30
+
31
+
32
+ if is_torch_available():
33
+ import torch
34
+
35
+ if is_vision_available():
36
+ from transformers import CLIPTokenizer, OneFormerImageProcessor, OneFormerProcessor
37
+ from transformers.models.oneformer.image_processing_oneformer import binary_mask_to_rle
38
+ from transformers.models.oneformer.modeling_oneformer import OneFormerForUniversalSegmentationOutput
39
+
40
+ if is_vision_available():
41
+ from PIL import Image
42
+
43
+
44
+ def prepare_metadata(class_info_file, repo_path="shi-labs/oneformer_demo"):
45
+ with open(hf_hub_download(repo_path, class_info_file, repo_type="dataset"), "r") as f:
46
+ class_info = json.load(f)
47
+ metadata = {}
48
+ class_names = []
49
+ thing_ids = []
50
+
51
+ for key, info in class_info.items():
52
+ metadata[key] = info["name"]
53
+ class_names.append(info["name"])
54
+ if info["isthing"]:
55
+ thing_ids.append(int(key))
56
+
57
+ metadata["thing_ids"] = thing_ids
58
+ metadata["class_names"] = class_names
59
+ return metadata
60
+
61
+
62
+ class OneFormerProcessorTester:
63
+ def __init__(
64
+ self,
65
+ parent,
66
+ batch_size=7,
67
+ num_channels=3,
68
+ min_resolution=30,
69
+ max_resolution=400,
70
+ size=None,
71
+ do_resize=True,
72
+ do_normalize=True,
73
+ image_mean=[0.5, 0.5, 0.5],
74
+ image_std=[0.5, 0.5, 0.5],
75
+ num_labels=10,
76
+ do_reduce_labels=False,
77
+ ignore_index=255,
78
+ max_seq_length=77,
79
+ task_seq_length=77,
80
+ model_repo="shi-labs/oneformer_ade20k_swin_tiny",
81
+ class_info_file="ade20k_panoptic.json",
82
+ num_text=10,
83
+ ):
84
+ self.parent = parent
85
+ self.batch_size = batch_size
86
+ self.num_channels = num_channels
87
+ self.min_resolution = min_resolution
88
+ self.max_resolution = max_resolution
89
+ self.do_resize = do_resize
90
+ self.size = {"shortest_edge": 32, "longest_edge": 1333} if size is None else size
91
+ self.do_normalize = do_normalize
92
+ self.image_mean = image_mean
93
+ self.image_std = image_std
94
+ self.max_seq_length = max_seq_length
95
+ self.task_seq_length = task_seq_length
96
+ self.class_info_file = class_info_file
97
+ self.metadata = prepare_metadata(class_info_file)
98
+ self.num_text = num_text
99
+ self.model_repo = model_repo
100
+
101
+ # for the post_process_functions
102
+ self.batch_size = 2
103
+ self.num_queries = 10
104
+ self.num_classes = 10
105
+ self.height = 3
106
+ self.width = 4
107
+ self.num_labels = num_labels
108
+ self.do_reduce_labels = do_reduce_labels
109
+ self.ignore_index = ignore_index
110
+
111
+ def prepare_processor_dict(self):
112
+ image_processor_dict = {
113
+ "do_resize": self.do_resize,
114
+ "size": self.size,
115
+ "do_normalize": self.do_normalize,
116
+ "image_mean": self.image_mean,
117
+ "image_std": self.image_std,
118
+ "num_labels": self.num_labels,
119
+ "do_reduce_labels": self.do_reduce_labels,
120
+ "ignore_index": self.ignore_index,
121
+ "class_info_file": self.class_info_file,
122
+ "metadata": self.metadata,
123
+ "num_text": self.num_text,
124
+ }
125
+
126
+ image_processor = OneFormerImageProcessor(**image_processor_dict)
127
+ tokenizer = CLIPTokenizer.from_pretrained(self.model_repo)
128
+
129
+ return {
130
+ "image_processor": image_processor,
131
+ "tokenizer": tokenizer,
132
+ "max_seq_length": self.max_seq_length,
133
+ "task_seq_length": self.task_seq_length,
134
+ }
135
+
136
+ def get_expected_values(self, image_inputs, batched=False):
137
+ """
138
+ This function computes the expected height and width when providing images to OneFormerProcessor,
139
+ assuming do_resize is set to True with a scalar size. It also provides the expected sequence length
140
+ for the task_inputs and text_list_input.
141
+ """
142
+ if not batched:
143
+ image = image_inputs[0]
144
+ if isinstance(image, Image.Image):
145
+ w, h = image.size
146
+ elif isinstance(image, np.ndarray):
147
+ h, w = image.shape[0], image.shape[1]
148
+ else:
149
+ h, w = image.shape[1], image.shape[2]
150
+ if w < h:
151
+ expected_height = int(self.size["shortest_edge"] * h / w)
152
+ expected_width = self.size["shortest_edge"]
153
+ elif w > h:
154
+ expected_height = self.size["shortest_edge"]
155
+ expected_width = int(self.size["shortest_edge"] * w / h)
156
+ else:
157
+ expected_height = self.size["shortest_edge"]
158
+ expected_width = self.size["shortest_edge"]
159
+
160
+ else:
161
+ expected_values = []
162
+ for image in image_inputs:
163
+ expected_height, expected_width, expected_sequence_length = self.get_expected_values([image])
164
+ expected_values.append((expected_height, expected_width, expected_sequence_length))
165
+ expected_height = max(expected_values, key=lambda item: item[0])[0]
166
+ expected_width = max(expected_values, key=lambda item: item[1])[1]
167
+
168
+ expected_sequence_length = self.max_seq_length
169
+
170
+ return expected_height, expected_width, expected_sequence_length
171
+
172
+ def get_fake_oneformer_outputs(self):
173
+ return OneFormerForUniversalSegmentationOutput(
174
+ # +1 for null class
175
+ class_queries_logits=torch.randn((self.batch_size, self.num_queries, self.num_classes + 1)),
176
+ masks_queries_logits=torch.randn((self.batch_size, self.num_queries, self.height, self.width)),
177
+ )
178
+
179
+ def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
180
+ return prepare_image_inputs(
181
+ batch_size=self.batch_size,
182
+ num_channels=self.num_channels,
183
+ min_resolution=self.min_resolution,
184
+ max_resolution=self.max_resolution,
185
+ equal_resolution=equal_resolution,
186
+ numpify=numpify,
187
+ torchify=torchify,
188
+ )
189
+
190
+
191
+ @require_torch
192
+ @require_vision
193
+ class OneFormerProcessingTest(unittest.TestCase):
194
+ processing_class = OneFormerProcessor if (is_vision_available() and is_torch_available()) else None
195
+ # only for test_feat_extracttion_common.test_feat_extract_to_json_string
196
+ feature_extraction_class = processing_class
197
+
198
+ def setUp(self):
199
+ self.processing_tester = OneFormerProcessorTester(self)
200
+
201
+ @property
202
+ def processor_dict(self):
203
+ return self.processing_tester.prepare_processor_dict()
204
+
205
+ def test_feat_extract_properties(self):
206
+ processor = self.processing_class(**self.processor_dict)
207
+ self.assertTrue(hasattr(processor, "image_processor"))
208
+ self.assertTrue(hasattr(processor, "tokenizer"))
209
+ self.assertTrue(hasattr(processor, "max_seq_length"))
210
+ self.assertTrue(hasattr(processor, "task_seq_length"))
211
+
212
+ @unittest.skip
213
+ def test_batch_feature(self):
214
+ pass
215
+
216
+ def test_call_pil(self):
217
+ # Initialize processor
218
+ processor = self.processing_class(**self.processor_dict)
219
+ # create random PIL images
220
+ image_inputs = self.processing_tester.prepare_image_inputs(equal_resolution=False)
221
+ for image in image_inputs:
222
+ self.assertIsInstance(image, Image.Image)
223
+
224
+ # Test not batched input
225
+ encoded_images = processor(image_inputs[0], ["semantic"], return_tensors="pt").pixel_values
226
+
227
+ expected_height, expected_width, expected_sequence_length = self.processing_tester.get_expected_values(
228
+ image_inputs
229
+ )
230
+
231
+ self.assertEqual(
232
+ encoded_images.shape,
233
+ (1, self.processing_tester.num_channels, expected_height, expected_width),
234
+ )
235
+
236
+ tokenized_task_inputs = processor(image_inputs[0], ["semantic"], return_tensors="pt").task_inputs
237
+
238
+ self.assertEqual(
239
+ tokenized_task_inputs.shape,
240
+ (1, expected_sequence_length),
241
+ )
242
+
243
+ # Test batched
244
+ expected_height, expected_width, expected_sequence_length = self.processing_tester.get_expected_values(
245
+ image_inputs, batched=True
246
+ )
247
+
248
+ encoded_images = processor(image_inputs, ["semantic"] * len(image_inputs), return_tensors="pt").pixel_values
249
+ self.assertEqual(
250
+ encoded_images.shape,
251
+ (
252
+ self.processing_tester.batch_size,
253
+ self.processing_tester.num_channels,
254
+ expected_height,
255
+ expected_width,
256
+ ),
257
+ )
258
+
259
+ tokenized_task_inputs = processor(
260
+ image_inputs, ["semantic"] * len(image_inputs), return_tensors="pt"
261
+ ).task_inputs
262
+
263
+ self.assertEqual(
264
+ tokenized_task_inputs.shape,
265
+ (self.processing_tester.batch_size, expected_sequence_length),
266
+ )
267
+
268
+ def test_call_numpy(self):
269
+ # Initialize processor
270
+ processor = self.processing_class(**self.processor_dict)
271
+ # create random numpy tensors
272
+ image_inputs = self.processing_tester.prepare_image_inputs(equal_resolution=False, numpify=True)
273
+ for image in image_inputs:
274
+ self.assertIsInstance(image, np.ndarray)
275
+
276
+ # Test not batched input
277
+ encoded_images = processor(image_inputs[0], ["semantic"], return_tensors="pt").pixel_values
278
+
279
+ expected_height, expected_width, expected_sequence_length = self.processing_tester.get_expected_values(
280
+ image_inputs
281
+ )
282
+
283
+ self.assertEqual(
284
+ encoded_images.shape,
285
+ (1, self.processing_tester.num_channels, expected_height, expected_width),
286
+ )
287
+
288
+ tokenized_task_inputs = processor(image_inputs[0], ["semantic"], return_tensors="pt").task_inputs
289
+
290
+ self.assertEqual(
291
+ tokenized_task_inputs.shape,
292
+ (1, expected_sequence_length),
293
+ )
294
+
295
+ # Test batched
296
+ expected_height, expected_width, expected_sequence_length = self.processing_tester.get_expected_values(
297
+ image_inputs, batched=True
298
+ )
299
+
300
+ encoded_images = processor(image_inputs, ["semantic"] * len(image_inputs), return_tensors="pt").pixel_values
301
+ self.assertEqual(
302
+ encoded_images.shape,
303
+ (
304
+ self.processing_tester.batch_size,
305
+ self.processing_tester.num_channels,
306
+ expected_height,
307
+ expected_width,
308
+ ),
309
+ )
310
+
311
+ tokenized_task_inputs = processor(
312
+ image_inputs, ["semantic"] * len(image_inputs), return_tensors="pt"
313
+ ).task_inputs
314
+
315
+ self.assertEqual(
316
+ tokenized_task_inputs.shape,
317
+ (self.processing_tester.batch_size, expected_sequence_length),
318
+ )
319
+
320
+ def test_call_pytorch(self):
321
+ # Initialize processor
322
+ processor = self.processing_class(**self.processor_dict)
323
+ # create random PyTorch tensors
324
+ image_inputs = self.processing_tester.prepare_image_inputs(equal_resolution=False, torchify=True)
325
+ for image in image_inputs:
326
+ self.assertIsInstance(image, torch.Tensor)
327
+
328
+ # Test not batched input
329
+ encoded_images = processor(image_inputs[0], ["semantic"], return_tensors="pt").pixel_values
330
+
331
+ expected_height, expected_width, expected_sequence_length = self.processing_tester.get_expected_values(
332
+ image_inputs
333
+ )
334
+
335
+ self.assertEqual(
336
+ encoded_images.shape,
337
+ (1, self.processing_tester.num_channels, expected_height, expected_width),
338
+ )
339
+
340
+ tokenized_task_inputs = processor(image_inputs[0], ["semantic"], return_tensors="pt").task_inputs
341
+
342
+ self.assertEqual(
343
+ tokenized_task_inputs.shape,
344
+ (1, expected_sequence_length),
345
+ )
346
+
347
+ # Test batched
348
+ expected_height, expected_width, expected_sequence_length = self.processing_tester.get_expected_values(
349
+ image_inputs, batched=True
350
+ )
351
+
352
+ encoded_images = processor(image_inputs, ["semantic"] * len(image_inputs), return_tensors="pt").pixel_values
353
+ self.assertEqual(
354
+ encoded_images.shape,
355
+ (
356
+ self.processing_tester.batch_size,
357
+ self.processing_tester.num_channels,
358
+ expected_height,
359
+ expected_width,
360
+ ),
361
+ )
362
+
363
+ tokenized_task_inputs = processor(
364
+ image_inputs, ["semantic"] * len(image_inputs), return_tensors="pt"
365
+ ).task_inputs
366
+
367
+ self.assertEqual(
368
+ tokenized_task_inputs.shape,
369
+ (self.processing_tester.batch_size, expected_sequence_length),
370
+ )
371
+
372
+ def comm_get_processor_inputs(self, with_segmentation_maps=False, is_instance_map=False, segmentation_type="np"):
373
+ processor = self.processing_class(**self.processor_dict)
374
+ # prepare image and target
375
+ num_labels = self.processing_tester.num_labels
376
+ annotations = None
377
+ instance_id_to_semantic_id = None
378
+ image_inputs = self.processing_tester.prepare_image_inputs(equal_resolution=False)
379
+ if with_segmentation_maps:
380
+ high = num_labels
381
+ if is_instance_map:
382
+ labels_expanded = list(range(num_labels)) * 2
383
+ instance_id_to_semantic_id = dict(enumerate(labels_expanded))
384
+ annotations = [
385
+ np.random.randint(0, high * 2, (img.size[1], img.size[0])).astype(np.uint8) for img in image_inputs
386
+ ]
387
+ if segmentation_type == "pil":
388
+ annotations = [Image.fromarray(annotation) for annotation in annotations]
389
+
390
+ inputs = processor(
391
+ image_inputs,
392
+ ["semantic"] * len(image_inputs),
393
+ annotations,
394
+ return_tensors="pt",
395
+ instance_id_to_semantic_id=instance_id_to_semantic_id,
396
+ pad_and_return_pixel_mask=True,
397
+ )
398
+
399
+ return inputs
400
+
401
+ @unittest.skip
402
+ def test_init_without_params(self):
403
+ pass
404
+
405
+ def test_feat_extract_from_and_save_pretrained(self):
406
+ feat_extract_first = self.feature_extraction_class(**self.processor_dict)
407
+
408
+ with tempfile.TemporaryDirectory() as tmpdirname:
409
+ feat_extract_first.save_pretrained(tmpdirname)
410
+ check_json_file_has_correct_format(os.path.join(tmpdirname, "preprocessor_config.json"))
411
+ feat_extract_second = self.feature_extraction_class.from_pretrained(tmpdirname)
412
+
413
+ self.assertEqual(feat_extract_second.image_processor.to_dict(), feat_extract_first.image_processor.to_dict())
414
+ self.assertIsInstance(feat_extract_first.image_processor, OneFormerImageProcessor)
415
+ self.assertIsInstance(feat_extract_first.tokenizer, CLIPTokenizer)
416
+
417
+ def test_call_with_segmentation_maps(self):
418
+ def common(is_instance_map=False, segmentation_type=None):
419
+ inputs = self.comm_get_processor_inputs(
420
+ with_segmentation_maps=True, is_instance_map=is_instance_map, segmentation_type=segmentation_type
421
+ )
422
+
423
+ mask_labels = inputs["mask_labels"]
424
+ class_labels = inputs["class_labels"]
425
+ pixel_values = inputs["pixel_values"]
426
+ text_inputs = inputs["text_inputs"]
427
+
428
+ # check the batch_size
429
+ for mask_label, class_label, text_input in zip(mask_labels, class_labels, text_inputs):
430
+ self.assertEqual(mask_label.shape[0], class_label.shape[0])
431
+ # this ensure padding has happened
432
+ self.assertEqual(mask_label.shape[1:], pixel_values.shape[2:])
433
+ self.assertEqual(text_input.shape[0], self.processing_tester.num_text)
434
+
435
+ common()
436
+ common(is_instance_map=True)
437
+ common(is_instance_map=False, segmentation_type="pil")
438
+ common(is_instance_map=True, segmentation_type="pil")
439
+
440
+ def test_integration_semantic_segmentation(self):
441
+ # load 2 images and corresponding panoptic annotations from the hub
442
+ dataset = load_dataset("nielsr/ade20k-panoptic-demo")
443
+ image1 = dataset["train"][0]["image"]
444
+ image2 = dataset["train"][1]["image"]
445
+ segments_info1 = dataset["train"][0]["segments_info"]
446
+ segments_info2 = dataset["train"][1]["segments_info"]
447
+ annotation1 = dataset["train"][0]["label"]
448
+ annotation2 = dataset["train"][1]["label"]
449
+
450
+ def rgb_to_id(color):
451
+ if isinstance(color, np.ndarray) and len(color.shape) == 3:
452
+ if color.dtype == np.uint8:
453
+ color = color.astype(np.int32)
454
+ return color[:, :, 0] + 256 * color[:, :, 1] + 256 * 256 * color[:, :, 2]
455
+ return int(color[0] + 256 * color[1] + 256 * 256 * color[2])
456
+
457
+ def create_panoptic_map(annotation, segments_info):
458
+ annotation = np.array(annotation)
459
+ # convert RGB to segment IDs per pixel
460
+ # 0 is the "ignore" label, for which we don't need to make binary masks
461
+ panoptic_map = rgb_to_id(annotation)
462
+
463
+ # create mapping between segment IDs and semantic classes
464
+ inst2class = {segment["id"]: segment["category_id"] for segment in segments_info}
465
+
466
+ return panoptic_map, inst2class
467
+
468
+ panoptic_map1, inst2class1 = create_panoptic_map(annotation1, segments_info1)
469
+ panoptic_map2, inst2class2 = create_panoptic_map(annotation2, segments_info2)
470
+
471
+ image_processor = OneFormerImageProcessor(
472
+ do_reduce_labels=True,
473
+ ignore_index=0,
474
+ size=(512, 512),
475
+ class_info_file="ade20k_panoptic.json",
476
+ num_text=self.processing_tester.num_text,
477
+ )
478
+
479
+ tokenizer = CLIPTokenizer.from_pretrained("shi-labs/oneformer_ade20k_swin_tiny")
480
+
481
+ processor = OneFormerProcessor(
482
+ image_processor=image_processor,
483
+ tokenizer=tokenizer,
484
+ max_seq_length=77,
485
+ task_seq_length=77,
486
+ )
487
+
488
+ # prepare the images and annotations
489
+ pixel_values_list = [np.moveaxis(np.array(image1), -1, 0), np.moveaxis(np.array(image2), -1, 0)]
490
+ inputs = processor.encode_inputs(
491
+ pixel_values_list,
492
+ ["semantic", "semantic"],
493
+ [panoptic_map1, panoptic_map2],
494
+ instance_id_to_semantic_id=[inst2class1, inst2class2],
495
+ return_tensors="pt",
496
+ )
497
+
498
+ # verify the pixel values, task inputs, text inputs and pixel mask
499
+ self.assertEqual(inputs["pixel_values"].shape, (2, 3, 512, 711))
500
+ self.assertEqual(inputs["pixel_mask"].shape, (2, 512, 711))
501
+ self.assertEqual(inputs["task_inputs"].shape, (2, 77))
502
+ self.assertEqual(inputs["text_inputs"].shape, (2, self.processing_tester.num_text, 77))
503
+
504
+ # verify the class labels
505
+ self.assertEqual(len(inputs["class_labels"]), 2)
506
+ expected_class_labels = torch.tensor([4, 17, 32, 42, 12, 3, 5, 0, 43, 96, 104, 31, 125, 138, 87, 149]) # noqa: E231 # fmt: skip
507
+ torch.testing.assert_close(inputs["class_labels"][0], expected_class_labels)
508
+ expected_class_labels = torch.tensor([19, 67, 82, 17, 12, 42, 3, 14, 5, 0, 115, 43, 8, 138, 125, 143]) # noqa: E231 # fmt: skip
509
+ torch.testing.assert_close(inputs["class_labels"][1], expected_class_labels)
510
+
511
+ # verify the task inputs
512
+ self.assertEqual(len(inputs["task_inputs"]), 2)
513
+ self.assertEqual(inputs["task_inputs"][0].sum().item(), 141082)
514
+ self.assertEqual(inputs["task_inputs"][0].sum().item(), inputs["task_inputs"][1].sum().item())
515
+
516
+ # verify the text inputs
517
+ self.assertEqual(len(inputs["text_inputs"]), 2)
518
+ self.assertEqual(inputs["text_inputs"][0].sum().item(), 1095752)
519
+ self.assertEqual(inputs["text_inputs"][1].sum().item(), 1062468)
520
+
521
+ # verify the mask labels
522
+ self.assertEqual(len(inputs["mask_labels"]), 2)
523
+ self.assertEqual(inputs["mask_labels"][0].shape, (16, 512, 711))
524
+ self.assertEqual(inputs["mask_labels"][1].shape, (16, 512, 711))
525
+ self.assertEqual(inputs["mask_labels"][0].sum().item(), 315193.0)
526
+ self.assertEqual(inputs["mask_labels"][1].sum().item(), 350747.0)
527
+
528
+ def test_integration_instance_segmentation(self):
529
+ # load 2 images and corresponding panoptic annotations from the hub
530
+ dataset = load_dataset("nielsr/ade20k-panoptic-demo")
531
+ image1 = dataset["train"][0]["image"]
532
+ image2 = dataset["train"][1]["image"]
533
+ segments_info1 = dataset["train"][0]["segments_info"]
534
+ segments_info2 = dataset["train"][1]["segments_info"]
535
+ annotation1 = dataset["train"][0]["label"]
536
+ annotation2 = dataset["train"][1]["label"]
537
+
538
+ def rgb_to_id(color):
539
+ if isinstance(color, np.ndarray) and len(color.shape) == 3:
540
+ if color.dtype == np.uint8:
541
+ color = color.astype(np.int32)
542
+ return color[:, :, 0] + 256 * color[:, :, 1] + 256 * 256 * color[:, :, 2]
543
+ return int(color[0] + 256 * color[1] + 256 * 256 * color[2])
544
+
545
+ def create_panoptic_map(annotation, segments_info):
546
+ annotation = np.array(annotation)
547
+ # convert RGB to segment IDs per pixel
548
+ # 0 is the "ignore" label, for which we don't need to make binary masks
549
+ panoptic_map = rgb_to_id(annotation)
550
+
551
+ # create mapping between segment IDs and semantic classes
552
+ inst2class = {segment["id"]: segment["category_id"] for segment in segments_info}
553
+
554
+ return panoptic_map, inst2class
555
+
556
+ panoptic_map1, inst2class1 = create_panoptic_map(annotation1, segments_info1)
557
+ panoptic_map2, inst2class2 = create_panoptic_map(annotation2, segments_info2)
558
+
559
+ image_processor = OneFormerImageProcessor(
560
+ do_reduce_labels=True,
561
+ ignore_index=0,
562
+ size=(512, 512),
563
+ class_info_file="ade20k_panoptic.json",
564
+ num_text=self.processing_tester.num_text,
565
+ )
566
+
567
+ tokenizer = CLIPTokenizer.from_pretrained("shi-labs/oneformer_ade20k_swin_tiny")
568
+
569
+ processor = OneFormerProcessor(
570
+ image_processor=image_processor,
571
+ tokenizer=tokenizer,
572
+ max_seq_length=77,
573
+ task_seq_length=77,
574
+ )
575
+
576
+ # prepare the images and annotations
577
+ pixel_values_list = [np.moveaxis(np.array(image1), -1, 0), np.moveaxis(np.array(image2), -1, 0)]
578
+ inputs = processor.encode_inputs(
579
+ pixel_values_list,
580
+ ["instance", "instance"],
581
+ [panoptic_map1, panoptic_map2],
582
+ instance_id_to_semantic_id=[inst2class1, inst2class2],
583
+ return_tensors="pt",
584
+ )
585
+
586
+ # verify the pixel values, task inputs, text inputs and pixel mask
587
+ self.assertEqual(inputs["pixel_values"].shape, (2, 3, 512, 711))
588
+ self.assertEqual(inputs["pixel_mask"].shape, (2, 512, 711))
589
+ self.assertEqual(inputs["task_inputs"].shape, (2, 77))
590
+ self.assertEqual(inputs["text_inputs"].shape, (2, self.processing_tester.num_text, 77))
591
+
592
+ # verify the class labels
593
+ self.assertEqual(len(inputs["class_labels"]), 2)
594
+ expected_class_labels = torch.tensor([32, 42, 42, 42, 42, 42, 42, 42, 32, 12, 12, 12, 12, 12, 42, 42, 12, 12, 12, 42, 12, 12, 12, 12, 12, 12, 12, 12, 12, 42, 42, 42, 12, 42, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 43, 43, 43, 43, 104, 43, 31, 125, 31, 125, 138, 87, 125, 149, 138, 125, 87, 87]) # fmt: skip
595
+ torch.testing.assert_close(inputs["class_labels"][0], expected_class_labels)
596
+ expected_class_labels = torch.tensor([19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 67, 82, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 12, 12, 42, 12, 12, 12, 12, 14, 12, 12, 12, 12, 12, 12, 12, 12, 14, 12, 12, 115, 43, 43, 115, 43, 43, 43, 8, 8, 8, 138, 138, 125, 143]) # fmt: skip
597
+ torch.testing.assert_close(inputs["class_labels"][1], expected_class_labels)
598
+
599
+ # verify the task inputs
600
+ self.assertEqual(len(inputs["task_inputs"]), 2)
601
+ self.assertEqual(inputs["task_inputs"][0].sum().item(), 144985)
602
+ self.assertEqual(inputs["task_inputs"][0].sum().item(), inputs["task_inputs"][1].sum().item())
603
+
604
+ # verify the text inputs
605
+ self.assertEqual(len(inputs["text_inputs"]), 2)
606
+ self.assertEqual(inputs["text_inputs"][0].sum().item(), 1037040)
607
+ self.assertEqual(inputs["text_inputs"][1].sum().item(), 1044078)
608
+
609
+ # verify the mask labels
610
+ self.assertEqual(len(inputs["mask_labels"]), 2)
611
+ self.assertEqual(inputs["mask_labels"][0].shape, (73, 512, 711))
612
+ self.assertEqual(inputs["mask_labels"][1].shape, (57, 512, 711))
613
+ self.assertEqual(inputs["mask_labels"][0].sum().item(), 35040.0)
614
+ self.assertEqual(inputs["mask_labels"][1].sum().item(), 98228.0)
615
+
616
+ def test_integration_panoptic_segmentation(self):
617
+ # load 2 images and corresponding panoptic annotations from the hub
618
+ dataset = load_dataset("nielsr/ade20k-panoptic-demo")
619
+ image1 = dataset["train"][0]["image"]
620
+ image2 = dataset["train"][1]["image"]
621
+ segments_info1 = dataset["train"][0]["segments_info"]
622
+ segments_info2 = dataset["train"][1]["segments_info"]
623
+ annotation1 = dataset["train"][0]["label"]
624
+ annotation2 = dataset["train"][1]["label"]
625
+
626
+ def rgb_to_id(color):
627
+ if isinstance(color, np.ndarray) and len(color.shape) == 3:
628
+ if color.dtype == np.uint8:
629
+ color = color.astype(np.int32)
630
+ return color[:, :, 0] + 256 * color[:, :, 1] + 256 * 256 * color[:, :, 2]
631
+ return int(color[0] + 256 * color[1] + 256 * 256 * color[2])
632
+
633
+ def create_panoptic_map(annotation, segments_info):
634
+ annotation = np.array(annotation)
635
+ # convert RGB to segment IDs per pixel
636
+ # 0 is the "ignore" label, for which we don't need to make binary masks
637
+ panoptic_map = rgb_to_id(annotation)
638
+
639
+ # create mapping between segment IDs and semantic classes
640
+ inst2class = {segment["id"]: segment["category_id"] for segment in segments_info}
641
+
642
+ return panoptic_map, inst2class
643
+
644
+ panoptic_map1, inst2class1 = create_panoptic_map(annotation1, segments_info1)
645
+ panoptic_map2, inst2class2 = create_panoptic_map(annotation2, segments_info2)
646
+
647
+ image_processor = OneFormerImageProcessor(
648
+ do_reduce_labels=True,
649
+ ignore_index=0,
650
+ size=(512, 512),
651
+ class_info_file="ade20k_panoptic.json",
652
+ num_text=self.processing_tester.num_text,
653
+ )
654
+
655
+ tokenizer = CLIPTokenizer.from_pretrained("shi-labs/oneformer_ade20k_swin_tiny")
656
+
657
+ processor = OneFormerProcessor(
658
+ image_processor=image_processor,
659
+ tokenizer=tokenizer,
660
+ max_seq_length=77,
661
+ task_seq_length=77,
662
+ )
663
+
664
+ # prepare the images and annotations
665
+ pixel_values_list = [np.moveaxis(np.array(image1), -1, 0), np.moveaxis(np.array(image2), -1, 0)]
666
+ inputs = processor.encode_inputs(
667
+ pixel_values_list,
668
+ ["panoptic", "panoptic"],
669
+ [panoptic_map1, panoptic_map2],
670
+ instance_id_to_semantic_id=[inst2class1, inst2class2],
671
+ return_tensors="pt",
672
+ )
673
+
674
+ # verify the pixel values, task inputs, text inputs and pixel mask
675
+ self.assertEqual(inputs["pixel_values"].shape, (2, 3, 512, 711))
676
+ self.assertEqual(inputs["pixel_mask"].shape, (2, 512, 711))
677
+ self.assertEqual(inputs["task_inputs"].shape, (2, 77))
678
+ self.assertEqual(inputs["text_inputs"].shape, (2, self.processing_tester.num_text, 77))
679
+
680
+ # verify the class labels
681
+ self.assertEqual(len(inputs["class_labels"]), 2)
682
+ expected_class_labels = torch.tensor([4, 17, 32, 42, 42, 42, 42, 42, 42, 42, 32, 12, 12, 12, 12, 12, 42, 42, 12, 12, 12, 42, 12, 12, 12, 12, 12, 3, 12, 12, 12, 12, 42, 42, 42, 12, 42, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 5, 12, 12, 12, 12, 12, 12, 12, 0, 43, 43, 43, 96, 43, 104, 43, 31, 125, 31, 125, 138, 87, 125, 149, 138, 125, 87, 87]) # fmt: skip
683
+ torch.testing.assert_close(inputs["class_labels"][0], expected_class_labels)
684
+ expected_class_labels = torch.tensor([19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 67, 82, 19, 19, 17, 19, 19, 19, 19, 19, 19, 19, 19, 19, 12, 12, 42, 12, 12, 12, 12, 3, 14, 12, 12, 12, 12, 12, 12, 12, 12, 14, 5, 12, 12, 0, 115, 43, 43, 115, 43, 43, 43, 8, 8, 8, 138, 138, 125, 143]) # fmt: skip
685
+ torch.testing.assert_close(inputs["class_labels"][1], expected_class_labels)
686
+
687
+ # verify the task inputs
688
+ self.assertEqual(len(inputs["task_inputs"]), 2)
689
+ self.assertEqual(inputs["task_inputs"][0].sum().item(), 136240)
690
+ self.assertEqual(inputs["task_inputs"][0].sum().item(), inputs["task_inputs"][1].sum().item())
691
+
692
+ # verify the text inputs
693
+ self.assertEqual(len(inputs["text_inputs"]), 2)
694
+ self.assertEqual(inputs["text_inputs"][0].sum().item(), 1048653)
695
+ self.assertEqual(inputs["text_inputs"][1].sum().item(), 1067160)
696
+
697
+ # verify the mask labels
698
+ self.assertEqual(len(inputs["mask_labels"]), 2)
699
+ self.assertEqual(inputs["mask_labels"][0].shape, (79, 512, 711))
700
+ self.assertEqual(inputs["mask_labels"][1].shape, (61, 512, 711))
701
+ self.assertEqual(inputs["mask_labels"][0].sum().item(), 315193.0)
702
+ self.assertEqual(inputs["mask_labels"][1].sum().item(), 350747.0)
703
+
704
+ def test_binary_mask_to_rle(self):
705
+ fake_binary_mask = np.zeros((20, 50))
706
+ fake_binary_mask[0, 20:] = 1
707
+ fake_binary_mask[1, :15] = 1
708
+ fake_binary_mask[5, :10] = 1
709
+
710
+ rle = binary_mask_to_rle(fake_binary_mask)
711
+ self.assertEqual(len(rle), 4)
712
+ self.assertEqual(rle[0], 21)
713
+ self.assertEqual(rle[1], 45)
714
+
715
+ def test_post_process_semantic_segmentation(self):
716
+ image_processor = OneFormerImageProcessor(
717
+ do_reduce_labels=True,
718
+ ignore_index=0,
719
+ size=(512, 512),
720
+ class_info_file="ade20k_panoptic.json",
721
+ num_text=self.processing_tester.num_text,
722
+ )
723
+ tokenizer = CLIPTokenizer.from_pretrained("shi-labs/oneformer_ade20k_swin_tiny")
724
+ processor = OneFormerProcessor(
725
+ image_processor=image_processor,
726
+ tokenizer=tokenizer,
727
+ max_seq_length=77,
728
+ task_seq_length=77,
729
+ )
730
+
731
+ outputs = self.processing_tester.get_fake_oneformer_outputs()
732
+
733
+ segmentation = processor.post_process_semantic_segmentation(outputs)
734
+
735
+ self.assertEqual(len(segmentation), self.processing_tester.batch_size)
736
+ self.assertEqual(
737
+ segmentation[0].shape,
738
+ (
739
+ self.processing_tester.height,
740
+ self.processing_tester.width,
741
+ ),
742
+ )
743
+
744
+ target_sizes = [(1, 4) for i in range(self.processing_tester.batch_size)]
745
+ segmentation = processor.post_process_semantic_segmentation(outputs, target_sizes=target_sizes)
746
+
747
+ self.assertEqual(segmentation[0].shape, target_sizes[0])
748
+
749
+ def test_post_process_instance_segmentation(self):
750
+ image_processor = OneFormerImageProcessor(
751
+ do_reduce_labels=True,
752
+ ignore_index=0,
753
+ size=(512, 512),
754
+ class_info_file="ade20k_panoptic.json",
755
+ num_text=self.processing_tester.num_text,
756
+ )
757
+ tokenizer = CLIPTokenizer.from_pretrained("shi-labs/oneformer_ade20k_swin_tiny")
758
+ processor = OneFormerProcessor(
759
+ image_processor=image_processor,
760
+ tokenizer=tokenizer,
761
+ max_seq_length=77,
762
+ task_seq_length=77,
763
+ )
764
+
765
+ outputs = self.processing_tester.get_fake_oneformer_outputs()
766
+ segmentation = processor.post_process_instance_segmentation(outputs, threshold=0)
767
+
768
+ self.assertTrue(len(segmentation) == self.processing_tester.batch_size)
769
+ for el in segmentation:
770
+ self.assertTrue("segmentation" in el)
771
+ self.assertTrue("segments_info" in el)
772
+ self.assertEqual(type(el["segments_info"]), list)
773
+ self.assertEqual(el["segmentation"].shape, (self.processing_tester.height, self.processing_tester.width))
774
+
775
+ def test_post_process_panoptic_segmentation(self):
776
+ image_processor = OneFormerImageProcessor(
777
+ do_reduce_labels=True,
778
+ ignore_index=0,
779
+ size=(512, 512),
780
+ class_info_file="ade20k_panoptic.json",
781
+ num_text=self.processing_tester.num_text,
782
+ )
783
+ tokenizer = CLIPTokenizer.from_pretrained("shi-labs/oneformer_ade20k_swin_tiny")
784
+ processor = OneFormerProcessor(
785
+ image_processor=image_processor,
786
+ tokenizer=tokenizer,
787
+ max_seq_length=77,
788
+ task_seq_length=77,
789
+ )
790
+
791
+ outputs = self.processing_tester.get_fake_oneformer_outputs()
792
+ segmentation = processor.post_process_panoptic_segmentation(outputs, threshold=0)
793
+
794
+ self.assertTrue(len(segmentation) == self.processing_tester.batch_size)
795
+ for el in segmentation:
796
+ self.assertTrue("segmentation" in el)
797
+ self.assertTrue("segments_info" in el)
798
+ self.assertEqual(type(el["segments_info"]), list)
799
+ self.assertEqual(el["segmentation"].shape, (self.processing_tester.height, self.processing_tester.width))
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/openai/__init__.py ADDED
File without changes
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/openai/test_modeling_openai.py ADDED
@@ -0,0 +1,312 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+
17
+ import unittest
18
+
19
+ from transformers import is_torch_available
20
+ from transformers.testing_utils import require_torch, slow, torch_device
21
+
22
+ from ...generation.test_utils import GenerationTesterMixin
23
+ from ...test_configuration_common import ConfigTester
24
+ from ...test_modeling_common import ModelTesterMixin, ids_tensor
25
+ from ...test_pipeline_mixin import PipelineTesterMixin
26
+
27
+
28
+ if is_torch_available():
29
+ import torch
30
+
31
+ from transformers import (
32
+ OpenAIGPTConfig,
33
+ OpenAIGPTDoubleHeadsModel,
34
+ OpenAIGPTForSequenceClassification,
35
+ OpenAIGPTLMHeadModel,
36
+ OpenAIGPTModel,
37
+ )
38
+
39
+
40
+ class OpenAIGPTModelTester:
41
+ def __init__(
42
+ self,
43
+ parent,
44
+ batch_size=13,
45
+ seq_length=7,
46
+ is_training=True,
47
+ use_token_type_ids=True,
48
+ use_labels=True,
49
+ vocab_size=99,
50
+ hidden_size=32,
51
+ num_hidden_layers=2,
52
+ num_attention_heads=4,
53
+ intermediate_size=37,
54
+ hidden_act="gelu",
55
+ hidden_dropout_prob=0.1,
56
+ attention_probs_dropout_prob=0.1,
57
+ max_position_embeddings=512,
58
+ type_vocab_size=16,
59
+ type_sequence_label_size=2,
60
+ initializer_range=0.02,
61
+ num_labels=3,
62
+ num_choices=4,
63
+ scope=None,
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_token_type_ids = use_token_type_ids
70
+ self.use_labels = use_labels
71
+ self.vocab_size = vocab_size
72
+ self.hidden_size = hidden_size
73
+ self.num_hidden_layers = num_hidden_layers
74
+ self.num_attention_heads = num_attention_heads
75
+ self.intermediate_size = intermediate_size
76
+ self.hidden_act = hidden_act
77
+ self.hidden_dropout_prob = hidden_dropout_prob
78
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
79
+ self.max_position_embeddings = max_position_embeddings
80
+ self.type_vocab_size = type_vocab_size
81
+ self.type_sequence_label_size = type_sequence_label_size
82
+ self.initializer_range = initializer_range
83
+ self.num_labels = num_labels
84
+ self.num_choices = num_choices
85
+ self.scope = scope
86
+ self.pad_token_id = self.vocab_size - 1
87
+
88
+ def prepare_config_and_inputs(self):
89
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
90
+
91
+ token_type_ids = None
92
+ if self.use_token_type_ids:
93
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
94
+
95
+ sequence_labels = None
96
+ token_labels = None
97
+ choice_labels = None
98
+ if self.use_labels:
99
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
100
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
101
+ choice_labels = ids_tensor([self.batch_size], self.num_choices)
102
+
103
+ config = OpenAIGPTConfig(
104
+ vocab_size=self.vocab_size,
105
+ n_embd=self.hidden_size,
106
+ n_layer=self.num_hidden_layers,
107
+ n_head=self.num_attention_heads,
108
+ # intermediate_size=self.intermediate_size,
109
+ # hidden_act=self.hidden_act,
110
+ # hidden_dropout_prob=self.hidden_dropout_prob,
111
+ # attention_probs_dropout_prob=self.attention_probs_dropout_prob,
112
+ n_positions=self.max_position_embeddings,
113
+ # type_vocab_size=self.type_vocab_size,
114
+ # initializer_range=self.initializer_range
115
+ pad_token_id=self.pad_token_id,
116
+ )
117
+
118
+ head_mask = ids_tensor([self.num_hidden_layers, self.num_attention_heads], 2)
119
+
120
+ return (
121
+ config,
122
+ input_ids,
123
+ head_mask,
124
+ token_type_ids,
125
+ sequence_labels,
126
+ token_labels,
127
+ choice_labels,
128
+ )
129
+
130
+ def create_and_check_openai_gpt_model(self, config, input_ids, head_mask, token_type_ids, *args):
131
+ model = OpenAIGPTModel(config=config)
132
+ model.to(torch_device)
133
+ model.eval()
134
+
135
+ result = model(input_ids, token_type_ids=token_type_ids, head_mask=head_mask)
136
+ result = model(input_ids, token_type_ids=token_type_ids)
137
+ result = model(input_ids)
138
+
139
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
140
+
141
+ def create_and_check_lm_head_model(self, config, input_ids, head_mask, token_type_ids, *args):
142
+ model = OpenAIGPTLMHeadModel(config)
143
+ model.to(torch_device)
144
+ model.eval()
145
+
146
+ result = model(input_ids, token_type_ids=token_type_ids, labels=input_ids)
147
+ self.parent.assertEqual(result.loss.shape, ())
148
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
149
+
150
+ def create_and_check_double_lm_head_model(self, config, input_ids, head_mask, token_type_ids, *args):
151
+ model = OpenAIGPTDoubleHeadsModel(config)
152
+ model.to(torch_device)
153
+ model.eval()
154
+
155
+ result = model(input_ids, token_type_ids=token_type_ids, labels=input_ids)
156
+ self.parent.assertEqual(result.loss.shape, ())
157
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
158
+
159
+ def create_and_check_openai_gpt_for_sequence_classification(
160
+ self, config, input_ids, head_mask, token_type_ids, *args
161
+ ):
162
+ config.num_labels = self.num_labels
163
+ model = OpenAIGPTForSequenceClassification(config)
164
+ model.to(torch_device)
165
+ model.eval()
166
+
167
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
168
+ result = model(input_ids, token_type_ids=token_type_ids, labels=sequence_labels)
169
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
170
+
171
+ def prepare_config_and_inputs_for_common(self):
172
+ config_and_inputs = self.prepare_config_and_inputs()
173
+ (
174
+ config,
175
+ input_ids,
176
+ head_mask,
177
+ token_type_ids,
178
+ sequence_labels,
179
+ token_labels,
180
+ choice_labels,
181
+ ) = config_and_inputs
182
+ inputs_dict = {
183
+ "input_ids": input_ids,
184
+ "token_type_ids": token_type_ids,
185
+ "head_mask": head_mask,
186
+ }
187
+
188
+ return config, inputs_dict
189
+
190
+
191
+ @require_torch
192
+ class OpenAIGPTModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
193
+ all_model_classes = (
194
+ (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
195
+ if is_torch_available()
196
+ else ()
197
+ )
198
+ pipeline_model_mapping = (
199
+ {
200
+ "feature-extraction": OpenAIGPTModel,
201
+ "text-classification": OpenAIGPTForSequenceClassification,
202
+ "text-generation": OpenAIGPTLMHeadModel,
203
+ "zero-shot": OpenAIGPTForSequenceClassification,
204
+ }
205
+ if is_torch_available()
206
+ else {}
207
+ )
208
+
209
+ # TODO: Fix the failed tests
210
+ def is_pipeline_test_to_skip(
211
+ self,
212
+ pipeline_test_case_name,
213
+ config_class,
214
+ model_architecture,
215
+ tokenizer_name,
216
+ image_processor_name,
217
+ feature_extractor_name,
218
+ processor_name,
219
+ ):
220
+ if pipeline_test_case_name == "ZeroShotClassificationPipelineTests":
221
+ # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
222
+ # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a
223
+ # tiny config could not be created.
224
+ return True
225
+
226
+ return False
227
+
228
+ # special case for DoubleHeads model
229
+ def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
230
+ inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
231
+
232
+ if return_labels:
233
+ if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
234
+ inputs_dict["labels"] = torch.zeros(
235
+ (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length),
236
+ dtype=torch.long,
237
+ device=torch_device,
238
+ )
239
+ inputs_dict["input_ids"] = inputs_dict["labels"]
240
+ inputs_dict["token_type_ids"] = inputs_dict["labels"]
241
+ inputs_dict["mc_token_ids"] = torch.zeros(
242
+ (self.model_tester.batch_size, self.model_tester.num_choices),
243
+ dtype=torch.long,
244
+ device=torch_device,
245
+ )
246
+ inputs_dict["mc_labels"] = torch.zeros(
247
+ self.model_tester.batch_size, dtype=torch.long, device=torch_device
248
+ )
249
+ return inputs_dict
250
+
251
+ def setUp(self):
252
+ self.model_tester = OpenAIGPTModelTester(self)
253
+ self.config_tester = ConfigTester(self, config_class=OpenAIGPTConfig, n_embd=37)
254
+
255
+ def test_config(self):
256
+ self.config_tester.run_common_tests()
257
+
258
+ def test_openai_gpt_model(self):
259
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
260
+ self.model_tester.create_and_check_openai_gpt_model(*config_and_inputs)
261
+
262
+ def test_openai_gpt_lm_head_model(self):
263
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
264
+ self.model_tester.create_and_check_lm_head_model(*config_and_inputs)
265
+
266
+ def test_openai_gpt_double_lm_head_model(self):
267
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
268
+ self.model_tester.create_and_check_double_lm_head_model(*config_and_inputs)
269
+
270
+ def test_openai_gpt_classification_model(self):
271
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
272
+ self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*config_and_inputs)
273
+
274
+ @slow
275
+ def test_model_from_pretrained(self):
276
+ model_name = "openai-community/openai-gpt"
277
+ model = OpenAIGPTModel.from_pretrained(model_name)
278
+ self.assertIsNotNone(model)
279
+
280
+
281
+ @require_torch
282
+ class OPENAIGPTModelLanguageGenerationTest(unittest.TestCase):
283
+ @slow
284
+ def test_lm_generate_openai_gpt(self):
285
+ model = OpenAIGPTLMHeadModel.from_pretrained("openai-community/openai-gpt")
286
+ model.to(torch_device)
287
+ input_ids = torch.tensor([[481, 4735, 544]], dtype=torch.long, device=torch_device) # the president is
288
+ expected_output_ids = [
289
+ 481,
290
+ 4735,
291
+ 544,
292
+ 246,
293
+ 963,
294
+ 870,
295
+ 762,
296
+ 239,
297
+ 244,
298
+ 40477,
299
+ 244,
300
+ 249,
301
+ 719,
302
+ 881,
303
+ 487,
304
+ 544,
305
+ 240,
306
+ 244,
307
+ 603,
308
+ 481,
309
+ ] # the president is a very good man. " \n " i\'m sure he is, " said the
310
+
311
+ output_ids = model.generate(input_ids, do_sample=False)
312
+ self.assertListEqual(output_ids[0].tolist(), expected_output_ids)
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/openai/test_modeling_tf_openai.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2020 The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+
17
+ from __future__ import annotations
18
+
19
+ import unittest
20
+
21
+ from transformers import OpenAIGPTConfig, is_tf_available
22
+ from transformers.testing_utils import require_tf, slow
23
+
24
+ from ...test_configuration_common import ConfigTester
25
+ from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
26
+ from ...test_pipeline_mixin import PipelineTesterMixin
27
+
28
+
29
+ if is_tf_available():
30
+ import tensorflow as tf
31
+
32
+ from transformers.models.openai.modeling_tf_openai import (
33
+ TFOpenAIGPTDoubleHeadsModel,
34
+ TFOpenAIGPTForSequenceClassification,
35
+ TFOpenAIGPTLMHeadModel,
36
+ TFOpenAIGPTModel,
37
+ )
38
+
39
+
40
+ class TFOpenAIGPTModelTester:
41
+ def __init__(
42
+ self,
43
+ parent,
44
+ ):
45
+ self.parent = parent
46
+ self.batch_size = 13
47
+ self.seq_length = 7
48
+ self.is_training = True
49
+ self.use_token_type_ids = True
50
+ self.use_input_mask = True
51
+ self.use_labels = True
52
+ self.use_mc_token_ids = True
53
+ self.vocab_size = 99
54
+ self.hidden_size = 32
55
+ self.num_hidden_layers = 2
56
+ self.num_attention_heads = 4
57
+ self.intermediate_size = 37
58
+ self.hidden_act = "gelu"
59
+ self.hidden_dropout_prob = 0.1
60
+ self.attention_probs_dropout_prob = 0.1
61
+ self.max_position_embeddings = 512
62
+ self.type_vocab_size = 16
63
+ self.type_sequence_label_size = 2
64
+ self.initializer_range = 0.02
65
+ self.num_labels = 3
66
+ self.num_choices = 4
67
+ self.scope = None
68
+ self.pad_token_id = self.vocab_size - 1
69
+
70
+ def prepare_config_and_inputs(self):
71
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
72
+
73
+ input_mask = None
74
+ if self.use_input_mask:
75
+ input_mask = random_attention_mask([self.batch_size, self.seq_length])
76
+
77
+ token_type_ids = None
78
+ if self.use_token_type_ids:
79
+ token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
80
+
81
+ mc_token_ids = None
82
+ if self.use_mc_token_ids:
83
+ mc_token_ids = ids_tensor([self.batch_size, self.num_choices], self.seq_length)
84
+
85
+ sequence_labels = None
86
+ token_labels = None
87
+ choice_labels = None
88
+ if self.use_labels:
89
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
90
+ token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
91
+ choice_labels = ids_tensor([self.batch_size], self.num_choices)
92
+
93
+ config = OpenAIGPTConfig(
94
+ vocab_size=self.vocab_size,
95
+ n_embd=self.hidden_size,
96
+ n_layer=self.num_hidden_layers,
97
+ n_head=self.num_attention_heads,
98
+ # intermediate_size=self.intermediate_size,
99
+ # hidden_act=self.hidden_act,
100
+ # hidden_dropout_prob=self.hidden_dropout_prob,
101
+ # attention_probs_dropout_prob=self.attention_probs_dropout_prob,
102
+ n_positions=self.max_position_embeddings,
103
+ # type_vocab_size=self.type_vocab_size,
104
+ # initializer_range=self.initializer_range,
105
+ pad_token_id=self.pad_token_id,
106
+ )
107
+
108
+ head_mask = ids_tensor([self.num_hidden_layers, self.num_attention_heads], 2)
109
+
110
+ return (
111
+ config,
112
+ input_ids,
113
+ input_mask,
114
+ head_mask,
115
+ token_type_ids,
116
+ mc_token_ids,
117
+ sequence_labels,
118
+ token_labels,
119
+ choice_labels,
120
+ )
121
+
122
+ def create_and_check_openai_gpt_model(self, config, input_ids, input_mask, head_mask, token_type_ids, *args):
123
+ model = TFOpenAIGPTModel(config=config)
124
+ inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
125
+ result = model(inputs)
126
+
127
+ inputs = [input_ids, input_mask]
128
+ result = model(inputs)
129
+
130
+ result = model(input_ids)
131
+
132
+ self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
133
+
134
+ def create_and_check_openai_gpt_lm_head(self, config, input_ids, input_mask, head_mask, token_type_ids, *args):
135
+ model = TFOpenAIGPTLMHeadModel(config=config)
136
+ inputs = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
137
+ result = model(inputs)
138
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
139
+
140
+ def create_and_check_openai_gpt_double_head(
141
+ self, config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, *args
142
+ ):
143
+ model = TFOpenAIGPTDoubleHeadsModel(config=config)
144
+
145
+ multiple_choice_inputs_ids = tf.tile(tf.expand_dims(input_ids, 1), (1, self.num_choices, 1))
146
+ multiple_choice_input_mask = tf.tile(tf.expand_dims(input_mask, 1), (1, self.num_choices, 1))
147
+ multiple_choice_token_type_ids = tf.tile(tf.expand_dims(token_type_ids, 1), (1, self.num_choices, 1))
148
+
149
+ inputs = {
150
+ "input_ids": multiple_choice_inputs_ids,
151
+ "mc_token_ids": mc_token_ids,
152
+ "attention_mask": multiple_choice_input_mask,
153
+ "token_type_ids": multiple_choice_token_type_ids,
154
+ }
155
+ result = model(inputs)
156
+ self.parent.assertEqual(
157
+ result.logits.shape, (self.batch_size, self.num_choices, self.seq_length, self.vocab_size)
158
+ )
159
+ self.parent.assertEqual(result.mc_logits.shape, (self.batch_size, self.num_choices))
160
+
161
+ def create_and_check_openai_gpt_for_sequence_classification(
162
+ self, config, input_ids, input_mask, head_mask, token_type_ids, *args
163
+ ):
164
+ config.num_labels = self.num_labels
165
+ sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
166
+ inputs = {
167
+ "input_ids": input_ids,
168
+ "attention_mask": input_mask,
169
+ "token_type_ids": token_type_ids,
170
+ "labels": sequence_labels,
171
+ }
172
+ model = TFOpenAIGPTForSequenceClassification(config)
173
+ result = model(inputs)
174
+ self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
175
+
176
+ def prepare_config_and_inputs_for_common(self):
177
+ config_and_inputs = self.prepare_config_and_inputs()
178
+
179
+ (
180
+ config,
181
+ input_ids,
182
+ input_mask,
183
+ head_mask,
184
+ token_type_ids,
185
+ mc_token_ids,
186
+ sequence_labels,
187
+ token_labels,
188
+ choice_labels,
189
+ ) = config_and_inputs
190
+
191
+ inputs_dict = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
192
+ return config, inputs_dict
193
+
194
+
195
+ @require_tf
196
+ class TFOpenAIGPTModelTest(TFModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
197
+ all_model_classes = (
198
+ (TFOpenAIGPTModel, TFOpenAIGPTLMHeadModel, TFOpenAIGPTDoubleHeadsModel, TFOpenAIGPTForSequenceClassification)
199
+ if is_tf_available()
200
+ else ()
201
+ )
202
+ all_generative_model_classes = (
203
+ (TFOpenAIGPTLMHeadModel,) if is_tf_available() else ()
204
+ ) # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
205
+ pipeline_model_mapping = (
206
+ {
207
+ "feature-extraction": TFOpenAIGPTModel,
208
+ "text-classification": TFOpenAIGPTForSequenceClassification,
209
+ "text-generation": TFOpenAIGPTLMHeadModel,
210
+ "zero-shot": TFOpenAIGPTForSequenceClassification,
211
+ }
212
+ if is_tf_available()
213
+ else {}
214
+ )
215
+ test_head_masking = False
216
+ test_onnx = False
217
+
218
+ # TODO: Fix the failed tests
219
+ def is_pipeline_test_to_skip(
220
+ self,
221
+ pipeline_test_case_name,
222
+ config_class,
223
+ model_architecture,
224
+ tokenizer_name,
225
+ image_processor_name,
226
+ feature_extractor_name,
227
+ processor_name,
228
+ ):
229
+ if pipeline_test_case_name == "ZeroShotClassificationPipelineTests":
230
+ # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
231
+ # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a
232
+ # tiny config could not be created.
233
+ return True
234
+
235
+ return False
236
+
237
+ def setUp(self):
238
+ self.model_tester = TFOpenAIGPTModelTester(self)
239
+ self.config_tester = ConfigTester(self, config_class=OpenAIGPTConfig, n_embd=37)
240
+
241
+ def test_config(self):
242
+ self.config_tester.run_common_tests()
243
+
244
+ def test_openai_gpt_model(self):
245
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
246
+ self.model_tester.create_and_check_openai_gpt_model(*config_and_inputs)
247
+
248
+ def test_openai_gpt_lm_head(self):
249
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
250
+ self.model_tester.create_and_check_openai_gpt_lm_head(*config_and_inputs)
251
+
252
+ def test_openai_gpt_double_head(self):
253
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
254
+ self.model_tester.create_and_check_openai_gpt_double_head(*config_and_inputs)
255
+
256
+ def test_openai_gpt_sequence_classification_model(self):
257
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
258
+ self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*config_and_inputs)
259
+
260
+ @slow
261
+ def test_model_from_pretrained(self):
262
+ model_name = "openai-community/openai-gpt"
263
+ model = TFOpenAIGPTModel.from_pretrained(model_name)
264
+ self.assertIsNotNone(model)
265
+
266
+
267
+ @require_tf
268
+ class TFOPENAIGPTModelLanguageGenerationTest(unittest.TestCase):
269
+ @slow
270
+ def test_lm_generate_openai_gpt(self):
271
+ model = TFOpenAIGPTLMHeadModel.from_pretrained("openai-community/openai-gpt")
272
+ input_ids = tf.convert_to_tensor([[481, 4735, 544]], dtype=tf.int32) # the president is
273
+ expected_output_ids = [
274
+ 481,
275
+ 4735,
276
+ 544,
277
+ 246,
278
+ 963,
279
+ 870,
280
+ 762,
281
+ 239,
282
+ 244,
283
+ 40477,
284
+ 244,
285
+ 249,
286
+ 719,
287
+ 881,
288
+ 487,
289
+ 544,
290
+ 240,
291
+ 244,
292
+ 603,
293
+ 481,
294
+ ] # the president is a very good man. " \n " i\'m sure he is, " said the
295
+
296
+ output_ids = model.generate(input_ids, do_sample=False)
297
+ self.assertListEqual(output_ids[0].numpy().tolist(), expected_output_ids)
tasks/tasksmith-e0f68dd4420c/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-e0f68dd4420c/tests/source/tests/models/opt/__init__.py ADDED
File without changes
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/opt/test_modeling_flax_opt.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor
23
+
24
+
25
+ if is_flax_available():
26
+ import os
27
+
28
+ # The slow tests are often failing with OOM error on GPU
29
+ # This makes JAX allocate exactly what is needed on demand, and deallocate memory that is no longer needed
30
+ # but will be slower as stated here https://jax.readthedocs.io/en/latest/gpu_memory_allocation.html
31
+ os.environ["XLA_PYTHON_CLIENT_ALLOCATOR"] = "platform"
32
+
33
+ import jax
34
+ import jax.numpy as jnp
35
+
36
+ from transformers import FlaxOPTForCausalLM, FlaxOPTModel, GPT2Tokenizer
37
+
38
+
39
+ def prepare_opt_inputs_dict(config, input_ids, attention_mask=None, head_mask=None):
40
+ if attention_mask is None:
41
+ attention_mask = np.where(input_ids != config.pad_token_id, 1, 0)
42
+ return {
43
+ "input_ids": input_ids,
44
+ "attention_mask": attention_mask,
45
+ }
46
+
47
+
48
+ @require_flax
49
+ class FlaxOPTModelTester:
50
+ def __init__(
51
+ self,
52
+ parent,
53
+ batch_size=13,
54
+ seq_length=7,
55
+ is_training=True,
56
+ use_labels=False,
57
+ vocab_size=99,
58
+ hidden_size=16,
59
+ num_hidden_layers=2,
60
+ num_attention_heads=4,
61
+ intermediate_size=4,
62
+ hidden_act="gelu",
63
+ hidden_dropout_prob=0.1,
64
+ attention_probs_dropout_prob=0.1,
65
+ max_position_embeddings=20,
66
+ eos_token_id=2,
67
+ pad_token_id=1,
68
+ bos_token_id=0,
69
+ embed_dim=16,
70
+ word_embed_proj_dim=16,
71
+ initializer_range=0.02,
72
+ attn_implemetation="eager",
73
+ ):
74
+ self.parent = parent
75
+ self.batch_size = batch_size
76
+ self.seq_length = seq_length
77
+ self.is_training = is_training
78
+ self.use_labels = use_labels
79
+ self.vocab_size = vocab_size
80
+ self.hidden_size = hidden_size
81
+ self.num_hidden_layers = num_hidden_layers
82
+ self.num_attention_heads = num_attention_heads
83
+ self.intermediate_size = intermediate_size
84
+ self.hidden_act = hidden_act
85
+ self.hidden_dropout_prob = hidden_dropout_prob
86
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
87
+ self.max_position_embeddings = max_position_embeddings
88
+ self.eos_token_id = eos_token_id
89
+ self.pad_token_id = pad_token_id
90
+ self.bos_token_id = bos_token_id
91
+ self.embed_dim = embed_dim
92
+ self.word_embed_proj_dim = word_embed_proj_dim
93
+ self.initializer_range = initializer_range
94
+ self.is_encoder_decoder = False
95
+ self.attn_implementation = attn_implemetation
96
+
97
+ def prepare_config_and_inputs(self):
98
+ input_ids = np.clip(ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size), 3, self.vocab_size)
99
+ input_ids = np.concatenate((input_ids, 2 * np.ones((self.batch_size, 1), dtype=np.int64)), -1)
100
+
101
+ config = OPTConfig(
102
+ vocab_size=self.vocab_size,
103
+ hidden_size=self.hidden_size,
104
+ num_hidden_layers=self.num_hidden_layers,
105
+ num_attention_heads=self.num_attention_heads,
106
+ ffn_dim=self.intermediate_size,
107
+ dropout=self.hidden_dropout_prob,
108
+ attention_dropout=self.attention_probs_dropout_prob,
109
+ max_position_embeddings=self.max_position_embeddings,
110
+ eos_token_id=self.eos_token_id,
111
+ bos_token_id=self.bos_token_id,
112
+ pad_token_id=self.pad_token_id,
113
+ embed_dim=self.embed_dim,
114
+ is_encoder_decoder=False,
115
+ word_embed_proj_dim=self.word_embed_proj_dim,
116
+ initializer_range=self.initializer_range,
117
+ use_cache=False,
118
+ attn_implementation=self.attn_implementation,
119
+ )
120
+ inputs_dict = prepare_opt_inputs_dict(config, input_ids)
121
+ return config, inputs_dict
122
+
123
+ def prepare_config_and_inputs_for_common(self):
124
+ config, inputs_dict = self.prepare_config_and_inputs()
125
+ return config, inputs_dict
126
+
127
+ def check_use_cache_forward(self, model_class_name, config, inputs_dict):
128
+ max_length = 20
129
+ model = model_class_name(config)
130
+
131
+ input_ids = inputs_dict["input_ids"]
132
+ attention_mask = inputs_dict["attention_mask"]
133
+
134
+ past_key_values = model.init_cache(input_ids.shape[0], max_length)
135
+ attention_mask = jnp.ones((input_ids.shape[0], max_length), dtype="i4")
136
+
137
+ position_ids = jnp.broadcast_to(
138
+ jnp.arange(input_ids.shape[-1] - 1)[None, :],
139
+ (input_ids.shape[0], input_ids.shape[-1] - 1),
140
+ )
141
+ outputs_cache = model(
142
+ input_ids[:, :-1],
143
+ attention_mask=attention_mask,
144
+ past_key_values=past_key_values,
145
+ position_ids=position_ids,
146
+ )
147
+
148
+ position_ids = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]], dtype="i4")
149
+ outputs_cache_next = model(
150
+ input_ids[:, -1:],
151
+ attention_mask=attention_mask,
152
+ past_key_values=outputs_cache.past_key_values,
153
+ position_ids=position_ids,
154
+ )
155
+
156
+ outputs = model(input_ids)
157
+
158
+ diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
159
+ self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}")
160
+
161
+ def check_use_cache_forward_with_attn_mask(self, model_class_name, config, inputs_dict):
162
+ max_length = 20
163
+ model = model_class_name(config)
164
+
165
+ input_ids, attention_mask = (
166
+ inputs_dict["input_ids"],
167
+ inputs_dict["attention_mask"],
168
+ )
169
+
170
+ attention_mask_cache = jnp.concatenate(
171
+ [
172
+ attention_mask,
173
+ jnp.zeros((attention_mask.shape[0], max_length - attention_mask.shape[1])),
174
+ ],
175
+ axis=-1,
176
+ )
177
+
178
+ past_key_values = model.init_cache(input_ids.shape[0], max_length)
179
+ position_ids = jnp.broadcast_to(
180
+ jnp.arange(input_ids.shape[-1] - 1)[None, :],
181
+ (input_ids.shape[0], input_ids.shape[-1] - 1),
182
+ )
183
+
184
+ outputs_cache = model(
185
+ input_ids[:, :-1],
186
+ attention_mask=attention_mask_cache,
187
+ past_key_values=past_key_values,
188
+ position_ids=position_ids,
189
+ )
190
+ position_ids = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]], dtype="i4")
191
+ outputs_cache_next = model(
192
+ input_ids[:, -1:],
193
+ past_key_values=outputs_cache.past_key_values,
194
+ attention_mask=attention_mask_cache,
195
+ position_ids=position_ids,
196
+ )
197
+
198
+ outputs = model(input_ids, attention_mask=attention_mask)
199
+
200
+ diff = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5])))
201
+ self.parent.assertTrue(diff < 1e-3, msg=f"Max diff is {diff}")
202
+
203
+
204
+ @require_flax
205
+ class FlaxOPTModelTest(FlaxModelTesterMixin, unittest.TestCase):
206
+ all_model_classes = (FlaxOPTModel, FlaxOPTForCausalLM) if is_flax_available() else ()
207
+
208
+ def setUp(self):
209
+ self.model_tester = FlaxOPTModelTester(self)
210
+
211
+ def test_use_cache_forward(self):
212
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
213
+ for model_class in self.all_model_classes:
214
+ self.model_tester.check_use_cache_forward(model_class, config, inputs_dict)
215
+
216
+ def test_use_cache_forward_with_attn_mask(self):
217
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
218
+ for model_class in self.all_model_classes:
219
+ self.model_tester.check_use_cache_forward_with_attn_mask(model_class, config, inputs_dict)
220
+
221
+ @slow
222
+ def test_model_from_pretrained(self):
223
+ for model_class_name in self.all_model_classes:
224
+ model = model_class_name.from_pretrained("facebook/opt-125m")
225
+ input_ids = np.ones((1, 1)) * model.config.eos_token_id
226
+ outputs = model(input_ids)
227
+ self.assertIsNotNone(outputs)
228
+
229
+
230
+ @require_sentencepiece
231
+ @require_flax
232
+ class FlaxOPTModelIntegrationTests(unittest.TestCase):
233
+ @slow
234
+ def test_inference_no_head(self):
235
+ model = FlaxOPTModel.from_pretrained("facebook/opt-350m")
236
+ input_ids = jnp.array([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
237
+ output = model(input_ids=input_ids).last_hidden_state
238
+ expected_shape = (1, 11, 512)
239
+ self.assertEqual(output.shape, expected_shape)
240
+ expected_slice = jnp.array(
241
+ [[-0.2867, -1.9256, -0.3062], [-1.2711, -0.1337, -0.1897], [0.4109, 0.1187, -1.3142]]
242
+ )
243
+ self.assertTrue(jnp.allclose(output[:, :3, :3], expected_slice, atol=4e-2))
244
+
245
+
246
+ @require_flax
247
+ @slow
248
+ class FlaxOPTEmbeddingsTest(unittest.TestCase):
249
+ def setUp(self):
250
+ super().setUp()
251
+ self.path_model = "facebook/opt-350m"
252
+
253
+ def test_logits(self):
254
+ model = FlaxOPTForCausalLM.from_pretrained(self.path_model)
255
+ tokenizer = GPT2Tokenizer.from_pretrained(self.path_model)
256
+
257
+ prompts = [
258
+ "Today is a beautiful day and I want to",
259
+ "In the city of",
260
+ "Paris is the capital of France and",
261
+ "Computers and mobile phones have taken",
262
+ ]
263
+ # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False
264
+ inputs = tokenizer(prompts, return_tensors="jax", padding=True, add_special_tokens=False)
265
+ logits = model(inputs.input_ids, attention_mask=inputs.attention_mask)[0].mean(axis=-1)
266
+ logits_meta = jnp.array(
267
+ [
268
+ [1.3851, -13.8923, -10.5229, -10.7533, -0.2309, -10.2384, -0.5365, -9.0947, -5.1670],
269
+ [-4.7073, -10.6276, -3.9415, -21.5242, -0.2822, -0.2822, -0.2822, -0.2822, -0.2822],
270
+ [0.6247, -3.4229, -8.9179, -1.4297, -14.1650, 1.4146, -9.0218, -0.2703, -0.2703],
271
+ [6.4783, -1.9913, -10.7926, -2.3336, 1.5092, -0.9974, -6.8213, 1.3477, 1.3477],
272
+ ]
273
+ )
274
+ self.assertTrue(jnp.allclose(logits, logits_meta, atol=4e-2))
275
+
276
+ model = jax.jit(model)
277
+ logits = model(inputs.input_ids, attention_mask=inputs.attention_mask)[0].mean(axis=-1)
278
+ self.assertTrue(jnp.allclose(logits, logits_meta, atol=4e-2))
279
+
280
+
281
+ @require_flax
282
+ @slow
283
+ class FlaxOPTGenerationTest(unittest.TestCase):
284
+ @property
285
+ def prompts(self):
286
+ return [
287
+ "Today is a beautiful day and I want",
288
+ "In the city of",
289
+ "Paris is the capital of France and",
290
+ "Computers and mobile phones have taken",
291
+ ]
292
+
293
+ def test_generation_pre_attn_layer_norm(self):
294
+ model_id = "facebook/opt-125m"
295
+
296
+ EXPECTED_OUTPUTS = [
297
+ "Today is a beautiful day and I want to",
298
+ "In the city of New York, the city",
299
+ "Paris is the capital of France and the capital",
300
+ "Computers and mobile phones have taken over the",
301
+ ]
302
+
303
+ predicted_outputs = []
304
+
305
+ model = FlaxOPTForCausalLM.from_pretrained(model_id)
306
+ tokenizer = GPT2Tokenizer.from_pretrained(model_id)
307
+
308
+ for prompt in self.prompts:
309
+ input_ids = tokenizer(prompt, return_tensors="jax").input_ids
310
+
311
+ generated_ids = model.generate(input_ids, max_length=10)
312
+ generated_ids = generated_ids[0]
313
+
314
+ generated_string = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
315
+ predicted_outputs += generated_string
316
+
317
+ self.assertListEqual(predicted_outputs, EXPECTED_OUTPUTS)
318
+
319
+ def test_generation_post_attn_layer_norm(self):
320
+ model_id = "facebook/opt-350m"
321
+
322
+ EXPECTED_OUTPUTS = [
323
+ "Today is a beautiful day and I want to",
324
+ "In the city of San Francisco, the city",
325
+ "Paris is the capital of France and the capital",
326
+ "Computers and mobile phones have taken over the",
327
+ ]
328
+
329
+ predicted_outputs = []
330
+ model = FlaxOPTForCausalLM.from_pretrained(model_id)
331
+ tokenizer = GPT2Tokenizer.from_pretrained(model_id)
332
+
333
+ for prompt in self.prompts:
334
+ input_ids = tokenizer(prompt, return_tensors="jax").input_ids
335
+
336
+ generated_ids = model.generate(input_ids, max_length=10)
337
+ generated_ids = generated_ids[0]
338
+
339
+ generated_string = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
340
+ predicted_outputs += generated_string
341
+
342
+ self.assertListEqual(predicted_outputs, EXPECTED_OUTPUTS)
343
+
344
+ def test_jitted_batch_generation(self):
345
+ model_id = "facebook/opt-125m"
346
+ EXPECTED_OUTPUTS = [
347
+ "Today is a beautiful day and I want to thank",
348
+ "In the city of Rome Canaver Canaver Canaver Canaver",
349
+ ]
350
+ model = FlaxOPTForCausalLM.from_pretrained(model_id)
351
+ tokenizer = GPT2Tokenizer.from_pretrained(model_id)
352
+ inputs = tokenizer(
353
+ [
354
+ "Today is a beautiful day and I want to",
355
+ "In the city of",
356
+ ],
357
+ return_tensors="jax",
358
+ padding=True,
359
+ )
360
+
361
+ jit_generate = jax.jit(model.generate)
362
+
363
+ output_sequences = jit_generate(inputs["input_ids"], attention_mask=inputs["attention_mask"]).sequences
364
+
365
+ output_string = tokenizer.batch_decode(output_sequences, skip_special_tokens=True)
366
+
367
+ self.assertIsNotNone(output_string, EXPECTED_OUTPUTS)
368
+
369
+ def test_batch_generation(self):
370
+ model_id = "facebook/opt-350m"
371
+
372
+ tokenizer = GPT2Tokenizer.from_pretrained(model_id)
373
+ model = FlaxOPTForCausalLM.from_pretrained(model_id)
374
+
375
+ tokenizer.padding_side = "left"
376
+
377
+ # use different length sentences to test batching
378
+ sentences = [
379
+ "Hello, my dog is a little",
380
+ "Today, I",
381
+ ]
382
+
383
+ inputs = tokenizer(sentences, return_tensors="jax", padding=True)
384
+ input_ids = inputs["input_ids"]
385
+
386
+ outputs = model.generate(input_ids=input_ids, attention_mask=inputs["attention_mask"], trace=False)
387
+
388
+ inputs_non_padded = tokenizer(sentences[0], return_tensors="jax").input_ids
389
+ output_non_padded = model.generate(input_ids=inputs_non_padded)
390
+
391
+ num_paddings = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].sum()
392
+ inputs_padded = tokenizer(sentences[1], return_tensors="jax").input_ids
393
+ output_padded = model.generate(input_ids=inputs_padded, max_length=model.config.max_length - num_paddings)
394
+
395
+ batch_out_sentence = tokenizer.batch_decode(outputs[0], skip_special_tokens=True)
396
+ non_padded_sentence = tokenizer.decode(output_non_padded[0][0], skip_special_tokens=True)
397
+ padded_sentence = tokenizer.decode(output_padded[0][0], skip_special_tokens=True)
398
+
399
+ expected_output_sentence = [
400
+ "Hello, my dog is a little bit of a dork.\nI'm a little bit",
401
+ "Today, I was in the middle of a conversation with a friend about the",
402
+ ]
403
+ self.assertListEqual(expected_output_sentence, batch_out_sentence)
404
+ self.assertListEqual(batch_out_sentence, [non_padded_sentence, padded_sentence])
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/opt/test_modeling_opt.py ADDED
@@ -0,0 +1,580 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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=50,
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
+ ):
93
+ self.parent = parent
94
+ self.batch_size = batch_size
95
+ self.seq_length = seq_length
96
+ self.is_training = is_training
97
+ self.use_labels = use_labels
98
+ self.vocab_size = vocab_size
99
+ self.hidden_size = hidden_size
100
+ self.num_hidden_layers = num_hidden_layers
101
+ self.num_attention_heads = num_attention_heads
102
+ self.intermediate_size = intermediate_size
103
+ self.hidden_act = hidden_act
104
+ self.hidden_dropout_prob = hidden_dropout_prob
105
+ self.attention_probs_dropout_prob = attention_probs_dropout_prob
106
+ self.max_position_embeddings = max_position_embeddings
107
+ self.eos_token_id = eos_token_id
108
+ self.pad_token_id = pad_token_id
109
+ self.bos_token_id = bos_token_id
110
+ self.embed_dim = embed_dim
111
+ self.num_labels = num_labels
112
+ self.type_sequence_label_size = type_sequence_label_size
113
+ self.word_embed_proj_dim = word_embed_proj_dim
114
+ self.is_encoder_decoder = False
115
+
116
+ def prepare_config_and_inputs(self):
117
+ input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size).clamp(
118
+ 3,
119
+ )
120
+ input_ids[:, -1] = self.eos_token_id # Eos Token
121
+
122
+ decoder_input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
123
+
124
+ config = self.get_config()
125
+ inputs_dict = prepare_opt_inputs_dict(config, input_ids, decoder_input_ids)
126
+ return config, inputs_dict
127
+
128
+ def get_config(self):
129
+ return OPTConfig(
130
+ vocab_size=self.vocab_size,
131
+ hidden_size=self.hidden_size,
132
+ num_hidden_layers=self.num_hidden_layers,
133
+ num_attention_heads=self.num_attention_heads,
134
+ ffn_dim=self.intermediate_size,
135
+ dropout=self.hidden_dropout_prob,
136
+ attention_dropout=self.attention_probs_dropout_prob,
137
+ max_position_embeddings=self.max_position_embeddings,
138
+ eos_token_id=self.eos_token_id,
139
+ bos_token_id=self.bos_token_id,
140
+ pad_token_id=self.pad_token_id,
141
+ embed_dim=self.embed_dim,
142
+ is_encoder_decoder=False,
143
+ word_embed_proj_dim=self.word_embed_proj_dim,
144
+ )
145
+
146
+ def get_pipeline_config(self):
147
+ config = self.get_config()
148
+ config.max_position_embeddings = 100
149
+ return config
150
+
151
+ def prepare_config_and_inputs_for_common(self):
152
+ config, inputs_dict = self.prepare_config_and_inputs()
153
+ return config, inputs_dict
154
+
155
+ def create_and_check_decoder_model_past_large_inputs(self, config, inputs_dict):
156
+ model = OPTModel(config=config).to(torch_device).eval()
157
+
158
+ input_ids = inputs_dict["input_ids"]
159
+ attention_mask = inputs_dict["attention_mask"]
160
+ head_mask = inputs_dict["head_mask"]
161
+
162
+ # first forward pass
163
+ outputs = model(input_ids, attention_mask=attention_mask, head_mask=head_mask, use_cache=True)
164
+
165
+ output, past_key_values = outputs.to_tuple()
166
+
167
+ # create hypothetical multiple next token and extent to next_input_ids
168
+ next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
169
+ next_attn_mask = ids_tensor((self.batch_size, 3), 2)
170
+
171
+ # append to next input_ids and
172
+ next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
173
+ next_attention_mask = torch.cat([attention_mask, next_attn_mask], dim=-1)
174
+
175
+ output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"]
176
+ output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[
177
+ "last_hidden_state"
178
+ ]
179
+
180
+ # select random slice
181
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
182
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
183
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
184
+
185
+ self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
186
+
187
+ # test that outputs are equal for slice
188
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
189
+
190
+ # test no attention_mask works
191
+ outputs = model(input_ids, attention_mask=attention_mask, head_mask=head_mask, use_cache=True)
192
+ _, past_key_values = outputs.to_tuple()
193
+ output_from_no_past = model(next_input_ids)["last_hidden_state"]
194
+
195
+ output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"]
196
+
197
+ random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
198
+ output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
199
+ output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
200
+ # test that outputs are equal for slice
201
+ self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
202
+
203
+
204
+ @require_torch
205
+ class OPTModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
206
+ all_model_classes = (
207
+ (OPTModel, OPTForCausalLM, OPTForSequenceClassification, OPTForQuestionAnswering)
208
+ if is_torch_available()
209
+ else ()
210
+ )
211
+ pipeline_model_mapping = (
212
+ {
213
+ "feature-extraction": OPTModel,
214
+ "question-answering": OPTForQuestionAnswering,
215
+ "text-classification": OPTForSequenceClassification,
216
+ "text-generation": OPTForCausalLM,
217
+ "zero-shot": OPTForSequenceClassification,
218
+ }
219
+ if is_torch_available()
220
+ else {}
221
+ )
222
+ is_encoder_decoder = False
223
+ fx_compatible = True
224
+ test_pruning = False
225
+ test_missing_keys = False
226
+
227
+ # TODO: Fix the failed tests
228
+ def is_pipeline_test_to_skip(
229
+ self,
230
+ pipeline_test_case_name,
231
+ config_class,
232
+ model_architecture,
233
+ tokenizer_name,
234
+ image_processor_name,
235
+ feature_extractor_name,
236
+ processor_name,
237
+ ):
238
+ if (
239
+ pipeline_test_case_name == "QAPipelineTests"
240
+ and tokenizer_name is not None
241
+ and not tokenizer_name.endswith("Fast")
242
+ ):
243
+ # `QAPipelineTests` fails for a few models when the slower tokenizer are used.
244
+ # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
245
+ # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
246
+ return True
247
+
248
+ return False
249
+
250
+ def setUp(self):
251
+ self.model_tester = OPTModelTester(self)
252
+ self.config_tester = ConfigTester(self, config_class=OPTConfig)
253
+
254
+ def test_config(self):
255
+ self.config_tester.run_common_tests()
256
+
257
+ def test_save_load_strict(self):
258
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs()
259
+ for model_class in self.all_model_classes:
260
+ model = model_class(config)
261
+
262
+ with tempfile.TemporaryDirectory() as tmpdirname:
263
+ model.save_pretrained(tmpdirname)
264
+ model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True)
265
+ self.assertEqual(info["missing_keys"], [])
266
+
267
+ def test_decoder_model_past_with_large_inputs(self):
268
+ config_and_inputs = self.model_tester.prepare_config_and_inputs()
269
+ self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
270
+
271
+ def test_inputs_embeds(self):
272
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
273
+
274
+ for model_class in (OPTModel,):
275
+ model = model_class(config)
276
+ model.to(torch_device)
277
+ model.eval()
278
+
279
+ inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class))
280
+
281
+ if not self.is_encoder_decoder:
282
+ input_ids = inputs["input_ids"]
283
+ del inputs["input_ids"]
284
+ else:
285
+ encoder_input_ids = inputs["input_ids"]
286
+ decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids)
287
+ del inputs["input_ids"]
288
+ inputs.pop("decoder_input_ids", None)
289
+
290
+ wte = model.get_input_embeddings()
291
+ if not self.is_encoder_decoder:
292
+ inputs["inputs_embeds"] = wte(input_ids)
293
+ else:
294
+ inputs["inputs_embeds"] = wte(encoder_input_ids)
295
+ inputs["decoder_inputs_embeds"] = wte(decoder_input_ids)
296
+
297
+ with torch.no_grad():
298
+ model(**inputs)[0]
299
+
300
+ @require_torch_fp16
301
+ def test_generate_fp16(self):
302
+ config, input_dict = self.model_tester.prepare_config_and_inputs()
303
+ input_ids = input_dict["input_ids"]
304
+ attention_mask = input_ids.ne(1).to(torch_device)
305
+ model = OPTForCausalLM(config).eval().to(torch_device)
306
+ model.half()
307
+ model.generate(input_ids, attention_mask=attention_mask)
308
+ model.generate(num_beams=4, do_sample=True, early_stopping=False, num_return_sequences=3)
309
+
310
+ def test_opt_sequence_classification_model(self):
311
+ config, input_dict = self.model_tester.prepare_config_and_inputs()
312
+ config.num_labels = 3
313
+ input_ids = input_dict["input_ids"]
314
+ attention_mask = input_ids.ne(1).to(torch_device)
315
+ sequence_labels = ids_tensor([self.model_tester.batch_size], self.model_tester.type_sequence_label_size)
316
+ model = OPTForSequenceClassification(config)
317
+ model.to(torch_device)
318
+ model.eval()
319
+ result = model(input_ids, attention_mask=attention_mask, labels=sequence_labels)
320
+ self.assertEqual(result.logits.shape, (self.model_tester.batch_size, self.model_tester.num_labels))
321
+
322
+ def test_opt_sequence_classification_model_for_multi_label(self):
323
+ config, input_dict = self.model_tester.prepare_config_and_inputs()
324
+ config.num_labels = 3
325
+ config.problem_type = "multi_label_classification"
326
+ input_ids = input_dict["input_ids"]
327
+ attention_mask = input_ids.ne(1).to(torch_device)
328
+ sequence_labels = ids_tensor(
329
+ [self.model_tester.batch_size, config.num_labels], self.model_tester.type_sequence_label_size
330
+ ).to(torch.float)
331
+ model = OPTForSequenceClassification(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
+ @unittest.skip(reason="Does not work on the tiny model as we keep hitting edge cases.")
338
+ def test_model_parallelism(self):
339
+ super().test_model_parallelism()
340
+
341
+
342
+ def assert_tensors_close(a, b, atol=1e-12, prefix=""):
343
+ """If tensors have different shapes, different values or a and b are not both tensors, raise a nice Assertion error."""
344
+ if a is None and b is None:
345
+ return True
346
+ try:
347
+ if torch.allclose(a, b, atol=atol):
348
+ return True
349
+ raise
350
+ except Exception:
351
+ pct_different = (torch.gt((a - b).abs(), atol)).float().mean().item()
352
+ if a.numel() > 100:
353
+ msg = f"tensor values are {pct_different:.1%} percent different."
354
+ else:
355
+ msg = f"{a} != {b}"
356
+ if prefix:
357
+ msg = prefix + ": " + msg
358
+ raise AssertionError(msg)
359
+
360
+
361
+ def _long_tensor(tok_lst):
362
+ return torch.tensor(tok_lst, dtype=torch.long, device=torch_device)
363
+
364
+
365
+ @require_torch
366
+ class OPTModelIntegrationTests(unittest.TestCase):
367
+ @slow
368
+ def test_inference_no_head(self):
369
+ model = OPTModel.from_pretrained("facebook/opt-350m").to(torch_device)
370
+ input_ids = _long_tensor([[0, 31414, 232, 328, 740, 1140, 12695, 69, 46078, 1588, 2]])
371
+
372
+ with torch.no_grad():
373
+ output = model(input_ids=input_ids).last_hidden_state
374
+
375
+ expected_shape = torch.Size((1, 11, 512))
376
+ self.assertEqual(output.shape, expected_shape)
377
+ # expected value works for CPU, as well as GPU (with TF32 disabled)
378
+ expected_slice = torch.tensor(
379
+ [
380
+ [-0.28726277, -1.9241608, -0.3058734],
381
+ [-1.2737825, -0.13332152, -0.18766522],
382
+ [0.41159445, 0.1191957, -1.3107123],
383
+ ],
384
+ device=torch_device,
385
+ )
386
+ assert_tensors_close(output[0, :3, :3], expected_slice, atol=5e-5)
387
+
388
+
389
+ @require_torch
390
+ @slow
391
+ class OPTEmbeddingsTest(unittest.TestCase):
392
+ def setUp(self):
393
+ super().setUp()
394
+ self.path_model = "facebook/opt-350m"
395
+
396
+ def test_load_model(self):
397
+ try:
398
+ _ = OPTForCausalLM.from_pretrained(self.path_model)
399
+ except BaseException:
400
+ self.fail("Failed loading model")
401
+
402
+ def test_logits(self):
403
+ model = OPTForCausalLM.from_pretrained(self.path_model)
404
+ model = model.eval()
405
+ tokenizer = GPT2Tokenizer.from_pretrained(self.path_model)
406
+
407
+ prompts = [
408
+ "Today is a beautiful day and I want to",
409
+ "In the city of",
410
+ "Paris is the capital of France and",
411
+ "Computers and mobile phones have taken",
412
+ ]
413
+ # verify that prompt without BOS token is identical to Metaseq -> add_special_tokens=False
414
+ inputs = tokenizer(prompts, return_tensors="pt", padding=True, add_special_tokens=False)
415
+ logits = model(inputs.input_ids, attention_mask=inputs.attention_mask)[0].mean(dim=-1)
416
+ # logits_meta = torch.load(self.path_logits_meta)
417
+ logits_meta = torch.Tensor(
418
+ [
419
+ [1.3851, -13.8923, -10.5229, -10.7533, -0.2309, -10.2384, -0.5365, -9.0947, -5.1670],
420
+ [-4.7073, -10.6276, -3.9415, -21.5242, -0.2822, -0.2822, -0.2822, -0.2822, -0.2822],
421
+ [0.6247, -3.4229, -8.9179, -1.4297, -14.1650, 1.4146, -9.0218, -0.2703, -0.2703],
422
+ [6.4783, -1.9913, -10.7926, -2.3336, 1.5092, -0.9974, -6.8213, 1.3477, 1.3477],
423
+ ]
424
+ )
425
+ assert torch.allclose(logits, logits_meta, atol=1e-4)
426
+
427
+
428
+ @slow
429
+ class OPTGenerationTest(unittest.TestCase):
430
+ @property
431
+ def prompts(self):
432
+ return [
433
+ "Today is a beautiful day and I want",
434
+ "In the city of",
435
+ "Paris is the capital of France and",
436
+ "Computers and mobile phones have taken",
437
+ ]
438
+
439
+ def test_generation_pre_attn_layer_norm(self):
440
+ model_id = "facebook/opt-125m"
441
+
442
+ EXPECTED_OUTPUTS = [
443
+ "Today is a beautiful day and I want to",
444
+ "In the city of New York, the city",
445
+ "Paris is the capital of France and the capital",
446
+ "Computers and mobile phones have taken over the",
447
+ ]
448
+
449
+ predicted_outputs = []
450
+ tokenizer = GPT2Tokenizer.from_pretrained(model_id)
451
+ model = OPTForCausalLM.from_pretrained(model_id)
452
+
453
+ for prompt in self.prompts:
454
+ input_ids = tokenizer(prompt, return_tensors="pt").input_ids
455
+
456
+ generated_ids = model.generate(input_ids, max_length=10)
457
+
458
+ generated_string = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
459
+ predicted_outputs += generated_string
460
+
461
+ self.assertListEqual(predicted_outputs, EXPECTED_OUTPUTS)
462
+
463
+ def test_batch_generation(self):
464
+ model_id = "facebook/opt-350m"
465
+
466
+ tokenizer = GPT2Tokenizer.from_pretrained(model_id)
467
+ model = OPTForCausalLM.from_pretrained(model_id)
468
+ model.to(torch_device)
469
+
470
+ tokenizer.padding_side = "left"
471
+
472
+ # use different length sentences to test batching
473
+ sentences = [
474
+ "Hello, my dog is a little",
475
+ "Today, I",
476
+ ]
477
+
478
+ inputs = tokenizer(sentences, return_tensors="pt", padding=True)
479
+ input_ids = inputs["input_ids"].to(torch_device)
480
+
481
+ outputs = model.generate(
482
+ input_ids=input_ids,
483
+ attention_mask=inputs["attention_mask"].to(torch_device),
484
+ )
485
+
486
+ inputs_non_padded = tokenizer(sentences[0], return_tensors="pt").input_ids.to(torch_device)
487
+ output_non_padded = model.generate(input_ids=inputs_non_padded)
488
+
489
+ num_paddings = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item()
490
+ inputs_padded = tokenizer(sentences[1], return_tensors="pt").input_ids.to(torch_device)
491
+ output_padded = model.generate(input_ids=inputs_padded, max_length=model.config.max_length - num_paddings)
492
+
493
+ batch_out_sentence = tokenizer.batch_decode(outputs, skip_special_tokens=True)
494
+ non_padded_sentence = tokenizer.decode(output_non_padded[0], skip_special_tokens=True)
495
+ padded_sentence = tokenizer.decode(output_padded[0], skip_special_tokens=True)
496
+
497
+ expected_output_sentence = [
498
+ "Hello, my dog is a little bit of a dork.\nI'm a little bit",
499
+ "Today, I was in the middle of a conversation with a friend about the",
500
+ ]
501
+ self.assertListEqual(expected_output_sentence, batch_out_sentence)
502
+ self.assertListEqual(batch_out_sentence, [non_padded_sentence, padded_sentence])
503
+
504
+ def test_generation_post_attn_layer_norm(self):
505
+ model_id = "facebook/opt-350m"
506
+
507
+ EXPECTED_OUTPUTS = [
508
+ "Today is a beautiful day and I want to",
509
+ "In the city of San Francisco, the city",
510
+ "Paris is the capital of France and the capital",
511
+ "Computers and mobile phones have taken over the",
512
+ ]
513
+
514
+ predicted_outputs = []
515
+ tokenizer = GPT2Tokenizer.from_pretrained(model_id)
516
+ model = OPTForCausalLM.from_pretrained(model_id)
517
+
518
+ for prompt in self.prompts:
519
+ input_ids = tokenizer(prompt, return_tensors="pt").input_ids
520
+
521
+ generated_ids = model.generate(input_ids, max_length=10)
522
+
523
+ generated_string = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)
524
+ predicted_outputs += generated_string
525
+
526
+ self.assertListEqual(predicted_outputs, EXPECTED_OUTPUTS)
527
+
528
+ @require_torch_accelerator
529
+ @require_torch_fp16
530
+ def test_batched_nan_fp16(self):
531
+ # a bug manifested starting at models facebook/opt-1.3 and larger when running batched generations,
532
+ # therefore not using a tiny model, but the smallest model the problem was seen with which is opt-1.3b.
533
+ # please refer to this github thread: https://github.com/huggingface/transformers/pull/17437 for more details
534
+ model_name = "facebook/opt-1.3b"
535
+ tokenizer = GPT2Tokenizer.from_pretrained(model_name, use_fast=False, padding_side="left")
536
+
537
+ model = OPTForCausalLM.from_pretrained(model_name, torch_dtype=torch.float16, use_cache=True).to(torch_device)
538
+ model = model.eval()
539
+
540
+ batch = tokenizer(["Who are you?", "Joe Biden is the president of"], padding=True, return_tensors="pt")
541
+
542
+ input_ids = batch["input_ids"].to(torch_device)
543
+ attention_mask = batch["attention_mask"].to(torch_device)
544
+
545
+ with torch.no_grad():
546
+ outputs = model(input_ids, attention_mask=attention_mask)
547
+ self.assertFalse(
548
+ torch.isnan(outputs.logits[0]).any().item()
549
+ ) # the first logits could contain NaNs if it fails
550
+
551
+ @slow
552
+ def test_contrastive_search_opt(self):
553
+ article = (
554
+ "A chat between a curious human and the Statue of Liberty.\n\nHuman: What is your name?\nStatue: I am the "
555
+ "Statue of Liberty.\nHuman: Where do you live?\nStatue: New York City.\nHuman: How long have you lived "
556
+ "there?"
557
+ )
558
+
559
+ opt_tokenizer = GPT2Tokenizer.from_pretrained("facebook/opt-1.3b")
560
+ opt_model = OPTForCausalLM.from_pretrained("facebook/opt-1.3b").to(torch_device)
561
+ input_ids = opt_tokenizer(article, return_tensors="pt").input_ids.to(torch_device)
562
+
563
+ outputs = opt_model.generate(input_ids, penalty_alpha=0.6, top_k=5, max_length=256)
564
+ generated_text = opt_tokenizer.batch_decode(outputs, skip_special_tokens=True)
565
+
566
+ self.assertListEqual(
567
+ generated_text,
568
+ [
569
+ "A chat between a curious human and the Statue of Liberty.\n\nHuman: What is your name?\nStatue: I "
570
+ "am the Statue of Liberty.\nHuman: Where do you live?\nStatue: New York City.\nHuman: How long have "
571
+ "you lived there?\nStatue: A hundred years.\nHuman: And you’re from what country?\nStatue: The United "
572
+ "States of America.\nHuman: Why did you come to America?\nStatue: I came to escape the tyranny of my "
573
+ "country.\nHuman: What tyranny?\nStatue: They didn’t let me speak my mind.\nHuman: What was your "
574
+ "country?\nStatue: It was a country of immigrants.\nHuman: Who were the immigrants?\nStatue: They "
575
+ "were from all over the world.\nHuman: What language did they speak?\nStatue: French, Spanish, "
576
+ "Italian, German, English—you name it.\nHuman: And where did they come from?\nStatue: They came from "
577
+ "every country in the world.\nHuman: And you were born in what country?\nStatue: I was born in "
578
+ "France.\nHuman: And your parents were French?\nStatue"
579
+ ],
580
+ )
tasks/tasksmith-e0f68dd4420c/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-e0f68dd4420c/tests/source/tests/models/owlv2/__init__.py ADDED
File without changes
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/owlv2/test_image_processing_owlv2.py ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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:
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
+ self.parent = parent
51
+ self.batch_size = batch_size
52
+ self.num_channels = num_channels
53
+ self.image_size = image_size
54
+ self.min_resolution = min_resolution
55
+ self.max_resolution = max_resolution
56
+ self.do_resize = do_resize
57
+ self.size = size if 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_normalize": self.do_normalize,
68
+ "image_mean": self.image_mean,
69
+ "image_std": self.image_std,
70
+ }
71
+
72
+ def expected_output_image_shape(self, images):
73
+ return self.num_channels, self.size["height"], self.size["width"]
74
+
75
+ def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
76
+ return prepare_image_inputs(
77
+ batch_size=self.batch_size,
78
+ num_channels=self.num_channels,
79
+ min_resolution=self.min_resolution,
80
+ max_resolution=self.max_resolution,
81
+ equal_resolution=equal_resolution,
82
+ numpify=numpify,
83
+ torchify=torchify,
84
+ )
85
+
86
+
87
+ @require_torch
88
+ @require_vision
89
+ class Owlv2ImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
90
+ image_processing_class = Owlv2ImageProcessor if is_vision_available() else None
91
+
92
+ def setUp(self):
93
+ super().setUp()
94
+ self.image_processor_tester = Owlv2ImageProcessingTester(self)
95
+
96
+ @property
97
+ def image_processor_dict(self):
98
+ return self.image_processor_tester.prepare_image_processor_dict()
99
+
100
+ def test_image_processor_properties(self):
101
+ image_processing = self.image_processing_class(**self.image_processor_dict)
102
+ self.assertTrue(hasattr(image_processing, "do_resize"))
103
+ self.assertTrue(hasattr(image_processing, "size"))
104
+ self.assertTrue(hasattr(image_processing, "do_normalize"))
105
+ self.assertTrue(hasattr(image_processing, "image_mean"))
106
+ self.assertTrue(hasattr(image_processing, "image_std"))
107
+
108
+ def test_image_processor_from_dict_with_kwargs(self):
109
+ image_processor = self.image_processing_class.from_dict(self.image_processor_dict)
110
+ self.assertEqual(image_processor.size, {"height": 18, "width": 18})
111
+
112
+ image_processor = self.image_processing_class.from_dict(
113
+ self.image_processor_dict, size={"height": 42, "width": 42}
114
+ )
115
+ self.assertEqual(image_processor.size, {"height": 42, "width": 42})
116
+
117
+ @slow
118
+ def test_image_processor_integration_test(self):
119
+ processor = Owlv2ImageProcessor()
120
+
121
+ image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
122
+ pixel_values = processor(image, return_tensors="pt").pixel_values
123
+
124
+ mean_value = round(pixel_values.mean().item(), 4)
125
+ self.assertEqual(mean_value, 0.2353)
126
+
127
+ @slow
128
+ def test_image_processor_integration_test_resize(self):
129
+ checkpoint = "google/owlv2-base-patch16-ensemble"
130
+ processor = AutoProcessor.from_pretrained(checkpoint)
131
+ model = Owlv2ForObjectDetection.from_pretrained(checkpoint)
132
+
133
+ image = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
134
+ text = ["cat"]
135
+ target_size = image.size[::-1]
136
+ expected_boxes = torch.tensor(
137
+ [
138
+ [341.66656494140625, 23.38756561279297, 642.321044921875, 371.3482971191406],
139
+ [6.753320693969727, 51.96149826049805, 326.61810302734375, 473.12982177734375],
140
+ ]
141
+ )
142
+
143
+ # single image
144
+ inputs = processor(text=[text], images=[image], return_tensors="pt")
145
+ with torch.no_grad():
146
+ outputs = model(**inputs)
147
+
148
+ results = processor.post_process_object_detection(outputs, threshold=0.2, target_sizes=[target_size])[0]
149
+
150
+ boxes = results["boxes"]
151
+ self.assertTrue(
152
+ torch.allclose(boxes, expected_boxes, atol=1e-2),
153
+ f"Single image bounding boxes fail. Expected {expected_boxes}, got {boxes}",
154
+ )
155
+
156
+ # batch of images
157
+ inputs = processor(text=[text, text], images=[image, image], return_tensors="pt")
158
+ with torch.no_grad():
159
+ outputs = model(**inputs)
160
+ results = processor.post_process_object_detection(
161
+ outputs, threshold=0.2, target_sizes=[target_size, target_size]
162
+ )
163
+
164
+ for result in results:
165
+ boxes = result["boxes"]
166
+ self.assertTrue(
167
+ torch.allclose(boxes, expected_boxes, atol=1e-2),
168
+ f"Batch image bounding boxes fail. Expected {expected_boxes}, got {boxes}",
169
+ )
170
+
171
+ @unittest.skip(reason="OWLv2 doesn't treat 4 channel PIL and numpy consistently yet") # FIXME Amy
172
+ def test_call_numpy_4_channels(self):
173
+ pass
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/owlv2/test_modeling_owlv2.py ADDED
@@ -0,0 +1,1071 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ torch.testing.assert_close(outputs.logits_per_image, expected_logits, rtol=1e-3, 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
+ torch.testing.assert_close(outputs.logits_per_image, expected_logits, rtol=1e-3, 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
+ torch.testing.assert_close(outputs.pred_boxes[0, :3, :3], expected_slice_boxes, rtol=1e-4, 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
+ torch.testing.assert_close(model.box_bias[:3, :4], expected_default_box_bias, rtol=1e-4, 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
+ torch.testing.assert_close(outputs.pred_boxes[0, :3, :3], expected_slice_boxes, rtol=1e-4, 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
+ text_labels = [["a photo of a cat", "a photo of a dog"]]
978
+ inputs = processor(
979
+ text=text_labels,
980
+ images=image,
981
+ max_length=16,
982
+ padding="max_length",
983
+ return_tensors="pt",
984
+ ).to(torch_device)
985
+
986
+ with torch.no_grad():
987
+ outputs = model(**inputs)
988
+
989
+ num_queries = int((model.config.vision_config.image_size / model.config.vision_config.patch_size) ** 2)
990
+ self.assertEqual(outputs.pred_boxes.shape, torch.Size((1, num_queries, 4)))
991
+
992
+ expected_slice_logits = torch.tensor(
993
+ [[-21.413497, -21.612638], [-19.008193, -19.548841], [-20.958896, -21.382694]]
994
+ ).to(torch_device)
995
+ torch.testing.assert_close(outputs.logits[0, :3, :3], expected_slice_logits, rtol=1e-4, atol=1e-4)
996
+ expected_slice_boxes = torch.tensor(
997
+ [[0.241309, 0.051896, 0.453267], [0.139474, 0.045701, 0.250660], [0.233022, 0.050479, 0.427671]],
998
+ ).to(torch_device)
999
+ torch.testing.assert_close(outputs.pred_boxes[0, :3, :3], expected_slice_boxes, rtol=1e-4, atol=1e-4)
1000
+ resulted_slice_boxes = outputs.pred_boxes[0, :3, :3]
1001
+ max_diff = torch.max(torch.abs(resulted_slice_boxes - expected_slice_boxes)).item()
1002
+ self.assertLess(max_diff, 3e-4)
1003
+
1004
+ # test post-processing
1005
+ post_processed_output = processor.post_process_grounded_object_detection(outputs)
1006
+ self.assertIsNone(post_processed_output[0]["text_labels"])
1007
+
1008
+ post_processed_output_with_text_labels = processor.post_process_grounded_object_detection(
1009
+ outputs, text_labels=text_labels
1010
+ )
1011
+
1012
+ objects_labels = post_processed_output_with_text_labels[0]["labels"].cpu().tolist()
1013
+ self.assertListEqual(objects_labels, [0, 0])
1014
+
1015
+ objects_text_labels = post_processed_output_with_text_labels[0]["text_labels"]
1016
+ self.assertIsNotNone(objects_text_labels)
1017
+ self.assertListEqual(objects_text_labels, ["a photo of a cat", "a photo of a cat"])
1018
+
1019
+ @slow
1020
+ def test_inference_one_shot_object_detection(self):
1021
+ model_name = "google/owlv2-base-patch16"
1022
+ model = Owlv2ForObjectDetection.from_pretrained(model_name).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
+ num_queries = int((model.config.vision_config.image_size / model.config.vision_config.patch_size) ** 2)
1040
+ self.assertEqual(outputs.target_pred_boxes.shape, torch.Size((1, num_queries, 4)))
1041
+
1042
+ expected_slice_boxes = torch.tensor(
1043
+ [[0.2413, 0.0519, 0.4533], [0.1395, 0.0457, 0.2507], [0.2330, 0.0505, 0.4277]],
1044
+ ).to(torch_device)
1045
+ torch.testing.assert_close(outputs.target_pred_boxes[0, :3, :3], expected_slice_boxes, rtol=1e-4, atol=1e-4)
1046
+
1047
+ @slow
1048
+ @require_torch_accelerator
1049
+ @require_torch_fp16
1050
+ def test_inference_one_shot_object_detection_fp16(self):
1051
+ model_name = "google/owlv2-base-patch16"
1052
+ model = Owlv2ForObjectDetection.from_pretrained(model_name, torch_dtype=torch.float16).to(torch_device)
1053
+
1054
+ processor = OwlViTProcessor.from_pretrained(model_name)
1055
+
1056
+ image = prepare_img()
1057
+ query_image = prepare_img()
1058
+ inputs = processor(
1059
+ images=image,
1060
+ query_images=query_image,
1061
+ max_length=16,
1062
+ padding="max_length",
1063
+ return_tensors="pt",
1064
+ ).to(torch_device)
1065
+
1066
+ with torch.no_grad():
1067
+ outputs = model.image_guided_detection(**inputs)
1068
+
1069
+ # No need to check the logits, we just check inference runs fine.
1070
+ num_queries = int((model.config.vision_config.image_size / model.config.vision_config.patch_size) ** 2)
1071
+ self.assertEqual(outputs.target_pred_boxes.shape, torch.Size((1, num_queries, 4)))
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/owlv2/test_processor_owlv2.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import shutil
2
+ import tempfile
3
+ import unittest
4
+
5
+ import pytest
6
+
7
+ from transformers import Owlv2Processor
8
+ from transformers.testing_utils import require_scipy
9
+
10
+ from ...test_processing_common import ProcessorTesterMixin
11
+
12
+
13
+ @require_scipy
14
+ class Owlv2ProcessorTest(ProcessorTesterMixin, unittest.TestCase):
15
+ processor_class = Owlv2Processor
16
+
17
+ def setUp(self):
18
+ self.tmpdirname = tempfile.mkdtemp()
19
+ processor = self.processor_class.from_pretrained("google/owlv2-base-patch16-ensemble")
20
+ processor.save_pretrained(self.tmpdirname)
21
+
22
+ def tearDown(self):
23
+ shutil.rmtree(self.tmpdirname)
24
+
25
+ def test_processor_query_images_positional(self):
26
+ processor_components = self.prepare_components()
27
+ processor = Owlv2Processor(**processor_components)
28
+
29
+ image_input = self.prepare_image_inputs()
30
+ query_images = self.prepare_image_inputs()
31
+
32
+ inputs = processor(None, image_input, query_images)
33
+
34
+ self.assertListEqual(list(inputs.keys()), ["query_pixel_values", "pixel_values"])
35
+
36
+ # test if it raises when no input is passed
37
+ with pytest.raises(ValueError):
38
+ processor()
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/owlvit/__init__.py ADDED
File without changes
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/owlvit/test_image_processing_owlvit.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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:
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
+ self.parent = parent
48
+ self.batch_size = batch_size
49
+ self.num_channels = num_channels
50
+ self.image_size = image_size
51
+ self.min_resolution = min_resolution
52
+ self.max_resolution = max_resolution
53
+ self.do_resize = do_resize
54
+ self.size = size if size is not None else {"height": 18, "width": 18}
55
+ self.do_center_crop = do_center_crop
56
+ self.crop_size = crop_size if crop_size is not None else {"height": 18, "width": 18}
57
+ self.do_normalize = do_normalize
58
+ self.image_mean = image_mean
59
+ self.image_std = image_std
60
+ self.do_convert_rgb = do_convert_rgb
61
+
62
+ def prepare_image_processor_dict(self):
63
+ return {
64
+ "do_resize": self.do_resize,
65
+ "size": self.size,
66
+ "do_center_crop": self.do_center_crop,
67
+ "crop_size": self.crop_size,
68
+ "do_normalize": self.do_normalize,
69
+ "image_mean": self.image_mean,
70
+ "image_std": self.image_std,
71
+ "do_convert_rgb": self.do_convert_rgb,
72
+ }
73
+
74
+ def expected_output_image_shape(self, images):
75
+ return self.num_channels, self.crop_size["height"], self.crop_size["width"]
76
+
77
+ def prepare_image_inputs(self, equal_resolution=False, numpify=False, torchify=False):
78
+ return prepare_image_inputs(
79
+ batch_size=self.batch_size,
80
+ num_channels=self.num_channels,
81
+ min_resolution=self.min_resolution,
82
+ max_resolution=self.max_resolution,
83
+ equal_resolution=equal_resolution,
84
+ numpify=numpify,
85
+ torchify=torchify,
86
+ )
87
+
88
+
89
+ @require_torch
90
+ @require_vision
91
+ class OwlViTImageProcessingTest(ImageProcessingTestMixin, unittest.TestCase):
92
+ image_processing_class = OwlViTImageProcessor if is_vision_available() else None
93
+
94
+ def setUp(self):
95
+ super().setUp()
96
+ self.image_processor_tester = OwlViTImageProcessingTester(self)
97
+
98
+ @property
99
+ def image_processor_dict(self):
100
+ return self.image_processor_tester.prepare_image_processor_dict()
101
+
102
+ def test_image_processor_properties(self):
103
+ image_processing = self.image_processing_class(**self.image_processor_dict)
104
+ self.assertTrue(hasattr(image_processing, "do_resize"))
105
+ self.assertTrue(hasattr(image_processing, "size"))
106
+ self.assertTrue(hasattr(image_processing, "do_center_crop"))
107
+ self.assertTrue(hasattr(image_processing, "center_crop"))
108
+ self.assertTrue(hasattr(image_processing, "do_normalize"))
109
+ self.assertTrue(hasattr(image_processing, "image_mean"))
110
+ self.assertTrue(hasattr(image_processing, "image_std"))
111
+ self.assertTrue(hasattr(image_processing, "do_convert_rgb"))
112
+
113
+ def test_image_processor_from_dict_with_kwargs(self):
114
+ image_processor = self.image_processing_class.from_dict(self.image_processor_dict)
115
+ self.assertEqual(image_processor.size, {"height": 18, "width": 18})
116
+ self.assertEqual(image_processor.crop_size, {"height": 18, "width": 18})
117
+
118
+ image_processor = self.image_processing_class.from_dict(self.image_processor_dict, size=42, crop_size=84)
119
+ self.assertEqual(image_processor.size, {"height": 42, "width": 42})
120
+ self.assertEqual(image_processor.crop_size, {"height": 84, "width": 84})
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/owlvit/test_modeling_owlvit.py ADDED
@@ -0,0 +1,1057 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ torch.testing.assert_close(outputs.logits_per_image, expected_logits, rtol=1e-3, 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
+ torch.testing.assert_close(outputs.logits_per_image, expected_logits, rtol=1e-3, 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
+ torch.testing.assert_close(outputs.pred_boxes[0, :3, :3], expected_slice_boxes, rtol=1e-4, 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
+ torch.testing.assert_close(model.box_bias[:3, :4], expected_default_box_bias, rtol=1e-4, 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
+ torch.testing.assert_close(outputs.pred_boxes[0, :3, :3], expected_slice_boxes, rtol=1e-4, 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
+ text_labels = [["a photo of a cat", "a photo of a dog"]]
971
+ inputs = processor(
972
+ text=text_labels,
973
+ images=image,
974
+ max_length=16,
975
+ padding="max_length",
976
+ return_tensors="pt",
977
+ ).to(torch_device)
978
+
979
+ with torch.no_grad():
980
+ outputs = model(**inputs)
981
+
982
+ num_queries = int((model.config.vision_config.image_size / model.config.vision_config.patch_size) ** 2)
983
+ self.assertEqual(outputs.pred_boxes.shape, torch.Size((1, num_queries, 4)))
984
+
985
+ expected_slice_boxes = torch.tensor(
986
+ [[0.0691, 0.0445, 0.1373], [0.1592, 0.0456, 0.3192], [0.1632, 0.0423, 0.2478]]
987
+ ).to(torch_device)
988
+ torch.testing.assert_close(outputs.pred_boxes[0, :3, :3], expected_slice_boxes, rtol=1e-4, atol=1e-4)
989
+
990
+ # test post-processing
991
+ post_processed_output = processor.post_process_grounded_object_detection(outputs)
992
+ self.assertIsNone(post_processed_output[0]["text_labels"])
993
+
994
+ post_processed_output_with_text_labels = processor.post_process_grounded_object_detection(
995
+ outputs, text_labels=text_labels
996
+ )
997
+
998
+ objects_labels = post_processed_output_with_text_labels[0]["labels"].cpu().tolist()
999
+ self.assertListEqual(objects_labels, [0, 0])
1000
+
1001
+ objects_text_labels = post_processed_output_with_text_labels[0]["text_labels"]
1002
+ self.assertIsNotNone(objects_text_labels)
1003
+ self.assertListEqual(objects_text_labels, ["a photo of a cat", "a photo of a cat"])
1004
+
1005
+ @slow
1006
+ def test_inference_one_shot_object_detection(self):
1007
+ model_name = "google/owlvit-base-patch32"
1008
+ model = OwlViTForObjectDetection.from_pretrained(model_name).to(torch_device)
1009
+
1010
+ processor = OwlViTProcessor.from_pretrained(model_name)
1011
+
1012
+ image = prepare_img()
1013
+ query_image = prepare_img()
1014
+ inputs = processor(
1015
+ images=image,
1016
+ query_images=query_image,
1017
+ max_length=16,
1018
+ padding="max_length",
1019
+ return_tensors="pt",
1020
+ ).to(torch_device)
1021
+
1022
+ with torch.no_grad():
1023
+ outputs = model.image_guided_detection(**inputs)
1024
+
1025
+ num_queries = int((model.config.vision_config.image_size / model.config.vision_config.patch_size) ** 2)
1026
+ self.assertEqual(outputs.target_pred_boxes.shape, torch.Size((1, num_queries, 4)))
1027
+
1028
+ expected_slice_boxes = torch.tensor(
1029
+ [[0.0691, 0.0445, 0.1373], [0.1592, 0.0456, 0.3192], [0.1632, 0.0423, 0.2478]]
1030
+ ).to(torch_device)
1031
+ torch.testing.assert_close(outputs.target_pred_boxes[0, :3, :3], expected_slice_boxes, rtol=1e-4, atol=1e-4)
1032
+
1033
+ @slow
1034
+ @require_torch_accelerator
1035
+ @require_torch_fp16
1036
+ def test_inference_one_shot_object_detection_fp16(self):
1037
+ model_name = "google/owlvit-base-patch32"
1038
+ model = OwlViTForObjectDetection.from_pretrained(model_name, torch_dtype=torch.float16).to(torch_device)
1039
+
1040
+ processor = OwlViTProcessor.from_pretrained(model_name)
1041
+
1042
+ image = prepare_img()
1043
+ query_image = prepare_img()
1044
+ inputs = processor(
1045
+ images=image,
1046
+ query_images=query_image,
1047
+ max_length=16,
1048
+ padding="max_length",
1049
+ return_tensors="pt",
1050
+ ).to(torch_device)
1051
+
1052
+ with torch.no_grad():
1053
+ outputs = model.image_guided_detection(**inputs)
1054
+
1055
+ # No need to check the logits, we just check inference runs fine.
1056
+ num_queries = int((model.config.vision_config.image_size / model.config.vision_config.patch_size) ** 2)
1057
+ self.assertEqual(outputs.target_pred_boxes.shape, torch.Size((1, num_queries, 4)))
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/owlvit/test_processor_owlvit.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_processor_query_images_positional(self):
236
+ processor_components = self.prepare_components()
237
+ processor = OwlViTProcessor(**processor_components)
238
+
239
+ image_input = self.prepare_image_inputs()
240
+ query_images = self.prepare_image_inputs()
241
+
242
+ inputs = processor(None, image_input, query_images)
243
+
244
+ self.assertListEqual(list(inputs.keys()), ["query_pixel_values", "pixel_values"])
245
+
246
+ # test if it raises when no input is passed
247
+ with pytest.raises(ValueError):
248
+ processor()
249
+
250
+ def test_tokenizer_decode(self):
251
+ image_processor = self.get_image_processor()
252
+ tokenizer = self.get_tokenizer()
253
+
254
+ processor = OwlViTProcessor(tokenizer=tokenizer, image_processor=image_processor)
255
+
256
+ predicted_ids = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
257
+
258
+ decoded_processor = processor.batch_decode(predicted_ids)
259
+ decoded_tok = tokenizer.batch_decode(predicted_ids)
260
+
261
+ self.assertListEqual(decoded_tok, decoded_processor)
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/paligemma/__init__.py ADDED
File without changes
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/paligemma/test_modeling_paligemma.py ADDED
@@ -0,0 +1,670 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ pipeline_model_mapping = {"image-text-to-text": PaliGemmaForConditionalGeneration}
183
+ fx_compatible = False
184
+ test_pruning = False
185
+ test_torchscript = False
186
+ test_head_masking = False
187
+ _is_composite = True
188
+
189
+ def setUp(self):
190
+ self.model_tester = PaliGemmaVisionText2TextModelTester(self)
191
+ self.config_tester = ConfigTester(self, config_class=PaliGemmaConfig, has_text_modality=False)
192
+
193
+ # overwrite inputs_embeds tests because we need to delete "pixel values" for LVLMs
194
+ def test_inputs_embeds(self):
195
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
196
+
197
+ for model_class in self.all_model_classes:
198
+ model = model_class(config)
199
+ model.to(torch_device)
200
+ model.eval()
201
+
202
+ inputs = self._prepare_for_class(inputs_dict, model_class)
203
+
204
+ input_ids = inputs["input_ids"]
205
+ del inputs["input_ids"]
206
+ del inputs["pixel_values"]
207
+
208
+ wte = model.get_input_embeddings()
209
+ inputs["inputs_embeds"] = wte(input_ids)
210
+
211
+ with torch.no_grad():
212
+ model(**inputs)
213
+
214
+ # overwrite inputs_embeds tests because we need to delete "pixel values" for LVLMs
215
+ # while some other models require pixel_values to be present
216
+ def test_inputs_embeds_matches_input_ids(self):
217
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
218
+
219
+ for model_class in self.all_model_classes:
220
+ model = model_class(config)
221
+ model.to(torch_device)
222
+ model.eval()
223
+
224
+ inputs = self._prepare_for_class(inputs_dict, model_class)
225
+ input_ids = inputs["input_ids"]
226
+ del inputs["input_ids"]
227
+ del inputs["pixel_values"]
228
+
229
+ inputs_embeds = model.get_input_embeddings()(input_ids)
230
+
231
+ with torch.no_grad():
232
+ out_ids = model(input_ids=input_ids, **inputs)[0]
233
+ out_embeds = model(inputs_embeds=inputs_embeds, **inputs)[0]
234
+ torch.testing.assert_close(out_embeds, out_ids)
235
+
236
+ # Copied from tests.models.llava.test_modeling_llava.LlavaForConditionalGenerationModelTest.test_mismatching_num_image_tokens
237
+ def test_mismatching_num_image_tokens(self):
238
+ """
239
+ Tests that VLMs through an error with explicit message saying what is wrong
240
+ when number of images don't match number of image tokens in the text.
241
+ Also we need to test multi-image cases when one prompr has multiple image tokens.
242
+ """
243
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
244
+ for model_class in self.all_model_classes:
245
+ model = model_class(config).to(torch_device)
246
+ _ = model(**input_dict) # successfull forward with no modifications
247
+
248
+ # remove one image but leave the image token in text
249
+ input_dict["pixel_values"] = input_dict["pixel_values"][-1:, ...]
250
+ with self.assertRaises(ValueError):
251
+ _ = model(**input_dict)
252
+
253
+ # simulate multi-image case by concatenating inputs where each has exactly one image/image-token
254
+ input_ids = input_dict["input_ids"][:1]
255
+ pixel_values = input_dict["pixel_values"][:1]
256
+ input_ids = torch.cat([input_ids, input_ids], dim=0)
257
+
258
+ # one image and two image tokens raise an error
259
+ with self.assertRaises(ValueError):
260
+ _ = model(input_ids=input_ids, pixel_values=pixel_values)
261
+
262
+ # two images and two image tokens don't raise an error
263
+ pixel_values = torch.cat([pixel_values, pixel_values], dim=0)
264
+ _ = model(input_ids=input_ids, pixel_values=pixel_values)
265
+
266
+ @unittest.skip(
267
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
268
+ )
269
+ def test_training_gradient_checkpointing(self):
270
+ pass
271
+
272
+ @unittest.skip(
273
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
274
+ )
275
+ def test_training_gradient_checkpointing_use_reentrant(self):
276
+ pass
277
+
278
+ @unittest.skip(
279
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
280
+ )
281
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
282
+ pass
283
+
284
+ @unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.")
285
+ def test_cpu_offload(self):
286
+ pass
287
+
288
+ @unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.")
289
+ def test_disk_offload_bin(self):
290
+ pass
291
+
292
+ @unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.")
293
+ def test_disk_offload_safetensors(self):
294
+ pass
295
+
296
+ @unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.")
297
+ def test_model_parallelism(self):
298
+ pass
299
+
300
+ @unittest.skip(
301
+ reason="PaliGemmma's SigLip encoder uses the same initialization scheme as the Flax original implementation"
302
+ )
303
+ def test_initialization(self):
304
+ pass
305
+
306
+ # TODO extend valid outputs to include this test @Molbap
307
+ @unittest.skip(reason="PaliGemma has currently one output format.")
308
+ def test_model_outputs_equivalence(self):
309
+ pass
310
+
311
+ # TODO fix the loss = nan in the testing configuration chosen @Molbap
312
+ @unittest.skip(reason="Edge case giving loss nan values in testing configuration.")
313
+ def test_determinism(self):
314
+ pass
315
+
316
+ @unittest.skip(reason="PaliGemma does not use feedforward chunking.")
317
+ def test_feed_forward_chunking(self):
318
+ pass
319
+
320
+ @unittest.skip(reason="PaliGemma does not support low_cpu_mem_usage.")
321
+ def test_save_load_low_cpu_mem_usage(self):
322
+ pass
323
+
324
+ @unittest.skip(reason="PaliGemma does not support low_cpu_mem_usage.")
325
+ def test_save_load_low_cpu_mem_usage_checkpoints(self):
326
+ pass
327
+
328
+ @unittest.skip(reason="PaliGemma does not support low_cpu_mem_usage.")
329
+ def test_save_load_low_cpu_mem_usage_no_safetensors(self):
330
+ pass
331
+
332
+ @unittest.skip(
333
+ 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"
334
+ )
335
+ def test_generate_from_inputs_embeds_with_static_cache(self):
336
+ pass
337
+
338
+ @unittest.skip("FlashAttention only support fp16 and bf16 data type")
339
+ def test_flash_attn_2_fp32_ln(self):
340
+ pass
341
+
342
+ @unittest.skip(
343
+ "VLMs need lots of steps to prepare images/mask correctly to get pad-free inputs. Can be tested as part of LLM test"
344
+ )
345
+ def test_flash_attention_2_padding_matches_padding_free_with_position_ids(self):
346
+ pass
347
+
348
+ # TODO (joao, raushan): fix me -- the problem is in `cache_position[0] == 0`, i.e. dynamic control flow
349
+ @unittest.skip("PaliGemma is not compatible with end-to-end generation compilation")
350
+ def test_generate_compile_model_forward(self):
351
+ pass
352
+
353
+ def test_attention_mask_with_token_types(self):
354
+ """Test that attention masking works correctly both with and without token type IDs."""
355
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
356
+
357
+ for model_class in self.all_model_classes:
358
+ model = model_class(config)
359
+ model.to(torch_device)
360
+ model.eval()
361
+
362
+ # Case 1: With token_type_ids
363
+ outputs_with_types = model(
364
+ **inputs_dict,
365
+ output_attentions=True,
366
+ )
367
+
368
+ # Case 2: Without token_type_ids
369
+ inputs_no_types = {k: v for k, v in inputs_dict.items() if k != "token_type_ids"}
370
+ outputs_no_types = model(
371
+ **inputs_no_types,
372
+ output_attentions=True,
373
+ )
374
+
375
+ attention_outputs_with_types = outputs_with_types.attentions
376
+ attention_outputs_no_types = outputs_no_types.attentions
377
+
378
+ # Verify pad tokens remain masked in both cases
379
+ attention_mask = inputs_dict["attention_mask"]
380
+ pad_positions = attention_mask == 0
381
+
382
+ for layer_attentions in [attention_outputs_with_types, attention_outputs_no_types]:
383
+ for layer_attn in layer_attentions:
384
+ # Check if pad tokens are properly masked
385
+ for batch_idx in range(layer_attn.shape[0]):
386
+ for seq_idx in range(layer_attn.shape[-1]):
387
+ if pad_positions[batch_idx, seq_idx]:
388
+ # Verify attention weights for pad tokens are zero
389
+ self.assertTrue(
390
+ torch.all(layer_attn[batch_idx, :, :, seq_idx] == 0),
391
+ f"Found non-zero attention weights for padding token at batch {batch_idx}, sequence position {seq_idx}",
392
+ )
393
+
394
+
395
+ @slow
396
+ @require_torch
397
+ @require_read_token
398
+ class PaliGemmaForConditionalGenerationIntegrationTest(unittest.TestCase):
399
+ def setUp(self):
400
+ self.processor = PaliGemmaProcessor.from_pretrained("google/paligemma-3b-pt-224")
401
+
402
+ def tearDown(self):
403
+ cleanup(torch_device, gc_collect=True)
404
+
405
+ def test_small_model_integration_test(self):
406
+ # Let' s make sure we test the preprocessing to replace what is used
407
+ model_id = "google/paligemma-3b-pt-224"
408
+ model = PaliGemmaForConditionalGeneration.from_pretrained(model_id)
409
+ prompt = ""
410
+ image_file = (
411
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/cow_beach_1.png"
412
+ )
413
+ raw_image = Image.open(requests.get(image_file, stream=True).raw)
414
+ inputs = self.processor(images=raw_image, text=prompt, return_tensors="pt")
415
+ EXPECTED_INPUT_IDS = torch.tensor([[257152] * 256 + [2, 108]])
416
+ self.assertTrue(torch.equal(inputs["input_ids"], EXPECTED_INPUT_IDS))
417
+
418
+ output = model.generate(**inputs, max_new_tokens=20)
419
+ EXPECTED_DECODED_TEXT = "\ncow on the beach" # fmt: skip
420
+
421
+ self.assertEqual(
422
+ self.processor.decode(output[0], skip_special_tokens=True),
423
+ EXPECTED_DECODED_TEXT,
424
+ )
425
+
426
+ def test_small_model_integration_test_multiimage(self):
427
+ model_id = "google/paligemma-3b-ft-nlvr2-448" # checkpoint tuned for multiple images
428
+ model = PaliGemmaForConditionalGeneration.from_pretrained(model_id)
429
+ processor = PaliGemmaProcessor.from_pretrained(model_id)
430
+ prompt = "answer en There is no snowman in any of the images. Is this true or false?"
431
+ stop_sign_image = Image.open(
432
+ requests.get("https://www.ilankelman.org/stopsigns/australia.jpg", stream=True).raw
433
+ )
434
+ snow_image = Image.open(
435
+ requests.get(
436
+ "https://huggingface.co/microsoft/kosmos-2-patch14-224/resolve/main/snowman.jpg", stream=True
437
+ ).raw
438
+ )
439
+
440
+ inputs = processor(text=prompt, images=[[snow_image, snow_image]], return_tensors="pt")
441
+
442
+ output = model.generate(**inputs, max_new_tokens=20)
443
+ EXPECTED_DECODED_TEXT = "answer en There is no snowman in any of the images. Is this true or false?\nFalse"
444
+
445
+ self.assertEqual(
446
+ self.processor.decode(output[0], skip_special_tokens=True),
447
+ EXPECTED_DECODED_TEXT,
448
+ )
449
+
450
+ # try another prompt with two different image this time
451
+ prompt = "answer en There is exactly one snowman. Is this true or false?"
452
+ inputs = processor(text=prompt, images=[[snow_image, stop_sign_image]], return_tensors="pt")
453
+ output = model.generate(**inputs, max_new_tokens=20)
454
+ EXPECTED_DECODED_TEXT = "answer en There is exactly one snowman. Is this true or false?\nTrue"
455
+ self.assertEqual(
456
+ self.processor.decode(output[0], skip_special_tokens=True),
457
+ EXPECTED_DECODED_TEXT,
458
+ )
459
+
460
+ def test_small_model_integration_test_paligemma_VQA(self):
461
+ # Let' s make sure we test the preprocessing to replace what is used
462
+ model_id = "google/paligemma-3b-pt-224"
463
+ model = PaliGemmaForConditionalGeneration.from_pretrained(model_id)
464
+ prompt = "answer en Where is the cow standing?"
465
+ image_file = (
466
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/cow_beach_1.png"
467
+ )
468
+ raw_image = Image.open(requests.get(image_file, stream=True).raw)
469
+ inputs = self.processor(images=raw_image, text=prompt, return_tensors="pt").to(torch.float16)
470
+
471
+ output = model.generate(**inputs, max_new_tokens=900, do_sample=False)
472
+ EXPECTED_DECODED_TEXT = "answer en Where is the cow standing?\nbeach" # fmt: skip
473
+
474
+ self.assertEqual(
475
+ self.processor.decode(output[0], skip_special_tokens=True),
476
+ EXPECTED_DECODED_TEXT,
477
+ )
478
+
479
+ def test_small_model_integration_test_paligemma_empty_prompt(self):
480
+ # Let' s make sure we test the preprocessing to replace what is used
481
+ model_id = "google/paligemma-3b-pt-224"
482
+ model = PaliGemmaForConditionalGeneration.from_pretrained(model_id)
483
+
484
+ prompt = ""
485
+ image_file = (
486
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/cow_beach_1.png"
487
+ )
488
+ raw_image = Image.open(requests.get(image_file, stream=True).raw)
489
+ inputs = self.processor(images=raw_image, text=prompt, return_tensors="pt").to(torch.float16)
490
+
491
+ output = model.generate(**inputs, max_new_tokens=900, do_sample=False)
492
+ EXPECTED_DECODED_TEXT = "\ncow on the beach" # fmt: skip
493
+
494
+ self.assertEqual(
495
+ self.processor.decode(output[0], skip_special_tokens=True),
496
+ EXPECTED_DECODED_TEXT,
497
+ )
498
+
499
+ def test_small_model_integration_test_paligemma_batched(self):
500
+ # Let' s make sure we test the preprocessing to replace what is used
501
+ model_id = "google/paligemma-3b-pt-224"
502
+
503
+ model = PaliGemmaForConditionalGeneration.from_pretrained(model_id)
504
+
505
+ prompts = [
506
+ "answer en Where is the cow standing?",
507
+ "",
508
+ ]
509
+ image1 = Image.open(
510
+ requests.get(
511
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/cow_beach_1.png",
512
+ stream=True,
513
+ ).raw
514
+ )
515
+ image2 = image1
516
+
517
+ inputs = self.processor(images=[image1, image2], text=prompts, return_tensors="pt", padding=True)
518
+
519
+ output = model.generate(**inputs, max_new_tokens=20)
520
+
521
+ EXPECTED_DECODED_TEXT = ["answer en Where is the cow standing?\nbeach", "\ncow on the beach"] # fmt: skip
522
+
523
+ self.assertEqual(self.processor.batch_decode(output, skip_special_tokens=True), EXPECTED_DECODED_TEXT)
524
+
525
+ def test_small_model_integration_test_paligemma_batched_bf16(self):
526
+ # Let' s make sure we test the preprocessing to replace what is used
527
+ model_id = "google/paligemma-3b-pt-224"
528
+ model = PaliGemmaForConditionalGeneration.from_pretrained(
529
+ model_id, revision="bfloat16", torch_dtype=torch.bfloat16
530
+ ).to(torch_device)
531
+ # The first batch is longer in terms of text, the second will be padded.
532
+ prompts = [
533
+ "answer en Where is the cow standing?",
534
+ "",
535
+ ]
536
+ image1 = Image.open(
537
+ requests.get(
538
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/cow_beach_1.png",
539
+ stream=True,
540
+ ).raw
541
+ )
542
+ image2 = image1
543
+
544
+ inputs = (
545
+ self.processor(images=[image1, image2], text=prompts, return_tensors="pt", padding=True)
546
+ .to(torch.bfloat16)
547
+ .to(torch_device)
548
+ )
549
+ output = model.generate(**inputs, max_new_tokens=20)
550
+
551
+ EXPECTED_DECODED_TEXT = ["answer en Where is the cow standing?\nbeach", "\ncow on the beach"] # fmt: skip
552
+ self.assertEqual(self.processor.batch_decode(output, skip_special_tokens=True), EXPECTED_DECODED_TEXT)
553
+
554
+ def test_small_model_integration_test_paligemma_batched_f16(self):
555
+ # Let' s make sure we test the preprocessing to replace what is used
556
+ model_id = "google/paligemma-3b-pt-224"
557
+ model = PaliGemmaForConditionalGeneration.from_pretrained(
558
+ model_id, revision="float16", torch_dtype=torch.float16
559
+ ).to(torch_device)
560
+ # The first batch is longer in terms of text, the second will be padded.
561
+ prompts = [
562
+ "answer en Where is the cow standing?",
563
+ "",
564
+ ]
565
+ image1 = Image.open(
566
+ requests.get(
567
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/cow_beach_1.png",
568
+ stream=True,
569
+ ).raw
570
+ )
571
+ image2 = image1
572
+
573
+ inputs = (
574
+ self.processor(images=[image1, image2], text=prompts, return_tensors="pt", padding=True)
575
+ .to(torch.float16)
576
+ .to(torch_device)
577
+ )
578
+
579
+ output = model.generate(**inputs, max_new_tokens=20)
580
+
581
+ EXPECTED_DECODED_TEXT = ["answer en Where is the cow standing?\nbeach", "\ncow on the beach"] # fmt: skip
582
+ self.assertEqual(self.processor.batch_decode(output, skip_special_tokens=True), EXPECTED_DECODED_TEXT)
583
+
584
+ def test_integration_detection_bug(self):
585
+ # this is a reproducer of https://github.com/huggingface/transformers/issues/31425 where not enough context
586
+ # impacted negatively segmentation generations.
587
+ model_id = "google/paligemma-3b-pt-224"
588
+ model = PaliGemmaForConditionalGeneration.from_pretrained(
589
+ model_id, revision="bfloat16", torch_dtype=torch.bfloat16
590
+ ).to(torch_device)
591
+ prompt = ("detect shoe",)
592
+
593
+ image = Image.open(
594
+ requests.get(
595
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/shoe.png",
596
+ stream=True,
597
+ ).raw
598
+ )
599
+
600
+ inputs = self.processor(images=image, text=prompt, return_tensors="pt").to(torch.bfloat16).to(torch_device)
601
+
602
+ output = model.generate(**inputs, max_new_tokens=20)
603
+
604
+ EXPECTED_DECODED_TEXT = "detect shoe\n<loc0051><loc0309><loc0708><loc0646> shoe" # fmt: skip
605
+ self.assertEqual(self.processor.decode(output[0], skip_special_tokens=True), EXPECTED_DECODED_TEXT)
606
+
607
+ def test_paligemma_index_error_bug(self):
608
+ # This is a reproducer of https://github.com/huggingface/transformers/pull/28032 and makes sure it does not happen anymore
609
+ # Please refer to that PR, or specifically https://github.com/huggingface/transformers/pull/28032#issuecomment-1860650043 for
610
+ # more details
611
+ model_id = "google/paligemma-3b-pt-224"
612
+ model = PaliGemmaForConditionalGeneration.from_pretrained(model_id)
613
+
614
+ # Simulate a super long prompt
615
+ prompt = "\n" * 200
616
+ image_file = (
617
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/cow_beach_1.png"
618
+ )
619
+
620
+ raw_image = Image.open(requests.get(image_file, stream=True).raw)
621
+ inputs = self.processor(
622
+ images=raw_image,
623
+ text=prompt,
624
+ return_tensors="pt",
625
+ ).to(torch.float16)
626
+
627
+ # Make sure that `generate` works
628
+ _ = model.generate(**inputs, max_new_tokens=20)
629
+
630
+ def test_paligemma_finetuning_with_suffixes_bf16(self):
631
+ # this is a supplementary test to ensure paligemma fine-tuning that relies on token_type_ids is robust to future changes
632
+ model_id = "google/paligemma-3b-pt-224"
633
+ model = PaliGemmaForConditionalGeneration.from_pretrained(
634
+ model_id, revision="bfloat16", torch_dtype=torch.bfloat16
635
+ ).to(torch_device)
636
+ # The first batch is longer in terms of text, the second will be padded.
637
+ prompts = [
638
+ "answer en Where is the cow standing?",
639
+ "",
640
+ ]
641
+
642
+ suffixes = ["beach", "cow standing on the beach"]
643
+ image1 = Image.open(
644
+ requests.get(
645
+ "https://huggingface.co/datasets/hf-internal-testing/fixtures-captioning/resolve/main/cow_beach_1.png",
646
+ stream=True,
647
+ ).raw
648
+ )
649
+ image2 = image1
650
+
651
+ inputs = (
652
+ self.processor(images=[image1, image2], text=prompts, suffix=suffixes, return_tensors="pt", padding=True)
653
+ .to(torch.bfloat16)
654
+ .to(torch_device)
655
+ )
656
+
657
+ expected_labels = torch.tensor(
658
+ [266 * [-100] + [54901, 1], 262 * [-100] + [14706, 9980, 611, 573, 8318, 1]]
659
+ ).to(torch_device)
660
+
661
+ assert torch.equal(inputs["labels"], expected_labels)
662
+
663
+ expected_token_type_ids = torch.tensor([266 * [0] + 2 * [1], 262 * [0] + 6 * [1]]).to(torch_device)
664
+
665
+ assert torch.equal(inputs["token_type_ids"], expected_token_type_ids)
666
+
667
+ output = model(**inputs)
668
+
669
+ # check that loss does not error out
670
+ _ = output.loss
tasks/tasksmith-e0f68dd4420c/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-e0f68dd4420c/tests/source/tests/models/paligemma2/__init__.py ADDED
File without changes
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/paligemma2/test_modeling_paligemma2.py ADDED
@@ -0,0 +1,388 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """Testing suite for the PyTorch PaliGemma model."""
16
+
17
+ import unittest
18
+
19
+ from parameterized import parameterized
20
+
21
+ from transformers import (
22
+ PaliGemmaConfig,
23
+ PaliGemmaForConditionalGeneration,
24
+ is_torch_available,
25
+ is_vision_available,
26
+ )
27
+ from transformers.testing_utils import (
28
+ require_torch,
29
+ torch_device,
30
+ )
31
+
32
+ from ...generation.test_utils import GenerationTesterMixin
33
+ from ...test_configuration_common import ConfigTester
34
+ from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
35
+
36
+
37
+ if is_torch_available():
38
+ import torch
39
+
40
+
41
+ if is_vision_available():
42
+ pass
43
+
44
+
45
+ class PaliGemma2VisionText2TextModelTester:
46
+ def __init__(
47
+ self,
48
+ parent,
49
+ ignore_index=-100,
50
+ image_token_index=0,
51
+ projector_hidden_act="gelu",
52
+ seq_length=25,
53
+ vision_feature_select_strategy="default",
54
+ vision_feature_layer=-1,
55
+ projection_dim=32,
56
+ text_config={
57
+ "model_type": "gemma2",
58
+ "seq_length": 128,
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
+ "num_key_value_heads": 1,
68
+ "head_dim": 8,
69
+ "intermediate_size": 37,
70
+ "hidden_activation": "gelu_pytorch_tanh",
71
+ "hidden_dropout_prob": 0.1,
72
+ "attention_probs_dropout_prob": 0.1,
73
+ "max_position_embeddings": 512,
74
+ "type_vocab_size": 16,
75
+ "type_sequence_label_size": 2,
76
+ "initializer_range": 0.02,
77
+ "num_labels": 3,
78
+ "num_choices": 4,
79
+ "pad_token_id": 1,
80
+ },
81
+ is_training=True,
82
+ vision_config={
83
+ "use_labels": True,
84
+ "image_size": 20,
85
+ "patch_size": 5,
86
+ "num_image_tokens": 4,
87
+ "num_channels": 3,
88
+ "is_training": True,
89
+ "hidden_size": 32,
90
+ "projection_dim": 32,
91
+ "num_key_value_heads": 1,
92
+ "num_hidden_layers": 2,
93
+ "num_attention_heads": 4,
94
+ "intermediate_size": 37,
95
+ "dropout": 0.1,
96
+ "attention_dropout": 0.1,
97
+ "initializer_range": 0.02,
98
+ },
99
+ use_cache=False,
100
+ ):
101
+ self.parent = parent
102
+ self.ignore_index = ignore_index
103
+ # `image_token_index` is set to 0 to pass "resize_embeddings" test, do not modify
104
+ self.image_token_index = image_token_index
105
+ self.projector_hidden_act = projector_hidden_act
106
+ self.vision_feature_select_strategy = vision_feature_select_strategy
107
+ self.vision_feature_layer = vision_feature_layer
108
+ self.text_config = text_config
109
+ self.vision_config = vision_config
110
+ self.seq_length = seq_length
111
+ self.projection_dim = projection_dim
112
+ self.pad_token_id = text_config["pad_token_id"]
113
+
114
+ self.num_hidden_layers = text_config["num_hidden_layers"]
115
+ self.vocab_size = text_config["vocab_size"]
116
+ self.hidden_size = text_config["hidden_size"]
117
+ self.num_attention_heads = text_config["num_attention_heads"]
118
+ self.is_training = is_training
119
+
120
+ self.batch_size = 3
121
+ self.num_channels = vision_config["num_channels"]
122
+ self.image_size = vision_config["image_size"]
123
+ self.encoder_seq_length = seq_length
124
+ self.use_cache = use_cache
125
+
126
+ def get_config(self):
127
+ return PaliGemmaConfig(
128
+ text_config=self.text_config,
129
+ vision_config=self.vision_config,
130
+ ignore_index=self.ignore_index,
131
+ image_token_index=self.image_token_index,
132
+ projector_hidden_act=self.projector_hidden_act,
133
+ projection_dim=self.projection_dim,
134
+ vision_feature_select_strategy=self.vision_feature_select_strategy,
135
+ vision_feature_layer=self.vision_feature_layer,
136
+ )
137
+
138
+ def prepare_config_and_inputs(self):
139
+ pixel_values = floats_tensor(
140
+ [
141
+ self.batch_size,
142
+ self.vision_config["num_channels"],
143
+ self.vision_config["image_size"],
144
+ self.vision_config["image_size"],
145
+ ]
146
+ )
147
+ config = self.get_config()
148
+
149
+ return config, pixel_values
150
+
151
+ def prepare_config_and_inputs_for_common(self):
152
+ config_and_inputs = self.prepare_config_and_inputs()
153
+ config, pixel_values = config_and_inputs
154
+ input_ids = ids_tensor([self.batch_size, self.seq_length], config.text_config.vocab_size - 1) + 1
155
+ attention_mask = input_ids.ne(self.pad_token_id).to(torch_device)
156
+
157
+ # set the 16 first tokens to be image, and ensure that no other tokens are image tokens
158
+ # do not change this unless you modified image size or patch size
159
+ input_ids[input_ids == config.image_token_index] = self.pad_token_id
160
+ input_ids[:, :16] = config.image_token_index
161
+ inputs_dict = {
162
+ "pixel_values": pixel_values,
163
+ "input_ids": input_ids,
164
+ "attention_mask": attention_mask,
165
+ "labels": input_ids,
166
+ "token_type_ids": torch.zeros_like(input_ids),
167
+ }
168
+ return config, inputs_dict
169
+
170
+
171
+ @require_torch
172
+ class PaliGemma2ForConditionalGenerationModelTest(ModelTesterMixin, GenerationTesterMixin, unittest.TestCase):
173
+ """
174
+ Model tester for `PaliGemmaForConditionalGeneration`.
175
+ """
176
+
177
+ all_model_classes = (PaliGemmaForConditionalGeneration,) if is_torch_available() else ()
178
+ pipeline_model_mapping = {"image-text-to-text": PaliGemmaForConditionalGeneration}
179
+ fx_compatible = False
180
+ test_pruning = False
181
+ test_torchscript = False
182
+ test_head_masking = False
183
+ _is_composite = True
184
+
185
+ def setUp(self):
186
+ self.model_tester = PaliGemma2VisionText2TextModelTester(self)
187
+ self.config_tester = ConfigTester(self, config_class=PaliGemmaConfig, has_text_modality=False)
188
+
189
+ # overwrite inputs_embeds tests because we need to delete "pixel values" for LVLMs
190
+ def test_inputs_embeds(self):
191
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
192
+
193
+ for model_class in self.all_model_classes:
194
+ model = model_class(config)
195
+ model.to(torch_device)
196
+ model.eval()
197
+
198
+ inputs = self._prepare_for_class(inputs_dict, model_class)
199
+
200
+ input_ids = inputs["input_ids"]
201
+ del inputs["input_ids"]
202
+ del inputs["pixel_values"]
203
+
204
+ wte = model.get_input_embeddings()
205
+ inputs["inputs_embeds"] = wte(input_ids)
206
+
207
+ with torch.no_grad():
208
+ model(**inputs)
209
+
210
+ # overwrite inputs_embeds tests because we need to delete "pixel values" for LVLMs
211
+ # while some other models require pixel_values to be present
212
+ def test_inputs_embeds_matches_input_ids(self):
213
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
214
+
215
+ for model_class in self.all_model_classes:
216
+ model = model_class(config)
217
+ model.to(torch_device)
218
+ model.eval()
219
+
220
+ inputs = self._prepare_for_class(inputs_dict, model_class)
221
+ input_ids = inputs["input_ids"]
222
+ del inputs["input_ids"]
223
+ del inputs["pixel_values"]
224
+
225
+ inputs_embeds = model.get_input_embeddings()(input_ids)
226
+
227
+ with torch.no_grad():
228
+ out_ids = model(input_ids=input_ids, **inputs)[0]
229
+ out_embeds = model(inputs_embeds=inputs_embeds, **inputs)[0]
230
+ torch.testing.assert_close(out_embeds, out_ids)
231
+
232
+ # Copied from tests.models.llava.test_modeling_llava.LlavaForConditionalGenerationModelTest.test_mismatching_num_image_tokens
233
+ def test_mismatching_num_image_tokens(self):
234
+ """
235
+ Tests that VLMs through an error with explicit message saying what is wrong
236
+ when number of images don't match number of image tokens in the text.
237
+ Also we need to test multi-image cases when one prompr has multiple image tokens.
238
+ """
239
+ config, input_dict = self.model_tester.prepare_config_and_inputs_for_common()
240
+ for model_class in self.all_model_classes:
241
+ model = model_class(config).to(torch_device)
242
+ _ = model(**input_dict) # successfull forward with no modifications
243
+
244
+ # remove one image but leave the image token in text
245
+ input_dict["pixel_values"] = input_dict["pixel_values"][-1:, ...]
246
+ with self.assertRaises(ValueError):
247
+ _ = model(**input_dict)
248
+
249
+ # simulate multi-image case by concatenating inputs where each has exactly one image/image-token
250
+ input_ids = input_dict["input_ids"][:1]
251
+ pixel_values = input_dict["pixel_values"][:1]
252
+ input_ids = torch.cat([input_ids, input_ids], dim=0)
253
+
254
+ # one image and two image tokens raise an error
255
+ with self.assertRaises(ValueError):
256
+ _ = model(input_ids=input_ids, pixel_values=pixel_values)
257
+
258
+ # two images and two image tokens don't raise an error
259
+ pixel_values = torch.cat([pixel_values, pixel_values], dim=0)
260
+ _ = model(input_ids=input_ids, pixel_values=pixel_values)
261
+
262
+ @unittest.skip(
263
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
264
+ )
265
+ def test_training_gradient_checkpointing(self):
266
+ pass
267
+
268
+ @unittest.skip(
269
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
270
+ )
271
+ def test_training_gradient_checkpointing_use_reentrant(self):
272
+ pass
273
+
274
+ @unittest.skip(
275
+ reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
276
+ )
277
+ def test_training_gradient_checkpointing_use_reentrant_false(self):
278
+ pass
279
+
280
+ @unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.")
281
+ def test_cpu_offload(self):
282
+ pass
283
+
284
+ @unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.")
285
+ def test_disk_offload_bin(self):
286
+ pass
287
+
288
+ @unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.")
289
+ def test_disk_offload_safetensors(self):
290
+ pass
291
+
292
+ @unittest.skip(reason="Some undefined behavior encountered with test versions of this model. Skip for now.")
293
+ def test_model_parallelism(self):
294
+ pass
295
+
296
+ @unittest.skip(
297
+ reason="PaliGemmma's SigLip encoder uses the same initialization scheme as the Flax original implementation"
298
+ )
299
+ def test_initialization(self):
300
+ pass
301
+
302
+ # TODO extend valid outputs to include this test @Molbap
303
+ @unittest.skip(reason="PaliGemma has currently one output format.")
304
+ def test_model_outputs_equivalence(self):
305
+ pass
306
+
307
+ # TODO fix the loss = nan in the testing configuration chosen @Molbap
308
+ @unittest.skip(reason="Edge case giving loss nan values in testing configuration.")
309
+ def test_determinism(self):
310
+ pass
311
+
312
+ @unittest.skip(reason="PaliGemma does not use feedforward chunking.")
313
+ def test_feed_forward_chunking(self):
314
+ pass
315
+
316
+ @unittest.skip(reason="PaliGemma does not support low_cpu_mem_usage.")
317
+ def test_save_load_low_cpu_mem_usage(self):
318
+ pass
319
+
320
+ @unittest.skip(reason="PaliGemma does not support low_cpu_mem_usage.")
321
+ def test_save_load_low_cpu_mem_usage_checkpoints(self):
322
+ pass
323
+
324
+ @unittest.skip(reason="PaliGemma does not support low_cpu_mem_usage.")
325
+ def test_save_load_low_cpu_mem_usage_no_safetensors(self):
326
+ pass
327
+
328
+ @unittest.skip(
329
+ 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"
330
+ )
331
+ def test_generate_from_inputs_embeds_with_static_cache(self):
332
+ pass
333
+
334
+ @unittest.skip("FlashAttention only support fp16 and bf16 data type")
335
+ def test_flash_attn_2_fp32_ln(self):
336
+ pass
337
+
338
+ @unittest.skip(
339
+ "VLMs need lots of steps to prepare images/mask correctly to get pad-free inputs. Can be tested as part of LLM test"
340
+ )
341
+ def test_flash_attention_2_padding_matches_padding_free_with_position_ids(self):
342
+ pass
343
+
344
+ # TODO (joao, raushan): fix me -- the problem is in `cache_position[0] == 0`, i.e. dynamic control flow
345
+ @unittest.skip("PaliGemma is not compatible with end-to-end generation compilation")
346
+ def test_generate_compile_model_forward(self):
347
+ pass
348
+
349
+ @unittest.skip("Low memory will be removed soon so no need to fix it")
350
+ def test_beam_search_low_memory(self):
351
+ pass
352
+
353
+ @parameterized.expand([("random",), ("same",)])
354
+ @unittest.skip("Gemma2 has HybridCache which is not compatible with assisted decoding")
355
+ def test_assisted_decoding_matches_greedy_search(self, assistant_type):
356
+ pass
357
+
358
+ @unittest.skip("Gemma2 has HybridCache which is not compatible with assisted decoding")
359
+ def test_prompt_lookup_decoding_matches_greedy_search(self, assistant_type):
360
+ pass
361
+
362
+ @unittest.skip("Gemma2 has HybridCache which is not compatible with assisted decoding")
363
+ def test_assisted_decoding_sample(self):
364
+ pass
365
+
366
+ @unittest.skip("Gemma2 has HybridCache which is not compatible with dola decoding")
367
+ def test_dola_decoding_sample(self):
368
+ pass
369
+
370
+ @unittest.skip("Gemma2 has HybridCache and doesn't support continue from past kv")
371
+ def test_generate_continue_from_past_key_values(self):
372
+ pass
373
+
374
+ @unittest.skip("Gemma2 has HybridCache and doesn't support contrastive generation")
375
+ def test_contrastive_generate(self):
376
+ pass
377
+
378
+ @unittest.skip("Gemma2 has HybridCache and doesn't support contrastive generation")
379
+ def test_contrastive_generate_dict_outputs_use_cache(self):
380
+ pass
381
+
382
+ @unittest.skip("Gemma2 has HybridCache and doesn't support contrastive generation")
383
+ def test_contrastive_generate_low_memory(self):
384
+ pass
385
+
386
+ @unittest.skip("Gemma2 has HybridCache and doesn't support StaticCache")
387
+ def test_generate_with_static_cache(self):
388
+ pass
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/patchtsmixer/__init__.py ADDED
File without changes
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/patchtsmixer/test_modeling_patchtsmixer.py ADDED
@@ -0,0 +1,1115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ pipeline_model_mapping = {"feature-extraction": PatchTSMixerModel} if is_torch_available() else {}
223
+ is_encoder_decoder = False
224
+ test_pruning = False
225
+ test_head_masking = False
226
+ test_missing_keys = False
227
+ test_torchscript = False
228
+ test_inputs_embeds = False
229
+
230
+ test_resize_embeddings = True
231
+ test_resize_position_embeddings = False
232
+ test_mismatched_shapes = True
233
+ test_model_parallel = False
234
+ has_attentions = False
235
+
236
+ def setUp(self):
237
+ self.model_tester = PatchTSMixerModelTester()
238
+ self.config_tester = ConfigTester(
239
+ self,
240
+ config_class=PatchTSMixerConfig,
241
+ has_text_modality=False,
242
+ prediction_length=self.model_tester.prediction_length,
243
+ common_properties=["hidden_size", "expansion_factor", "num_hidden_layers"],
244
+ )
245
+
246
+ def test_config(self):
247
+ self.config_tester.run_common_tests()
248
+
249
+ def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
250
+ inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
251
+
252
+ if model_class == PatchTSMixerForPrediction:
253
+ rng = random.Random(self.model_tester.seed_number)
254
+ labels = floats_tensor(
255
+ [
256
+ self.model_tester.batch_size,
257
+ self.model_tester.prediction_length,
258
+ self.model_tester.num_input_channels,
259
+ ],
260
+ rng=rng,
261
+ )
262
+ inputs_dict["future_values"] = labels
263
+ elif model_class in get_values(MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING):
264
+ rng = random.Random(self.model_tester.seed_number)
265
+ labels = ids_tensor([self.model_tester.batch_size], self.model_tester.num_targets, rng=rng)
266
+ inputs_dict["target_values"] = labels
267
+ elif model_class in get_values(MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING):
268
+ rng = random.Random(self.model_tester.seed_number)
269
+ labels = floats_tensor([self.model_tester.batch_size, self.model_tester.num_targets], rng=rng)
270
+ inputs_dict["target_values"] = labels
271
+
272
+ inputs_dict["output_hidden_states"] = True
273
+ return inputs_dict
274
+
275
+ def test_save_load_strict(self):
276
+ config, _ = self.model_tester.prepare_config_and_inputs()
277
+ for model_class in self.all_model_classes:
278
+ model = model_class(config)
279
+
280
+ with tempfile.TemporaryDirectory() as tmpdirname:
281
+ model.save_pretrained(tmpdirname)
282
+ model2, info = model_class.from_pretrained(tmpdirname, output_loading_info=True)
283
+ self.assertEqual(info["missing_keys"], [])
284
+
285
+ def test_hidden_states_output(self):
286
+ def check_hidden_states_output(inputs_dict, config, model_class):
287
+ model = model_class(config)
288
+ model.to(torch_device)
289
+ model.eval()
290
+
291
+ with torch.no_grad():
292
+ outputs = model(**self._prepare_for_class(inputs_dict, model_class))
293
+
294
+ hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
295
+
296
+ expected_num_layers = getattr(
297
+ self.model_tester,
298
+ "expected_num_hidden_layers",
299
+ self.model_tester.num_hidden_layers,
300
+ )
301
+ self.assertEqual(len(hidden_states), expected_num_layers)
302
+
303
+ expected_hidden_size = self.model_tester.hidden_size
304
+ self.assertEqual(hidden_states[0].shape[-1], expected_hidden_size)
305
+
306
+ num_patch = self.model_tester.num_patches
307
+ self.assertListEqual(
308
+ list(hidden_states[0].shape[-2:]),
309
+ [num_patch, self.model_tester.hidden_size],
310
+ )
311
+
312
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
313
+
314
+ for model_class in self.all_model_classes:
315
+ check_hidden_states_output(inputs_dict, config, model_class)
316
+
317
+ @unittest.skip(reason="No tokens embeddings")
318
+ def test_resize_tokens_embeddings(self):
319
+ pass
320
+
321
+ def test_model_outputs_equivalence(self):
322
+ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
323
+
324
+ def set_nan_tensor_to_zero(t):
325
+ t[t != t] = 0
326
+ return t
327
+
328
+ def check_equivalence(model, tuple_inputs, dict_inputs, additional_kwargs={}):
329
+ with torch.no_grad():
330
+ tuple_output = model(**tuple_inputs, return_dict=False, **additional_kwargs)
331
+ output_ = model(**dict_inputs, return_dict=True, **additional_kwargs)
332
+ attributes_ = vars(output_)
333
+ dict_output = tuple(attributes_.values())
334
+
335
+ def recursive_check(tuple_object, dict_object):
336
+ if isinstance(tuple_object, (List, Tuple)):
337
+ for tuple_iterable_value, dict_iterable_value in zip(tuple_object, dict_object):
338
+ recursive_check(tuple_iterable_value, dict_iterable_value)
339
+ elif isinstance(tuple_object, Dict):
340
+ for tuple_iterable_value, dict_iterable_value in zip(
341
+ tuple_object.values(), dict_object.values()
342
+ ):
343
+ recursive_check(tuple_iterable_value, dict_iterable_value)
344
+ elif tuple_object is None:
345
+ return
346
+ else:
347
+ self.assertTrue(
348
+ torch.allclose(
349
+ set_nan_tensor_to_zero(tuple_object),
350
+ set_nan_tensor_to_zero(dict_object),
351
+ atol=1e-5,
352
+ ),
353
+ msg=(
354
+ "Tuple and dict output are not equal. Difference:"
355
+ f" {torch.max(torch.abs(tuple_object - dict_object))}. Tuple has `nan`:"
356
+ f" {torch.isnan(tuple_object).any()} and `inf`: {torch.isinf(tuple_object)}. Dict has"
357
+ f" `nan`: {torch.isnan(dict_object).any()} and `inf`: {torch.isinf(dict_object)}."
358
+ ),
359
+ )
360
+
361
+ recursive_check(tuple_output, dict_output)
362
+
363
+ for model_class in self.all_model_classes:
364
+ print(model_class)
365
+ model = model_class(config)
366
+ model.to(torch_device)
367
+ model.eval()
368
+
369
+ tuple_inputs = self._prepare_for_class(inputs_dict, model_class)
370
+ dict_inputs = self._prepare_for_class(inputs_dict, model_class)
371
+
372
+ check_equivalence(model, tuple_inputs, dict_inputs)
373
+
374
+ tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
375
+ dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
376
+ check_equivalence(model, tuple_inputs, dict_inputs)
377
+
378
+ tuple_inputs = self._prepare_for_class(inputs_dict, model_class)
379
+ dict_inputs = self._prepare_for_class(inputs_dict, model_class)
380
+ tuple_inputs.update({"output_hidden_states": False})
381
+ dict_inputs.update({"output_hidden_states": False})
382
+ check_equivalence(model, tuple_inputs, dict_inputs)
383
+
384
+ tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
385
+ dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True)
386
+ tuple_inputs.update({"output_hidden_states": False})
387
+ dict_inputs.update({"output_hidden_states": False})
388
+ check_equivalence(
389
+ model,
390
+ tuple_inputs,
391
+ dict_inputs,
392
+ )
393
+
394
+ def test_model_main_input_name(self):
395
+ model_signature = inspect.signature(getattr(PatchTSMixerModel, "forward"))
396
+ # The main input is the name of the argument after `self`
397
+ observed_main_input_name = list(model_signature.parameters.keys())[1]
398
+ self.assertEqual(PatchTSMixerModel.main_input_name, observed_main_input_name)
399
+
400
+ def test_forward_signature(self):
401
+ config, _ = self.model_tester.prepare_config_and_inputs_for_common()
402
+
403
+ for model_class in self.all_model_classes:
404
+ model = model_class(config)
405
+ signature = inspect.signature(model.forward)
406
+ # signature.parameters is an OrderedDict => so arg_names order is deterministic
407
+ arg_names = [*signature.parameters.keys()]
408
+
409
+ if model_class == PatchTSMixerForPretraining:
410
+ expected_arg_names = [
411
+ "past_values",
412
+ "observed_mask",
413
+ "output_hidden_states",
414
+ "return_loss",
415
+ ]
416
+ elif model_class == PatchTSMixerModel:
417
+ expected_arg_names = [
418
+ "past_values",
419
+ "observed_mask",
420
+ "output_hidden_states",
421
+ ]
422
+ elif model_class in get_values(MODEL_FOR_TIME_SERIES_CLASSIFICATION_MAPPING) or model_class in get_values(
423
+ MODEL_FOR_TIME_SERIES_REGRESSION_MAPPING
424
+ ):
425
+ expected_arg_names = [
426
+ "past_values",
427
+ "target_values",
428
+ "output_hidden_states",
429
+ "return_loss",
430
+ ]
431
+ else:
432
+ # PatchTSMixerForPrediction
433
+ expected_arg_names = [
434
+ "past_values",
435
+ "observed_mask",
436
+ "future_values",
437
+ "output_hidden_states",
438
+ "return_loss",
439
+ ]
440
+
441
+ self.assertListEqual(arg_names[: len(expected_arg_names)], expected_arg_names)
442
+
443
+ @is_flaky()
444
+ def test_retain_grad_hidden_states_attentions(self):
445
+ super().test_retain_grad_hidden_states_attentions()
446
+
447
+ @unittest.skip(reason="Model does not have input embeddings")
448
+ def test_model_get_set_embeddings(self):
449
+ pass
450
+
451
+
452
+ def prepare_batch(repo_id="ibm/patchtsmixer-etth1-test-data", file="pretrain_batch.pt"):
453
+ # TODO: Make repo public
454
+ file = hf_hub_download(repo_id=repo_id, filename=file, repo_type="dataset")
455
+ batch = torch.load(file, map_location=torch_device)
456
+ return batch
457
+
458
+
459
+ @require_torch
460
+ @slow
461
+ class PatchTSMixerModelIntegrationTests(unittest.TestCase):
462
+ def test_pretrain_head(self):
463
+ model = PatchTSMixerForPretraining.from_pretrained("ibm/patchtsmixer-etth1-pretrain").to(torch_device)
464
+ batch = prepare_batch()
465
+
466
+ torch.manual_seed(0)
467
+ with torch.no_grad():
468
+ output = model(past_values=batch["past_values"].to(torch_device)).prediction_outputs
469
+ num_patch = (
470
+ max(model.config.context_length, model.config.patch_length) - model.config.patch_length
471
+ ) // model.config.patch_stride + 1
472
+ expected_shape = torch.Size(
473
+ [
474
+ 64,
475
+ model.config.num_input_channels,
476
+ num_patch,
477
+ model.config.patch_length,
478
+ ]
479
+ )
480
+ self.assertEqual(output.shape, expected_shape)
481
+
482
+ expected_slice = torch.tensor([[[[-0.9106]],[[1.5326]],[[-0.8245]],[[0.7439]],[[-0.7830]],[[2.6256]],[[-0.6485]],]],device=torch_device) # fmt: skip
483
+ torch.testing.assert_close(output[0, :7, :1, :1], expected_slice, rtol=TOLERANCE, atol=TOLERANCE)
484
+
485
+ def test_forecasting_head(self):
486
+ model = PatchTSMixerForPrediction.from_pretrained("ibm/patchtsmixer-etth1-forecasting").to(torch_device)
487
+ batch = prepare_batch(file="forecast_batch.pt")
488
+
489
+ model.eval()
490
+ torch.manual_seed(0)
491
+ with torch.no_grad():
492
+ output = model(
493
+ past_values=batch["past_values"].to(torch_device),
494
+ future_values=batch["future_values"].to(torch_device),
495
+ ).prediction_outputs
496
+
497
+ expected_shape = torch.Size([64, model.config.prediction_length, model.config.num_input_channels])
498
+ self.assertEqual(output.shape, expected_shape)
499
+
500
+ expected_slice = torch.tensor(
501
+ [[0.2471, 0.5036, 0.3596, 0.5401, -0.0985, 0.3423, -0.8439]],
502
+ device=torch_device,
503
+ )
504
+ torch.testing.assert_close(output[0, :1, :7], expected_slice, rtol=TOLERANCE, atol=TOLERANCE)
505
+
506
+ def test_prediction_generation(self):
507
+ model = PatchTSMixerForPrediction.from_pretrained("ibm/patchtsmixer-etth1-generate").to(torch_device)
508
+ batch = prepare_batch(file="forecast_batch.pt")
509
+ print(batch["past_values"])
510
+
511
+ torch.manual_seed(0)
512
+ model.eval()
513
+ with torch.no_grad():
514
+ outputs = model.generate(past_values=batch["past_values"].to(torch_device))
515
+ expected_shape = torch.Size((64, 1, model.config.prediction_length, model.config.num_input_channels))
516
+
517
+ self.assertEqual(outputs.sequences.shape, expected_shape)
518
+
519
+ expected_slice = torch.tensor(
520
+ [[0.4308, -0.4731, 1.3512, -0.1038, -0.4655, 1.1279, -0.7179]],
521
+ device=torch_device,
522
+ )
523
+
524
+ mean_prediction = outputs.sequences.mean(dim=1)
525
+
526
+ torch.testing.assert_close(mean_prediction[0, -1:], expected_slice, rtol=TOLERANCE, atol=TOLERANCE)
527
+
528
+
529
+ @require_torch
530
+ class PatchTSMixerFunctionalTests(unittest.TestCase):
531
+ @classmethod
532
+ def setUpClass(cls):
533
+ """Setup method: Called once before test-cases execution"""
534
+ cls.params = {}
535
+ cls.params.update(
536
+ context_length=32,
537
+ patch_length=8,
538
+ num_input_channels=3,
539
+ patch_stride=8,
540
+ d_model=4,
541
+ expansion_factor=2,
542
+ num_layers=3,
543
+ dropout=0.2,
544
+ mode="common_channel", # common_channel, mix_channel
545
+ gated_attn=True,
546
+ norm_mlp="LayerNorm",
547
+ mask_type="random",
548
+ random_mask_ratio=0.5,
549
+ mask_patches=[2, 3],
550
+ forecast_mask_ratios=[1, 1],
551
+ mask_value=0,
552
+ masked_loss=True,
553
+ channel_consistent_masking=True,
554
+ head_dropout=0.2,
555
+ prediction_length=64,
556
+ out_channels=None,
557
+ # num_labels=3,
558
+ num_targets=3,
559
+ output_range=None,
560
+ head_aggregation=None,
561
+ scaling="std",
562
+ use_positional_encoding=False,
563
+ positional_encoding="sincos",
564
+ self_attn=False,
565
+ self_attn_heads=1,
566
+ num_parallel_samples=4,
567
+ )
568
+
569
+ cls.num_patches = (
570
+ max(cls.params["context_length"], cls.params["patch_length"]) - cls.params["patch_length"]
571
+ ) // cls.params["patch_stride"] + 1
572
+
573
+ # batch_size = 32
574
+ batch_size = 2
575
+
576
+ int(cls.params["prediction_length"] / cls.params["patch_length"])
577
+
578
+ cls.data = torch.rand(
579
+ batch_size,
580
+ cls.params["context_length"],
581
+ cls.params["num_input_channels"],
582
+ )
583
+
584
+ cls.enc_data = torch.rand(
585
+ batch_size,
586
+ cls.params["num_input_channels"],
587
+ cls.num_patches,
588
+ cls.params["patch_length"],
589
+ )
590
+
591
+ cls.enc_output = torch.rand(
592
+ batch_size,
593
+ cls.params["num_input_channels"],
594
+ cls.num_patches,
595
+ cls.params["d_model"],
596
+ )
597
+
598
+ cls.flat_enc_output = torch.rand(
599
+ batch_size,
600
+ cls.num_patches,
601
+ cls.params["d_model"],
602
+ )
603
+
604
+ cls.correct_pred_output = torch.rand(
605
+ batch_size,
606
+ cls.params["prediction_length"],
607
+ cls.params["num_input_channels"],
608
+ )
609
+ cls.correct_regression_output = torch.rand(batch_size, cls.params["num_targets"])
610
+
611
+ cls.correct_pretrain_output = torch.rand(
612
+ batch_size,
613
+ cls.params["num_input_channels"],
614
+ cls.num_patches,
615
+ cls.params["patch_length"],
616
+ )
617
+
618
+ cls.correct_forecast_output = torch.rand(
619
+ batch_size,
620
+ cls.params["prediction_length"],
621
+ cls.params["num_input_channels"],
622
+ )
623
+
624
+ cls.correct_sel_forecast_output = torch.rand(batch_size, cls.params["prediction_length"], 2)
625
+
626
+ cls.correct_classification_output = torch.rand(
627
+ batch_size,
628
+ cls.params["num_targets"],
629
+ )
630
+
631
+ cls.correct_classification_classes = torch.randint(0, cls.params["num_targets"], (batch_size,))
632
+
633
+ def test_patchtsmixer_encoder(self):
634
+ config = PatchTSMixerConfig(**self.__class__.params)
635
+ enc = PatchTSMixerEncoder(config)
636
+ output = enc(self.__class__.enc_data)
637
+ self.assertEqual(output.last_hidden_state.shape, self.__class__.enc_output.shape)
638
+
639
+ def test_patchmodel(self):
640
+ config = PatchTSMixerConfig(**self.__class__.params)
641
+ mdl = PatchTSMixerModel(config)
642
+ output = mdl(self.__class__.data)
643
+ self.assertEqual(output.last_hidden_state.shape, self.__class__.enc_output.shape)
644
+ self.assertEqual(output.patch_input.shape, self.__class__.enc_data.shape)
645
+
646
+ def test_pretrainhead(self):
647
+ config = PatchTSMixerConfig(**self.__class__.params)
648
+ head = PatchTSMixerPretrainHead(
649
+ config=config,
650
+ )
651
+ output = head(self.__class__.enc_output)
652
+
653
+ self.assertEqual(output.shape, self.__class__.correct_pretrain_output.shape)
654
+
655
+ def test_pretrain_full(self):
656
+ config = PatchTSMixerConfig(**self.__class__.params)
657
+ mdl = PatchTSMixerForPretraining(config)
658
+ output = mdl(self.__class__.data)
659
+ self.assertEqual(
660
+ output.prediction_outputs.shape,
661
+ self.__class__.correct_pretrain_output.shape,
662
+ )
663
+ self.assertEqual(output.last_hidden_state.shape, self.__class__.enc_output.shape)
664
+ self.assertEqual(output.loss.item() < np.inf, True)
665
+
666
+ def test_pretrain_full_with_return_dict(self):
667
+ config = PatchTSMixerConfig(**self.__class__.params)
668
+ mdl = PatchTSMixerForPretraining(config)
669
+ output = mdl(self.__class__.data, return_dict=False)
670
+ self.assertEqual(output[1].shape, self.__class__.correct_pretrain_output.shape)
671
+ self.assertEqual(output[2].shape, self.__class__.enc_output.shape)
672
+ self.assertEqual(output[0].item() < np.inf, True)
673
+
674
+ def test_forecast_head(self):
675
+ config = PatchTSMixerConfig(**self.__class__.params)
676
+ head = PatchTSMixerForPredictionHead(
677
+ config=config,
678
+ )
679
+ # output = head(self.__class__.enc_output, raw_data = self.__class__.correct_pretrain_output)
680
+ output = head(self.__class__.enc_output)
681
+
682
+ self.assertEqual(output.shape, self.__class__.correct_forecast_output.shape)
683
+
684
+ def check_module(
685
+ self,
686
+ task,
687
+ params=None,
688
+ output_hidden_states=True,
689
+ ):
690
+ config = PatchTSMixerConfig(**params)
691
+ if task == "forecast":
692
+ mdl = PatchTSMixerForPrediction(config)
693
+ target_input = self.__class__.correct_forecast_output
694
+ if config.prediction_channel_indices is not None:
695
+ target_output = self.__class__.correct_sel_forecast_output
696
+ else:
697
+ target_output = target_input
698
+ ref_samples = target_output.unsqueeze(1).expand(-1, config.num_parallel_samples, -1, -1)
699
+ ground_truth_arg = "future_values"
700
+ output_predictions_arg = "prediction_outputs"
701
+ elif task == "classification":
702
+ mdl = PatchTSMixerForTimeSeriesClassification(config)
703
+ target_input = self.__class__.correct_classification_classes
704
+ target_output = self.__class__.correct_classification_output
705
+ ground_truth_arg = "target_values"
706
+ output_predictions_arg = "prediction_outputs"
707
+ elif task == "regression":
708
+ mdl = PatchTSMixerForRegression(config)
709
+ target_input = self.__class__.correct_regression_output
710
+ target_output = self.__class__.correct_regression_output
711
+ ref_samples = target_output.unsqueeze(1).expand(-1, config.num_parallel_samples, -1)
712
+ ground_truth_arg = "target_values"
713
+ output_predictions_arg = "regression_outputs"
714
+ elif task == "pretrain":
715
+ mdl = PatchTSMixerForPretraining(config)
716
+ target_input = None
717
+ target_output = self.__class__.correct_pretrain_output
718
+ ground_truth_arg = None
719
+ output_predictions_arg = "prediction_outputs"
720
+ else:
721
+ print("invalid task")
722
+
723
+ enc_output = self.__class__.enc_output
724
+
725
+ if target_input is None:
726
+ output = mdl(self.__class__.data, output_hidden_states=output_hidden_states)
727
+ else:
728
+ output = mdl(
729
+ self.__class__.data,
730
+ **{
731
+ ground_truth_arg: target_input,
732
+ "output_hidden_states": output_hidden_states,
733
+ },
734
+ )
735
+
736
+ prediction_outputs = getattr(output, output_predictions_arg)
737
+ if isinstance(prediction_outputs, tuple):
738
+ for t in prediction_outputs:
739
+ self.assertEqual(t.shape, target_output.shape)
740
+ else:
741
+ self.assertEqual(prediction_outputs.shape, target_output.shape)
742
+
743
+ self.assertEqual(output.last_hidden_state.shape, enc_output.shape)
744
+
745
+ if output_hidden_states is True:
746
+ self.assertEqual(len(output.hidden_states), params["num_layers"])
747
+
748
+ else:
749
+ self.assertEqual(output.hidden_states, None)
750
+
751
+ self.assertEqual(output.loss.item() < np.inf, True)
752
+
753
+ if config.loss == "nll" and task in ["forecast", "regression"]:
754
+ samples = mdl.generate(self.__class__.data)
755
+ self.assertEqual(samples.sequences.shape, ref_samples.shape)
756
+
757
+ @parameterized.expand(
758
+ list(
759
+ itertools.product(
760
+ ["common_channel", "mix_channel"],
761
+ [True, False],
762
+ [True, False, "mean", "std"],
763
+ [True, False],
764
+ [None, [0, 2]],
765
+ ["mse", "nll"],
766
+ )
767
+ )
768
+ )
769
+ def test_forecast(self, mode, self_attn, scaling, gated_attn, prediction_channel_indices, loss):
770
+ params = self.__class__.params.copy()
771
+ params.update(
772
+ mode=mode,
773
+ self_attn=self_attn,
774
+ scaling=scaling,
775
+ prediction_channel_indices=prediction_channel_indices,
776
+ gated_attn=gated_attn,
777
+ loss=loss,
778
+ )
779
+
780
+ self.check_module(task="forecast", params=params)
781
+
782
+ @parameterized.expand(
783
+ list(
784
+ itertools.product(
785
+ ["common_channel", "mix_channel"],
786
+ [True, False],
787
+ [True, False, "mean", "std"],
788
+ [True, False],
789
+ ["max_pool", "avg_pool"],
790
+ )
791
+ )
792
+ )
793
+ def test_classification(self, mode, self_attn, scaling, gated_attn, head_aggregation):
794
+ params = self.__class__.params.copy()
795
+ params.update(
796
+ mode=mode,
797
+ self_attn=self_attn,
798
+ scaling=scaling,
799
+ head_aggregation=head_aggregation,
800
+ gated_attn=gated_attn,
801
+ )
802
+
803
+ self.check_module(task="classification", params=params)
804
+
805
+ @parameterized.expand(
806
+ list(
807
+ itertools.product(
808
+ ["common_channel", "mix_channel"],
809
+ [True, False],
810
+ [True, False, "mean", "std"],
811
+ [True, False],
812
+ ["max_pool", "avg_pool"],
813
+ ["mse", "nll"],
814
+ )
815
+ )
816
+ )
817
+ def test_regression(self, mode, self_attn, scaling, gated_attn, head_aggregation, loss):
818
+ params = self.__class__.params.copy()
819
+ params.update(
820
+ mode=mode,
821
+ self_attn=self_attn,
822
+ scaling=scaling,
823
+ head_aggregation=head_aggregation,
824
+ gated_attn=gated_attn,
825
+ loss=loss,
826
+ )
827
+
828
+ self.check_module(task="regression", params=params)
829
+
830
+ @parameterized.expand(
831
+ list(
832
+ itertools.product(
833
+ ["common_channel", "mix_channel"],
834
+ [True, False],
835
+ [True, False, "mean", "std"],
836
+ [True, False],
837
+ ["random", "forecast"],
838
+ [True, False],
839
+ [True, False],
840
+ )
841
+ )
842
+ )
843
+ def test_pretrain(
844
+ self,
845
+ mode,
846
+ self_attn,
847
+ scaling,
848
+ gated_attn,
849
+ mask_type,
850
+ masked_loss,
851
+ channel_consistent_masking,
852
+ ):
853
+ params = self.__class__.params.copy()
854
+ params.update(
855
+ mode=mode,
856
+ self_attn=self_attn,
857
+ scaling=scaling,
858
+ gated_attn=gated_attn,
859
+ mask_type=mask_type,
860
+ masked_loss=masked_loss,
861
+ channel_consistent_masking=channel_consistent_masking,
862
+ )
863
+
864
+ self.check_module(task="pretrain", params=params)
865
+
866
+ def forecast_full_module(self, params=None, output_hidden_states=False, return_dict=None):
867
+ config = PatchTSMixerConfig(**params)
868
+ mdl = PatchTSMixerForPrediction(config)
869
+
870
+ target_val = self.__class__.correct_forecast_output
871
+
872
+ if config.prediction_channel_indices is not None:
873
+ target_val = self.__class__.correct_sel_forecast_output
874
+
875
+ enc_output = self.__class__.enc_output
876
+
877
+ output = mdl(
878
+ self.__class__.data,
879
+ future_values=self.__class__.correct_forecast_output,
880
+ output_hidden_states=output_hidden_states,
881
+ return_dict=return_dict,
882
+ )
883
+
884
+ if isinstance(output, tuple):
885
+ output = PatchTSMixerForPredictionOutput(*output)
886
+
887
+ if config.loss == "mse":
888
+ self.assertEqual(output.prediction_outputs.shape, target_val.shape)
889
+
890
+ self.assertEqual(output.last_hidden_state.shape, enc_output.shape)
891
+
892
+ if output_hidden_states is True:
893
+ self.assertEqual(len(output.hidden_states), params["num_layers"])
894
+
895
+ else:
896
+ self.assertEqual(output.hidden_states, None)
897
+
898
+ self.assertEqual(output.loss.item() < np.inf, True)
899
+
900
+ if config.loss == "nll":
901
+ samples = mdl.generate(self.__class__.data)
902
+ ref_samples = target_val.unsqueeze(1).expand(-1, params["num_parallel_samples"], -1, -1)
903
+ self.assertEqual(samples.sequences.shape, ref_samples.shape)
904
+
905
+ def test_forecast_full(self):
906
+ self.check_module(task="forecast", params=self.__class__.params, output_hidden_states=True)
907
+ # self.forecast_full_module(self.__class__.params, output_hidden_states = True)
908
+
909
+ def test_forecast_full_2(self):
910
+ params = self.__class__.params.copy()
911
+ params.update(
912
+ mode="mix_channel",
913
+ )
914
+ self.forecast_full_module(params, output_hidden_states=True)
915
+
916
+ def test_forecast_full_2_with_return_dict(self):
917
+ params = self.__class__.params.copy()
918
+ params.update(
919
+ mode="mix_channel",
920
+ )
921
+ self.forecast_full_module(params, output_hidden_states=True, return_dict=False)
922
+
923
+ def test_forecast_full_3(self):
924
+ params = self.__class__.params.copy()
925
+ params.update(
926
+ mode="mix_channel",
927
+ )
928
+ self.forecast_full_module(params, output_hidden_states=True)
929
+
930
+ def test_forecast_full_5(self):
931
+ params = self.__class__.params.copy()
932
+ params.update(
933
+ self_attn=True,
934
+ use_positional_encoding=True,
935
+ positional_encoding="sincos",
936
+ )
937
+ self.forecast_full_module(params, output_hidden_states=True)
938
+
939
+ def test_forecast_full_4(self):
940
+ params = self.__class__.params.copy()
941
+ params.update(
942
+ mode="mix_channel",
943
+ prediction_channel_indices=[0, 2],
944
+ )
945
+ self.forecast_full_module(params)
946
+
947
+ def test_forecast_full_distributional(self):
948
+ params = self.__class__.params.copy()
949
+ params.update(
950
+ mode="mix_channel",
951
+ prediction_channel_indices=[0, 2],
952
+ loss="nll",
953
+ distribution_output="normal",
954
+ )
955
+
956
+ self.forecast_full_module(params)
957
+
958
+ def test_forecast_full_distributional_2(self):
959
+ params = self.__class__.params.copy()
960
+ params.update(
961
+ mode="mix_channel",
962
+ prediction_channel_indices=[0, 2],
963
+ loss="nll",
964
+ # distribution_output = "normal",
965
+ )
966
+ self.forecast_full_module(params)
967
+
968
+ def test_forecast_full_distributional_3(self):
969
+ params = self.__class__.params.copy()
970
+ params.update(
971
+ mode="mix_channel",
972
+ # prediction_channel_indices=[0, 2],
973
+ loss="nll",
974
+ distribution_output="normal",
975
+ )
976
+ self.forecast_full_module(params)
977
+
978
+ def test_forecast_full_distributional_4(self):
979
+ params = self.__class__.params.copy()
980
+ params.update(
981
+ mode="mix_channel",
982
+ # prediction_channel_indices=[0, 2],
983
+ loss="nll",
984
+ distribution_output="normal",
985
+ )
986
+ self.forecast_full_module(params)
987
+
988
+ def test_classification_head(self):
989
+ config = PatchTSMixerConfig(**self.__class__.params)
990
+ head = PatchTSMixerLinearHead(
991
+ config=config,
992
+ )
993
+ # output = head(self.__class__.enc_output, raw_data = self.__class__.correct_pretrain_output)
994
+ output = head(self.__class__.enc_output)
995
+
996
+ self.assertEqual(output.shape, self.__class__.correct_classification_output.shape)
997
+
998
+ def test_classification_full(self):
999
+ config = PatchTSMixerConfig(**self.__class__.params)
1000
+ mdl = PatchTSMixerForTimeSeriesClassification(config)
1001
+ output = mdl(
1002
+ self.__class__.data,
1003
+ target_values=self.__class__.correct_classification_classes,
1004
+ )
1005
+ self.assertEqual(
1006
+ output.prediction_outputs.shape,
1007
+ self.__class__.correct_classification_output.shape,
1008
+ )
1009
+ self.assertEqual(output.last_hidden_state.shape, self.__class__.enc_output.shape)
1010
+ self.assertEqual(output.loss.item() < np.inf, True)
1011
+
1012
+ def test_classification_full_with_return_dict(self):
1013
+ config = PatchTSMixerConfig(**self.__class__.params)
1014
+ mdl = PatchTSMixerForTimeSeriesClassification(config)
1015
+ output = mdl(
1016
+ self.__class__.data,
1017
+ target_values=self.__class__.correct_classification_classes,
1018
+ return_dict=False,
1019
+ )
1020
+ if isinstance(output, tuple):
1021
+ output = PatchTSMixerForTimeSeriesClassificationOutput(*output)
1022
+ self.assertEqual(
1023
+ output.prediction_outputs.shape,
1024
+ self.__class__.correct_classification_output.shape,
1025
+ )
1026
+ self.assertEqual(output.last_hidden_state.shape, self.__class__.enc_output.shape)
1027
+ self.assertEqual(output.loss.item() < np.inf, True)
1028
+
1029
+ def test_regression_head(self):
1030
+ config = PatchTSMixerConfig(**self.__class__.params)
1031
+ head = PatchTSMixerLinearHead(
1032
+ config=config,
1033
+ )
1034
+ output = head(self.__class__.enc_output)
1035
+ self.assertEqual(output.shape, self.__class__.correct_regression_output.shape)
1036
+
1037
+ def test_regression_full(self):
1038
+ config = PatchTSMixerConfig(**self.__class__.params)
1039
+ mdl = PatchTSMixerForRegression(config)
1040
+ output = mdl(self.__class__.data, target_values=self.__class__.correct_regression_output)
1041
+ self.assertEqual(
1042
+ output.regression_outputs.shape,
1043
+ self.__class__.correct_regression_output.shape,
1044
+ )
1045
+ self.assertEqual(output.last_hidden_state.shape, self.__class__.enc_output.shape)
1046
+ self.assertEqual(output.loss.item() < np.inf, True)
1047
+
1048
+ def test_regression_full_with_return_dict(self):
1049
+ config = PatchTSMixerConfig(**self.__class__.params)
1050
+ mdl = PatchTSMixerForRegression(config)
1051
+ output = mdl(
1052
+ self.__class__.data,
1053
+ target_values=self.__class__.correct_regression_output,
1054
+ return_dict=False,
1055
+ )
1056
+ if isinstance(output, tuple):
1057
+ output = PatchTSMixerForRegressionOutput(*output)
1058
+ self.assertEqual(
1059
+ output.regression_outputs.shape,
1060
+ self.__class__.correct_regression_output.shape,
1061
+ )
1062
+ self.assertEqual(output.last_hidden_state.shape, self.__class__.enc_output.shape)
1063
+ self.assertEqual(output.loss.item() < np.inf, True)
1064
+
1065
+ def test_regression_full_distribute(self):
1066
+ params = self.__class__.params.copy()
1067
+ params.update(loss="nll", distribution_output="normal")
1068
+
1069
+ config = PatchTSMixerConfig(**params)
1070
+
1071
+ mdl = PatchTSMixerForRegression(config)
1072
+ output = mdl(self.__class__.data, target_values=self.__class__.correct_regression_output)
1073
+ self.assertEqual(
1074
+ output.regression_outputs[0].shape,
1075
+ self.__class__.correct_regression_output.shape,
1076
+ )
1077
+ self.assertEqual(
1078
+ output.regression_outputs[1].shape,
1079
+ self.__class__.correct_regression_output.shape,
1080
+ )
1081
+ self.assertEqual(output.last_hidden_state.shape, self.__class__.enc_output.shape)
1082
+ self.assertEqual(output.loss.item() < np.inf, True)
1083
+
1084
+ if config.loss == "nll":
1085
+ samples = mdl.generate(self.__class__.data)
1086
+ ref_samples = self.__class__.correct_regression_output.unsqueeze(1).expand(
1087
+ -1, params["num_parallel_samples"], -1
1088
+ )
1089
+ self.assertEqual(samples.sequences.shape, ref_samples.shape)
1090
+
1091
+ def test_regression_full_distribute_2(self):
1092
+ params = self.__class__.params.copy()
1093
+ params.update(loss="nll", distribution_output="student_t")
1094
+
1095
+ config = PatchTSMixerConfig(**params)
1096
+
1097
+ mdl = PatchTSMixerForRegression(config)
1098
+ output = mdl(self.__class__.data, target_values=self.__class__.correct_regression_output)
1099
+ self.assertEqual(
1100
+ output.regression_outputs[0].shape,
1101
+ self.__class__.correct_regression_output.shape,
1102
+ )
1103
+ self.assertEqual(
1104
+ output.regression_outputs[1].shape,
1105
+ self.__class__.correct_regression_output.shape,
1106
+ )
1107
+ self.assertEqual(output.last_hidden_state.shape, self.__class__.enc_output.shape)
1108
+ self.assertEqual(output.loss.item() < np.inf, True)
1109
+
1110
+ if config.loss == "nll":
1111
+ samples = mdl.generate(self.__class__.data)
1112
+ ref_samples = self.__class__.correct_regression_output.unsqueeze(1).expand(
1113
+ -1, params["num_parallel_samples"], -1
1114
+ )
1115
+ self.assertEqual(samples.sequences.shape, ref_samples.shape)
tasks/tasksmith-e0f68dd4420c/tests/source/tests/models/patchtst/__init__.py ADDED
File without changes