transformers

Форк
0
/
test_modeling_gpt2.py 
861 строка · 37.1 Кб
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 datetime
18
import gc
19
import math
20
import unittest
21

22
from transformers import GPT2Config, is_torch_available
23
from transformers.testing_utils import backend_empty_cache, require_torch, slow, torch_device
24

25
from ...generation.test_utils import GenerationTesterMixin
26
from ...test_configuration_common import ConfigTester
27
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
28
from ...test_pipeline_mixin import PipelineTesterMixin
29

30

31
if is_torch_available():
32
    import torch
33

34
    from transformers import (
35
        GPT2_PRETRAINED_MODEL_ARCHIVE_LIST,
36
        GPT2DoubleHeadsModel,
37
        GPT2ForQuestionAnswering,
38
        GPT2ForSequenceClassification,
39
        GPT2ForTokenClassification,
40
        GPT2LMHeadModel,
41
        GPT2Model,
42
        GPT2Tokenizer,
43
    )
44

45

46
class GPT2ModelTester:
47
    def __init__(
48
        self,
49
        parent,
50
        batch_size=14,
51
        seq_length=7,
52
        is_training=True,
53
        use_token_type_ids=True,
54
        use_input_mask=True,
55
        use_labels=True,
56
        use_mc_token_ids=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="gelu",
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
        scope=None,
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_token_type_ids = use_token_type_ids
78
        self.use_input_mask = use_input_mask
79
        self.use_labels = use_labels
80
        self.use_mc_token_ids = use_mc_token_ids
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.scope = None
96
        self.bos_token_id = vocab_size - 1
97
        self.eos_token_id = vocab_size - 1
98
        self.pad_token_id = vocab_size - 1
99

100
    def get_large_model_config(self):
101
        return GPT2Config.from_pretrained("openai-community/gpt2")
102

103
    def prepare_config_and_inputs(
104
        self, gradient_checkpointing=False, scale_attn_by_inverse_layer_idx=False, reorder_and_upcast_attn=False
105
    ):
106
        input_ids = ids_tensor([self.batch_size, self.seq_length], self.vocab_size)
107

108
        input_mask = None
109
        if self.use_input_mask:
110
            input_mask = random_attention_mask([self.batch_size, self.seq_length])
111

112
        token_type_ids = None
113
        if self.use_token_type_ids:
114
            token_type_ids = ids_tensor([self.batch_size, self.seq_length], self.type_vocab_size)
115

116
        mc_token_ids = None
117
        if self.use_mc_token_ids:
118
            mc_token_ids = ids_tensor([self.batch_size, self.num_choices], self.seq_length)
119

120
        sequence_labels = None
121
        token_labels = None
122
        choice_labels = None
123
        if self.use_labels:
124
            sequence_labels = ids_tensor([self.batch_size], self.type_sequence_label_size)
125
            token_labels = ids_tensor([self.batch_size, self.seq_length], self.num_labels)
126
            choice_labels = ids_tensor([self.batch_size], self.num_choices)
127

128
        config = self.get_config(
129
            gradient_checkpointing=gradient_checkpointing,
130
            scale_attn_by_inverse_layer_idx=scale_attn_by_inverse_layer_idx,
131
            reorder_and_upcast_attn=reorder_and_upcast_attn,
132
        )
133

134
        head_mask = ids_tensor([self.num_hidden_layers, self.num_attention_heads], 2)
135

136
        return (
137
            config,
138
            input_ids,
139
            input_mask,
140
            head_mask,
141
            token_type_ids,
142
            mc_token_ids,
143
            sequence_labels,
144
            token_labels,
145
            choice_labels,
146
        )
147

148
    def get_config(
149
        self, gradient_checkpointing=False, scale_attn_by_inverse_layer_idx=False, reorder_and_upcast_attn=False
150
    ):
151
        return GPT2Config(
152
            vocab_size=self.vocab_size,
153
            n_embd=self.hidden_size,
154
            n_layer=self.num_hidden_layers,
155
            n_head=self.num_attention_heads,
156
            n_inner=self.intermediate_size,
157
            activation_function=self.hidden_act,
158
            resid_pdrop=self.hidden_dropout_prob,
159
            attn_pdrop=self.attention_probs_dropout_prob,
160
            n_positions=self.max_position_embeddings,
161
            type_vocab_size=self.type_vocab_size,
162
            initializer_range=self.initializer_range,
163
            use_cache=True,
164
            bos_token_id=self.bos_token_id,
165
            eos_token_id=self.eos_token_id,
166
            pad_token_id=self.pad_token_id,
167
            gradient_checkpointing=gradient_checkpointing,
168
            scale_attn_by_inverse_layer_idx=scale_attn_by_inverse_layer_idx,
169
            reorder_and_upcast_attn=reorder_and_upcast_attn,
170
        )
171

172
    def get_pipeline_config(self):
173
        config = self.get_config()
174
        config.vocab_size = 300
175
        return config
176

177
    def prepare_config_and_inputs_for_decoder(self):
178
        (
179
            config,
180
            input_ids,
181
            input_mask,
182
            head_mask,
183
            token_type_ids,
184
            mc_token_ids,
185
            sequence_labels,
186
            token_labels,
187
            choice_labels,
188
        ) = self.prepare_config_and_inputs()
189

190
        encoder_hidden_states = floats_tensor([self.batch_size, self.seq_length, self.hidden_size])
191
        encoder_attention_mask = ids_tensor([self.batch_size, self.seq_length], vocab_size=2)
192

193
        return (
194
            config,
195
            input_ids,
196
            input_mask,
197
            head_mask,
198
            token_type_ids,
199
            sequence_labels,
200
            token_labels,
201
            choice_labels,
202
            encoder_hidden_states,
203
            encoder_attention_mask,
204
        )
205

206
    def create_and_check_gpt2_model(self, config, input_ids, input_mask, head_mask, token_type_ids, *args):
207
        model = GPT2Model(config=config)
208
        model.to(torch_device)
209
        model.eval()
210

211
        result = model(input_ids, token_type_ids=token_type_ids, head_mask=head_mask)
212
        result = model(input_ids, token_type_ids=token_type_ids)
213
        result = model(input_ids)
214

215
        self.parent.assertEqual(result.last_hidden_state.shape, (self.batch_size, self.seq_length, self.hidden_size))
216
        self.parent.assertEqual(len(result.past_key_values), config.n_layer)
217

218
    def create_and_check_gpt2_model_past(self, config, input_ids, input_mask, head_mask, token_type_ids, *args):
219
        model = GPT2Model(config=config)
220
        model.to(torch_device)
221
        model.eval()
222

223
        # first forward pass
224
        outputs = model(input_ids, token_type_ids=token_type_ids, use_cache=True)
225
        outputs_use_cache_conf = model(input_ids, token_type_ids=token_type_ids)
226
        outputs_no_past = model(input_ids, token_type_ids=token_type_ids, use_cache=False)
227

228
        self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))
