





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_xlnet import XLNetTokenizer
else:
      __UpperCAmelCase	:       Any    	=							None


__UpperCAmelCase	:       Tuple    	=							logging.get_logger(__name__)

__UpperCAmelCase	:       str    	=							{"vocab_file": "spiece.model", "tokenizer_file": "tokenizer.json"}

__UpperCAmelCase	:       Optional[int]    	=							{
    "vocab_file": {
        "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/spiece.model",
        "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/spiece.model",
    },
    "tokenizer_file": {
        "xlnet-base-cased": "https://huggingface.co/xlnet-base-cased/resolve/main/tokenizer.json",
        "xlnet-large-cased": "https://huggingface.co/xlnet-large-cased/resolve/main/tokenizer.json",
    },
}

__UpperCAmelCase	:       Optional[int]    	=							{
    "xlnet-base-cased": None,
    "xlnet-large-cased": None,
}

__UpperCAmelCase	:       Any    	=							"▁"

# Segments (not really needed)
__UpperCAmelCase	:       Optional[Any]    	=							0
__UpperCAmelCase	:       int    	=							1
__UpperCAmelCase	:       Any    	=							2
__UpperCAmelCase	:       Optional[Any]    	=							3
__UpperCAmelCase	:       Union[str, Any]    	=							4







class    __snake_case	(							__lowerCamelCase      ):





       '''simple docstring'''







       lowerCAmelCase__						=					VOCAB_FILES_NAMES
       lowerCAmelCase__						=					PRETRAINED_VOCAB_FILES_MAP
       lowerCAmelCase__						=					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       lowerCAmelCase__						=					"""left"""
       lowerCAmelCase__						=					XLNetTokenizer




       def __init__(  self			:   Tuple							,    A			:   Dict=None							,    A			:   Union[str, Any]=None							,    A			:   Union[str, Any]=False							,    A			:   Any=True							,    A			:   Tuple=False							,    A			:   int="<s>"							,    A			:   str="</s>"							,    A			:   int="<unk>"							,    A			:   Optional[Any]="<sep>"							,    A			:   Dict="<pad>"							,    A			:   Tuple="<cls>"							,    A			:   List[Any]="<mask>"							,    A			:   Any=["<eop>", "<eod>"]							,    **A			:   Optional[int]							,    ):
         # Mask token behave like a normal word, i.e. include the space before it
         __snake_case:						List[Any]			  =						AddedToken(A							,    lstrip=A							,    rstrip=A		) if isinstance(A							,    A		) else mask_token

         super().__init__(
             vocab_file=A							,    tokenizer_file=A							,    do_lower_case=A							,    remove_space=A							,    keep_accents=A							,    bos_token=A							,    eos_token=A							,    unk_token=A							,    sep_token=A							,    pad_token=A							,    cls_token=A							,    mask_token=A							,    additional_special_tokens=A							,    **A							,    )

         __snake_case:						str			  =						3
         __snake_case:						int			  =						do_lower_case
         __snake_case:						Tuple			  =						remove_space
         __snake_case:						Union[str, Any]			  =						keep_accents
         __snake_case:						Optional[Any]			  =						vocab_file
         __snake_case:						Union[str, Any]			  =						False if not self.vocab_file else True




       def 							UpperCAmelCase__			(  self			:   Dict							,    A			:   List[int]							,    A			:   Optional[List[int]] = None		):
         __snake_case:						Optional[int]			  =						[self.sep_token_id]
         __snake_case:						Dict			  =						[self.cls_token_id]
         if token_ids_a is None:
           return token_ids_a + sep + cls
         return token_ids_a + sep + token_ids_a + sep + cls




       def 							UpperCAmelCase__			(  self			:   Optional[Any]							,    A			:   List[int]							,    A			:   Optional[List[int]] = None		):
         __snake_case:						Tuple			  =						[self.sep_token_id]
         __snake_case:						Optional[int]			  =						[2]

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






       def 							UpperCAmelCase__			(  self			:   Any							,    A			:   str							,    A			:   Optional[str] = None		):
         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
         __snake_case:						Any			  =						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,)













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





       '''simple docstring'''







       def __init__(  self			:   str							,    *A			:   Dict							,    A			:   Optional[int]=None							,    A			:   Tuple=None							,    **A			:   Optional[int]		):
         super().__init__(*A							,    **A		)
         __snake_case:						List[Any]			  =						eval_examples
         __snake_case:						str			  =						post_process_function




       def 							UpperCAmelCase__			(  self			:   List[Any]							,    A			:   Dict=None							,    A			:   int=None							,    A			:   List[Any]=None							,    A			:   str = "eval"		):
         __snake_case:						int			  =						self.eval_dataset if eval_dataset is None else eval_dataset
         __snake_case:						Any			  =						self.get_eval_dataloader(A		)
         __snake_case:						Optional[Any]			  =						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:						Union[str, Any]			  =						self.compute_metrics
         __snake_case:						List[str]			  =						None
         __snake_case:						Tuple			  =						self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
         __snake_case:						Tuple			  =						time.time()
         try:
           __snake_case:						Any			  =						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:						Optional[int]			  =						compute_metrics
         __snake_case:						Union[str, 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(
                 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:						List[str]			  =						self.post_process_function(A							,    A							,    output.predictions		)
           __snake_case:						List[Any]			  =						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:						str			  =						metrics.pop(A		)
           metrics.update(output.metrics		)
         else:
           __snake_case:						List[Any]			  =						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:						str			  =						self.callback_handler.on_evaluate(self.args							,    self.state							,    self.control							,    A		)
         return metrics






       def 							UpperCAmelCase__			(  self			:   Optional[Any]							,    A			:   List[Any]							,    A			:   List[str]							,    A			:   str=None							,    A			:   str = "test"		):
         __snake_case:						Optional[Any]			  =						self.get_test_dataloader(A		)

         # Temporarily disable metric computation, we will do it in the loop here.
         __snake_case:						Optional[int]			  =						self.compute_metrics
         __snake_case:						List[Any]			  =						None
         __snake_case:						str			  =						self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
         __snake_case:						Dict			  =						time.time()
         try:
           __snake_case:						str			  =						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:						List[Any]			  =						compute_metrics
         __snake_case:						Dict			  =						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:						Union[str, Any]			  =						self.post_process_function(A							,    A							,    output.predictions							,    """predict"""		)
         __snake_case:						str			  =						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:						List[str]			  =						metrics.pop(A		)
         metrics.update(output.metrics		)
         return PredictionOutput(predictions=predictions.predictions							,    label_ids=predictions.label_ids							,    metrics=A		)






