



import json
import os
import unittest

from transformers import BatchEncoding, LEDTokenizer, LEDTokenizerFast
from transformers.models.led.tokenization_led import VOCAB_FILES_NAMES
from transformers.testing_utils import require_tokenizers, require_torch
from transformers.utils import cached_property

from ...test_tokenization_common import TokenizerTesterMixin

@require_tokenizers
class     _A       (	__UpperCAmelCase      ,unittest.TestCase    ):
       UpperCamelCase__  :    Any											=						LEDTokenizer
       UpperCamelCase__  :    str											=						LEDTokenizerFast
       UpperCamelCase__  :    List[Any]											=						True



       def 		_lowerCamelCase			(		self							:     Optional[int]):


           '''simple docstring'''

           super().setUp()
           __a						       =				[
               '''l''',
               '''o''',
               '''w''',
               '''e''',
               '''r''',
               '''s''',
               '''t''',
               '''i''',
               '''d''',
               '''n''',
               '''\u0120''',
               '''\u0120l''',
               '''\u0120n''',
               '''\u0120lo''',
               '''\u0120low''',
               '''er''',
               '''\u0120lowest''',
               '''\u0120newer''',
               '''\u0120wider''',
               '''<unk>''',
           ]
           __a						       =				dict(zip(__SCREAMING_SNAKE_CASE     ,		range(len(__SCREAMING_SNAKE_CASE))))
           __a						       =				['''#version: 0.2''', '''\u0120 l''', '''\u0120l o''', '''\u0120lo w''', '''e r''', '''''']
           __a						       =				{'''unk_token''': '''<unk>'''}

           __a						       =				os.path.join(self.tmpdirname     ,		VOCAB_FILES_NAMES['''vocab_file'''])
           __a						       =				os.path.join(self.tmpdirname     ,		VOCAB_FILES_NAMES['''merges_file'''])
           with open(self.vocab_file     ,		'''w'''     ,		encoding='''utf-8''') as fp:
               fp.write(json.dumps(__SCREAMING_SNAKE_CASE) + '''\n''')
           with open(self.merges_file     ,		'''w'''     ,		encoding='''utf-8''') as fp:
               fp.write('''\n'''.join(__SCREAMING_SNAKE_CASE))



       def 		_lowerCamelCase			(		self							:     str     ,		**__SCREAMING_SNAKE_CASE							:     Dict):


           '''simple docstring'''

           kwargs.update(self.special_tokens_map)
           return self.tokenizer_class.from_pretrained(self.tmpdirname     ,		**__SCREAMING_SNAKE_CASE)



       def 		_lowerCamelCase			(		self							:     int     ,		**__SCREAMING_SNAKE_CASE							:     int):


           '''simple docstring'''

           kwargs.update(self.special_tokens_map)
           return self.rust_tokenizer_class.from_pretrained(self.tmpdirname     ,		**__SCREAMING_SNAKE_CASE)



       def 		_lowerCamelCase			(		self							:     Optional[int]     ,		__SCREAMING_SNAKE_CASE							:     Union[str, Any]):


           '''simple docstring'''

           return "lower newer", "lower newer"



       @cached_property
       def 		_lowerCamelCase			(		self							:     Optional[int]):


           '''simple docstring'''

           return LEDTokenizer.from_pretrained('''allenai/led-base-16384''')



       @cached_property
       def 		_lowerCamelCase			(		self							:     Any):


           '''simple docstring'''

           return LEDTokenizerFast.from_pretrained('''allenai/led-base-16384''')



       @require_torch
       def 		_lowerCamelCase			(		self							:     Optional[int]):


           '''simple docstring'''

           __a						       =				['''A long paragraph for summarization.''', '''Another paragraph for summarization.''']
           __a						       =				[0, 250, 251, 17_818, 13, 39_186, 1_938, 4, 2]

           for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
               __a						       =				tokenizer(__SCREAMING_SNAKE_CASE     ,		max_length=len(__SCREAMING_SNAKE_CASE)     ,		padding=__SCREAMING_SNAKE_CASE     ,		return_tensors='''pt''')
               self.assertIsInstance(__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE)

               self.assertEqual((2, 9)     ,		batch.input_ids.shape)
               self.assertEqual((2, 9)     ,		batch.attention_mask.shape)
               __a						       =				batch.input_ids.tolist()[0]
               self.assertListEqual(__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE)



       @require_torch
       def 		_lowerCamelCase			(		self							:     Union[str, Any]):


           '''simple docstring'''

           __a						       =				['''A long paragraph for summarization.''', '''Another paragraph for summarization.''']
           for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
               __a						       =				tokenizer(__SCREAMING_SNAKE_CASE     ,		padding=__SCREAMING_SNAKE_CASE     ,		return_tensors='''pt''')
               self.assertIn('''input_ids'''     ,		__SCREAMING_SNAKE_CASE)
               self.assertIn('''attention_mask'''     ,		__SCREAMING_SNAKE_CASE)
               self.assertNotIn('''labels'''     ,		__SCREAMING_SNAKE_CASE)
               self.assertNotIn('''decoder_attention_mask'''     ,		__SCREAMING_SNAKE_CASE)



       @require_torch
       def 		_lowerCamelCase			(		self							:     List[Any]):


           '''simple docstring'''

           __a						       =				[
               '''Summary of the text.''',
               '''Another summary.''',
           ]
           for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
               __a						       =				tokenizer(text_target=__SCREAMING_SNAKE_CASE     ,		max_length=32     ,		padding='''max_length'''     ,		return_tensors='''pt''')
               self.assertEqual(32     ,		targets['''input_ids'''].shape[1])



       @require_torch
       def 		_lowerCamelCase			(		self							:     Union[str, Any]):


           '''simple docstring'''

           for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
               __a						       =				tokenizer(
                   ['''I am a small frog''' * 1_024, '''I am a small frog''']     ,		padding=__SCREAMING_SNAKE_CASE     ,		truncation=__SCREAMING_SNAKE_CASE     ,		return_tensors='''pt''')
               self.assertIsInstance(__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE)
               self.assertEqual(batch.input_ids.shape     ,		(2, 5_122))



       @require_torch
       def 		_lowerCamelCase			(		self							:     List[Any]):


           '''simple docstring'''

           __a						       =				['''A long paragraph for summarization.''']
           __a						       =				[
               '''Summary of the text.''',
           ]
           for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
               __a						       =				tokenizer(__SCREAMING_SNAKE_CASE     ,		return_tensors='''pt''')
               __a						       =				tokenizer(text_target=__SCREAMING_SNAKE_CASE     ,		return_tensors='''pt''')
               __a						       =				inputs['''input_ids''']
               __a						       =				targets['''input_ids''']
               self.assertTrue((input_ids[:, 0] == tokenizer.bos_token_id).all().item())
               self.assertTrue((labels[:, 0] == tokenizer.bos_token_id).all().item())
               self.assertTrue((input_ids[:, -1] == tokenizer.eos_token_id).all().item())
               self.assertTrue((labels[:, -1] == tokenizer.eos_token_id).all().item())



       @require_torch
       def 		_lowerCamelCase			(		self							:     Tuple):


           '''simple docstring'''

           for tokenizer in [self.default_tokenizer, self.default_tokenizer_fast]:
               __a						       =				['''Summary of the text.''', '''Another summary.''']
               __a						       =				[[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, -1, -1]]

               __a						       =				tokenizer(__SCREAMING_SNAKE_CASE     ,		padding=__SCREAMING_SNAKE_CASE)
               __a						       =				[[0] * len(__SCREAMING_SNAKE_CASE) for x in encoded_output['''input_ids''']]
               __a						       =				tokenizer.pad(__SCREAMING_SNAKE_CASE)
               self.assertSequenceEqual(outputs['''global_attention_mask''']     ,		__SCREAMING_SNAKE_CASE)



       def 		_lowerCamelCase			(		self							:     Dict):


           '''simple docstring'''

           pass





       def 		_lowerCamelCase			(		self							:     Tuple):


           '''simple docstring'''

           for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
               with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})'):
                   __a						       =				self.rust_tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE     ,		**__SCREAMING_SNAKE_CASE)
                   __a						       =				self.tokenizer_class.from_pretrained(__SCREAMING_SNAKE_CASE     ,		**__SCREAMING_SNAKE_CASE)
                   __a						       =				'''A, <mask> AllenNLP sentence.'''
                   __a						       =				tokenizer_r.encode_plus(__SCREAMING_SNAKE_CASE     ,		add_special_tokens=__SCREAMING_SNAKE_CASE     ,		return_token_type_ids=__SCREAMING_SNAKE_CASE)
                   __a						       =				tokenizer_p.encode_plus(__SCREAMING_SNAKE_CASE     ,		add_special_tokens=__SCREAMING_SNAKE_CASE     ,		return_token_type_ids=__SCREAMING_SNAKE_CASE)
                   self.assertEqual(sum(tokens_r['''token_type_ids'''])     ,		sum(tokens_p['''token_type_ids''']))
                   self.assertEqual(
                       sum(tokens_r['''attention_mask''']) / len(tokens_r['''attention_mask'''])     ,		sum(tokens_p['''attention_mask''']) / len(tokens_p['''attention_mask'''])     ,		)

                   __a						       =				tokenizer_r.convert_ids_to_tokens(tokens_r['''input_ids'''])
                   __a						       =				tokenizer_p.convert_ids_to_tokens(tokens_p['''input_ids'''])
                   self.assertSequenceEqual(tokens_p['''input_ids''']     ,		[0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2])
                   self.assertSequenceEqual(tokens_r['''input_ids''']     ,		[0, 250, 6, 50_264, 3_823, 487, 21_992, 3_645, 4, 2])

                   self.assertSequenceEqual(
                       __SCREAMING_SNAKE_CASE     ,		['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>'''])
                   self.assertSequenceEqual(
                       __SCREAMING_SNAKE_CASE     ,		['''<s>''', '''A''', ''',''', '''<mask>''', '''ĠAllen''', '''N''', '''LP''', '''Ġsentence''', '''.''', '''</s>'''])