229
        self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)
230

231
        output, past = outputs.to_tuple()
232

233
        # create hypothetical next token and extent to next_input_ids
234
        next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
235
        next_token_types = ids_tensor([self.batch_size, 1], self.type_vocab_size)
236

237
        # append to next input_ids and token_type_ids
238
        next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
239
        next_token_type_ids = torch.cat([token_type_ids, next_token_types], dim=-1)
240

241
        output_from_no_past = model(next_input_ids, token_type_ids=next_token_type_ids)["last_hidden_state"]
242
        output_from_past = model(next_tokens, token_type_ids=next_token_types, past_key_values=past)[
243
            "last_hidden_state"
244
        ]
245

246
        # select random slice
247
        random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
248
        output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach()
249
        output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
250

251
        # test that outputs are equal for slice
252
        self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
253

254
    def create_and_check_gpt2_model_attention_mask_past(
255
        self, config, input_ids, input_mask, head_mask, token_type_ids, *args
256
    ):
257
        model = GPT2Model(config=config)
258
        model.to(torch_device)
259
        model.eval()
260

261
        # create attention mask
262
        attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
263
        half_seq_length = self.seq_length // 2
264
        attn_mask[:, half_seq_length:] = 0
265

266
        # first forward pass
267
        output, past = model(input_ids, attention_mask=attn_mask).to_tuple()
268

269
        # create hypothetical next token and extent to next_input_ids
270
        next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
271

272
        # change a random masked slice from input_ids
273
        random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1
274
        random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1)
275
        input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens
276

277
        # append to next input_ids and attn_mask
278
        next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
279
        attn_mask = torch.cat(
280
            [attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)],
281
            dim=1,
282
        )
283

284
        # get two different outputs
285
        output_from_no_past = model(next_input_ids, attention_mask=attn_mask)["last_hidden_state"]
