transformers

Форк
0
/
test_modeling_t5.py 
1633 строки · 80.2 Кб
1
# coding=utf-8
2
# Copyright 2018 Google T5 Authors and HuggingFace Inc. team.
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 copy
18
import os
19
import pickle
20
import tempfile
21
import unittest
22

23
from transformers import T5Config, is_torch_available
24
from transformers.models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES
25
from transformers.testing_utils import (
26
    require_accelerate,
27
    require_sentencepiece,
28
    require_tokenizers,
29
    require_torch,
30
    slow,
31
    torch_device,
32
)
33
from transformers.utils import cached_property, is_torch_fx_available
34

35
from ...generation.test_utils import GenerationTesterMixin
36
from ...test_configuration_common import ConfigTester
37
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, ids_tensor
38
from ...test_pipeline_mixin import PipelineTesterMixin
39

40

41
if is_torch_fx_available():
42
    from transformers.utils.fx import symbolic_trace
43

44

45
if is_torch_available():
46
    import torch
47

48
    from transformers import (
49
        AutoTokenizer,
50
        ByT5Tokenizer,
51
        T5EncoderModel,
52
        T5ForConditionalGeneration,
53
        T5ForQuestionAnswering,
54
        T5ForSequenceClassification,
55
        T5ForTokenClassification,
56
        T5Model,
57
        T5Tokenizer,
58
    )
59
    from transformers.models.t5.modeling_t5 import T5_PRETRAINED_MODEL_ARCHIVE_LIST
60

61

62
class T5ModelTester:
63
    def __init__(
64
        self,
65
        parent,
66
        vocab_size=99,
67
        batch_size=13,
68
        encoder_seq_length=7,
69
        decoder_seq_length=7,
70
        # For common tests
71
        is_training=True,
72
        use_attention_mask=True,
73
        use_labels=True,
74
        hidden_size=32,
75
        num_hidden_layers=2,
76
        num_attention_heads=4,
77
        d_ff=37,
78
        relative_attention_num_buckets=8,
79
        dropout_rate=0.1,
80
        initializer_factor=0.002,
81
        eos_token_id=1,
82
        pad_token_id=0,
83
        decoder_start_token_id=0,
84
        scope=None,
85
        decoder_layers=None,
86
    ):
87
        self.parent = parent
88
        self.batch_size = batch_size
89
        self.encoder_seq_length = encoder_seq_length
90
        self.decoder_seq_length = decoder_seq_length
91
        # For common tests
92
        self.seq_length = self.decoder_seq_length
93
        self.is_training = is_training
94
        self.use_attention_mask = use_attention_mask
95
        self.use_labels = use_labels
96
        self.vocab_size = vocab_size
97
        self.hidden_size = hidden_size
98
        self.num_hidden_layers = num_hidden_layers
99
        self.num_attention_heads = num_attention_heads
100
        self.d_ff = d_ff
101
        self.relative_attention_num_buckets = relative_attention_num_buckets
102
        self.dropout_rate = dropout_rate
103
        self.initializer_factor = initializer_factor
104
        self.eos_token_id = eos_token_id
105
        self.pad_token_id = pad_token_id
106
        self.decoder_start_token_id = decoder_start_token_id
107
        self.scope = None
108
        self.decoder_layers = decoder_layers
109

110
    def get_large_model_config(self):
111
        return T5Config.from_pretrained("google-t5/t5-base")
112

113
    def prepare_config_and_inputs(self):
114
        input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size).clamp(2)
115
        input_ids[:, -1] = self.eos_token_id  # Eos Token
116
        decoder_input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)
117

118
        attention_mask = None
119
        decoder_attention_mask = None
120
        if self.use_attention_mask:
121
            attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2)
122
            decoder_attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2)
123

124
        lm_labels = None
125
        if self.use_labels:
126
            lm_labels = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)
127

128
        config = self.get_config()
129

130
        return (
131
            config,
132
            input_ids,
133
            decoder_input_ids,
134
            attention_mask,
135
            decoder_attention_mask,
136
            lm_labels,
137
        )
138

139
    def get_pipeline_config(self):
140
        return T5Config(
141
            vocab_size=166,  # t5 forces 100 extra tokens
142
            d_model=self.hidden_size,
143
            d_ff=self.d_ff,
144
            d_kv=self.hidden_size // self.num_attention_heads,
145
            num_layers=self.num_hidden_layers,
146
            num_decoder_layers=self.decoder_layers,
147
            num_heads=self.num_attention_heads,
148
            relative_attention_num_buckets=self.relative_attention_num_buckets,
149
            dropout_rate=self.dropout_rate,
150
            initializer_factor=self.initializer_factor,
151
            eos_token_id=self.eos_token_id,
152
            bos_token_id=self.pad_token_id,
153
            pad_token_id=self.pad_token_id,
154
            decoder_start_token_id=self.decoder_start_token_id,
155
        )
156

157
    def get_config(self):
158
        return T5Config(
159
            vocab_size=self.vocab_size,
160
            d_model=self.hidden_size,
161
            d_ff=self.d_ff,
162
            d_kv=self.hidden_size // self.num_attention_heads,
163
            num_layers=self.num_hidden_layers,
164
            num_decoder_layers=self.decoder_layers,
165
            num_heads=self.num_attention_heads,
166
            relative_attention_num_buckets=self.relative_attention_num_buckets,
167
            dropout_rate=self.dropout_rate,
168
            initializer_factor=self.initializer_factor,
169
            eos_token_id=self.eos_token_id,
170
            bos_token_id=self.pad_token_id,
171
            pad_token_id=self.pad_token_id,
172
            decoder_start_token_id=self.decoder_start_token_id,
173
        )
174

175
    def check_prepare_lm_labels_via_shift_left(
176
        self,
177
        config,
178
        input_ids,
179
        decoder_input_ids,
180
        attention_mask,
181
        decoder_attention_mask,
182
        lm_labels,
183
    ):
184
        model = T5Model(config=config)
185
        model.to(torch_device)
186
        model.eval()
187

188
        # make sure that lm_labels are correctly padded from the right
189
        lm_labels.masked_fill_((lm_labels == self.decoder_start_token_id), self.eos_token_id)
190

191
        # add casaul pad token mask
192
        triangular_mask = torch.tril(lm_labels.new_ones(lm_labels.shape)).logical_not()
193
        lm_labels.masked_fill_(triangular_mask, self.pad_token_id)
194
        decoder_input_ids = model._shift_right(lm_labels)
195

196
        for i, (decoder_input_ids_slice, lm_labels_slice) in enumerate(zip(decoder_input_ids, lm_labels)):
197
            # first item
198
            self.parent.assertEqual(decoder_input_ids_slice[0].item(), self.decoder_start_token_id)
199
            if i < decoder_input_ids_slice.shape[-1]:
200
                if i < decoder_input_ids.shape[-1] - 1:
201
                    # items before diagonal
202
                    self.parent.assertListEqual(
203
                        decoder_input_ids_slice[1 : i + 1].tolist(), lm_labels_slice[:i].tolist()
204
                    )
205
                # pad items after diagonal
206
                if i < decoder_input_ids.shape[-1] - 2:
207
                    self.parent.assertListEqual(
208
                        decoder_input_ids_slice[i + 2 :].tolist(), lm_labels_slice[i + 1 : -1].tolist()
209
                    )
210
            else:
211
                # all items after square
212
                self.parent.assertListEqual(decoder_input_ids_slice[1:].tolist(), lm_labels_slice[:-1].tolist())
213

214
    def create_and_check_model(
215
        self,
216
        config,
217
        input_ids,
218
        decoder_input_ids,
219
        attention_mask,
220
        decoder_attention_mask,
221
        lm_labels,
222
    ):
223
        model = T5Model(config=config)
224
        model.to(torch_device)
225
        model.eval()
226
        result = model(
227
            input_ids=input_ids,
228
            decoder_input_ids=decoder_input_ids,
229
            attention_mask=attention_mask,
230
            decoder_attention_mask=decoder_attention_mask,
231
        )
232
        result = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)
233
        decoder_output = result.last_hidden_state
234
        decoder_past = result.past_key_values
235
        encoder_output = result.encoder_last_hidden_state
236

237
        self.parent.assertEqual(encoder_output.size(), (self.batch_size, self.encoder_seq_length, self.hidden_size))
238
        self.parent.assertEqual(decoder_output.size(), (self.batch_size, self.decoder_seq_length, self.hidden_size))
239
        # There should be `num_layers` key value embeddings stored in decoder_past
240
        self.parent.assertEqual(len(decoder_past), config.num_layers)
241
        # There should be a self attn key, a self attn value, a cross attn key and a cross attn value stored in each decoder_past tuple
242
        self.parent.assertEqual(len(decoder_past[0]), 4)
243

244
    def create_and_check_with_lm_head(
245
        self,
246
        config,
247
        input_ids,
248
        decoder_input_ids,
249
        attention_mask,
250
        decoder_attention_mask,
251
        lm_labels,
252
    ):
253
        model = T5ForConditionalGeneration(config=config).to(torch_device).eval()
254
        outputs = model(
255
            input_ids=input_ids,
256
            decoder_input_ids=decoder_input_ids,
257
            decoder_attention_mask=decoder_attention_mask,
258
            labels=lm_labels,
259
        )
260
        self.parent.assertEqual(len(outputs), 4)
261
        self.parent.assertEqual(outputs["logits"].size(), (self.batch_size, self.decoder_seq_length, self.vocab_size))