import math
import time
from typing import Dict, List, Optional

from torch.utils.data import Dataset

from transformers import SeqaSeqTrainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
 import torch_xla.core.xla_model as xm
 import torch_xla.debug.metrics as met

class     _A       (	__UpperCAmelCase    ):



       def __init__(		self							:     List[Any]     ,		*__SCREAMING_SNAKE_CASE							:     Tuple     ,		__SCREAMING_SNAKE_CASE							:     Any=None     ,		__SCREAMING_SNAKE_CASE							:     Union[str, Any]=None     ,		**__SCREAMING_SNAKE_CASE							:     str):


           '''simple docstring'''

           super().__init__(*__SCREAMING_SNAKE_CASE     ,		**__SCREAMING_SNAKE_CASE)
           __a						       =				eval_examples
           __a						       =				post_process_function



       def 		_lowerCamelCase			(		self							:     Dict     ,		__SCREAMING_SNAKE_CASE							:     Optional[Dataset] = None     ,		__SCREAMING_SNAKE_CASE							:     List[Any]=None     ,		__SCREAMING_SNAKE_CASE							:     Optional[List[str]] = None     ,		__SCREAMING_SNAKE_CASE							:     str = "eval"     ,		**__SCREAMING_SNAKE_CASE							:     Any     ,		):


           '''simple docstring'''

           __a						       =				gen_kwargs.copy()
           __a						       =				(
               gen_kwargs['''max_length'''] if gen_kwargs.get('''max_length''') is not None else self.args.generation_max_length
           )
           __a						       =				(
               gen_kwargs['''num_beams'''] if gen_kwargs.get('''num_beams''') is not None else self.args.generation_num_beams
           )
           __a						       =				gen_kwargs

           __a						       =				self.eval_dataset if eval_dataset is None else eval_dataset
           __a						       =				self.get_eval_dataloader(__SCREAMING_SNAKE_CASE)
           __a						       =				self.eval_examples if eval_examples is None else eval_examples

           # Temporarily disable metric computation, we will do it in the loop here.
           __a						       =				self.compute_metrics
           __a						       =				None
           __a						       =				time.time()
           __a						       =				self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
           try:
               __a						       =				eval_loop(
                   __SCREAMING_SNAKE_CASE     ,		description='''Evaluation'''     ,		prediction_loss_only=True if compute_metrics is None else None     ,		ignore_keys=__SCREAMING_SNAKE_CASE     ,		metric_key_prefix=__SCREAMING_SNAKE_CASE     ,		)
           finally:
               __a						       =				compute_metrics
           __a						       =				self.args.eval_batch_size * self.args.world_size
           if F'{metric_key_prefix}_jit_compilation_time' in output.metrics:
               start_time += output.metrics[F'{metric_key_prefix}_jit_compilation_time']
           output.metrics.update(
               speed_metrics(
                   __SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE     ,		num_samples=output.num_samples     ,		num_steps=math.ceil(output.num_samples / total_batch_size)     ,		))

           if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
               # Only the main node write the results by default
               __a						       =				self.post_process_function(__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE)
               __a						       =				self.compute_metrics(__SCREAMING_SNAKE_CASE)

               # Prefix all keys with metric_key_prefix + '_'
               for key in list(metrics.keys()):
                   if not key.startswith(F'{metric_key_prefix}_'):
                       __a						       =				metrics.pop(__SCREAMING_SNAKE_CASE)

               metrics.update(output.metrics)
           else:
               __a						       =				output.metrics

           if self.args.should_log:
               # Only the main node log the results by default
               self.log(__SCREAMING_SNAKE_CASE)

           if self.args.tpu_metrics_debug or self.args.debug:
               # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
               xm.master_print(met.metrics_report())

           __a						       =				self.callback_handler.on_evaluate(self.args     ,		self.state     ,		self.control     ,		__SCREAMING_SNAKE_CASE)
           return metrics





       def 		_lowerCamelCase			(		self							:     Tuple     ,		__SCREAMING_SNAKE_CASE							:     Any     ,		__SCREAMING_SNAKE_CASE							:     int     ,		__SCREAMING_SNAKE_CASE							:     Tuple=None     ,		__SCREAMING_SNAKE_CASE							:     str = "test"     ,		**__SCREAMING_SNAKE_CASE							:     Dict):


           '''simple docstring'''

           __a						       =				gen_kwargs.copy()

           __a						       =				self.get_test_dataloader(__SCREAMING_SNAKE_CASE)

           # Temporarily disable metric computation, we will do it in the loop here.
           __a						       =				self.compute_metrics
           __a						       =				None
           __a						       =				time.time()
           __a						       =				self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
           try:
               __a						       =				eval_loop(
                   __SCREAMING_SNAKE_CASE     ,		description='''Prediction'''     ,		prediction_loss_only=True if compute_metrics is None else None     ,		ignore_keys=__SCREAMING_SNAKE_CASE     ,		metric_key_prefix=__SCREAMING_SNAKE_CASE     ,		)
           finally:
               __a						       =				compute_metrics

           __a						       =				self.args.eval_batch_size * self.args.world_size
           if F'{metric_key_prefix}_jit_compilation_time' in output.metrics:
               start_time += output.metrics[F'{metric_key_prefix}_jit_compilation_time']
           output.metrics.update(
               speed_metrics(
                   __SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE     ,		num_samples=output.num_samples     ,		num_steps=math.ceil(output.num_samples / total_batch_size)     ,		))
           if self.post_process_function is None or self.compute_metrics is None:
               return output

           __a						       =				self.post_process_function(__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE     ,		__SCREAMING_SNAKE_CASE     ,		'''predict''')
           __a						       =				self.compute_metrics(__SCREAMING_SNAKE_CASE)

           # Prefix all keys with metric_key_prefix + '_'
           for key in list(metrics.keys()):
               if not key.startswith(F'{metric_key_prefix}_'):
                   __a						       =				metrics.pop(__SCREAMING_SNAKE_CASE)
           metrics.update(output.metrics)
           return PredictionOutput(predictions=predictions.predictions     ,		label_ids=predictions.label_ids     ,		metrics=__SCREAMING_SNAKE_CASE)





