"tests/rembert/test_modeling_rembert.py" did not exist on "c824d15aa1590ddb5d2fc977a8a1009a4b1d7262"
test_onnx_v2.py 17 KB
Newer Older
1
import os
2
3
4
5
6
from pathlib import Path
from tempfile import NamedTemporaryFile
from unittest import TestCase
from unittest.mock import patch

lewtun's avatar
lewtun committed
7
8
import pytest

9
from parameterized import parameterized
10
from transformers import AutoConfig, PreTrainedTokenizerBase, is_tf_available, is_torch_available
11
12
13
from transformers.onnx import (
    EXTERNAL_DATA_FORMAT_SIZE_LIMIT,
    OnnxConfig,
lewtun's avatar
lewtun committed
14
    OnnxConfigWithPast,
15
16
17
18
    ParameterFormat,
    export,
    validate_model_outputs,
)
19
20
21
22
23
from transformers.onnx.utils import (
    compute_effective_axis_dimension,
    compute_serialized_parameters_size,
    get_preprocessor,
)
24
from transformers.testing_utils import require_onnx, require_rjieba, require_tf, require_torch, require_vision, slow
25
26


27
if is_torch_available() or is_tf_available():
28
29
    from transformers.onnx.features import FeaturesManager

30
31
32
33
34
if is_torch_available():
    import torch

    from transformers.models.deberta import modeling_deberta

35
36
37
38
39
40
41

@require_onnx
class OnnxUtilsTestCaseV2(TestCase):
    """
    Cover all the utilities involved to export ONNX models
    """

42
43
44
45
46
47
48
49
50
    @require_torch
    @patch("transformers.onnx.convert.is_torch_onnx_dict_inputs_support_available", return_value=False)
    def test_ensure_pytorch_version_ge_1_8_0(self, mock_is_torch_onnx_dict_inputs_support_available):
        """
        Ensure we raise an Exception if the pytorch version is unsupported (< 1.8.0)
        """
        self.assertRaises(AssertionError, export, None, None, None, None, None)
        mock_is_torch_onnx_dict_inputs_support_available.assert_called()

51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
    def test_compute_effective_axis_dimension(self):
        """
        When exporting ONNX model with dynamic axis (batch or sequence) we set batch_size and/or sequence_length = -1.
        We cannot generate an effective tensor with axis dim == -1, so we trick by using some "fixed" values
        (> 1 to avoid ONNX squeezing the axis).

        This test ensure we are correctly replacing generated batch / sequence tensor with axis > 1
        """

        # Dynamic axis (batch, no token added by the tokenizer)
        self.assertEqual(compute_effective_axis_dimension(-1, fixed_dimension=2, num_token_to_add=0), 2)

        # Static axis (batch, no token added by the tokenizer)
        self.assertEqual(compute_effective_axis_dimension(0, fixed_dimension=2, num_token_to_add=0), 2)

        # Dynamic axis (sequence, token added by the tokenizer 2 (no pair))
        self.assertEqual(compute_effective_axis_dimension(0, fixed_dimension=8, num_token_to_add=2), 6)
        self.assertEqual(compute_effective_axis_dimension(0, fixed_dimension=8, num_token_to_add=2), 6)

        # Dynamic axis (sequence, token added by the tokenizer 3 (pair))
        self.assertEqual(compute_effective_axis_dimension(0, fixed_dimension=8, num_token_to_add=3), 5)
        self.assertEqual(compute_effective_axis_dimension(0, fixed_dimension=8, num_token_to_add=3), 5)

    def test_compute_parameters_serialized_size(self):
        """
        This test ensures we compute a "correct" approximation of the underlying storage requirement (size) for all the
        parameters for the specified parameter's dtype.
        """
        self.assertEqual(compute_serialized_parameters_size(2, ParameterFormat.Float), 2 * ParameterFormat.Float.size)

    def test_flatten_output_collection_property(self):
        """
        This test ensures we correctly flatten nested collection such as the one we use when returning past_keys.
        past_keys = Tuple[Tuple]

        ONNX exporter will export nested collections as ${collection_name}.${level_idx_0}.${level_idx_1}...${idx_n}
        """
        self.assertEqual(
89
            OnnxConfig.flatten_output_collection_property("past_key", [[0], [1], [2]]),
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
            {
                "past_key.0": 0,
                "past_key.1": 1,
                "past_key.2": 2,
            },
        )


