transformers

Форк
0
/
test_modeling_ernie_m.py 
325 строк · 12.4 Кб
1
# coding=utf-8
2
# Copyright 2023 The HuggingFace Inc. and Baidu 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 ErnieM model. """
16

17

18
import unittest
19

20
from transformers import ErnieMConfig, is_torch_available
21
from transformers.testing_utils import require_torch, slow, torch_device
22

23
from ...test_configuration_common import ConfigTester
24
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
25
from ...test_pipeline_mixin import PipelineTesterMixin
26

27

28
if is_torch_available():
29
    import torch
30

31
    from transformers import (
32
        ErnieMForInformationExtraction,
33
        ErnieMForMultipleChoice,
34
        ErnieMForQuestionAnswering,
35
        ErnieMForSequenceClassification,
36
        ErnieMForTokenClassification,
37
        ErnieMModel,
38
    )
39
    from transformers.models.ernie_m.modeling_ernie_m import ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST
40

41

42
class ErnieMModelTester:
43
    def __init__(
44
        self,
45
        parent,
46
        batch_size=13,
47
        seq_length=7,
48
        is_training=True,
49
        use_input_mask=True,
50
        use_labels=True,
51
        vocab_size=99,
52
        hidden_size=32,
53
        num_hidden_layers=2,
54
        num_attention_heads=4,
55
        intermediate_size=37,
56
        hidden_act="gelu",
57
        hidden_dropout_prob=0.1,
58
        attention_probs_dropout_prob=0.1,
59
        max_position_embeddings=512,
60
        type_vocab_size=16,
61
        type_sequence_label_size=2,
62
        initializer_range=0.02,
63
        num_labels=3,
64
        num_choices=4,
65
        scope=None,
66
    ):
67
        self.parent = parent
68
        self.batch_size = batch_size
69
        self.seq_length = seq_length
70
        self.is_training = is_training
71
        self.use_input_mask = use_input_mask
72
        self.use_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
        sequence_labels = None
97
        token_labels = None
98
        choice_labels = None
99
        if self.use_labels:
100
            sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
101
            token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
102
            choice_labels = ids_tensor([self.batch_size], self.num_choices)
103

104
        config = self.get_config()
105

106
        return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
107

108
    def prepare_config_and_inputs_for_uiem(self):
109
        input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
110

111
        input_mask = None
112
        if self.use_input_mask:
113
            input_mask = random_attention_mask([self.batch_size, self.seq_length])
114
        config = self.get_config()
115

116
        return config, input_ids, input_mask
117

118
    def get_config(self):
119
        return ErnieMConfig(
120
            vocab_size=self.vocab_size,
121
            hidden_size=self.hidden_size,
122
            num_hidden_layers=self.num_hidden_layers,
123
            num_attention_heads=self.num_attention_heads,
124
            intermediate_size=self.intermediate_size,
125
            hidden_act=self.hidden_act,
126
            hidden_dropout_prob=self.hidden_dropout_prob,
127
            attention_probs_dropout_prob=self.attention_probs_dropout_prob,
128
            max_position_embeddings=self.max_position_embeddings,
129
            type_vocab_size=self.type_vocab_size,
130
            initializer_range=self.initializer_range,
131
        )
132

133
    def create_and_check_model(self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels):
134
        model = ErnieMModel(config=config)
135
        model.to(torch_device)
136
        model.eval()
137
        result = model(input_ids, return_dict=True)
138
        self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
139

140
    def create_and_check_for_question_answering(
141
        self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
142
    ):
143
        model = ErnieMForQuestionAnswering(config=config)
144
        model.to(torch_device)
145
        model.eval()
146
        result = model(
147
            input_ids,
148
            attention_mask=input_mask,
149
            start_positions=sequence_labels,
150
            end_positions=sequence_labels,
151
        )
152
        self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
153
        self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
154

155
    def create_and_check_for_information_extraction(
156
        self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
157
    ):
158
        model = ErnieMForInformationExtraction(config=config)
159
        model.to(torch_device)
160
        model.eval()
161
        sequence_labels = torch.ones_like(input_ids, dtype=torch.float32)
162
        result = model(
163
            input_ids,
164
            attention_mask=input_mask,
165
            start_positions=sequence_labels,
166
            end_positions=sequence_labels,
167
        )
168
        self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
169
        self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
170

171
    def create_and_check_for_sequence_classification(
172
        self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
173
    ):
174
        config.num_labels = self.num_labels
175
        model = ErnieMForSequenceClassification(config)
176
        model.to(torch_device)
177
        model.eval()
178
        result = model(input_ids, attention_mask=input_mask, labels=sequence_labels)