262
        self.parent.assertEqual(outputs["loss"].size(), ())
263

264
    def create_and_check_with_sequence_classification_head(
265
        self,
266
        config,
267
        input_ids,
268
        decoder_input_ids,
269
        attention_mask,
270
        decoder_attention_mask,
271
        lm_labels,
272
    ):
273
        labels = torch.tensor([1] * self.batch_size, dtype=torch.long, device=torch_device)
274
        model = T5ForSequenceClassification(config=config).to(torch_device).eval()
275
        outputs = model(
276
            input_ids=input_ids,
277
            decoder_input_ids=input_ids,
278
            labels=labels,
279
        )
280
        # self.parent.assertEqual(len(outputs), 4)
281
        self.parent.assertEqual(outputs["logits"].size(), (self.batch_size, config.num_labels))
282
        self.parent.assertEqual(outputs["loss"].size(), ())
283

284
    def create_and_check_decoder_model_past(
285
        self,
286
        config,
287
        input_ids,
288
        decoder_input_ids,
289
        attention_mask,
290
        decoder_attention_mask,
291
        lm_labels,
292
    ):
293
        model = T5Model(config=config).get_decoder().to(torch_device).eval()
294
        # first forward pass
295
        outputs = model(input_ids, use_cache=True)
296
        outputs_use_cache_conf = model(input_ids)
297
        outputs_no_past = model(input_ids, use_cache=False)
298

299
        self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))
300
        self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)
301

302
        output, past_key_values = outputs.to_tuple()
303

304
        # create hypothetical next token and extent to next_input_ids
305
        next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
306

307
        # append to next input_ids and
308
        next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
309

310
        output_from_no_past = model(next_input_ids)["last_hidden_state"]
311
        output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"]
312

313
        # select random slice
314
        random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
315
        output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach()
316
        output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
317

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

321
    def create_and_check_decoder_model_attention_mask_past(
322
        self,
323
        config,
324
        input_ids,
325
        decoder_input_ids,
326
        attention_mask,
327
        decoder_attention_mask,
328
        lm_labels,
329
    ):
330
        model = T5Model(config=config).get_decoder()
331
        model.to(torch_device)
332
        model.eval()
333

334
        # create attention mask
335
        attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
336

337
        half_seq_length = input_ids.shape[-1] // 2
338
        attn_mask[:, half_seq_length:] = 0
339

340
        # first forward pass
341
        output, past_key_values = model(input_ids, attention_mask=attn_mask, use_cache=True).to_tuple()
342

343
        # create hypothetical next token and extent to next_input_ids
344
        next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
345

346
        # change a random masked slice from input_ids
347
        random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1
348
        random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1)
349
        input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens
350

351
        # append to next input_ids and attn_mask
352
        next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
353
        attn_mask = torch.cat(
354
            [attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)],
355
            dim=1,
356
        )
357

358
        # get two different outputs
359
        output_from_no_past = model(next_input_ids, attention_mask=attn_mask)["last_hidden_state"]
360
        output_from_past = model(next_tokens, past_key_values=past_key_values, attention_mask=attn_mask)[
361
            "last_hidden_state"
362
        ]
363

364
        # select random slice
365
        random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
366
        output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach()
367
        output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
368

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

372
    def create_and_check_decoder_model_past_large_inputs(
373
        self,
374
        config,
375
        input_ids,
376
        decoder_input_ids,
377
        attention_mask,
378
        decoder_attention_mask,
379
        lm_labels,
380
    ):
381
        model = T5Model(config=config).get_decoder().to(torch_device).eval()
382
        # first forward pass
383
        outputs = model(input_ids, attention_mask=attention_mask, use_cache=True)
384

385
        output, past_key_values = outputs.to_tuple()
386

387
        # create hypothetical multiple next token and extent to next_input_ids
388
        next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
389
        next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
390

391
        # append to next input_ids and
392
        next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
393
        next_attention_mask = torch.cat([attention_mask, next_mask], dim=-1)
394

395
        output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"]
396
        output_from_past = model(next_tokens, attention_mask=next_attention_mask, past_key_values=past_key_values)[
397
            "last_hidden_state"
398
        ]
399

400
        # select random slice
401
        random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
402
        output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
403
        output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
404

405
        self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
406

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

410
    def create_and_check_generate_with_past_key_values(
411
        self,
412
        config,
413
        input_ids,
414
        decoder_input_ids,
415
        attention_mask,
416
        decoder_attention_mask,
417
        lm_labels,
418
    ):
419
        model = T5ForConditionalGeneration(config=config).to(torch_device).eval()
420
        torch.manual_seed(0)
421
        output_without_past_cache = model.generate(
422
            input_ids[:1], num_beams=2, max_length=5, do_sample=True, use_cache=False
423
        )
424
        torch.manual_seed(0)
425
        output_with_past_cache = model.generate(input_ids[:1], num_beams=2, max_length=5, do_sample=True)
426
        self.parent.assertTrue(torch.all(output_with_past_cache == output_without_past_cache))
427

428
    def create_and_check_model_fp16_forward(
429
        self,
430
        config,
431
        input_ids,
432
        decoder_input_ids,
433
        attention_mask,
434
        decoder_attention_mask,
435
        lm_labels,
436
    ):
437
        model = T5Model(config=config).to(torch_device).half().eval()
438
        output = model(input_ids, decoder_input_ids=input_ids, attention_mask=attention_mask)["last_hidden_state"]
439
        self.parent.assertFalse(torch.isnan(output).any().item())
440

441
    def create_and_check_encoder_decoder_shared_weights(
442
        self,
443
        config,
444
        input_ids,
445
        decoder_input_ids,
446
        attention_mask,
447
        decoder_attention_mask,
448
        lm_labels,
449
    ):
450
        for model_class in [T5Model, T5ForConditionalGeneration]:
451
            torch.manual_seed(0)
452
            model = model_class(config=config).to(torch_device).eval()
453
            # load state dict copies weights but does not tie them
454
            model.encoder.load_state_dict(model.decoder.state_dict(), strict=False)
455

456
            torch.manual_seed(0)
457
            tied_config = copy.deepcopy(config)
458
            tied_config.tie_encoder_decoder = True
459
            tied_model = model_class(config=tied_config).to(torch_device).eval()
460

461
            model_result = model(
462
                input_ids=input_ids,
463
                decoder_input_ids=decoder_input_ids,
464
                attention_mask=attention_mask,
465
                decoder_attention_mask=decoder_attention_mask,
466
            )
467

468
            tied_model_result = tied_model(
469
                input_ids=input_ids,
470
                decoder_input_ids=decoder_input_ids,
471
                attention_mask=attention_mask,
472
                decoder_attention_mask=decoder_attention_mask,
473
            )
474

475
            # check that models has less parameters
476
            self.parent.assertLess(
477
                sum(p.numel() for p in tied_model.parameters()), sum(p.numel() for p in model.parameters())
478
            )
479
            random_slice_idx = ids_tensor((1,), model_result[0].shape[-1]).item()
480

481
            # check that outputs are equal
482
            self.parent.assertTrue(
483
                torch.allclose(
484
                    model_result[0][0, :, random_slice_idx], tied_model_result[0][0, :, random_slice_idx], atol=1e-4
485
                )
486
            )
487

488
            # check that outputs after saving and loading are equal
489
            with tempfile.TemporaryDirectory() as tmpdirname:
490
                tied_model.save_pretrained(tmpdirname)
491
                tied_model = model_class.from_pretrained(tmpdirname)
492
                tied_model.to(torch_device)
493
                tied_model.eval()
494

495
                # check that models has less parameters
496
                self.parent.assertLess(
497
                    sum(p.numel() for p in tied_model.parameters()), sum(p.numel() for p in model.parameters())
498
                )
499
                random_slice_idx = ids_tensor((1,), model_result[0].shape[-1]).item()
500

501
                tied_model_result = tied_model(
502
                    input_ids=input_ids,
503
                    decoder_input_ids=decoder_input_ids,
504
                    attention_mask=attention_mask,
505
                    decoder_attention_mask=decoder_attention_mask,
506
                )
507

508
                # check that outputs are equal
509
                self.parent.assertTrue(
510
                    torch.allclose(
511
                        model_result[0][0, :, random_slice_idx],
512
                        tied_model_result[0][0, :, random_slice_idx],
513
                        atol=1e-4,
514
                    )
515
                )
516

517
    def check_resize_embeddings_t5_v1_1(
518
        self,
519
        config,
520
    ):
521
        prev_vocab_size = config.vocab_size
522

523
        config.tie_word_embeddings = False
524
        model = T5ForConditionalGeneration(config=config).to(torch_device).eval()
525
        model.resize_token_embeddings(prev_vocab_size - 10)
526

527
        self.parent.assertEqual(model.get_input_embeddings().weight.shape[0], prev_vocab_size - 10)
528
        self.parent.assertEqual(model.get_output_embeddings().weight.shape[0], prev_vocab_size - 10)
529
        self.parent.assertEqual(model.config.vocab_size, prev_vocab_size - 10)
530

531
    def prepare_config_and_inputs_for_common(self):
532
        config_and_inputs = self.prepare_config_and_inputs()
533
        (
534
            config,
535
            input_ids,
536
            decoder_input_ids,
537
            attention_mask,
538
            decoder_attention_mask,
539
            lm_labels,
540
        ) = config_and_inputs
541