286
        output_from_past = model(next_tokens, past_key_values=past, attention_mask=attn_mask)["last_hidden_state"]
287

288
        # select random slice
289
        random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
290
        output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach()
291
        output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
292

293
        # test that outputs are equal for slice
294
        self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
295

296
    def create_and_check_gpt2_model_past_large_inputs(
297
        self, config, input_ids, input_mask, head_mask, token_type_ids, *args
298
    ):
299
        model = GPT2Model(config=config)
300
        model.to(torch_device)
301
        model.eval()
302

303
        # first forward pass
304
        outputs = model(input_ids, token_type_ids=token_type_ids, attention_mask=input_mask, use_cache=True)
305

306
        output, past = outputs.to_tuple()
307

308
        # create hypothetical next token and extent to next_input_ids
309
        next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
310
        next_token_types = ids_tensor([self.batch_size, 3], self.type_vocab_size)
311
        next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
312

313
        # append to next input_ids and token_type_ids
314
        next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
315
        next_token_type_ids = torch.cat([token_type_ids, next_token_types], dim=-1)
316
        next_attention_mask = torch.cat([input_mask, next_mask], dim=-1)
317

318
        output_from_no_past = model(
319
            next_input_ids, token_type_ids=next_token_type_ids, attention_mask=next_attention_mask
320
        )["last_hidden_state"]
321
        output_from_past = model(
322
            next_tokens, token_type_ids=next_token_types, attention_mask=next_attention_mask, past_key_values=past
323
        )["last_hidden_state"]
324
        self.parent.assertTrue(output_from_past.shape[1] == next_tokens.shape[1])
325

326
        # select random slice
327
        random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
328
        output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
329
        output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
330

331
        # test that outputs are equal for slice
332
        self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
333

334
    def create_and_check_lm_head_model(self, config, input_ids, input_mask, head_mask, token_type_ids, *args):
335
        model = GPT2LMHeadModel(config)
336
        model.to(torch_device)
337
        model.eval()
338

339
        result = model(input_ids, token_type_ids=token_type_ids, labels=input_ids)
340
        self.parent.assertEqual(result.loss.shape, ())
341
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
342

343
    def create_and_check_forward_and_backwards(
344
        self, config, input_ids, input_mask, head_mask, token_type_ids, *args, gradient_checkpointing=False
345
    ):
346
        model = GPT2LMHeadModel(config)
347
        model.to(torch_device)
348
        if gradient_checkpointing:
349
            model.gradient_checkpointing_enable()
350

351
        result = model(input_ids, token_type_ids=token_type_ids, labels=input_ids)
352
        self.parent.assertEqual(result.loss.shape, ())
353
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.vocab_size))
354
        result.loss.backward()
355

356
    def create_and_check_double_lm_head_model(
357
        self, config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, *args
358
    ):
359
        model = GPT2DoubleHeadsModel(config)
360
        model.to(torch_device)
361
        model.eval()
362

363
        multiple_choice_inputs_ids = input_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
364
        multiple_choice_input_mask = input_mask.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
365
        multiple_choice_token_type_ids = token_type_ids.unsqueeze(1).expand(-1, self.num_choices, -1).contiguous()
366

367
        inputs = {
368
            "input_ids": multiple_choice_inputs_ids,
369
            "mc_token_ids": mc_token_ids,
370
            "attention_mask": multiple_choice_input_mask,
371
            "token_type_ids": multiple_choice_token_type_ids,
372
            "labels": multiple_choice_inputs_ids,
373
        }
374

375
        result = model(**inputs)
376
        self.parent.assertEqual(result.loss.shape, ())
377
        self.parent.assertEqual(
378
            result.logits.shape, (self.batch_size, self.num_choices, self.seq_length, self.vocab_size)
379
        )
380
        self.parent.assertEqual(result.mc_logits.shape, (self.batch_size, self.num_choices))
381

382
    def create_and_check_gpt2_for_question_answering(
383
        self, config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, *args
384
    ):
385
        config.num_labels = self.num_labels
386
        model = GPT2ForQuestionAnswering(config)
387
        model.to(torch_device)
388
        model.eval()
389
        result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
390
        self.parent.assertEqual(result.start_logits.shape, (self.batch_size, self.seq_length))
391
        self.parent.assertEqual(result.end_logits.shape, (self.batch_size, self.seq_length))
392

