transformers
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
17import copy
18import os
19import pickle
20import tempfile
21import unittest
22
23from transformers import T5Config, is_torch_available
24from transformers.models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES
25from transformers.testing_utils import (
26require_accelerate,
27require_sentencepiece,
28require_tokenizers,
29require_torch,
30slow,
31torch_device,
32)
33from transformers.utils import cached_property, is_torch_fx_available
34
35from ...generation.test_utils import GenerationTesterMixin
36from ...test_configuration_common import ConfigTester
37from ...test_modeling_common import ModelTesterMixin, _config_zero_init, ids_tensor
38from ...test_pipeline_mixin import PipelineTesterMixin
39
40
41if is_torch_fx_available():
42from transformers.utils.fx import symbolic_trace
43
44
45if is_torch_available():
46import torch
47
48from transformers import (
49AutoTokenizer,
50ByT5Tokenizer,
51T5EncoderModel,
52T5ForConditionalGeneration,
53T5ForQuestionAnswering,
54T5ForSequenceClassification,
55T5ForTokenClassification,
56T5Model,
57T5Tokenizer,
58)
59from transformers.models.t5.modeling_t5 import T5_PRETRAINED_MODEL_ARCHIVE_LIST
60
61
62class T5ModelTester:
63def __init__(
64self,
65parent,
66vocab_size=99,
67batch_size=13,
68encoder_seq_length=7,
69decoder_seq_length=7,
70# For common tests
71is_training=True,
72use_attention_mask=True,
73use_labels=True,
74hidden_size=32,
75num_hidden_layers=2,
76num_attention_heads=4,
77d_ff=37,
78relative_attention_num_buckets=8,
79dropout_rate=0.1,
80initializer_factor=0.002,
81eos_token_id=1,
82pad_token_id=0,
83decoder_start_token_id=0,
84scope=None,
85decoder_layers=None,
86):
87self.parent = parent
88self.batch_size = batch_size
89self.encoder_seq_length = encoder_seq_length
90self.decoder_seq_length = decoder_seq_length
91# For common tests
92self.seq_length = self.decoder_seq_length
93self.is_training = is_training
94self.use_attention_mask = use_attention_mask
95self.use_labels = use_labels
96self.vocab_size = vocab_size
97self.hidden_size = hidden_size
98self.num_hidden_layers = num_hidden_layers
99self.num_attention_heads = num_attention_heads
100self.d_ff = d_ff
101self.relative_attention_num_buckets = relative_attention_num_buckets
102self.dropout_rate = dropout_rate
103self.initializer_factor = initializer_factor
104self.eos_token_id = eos_token_id
105self.pad_token_id = pad_token_id
106self.decoder_start_token_id = decoder_start_token_id
107self.scope = None
108self.decoder_layers = decoder_layers
109
110def get_large_model_config(self):
111return T5Config.from_pretrained("google-t5/t5-base")
112
113def prepare_config_and_inputs(self):
114input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size).clamp(2)
115input_ids[:, -1] = self.eos_token_id # Eos Token
116decoder_input_ids = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)
117
118attention_mask = None
119decoder_attention_mask = None
120if self.use_attention_mask:
121attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2)
122decoder_attention_mask = ids_tensor([self.batch_size, self.decoder_seq_length], vocab_size=2)
123
124lm_labels = None
125if self.use_labels:
126lm_labels = ids_tensor([self.batch_size, self.decoder_seq_length], self.vocab_size)
127
128config = self.get_config()
129
130return (
131config,
132input_ids,
133decoder_input_ids,
134attention_mask,
135decoder_attention_mask,
136lm_labels,
137)
138
139def get_pipeline_config(self):
140return T5Config(
141vocab_size=166, # t5 forces 100 extra tokens
142d_model=self.hidden_size,
143d_ff=self.d_ff,
144d_kv=self.hidden_size // self.num_attention_heads,
145num_layers=self.num_hidden_layers,
146num_decoder_layers=self.decoder_layers,
147num_heads=self.num_attention_heads,
148relative_attention_num_buckets=self.relative_attention_num_buckets,
149dropout_rate=self.dropout_rate,
150initializer_factor=self.initializer_factor,
151eos_token_id=self.eos_token_id,
152bos_token_id=self.pad_token_id,
153pad_token_id=self.pad_token_id,
154decoder_start_token_id=self.decoder_start_token_id,
155)
156
157def get_config(self):
158return T5Config(
159vocab_size=self.vocab_size,
160d_model=self.hidden_size,
161d_ff=self.d_ff,
162d_kv=self.hidden_size // self.num_attention_heads,
163num_layers=self.num_hidden_layers,
164num_decoder_layers=self.decoder_layers,
165num_heads=self.num_attention_heads,
166relative_attention_num_buckets=self.relative_attention_num_buckets,
167dropout_rate=self.dropout_rate,
168initializer_factor=self.initializer_factor,
169eos_token_id=self.eos_token_id,
170bos_token_id=self.pad_token_id,
171pad_token_id=self.pad_token_id,
172decoder_start_token_id=self.decoder_start_token_id,
173)
174
175def check_prepare_lm_labels_via_shift_left(
176self,
177config,
178input_ids,
179decoder_input_ids,
180attention_mask,
181decoder_attention_mask,
182lm_labels,
183):
184model = T5Model(config=config)
185model.to(torch_device)
186model.eval()
187
188# make sure that lm_labels are correctly padded from the right
189lm_labels.masked_fill_((lm_labels == self.decoder_start_token_id), self.eos_token_id)
190
191# add casaul pad token mask
192triangular_mask = torch.tril(lm_labels.new_ones(lm_labels.shape)).logical_not()
193lm_labels.masked_fill_(triangular_mask, self.pad_token_id)
194decoder_input_ids = model._shift_right(lm_labels)
195
196for i, (decoder_input_ids_slice, lm_labels_slice) in enumerate(zip(decoder_input_ids, lm_labels)):
197# first item
198self.parent.assertEqual(decoder_input_ids_slice[0].item(), self.decoder_start_token_id)
199if i < decoder_input_ids_slice.shape[-1]:
200if i < decoder_input_ids.shape[-1] - 1:
201# items before diagonal
202self.parent.assertListEqual(
203decoder_input_ids_slice[1 : i + 1].tolist(), lm_labels_slice[:i].tolist()
204)
205# pad items after diagonal
206if i < decoder_input_ids.shape[-1] - 2:
207self.parent.assertListEqual(
208decoder_input_ids_slice[i + 2 :].tolist(), lm_labels_slice[i + 1 : -1].tolist()
209)
210else:
211# all items after square
212self.parent.assertListEqual(decoder_input_ids_slice[1:].tolist(), lm_labels_slice[:-1].tolist())
213
214def create_and_check_model(
215self,
216config,
217input_ids,
218decoder_input_ids,
219attention_mask,
220decoder_attention_mask,
221lm_labels,
222):
223model = T5Model(config=config)
224model.to(torch_device)
225model.eval()
226result = model(
227input_ids=input_ids,
228decoder_input_ids=decoder_input_ids,
229attention_mask=attention_mask,
230decoder_attention_mask=decoder_attention_mask,
231)
232result = model(input_ids=input_ids, decoder_input_ids=decoder_input_ids)
233decoder_output = result.last_hidden_state
234decoder_past = result.past_key_values
235encoder_output = result.encoder_last_hidden_state
236
237self.parent.assertEqual(encoder_output.size(), (self.batch_size, self.encoder_seq_length, self.hidden_size))
238self.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
240self.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
242self.parent.assertEqual(len(decoder_past[0]), 4)
243
244def create_and_check_with_lm_head(
245self,
246config,
247input_ids,
248decoder_input_ids,
249attention_mask,
250decoder_attention_mask,
251lm_labels,
252):
253model = T5ForConditionalGeneration(config=config).to(torch_device).eval()
254outputs = model(
255input_ids=input_ids,
256decoder_input_ids=decoder_input_ids,
257decoder_attention_mask=decoder_attention_mask,
258labels=lm_labels,
259)
260self.parent.assertEqual(len(outputs), 4)
261self.parent.assertEqual(outputs["logits"].size(), (self.batch_size, self.decoder_seq_length, self.vocab_size))
262self.parent.assertEqual(outputs["loss"].size(), ())
263
264def create_and_check_with_sequence_classification_head(
265self,
266config,
267input_ids,
268decoder_input_ids,
269attention_mask,
270decoder_attention_mask,
271lm_labels,
272):
273labels = torch.tensor([1] * self.batch_size, dtype=torch.long, device=torch_device)
274model = T5ForSequenceClassification(config=config).to(torch_device).eval()
275outputs = model(
276input_ids=input_ids,
277decoder_input_ids=input_ids,
278labels=labels,
279)
280# self.parent.assertEqual(len(outputs), 4)
281self.parent.assertEqual(outputs["logits"].size(), (self.batch_size, config.num_labels))
282self.parent.assertEqual(outputs["loss"].size(), ())
283
284def create_and_check_decoder_model_past(
285self,
286config,
287input_ids,
288decoder_input_ids,
289attention_mask,
290decoder_attention_mask,
291lm_labels,
292):
293model = T5Model(config=config).get_decoder().to(torch_device).eval()
294# first forward pass
295outputs = model(input_ids, use_cache=True)
296outputs_use_cache_conf = model(input_ids)
297outputs_no_past = model(input_ids, use_cache=False)
298
299self.parent.assertTrue(len(outputs) == len(outputs_use_cache_conf))
300self.parent.assertTrue(len(outputs) == len(outputs_no_past) + 1)
301
302output, past_key_values = outputs.to_tuple()
303
304# create hypothetical next token and extent to next_input_ids
305next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
306
307# append to next input_ids and
308next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
309
310output_from_no_past = model(next_input_ids)["last_hidden_state"]
311output_from_past = model(next_tokens, past_key_values=past_key_values)["last_hidden_state"]
312
313# select random slice
314random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
315output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach()
316output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
317
318# test that outputs are equal for slice
319self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
320
321def create_and_check_decoder_model_attention_mask_past(
322self,
323config,
324input_ids,
325decoder_input_ids,
326attention_mask,
327decoder_attention_mask,
328lm_labels,
329):
330model = T5Model(config=config).get_decoder()
331model.to(torch_device)
332model.eval()
333
334# create attention mask
335attn_mask = torch.ones(input_ids.shape, dtype=torch.long, device=torch_device)
336
337half_seq_length = input_ids.shape[-1] // 2
338attn_mask[:, half_seq_length:] = 0
339
340# first forward pass
341output, 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
344next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size)
345
346# change a random masked slice from input_ids
347random_seq_idx_to_change = ids_tensor((1,), half_seq_length).item() + 1
348random_other_next_tokens = ids_tensor((self.batch_size, 1), config.vocab_size).squeeze(-1)
349input_ids[:, -random_seq_idx_to_change] = random_other_next_tokens
350
351# append to next input_ids and attn_mask
352next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
353attn_mask = torch.cat(
354[attn_mask, torch.ones((attn_mask.shape[0], 1), dtype=torch.long, device=torch_device)],
355dim=1,
356)
357
358# get two different outputs
359output_from_no_past = model(next_input_ids, attention_mask=attn_mask)["last_hidden_state"]
360output_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
365random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
366output_from_no_past_slice = output_from_no_past[:, -1, random_slice_idx].detach()
367output_from_past_slice = output_from_past[:, 0, random_slice_idx].detach()
368
369# test that outputs are equal for slice
370self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
371
372def create_and_check_decoder_model_past_large_inputs(
373self,
374config,
375input_ids,
376decoder_input_ids,
377attention_mask,
378decoder_attention_mask,
379lm_labels,
380):
381model = T5Model(config=config).get_decoder().to(torch_device).eval()
382# first forward pass
383outputs = model(input_ids, attention_mask=attention_mask, use_cache=True)
384
385output, past_key_values = outputs.to_tuple()
386
387# create hypothetical multiple next token and extent to next_input_ids
388next_tokens = ids_tensor((self.batch_size, 3), config.vocab_size)
389next_mask = ids_tensor((self.batch_size, 3), vocab_size=2)
390
391# append to next input_ids and
392next_input_ids = torch.cat([input_ids, next_tokens], dim=-1)
393next_attention_mask = torch.cat([attention_mask, next_mask], dim=-1)
394
395output_from_no_past = model(next_input_ids, attention_mask=next_attention_mask)["last_hidden_state"]
396output_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
401random_slice_idx = ids_tensor((1,), output_from_past.shape[-1]).item()
402output_from_no_past_slice = output_from_no_past[:, -3:, random_slice_idx].detach()
403output_from_past_slice = output_from_past[:, :, random_slice_idx].detach()
404
405self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1])
406
407# test that outputs are equal for slice
408self.parent.assertTrue(torch.allclose(output_from_past_slice, output_from_no_past_slice, atol=1e-3))
409
410def create_and_check_generate_with_past_key_values(
411self,
412config,
413input_ids,
414decoder_input_ids,
415attention_mask,
416decoder_attention_mask,
417lm_labels,
418):
419model = T5ForConditionalGeneration(config=config).to(torch_device).eval()
420torch.manual_seed(0)
421output_without_past_cache = model.generate(
422input_ids[:1], num_beams=2, max_length=5, do_sample=True, use_cache=False
423)
424torch.manual_seed(0)
425output_with_past_cache = model.generate(input_ids[:1], num_beams=2, max_length=5, do_sample=True)
426self.parent.assertTrue(torch.all(output_with_past_cache == output_without_past_cache))
427
428def create_and_check_model_fp16_forward(
429self,
430config,
431input_ids,
432decoder_input_ids,
433attention_mask,
434decoder_attention_mask,
435lm_labels,
436):
437model = T5Model(config=config).to(torch_device).half().eval()
438output = model(input_ids, decoder_input_ids=input_ids, attention_mask=attention_mask)["last_hidden_state"]
439self.parent.assertFalse(torch.isnan(output).any().item())
440
441def create_and_check_encoder_decoder_shared_weights(
442self,
443config,
444input_ids,
445decoder_input_ids,
446attention_mask,
447decoder_attention_mask,
448lm_labels,
449):
450for model_class in [T5Model, T5ForConditionalGeneration]:
451torch.manual_seed(0)
452model = model_class(config=config).to(torch_device).eval()
453# load state dict copies weights but does not tie them
454model.encoder.load_state_dict(model.decoder.state_dict(), strict=False)
455
456torch.manual_seed(0)
457tied_config = copy.deepcopy(config)
458tied_config.tie_encoder_decoder = True
459tied_model = model_class(config=tied_config).to(torch_device).eval()
460
461model_result = model(
462input_ids=input_ids,
463decoder_input_ids=decoder_input_ids,
464attention_mask=attention_mask,
465decoder_attention_mask=decoder_attention_mask,
466)
467
468tied_model_result = tied_model(
469input_ids=input_ids,
470decoder_input_ids=decoder_input_ids,
471attention_mask=attention_mask,
472decoder_attention_mask=decoder_attention_mask,
473)
474
475# check that models has less parameters
476self.parent.assertLess(
477sum(p.numel() for p in tied_model.parameters()), sum(p.numel() for p in model.parameters())
478)
479random_slice_idx = ids_tensor((1,), model_result[0].shape[-1]).item()
480
481# check that outputs are equal
482self.parent.assertTrue(
483torch.allclose(
484model_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
489with tempfile.TemporaryDirectory() as tmpdirname:
490tied_model.save_pretrained(tmpdirname)
491tied_model = model_class.from_pretrained(tmpdirname)
492tied_model.to(torch_device)
493tied_model.eval()
494
495# check that models has less parameters
496self.parent.assertLess(
497sum(p.numel() for p in tied_model.parameters()), sum(p.numel() for p in model.parameters())
498)
499random_slice_idx = ids_tensor((1,), model_result[0].shape[-1]).item()
500
501tied_model_result = tied_model(
502input_ids=input_ids,
503decoder_input_ids=decoder_input_ids,
504attention_mask=attention_mask,
505decoder_attention_mask=decoder_attention_mask,
506)
507
508# check that outputs are equal
509self.parent.assertTrue(
510torch.allclose(
511model_result[0][0, :, random_slice_idx],
512tied_model_result[0][0, :, random_slice_idx],
513atol=1e-4,
514)
515)
516
517def check_resize_embeddings_t5_v1_1(
518self,
519config,
520):
521prev_vocab_size = config.vocab_size
522
523config.tie_word_embeddings = False
524model = T5ForConditionalGeneration(config=config).to(torch_device).eval()
525model.resize_token_embeddings(prev_vocab_size - 10)
526
527self.parent.assertEqual(model.get_input_embeddings().weight.shape[0], prev_vocab_size - 10)
528self.parent.assertEqual(model.get_output_embeddings().weight.shape[0], prev_vocab_size - 10)
529self.parent.assertEqual(model.config.vocab_size, prev_vocab_size - 10)
530
531def prepare_config_and_inputs_for_common(self):
532config_and_inputs = self.prepare_config_and_inputs()
533(
534config,
535input_ids,
536decoder_input_ids,
537attention_mask,
538decoder_attention_mask,
539lm_labels,
540) = config_and_inputs
541
542inputs_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}
549return config, inputs_dict
550
551
552@require_torch
553class T5ModelTest(ModelTesterMixin, GenerationTesterMixin, PipelineTesterMixin, unittest.TestCase):
554all_model_classes = (
555(T5Model, T5ForConditionalGeneration, T5ForSequenceClassification, T5ForQuestionAnswering)
556if is_torch_available()
557else ()
558)
559all_generative_model_classes = (T5ForConditionalGeneration,) if is_torch_available() else ()
560pipeline_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}
571if is_torch_available()
572else {}
573)
574all_parallelizable_model_classes = (T5Model, T5ForConditionalGeneration) if is_torch_available() else ()
575fx_compatible = True
576test_pruning = False
577test_resize_embeddings = True
578test_model_parallel = True
579is_encoder_decoder = True
580# The small T5 model needs higher percentages for CPU/MP tests
581model_split_percents = [0.8, 0.9]
582
583def setUp(self):
584self.model_tester = T5ModelTester(self)
585self.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)
589def is_pipeline_test_to_skip(
590self, pipeline_test_case_name, config_class, model_architecture, tokenizer_name, processor_name
591):
592if tokenizer_name is None:
593return True
594if pipeline_test_case_name == "QAPipelineTests" and not tokenizer_name.endswith("Fast"):
595return True
596
597return False
598
599def _create_and_check_torch_fx_tracing(self, config, inputs_dict, output_loss=False):
600if not is_torch_fx_available() or not self.fx_compatible:
601return
602
603configs_no_init = _config_zero_init(config) # To be sure we have no Nan
604configs_no_init.return_dict = False
605
606for model_class in self.all_model_classes:
607if model_class.__name__ == "T5ForSequenceClassification":
608continue
609model = model_class(config=configs_no_init)
610model.to(torch_device)
611model.eval()
612inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=output_loss)
613
614try:
615if model.config.is_encoder_decoder:
616model.config.use_cache = False # FSTM still requires this hack -> FSTM should probably be refactored similar to BART afterward
617labels = inputs.get("labels", None)
618input_names = [
619"attention_mask",
620"decoder_attention_mask",
621"decoder_input_ids",
622"input_features",
623"input_ids",
624"input_values",
625]
626if labels is not None:
627input_names.append("labels")
628
629filtered_inputs = {k: v for (k, v) in inputs.items() if k in input_names}
630input_names = list(filtered_inputs.keys())
631
632model_output = model(**filtered_inputs)
633
634traced_model = symbolic_trace(model, input_names)
635traced_output = traced_model(**filtered_inputs)
636else:
637input_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
649labels = inputs.get("labels", None)
650start_positions = inputs.get("start_positions", None)
651end_positions = inputs.get("end_positions", None)
652if labels is not None:
653input_names.append("labels")
654if start_positions is not None:
655input_names.append("start_positions")
656if end_positions is not None:
657input_names.append("end_positions")
658
659filtered_inputs = {k: v for (k, v) in inputs.items() if k in input_names}
660input_names = list(filtered_inputs.keys())
661
662if model.__class__.__name__ in set(MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES.values()) and (
663not hasattr(model.config, "problem_type") or model.config.problem_type is None
664):
665model.config.problem_type = "single_label_classification"
666
667traced_model = symbolic_trace(model, input_names)
668traced_output = traced_model(**filtered_inputs)
669model_output = model(**filtered_inputs)
670
671except Exception as e:
672self.fail(f"Couldn't trace module: {e}")
673
674def flatten_output(output):
675flatten = []
676for x in output:
677if isinstance(x, (tuple, list)):
678flatten += flatten_output(x)
679elif not isinstance(x, torch.Tensor):
680continue
681else:
682flatten.append(x)
683return flatten
684
685model_output = flatten_output(model_output)
686traced_output = flatten_output(traced_output)
687num_outputs = len(model_output)
688
689for i in range(num_outputs):
690self.assertTrue(
691torch.allclose(model_output[i], traced_output[i]),
692f"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
696with tempfile.TemporaryDirectory() as tmp_dir_name:
697pkl_file_name = os.path.join(tmp_dir_name, "model.pkl")
698try:
699with open(pkl_file_name, "wb") as f:
700pickle.dump(traced_model, f)
701with open(pkl_file_name, "rb") as f:
702loaded = pickle.load(f)
703except Exception as e:
704self.fail(f"Couldn't serialize / deserialize the traced model: {e}")
705
706loaded_output = loaded(**filtered_inputs)
707loaded_output = flatten_output(loaded_output)
708
709for i in range(num_outputs):
710self.assertTrue(
711torch.allclose(model_output[i], loaded_output[i]),
712f"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)
717self.clear_torch_jit_class_registry()
718
719def test_config(self):
720self.config_tester.run_common_tests()
721
722def test_shift_right(self):
723config_and_inputs = self.model_tester.prepare_config_and_inputs()
724self.model_tester.check_prepare_lm_labels_via_shift_left(*config_and_inputs)
725
726def test_model(self):
727config_and_inputs = self.model_tester.prepare_config_and_inputs()
728self.model_tester.create_and_check_model(*config_and_inputs)
729
730def test_model_v1_1(self):
731config_and_inputs = self.model_tester.prepare_config_and_inputs()
732# check that gated gelu feed forward and different word embeddings work
733config = config_and_inputs[0]
734config.tie_word_embeddings = False
735config.feed_forward_proj = "gated-gelu"
736self.model_tester.create_and_check_model(config, *config_and_inputs[1:])
737
738# T5ForSequenceClassification does not support inputs_embeds
739def test_inputs_embeds(self):
740config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common()
741
742for model_class in (T5Model, T5ForConditionalGeneration, T5ForQuestionAnswering):
743model = model_class(config)
744model.to(torch_device)
745model.eval()
746
747inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class))
748
749if not self.is_encoder_decoder:
750input_ids = inputs["input_ids"]
751del inputs["input_ids"]
752else:
753encoder_input_ids = inputs["input_ids"]
754decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids)
755del inputs["input_ids"]
756inputs.pop("decoder_input_ids", None)
757
758wte = model.get_input_embeddings()
759if not self.is_encoder_decoder:
760inputs["inputs_embeds"] = wte(input_ids)
761else:
762inputs["inputs_embeds"] = wte(encoder_input_ids)
763inputs["decoder_inputs_embeds"] = wte(decoder_input_ids)
764
765with torch.no_grad():
766model(**inputs)[0]
767
768def test_config_and_model_silu_gated(self):
769config_and_inputs = self.model_tester.prepare_config_and_inputs()
770config = config_and_inputs[0]
771config.feed_forward_proj = "gated-silu"
772self.model_tester.create_and_check_model(*config_and_inputs)
773
774def test_with_lm_head(self):
775config_and_inputs = self.model_tester.prepare_config_and_inputs()
776self.model_tester.create_and_check_with_lm_head(*config_and_inputs)
777
778def test_with_sequence_classification_head(self):
779config_and_inputs = self.model_tester.prepare_config_and_inputs()
780self.model_tester.create_and_check_with_sequence_classification_head(*config_and_inputs)
781
782def test_decoder_model_past(self):
783config_and_inputs = self.model_tester.prepare_config_and_inputs()
784self.model_tester.create_and_check_decoder_model_past(*config_and_inputs)
785
786def test_decoder_model_past_with_attn_mask(self):
787config_and_inputs = self.model_tester.prepare_config_and_inputs()
788self.model_tester.create_and_check_decoder_model_attention_mask_past(*config_and_inputs)
789
790def test_decoder_model_past_with_3d_attn_mask(self):
791(
792config,
793input_ids,
794decoder_input_ids,
795attention_mask,
796decoder_attention_mask,
797lm_labels,
798) = self.model_tester.prepare_config_and_inputs()
799
800attention_mask = ids_tensor(
801[self.model_tester.batch_size, self.model_tester.encoder_seq_length, self.model_tester.encoder_seq_length],
802vocab_size=2,
803)
804decoder_attention_mask = ids_tensor(
805[self.model_tester.batch_size, self.model_tester.decoder_seq_length, self.model_tester.decoder_seq_length],
806vocab_size=2,
807)
808
809self.model_tester.create_and_check_decoder_model_attention_mask_past(
810config,
811input_ids,
812decoder_input_ids,
813attention_mask,
814decoder_attention_mask,
815lm_labels,
816)
817
818def test_decoder_model_past_with_large_inputs(self):
819config_and_inputs = self.model_tester.prepare_config_and_inputs()
820self.model_tester.create_and_check_decoder_model_past_large_inputs(*config_and_inputs)
821
822def test_generate_with_past_key_values(self):
823config_and_inputs = self.model_tester.prepare_config_and_inputs()
824self.model_tester.create_and_check_generate_with_past_key_values(*config_and_inputs)
825
826def test_encoder_decoder_shared_weights(self):
827config_and_inputs = self.model_tester.prepare_config_and_inputs()
828self.model_tester.create_and_check_encoder_decoder_shared_weights(*config_and_inputs)
829
830@unittest.skipIf(torch_device == "cpu", "Cant do half precision")
831def test_model_fp16_forward(self):
832config_and_inputs = self.model_tester.prepare_config_and_inputs()
833self.model_tester.create_and_check_model_fp16_forward(*config_and_inputs)
834
835def test_v1_1_resize_embeddings(self):
836config = self.model_tester.prepare_config_and_inputs()[0]
837self.model_tester.check_resize_embeddings_t5_v1_1(config)
838
839@slow
840def test_model_from_pretrained(self):
841for model_name in T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
842model = T5Model.from_pretrained(model_name)
843self.assertIsNotNone(model)
844
845@unittest.skip("Test has a segmentation fault on torch 1.8.0")
846def test_export_to_onnx(self):
847config_and_inputs = self.model_tester.prepare_config_and_inputs()
848model = T5Model(config_and_inputs[0]).to(torch_device)
849with tempfile.TemporaryDirectory() as tmpdirname:
850torch.onnx.export(
851model,
852(config_and_inputs[1], config_and_inputs[3], config_and_inputs[2]),
853f"{tmpdirname}/t5_test.onnx",
854export_params=True,
855opset_version=9,
856input_names=["input_ids", "decoder_input_ids"],
857)
858
859def test_generate_with_head_masking(self):
860attention_names = ["encoder_attentions", "decoder_attentions", "cross_attentions"]
861config_and_inputs = self.model_tester.prepare_config_and_inputs()
862config = config_and_inputs[0]
863max_length = config_and_inputs[1].shape[-1] + 3
864model = T5ForConditionalGeneration(config).eval()
865model.to(torch_device)
866
867head_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
873for attn_name, (name, mask) in zip(attention_names, head_masking.items()):
874head_masks = {name: mask}
875# Explicitly pass decoder_head_mask as it is required from T5 model when head_mask specified
876if name == "head_mask":
877head_masks["decoder_head_mask"] = torch.ones(
878config.num_decoder_layers, config.num_heads, device=torch_device
879)
880
881out = model.generate(
882config_and_inputs[1],
883num_beams=1,
884max_length=max_length,
885output_attentions=True,
886return_dict_in_generate=True,
887**head_masks,
888)
889# We check the state of decoder_attentions and cross_attentions just from the last step
890attn_weights = out[attn_name] if attn_name == attention_names[0] else out[attn_name][-1]
891self.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.")
894def test_disk_offload(self):
895pass
896
897@unittest.skip("Does not support conversations.")
898def test_pipeline_conversational(self):
899pass
900
901
902class T5EncoderOnlyModelTester:
903def __init__(
904self,
905parent,
906vocab_size=99,
907batch_size=13,
908encoder_seq_length=7,
909# For common tests
910use_attention_mask=True,
911hidden_size=32,
912num_hidden_layers=2,
913num_attention_heads=4,
914d_ff=37,
915relative_attention_num_buckets=8,
916is_training=False,
917dropout_rate=0.1,
918initializer_factor=0.002,
919is_encoder_decoder=False,
920eos_token_id=1,
921pad_token_id=0,
922scope=None,
923):
924self.parent = parent
925self.batch_size = batch_size
926self.encoder_seq_length = encoder_seq_length
927# For common tests
928self.seq_length = self.encoder_seq_length
929self.use_attention_mask = use_attention_mask
930self.vocab_size = vocab_size
931self.hidden_size = hidden_size
932self.num_hidden_layers = num_hidden_layers
933self.num_attention_heads = num_attention_heads
934self.d_ff = d_ff
935self.relative_attention_num_buckets = relative_attention_num_buckets
936self.dropout_rate = dropout_rate
937self.initializer_factor = initializer_factor
938self.eos_token_id = eos_token_id
939self.pad_token_id = pad_token_id
940self.is_encoder_decoder = is_encoder_decoder
941self.scope = None
942self.is_training = is_training
943
944def get_large_model_config(self):
945return T5Config.from_pretrained("google-t5/t5-base")
946
947def prepare_config_and_inputs(self):
948input_ids = ids_tensor([self.batch_size, self.encoder_seq_length], self.vocab_size)
949
950attention_mask = None
951if self.use_attention_mask:
952attention_mask = ids_tensor([self.batch_size, self.encoder_seq_length], vocab_size=2)
953
954config = T5Config(
955vocab_size=self.vocab_size,
956d_model=self.hidden_size,
957d_ff=self.d_ff,
958d_kv=self.hidden_size // self.num_attention_heads,
959num_layers=self.num_hidden_layers,
960num_heads=self.num_attention_heads,
961relative_attention_num_buckets=self.relative_attention_num_buckets,
962dropout_rate=self.dropout_rate,
963initializer_factor=self.initializer_factor,
964eos_token_id=self.eos_token_id,
965bos_token_id=self.pad_token_id,
966pad_token_id=self.pad_token_id,
967is_encoder_decoder=self.is_encoder_decoder,
968)
969
970return (
971config,
972input_ids,
973attention_mask,
974)
975
976def create_and_check_model(
977self,
978config,
979input_ids,
980attention_mask,
981):
982model = T5EncoderModel(config=config)
983model.to(torch_device)
984model.eval()
985result = model(
986input_ids=input_ids,
987attention_mask=attention_mask,
988)
989result = model(input_ids=input_ids)
990encoder_output = result.last_hidden_state
991
992self.parent.assertEqual(encoder_output.size(), (self.batch_size, self.encoder_seq_length, self.hidden_size))
993
994def create_and_check_model_fp16_forward(
995self,
996config,
997input_ids,
998attention_mask,
999):
1000model = T5EncoderModel(config=config).to(torch_device).half().eval()
1001output = model(input_ids, attention_mask=attention_mask)["last_hidden_state"]
1002self.parent.assertFalse(torch.isnan(output).any().item())
1003
1004def create_and_check_with_token_classification_head(
1005self,
1006config,
1007input_ids,
1008attention_mask,
1009):
1010labels = torch.tensor([1] * self.seq_length * self.batch_size, dtype=torch.long, device=torch_device)
1011model = T5ForTokenClassification(config=config).to(torch_device).eval()
1012outputs = model(
1013input_ids=input_ids,
1014labels=labels,
1015attention_mask=attention_mask,
1016)
1017self.parent.assertEqual(outputs["logits"].size(), (self.batch_size, self.seq_length, config.num_labels))
1018self.parent.assertEqual(outputs["loss"].size(), ())
1019
1020def prepare_config_and_inputs_for_common(self):
1021config_and_inputs = self.prepare_config_and_inputs()
1022(
1023config,
1024input_ids,
1025attention_mask,
1026) = config_and_inputs
1027
1028inputs_dict = {
1029"input_ids": input_ids,
1030"attention_mask": attention_mask,
1031}
1032return config, inputs_dict
1033
1034
1035class T5EncoderOnlyModelTest(ModelTesterMixin, PipelineTesterMixin, unittest.TestCase):
1036all_model_classes = (T5EncoderModel, T5ForTokenClassification) if is_torch_available() else ()
1037test_pruning = False
1038test_resize_embeddings = False
1039test_model_parallel = True
1040pipeline_model_mapping = (
1041{
1042"token-classification": T5ForTokenClassification,
1043}
1044if is_torch_available()
1045else {}
1046)
1047all_parallelizable_model_classes = (T5EncoderModel,) if is_torch_available() else ()
1048
1049def setUp(self):
1050self.model_tester = T5EncoderOnlyModelTester(self)
1051self.config_tester = ConfigTester(self, config_class=T5Config, d_model=37)
1052
1053def test_config(self):
1054self.config_tester.run_common_tests()
1055
1056def test_model(self):
1057config_and_inputs = self.model_tester.prepare_config_and_inputs()
1058self.model_tester.create_and_check_model(*config_and_inputs)
1059
1060@unittest.skipIf(torch_device == "cpu", "Cant do half precision")
1061def test_model_fp16_forward(self):
1062config_and_inputs = self.model_tester.prepare_config_and_inputs()
1063self.model_tester.create_and_check_model_fp16_forward(*config_and_inputs)
1064
1065def test_with_token_classification_head(self):
1066config_and_inputs = self.model_tester.prepare_config_and_inputs()
1067self.model_tester.create_and_check_with_token_classification_head(*config_and_inputs)
1068
1069
1070def use_task_specific_params(model, task):
1071model.config.update(model.config.task_specific_params[task])
1072
1073
1074@require_torch
1075@require_accelerate
1076@require_tokenizers
1077@slow
1078class T5ModelFp16Tests(unittest.TestCase):
1079def test_fp16_fp32_conversion(self):
1080r"""
1081A test to check whether the argument `keep_in_fp32_modules` correctly does its job
1082"""
1083orig_import = __import__
1084accelerate_mock = unittest.mock.Mock()
1085
1086# mock import of accelerate
1087def import_accelerate_mock(name, *args, **kwargs):
1088if name == "accelerate":
1089if accelerate_available:
1090return accelerate_mock
1091else:
1092raise ImportError
1093return orig_import(name, *args, **kwargs)
1094
1095# Load without using `accelerate`
1096with unittest.mock.patch("builtins.__import__", side_effect=import_accelerate_mock):
1097accelerate_available = False
1098
1099model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small", torch_dtype=torch.float16)
1100self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.float32)
1101self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wi.weight.dtype == torch.float16)
1102
1103# Load without in bf16
1104model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small", torch_dtype=torch.bfloat16)
1105self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.bfloat16)
1106self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wi.weight.dtype == torch.bfloat16)
1107
1108# Load using `accelerate` in bf16
1109model = T5ForConditionalGeneration.from_pretrained(
1110"google-t5/t5-small", torch_dtype=torch.bfloat16, device_map="auto"
1111)
1112self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.bfloat16)
1113self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wi.weight.dtype == torch.bfloat16)
1114
1115# Load using `accelerate` in bf16
1116model = T5ForConditionalGeneration.from_pretrained(
1117"google-t5/t5-small", torch_dtype=torch.bfloat16, low_cpu_mem_usage=True
1118)
1119self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.bfloat16)
1120self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wi.weight.dtype == torch.bfloat16)
1121
1122# Load without using `accelerate`
1123model = T5ForConditionalGeneration.from_pretrained(
1124"google-t5/t5-small", torch_dtype=torch.float16, low_cpu_mem_usage=True
1125)
1126self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.float32)
1127self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wi.weight.dtype == torch.float16)
1128
1129# Load using `accelerate`
1130model = T5ForConditionalGeneration.from_pretrained(
1131"google-t5/t5-small", torch_dtype=torch.float16, device_map="auto"
1132)
1133self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.float32)
1134self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wi.weight.dtype == torch.float16)
1135
1136
1137@require_torch
1138@require_sentencepiece
1139@require_tokenizers
1140class T5ModelIntegrationTests(unittest.TestCase):
1141@cached_property
1142def model(self):
1143return T5ForConditionalGeneration.from_pretrained("google-t5/t5-base").to(torch_device)
1144
1145@cached_property
1146def tokenizer(self):
1147return T5Tokenizer.from_pretrained("google-t5/t5-base")
1148
1149@slow
1150def test_torch_quant(self):
1151r"""
1152Test that a simple `torch.quantization.quantize_dynamic` call works on a T5 model.
1153"""
1154model_name = "google/flan-t5-small"
1155tokenizer = T5Tokenizer.from_pretrained(model_name)
1156model = T5ForConditionalGeneration.from_pretrained(model_name)
1157model = torch.quantization.quantize_dynamic(model, {torch.nn.Linear}, dtype=torch.qint8)
1158input_text = "Answer the following yes/no question by reasoning step-by-step. Can you write a whole Haiku in a single tweet?"
1159input_ids = tokenizer(input_text, return_tensors="pt").input_ids
1160_ = model.generate(input_ids)
1161
1162@slow
1163def test_small_generation(self):
1164model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small").to(torch_device)
1165model.config.max_length = 8
1166model.config.num_beams = 1
1167model.config.do_sample = False
1168tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small")
1169
1170input_ids = tokenizer("summarize: Hello there", return_tensors="pt").input_ids.to(torch_device)
1171
1172sequences = model.generate(input_ids)
1173
1174output_str = tokenizer.batch_decode(sequences, skip_special_tokens=True)[0]
1175self.assertTrue(output_str == "Hello there!")
1176
1177@slow
1178def test_small_integration_test(self):
1179"""
1180For 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
1191model = T5ForConditionalGeneration.from_pretrained("google-t5/t5-small").to(torch_device)
1192tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small")
1193
1194input_ids = tokenizer("Hello there", return_tensors="pt").input_ids
1195labels = tokenizer("Hi I am", return_tensors="pt").input_ids
1196
1197loss = model(input_ids.to(torch_device), labels=labels.to(torch_device)).loss
1198mtf_score = -(labels.shape[-1] * loss.item())
1199
1200EXPECTED_SCORE = -19.0845
1201self.assertTrue(abs(mtf_score - EXPECTED_SCORE) < 1e-4)
1202
1203@slow
1204def test_small_v1_1_integration_test(self):
1205"""
1206For 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
1217model = T5ForConditionalGeneration.from_pretrained("google/t5-v1_1-small").to(torch_device)
1218tokenizer = T5Tokenizer.from_pretrained("google/t5-v1_1-small")
1219
1220input_ids = tokenizer("Hello there", return_tensors="pt").input_ids
1221labels = tokenizer("Hi I am", return_tensors="pt").input_ids
1222
1223loss = model(input_ids.to(torch_device), labels=labels.to(torch_device)).loss
1224mtf_score = -(labels.shape[-1] * loss.item())
1225
1226EXPECTED_SCORE = -59.0293
1227self.assertTrue(abs(mtf_score - EXPECTED_SCORE) < 1e-4)
1228
1229@slow
1230def test_small_byt5_integration_test(self):
1231"""
1232For 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
1241model = T5ForConditionalGeneration.from_pretrained("google/byt5-small").to(torch_device)
1242tokenizer = ByT5Tokenizer.from_pretrained("google/byt5-small")
1243
1244input_ids = tokenizer("Hello there", return_tensors="pt").input_ids
1245labels = tokenizer("Hi I am", return_tensors="pt").input_ids
1246
1247loss = model(input_ids.to(torch_device), labels=labels.to(torch_device)).loss
1248mtf_score = -(labels.shape[-1] * loss.item())
1249
1250EXPECTED_SCORE = -60.7397
1251self.assertTrue(abs(mtf_score - EXPECTED_SCORE) < 1e-4)
1252
1253@slow
1254def test_summarization(self):
1255model = self.model
1256tok = self.tokenizer
1257
1258FRANCE_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)
1331SHORTER_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)
1369IRAN_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)
1420ARTICLE_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
1446expected_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
1462use_task_specific_params(model, "summarization")
1463
1464dct = tok(
1465[model.config.prefix + x for x in [FRANCE_ARTICLE, SHORTER_ARTICLE, IRAN_ARTICLE, ARTICLE_SUBWAY]],
1466padding="max_length",
1467truncation=True,
1468return_tensors="pt",
1469).to(torch_device)
1470self.assertEqual(512, dct["input_ids"].shape[1])
1471
1472hypotheses_batch = model.generate(
1473**dct,
1474num_beams=4,
1475length_penalty=2.0,
1476max_length=142,
1477min_length=56,
1478no_repeat_ngram_size=3,
1479do_sample=False,
1480early_stopping=True,
1481)
1482
1483decoded = tok.batch_decode(hypotheses_batch, skip_special_tokens=True, clean_up_tokenization_spaces=False)
1484self.assertListEqual(
1485expected_summaries,
1486decoded,
1487)
1488
1489@slow
1490def test_translation_en_to_de(self):
1491model = self.model
1492tok = self.tokenizer
1493use_task_specific_params(model, "translation_en_to_de")
1494
1495en_text = '"Luigi often said to me that he never wanted the brothers to end up in court", she wrote.'
1496expected_translation = (
1497'"Luigi sagte mir oft, dass er nie wollte, dass die Brüder am Gericht sitzen", schrieb sie.'
1498)
1499
1500input_ids = tok.encode(model.config.prefix + en_text, return_tensors="pt")
1501input_ids = input_ids.to(torch_device)
1502output = model.generate(input_ids)
1503translation = tok.decode(output[0], skip_special_tokens=True, clean_up_tokenization_spaces=False)
1504self.assertEqual(translation, expected_translation)
1505
1506@slow
1507def test_translation_en_to_fr(self):
1508model = self.model # google-t5/t5-base
1509tok = self.tokenizer
1510use_task_specific_params(model, "translation_en_to_fr")
1511
1512en_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
1517input_ids = tok.encode(model.config.prefix + en_text, return_tensors="pt")
1518input_ids = input_ids.to(torch_device)
1519
1520output = model.generate(
1521input_ids=input_ids,
1522num_beams=4,
1523length_penalty=2.0,
1524max_length=100,
1525no_repeat_ngram_size=3,
1526do_sample=False,
1527early_stopping=True,
1528)
1529translation = tok.decode(output[0], skip_special_tokens=True, clean_up_tokenization_spaces=False)
1530new_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
1538self.assertEqual(translation, new_truncated_translation)
1539
1540@slow
1541def test_translation_en_to_ro(self):
1542model = self.model
1543tok = self.tokenizer
1544use_task_specific_params(model, "translation_en_to_ro")
1545en_text = "Taco Bell said it plans to add 2,000 locations in the US by 2022."
1546expected_translation = "Taco Bell a declarat că intenţionează să adauge 2 000 de locaţii în SUA până în 2022."
1547
1548inputs = tok(model.config.prefix + en_text, return_tensors="pt").to(torch_device)
1549output = model.generate(**inputs)
1550translation = tok.decode(output[0], skip_special_tokens=True, clean_up_tokenization_spaces=False)
1551self.assertEqual(translation, expected_translation)
1552
1553@slow
1554def test_contrastive_search_t5(self):
1555article = (
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)
1580article = "summarize: " + article.strip()
1581t5_tokenizer = AutoTokenizer.from_pretrained("flax-community/t5-base-cnn-dm")
1582t5_model = T5ForConditionalGeneration.from_pretrained("flax-community/t5-base-cnn-dm").to(torch_device)
1583input_ids = t5_tokenizer(
1584article, add_special_tokens=False, truncation=True, max_length=512, return_tensors="pt"
1585).input_ids.to(torch_device)
1586
1587outputs = t5_model.generate(input_ids, penalty_alpha=0.5, top_k=5, max_length=64)
1588generated_text = t5_tokenizer.batch_decode(outputs, skip_special_tokens=True)
1589
1590self.assertListEqual(
1591generated_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
1600class TestAsymmetricT5(unittest.TestCase):
1601def build_model_and_check_forward_pass(self, **kwargs):
1602tester = T5ModelTester(self, **kwargs)
1603config, *inputs = tester.prepare_config_and_inputs()
1604(
1605input_ids,
1606decoder_input_ids,
1607attention_mask,
1608decoder_attention_mask,
1609lm_labels,
1610) = inputs
1611model = T5ForConditionalGeneration(config=config).to(torch_device).eval()
1612outputs = model(
1613input_ids=input_ids,
1614decoder_input_ids=decoder_input_ids,
1615decoder_attention_mask=decoder_attention_mask,
1616labels=lm_labels,
1617)
1618# outputs = model(*inputs)
1619assert len(outputs) == 4
1620assert outputs["logits"].size() == (tester.batch_size, tester.decoder_seq_length, tester.vocab_size)
1621assert outputs["loss"].size() == ()
1622return model
1623
1624def test_small_decoder(self):
1625# num_hidden_layers is passed to T5Config as num_layers
1626model = self.build_model_and_check_forward_pass(decoder_layers=1, num_hidden_layers=2)
1627assert len(model.encoder.block) == 2
1628assert len(model.decoder.block) == 1
1629
1630def test_defaulting_to_symmetry(self):
1631# num_hidden_layers is passed to T5Config as num_layers
1632model = self.build_model_and_check_forward_pass(num_hidden_layers=2)
1633assert len(model.decoder.block) == len(model.encoder.block) == 2
1634