542
        inputs_dict = {
543
            "input_ids": input_ids,
544
            "attention_mask": attention_mask,
545
            "decoder_input_ids": decoder_input_ids,
546
            "decoder_attention_mask": decoder_attention_mask,
547
            "use_cache": False,
548
        }
549
        return config, inputs_dict
550

551

552
@require_torch
553
class T5ModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
554
    all_model_classes = (
555
        (T5Model, T5ForConditionalGeneration, T5ForSequenceClassification, T5ForQuestionAnswering)
556
        if is_torch_available()
557
        else ()
558
    )
559
    all_generative_model_classes = (T5ForConditionalGeneration,) if is_torch_available() else ()
560
    pipeline_model_mapping = (
561
        {
562
            "conversational": T5ForConditionalGeneration,
563
            "feature-extraction": T5Model,
564
            "question-answering": T5ForQuestionAnswering,
565
            "summarization": T5ForConditionalGeneration,
566
            "text-classification": T5ForSequenceClassification,
567
            "text2text-generation": T5ForConditionalGeneration,
568
            "translation": T5ForConditionalGeneration,
569
            "zero-shot": T5ForSequenceClassification,
570
        }
571
        if is_torch_available()
572
        else {}
573
    )
574
    all_parallelizable_model_classes = (T5Model, T5ForConditionalGeneration) if is_torch_available() else ()
575
    fx_compatible = True
576
    test_pruning = False
577
    test_resize_embeddings = True
578
    test_model_parallel = True
579
    is_encoder_decoder = True
580
    # The small T5 model needs higher percentages for CPU/MP tests
581
    model_split_percents = [0.8, 0.9]
582

583
    def setUp(self):
584
        self.model_tester = T5ModelTester(self)
585
        self.config_tester = ConfigTester(self, config_class=T5Config, d_model=37)
586

587
    # `QAPipelineTests` is not working well with slow tokenizers (for some models) and we don't want to touch the file
588
    # `src/transformers/data/processors/squad.py` (where this test fails for this model)
589
    def is_pipeline_test_to_skip(
590
        self, pipeline_test_case_name, config_class, model_architecture, tokenizer_name, processor_name
591
    ):
592
        if tokenizer_name is None:
593
            return True
594
        if pipeline_test_case_name == "QAPipelineTests" and not tokenizer_name.endswith("Fast"):
595
            return True
596

597
        return False
598

599
    def _create_and_check_torch_fx_tracing(self, config, inputs_dict, output_loss=False):
600
        if not is_torch_fx_available() or not self.fx_compatible:
601
            return
602

603
        configs_no_init = _config_zero_init(config)  # To be sure we have no Nan
604
        configs_no_init.return_dict = False
605

606
        for model_class in self.all_model_classes:
607
            if model_class.__name__ == "T5ForSequenceClassification":
608
                continue
609
            model = model_class(config=configs_no_init)
610
            model.to(torch_device)
611
            model.eval()
612
            inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=output_loss)
613

614
            try:
615
                if model.config.is_encoder_decoder:
616
                    model.config.use_cache = False  # FSTM still requires this hack -> FSTM should probably be refactored similar to BART afterward
617
                    labels = inputs.get("labels", None)
618
                    input_names = [
619
                        "attention_mask",
620
                        "decoder_attention_mask",
621
                        "decoder_input_ids",
622
                        "input_features",
623
                        "input_ids",
624
                        "input_values",
625
                    ]
626
                    if labels is not None:
627
                        input_names.append("labels")
628

629
                    filtered_inputs = {k: v for (k, v) in inputs.items() if k in input_names}
630
                    input_names = list(filtered_inputs.keys())
631

632
                    model_output = model(**filtered_inputs)
633

634
                    traced_model = symbolic_trace(model, input_names)
635
                    traced_output = traced_model(**filtered_inputs)
636
                else:
637
                    input_names = [
638
                        "attention_mask",
639
                        "bbox",
640
                        "input_features",
641
                        "input_ids",
642
                        "input_values",
643
                        "pixel_values",
644
                        "token_type_ids",
645
                        "visual_feats",
646
                        "visual_pos",
647
                    ]
648

649
                    labels = inputs.get("labels", None)
650
                    start_positions = inputs.get("start_positions", None)
651
                    end_positions = inputs.get("end_positions", None)
652
                    if labels is not None:
653
                        input_names.append("labels")
654
                    if start_positions is not None:
655
                        input_names.append("start_positions")
656
                    if end_positions is not None:
657
                        input_names.append("end_positions")
658

659
                    filtered_inputs = {k: v for (k, v) in inputs.items() if k in input_names}
660
                    input_names = list(filtered_inputs.keys())
661

662
                    if model.__class__.__name__ in set(MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES.values()) and (
663
                        not hasattr(model.config, "problem_type") or model.config.problem_type is None
664
                    ):
665
                        model.config.problem_type = "single_label_classification"
666

667
                    traced_model = symbolic_trace(model, input_names)
668
                    traced_output = traced_model(**filtered_inputs)
669
                    model_output = model(**filtered_inputs)
670

671
            except Exception as e:
672
                self.fail(f"Couldn't trace module: {e}")
673

674
            def flatten_output(output):
675
                flatten = []
676
                for x in output:
677
                    if isinstance(x, (tuple, list)):
678
                        flatten += flatten_output(x)
679
                    elif not isinstance(x, torch.Tensor):
680
                        continue
681
                    else:
682
                        flatten.append(x)
683
                return flatten
684

685
            model_output = flatten_output(model_output)
686
            traced_output = flatten_output(traced_output)
687
            num_outputs = len(model_output)
688

689
            for i in range(num_outputs):
690
                self.assertTrue(
691
                    torch.allclose(model_output[i], traced_output[i]),
692
                    f"traced {i}th output doesn't match model {i}th output for {model_class}",
693
                )
694

695
            # Test that the model can be serialized and restored properly
696
            with tempfile.TemporaryDirectory() as tmp_dir_name:
697
                pkl_file_name = os.path.join(tmp_dir_name, "model.pkl")
698
                try:
699
                    with open(pkl_file_name, "wb") as f:
700
                        pickle.dump(traced_model, f)
701
                    with open(pkl_file_name, "rb") as f:
702
                        loaded = pickle.load(f)
703
                except Exception as e:
704
                    self.fail(f"Couldn't serialize / deserialize the traced model: {e}")
705

706
                loaded_output = loaded(**filtered_inputs)
707
                loaded_output = flatten_output(loaded_output)
708

709
                for i in range(num_outputs):
710
                    self.assertTrue(
711
                        torch.allclose(model_output[i], loaded_output[i]),
712
                        f"serialized model {i}th output doesn't match model {i}th output for {model_class}",
713
                    )
714

715
            # Avoid memory leak. Without this, each call increase RAM usage by ~20MB.
716
            # (Even with this call, there are still memory leak by ~0.04MB)
717
            self.clear_torch_jit_class_registry()
718

719
    def test_config(self):
720
        self.config_tester.run_common_tests()
721

722
    def test_shift_right(self):
723
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
724
        self.model_tester.check_prepare_lm_labels_via_shift_left(*config_and_inputs)
725

726
    def test_model(self):
727
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
728
        self.model_tester.create_and_check_model(*config_and_inputs)
729

730
    def test_model_v1_1(self):
731
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
732
        # check that gated gelu feed forward and different word embeddings work
733
        config = config_and_inputs[0]
734
        config.tie_word_embeddings = False
735
        config.feed_forward_proj = "gated-gelu"
736
        self.model_tester.create_and_check_model(config, *config_and_inputs[1:])
737

738
    # T5ForSequenceClassification does not support inputs_embeds
739
    def test_inputs_embeds(self):
740
        config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
741

742
        for model_class in (T5Model, T5ForConditionalGeneration, T5ForQuestionAnswering):
743
            model = model_class(config)
744
            model.to(torch_device)
745
            model.eval()
746

747
            inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class))
748

749
            if not self.is_encoder_decoder:
750
                input_ids = inputs["input_ids"]
751
                del inputs["input_ids"]
752
            else:
753
                encoder_input_ids = inputs["input_ids"]
754
                decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids)
755
                del inputs["input_ids"]
756
                inputs.pop("decoder_input_ids", None)
757

758
            wte = model.get_input_embeddings()
759
            if not self.is_encoder_decoder:
760
                inputs["inputs_embeds"] = wte(input_ids)
761
            else:
762
                inputs["inputs_embeds"] = wte(encoder_input_ids)
763
                inputs["decoder_inputs_embeds"] = wte(decoder_input_ids)
764

765
            with torch.no_grad():
766
                model(**inputs)[0]
767

768
    def test_config_and_model_silu_gated(self):
769
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
770
        config = config_and_inputs[0]
771
        config.feed_forward_proj = "gated-silu"
772
        self.model_tester.create_and_check_model(*config_and_inputs)
773

774
    def test_with_lm_head(self):
775
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
776
        self.model_tester.create_and_check_with_lm_head(*config_and_inputs)
777

778
    def test_with_sequence_classification_head(self):
779
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
780
        self.model_tester.create_and_check_with_sequence_classification_head(*config_and_inputs)
781

782
    def test_decoder_model_past(self):
783
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
784
        self.model_tester.create_and_check_decoder_model_past(*config_and_inputs)
785

786
    def test_decoder_model_past_with_attn_mask(self):
787
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
788
        self.model_tester.create_and_check_decoder_model_attention_mask_past(*config_and_inputs)
