transformers
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
18import unittest
19
20from transformers import ErnieMConfig, is_torch_available
21from transformers.testing_utils import require_torch, slow, torch_device
22
23from ...test_configuration_common import ConfigTester
24from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
25from ...test_pipeline_mixin import PipelineTesterMixin
26
27
28if is_torch_available():
29import torch
30
31from transformers import (
32ErnieMForInformationExtraction,
33ErnieMForMultipleChoice,
34ErnieMForQuestionAnswering,
35ErnieMForSequenceClassification,
36ErnieMForTokenClassification,
37ErnieMModel,
38)
39from transformers.models.ernie_m.modeling_ernie_m import ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST
40
41
42class ErnieMModelTester:
43def __init__(
44self,
45parent,
46batch_size=13,
47seq_length=7,
48is_training=True,
49use_input_mask=True,
50use_labels=True,
51vocab_size=99,
52hidden_size=32,
53num_hidden_layers=2,
54num_attention_heads=4,
55intermediate_size=37,
56hidden_act="gelu",
57hidden_dropout_prob=0.1,
58attention_probs_dropout_prob=0.1,
59max_position_embeddings=512,
60type_vocab_size=16,
61type_sequence_label_size=2,
62initializer_range=0.02,
63num_labels=3,
64num_choices=4,
65scope=None,
66):
67self.parent = parent
68self.batch_size = batch_size
69self.seq_length = seq_length
70self.is_training = is_training
71self.use_input_mask = use_input_mask
72self.use_labels = use_labels
73self.vocab_size = vocab_size
74self.hidden_size = hidden_size
75self.num_hidden_layers = num_hidden_layers
76self.num_attention_heads = num_attention_heads
77self.intermediate_size = intermediate_size
78self.hidden_act = hidden_act
79self.hidden_dropout_prob = hidden_dropout_prob
80self.attention_probs_dropout_prob = attention_probs_dropout_prob
81self.max_position_embeddings = max_position_embeddings
82self.type_vocab_size = type_vocab_size
83self.type_sequence_label_size = type_sequence_label_size
84self.initializer_range = initializer_range
85self.num_labels = num_labels
86self.num_choices = num_choices
87self.scope = scope
88
89def prepare_config_and_inputs(self):
90input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
91
92input_mask = None
93if self.use_input_mask:
94input_mask = random_attention_mask([self.batch_size, self.seq_length])
95
96sequence_labels = None
97token_labels = None
98choice_labels = None
99if self.use_labels:
100sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
101token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
102choice_labels = ids_tensor([self.batch_size], self.num_choices)
103
104config = self.get_config()
105
106return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
107
108def prepare_config_and_inputs_for_uiem(self):
109input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
110
111input_mask = None
112if self.use_input_mask:
113input_mask = random_attention_mask([self.batch_size, self.seq_length])
114config = self.get_config()
115
116return config, input_ids, input_mask
117
118def get_config(self):
119return ErnieMConfig(
120vocab_size=self.vocab_size,
121hidden_size=self.hidden_size,
122num_hidden_layers=self.num_hidden_layers,
123num_attention_heads=self.num_attention_heads,
124intermediate_size=self.intermediate_size,
125hidden_act=self.hidden_act,
126hidden_dropout_prob=self.hidden_dropout_prob,
127attention_probs_dropout_prob=self.attention_probs_dropout_prob,
128max_position_embeddings=self.max_position_embeddings,
129type_vocab_size=self.type_vocab_size,
130initializer_range=self.initializer_range,
131)
132
133def create_and_check_model(self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels):
134model = ErnieMModel(config=config)
135model.to(torch_device)
136model.eval()
137result = model(input_ids, return_dict=True)
138self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
139
140def create_and_check_for_question_answering(
141self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
142):
143model = ErnieMForQuestionAnswering(config=config)
144model.to(torch_device)
145model.eval()
146result = model(
147input_ids,
148attention_mask=input_mask,
149start_positions=sequence_labels,
150end_positions=sequence_labels,
151)
152self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
153self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
154
155def create_and_check_for_information_extraction(
156self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
157):
158model = ErnieMForInformationExtraction(config=config)
159model.to(torch_device)
160model.eval()
161sequence_labels = torch.ones_like(input_ids, dtype=torch.float32)
162result = model(
163input_ids,
164attention_mask=input_mask,
165start_positions=sequence_labels,
166end_positions=sequence_labels,
167)
168self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
169self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
170
171def create_and_check_for_sequence_classification(
172self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
173):
174config.num_labels = self.num_labels
175model = ErnieMForSequenceClassification(config)
176model.to(torch_device)
177model.eval()
178result = model(input_ids, attention_mask=input_mask, labels=sequence_labels)
179self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
180
181def create_and_check_for_token_classification(
182self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
183):
184config.num_labels = self.num_labels
185model = ErnieMForTokenClassification(config=config)
186model.to(torch_device)
187model.eval()
188input_ids.to(torch_device)
189input_mask.to(torch_device)
190token_labels.to(torch_device)
191
192result = model(input_ids, attention_mask=input_mask, labels=token_labels)
193
194self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
195
196def create_and_check_for_multiple_choice(
197self, config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
198):
199config.num_choices = self.num_choices
200model = ErnieMForMultipleChoice(config=config)
201model.to(torch_device)
202model.eval()
203multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
204multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
205result = model(
206multiple_choice_inputs_ids,
207attention_mask=multiple_choice_input_mask,
208labels=choice_labels,
209)
210self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_choices))
211
212def prepare_config_and_inputs_for_common(self):
213config_and_inputs = self.prepare_config_and_inputs()
214(
215config,
216input_ids,
217input_mask,
218sequence_labels,
219token_labels,
220choice_labels,
221) = config_and_inputs
222inputs_dict = {"input_ids": input_ids, "attention_mask": input_mask}
223return config, inputs_dict
224
225
226@require_torch
227class ErnieMModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
228all_model_classes = (
229(
230ErnieMModel,
231ErnieMForMultipleChoice,
232ErnieMForQuestionAnswering,
233ErnieMForSequenceClassification,
234ErnieMForTokenClassification,
235)
236if is_torch_available()
237else ()
238)
239all_generative_model_classes = ()
240pipeline_model_mapping = (
241{
242"feature-extraction": ErnieMModel,
243"question-answering": ErnieMForQuestionAnswering,
244"text-classification": ErnieMForSequenceClassification,
245"token-classification": ErnieMForTokenClassification,
246"zero-shot": ErnieMForSequenceClassification,
247}
248if is_torch_available()
249else {}
250)
251test_torchscript = False
252
253# TODO: Fix the failed tests when this model gets more usage
254def is_pipeline_test_to_skip(
255self, pipeline_test_casse_name, config_class, model_architecture, tokenizer_name, processor_name
256):
257if pipeline_test_casse_name == "QAPipelineTests":
258return True
259
260return False
261
262def setUp(self):
263self.model_tester = ErnieMModelTester(self)
264self.config_tester = ConfigTester(self, config_class=ErnieMConfig, hidden_size=37)
265
266def test_config(self):
267self.config_tester.run_common_tests()
268
269def test_model(self):
270config_and_inputs = self.model_tester.prepare_config_and_inputs()
271self.model_tester.create_and_check_model(*config_and_inputs)
272
273def test_model_various_embeddings(self):
274config_and_inputs = self.model_tester.prepare_config_and_inputs()
275for type in ["absolute", "relative_key", "relative_key_query"]:
276config_and_inputs[0].position_embedding_type = type
277self.model_tester.create_and_check_model(*config_and_inputs)
278
279def test_for_multiple_choice(self):
280config_and_inputs = self.model_tester.prepare_config_and_inputs()
281self.model_tester.create_and_check_for_multiple_choice(*config_and_inputs)
282
283def test_for_question_answering(self):
284config_and_inputs = self.model_tester.prepare_config_and_inputs()
285self.model_tester.create_and_check_for_question_answering(*config_and_inputs)
286
287def test_for_sequence_classification(self):
288config_and_inputs = self.model_tester.prepare_config_and_inputs()
289self.model_tester.create_and_check_for_sequence_classification(*config_and_inputs)
290
291def test_for_information_extraction(self):
292config_and_inputs = self.model_tester.prepare_config_and_inputs()
293self.model_tester.create_and_check_for_information_extraction(*config_and_inputs)
294
295def test_for_token_classification(self):
296config_and_inputs = self.model_tester.prepare_config_and_inputs()
297self.model_tester.create_and_check_for_token_classification(*config_and_inputs)
298
299@slow
300def test_model_from_pretrained(self):
301for model_name in ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
302model = ErnieMModel.from_pretrained(model_name)
303self.assertIsNotNone(model)
304
305
306@require_torch
307class ErnieMModelIntegrationTest(unittest.TestCase):
308@slow
309def test_inference_model(self):
310model = ErnieMModel.from_pretrained("susnato/ernie-m-base_pytorch")
311model.eval()
312input_ids = torch.tensor([[0, 1, 2, 3, 4, 5]])
313output = model(input_ids)[0]
314
315# TODO Replace vocab size
316hidden_size = 768
317
318expected_shape = torch.Size((1, 6, hidden_size))
319self.assertEqual(output.shape, expected_shape)
320
321expected_slice = torch.tensor(
322[[[-0.0012, 0.1245, -0.0214], [-0.0742, 0.0244, -0.0771], [-0.0333, 0.1164, -0.1554]]]
323)
324
325self.assertTrue(torch.allclose(output[:, :3, :3], expected_slice, atol=1e-3))
326