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        __snake_case	(					UpperCamelCase__    ):



      def __init__(						self   ,      *lowercase   ,      lowercase=None   ,      lowercase=None   ,      **lowercase)     ->      int:





        '''simple docstring'''





        super().__init__(*__lowerCamelCase   ,      **__lowerCamelCase)
        a__:					Dict      							=     eval_examples
        a__:					List[str]      							=     post_process_function



      def   lowerCamelCase_       (						self   ,      lowercase=None   ,      lowercase=None   ,      lowercase=None   ,      lowercase = "eval")     ->      List[Any]:





        '''simple docstring'''





        a__:					List[str]      							=     self.eval_dataset if eval_dataset is None else eval_dataset
        a__:					Tuple      							=     self.get_eval_dataloader(__lowerCamelCase)
        a__:					Any      							=     self.eval_examples if eval_examples is None else eval_examples

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

          # Prefix all keys with metric_key_prefix + '_'
          for key in list(metrics.keys()):
            if not key.startswith(f'{metric_key_prefix}_'):
              a__:					List[str]      							=     metrics.pop(__lowerCamelCase)
          metrics.update(output.metrics)
        else:
          a__:					Union[str, Any]      							=     output.metrics

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

        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__:					str      							=     self.callback_handler.on_evaluate(self.args   ,      self.state   ,      self.control   ,      __lowerCamelCase)
        return metrics



      def   lowerCamelCase_       (						self   ,      lowercase   ,      lowercase   ,      lowercase=None   ,      lowercase = "test")     ->      Union[str, Any]:





        '''simple docstring'''





        a__:					Dict      							=     self.get_test_dataloader(__lowerCamelCase)

        # Temporarily disable metric computation, we will do it in the loop here.
        a__:					Union[str, Any]      							=     self.compute_metrics
        a__:					List[Any]      							=     None
        a__:					int      							=     self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
        a__:					int      							=     time.time()
        try:
          a__:					int      							=     eval_loop(
              __lowerCamelCase   ,      description='Prediction'   ,      prediction_loss_only=True if compute_metrics is None else None   ,      ignore_keys=__lowerCamelCase   ,      metric_key_prefix=__lowerCamelCase   ,      )
        finally:
          a__:					List[Any]      							=     compute_metrics
        a__:					Any      							=     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(
                __lowerCamelCase   ,      __lowerCamelCase   ,      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__:					List[str]      							=     self.post_process_function(__lowerCamelCase   ,      __lowerCamelCase   ,      output.predictions   ,      'predict')
        a__:					int      							=     self.compute_metrics(__lowerCamelCase)

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



"""simple docstring"""
import json
import os
import unittest

from transformers import DebertaTokenizer, DebertaTokenizerFast
from transformers.models.deberta.tokenization_deberta import VOCAB_FILES_NAMES
from transformers.testing_utils import slow

from ...test_tokenization_common import TokenizerTesterMixin




class        __snake_case	(					__lowerCAmelCase	,				unittest.TestCase    ):
      a__				=		DebertaTokenizer
      a__				=		True
      a__				=		DebertaTokenizerFast



      def   lowerCamelCase_       (						self)     ->      str:





        '''simple docstring'''





        super().setUp()

        # Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
        a__:					List[str]      							=     [
            'l',
            'o',
            'w',
            'e',
            'r',
            's',
            't',
            'i',
            'd',
            'n',
            '\u0120',
            '\u0120l',
            '\u0120n',
            '\u0120lo',
            '\u0120low',
            'er',
            '\u0120lowest',
            '\u0120newer',
            '\u0120wider',
            '[UNK]',
        ]
        a__:					List[str]      							=     dict(zip(lowercase   ,      range(len(lowercase))))
        a__:					Any      							=     ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', '']
        a__:					Optional[Any]      							=     {'unk_token': '[UNK]'}

        a__:					Any      							=     os.path.join(self.tmpdirname   ,      VOCAB_FILES_NAMES['vocab_file'])
        a__:					Dict      							=     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(lowercase) + '\n')
        with open(self.merges_file   ,      'w'   ,      encoding='utf-8') as fp:
          fp.write('\n'.join(lowercase))



      def   lowerCamelCase_       (						self   ,      **lowercase)     ->      int:





        '''simple docstring'''





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



      def   lowerCamelCase_       (						self   ,      lowercase)     ->      Dict:





        '''simple docstring'''





        a__:					Tuple      							=     'lower newer'
        a__:					int      							=     'lower newer'
        return input_text, output_text



      def   lowerCamelCase_       (						self)     ->      Optional[int]:





        '''simple docstring'''





        a__:					Optional[int]      							=     self.get_tokenizer()
        a__:					List[Any]      							=     'lower newer'
        a__:					Optional[int]      							=     ['l', 'o', 'w', 'er', '\u0120', 'n', 'e', 'w', 'er']
        a__:					Optional[Any]      							=     tokenizer.tokenize(lowercase)
        self.assertListEqual(lowercase   ,      lowercase)

        a__:					int      							=     tokens + [tokenizer.unk_token]
        a__:					Optional[int]      							=     [0, 1, 2, 15, 10, 9, 3, 2, 15, 19]
        self.assertListEqual(tokenizer.convert_tokens_to_ids(lowercase)   ,      lowercase)



      def   lowerCamelCase_       (						self)     ->      List[str]:





        '''simple docstring'''





        a__:					int      							=     self.get_tokenizer()
        a__:					Any      							=     tokenizer('Hello'   ,      'World')
        a__:					Optional[Any]      							=     [0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]
        self.assertListEqual(tokd['token_type_ids']   ,      lowercase)



      @slow
      def   lowerCamelCase_       (						self)     ->      int:





        '''simple docstring'''





        a__:					Dict      							=     self.tokenizer_class.from_pretrained('microsoft/deberta-base')

        a__:					Union[str, Any]      							=     tokenizer.encode('sequence builders'   ,      add_special_tokens=lowercase)
        a__:					Optional[Any]      							=     tokenizer.encode('multi-sequence build'   ,      add_special_tokens=lowercase)

        a__:					List[str]      							=     tokenizer.encode(
            'sequence builders'   ,      add_special_tokens=lowercase   ,      add_prefix_space=lowercase)
        a__:					Any      							=     tokenizer.encode(
            'sequence builders'   ,      'multi-sequence build'   ,      add_special_tokens=lowercase   ,      add_prefix_space=lowercase)

        a__:					Optional[int]      							=     tokenizer.build_inputs_with_special_tokens(lowercase)
        a__:					Union[str, Any]      							=     tokenizer.build_inputs_with_special_tokens(lowercase   ,      lowercase)

        assert encoded_sentence == encoded_text_from_decode
        assert encoded_pair == encoded_pair_from_decode



      @slow
      def   lowerCamelCase_       (						self)     ->      Any:





        '''simple docstring'''





        a__:					List[Any]      							=     [self.tokenizer_class]
        if self.test_rust_tokenizer:
          tokenizer_classes.append(self.rust_tokenizer_class)

        for tokenizer_class in tokenizer_classes:
          a__:					int      							=     tokenizer_class.from_pretrained('microsoft/deberta-base')

          a__:					List[str]      							=     [
              'ALBERT: A Lite BERT for Self-supervised Learning of Language Representations',
              'ALBERT incorporates two parameter reduction techniques',
              'The first one is a factorized embedding parameterization. By decomposing the large vocabulary'
              ' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of'
              ' vocabulary embedding.',
          ]

          a__:					Dict      							=     tokenizer(lowercase   ,      padding=lowercase)
          a__:					Union[str, Any]      							=     [tokenizer.decode(lowercase   ,      skip_special_tokens=lowercase) for seq in encoding['input_ids']]

          # fmt: off
          a__:					Any      							=     {
              'input_ids': [
                  [1, 21_18, 1_11_26, 5_65, 35, 83, 2_51_91, 1_63, 1_88_54, 13, 1_21_56, 12, 1_61_01, 2_53_76, 1_38_07, 9, 2_22_05, 2_78_93, 16_35, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [1, 21_18, 1_11_26, 5_65, 2_45_36, 80, 4_37_97, 48_78, 73_73, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [1, 1_33, 78, 65, 16, 10, 37_24, 15_38, 3_31_83, 1_13_03, 4_37_97, 19_38, 4, 8_70, 2_41_65, 2_91_05, 5, 7_39, 3_26_44, 3_31_83, 1_13_03, 3_61_73, 88, 80, 6_50, 78_21, 4_59_40, 6, 52, 25_59, 5, 18_36, 9, 5, 73_97, 1_31_71, 31, 5, 18_36, 9, 3_26_44, 3_31_83, 1_13_03, 4, 2]
              ],
              'token_type_ids': [
                  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
              ],
              'attention_mask': [
                  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
                  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
              ]
          }
          # fmt: on

          a__:					str      							=     [
              'ALBERT: A Lite BERT for Self-supervised Learning of Language Representations',
              'ALBERT incorporates two parameter reduction techniques',
              'The first one is a factorized embedding parameterization. By decomposing the large vocabulary'
              ' embedding matrix into two small matrices, we separate the size of the hidden layers from the size of'
              ' vocabulary embedding.',
          ]

          self.assertDictEqual(encoding.data   ,      lowercase)

          for expected, decoded in zip(lowercase   ,      lowercase):
            self.assertEqual(lowercase   ,      lowercase)