789

790
    def test_decoder_model_past_with_3d_attn_mask(self):
791
        (
792
            config,
793
            input_ids,
794
            decoder_input_ids,
795
            attention_mask,
796
            decoder_attention_mask,
797
            lm_labels,
798
        ) = self.model_tester.prepare_config_and_inputs()
799

800
        attention_mask = ids_tensor(
801
            [self.model_tester.batch_size, self.model_tester.encoder_seq_length, self.model_tester.encoder_seq_length],
802
            vocab_size=2,
803
        )
804
        decoder_attention_mask = ids_tensor(
805
            [self.model_tester.batch_size, self.model_tester.decoder_seq_length, self.model_tester.decoder_seq_length],
806
            vocab_size=2,
807
        )
808

809
        self.model_tester.create_and_check_decoder_model_attention_mask_past(
810
            config,
811
            input_ids,
812
            decoder_input_ids,
813
            attention_mask,
814
            decoder_attention_mask,
815
            lm_labels,
816
        )
817

818
    def test_decoder_model_past_with_large_inputs(self):
819
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
820
        self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
821

822
    def test_generate_with_past_key_values(self):
823
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
824
        self.model_tester.create_and_check_generate_with_past_key_values(*config_and_inputs)
825

826
    def test_encoder_decoder_shared_weights(self):
827
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
828
        self.model_tester.create_and_check_encoder_decoder_shared_weights(*config_and_inputs)
829

830
    @unittest.skipIf(torch_device == "cpu", "Cant do half precision")
831
    def test_model_fp16_forward(self):
832
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
833
        self.model_tester.create_and_check_model_fp16_forward(*config_and_inputs)
834

835
    def test_v1_1_resize_embeddings(self):
836
        config = self.model_tester.prepare_config_and_inputs()[0]
837
        self.model_tester.check_resize_embeddings_t5_v1_1(config)
838

839
    @slow
840
    def test_model_from_pretrained(self):
841
        for model_name in T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
842
            model = T5Model.from_pretrained(model_name)
843
            self.assertIsNotNone(model)
844

845
    @unittest.skip("Test has a segmentation fault on torch 1.8.0")
846
    def test_export_to_onnx(self):
847
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
848
        model = T5Model(config_and_inputs[0]).to(torch_device)
849
        with tempfile.TemporaryDirectory() as tmpdirname:
850
            torch.onnx.export(
851
                model,
852
                (config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]),
853
                f"{tmpdirname}/t5_test.onnx",
854
                export_params=True,
855
                opset_version=9,
856
                input_names=["input_ids", "decoder_input_ids"],
857
            )
858

859
    def test_generate_with_head_masking(self):
860
        attention_names = ["encoder_attentions", "decoder_attentions", "cross_attentions"]
861
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
862
        config = config_and_inputs[0]
863
        max_length = config_and_inputs[1].shape[-1] + 3
864
        model = T5ForConditionalGeneration(config).eval()
865
        model.to(torch_device)
866

867
        head_masking = {
868
            "head_mask": torch.zeros(config.num_layers, config.num_heads, device=torch_device),
869
            "decoder_head_mask": torch.zeros(config.num_decoder_layers, config.num_heads, device=torch_device),
870
            "cross_attn_head_mask": torch.zeros(config.num_decoder_layers, config.num_heads, device=torch_device),
871
        }
872

873
        for attn_name, (name, mask) in zip(attention_names, head_masking.items()):
874
            head_masks = {name: mask}
875
            # Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified
876
            if name == "head_mask":
877
                head_masks["decoder_head_mask"] = torch.ones(
878
                    config.num_decoder_layers, config.num_heads, device=torch_device
879
                )
880

881
            out = model.generate(
882
                config_and_inputs[1],
883
                num_beams=1,
884
                max_length=max_length,
885
                output_attentions=True,
886
                return_dict_in_generate=True,
887
                **head_masks,
888
            )
889
            # We check the state of decoder_attentions and cross_attentions just from the last step
890
            attn_weights = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1]
891
            self.assertEqual(sum([w.sum().item() for w in attn_weights]), 0.0)
892

893
    @unittest.skip("Does not work on the tiny model as we keep hitting edge cases.")
894
    def test_disk_offload(self):
895
        pass
896

897
    @unittest.skip("Does not support conversations.")
898
    def test_pipeline_conversational(self):
899
        pass
900

901

902
class T5EncoderOnlyModelTester:
903
    def __init__(
904
        self,
905
        parent,
906
        vocab_size=99,
907
        batch_size=13,
908
        encoder_seq_length=7,
909
        # For common tests
910
        use_attention_mask=True,
911
        hidden_size=32,
912
        num_hidden_layers=2,
913
        num_attention_heads=4,
914
        d_ff=37,
915
        relative_attention_num_buckets=8,
916
        is_training=False,
917
        dropout_rate=0.1,
918
        initializer_factor=0.002,
919
        is_encoder_decoder=False,
920
        eos_token_id=1,
921
        pad_token_id=0,
922
        scope=None,
923
    ):
924
        self.parent = parent
925
        self.batch_size = batch_size
926
        self.encoder_seq_length = encoder_seq_length
927
        # For common tests
928
        self.seq_length = self.encoder_seq_length
929
        self.use_attention_mask = use_attention_mask
930
        self.vocab_size = vocab_size
931
        self.hidden_size = hidden_size
932
        self.num_hidden_layers = num_hidden_layers
933
        self.num_attention_heads = num_attention_heads
934
        self.d_ff = d_ff
935
        self.relative_attention_num_buckets = relative_attention_num_buckets
936
        self.dropout_rate = dropout_rate
937
        self.initializer_factor = initializer_factor
938
        self.eos_token_id = eos_token_id
939
        self.pad_token_id = pad_token_id
940
        self.is_encoder_decoder = is_encoder_decoder
941
        self.scope = None
942
        self.is_training = is_training
943

944
    def get_large_model_config(self):
945
        return T5Config.from_pretrained("google-t5/t5-base")
946

947
    def prepare_config_and_inputs(self):
948
        input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size)
949

950
        attention_mask = None
951
        if self.use_attention_mask:
952
            attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2)
953

954
        config = T5Config(
955
            vocab_size=self.vocab_size,
956
            d_model=self.hidden_size,
957
            d_ff=self.d_ff,
958
            d_kv=self.hidden_size // self.num_attention_heads,
959
            num_layers=self.num_hidden_layers,
960
            num_heads=self.num_attention_heads,
961
            relative_attention_num_buckets=self.relative_attention_num_buckets,
962
            dropout_rate=self.dropout_rate,
963
            initializer_factor=self.initializer_factor,
964
            eos_token_id=self.eos_token_id,
965
            bos_token_id=self.pad_token_id,
966
            pad_token_id=self.pad_token_id,
967
            is_encoder_decoder=self.is_encoder_decoder,
968
        )
969

970
        return (
971
            config,
972
            input_ids,
973
            attention_mask,
974
        )
975

976
    def create_and_check_model(
977
        self,
978
        config,
979
        input_ids,
980
        attention_mask,
981
    ):
982
        model = T5EncoderModel(config=config)
983
        model.to(torch_device)
984
        model.eval()
985
        result = model(
986
            input_ids=input_ids,
987
            attention_mask=attention_mask,
988
        )
989
        result = model(input_ids=input_ids)
990
        encoder_output = result.last_hidden_state
991

992
        self.parent.assertEqual(encoder_output.size(), (self.batch_size, self.encoder_seq_length, self.hidden_size))
993

994
    def create_and_check_model_fp16_forward(
995
        self,
996
        config,
997
        input_ids,
998
        attention_mask,
999
    ):
1000
        model = T5EncoderModel(config=config).to(torch_device).half().eval()
1001
        output = model(input_ids, attention_mask=attention_mask)["last_hidden_state"]
1002
        self.parent.assertFalse(torch.isnan(output).any().item())
1003

1004
    def create_and_check_with_token_classification_head(
1005
        self,
1006
        config,
1007
        input_ids,
1008
        attention_mask,
1009
    ):
1010
        labels = torch.tensor([1] * self.seq_length * self.batch_size, dtype=torch.long, device=torch_device)
1011
        model = T5ForTokenClassification(config=config).to(torch_device).eval()
1012
        outputs = model(
1013
            input_ids=input_ids,
1014
            labels=labels,
1015
            attention_mask=attention_mask,
1016
        )
1017
        self.parent.assertEqual(outputs["logits"].size(), (self.batch_size, self.seq_length, config.num_labels))
1018
        self.parent.assertEqual(outputs["loss"].size(), ())
1019

1020
    def prepare_config_and_inputs_for_common(self):
1021
        config_and_inputs = self.prepare_config_and_inputs()
1022
        (
1023
            config,
1024
            input_ids,
1025
            attention_mask,
1026
        ) = config_and_inputs
1027

1028
        inputs_dict = {
1029
            "input_ids": input_ids,
1030
            "attention_mask": attention_mask,
1031
        }
1032
        return config, inputs_dict
1033

1034

1035
class T5EncoderOnlyModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
1036
    all_model_classes = (T5EncoderModel, T5ForTokenClassification) if is_torch_available() else ()
1037
    test_pruning = False
1038
    test_resize_embeddings = False
1039
    test_model_parallel = True
1040
    pipeline_model_mapping = (
1041
        {
1042
            "token-classification": T5ForTokenClassification,
1043
        }
1044
        if is_torch_available()
1045
        else {}
1046
    )
