





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

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


__UpperCAmelCase	:       Optional[int]    	=							logging.get_logger(__name__)

__UpperCAmelCase	:       Any    	=							{"vocab_file": "spiece.model"}

__UpperCAmelCase	:       Optional[Any]    	=							{
    "vocab_file": {
        "bert_for_seq_generation": (
            "https://huggingface.co/google/bert_for_seq_generation_L-24_bbc_encoder/resolve/main/spiece.model"
        ),
    }
}

__UpperCAmelCase	:       str    	=							{"bert_for_seq_generation": 512}







class    __snake_case	(							__lowerCamelCase      ):





       '''simple docstring'''







       lowerCAmelCase__						=					VOCAB_FILES_NAMES
       lowerCAmelCase__						=					PRETRAINED_VOCAB_FILES_MAP
       lowerCAmelCase__						=					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       lowerCAmelCase__						=					[]
       lowerCAmelCase__						=					["""input_ids""", """attention_mask"""]




       def __init__(  self			:   int							,    A			:   Any							,    A			:   Tuple="<s>"							,    A			:   Dict="</s>"							,    A			:   List[Any]="<unk>"							,    A			:   int="<pad>"							,    A			:   List[str]="<::::>"							,    A			:   Optional[Dict[str, Any]] = None							,    **A			:   Union[str, Any]							,    ):
         __snake_case:						Optional[int]			  =						{} if sp_model_kwargs is None else sp_model_kwargs

         # Add extra_ids to the special token list
         super().__init__(
             bos_token=A							,    eos_token=A							,    unk_token=A							,    pad_token=A							,    sep_token=A							,    sp_model_kwargs=self.sp_model_kwargs							,    **A							,    )

         __snake_case:						Any			  =						vocab_file

         __snake_case:						List[str]			  =						spm.SentencePieceProcessor(**self.sp_model_kwargs		)
         self.sp_model.Load(A		)




       @property
       def 							UpperCAmelCase__			(  self			:   Union[str, Any]		):
         return self.sp_model.get_piece_size()




       def 							UpperCAmelCase__			(  self			:   Union[str, Any]		):
         __snake_case:						int			  =						{self.convert_ids_to_tokens(A		): i for i in range(self.vocab_size		)}
         vocab.update(self.added_tokens_encoder		)
         return vocab




       def __getstate__(  self			:   Optional[Any]		):
         __snake_case:						int			  =						self.__dict__.copy()
         __snake_case:						Tuple			  =						None
         return state




       def __setstate__(  self			:   Union[str, Any]							,    A			:   List[Any]		):
         __snake_case:						List[str]			  =						d

         # for backward compatibility
         if not hasattr(self							,    """sp_model_kwargs"""		):
           __snake_case:						int			  =						{}

         __snake_case:						Any			  =						spm.SentencePieceProcessor(**self.sp_model_kwargs		)
         self.sp_model.Load(self.vocab_file		)




       def 							UpperCAmelCase__			(  self			:   List[str]							,    A			:   str		):
         return self.sp_model.encode(A							,    out_type=A		)




       def 							UpperCAmelCase__			(  self			:   List[str]							,    A			:   Optional[Any]		):
         return self.sp_model.piece_to_id(A		)




       def 							UpperCAmelCase__			(  self			:   Optional[int]							,    A			:   Union[str, Any]		):
         __snake_case:						Optional[Any]			  =						self.sp_model.IdToPiece(A		)
         return token




       def 							UpperCAmelCase__			(  self			:   Optional[Any]							,    A			:   List[Any]		):
         __snake_case:						str			  =						[]
         __snake_case:						Optional[Any]			  =						""""""
         for token in tokens:
           # make sure that special tokens are not decoded using sentencepiece model
           if token in self.all_special_tokens:
             out_string += self.sp_model.decode(A		) + token
             __snake_case:						List[Any]			  =						[]
           else:
             current_sub_tokens.append(A		)
         out_string += self.sp_model.decode(A		)
         return out_string.strip()






       def 							UpperCAmelCase__			(  self			:   List[Any]							,    A			:   str							,    A			:   Optional[str] = None		):
         if not os.path.isdir(A		):
           logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''		)
           return
         __snake_case:						List[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		) and os.path.isfile(self.vocab_file		):
           copyfile(self.vocab_file							,    A		)
         elif not os.path.isfile(self.vocab_file		):
           with open(A							,    """wb"""		) as fi:
             __snake_case:						Union[str, Any]			  =						self.sp_model.serialized_model_proto()
             fi.write(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		)