393
    def create_and_check_gpt2_for_sequence_classification(
394
        self, config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, *args
395
    ):
396
        config.num_labels = self.num_labels
397
        model = GPT2ForSequenceClassification(config)
398
        model.to(torch_device)
399
        model.eval()
400
        result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids, labels=sequence_labels)
401
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.num_labels))
402

403
    def create_and_check_gpt2_for_token_classification(
404
        self, config, input_ids, input_mask, head_mask, token_type_ids, mc_token_ids, sequence_labels, *args
405
    ):
406
        config.num_labels = self.num_labels
407
        model = GPT2ForTokenClassification(config)
408
        model.to(torch_device)
409
        model.eval()
410
        result = model(input_ids, attention_mask=input_mask, token_type_ids=token_type_ids)
411
        self.parent.assertEqual(result.logits.shape, (self.batch_size, self.seq_length, self.num_labels))
412

413
    def create_and_check_gpt2_weight_initialization(self, config, *args):
414
        model = GPT2Model(config)
415
        model_std = model.config.initializer_range / math.sqrt(2 * model.config.n_layer)
416
        for key in model.state_dict().keys():
417
            if "c_proj" in key and "weight" in key:
418
                self.parent.assertLessEqual(abs(torch.std(model.state_dict()[key]) - model_std), 0.001)
419
                self.parent.assertLessEqual(abs(torch.mean(model.state_dict()[key]) - 0.0), 0.01)
420

421
    def prepare_config_and_inputs_for_common(self):
422
        config_and_inputs = self.prepare_config_and_inputs()
423

424
        (
425
            config,
426
            input_ids,
427
            input_mask,
428
            head_mask,
429
            token_type_ids,
430
            mc_token_ids,
431
            sequence_labels,
432
            token_labels,
433
            choice_labels,
434
        ) = config_and_inputs
435

436
        inputs_dict = {
437
            "input_ids": input_ids,
438
            "token_type_ids": token_type_ids,
439
            "head_mask": head_mask,
440
        }
441

442
        return config, inputs_dict
443

444

445
@require_torch
446
class GPT2ModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
447
    all_model_classes = (
448
        (
449
            GPT2Model,
450
            GPT2LMHeadModel,
451
            GPT2DoubleHeadsModel,
452
            GPT2ForQuestionAnswering,
453
            GPT2ForSequenceClassification,
454
            GPT2ForTokenClassification,
455
        )
456
        if is_torch_available()
457
        else ()
458
    )
459
    all_generative_model_classes = (GPT2LMHeadModel, GPT2DoubleHeadsModel) if is_torch_available() else ()
460
    pipeline_model_mapping = (
461
        {
462
            "feature-extraction": GPT2Model,
463
            "question-answering": GPT2ForQuestionAnswering,
464
            "text-classification": GPT2ForSequenceClassification,
465
            "text-generation": GPT2LMHeadModel,
466
            "token-classification": GPT2ForTokenClassification,
467
            "zero-shot": GPT2ForSequenceClassification,
468
        }
469
        if is_torch_available()
470
        else {}
471
    )
472
    all_parallelizable_model_classes = (GPT2LMHeadModel, GPT2DoubleHeadsModel) if is_torch_available() else ()
473
    fx_compatible = True
474
    test_missing_keys = False
475
    test_model_parallel = True
476

477
    # special case for DoubleHeads model
478
    def _prepare_for_class(self, inputs_dict, model_class, return_labels=False):
479
        inputs_dict = super()._prepare_for_class(inputs_dict, model_class, return_labels=return_labels)
480

481
        if return_labels:
482
            if model_class.__name__ == "GPT2DoubleHeadsModel":
483
                inputs_dict["labels"] = torch.zeros(
484
                    (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length),
485
                    dtype=torch.long,
486
                    device=torch_device,
487
                )
488
                inputs_dict["input_ids"] = inputs_dict["labels"]
489
                inputs_dict["token_type_ids"] = inputs_dict["labels"]
490
                inputs_dict["mc_token_ids"] = torch.zeros(
491
                    (self.model_tester.batch_size, self.model_tester.num_choices),
492
                    dtype=torch.long,
493
                    device=torch_device,
494
                )
495
                inputs_dict["mc_labels"] = torch.zeros(
496
                    self.model_tester.batch_size, dtype=torch.long, device=torch_device
497
                )
498
        return inputs_dict
499

500
    def setUp(self):