1047
    all_parallelizable_model_classes = (T5EncoderModel,) if is_torch_available() else ()
1048

1049
    def setUp(self):
1050
        self.model_tester = T5EncoderOnlyModelTester(self)
1051
        self.config_tester = ConfigTester(self, config_class=T5Config, d_model=37)
1052

1053
    def test_config(self):
1054
        self.config_tester.run_common_tests()
1055

1056
    def test_model(self):
1057
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
1058
        self.model_tester.create_and_check_model(*config_and_inputs)
1059

1060
    @unittest.skipIf(torch_device == "cpu", "Cant do half precision")
1061
    def test_model_fp16_forward(self):
1062
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
1063
        self.model_tester.create_and_check_model_fp16_forward(*config_and_inputs)
1064

1065
    def test_with_token_classification_head(self):
1066
        config_and_inputs = self.model_tester.prepare_config_and_inputs()
1067
        self.model_tester.create_and_check_with_token_classification_head(*config_and_inputs)
1068

1069

1070
def use_task_specific_params(model, task):
1071
    model.config.update(model.config.task_specific_params[task])
1072

1073

1074
@require_torch
1075
@require_accelerate
1076
@require_tokenizers
1077
@slow
1078
class T5ModelFp16Tests(unittest.TestCase):
1079
    def test_fp16_fp32_conversion(self):
1080
        r"""
1081
        A test to check whether the argument `keep_in_fp32_modules` correctly does its job
1082
        """
1083
        orig_import = __import__
1084
        accelerate_mock = unittest.mock.Mock()
1085

1086
        # mock import of accelerate
1087
        def import_accelerate_mock(name, *args, **kwargs):
1088
            if name == "accelerate":
1089
                if accelerate_available:
1090
                    return accelerate_mock
1091
                else:
1092
                    raise ImportError
1093
            return orig_import(name, *args, **kwargs)
1094

1095
        # Load without using `accelerate`
1096
        with unittest.mock.patch("builtins.__import__", side_effect=import_accelerate_mock):
1097
            accelerate_available = False
1098

1099
            model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small", torch_dtype=torch.float16)
1100
            self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.float32)
1101
            self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wi.weight.dtype == torch.float16)
1102

1103
            # Load without in bf16
1104
            model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small", torch_dtype=torch.bfloat16)
1105
            self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.bfloat16)
1106
            self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wi.weight.dtype == torch.bfloat16)
1107

1108
        # Load using `accelerate` in bf16
1109
        model = T5ForConditionalGeneration.from_pretrained(
1110
            "google-t5/t5-small", torch_dtype=torch.bfloat16, device_map="auto"
1111
        )
1112
        self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.bfloat16)
1113
        self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wi.weight.dtype == torch.bfloat16)
1114

1115
        # Load using `accelerate` in bf16
1116
        model = T5ForConditionalGeneration.from_pretrained(
1117
            "google-t5/t5-small", torch_dtype=torch.bfloat16, low_cpu_mem_usage=True
1118
        )
1119
        self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.bfloat16)
1120
        self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wi.weight.dtype == torch.bfloat16)
1121

1122
        # Load without using `accelerate`
1123
        model = T5ForConditionalGeneration.from_pretrained(
1124
            "google-t5/t5-small", torch_dtype=torch.float16, low_cpu_mem_usage=True
1125
        )
1126
        self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.float32)
1127
        self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wi.weight.dtype == torch.float16)
1128

1129
        # Load using `accelerate`
1130
        model = T5ForConditionalGeneration.from_pretrained(
1131
            "google-t5/t5-small", torch_dtype=torch.float16, device_map="auto"
1132
        )
1133
        self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.float32)
1134
        self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wi.weight.dtype == torch.float16)
1135

1136

1137
@require_torch
1138
@require_sentencepiece
1139
@require_tokenizers
1140
class T5ModelIntegrationTests(unittest.TestCase):
1141
    @cached_property
1142
    def model(self):
1143
        return T5ForConditionalGeneration.from_pretrained("google-t5/t5-base").to(torch_device)
1144

1145
    @cached_property
1146
    def tokenizer(self):
1147
        return T5Tokenizer.from_pretrained("google-t5/t5-base")
1148

1149
    @slow
1150
    def test_torch_quant(self):
1151
        r"""
1152
        Test that a simple `torch.quantization.quantize_dynamic` call works on a T5 model.
1153
        """
1154
        model_name = "google/flan-t5-small"
1155
        tokenizer = T5Tokenizer.from_pretrained(model_name)
1156
        model = T5ForConditionalGeneration.from_pretrained(model_name)
1157
        model = torch.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=torch.qint8)
1158
        input_text = "Answer the following yes/no question by reasoning step-by-step. Can you write a whole Haiku in a single tweet?"
1159
        input_ids = tokenizer(input_text, return_tensors="pt").input_ids
1160
        _ = model.generate(input_ids)
1161

1162
    @slow
1163
    def test_small_generation(self):
1164
        model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small").to(torch_device)
1165
        model.config.max_length = 8
1166
        model.config.num_beams = 1
1167
        model.config.do_sample = False
1168
        tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small")
1169

1170
        input_ids = tokenizer("summarize: Hello there", return_tensors="pt").input_ids.to(torch_device)
1171

1172
        sequences = model.generate(input_ids)
1173

1174
        output_str = tokenizer.batch_decode(sequences, skip_special_tokens=True)[0]
1175
        self.assertTrue(output_str == "Hello there!")
1176

1177
    @slow
1178
    def test_small_integration_test(self):
1179
        """
1180
        For comparision run:
1181
        >>> import t5  # pip install t5==0.7.1
1182
        >>> from t5.data.sentencepiece_vocabulary import SentencePieceVocabulary
1183

1184
        >>> path_to_mtf_small_t5_checkpoint = '<fill_in>'
1185
        >>> path_to_mtf_small_spm_model_path = '<fill_in>'
1186
        >>> t5_model = t5.models.MtfModel(model_dir=path_to_mtf_small_t5_checkpoint, batch_size=1, tpu=None)
1187
        >>> vocab = SentencePieceVocabulary(path_to_mtf_small_spm_model_path, extra_ids=100)
1188
        >>> score = t5_model.score(inputs=["Hello there"], targets=["Hi I am"], vocabulary=vocab)
1189
        """
1190

1191
        model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small").to(torch_device)
1192
        tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small")
1193

1194
        input_ids = tokenizer("Hello there", return_tensors="pt").input_ids
1195
        labels = tokenizer("Hi I am", return_tensors="pt").input_ids
1196

1197
        loss = model(input_ids.to(torch_device), labels=labels.to(torch_device)).loss
1198
        mtf_score = -(labels.shape[-1] * loss.item())
1199

1200
        EXPECTED_SCORE = -19.0845
1201
        self.assertTrue(abs(mtf_score - EXPECTED_SCORE) < 1e-4)
1202

1203
    @slow
1204
    def test_small_v1_1_integration_test(self):
1205
        """
1206
        For comparision run:
1207
        >>> import t5  # pip install t5==0.7.1
1208
        >>> from t5.data.sentencepiece_vocabulary import SentencePieceVocabulary
1209

1210
        >>> path_to_mtf_small_t5_v1_1_checkpoint = '<fill_in>'
1211
        >>> path_to_mtf_small_spm_model_path = '<fill_in>'
1212
        >>> t5_model = t5.models.MtfModel(model_dir=path_to_mtf_small_t5_v1_1_checkpoint, batch_size=1, tpu=None)
1213
        >>> vocab = SentencePieceVocabulary(path_to_mtf_small_spm_model_path, extra_ids=100)
1214
        >>> score = t5_model.score(inputs=["Hello there"], targets=["Hi I am"], vocabulary=vocab)
1215
        """
1216

1217
        model = T5ForConditionalGeneration.from_pretrained("google/t5-v1_1-small").to(torch_device)
1218
        tokenizer = T5Tokenizer.from_pretrained("google/t5-v1_1-small")
1219

1220
        input_ids = tokenizer("Hello there", return_tensors="pt").input_ids
1221
        labels = tokenizer("Hi I am", return_tensors="pt").input_ids
1222

1223
        loss = model(input_ids.to(torch_device), labels=labels.to(torch_device)).loss
1224
        mtf_score = -(labels.shape[-1] * loss.item())
1225

1226
        EXPECTED_SCORE = -59.0293
1227
        self.assertTrue(abs(mtf_score - EXPECTED_SCORE) < 1e-4)
1228

1229
    @slow
1230
    def test_small_byt5_integration_test(self):
1231
        """
1232
        For comparision run:
1233
        >>> import t5  # pip install t5==0.9.1
1234

1235
        >>> path_to_byt5_small_checkpoint = '<fill_in>'
1236
        >>> t5_model = t5.models.MtfModel(model_dir=path_to_tf_checkpoint, batch_size=1, tpu=None)
1237
        >>> vocab = t5.data.ByteVocabulary()
1238
        >>> score = t5_model.score(inputs=["Hello there"], targets=["Hi I am"], vocabulary=vocab)
1239
        """
1240

1241
        model = T5ForConditionalGeneration.from_pretrained("google/byt5-small").to(torch_device)
1242
        tokenizer = ByT5Tokenizer.from_pretrained("google/byt5-small")
1243

1244
        input_ids = tokenizer("Hello there", return_tensors="pt").input_ids
