





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  __A(						__UpperCAmelCase ):

     def __init__(      self,       *A,       A=None,       A=None,       **A      ):





            """simple docstring"""

            super().__init__(*A,       **A      )
            _UpperCamelCase              =						eval_examples
            _UpperCamelCase              =						post_process_function

     def 	_UpperCamelCase     (      self,       A=None,       A=None,       A=None,       A = "eval"      ):





            """simple docstring"""

            _UpperCamelCase              =						self.eval_dataset if eval_dataset is None else eval_dataset
            _UpperCamelCase              =						self.get_eval_dataloader(A      )
            _UpperCamelCase              =						self.eval_examples if eval_examples is None else eval_examples

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

            _UpperCamelCase              =						self.callback_handler.on_evaluate(self.args,       self.state,       self.control,       A      )
            return metrics



     def 	_UpperCamelCase     (      self,       A,       A,       A=None,       A = "test"      ):





            """simple docstring"""

            _UpperCamelCase              =						self.get_test_dataloader(A      )

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

            _UpperCamelCase              =						self.post_process_function(A,       A,       output.predictions,       '''predict'''      )
            _UpperCamelCase              =						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}_'''      ):
                          _UpperCamelCase              =						metrics.pop(A      )
            metrics.update(output.metrics      )
            return PredictionOutput(predictions=predictions.predictions,       label_ids=predictions.label_ids,       metrics=A      )













import os
from shutil import copyfile
from typing import List, Optional, Tuple

from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
       from .tokenization_big_bird import BigBirdTokenizer
else:
       lowercase    : Union[str, Any]    	=  None

lowercase    : Union[str, Any]    	=  logging.get_logger(__name__)
lowercase    : Tuple    	=  {"""vocab_file""": """spiece.model""", """tokenizer_file""": """tokenizer.json"""}

lowercase    : Any    	=  {
    """vocab_file""": {
        """google/bigbird-roberta-base""": """https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model""",
        """google/bigbird-roberta-large""": (
            """https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model"""
        ),
        """google/bigbird-base-trivia-itc""": (
            """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model"""
        ),
    },
    """tokenizer_file""": {
        """google/bigbird-roberta-base""": (
            """https://huggingface.co/google/bigbird-roberta-base/resolve/main/tokenizer.json"""
        ),
        """google/bigbird-roberta-large""": (
            """https://huggingface.co/google/bigbird-roberta-large/resolve/main/tokenizer.json"""
        ),
        """google/bigbird-base-trivia-itc""": (
            """https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/tokenizer.json"""
        ),
    },
}

lowercase    : Tuple    	=  {
    """google/bigbird-roberta-base""": 4096,
    """google/bigbird-roberta-large""": 4096,
    """google/bigbird-base-trivia-itc""": 4096,
}


lowercase    : List[str]    	=  """▁"""

class  __A(						__UpperCAmelCase ):
     __A	  =       VOCAB_FILES_NAMES
     __A	  =       PRETRAINED_VOCAB_FILES_MAP
     __A	  =       PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     __A	  =       BigBirdTokenizer
     __A	  =       ["input_ids", "attention_mask"]
     __A	  =       []

     def __init__(      self,       A=None,       A=None,       A="<unk>",       A="<s>",       A="</s>",       A="<pad>",       A="[SEP]",       A="[MASK]",       A="[CLS]",       **A,       ):





            """simple docstring"""

            _UpperCamelCase              =						AddedToken(A,       lstrip=A,       rstrip=A      ) if isinstance(A,       A      ) else bos_token
            _UpperCamelCase              =						AddedToken(A,       lstrip=A,       rstrip=A      ) if isinstance(A,       A      ) else eos_token
            _UpperCamelCase              =						AddedToken(A,       lstrip=A,       rstrip=A      ) if isinstance(A,       A      ) else unk_token
            _UpperCamelCase              =						AddedToken(A,       lstrip=A,       rstrip=A      ) if isinstance(A,       A      ) else pad_token
            _UpperCamelCase              =						AddedToken(A,       lstrip=A,       rstrip=A      ) if isinstance(A,       A      ) else cls_token
            _UpperCamelCase              =						AddedToken(A,       lstrip=A,       rstrip=A      ) if isinstance(A,       A      ) else sep_token

            # Mask token behave like a normal word, i.e. include the space before it
            _UpperCamelCase              =						AddedToken(A,       lstrip=A,       rstrip=A      ) if isinstance(A,       A      ) else mask_token

            super().__init__(
                A,       tokenizer_file=A,       bos_token=A,       eos_token=A,       unk_token=A,       sep_token=A,       pad_token=A,       cls_token=A,       mask_token=A,       **A,       )

            _UpperCamelCase              =						vocab_file
            _UpperCamelCase              =						False if not self.vocab_file else True

     def 	_UpperCamelCase     (      self,       A,       A = None      ):





            """simple docstring"""

            _UpperCamelCase              =						[self.sep_token_id]
            _UpperCamelCase              =						[self.cls_token_id]
            if token_ids_a is None:
                   return cls + token_ids_a + sep
            return cls + token_ids_a + sep + token_ids_a + sep

     def 	_UpperCamelCase     (      self,       A,       A = None,       A = False      ):





            """simple docstring"""

            if already_has_special_tokens:
                   if token_ids_a is not None:
                          raise ValueError(
                              '''You should not supply a second sequence if the provided sequence of '''
                              '''ids is already formatted with special tokens for the model.'''      )
                   return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a]

            if token_ids_a is None:
                   return [1] + ([0] * len(A      )) + [1]
            return [1] + ([0] * len(A      )) + [1] + ([0] * len(A      )) + [1]

     def 	_UpperCamelCase     (      self,       A,       A = None      ):





            """simple docstring"""

            _UpperCamelCase              =						[self.sep_token_id]
            _UpperCamelCase              =						[self.cls_token_id]

            if token_ids_a is None:
                   return len(cls + token_ids_a + sep      ) * [0]
            return len(cls + token_ids_a + sep      ) * [0] + len(token_ids_a + sep      ) * [1]



     def 	_UpperCamelCase     (      self,       A,       A = None      ):





            """simple docstring"""

            if not self.can_save_slow_tokenizer:
                   raise ValueError(
                       '''Your fast tokenizer does not have the necessary information to save the vocabulary for a slow '''
                       '''tokenizer.'''      )

            if not os.path.isdir(A      ):
                   logger.error(F'''Vocabulary path ({save_directory}) should be a directory'''      )
                   return
            _UpperCamelCase              =						os.path.join(
                A,       (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']      )

            if os.path.abspath(self.vocab_file      ) != os.path.abspath(A      ):
                   copyfile(self.vocab_file,       A      )

            return (out_vocab_file,)