501
        self.model_tester = GPT2ModelTester(self)
502
        self.config_tester = ConfigTester(self, config_class=GPT2Config, n_embd=37)
503

504
    def tearDown(self):
505
        super().tearDown()
506
        # clean-up as much as possible GPU memory occupied by PyTorch
507
        gc.collect()
508
        backend_empty_cache(torch_device)
509

510
    def test_config(self):
511
        self.config_tester.run_common_tests()
512

513
    def test_gpt2_model(self):
514
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
515
        self.model_tester.create_and_check_gpt2_model(*config_and_inputs)
516

517
    def test_gpt2_model_past(self):
518
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
519
        self.model_tester.create_and_check_gpt2_model_past(*config_and_inputs)
520

521
    def test_gpt2_model_att_mask_past(self):
522
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
523
        self.model_tester.create_and_check_gpt2_model_attention_mask_past(*config_and_inputs)
524

525
    def test_gpt2_model_past_large_inputs(self):
526
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
527
        self.model_tester.create_and_check_gpt2_model_past_large_inputs(*config_and_inputs)
528

529
    def test_gpt2_lm_head_model(self):
530
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
531
        self.model_tester.create_and_check_lm_head_model(*config_and_inputs)
532

533
    def test_gpt2_double_lm_head_model(self):
534
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
535
        self.model_tester.create_and_check_double_lm_head_model(*config_and_inputs)
536

537
    def test_gpt2_question_answering_model(self):
538
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
539
        self.model_tester.create_and_check_gpt2_for_question_answering(*config_and_inputs)
540

541
    def test_gpt2_sequence_classification_model(self):
542
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
543
        self.model_tester.create_and_check_gpt2_for_sequence_classification(*config_and_inputs)
544

545
    def test_gpt2_token_classification_model(self):
546
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
547
        self.model_tester.create_and_check_gpt2_for_token_classification(*config_and_inputs)
548

549
    def test_gpt2_gradient_checkpointing(self):
550
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
551
        self.model_tester.create_and_check_forward_and_backwards(*config_and_inputs, gradient_checkpointing=True)
552

553
    def test_gpt2_scale_attn_by_inverse_layer_idx(self):
554
        config_and_inputs = self.model_tester.prepare_config_and_inputs(scale_attn_by_inverse_layer_idx=True)
555
        self.model_tester.create_and_check_forward_and_backwards(*config_and_inputs)
556

557
    def test_gpt2_reorder_and_upcast_attn(self):
558
        config_and_inputs = self.model_tester.prepare_config_and_inputs(reorder_and_upcast_attn=True)
559
        self.model_tester.create_and_check_forward_and_backwards(*config_and_inputs)
560

561
    def test_gpt2_weight_initialization(self):
562
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
563
        self.model_tester.create_and_check_gpt2_weight_initialization(*config_and_inputs)
564

565
    @unittest.skip(
566
        reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
567
    )
568
    def test_training_gradient_checkpointing(self):
569
        pass
570

571
    @unittest.skip(
572
        reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
573
    )
574
    def test_training_gradient_checkpointing_use_reentrant(self):
575
        pass
576

577
    @unittest.skip(
578
        reason="This architecure seem to not compute gradients properly when using GC, check: https://github.com/huggingface/transformers/pull/27124"
579
    )
580
    def test_training_gradient_checkpointing_use_reentrant_false(self):
581
        pass
582

583
    @slow
584
    def test_batch_generation(self):
585
        model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2")
586
        model.to(torch_device)
587
        tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
588

589
        tokenizer.padding_side = "left"
590

591
        # Define PAD Token = EOS Token = 50256
592
        tokenizer.pad_token = tokenizer.eos_token
593
        model.config.pad_token_id = model.config.eos_token_id
594

595
        # use different length sentences to test batching
596
        sentences = [
597
            "Hello, my dog is a little",
598
            "Today, I",
599
        ]
600

601
        inputs = tokenizer(sentences, return_tensors="pt", padding=True)
602
        input_ids = inputs["input_ids"].to(torch_device)
603
        token_type_ids = torch.cat(
604
            [
605
                input_ids.new_full((input_ids.shape[0], input_ids.shape[1] - 1), 0),
606
                input_ids.new_full((input_ids.shape[0], 1), 500),
607
            ],
608
            dim=-1,
609
        )
610