1245
        labels = tokenizer("Hi I am", return_tensors="pt").input_ids
1246

1247
        loss = model(input_ids.to(torch_device), labels=labels.to(torch_device)).loss
1248
        mtf_score = -(labels.shape[-1] * loss.item())
1249

1250
        EXPECTED_SCORE = -60.7397
1251
        self.assertTrue(abs(mtf_score - EXPECTED_SCORE) < 1e-4)
1252

1253
    @slow
1254
    def test_summarization(self):
1255
        model = self.model
1256
        tok = self.tokenizer
1257

1258
        FRANCE_ARTICLE = (  # @noqa
1259
            "Marseille, France (CNN)The French prosecutor leading an investigation into the crash of Germanwings"
1260
            " Flight 9525 insisted Wednesday that he was not aware of any video footage from on board the plane."
1261
            ' Marseille prosecutor Brice Robin told CNN that "so far no videos were used in the crash investigation."'
1262
            ' He added, "A person who has such a video needs to immediately give it to the investigators." Robin\'s'
1263
            " comments follow claims by two magazines, German daily Bild and French Paris Match, of a cell phone video"
1264
            " showing the harrowing final seconds from on board Germanwings Flight 9525 as it crashed into the French"
1265
            " Alps. All 150 on board were killed. Paris Match and Bild reported that the video was recovered from a"
1266
            " phone at the wreckage site. The two publications described the supposed video, but did not post it on"
1267
            " their websites. The publications said that they watched the video, which was found by a source close to"
1268
            " the investigation. \"One can hear cries of 'My God' in several languages,\" Paris Match reported."
1269
            ' "Metallic banging can also be heard more than three times, perhaps of the pilot trying to open the'
1270
            " cockpit door with a heavy object.  Towards the end, after a heavy shake, stronger than the others, the"
1271
            ' screaming intensifies. Then nothing." "It is a very disturbing scene," said Julian Reichelt,'
1272
            " editor-in-chief of Bild online. An official with France's accident investigation agency, the BEA, said"
1273
            " the agency is not aware of any such video. Lt. Col. Jean-Marc Menichini, a French Gendarmerie spokesman"
1274
            " in charge of communications on rescue efforts around the Germanwings crash site, told CNN that the"
1275
            ' reports were "completely wrong" and "unwarranted." Cell phones have been collected at the site, he said,'
1276
            ' but that they "hadn\'t been exploited yet." Menichini said he believed the cell phones would need to be'
1277
            " sent to the Criminal Research Institute in Rosny sous-Bois, near Paris, in order to be analyzed by"
1278
            " specialized technicians working hand-in-hand with investigators. But none of the cell phones found so"
1279
            " far have been sent to the institute, Menichini said. Asked whether staff involved in the search could"
1280
            ' have leaked a memory card to the media, Menichini answered with a categorical "no." Reichelt told "Erin'
1281
            ' Burnett: Outfront" that he had watched the video and stood by the report, saying Bild and Paris Match'
1282
            ' are "very confident" that the clip is real. He noted that investigators only revealed they\'d recovered'
1283
            ' cell phones from the crash site after Bild and Paris Match published their reports. "That is something'
1284
            " we did not know before. ... Overall we can say many things of the investigation weren't revealed by the"
1285
            ' investigation at the beginning," he said. What was mental state of Germanwings co-pilot? German airline'
1286
            " Lufthansa confirmed Tuesday that co-pilot Andreas Lubitz had battled depression years before he took the"
1287
            " controls of Germanwings Flight 9525, which he's accused of deliberately crashing last week in the"
1288
            ' French Alps. Lubitz told his Lufthansa flight training school in 2009 that he had a "previous episode of'
1289
            ' severe depression," the airline said Tuesday. Email correspondence between Lubitz and the school'
1290
            " discovered in an internal investigation, Lufthansa said, included medical documents he submitted in"
1291
            " connection with resuming his flight training. The announcement indicates that Lufthansa, the parent"
1292
            " company of Germanwings, knew of Lubitz's battle with depression, allowed him to continue training and"
1293
            " ultimately put him in the cockpit. Lufthansa, whose CEO Carsten Spohr previously said Lubitz was 100%"
1294
            ' fit to fly, described its statement Tuesday as a "swift and seamless clarification" and said it was'
1295
            " sharing the information and documents -- including training and medical records -- with public"
1296
            " prosecutors. Spohr traveled to the crash site Wednesday, where recovery teams have been working for the"
1297
            " past week to recover human remains and plane debris scattered across a steep mountainside. He saw the"
1298
            " crisis center set up in Seyne-les-Alpes, laid a wreath in the village of Le Vernet, closer to the crash"
1299
            " site, where grieving families have left flowers at a simple stone memorial. Menichini told CNN late"
1300
            " Tuesday that no visible human remains were left at the site but recovery teams would keep searching."
1301
            " French President Francois Hollande, speaking Tuesday, said that it should be possible to identify all"
1302
            " the victims using DNA analysis by the end of the week, sooner than authorities had previously suggested."
1303
            " In the meantime, the recovery of the victims' personal belongings will start Wednesday, Menichini said."
1304
            " Among those personal belongings could be more cell phones belonging to the 144 passengers and six crew"
1305
            " on board. Check out the latest from our correspondents . The details about Lubitz's correspondence with"
1306
            " the flight school during his training were among several developments as investigators continued to"
1307
            " delve into what caused the crash and Lubitz's possible motive for downing the jet. A Lufthansa"
1308
            " spokesperson told CNN on Tuesday that Lubitz had a valid medical certificate, had passed all his"
1309
            ' examinations and "held all the licenses required." Earlier, a spokesman for the prosecutor\'s office in'
1310
            " Dusseldorf, Christoph Kumpa, said medical records reveal Lubitz suffered from suicidal tendencies at"
1311
            " some point before his aviation career and underwent psychotherapy before he got his pilot's license."
1312
            " Kumpa emphasized there's no evidence suggesting Lubitz was suicidal or acting aggressively before the"
1313
            " crash. Investigators are looking into whether Lubitz feared his medical condition would cause him to"
1314
            " lose his pilot's license, a European government official briefed on the investigation told CNN on"
1315
            ' Tuesday. While flying was "a big part of his life," the source said, it\'s only one theory being'
1316
            " considered. Another source, a law enforcement official briefed on the investigation, also told CNN that"
1317
            " authorities believe the primary motive for Lubitz to bring down the plane was that he feared he would"
1318
            " not be allowed to fly because of his medical problems. Lubitz's girlfriend told investigators he had"
1319
            " seen an eye doctor and a neuropsychologist, both of whom deemed him unfit to work recently and concluded"
1320
            " he had psychological issues, the European government official said. But no matter what details emerge"
1321
            " about his previous mental health struggles, there's more to the story, said Brian Russell, a forensic"
1322
            ' psychologist. "Psychology can explain why somebody would turn rage inward on themselves about the fact'
1323
            " that maybe they weren't going to keep doing their job and they're upset about that and so they're"
1324
            ' suicidal," he said. "But there is no mental illness that explains why somebody then feels entitled to'
1325
            " also take that rage and turn it outward on 149 other people who had nothing to do with the person's"
1326
            ' problems." Germanwings crash compensation: What we know . Who was the captain of Germanwings Flight'
1327
            " 9525? CNN's Margot Haddad reported from Marseille and Pamela Brown from Dusseldorf, while Laura"
1328
            " Smith-Spark wrote from London. CNN's Frederik Pleitgen, Pamela Boykoff, Antonia Mortensen, Sandrine"
1329
            " Amiel and Anna-Maja Rappard contributed to this report."
1330
        )
1331
        SHORTER_ARTICLE = (
1332
            "(CNN)The Palestinian Authority officially became the 123rd member of the International Criminal Court on"
1333
            " Wednesday, a step that gives the court jurisdiction over alleged crimes in Palestinian territories. The"
1334
            " formal accession was marked with a ceremony at The Hague, in the Netherlands, where the court is based."
1335
            " The Palestinians signed the ICC's founding Rome Statute in January, when they also accepted its"
1336
            ' jurisdiction over alleged crimes committed "in the occupied Palestinian territory, including East'
1337
            ' Jerusalem, since June 13, 2014." Later that month, the ICC opened a preliminary examination into the'
1338
            " situation in Palestinian territories, paving the way for possible war crimes investigations against"
1339
            " Israelis. As members of the court, Palestinians may be subject to counter-charges as well. Israel and"
1340
            " the United States, neither of which is an ICC member, opposed the Palestinians' efforts to join the"
1341
            " body. But Palestinian Foreign Minister Riad al-Malki, speaking at Wednesday's ceremony, said it was a"
1342
            ' move toward greater justice. "As Palestine formally becomes a State Party to the Rome Statute today, the'
1343
            ' world is also a step closer to ending a long era of impunity and injustice," he said, according to an'
1344
            ' ICC news release. "Indeed, today brings us closer to our shared goals of justice and peace." Judge'
1345
            " Kuniko Ozaki, a vice president of the ICC, said acceding to the treaty was just the first step for the"
1346
            ' Palestinians. "As the Rome Statute today enters into force for the State of Palestine, Palestine'
1347
            " acquires all the rights as well as responsibilities that come with being a State Party to the Statute."
1348
            ' These are substantive commitments, which cannot be taken lightly," she said. Rights group Human Rights'
1349
            ' Watch welcomed the development. "Governments seeking to penalize Palestine for joining the ICC should'
1350
            " immediately end their pressure, and countries that support universal acceptance of the court's treaty"
1351
            ' should speak out to welcome its membership," said Balkees Jarrah, international justice counsel for the'
1352
            " group. \"What's objectionable is the attempts to undermine international justice, not Palestine's"
1353
            ' decision to join a treaty to which over 100 countries around the world are members." In January, when'
1354
            " the preliminary ICC examination was opened, Israeli Prime Minister Benjamin Netanyahu described it as an"
1355
            ' outrage, saying the court was overstepping its boundaries. The United States also said it "strongly"'
1356
            " disagreed with the court's decision. \"As we have said repeatedly, we do not believe that Palestine is a"
1357
            ' state and therefore we do not believe that it is eligible to join the ICC," the State Department said in'
1358
            ' a statement. It urged the warring sides to resolve their differences through direct negotiations. "We'
1359
            ' will continue to oppose actions against Israel at the ICC as counterproductive to the cause of peace,"'
1360
            " it said. But the ICC begs to differ with the definition of a state for its purposes and refers to the"
1361
            ' territories as "Palestine." While a preliminary examination is not a formal investigation, it allows the'
1362
            " court to review evidence and determine whether to investigate suspects on both sides. Prosecutor Fatou"
1363
            ' Bensouda said her office would "conduct its analysis in full independence and impartiality." The war'
1364
            " between Israel and Hamas militants in Gaza last summer left more than 2,000 people dead. The inquiry"
1365
            " will include alleged war crimes committed since June. The International Criminal Court was set up in"
1366
            " 2002 to prosecute genocide, crimes against humanity and war crimes. CNN's Vasco Cotovio, Kareem Khadder"
1367
            " and Faith Karimi contributed to this report."
1368
        )