class OnnxConfigTestCaseV2(TestCase):
    """
    Cover the test for models default.

    Default means no specific features is being enabled on the model.
    """

    @patch.multiple(OnnxConfig, __abstractmethods__=set())
    def test_use_external_data_format(self):
        """
        External data format is required only if the serialized size of the parameters if bigger than 2Gb
        """
        TWO_GB_LIMIT = EXTERNAL_DATA_FORMAT_SIZE_LIMIT

        # No parameters
        self.assertFalse(OnnxConfig.use_external_data_format(0))

        # Some parameters
        self.assertFalse(OnnxConfig.use_external_data_format(1))

        # Almost 2Gb parameters
        self.assertFalse(OnnxConfig.use_external_data_format((TWO_GB_LIMIT - 1) // ParameterFormat.Float.size))

        # Exactly 2Gb parameters
        self.assertTrue(OnnxConfig.use_external_data_format(TWO_GB_LIMIT))

        # More than 2Gb parameters
        self.assertTrue(OnnxConfig.use_external_data_format((TWO_GB_LIMIT + 1) // ParameterFormat.Float.size))


class OnnxConfigWithPastTestCaseV2(TestCase):
    """
    Cover the tests for model which have use_cache feature (i.e. "with_past" for ONNX)
    """

133
134
135
136
137
138
    SUPPORTED_WITH_PAST_CONFIGS = {}
    # SUPPORTED_WITH_PAST_CONFIGS = {
    #     ("BART", BartConfig),
    #     ("GPT2", GPT2Config),
    #     # ("T5", T5Config)
    # }
139
140
141
142
143
144
145
146
147

    @patch.multiple(OnnxConfigWithPast, __abstractmethods__=set())
    def test_use_past(self):
        """
        Ensure the use_past variable is correctly being set
        """
        for name, config in OnnxConfigWithPastTestCaseV2.SUPPORTED_WITH_PAST_CONFIGS:
            with self.subTest(name):
                self.assertFalse(
148
149
                    OnnxConfigWithPast.from_model_config(config()).use_past,
                    "OnnxConfigWithPast.from_model_config() should not use_past",
150
151
152
                )

                self.assertTrue(
153
154
                    OnnxConfigWithPast.with_past(config()).use_past,
                    "OnnxConfigWithPast.from_model_config() should use_past",
155
156
157
158
159
160
161
162
163
164
165
                )

    @patch.multiple(OnnxConfigWithPast, __abstractmethods__=set())
    def test_values_override(self):
        """
        Ensure the use_past variable correctly set the `use_cache` value in model's configuration
        """
        for name, config in OnnxConfigWithPastTestCaseV2.SUPPORTED_WITH_PAST_CONFIGS:
            with self.subTest(name):

                # without past
166
                onnx_config_default = OnnxConfigWithPast.from_model_config(config())
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
                self.assertIsNotNone(onnx_config_default.values_override, "values_override should not be None")
                self.assertIn("use_cache", onnx_config_default.values_override, "use_cache should be present")
                self.assertFalse(
                    onnx_config_default.values_override["use_cache"], "use_cache should be False if not using past"
                )

                # with past
                onnx_config_default = OnnxConfigWithPast.with_past(config())
                self.assertIsNotNone(onnx_config_default.values_override, "values_override should not be None")
                self.assertIn("use_cache", onnx_config_default.values_override, "use_cache should be present")
                self.assertTrue(
                    onnx_config_default.values_override["use_cache"], "use_cache should be False if not using past"
                )


182
183
184
PYTORCH_EXPORT_MODELS = {
    ("albert", "hf-internal-testing/tiny-albert"),
    ("bert", "bert-base-cased"),
185
    ("big-bird", "google/bigbird-roberta-base"),
186
    ("ibert", "kssteven/ibert-roberta-base"),
187
    ("camembert", "camembert-base"),
188
    ("clip", "openai/clip-vit-base-patch32"),
189
    ("convbert", "YituTech/conv-bert-base"),
mrbean's avatar
mrbean committed
190
    ("codegen", "Salesforce/codegen-350M-multi"),
191
192
    ("deberta", "microsoft/deberta-base"),
    ("deberta-v2", "microsoft/deberta-v2-xlarge"),
193
    ("convnext", "facebook/convnext-tiny-224"),
regisss's avatar
regisss committed
194
    ("detr", "facebook/detr-resnet-50"),
195
    ("distilbert", "distilbert-base-cased"),
196
    ("electra", "google/electra-base-generator"),
regisss's avatar
regisss committed
197
    ("resnet", "microsoft/resnet-50"),
198
    ("roberta", "roberta-base"),
199
    ("roformer", "junnyu/roformer_chinese_base"),
200
    ("squeezebert", "squeezebert/squeezebert-uncased"),
201
    ("mobilebert", "google/mobilebert-uncased"),
202
    ("mobilevit", "apple/mobilevit-small"),
Ritik Nandwal's avatar
Ritik Nandwal committed
203
    ("xlm", "xlm-clm-ende-1024"),
204
205
    ("xlm-roberta", "xlm-roberta-base"),
    ("layoutlm", "microsoft/layoutlm-base-uncased"),
206
    ("layoutlmv3", "microsoft/layoutlmv3-base"),
gcheron's avatar
gcheron committed
207
    ("levit", "facebook/levit-128S"),
lewtun's avatar
lewtun committed
208
    ("vit", "google/vit-base-patch16-224"),
209
    ("deit", "facebook/deit-small-patch16-224"),
Jim Rohrer's avatar
Jim Rohrer committed
210
    ("beit", "microsoft/beit-base-patch16-224"),
211
    ("data2vec-text", "facebook/data2vec-text-base"),
212
    ("data2vec-vision", "facebook/data2vec-vision-base"),
213
214
    ("perceiver", "deepmind/language-perceiver", ("masked-lm", "sequence-classification")),
    ("perceiver", "deepmind/vision-perceiver-conv", ("image-classification",)),
NielsRogge's avatar
NielsRogge committed
215
    ("yolos", "hustvl/yolos-tiny"),
216
217
218
}

PYTORCH_EXPORT_WITH_PAST_MODELS = {
219
    ("bloom", "bigscience/bloom-560m"),
220
221
222
223
224
225
226
227
    ("gpt2", "gpt2"),
    ("gpt-neo", "EleutherAI/gpt-neo-125M"),
}

PYTORCH_EXPORT_SEQ2SEQ_WITH_PAST_MODELS = {
    ("bart", "facebook/bart-base"),
    ("mbart", "sshleifer/tiny-mbart"),
    ("t5", "t5-small"),
228
    ("marian", "Helsinki-NLP/opus-mt-en-de"),
229
    ("mt5", "google/mt5-base"),
230
    ("m2m-100", "facebook/m2m100_418M"),
231
232
    ("blenderbot-small", "facebook/blenderbot_small-90M"),
    ("blenderbot", "facebook/blenderbot-400M-distill"),
233
    ("bigbird-pegasus", "google/bigbird-pegasus-large-arxiv"),
234
    ("longt5", "google/long-t5-local-base"),
235
236
237
    # Disable for now as it causes fatal error `Floating point exception (core dumped)` and the subsequential tests are
    # not run.
    # ("longt5", "google/long-t5-tglobal-base"),
238
239
}

240
# TODO(lewtun): Include the same model types in `PYTORCH_EXPORT_MODELS` once TensorFlow has parity with the PyTorch model implementations.
241
242
243
TENSORFLOW_EXPORT_DEFAULT_MODELS = {
    ("albert", "hf-internal-testing/tiny-albert"),
    ("bert", "bert-base-cased"),
244
    ("camembert", "camembert-base"),
245
246
247
248
    ("distilbert", "distilbert-base-cased"),
    ("roberta", "roberta-base"),
}

249
250
# TODO(lewtun): Include the same model types in `PYTORCH_EXPORT_WITH_PAST_MODELS` once TensorFlow has parity with the PyTorch model implementations.
TENSORFLOW_EXPORT_WITH_PAST_MODELS = {}
251

252
253
# TODO(lewtun): Include the same model types in `PYTORCH_EXPORT_SEQ2SEQ_WITH_PAST_MODELS` once TensorFlow has parity with the PyTorch model implementations.
TENSORFLOW_EXPORT_SEQ2SEQ_WITH_PAST_MODELS = {}
254

255
256
257

def _get_models_to_test(export_models_list):
    models_to_test = []
258
    if is_torch_available() or is_tf_available():
259
260
261
262
263
264
265
266
267
        for name, model, *features in export_models_list:
            if features:
                feature_config_mapping = {
                    feature: FeaturesManager.get_config(name, feature) for _ in features for feature in _
                }
            else:
                feature_config_mapping = FeaturesManager.get_supported_features_for_model_type(name)

            for feature, onnx_config_class_constructor in feature_config_mapping.items():
268
269
270
271
272
                models_to_test.append((f"{name}_{feature}", name, model, feature, onnx_config_class_constructor))
        return sorted(models_to_test)
    else:
        # Returning some dummy test that should not be ever called because of the @require_torch / @require_tf
        # decorators.
273
274
        # The reason for not returning an empty list is because parameterized.expand complains when it's empty.
        return [("dummy", "dummy", "dummy", "dummy", OnnxConfig.from_model_config)]
275
276
277
278
279
280
281


class OnnxExportTestCaseV2(TestCase):
    """
    Integration tests ensuring supported models are correctly exported
    """

282
    def _onnx_export(self, test_name, name, model_name, feature, onnx_config_class_constructor, device="cpu"):
283
284
        from transformers.onnx import export

285
        model_class = FeaturesManager.get_model_class_for_feature(feature)
lewtun's avatar
lewtun committed
286
        config = AutoConfig.from_pretrained(model_name)
287
        model = model_class.from_config(config)
Yih-Dar's avatar
Yih-Dar committed
288
289
290
291
292
293

        # Dynamic axes aren't supported for YOLO-like models. This means they cannot be exported to ONNX on CUDA devices.
        # See: https://github.com/ultralytics/yolov5/pull/8378
        if model.__class__.__name__.startswith("Yolos") and device != "cpu":
            return

294
        onnx_config = onnx_config_class_constructor(model.config)
295

lewtun's avatar
lewtun committed
296
        if is_torch_available():
297
            from transformers.utils import torch_version
lewtun's avatar
lewtun committed
298
299
300

            if torch_version < onnx_config.torch_onnx_minimum_version:
                pytest.skip(
Sylvain Gugger's avatar
Sylvain Gugger committed
301
302
                    "Skipping due to incompatible PyTorch version. Minimum required is"
                    f" {onnx_config.torch_onnx_minimum_version}, got: {torch_version}"
lewtun's avatar
lewtun committed
303
304
                )

305
306
307
308
309
        preprocessor = get_preprocessor(model_name)

        # Useful for causal lm models that do not use pad tokens.
        if isinstance(preprocessor, PreTrainedTokenizerBase) and not getattr(config, "pad_token_id", None):
            config.pad_token_id = preprocessor.eos_token_id
lewtun's avatar
lewtun committed
310

311
312
313
        with NamedTemporaryFile("w") as output:
            try:
                onnx_inputs, onnx_outputs = export(
314
                    preprocessor, model, onnx_config, onnx_config.default_onnx_opset, Path(output.name), device=device
315
316
317
                )
                validate_model_outputs(
                    onnx_config,
lewtun's avatar
lewtun committed
318
                    preprocessor,
319
320
321
322
323
324
325
                    model,
                    Path(output.name),
                    onnx_outputs,
                    onnx_config.atol_for_validation,
                )
            except (RuntimeError, ValueError) as e:
                self.fail(f"{name}, {feature} -> {e}")
326

327
    @parameterized.expand(_get_models_to_test(PYTORCH_EXPORT_MODELS))
328
329
    @slow
    @require_torch
lewtun's avatar
lewtun committed
330
    @require_vision
331
    @require_rjieba
332
    def test_pytorch_export(self, test_name, name, model_name, feature, onnx_config_class_constructor):
333
        self._onnx_export(test_name, name, model_name, feature, onnx_config_class_constructor)
334

335
336
337
338
339
340
341
342
    @parameterized.expand(_get_models_to_test(PYTORCH_EXPORT_MODELS))
    @slow
    @require_torch
    @require_vision
    @require_rjieba
    def test_pytorch_export_on_cuda(self, test_name, name, model_name, feature, onnx_config_class_constructor):
        self._onnx_export(test_name, name, model_name, feature, onnx_config_class_constructor, device="cuda")

343
344
345
346
    @parameterized.expand(_get_models_to_test(PYTORCH_EXPORT_WITH_PAST_MODELS))
    @slow
    @require_torch
    def test_pytorch_export_with_past(self, test_name, name, model_name, feature, onnx_config_class_constructor):
347
        self._onnx_export(test_name, name, model_name, feature, onnx_config_class_constructor)
348

349
350
351
352
353
354
    @parameterized.expand(_get_models_to_test(PYTORCH_EXPORT_SEQ2SEQ_WITH_PAST_MODELS))
    @slow
    @require_torch
    def test_pytorch_export_seq2seq_with_past(
        self, test_name, name, model_name, feature, onnx_config_class_constructor
    ):
355
356
357
358
359
        self._onnx_export(test_name, name, model_name, feature, onnx_config_class_constructor)

    @parameterized.expand(_get_models_to_test(TENSORFLOW_EXPORT_DEFAULT_MODELS))
    @slow
    @require_tf
lewtun's avatar
lewtun committed
360
    @require_vision
361
362
363
    def test_tensorflow_export(self, test_name, name, model_name, feature, onnx_config_class_constructor):
        self._onnx_export(test_name, name, model_name, feature, onnx_config_class_constructor)

364
    @parameterized.expand(_get_models_to_test(TENSORFLOW_EXPORT_WITH_PAST_MODELS), skip_on_empty=True)
365
366
367
368
369
    @slow
    @require_tf
    def test_tensorflow_export_with_past(self, test_name, name, model_name, feature, onnx_config_class_constructor):
        self._onnx_export(test_name, name, model_name, feature, onnx_config_class_constructor)

370
    @parameterized.expand(_get_models_to_test(TENSORFLOW_EXPORT_SEQ2SEQ_WITH_PAST_MODELS), skip_on_empty=True)
371
372
373
374
375
376
    @slow
    @require_tf
    def test_tensorflow_export_seq2seq_with_past(
        self, test_name, name, model_name, feature, onnx_config_class_constructor
    ):
        self._onnx_export(test_name, name, model_name, feature, onnx_config_class_constructor)
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413


class StableDropoutTestCase(TestCase):
    """Tests export of StableDropout module."""

    @require_torch
    @pytest.mark.filterwarnings("ignore:.*Dropout.*:UserWarning:torch.onnx.*")  # torch.onnx is spammy.
    def test_training(self):
        """Tests export of StableDropout in training mode."""
        devnull = open(os.devnull, "wb")
        # drop_prob must be > 0 for the test to be meaningful
        sd = modeling_deberta.StableDropout(0.1)
        # Avoid warnings in training mode
        do_constant_folding = False
        # Dropout is a no-op in inference mode
        training = torch.onnx.TrainingMode.PRESERVE
        input = (torch.randn(2, 2),)

        torch.onnx.export(
            sd,
            input,
            devnull,
            opset_version=12,  # Minimum supported
            do_constant_folding=do_constant_folding,
            training=training,
        )

        # Expected to fail with opset_version < 12
        with self.assertRaises(Exception):
            torch.onnx.export(
                sd,
                input,
                devnull,
                opset_version=11,
                do_constant_folding=do_constant_folding,
                training=training,
            )