611
        outputs = model.generate(
612
            input_ids=input_ids,
613
            attention_mask=inputs["attention_mask"].to(torch_device),
614
        )
615

616
        outputs_tt = model.generate(
617
            input_ids=input_ids,
618
            attention_mask=inputs["attention_mask"].to(torch_device),
619
            token_type_ids=token_type_ids,
620
        )
621

622
        inputs_non_padded = tokenizer(sentences[0], return_tensors="pt").input_ids.to(torch_device)
623
        output_non_padded = model.generate(input_ids=inputs_non_padded)
624

625
        num_paddings = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item()
626
        inputs_padded = tokenizer(sentences[1], return_tensors="pt").input_ids.to(torch_device)
627
        output_padded = model.generate(input_ids=inputs_padded, max_length=model.config.max_length - num_paddings)
628

629
        batch_out_sentence = tokenizer.batch_decode(outputs, skip_special_tokens=True)
630
        batch_out_sentence_tt = tokenizer.batch_decode(outputs_tt, skip_special_tokens=True)
631
        non_padded_sentence = tokenizer.decode(output_non_padded[0], skip_special_tokens=True)
632
        padded_sentence = tokenizer.decode(output_padded[0], skip_special_tokens=True)
633

634
        expected_output_sentence = [
635
            "Hello, my dog is a little bit of a mess. I'm not sure if he's going",
636
            "Today, I'm going to be doing a lot of research on this. I",
637
        ]
638
        self.assertListEqual(expected_output_sentence, batch_out_sentence)
639
        self.assertTrue(batch_out_sentence_tt != batch_out_sentence)  # token_type_ids should change output
640
        self.assertListEqual(expected_output_sentence, [non_padded_sentence, padded_sentence])
641

642
    @slow
643
    def test_batch_generation_2heads(self):
644
        model = GPT2DoubleHeadsModel.from_pretrained("openai-community/gpt2")
645
        model.to(torch_device)
646
        tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
647

648
        tokenizer.padding_side = "left"
649

650
        # This tokenizer has no pad token, so we have to set it in some way
651
        # Define PAD Token = EOS Token = 50256
652
        tokenizer.pad_token = tokenizer.eos_token
653
        model.config.pad_token_id = model.config.eos_token_id
654

655
        # use different length sentences to test batching
656
        sentences = [
657
            "Hello, my dog is a little",
658
            "Today, I",
659
        ]
660

661
        inputs = tokenizer(sentences, return_tensors="pt", padding=True)
662
        input_ids = inputs["input_ids"].to(torch_device)
663
        token_type_ids = torch.cat(
664
            [
665
                input_ids.new_full((input_ids.shape[0], input_ids.shape[1] - 1), 0),
666
                input_ids.new_full((input_ids.shape[0], 1), 500),
667
            ],
668
            dim=-1,
669
        )
670

671
        outputs = model.generate(
672
            input_ids=input_ids,
673
            attention_mask=inputs["attention_mask"].to(torch_device),
674
        )
675

676
        outputs_tt = model.generate(
677
            input_ids=input_ids,
678
            attention_mask=inputs["attention_mask"].to(torch_device),
679
            token_type_ids=token_type_ids,
680
        )
681

682
        inputs_non_padded = tokenizer(sentences[0], return_tensors="pt").input_ids.to(torch_device)
683
        output_non_padded = model.generate(input_ids=inputs_non_padded)
684

685
        num_paddings = inputs_non_padded.shape[-1] - inputs["attention_mask"][-1].long().sum().cpu().item()
686
        inputs_padded = tokenizer(sentences[1], return_tensors="pt").input_ids.to(torch_device)
687
        output_padded = model.generate(input_ids=inputs_padded, max_length=model.config.max_length - num_paddings)
688

689
        batch_out_sentence = tokenizer.batch_decode(outputs, skip_special_tokens=True)
690
        batch_out_sentence_tt = tokenizer.batch_decode(outputs_tt, skip_special_tokens=True)
691
        non_padded_sentence = tokenizer.decode(output_non_padded[0], skip_special_tokens=True)
692
        padded_sentence = tokenizer.decode(output_padded[0], skip_special_tokens=True)
693

694
        expected_output_sentence = [
695
            "Hello, my dog is a little bit of a mess. I'm not sure if he's going",
696
            "Today, I'm going to be doing a lot of research on this. I",
697
        ]
698
        self.assertListEqual(expected_output_sentence, batch_out_sentence)