1369
        IRAN_ARTICLE = (
1370
            "(CNN)The United States and its negotiating partners reached a very strong framework agreement with Iran"
1371
            " in Lausanne, Switzerland, on Thursday that limits Iran's nuclear program in such a way as to effectively"
1372
            " block it from building a nuclear weapon. Expect pushback anyway, if the recent past is any harbinger."
1373
            " Just last month, in an attempt to head off such an agreement, House Speaker John Boehner invited Israeli"
1374
            " Prime Minister Benjamin Netanyahu to preemptively blast it before Congress, and 47 senators sent a"
1375
            " letter to the Iranian leadership warning them away from a deal. The debate that has already begun since"
1376
            " the announcement of the new framework will likely result in more heat than light. It will not be helped"
1377
            " by the gathering swirl of dubious assumptions and doubtful assertions. Let us address some of these: ."
1378
            " The most misleading assertion, despite universal rejection by experts, is that the negotiations'"
1379
            " objective at the outset was the total elimination of any nuclear program in Iran. That is the position"
1380
            " of Netanyahu and his acolytes in the U.S. Congress. But that is not and never was the objective. If it"
1381
            " had been, there would have been no Iranian team at the negotiating table. Rather, the objective has"
1382
            " always been to structure an agreement or series of agreements so that Iran could not covertly develop a"
1383
            " nuclear arsenal before the United States and its allies could respond. The new framework has exceeded"
1384
            " expectations in achieving that goal. It would reduce Iran's low-enriched uranium stockpile, cut by"
1385
            " two-thirds its number of installed centrifuges and implement a rigorous inspection regime. Another"
1386
            " dubious assumption of opponents is that the Iranian nuclear program is a covert weapons program. Despite"
1387
            " sharp accusations by some in the United States and its allies, Iran denies having such a program, and"
1388
            " U.S. intelligence contends that Iran has not yet made the decision to build a nuclear weapon. Iran's"
1389
            " continued cooperation with International Atomic Energy Agency inspections is further evidence on this"
1390
            " point, and we'll know even more about Iran's program in the coming months and years because of the deal."
1391
            " In fact, the inspections provisions that are part of this agreement are designed to protect against any"
1392
            " covert action by the Iranians. What's more, the rhetoric of some members of Congress has implied that"
1393
            " the negotiations have been between only the United States and Iran (i.e., the 47 senators' letter"
1394
            " warning that a deal might be killed by Congress or a future president). This of course is not the case."
1395
            " The talks were between Iran and the five permanent members of the U.N. Security Council (United States,"
1396
            " United Kingdom, France, China and Russia) plus Germany, dubbed the P5+1. While the United States has"
1397
            " played a leading role in the effort, it negotiated the terms alongside its partners. If the agreement"
1398
            " reached by the P5+1 is rejected by Congress, it could result in an unraveling of the sanctions on Iran"
1399
            " and threaten NATO cohesion in other areas. Another questionable assertion is that this agreement"
1400
            " contains a sunset clause, after which Iran will be free to do as it pleases. Again, this is not the"
1401
            " case. Some of the restrictions on Iran's nuclear activities, such as uranium enrichment, will be eased"
1402
            " or eliminated over time, as long as 15 years. But most importantly, the framework agreement includes"
1403
            " Iran's ratification of the Additional Protocol, which allows IAEA inspectors expanded access to nuclear"
1404
            " sites both declared and nondeclared. This provision will be permanent. It does not sunset. Thus, going"
1405
            " forward, if Iran decides to enrich uranium to weapons-grade levels, monitors will be able to detect such"
1406
            " a move in a matter of days and alert the U.N. Security Council. Many in Congress have said that the"
1407
            ' agreement should be a formal treaty requiring the Senate to "advise and consent." But the issue is not'
1408
            " suited for a treaty. Treaties impose equivalent obligations on all signatories. For example, the New"
1409
            " START treaty limits Russia and the United States to 1,550 deployed strategic warheads. But any agreement"
1410
            " with Iran will not be so balanced.  The restrictions and obligations in the final framework agreement"
1411
            " will be imposed almost exclusively on Iran. The P5+1 are obligated only to ease and eventually remove"
1412
            " most but not all economic sanctions, which were imposed as leverage to gain this final deal. Finally"
1413
            " some insist that any agreement must address Iranian missile programs, human rights violations or support"
1414
            " for Hamas or Hezbollah.  As important as these issues are, and they must indeed be addressed, they are"
1415
            " unrelated to the most important aim of a nuclear deal: preventing a nuclear Iran.  To include them in"
1416
            " the negotiations would be a poison pill. This agreement should be judged on its merits and on how it"
1417
            " affects the security of our negotiating partners and allies, including Israel. Those judgments should be"
1418
            " fact-based, not based on questionable assertions or dubious assumptions."
1419
        )
1420
        ARTICLE_SUBWAY = (
1421
            "New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County, New York. A"
1422
            " year later, she got married again in Westchester County, but to a different man and without divorcing"
1423
            " her first husband.  Only 18 days after that marriage, she got hitched yet again. Then, Barrientos"
1424
            ' declared "I do" five more times, sometimes only within two weeks of each other. In 2010, she married'
1425
            " once more, this time in the Bronx. In an application for a marriage license, she stated it was her"
1426
            ' "first and only" marriage. Barrientos, now 39, is facing two criminal counts of "offering a false'
1427
            ' instrument for filing in the first degree," referring to her false statements on the 2010 marriage'
1428
            " license application, according to court documents. Prosecutors said the marriages were part of an"
1429
            " immigration scam. On Friday, she pleaded not guilty at State Supreme Court in the Bronx, according to"
1430
            " her attorney, Christopher Wright, who declined to comment further. After leaving court, Barrientos was"
1431
            " arrested and charged with theft of service and criminal trespass for allegedly sneaking into the New"
1432
            " York subway through an emergency exit, said Detective Annette Markowski, a police spokeswoman. In total,"
1433
            " Barrientos has been married 10 times, with nine of her marriages occurring between 1999 and 2002.  All"
1434
            " occurred either in Westchester County, Long Island, New Jersey or the Bronx. She is believed to still be"
1435
            " married to four men, and at one time, she was married to eight men at once, prosecutors say. Prosecutors"
1436
            " said the immigration scam involved some of her husbands, who filed for permanent residence status"
1437
            " shortly after the marriages.  Any divorces happened only after such filings were approved. It was"
1438
            " unclear whether any of the men will be prosecuted. The case was referred to the Bronx District"
1439
            " Attorney's Office by Immigration and Customs Enforcement and the Department of Homeland Security's"
1440
            ' Investigation Division. Seven of the men are from so-called "red-flagged" countries, including Egypt,'
1441
            " Turkey, Georgia, Pakistan and Mali. Her eighth husband, Rashid Rajput, was deported in 2006 to his"
1442
            " native Pakistan after an investigation by the Joint Terrorism Task Force. If convicted, Barrientos faces"
1443
            " up to four years in prison.  Her next court appearance is scheduled for May 18."
1444
        )
1445

1446
        expected_summaries = [
1447
            'prosecutor: "so far no videos were used in the crash investigation" two magazines claim to have found a'
1448
            " cell phone video of the final seconds . \"one can hear cries of 'My God' in several languages,\" one"
1449
            " magazine says .",
1450
            "the formal accession was marked by a ceremony at The Hague, in the Netherlands . the ICC opened a"
1451
            " preliminary examination into the situation in the occupied Palestinian territory . as members of the"
1452
            " court, Palestinians may be subject to counter-charges as well .",
1453
            "the u.s. and its negotiating partners reached a very strong framework agreement with Iran . aaron miller:"
1454
            " the debate that has already begun since the announcement of the new framework will likely result in more"
1455
            " heat than light . the deal would reduce Iran's low-enriched uranium stockpile, cut centrifuges and"
1456
            " implement a rigorous inspection regime .",
1457
            "prosecutors say the marriages were part of an immigration scam . if convicted, barrientos faces two"
1458
            ' criminal counts of "offering a false instrument for filing in the first degree" she has been married 10'
1459
            " times, with nine of her marriages occurring between 1999 and 2002 .",
1460
        ]
