





import math
import time

from transformers import Trainer, 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 		SCREAMING_SNAKE_CASE__				(       _UpperCAmelCase  ):


      def __init__(self       :      Tuple				,			*a__       :      Union[str, Any]				,			a__       :      Tuple=None				,			a__       :      Optional[int]=None				,			**a__       :      int      ):





         """simple docstring"""



         super().__init__(*a__				,			**a__      )
         __snake_case							       =   eval_examples
         __snake_case							       =   post_process_function


      def    a (self       :      int				,			a__       :      int=None				,			a__       :      Union[str, Any]=None				,			a__       :      Optional[Any]=None				,			a__       :      str = "eval"      ):





         """simple docstring"""



         __snake_case							       =   self.eval_dataset if eval_dataset is None else eval_dataset
         __snake_case							       =   self.get_eval_dataloader(a__      )
         __snake_case							       =   self.eval_examples if eval_examples is None else eval_examples

         # Temporarily disable metric computation, we will do it in the loop here.
         __snake_case							       =   self.compute_metrics
         __snake_case							       =   None
         __snake_case							       =   self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
         __snake_case							       =   time.time()
         try:
            __snake_case							       =   eval_loop(
                a__				,			description='''Evaluation'''				,			prediction_loss_only=True if compute_metrics is None else None				,			ignore_keys=a__				,			metric_key_prefix=a__				,			)
         finally:
            __snake_case							       =   compute_metrics
         __snake_case							       =   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(
                 a__				,			a__				,			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
            __snake_case							       =   self.post_process_function(a__				,			a__				,			output.predictions      )
            __snake_case							       =   self.compute_metrics(a__      )

            # Prefix all keys with metric_key_prefix + '_'
            for key in list(metrics.keys()      ):
               if not key.startswith(f"""{metric_key_prefix}_"""      ):
                  __snake_case							       =   metrics.pop(a__      )
            metrics.update(output.metrics      )
         else:
            __snake_case							       =   output.metrics

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

         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()      )

         __snake_case							       =   self.callback_handler.on_evaluate(self.args				,			self.state				,			self.control				,			a__      )
         return metrics


      def    a (self       :      str				,			a__       :      List[Any]				,			a__       :      int				,			a__       :      List[str]=None				,			a__       :      str = "test"      ):





         """simple docstring"""



         __snake_case							       =   self.get_test_dataloader(a__      )

         # Temporarily disable metric computation, we will do it in the loop here.
         __snake_case							       =   self.compute_metrics
         __snake_case							       =   None
         __snake_case							       =   self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
         __snake_case							       =   time.time()
         try:
            __snake_case							       =   eval_loop(
                a__				,			description='''Prediction'''				,			prediction_loss_only=True if compute_metrics is None else None				,			ignore_keys=a__				,			metric_key_prefix=a__				,			)
         finally:
            __snake_case							       =   compute_metrics
         __snake_case							       =   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(
                 a__				,			a__				,			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

         __snake_case							       =   self.post_process_function(a__				,			a__				,			output.predictions				,			'''predict'''      )
         __snake_case							       =   self.compute_metrics(a__      )

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








import os
import unittest

from transformers.models.bartpho.tokenization_bartpho import VOCAB_FILES_NAMES, BartphoTokenizer
from transformers.testing_utils import get_tests_dir

from ...test_tokenization_common import TokenizerTesterMixin


snake_case_				=			get_tests_dir('fixtures/test_sentencepiece_bpe.model')

class 		SCREAMING_SNAKE_CASE__				(       _UpperCAmelCase						,      unittest.TestCase  ):
      A_						:				List[Any]							=    BartphoTokenizer
      A_						:				List[str]							=    False
      A_						:				Optional[Any]							=    True


      def    a (self       :      Tuple      ):





         """simple docstring"""



         super().setUp()

         __snake_case							       =   ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est''']
         __snake_case							       =   dict(zip(a__				,			range(len(a__      )      )      )      )
         __snake_case							       =   {'''unk_token''': '''<unk>'''}

         __snake_case							       =   os.path.join(self.tmpdirname				,			VOCAB_FILES_NAMES['''monolingual_vocab_file''']      )
         with open(self.monolingual_vocab_file				,			'''w'''				,			encoding='''utf-8'''      ) as fp:
            for token in vocab_tokens:
               fp.write(f"""{token} {vocab_tokens[token]}\n"""      )

         __snake_case							       =   BartphoTokenizer(a__				,			self.monolingual_vocab_file				,			**self.special_tokens_map      )
         tokenizer.save_pretrained(self.tmpdirname      )


      def    a (self       :      str				,			**a__       :      str      ):





         """simple docstring"""



         kwargs.update(self.special_tokens_map      )
         return BartphoTokenizer.from_pretrained(self.tmpdirname				,			**a__      )


      def    a (self       :      str				,			a__       :      Any      ):





         """simple docstring"""



         __snake_case							       =   '''This is a là test'''
         __snake_case							       =   '''This is a<unk><unk> test'''
         return input_text, output_text


      def    a (self       :      Dict      ):





         """simple docstring"""



         __snake_case							       =   BartphoTokenizer(a__				,			self.monolingual_vocab_file				,			**self.special_tokens_map      )
         __snake_case							       =   '''This is a là test'''
         __snake_case							       =   '''▁This ▁is ▁a ▁l à ▁t est'''.split()
         __snake_case							       =   tokenizer.tokenize(a__      )
         self.assertListEqual(a__				,			a__      )

         __snake_case							       =   tokens + [tokenizer.unk_token]
         __snake_case							       =   [4, 5, 6, 3, 3, 7, 8, 3]
         self.assertListEqual(tokenizer.convert_tokens_to_ids(a__      )				,			a__      )