699
        self.assertTrue(batch_out_sentence_tt != batch_out_sentence)  # token_type_ids should change output
700
        self.assertListEqual(expected_output_sentence, [non_padded_sentence, padded_sentence])
701

702
    @slow
703
    def test_model_from_pretrained(self):
704
        for model_name in GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
705
            model = GPT2Model.from_pretrained(model_name)
706
            self.assertIsNotNone(model)
707

708

709
@require_torch
710
class GPT2ModelLanguageGenerationTest(unittest.TestCase):
711
    def tearDown(self):
712
        super().tearDown()
713
        # clean-up as much as possible GPU memory occupied by PyTorch
714
        gc.collect()
715
        backend_empty_cache(torch_device)
716

717
    def _test_lm_generate_gpt2_helper(
718
        self,
719
        gradient_checkpointing=False,
720
        reorder_and_upcast_attn=False,
721
        scale_attn_by_inverse_layer_idx=False,
722
        verify_outputs=True,
723
    ):
724
        model = GPT2LMHeadModel.from_pretrained(
725
            "openai-community/gpt2",
726
            reorder_and_upcast_attn=reorder_and_upcast_attn,
727
            scale_attn_by_inverse_layer_idx=scale_attn_by_inverse_layer_idx,
728
        )
729
        if gradient_checkpointing:
730
            model.gradient_checkpointing_enable()
731
        else:
732
            model.gradient_checkpointing_disable()
733
        model.to(torch_device)
734

735
        # The dog
736
        input_ids = torch.tensor([[464, 3290]], dtype=torch.long, device=torch_device)
737

738
        # The dog was found in a field near the intersection of West and West Streets.\n\nThe dog
739
        expected_output_ids = [464, 3290, 373, 1043, 287, 257, 2214, 1474, 262, 16246, 286, 2688, 290, 2688, 27262, 13, 198, 198, 464, 3290,]  # fmt: skip
740
        output_ids = model.generate(input_ids, do_sample=False)
741
        if verify_outputs:
742
            self.assertListEqual(output_ids[0].tolist(), expected_output_ids)
743

744
    @slow
745
    def test_lm_generate_gpt2(self):
746
        self._test_lm_generate_gpt2_helper()
747

748
    @slow
749
    def test_lm_generate_gpt2_with_gradient_checkpointing(self):
750
        self._test_lm_generate_gpt2_helper(gradient_checkpointing=True)
751

752
    @slow
753
    def test_lm_generate_gpt2_with_reorder_and_upcast_attn(self):
754
        self._test_lm_generate_gpt2_helper(reorder_and_upcast_attn=True)
755

756
    @slow
757
    def test_lm_generate_gpt2_with_scale_attn_by_inverse_layer_idx(self):
758
        self._test_lm_generate_gpt2_helper(scale_attn_by_inverse_layer_idx=True, verify_outputs=False)
759

760
    @slow
761
    def test_gpt2_sample(self):
762
        tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
763
        model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2")
764
        model.to(torch_device)
765

766
        torch.manual_seed(0)
767
        tokenized = tokenizer("Today is a nice day and", return_tensors="pt", return_token_type_ids=True)
768
        input_ids = tokenized.input_ids.to(torch_device)
769
        output_ids = model.generate(input_ids, do_sample=True)
770
        output_str = tokenizer.decode(output_ids[0], skip_special_tokens=True)
771

772
        token_type_ids = tokenized.token_type_ids.to(torch_device)
773
        output_seq = model.generate(input_ids=input_ids, do_sample=True, num_return_sequences=5)
774
        output_seq_tt = model.generate(
775
            input_ids=input_ids, token_type_ids=token_type_ids, do_sample=True, num_return_sequences=5
776
        )
777
        output_seq_strs = tokenizer.batch_decode(output_seq, skip_special_tokens=True)
778
        output_seq_tt_strs = tokenizer.batch_decode(output_seq_tt, skip_special_tokens=True)
779

780
        EXPECTED_OUTPUT_STR = (
781
            "Today is a nice day and if you don't know anything about the state of play during your holiday"
782
        )
783
        self.assertEqual(output_str, EXPECTED_OUTPUT_STR)
784
        self.assertTrue(
785
            all(output_seq_strs[idx] != output_seq_tt_strs[idx] for idx in range(len(output_seq_tt_strs)))
786
        )  # token_type_ids should change output
787

788
    @slow
789
    def test_gpt2_sample_max_time(self):