1461

1462
        use_task_specific_params(model, "summarization")
1463

1464
        dct = tok(
1465
            [model.config.prefix + x for x in [FRANCE_ARTICLE, SHORTER_ARTICLE, IRAN_ARTICLE, ARTICLE_SUBWAY]],
1466
            padding="max_length",
1467
            truncation=True,
1468
            return_tensors="pt",
1469
        ).to(torch_device)
1470
        self.assertEqual(512, dct["input_ids"].shape[1])
1471

1472
        hypotheses_batch = model.generate(
1473
            **dct,
1474
            num_beams=4,
1475
            length_penalty=2.0,
1476
            max_length=142,
1477
            min_length=56,
1478
            no_repeat_ngram_size=3,
1479
            do_sample=False,
1480
            early_stopping=True,
1481
        )
1482

1483
        decoded = tok.batch_decode(hypotheses_batch, skip_special_tokens=True, clean_up_tokenization_spaces=False)
1484
        self.assertListEqual(
1485
            expected_summaries,
1486
            decoded,
1487
        )
1488

1489
    @slow
1490
    def test_translation_en_to_de(self):
1491
        model = self.model
1492
        tok = self.tokenizer
1493
        use_task_specific_params(model, "translation_en_to_de")
1494

1495
        en_text = '"Luigi often said to me that he never wanted the brothers to end up in court", she wrote.'
1496
        expected_translation = (
1497
            '"Luigi sagte mir oft, dass er nie wollte, dass die Brüder am Gericht sitzen", schrieb sie.'
1498
        )
1499

1500
        input_ids = tok.encode(model.config.prefix + en_text, return_tensors="pt")
1501
        input_ids = input_ids.to(torch_device)
1502
        output = model.generate(input_ids)
1503
        translation = tok.decode(output[0], skip_special_tokens=True, clean_up_tokenization_spaces=False)
1504
        self.assertEqual(translation, expected_translation)
1505

1506
    @slow
1507
    def test_translation_en_to_fr(self):
1508
        model = self.model  # google-t5/t5-base
1509
        tok = self.tokenizer
1510
        use_task_specific_params(model, "translation_en_to_fr")
1511

1512
        en_text = (
1513
            ' This image section from an infrared recording by the Spitzer telescope shows a "family portrait" of'
1514
            " countless generations of stars: the oldest stars are seen as blue dots. "
1515
        )
1516

1517
        input_ids = tok.encode(model.config.prefix + en_text, return_tensors="pt")
1518
        input_ids = input_ids.to(torch_device)
1519

1520
        output = model.generate(
1521
            input_ids=input_ids,
1522
            num_beams=4,
1523
            length_penalty=2.0,
1524
            max_length=100,
1525
            no_repeat_ngram_size=3,
1526
            do_sample=False,
1527
            early_stopping=True,
1528
        )
1529
        translation = tok.decode(output[0], skip_special_tokens=True, clean_up_tokenization_spaces=False)
1530
        new_truncated_translation = (
1531
            "Cette section d'images provenant de l'enregistrement infrarouge effectué par le télescope Spitzer montre "
1532
            "un "
1533
            "« portrait familial » de générations innombrables d’étoiles : les plus anciennes sont observées "
1534
            "sous forme "
1535
            "de points bleus."
1536
        )
1537

1538
        self.assertEqual(translation, new_truncated_translation)
1539

1540
    @slow
1541
    def test_translation_en_to_ro(self):
1542
        model = self.model
1543
        tok = self.tokenizer
1544
        use_task_specific_params(model, "translation_en_to_ro")
1545
        en_text = "Taco Bell said it plans to add 2,000 locations in the US by 2022."
1546
        expected_translation = "Taco Bell a declarat că intenţionează să adauge 2 000 de locaţii în SUA până în 2022."
1547

1548
        inputs = tok(model.config.prefix + en_text, return_tensors="pt").to(torch_device)
1549
        output = model.generate(**inputs)
1550
        translation = tok.decode(output[0], skip_special_tokens=True, clean_up_tokenization_spaces=False)
1551
        self.assertEqual(translation, expected_translation)
1552

1553
    @slow
1554
    def test_contrastive_search_t5(self):
1555
        article = (
1556
            " New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County, New York. A"
1557
            " year later, she got married again in Westchester County, but to a different man and without divorcing"
1558
            " her first husband.  Only 18 days after that marriage, she got hitched yet again. Then, Barrientos"
1559
            ' declared "I do" five more times, sometimes only within two weeks of each other. In 2010, she married'
1560
            " once more, this time in the Bronx. In an application for a marriage license, she stated it was her"
1561
            ' "first and only" marriage. Barrientos, now 39, is facing two criminal counts of "offering a false'
1562
            ' instrument for filing in the first degree," referring to her false statements on the 2010 marriage'
1563
            " license application, according to court documents. Prosecutors said the marriages were part of an"
1564
            " immigration scam. On Friday, she pleaded not guilty at State Supreme Court in the Bronx, according to"
1565
            " her attorney, Christopher Wright, who declined to comment further. After leaving court, Barrientos was"
1566
            " arrested and charged with theft of service and criminal trespass for allegedly sneaking into the New"
1567
            " York subway through an emergency exit, said Detective Annette Markowski, a police spokeswoman. In total,"
1568
            " Barrientos has been married 10 times, with nine of her marriages occurring between 1999 and 2002.  All"
1569
            " occurred either in Westchester County, Long Island, New Jersey or the Bronx. She is believed to still be"
1570
            " married to four men, and at one time, she was married to eight men at once, prosecutors say. Prosecutors"
1571
            " said the immigration scam involved some of her husbands, who filed for permanent residence status"
1572
            " shortly after the marriages.  Any divorces happened only after such filings were approved. It was"
1573
            " unclear whether any of the men will be prosecuted. The case was referred to the Bronx District"
1574
            " Attorney's Office by Immigration and Customs Enforcement and the Department of Homeland Security's"
1575
            ' Investigation Division. Seven of the men are from so-called "red-flagged" countries, including Egypt,'
1576
            " Turkey, Georgia, Pakistan and Mali. Her eighth husband, Rashid Rajput, was deported in 2006 to his"
1577
            " native Pakistan after an investigation by the Joint Terrorism Task Force. If convicted, Barrientos faces"
1578
            " up to four years in prison.  Her next court appearance is scheduled for May 18."
1579
        )
1580
        article = "summarize: " + article.strip()
1581
        t5_tokenizer = AutoTokenizer.from_pretrained("flax-community/t5-base-cnn-dm")
1582
        t5_model = T5ForConditionalGeneration.from_pretrained("flax-community/t5-base-cnn-dm").to(torch_device)
1583
        input_ids = t5_tokenizer(
1584
            article, add_special_tokens=False, truncation=True, max_length=512, return_tensors="pt"
1585
        ).input_ids.to(torch_device)
1586

1587
        outputs = t5_model.generate(input_ids, penalty_alpha=0.5, top_k=5, max_length=64)
1588
        generated_text = t5_tokenizer.batch_decode(outputs, skip_special_tokens=True)
1589

1590
        self.assertListEqual(
1591
            generated_text,
1592
            [
1593
                "Liana Barrientos has been married 10 times, nine of them in the Bronx. Her husbands filed for "
1594
                "permanent residence after the marriages, prosecutors say."
1595
            ],
1596
        )
1597

1598

1599
@require_torch
1600
class TestAsymmetricT5(unittest.TestCase):
1601
    def build_model_and_check_forward_pass(self, **kwargs):
1602
        tester = T5ModelTester(self, **kwargs)
1603
        config, *inputs = tester.prepare_config_and_inputs()
1604
        (
1605
            input_ids,
1606
            decoder_input_ids,
1607
            attention_mask,
1608
            decoder_attention_mask,
1609
            lm_labels,
1610
        ) = inputs
1611
        model = T5ForConditionalGeneration(config=config).to(torch_device).eval()
1612
        outputs = model(
1613
            input_ids=input_ids,
1614
            decoder_input_ids=decoder_input_ids,
1615
            decoder_attention_mask=decoder_attention_mask,
1616
            labels=lm_labels,
1617
        )
1618
        # outputs = model(*inputs)
1619
        assert len(outputs) == 4
1620
        assert outputs["logits"].size() == (tester.batch_size, tester.decoder_seq_length, tester.vocab_size)
1621
        assert outputs["loss"].size() == ()
1622
        return model
1623

1624
    def test_small_decoder(self):
1625
        # num_hidden_layers is passed to T5Config as num_layers
1626
        model = self.build_model_and_check_forward_pass(decoder_layers=1, num_hidden_layers=2)
1627
        assert len(model.encoder.block) == 2
1628
        assert len(model.decoder.block) == 1
1629

1630
    def test_defaulting_to_symmetry(self):
1631
        # num_hidden_layers is passed to T5Config as num_layers
1632
        model = self.build_model_and_check_forward_pass(num_hidden_layers=2)
1633
        assert len(model.decoder.block) == len(model.encoder.block) == 2
1634

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

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

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

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