179
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
180

181
    def create_and_check_for_token_classification(
182
        self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
183
    ):
184
        config.num_labels = self.num_labels
185
        model = ErnieMForTokenClassification(config=config)
186
        model.to(torch_device)
187
        model.eval()
188
        input_ids.to(torch_device)
189
        input_mask.to(torch_device)
190
        token_labels.to(torch_device)
191

192
        result = model(input_ids, attention_mask=input_mask, labels=token_labels)
193

194
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
195

196
    def create_and_check_for_multiple_choice(
197
        self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
198
    ):
199
        config.num_choices = self.num_choices
200
        model = ErnieMForMultipleChoice(config=config)
201
        model.to(torch_device)
202
        model.eval()
203
        multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
204
        multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
205
        result = model(
206
            multiple_choice_inputs_ids,
207
            attention_mask=multiple_choice_input_mask,
208
            labels=choice_labels,
209
        )
210
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
211

212
    def prepare_config_and_inputs_for_common(self):
213
        config_and_inputs = self.prepare_config_and_inputs()
214
        (
215
            config,
216
            input_ids,
217
            input_mask,
218
            sequence_labels,
219
            token_labels,
220
            choice_labels,
221
        ) = config_and_inputs
222
        inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
223
        return config, inputs_dict
224

225

226
@require_torch
227
class ErnieMModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
228
    all_model_classes = (
229
        (
230
            ErnieMModel,
231
            ErnieMForMultipleChoice,
232
            ErnieMForQuestionAnswering,
233
            ErnieMForSequenceClassification,
234
            ErnieMForTokenClassification,
235
        )
236
        if is_torch_available()
237
        else ()
238
    )
239
    all_generative_model_classes = ()
240
    pipeline_model_mapping = (
241
        {
242
            "feature-extraction": ErnieMModel,
243
            "question-answering": ErnieMForQuestionAnswering,
244
            "text-classification": ErnieMForSequenceClassification,
245
            "token-classification": ErnieMForTokenClassification,
246
            "zero-shot": ErnieMForSequenceClassification,
247
        }
248
        if is_torch_available()
249
        else {}
250
    )
251
    test_torchscript = False
252

253
    # TODO: Fix the failed tests when this model gets more usage
254
    def is_pipeline_test_to_skip(
255
        self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name
256
    ):
257
        if pipeline_test_casse_name == "QAPipelineTests":
258
            return True
259

260
        return False
261

262
    def setUp(self):
263
        self.model_tester = ErnieMModelTester(self)
264
        self.config_tester = ConfigTester(self, config_class=ErnieMConfig, hidden_size=37)
265

266
    def test_config(self):
267
        self.config_tester.run_common_tests()
268

269
    def test_model(self):
270
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
271
        self.model_tester.create_and_check_model(*config_and_inputs)
272

273
    def test_model_various_embeddings(self):
274
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
275
        for type in ["absolute", "relative_key", "relative_key_query"]:
276
            config_and_inputs[0].position_embedding_type = type
277
            self.model_tester.create_and_check_model(*config_and_inputs)
278

279
    def test_for_multiple_choice(self):
280
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
281
        self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
282

283
    def test_for_question_answering(self):
284
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
285
        self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
286

287
    def test_for_sequence_classification(self):
288
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
289
        self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs)
290

291
    def test_for_information_extraction(self):
292
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
293
        self.model_tester.create_and_check_for_information_extraction(*config_and_inputs)
294

295
    def test_for_token_classification(self):
296
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
297
        self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
298

299
    @slow
300
    def test_model_from_pretrained(self):
301
        for model_name in ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
302
            model = ErnieMModel.from_pretrained(model_name)
303
            self.assertIsNotNone(model)
304

305

306
@require_torch
307
class ErnieMModelIntegrationTest(unittest.TestCase):
308
    @slow
309
    def test_inference_model(self):
310
        model = ErnieMModel.from_pretrained("susnato/ernie-m-base_pytorch")
311
        model.eval()
312
        input_ids = torch.tensor([[0, 1, 2, 3, 4, 5]])
313
        output = model(input_ids)[0]
314

315
        # TODO Replace vocab size
316
        hidden_size = 768
317

318
        expected_shape = torch.Size((1, 6, hidden_size))
319
        self.assertEqual(output.shape, expected_shape)
320

321
        expected_slice = torch.tensor(
322
            [[[-0.0012, 0.1245, -0.0214], [-0.0742, 0.0244, -0.0771], [-0.0333, 0.1164, -0.1554]]]
323
        )
324

325
        self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-3))
326

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.