790
        tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2")
791
        model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2")
792
        model.to(torch_device)
793

794
        torch.manual_seed(0)
795
        tokenized = tokenizer("Today is a nice day and", return_tensors="pt", return_token_type_ids=True)
796
        input_ids = tokenized.input_ids.to(torch_device)
797

798
        MAX_TIME = 0.5
799

800
        start = datetime.datetime.now()
801
        model.generate(input_ids, do_sample=True, max_time=MAX_TIME, max_length=256)
802
        duration = datetime.datetime.now() - start
803
        self.assertGreater(duration, datetime.timedelta(seconds=MAX_TIME))
804
        self.assertLess(duration, datetime.timedelta(seconds=1.5 * MAX_TIME))
805

806
        start = datetime.datetime.now()
807
        model.generate(input_ids, do_sample=False, max_time=MAX_TIME, max_length=256)
808
        duration = datetime.datetime.now() - start
809
        self.assertGreater(duration, datetime.timedelta(seconds=MAX_TIME))
810
        self.assertLess(duration, datetime.timedelta(seconds=1.5 * MAX_TIME))
811

812
        start = datetime.datetime.now()
813
        model.generate(input_ids, do_sample=False, num_beams=2, max_time=MAX_TIME, max_length=256)
814
        duration = datetime.datetime.now() - start
815
        self.assertGreater(duration, datetime.timedelta(seconds=MAX_TIME))
816
        self.assertLess(duration, datetime.timedelta(seconds=1.5 * MAX_TIME))
817

818
        start = datetime.datetime.now()
819
        model.generate(input_ids, do_sample=True, num_beams=2, max_time=MAX_TIME, max_length=256)
820
        duration = datetime.datetime.now() - start
821
        self.assertGreater(duration, datetime.timedelta(seconds=MAX_TIME))
822
        self.assertLess(duration, datetime.timedelta(seconds=1.5 * MAX_TIME))
823

824
        start = datetime.datetime.now()
825
        model.generate(input_ids, do_sample=False, max_time=None, max_length=256)
826
        duration = datetime.datetime.now() - start
827
        self.assertGreater(duration, datetime.timedelta(seconds=1.5 * MAX_TIME))
828

829
    @slow
830
    def test_contrastive_search_gpt2(self):
831
        article = (
832
            "DeepMind Technologies is a British artificial intelligence subsidiary of Alphabet Inc. and research "
833
            "laboratory founded in 2010. DeepMind was acquired by Google in 2014. The company is based"
834
        )
835

836
        gpt2_tokenizer = GPT2Tokenizer.from_pretrained("openai-community/gpt2-large")
837
        gpt2_model = GPT2LMHeadModel.from_pretrained("openai-community/gpt2-large").to(torch_device)
838
        input_ids = gpt2_tokenizer(article, return_tensors="pt").input_ids.to(torch_device)
839

840
        outputs = gpt2_model.generate(input_ids, penalty_alpha=0.6, top_k=4, max_length=256)
841

842
        generated_text = gpt2_tokenizer.batch_decode(outputs, skip_special_tokens=True)
843

844
        self.assertListEqual(
845
            generated_text,
846
            [
847
                "DeepMind Technologies is a British artificial intelligence subsidiary of Alphabet Inc. and research "
848
                "laboratory founded in 2010. DeepMind was acquired by Google in 2014. The company is based in London, "
849
                "United Kingdom\n\nGoogle has a lot of data on its users and uses it to improve its products, such as "
850
                "Google Now, which helps users find the information they're looking for on the web. But the company "
851
                "is not the only one to collect data on its users. Facebook, for example, has its own facial "
852
                "recognition technology, as well as a database of millions of photos that it uses to personalize its "
853
                "News Feed.\n\nFacebook's use of data is a hot topic in the tech industry, with privacy advocates "
854
                "concerned about the company's ability to keep users' information private. In a blog post last "
855
                'year, Facebook CEO Mark Zuckerberg said his company would "do our best to be transparent about our '
856
                'data use and how we use it."\n\n"We have made it clear that we do not sell or share your data with '
857
                'third parties," Zuckerberg wrote. "If you have questions or concerns, please reach out to us at '
858
                'privacy@facebook.com."\n\nGoogle declined to comment on the privacy implications of its use of data, '
859
                "but said in a statement to The Associated Press that"
860
            ],
861
        )
862

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

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

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

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