
"""simple docstring"""




import dataclasses
import json
import warnings
from dataclasses import dataclass, field
from time import time
from typing import List

from ..utils import logging


A__   :					Optional[Any]							=   logging.get_logger(__name__)




def  _lowerCAmelCase		(		_UpperCamelCase=None ,				_UpperCamelCase=None						):






  """simple docstring"""



  return field(default_factory=lambda: default ,				metadata=_UpperCamelCase						)







@dataclass
class 			__magic_name__       :
       UpperCamelCase_   =		list_field(
           default=[]   ,					metadata={
               '''help''': (
                   '''Model checkpoints to be provided to the AutoModel classes. Leave blank to benchmark the base version'''
                   ''' of all available models'''
               )
           }   ,					)

       UpperCamelCase_   =		list_field(
           default=[8]   ,					metadata={'''help''': '''List of batch sizes for which memory and time performance will be evaluated'''} )

       UpperCamelCase_   =		list_field(
           default=[8, 32, 128, 512]   ,					metadata={'''help''': '''List of sequence lengths for which memory and time performance will be evaluated'''}   ,					)

       UpperCamelCase_   =		field(
           default=SCREAMING_SNAKE_CASE__   ,					metadata={'''help''': '''Whether to benchmark inference of model. Inference can be disabled via --no-inference.'''}   ,					)
       UpperCamelCase_   =		field(
           default=SCREAMING_SNAKE_CASE__   ,					metadata={'''help''': '''Whether to run on available cuda devices. Cuda can be disabled via --no-cuda.'''}   ,					)
       UpperCamelCase_   =		field(
           default=SCREAMING_SNAKE_CASE__   ,					metadata={'''help''': '''Whether to run on available tpu devices. TPU can be disabled via --no-tpu.'''} )
       UpperCamelCase_   =		field(default=SCREAMING_SNAKE_CASE__   ,					metadata={'''help''': '''Use FP16 to accelerate inference.'''} )
       UpperCamelCase_   =		field(default=SCREAMING_SNAKE_CASE__   ,					metadata={'''help''': '''Benchmark training of model'''} )
       UpperCamelCase_   =		field(default=SCREAMING_SNAKE_CASE__   ,					metadata={'''help''': '''Verbose memory tracing'''} )
       UpperCamelCase_   =		field(
           default=SCREAMING_SNAKE_CASE__   ,					metadata={'''help''': '''Whether to perform speed measurements. Speed measurements can be disabled via --no-speed.'''}   ,					)
       UpperCamelCase_   =		field(
           default=SCREAMING_SNAKE_CASE__   ,					metadata={
               '''help''': '''Whether to perform memory measurements. Memory measurements can be disabled via --no-memory'''
           }   ,					)
       UpperCamelCase_   =		field(default=SCREAMING_SNAKE_CASE__   ,					metadata={'''help''': '''Trace memory line by line'''} )
       UpperCamelCase_   =		field(default=SCREAMING_SNAKE_CASE__   ,					metadata={'''help''': '''Save result to a CSV file'''} )
       UpperCamelCase_   =		field(default=SCREAMING_SNAKE_CASE__   ,					metadata={'''help''': '''Save all print statements in a log file'''} )
       UpperCamelCase_   =		field(default=SCREAMING_SNAKE_CASE__   ,					metadata={'''help''': '''Whether to print environment information'''} )
       UpperCamelCase_   =		field(
           default=SCREAMING_SNAKE_CASE__   ,					metadata={
               '''help''': (
                   '''Whether to use multiprocessing for memory and speed measurement. It is highly recommended to use'''
                   ''' multiprocessing for accurate CPU and GPU memory measurements. This option should only be disabled'''
                   ''' for debugging / testing and on TPU.'''
               )
           }   ,					)
       UpperCamelCase_   =		field(
           default=F'inference_time_{round(time() )}.csv'   ,					metadata={'''help''': '''CSV filename used if saving time results to csv.'''}   ,					)
       UpperCamelCase_   =		field(
           default=F'inference_memory_{round(time() )}.csv'   ,					metadata={'''help''': '''CSV filename used if saving memory results to csv.'''}   ,					)
       UpperCamelCase_   =		field(
           default=F'train_time_{round(time() )}.csv'   ,					metadata={'''help''': '''CSV filename used if saving time results to csv for training.'''}   ,					)
       UpperCamelCase_   =		field(
           default=F'train_memory_{round(time() )}.csv'   ,					metadata={'''help''': '''CSV filename used if saving memory results to csv for training.'''}   ,					)
       UpperCamelCase_   =		field(
           default=F'env_info_{round(time() )}.csv'   ,					metadata={'''help''': '''CSV filename used if saving environment information.'''}   ,					)
       UpperCamelCase_   =		field(
           default=F'log_{round(time() )}.csv'   ,					metadata={'''help''': '''Log filename used if print statements are saved in log.'''}   ,					)
       UpperCamelCase_   =		field(default=3   ,					metadata={'''help''': '''Times an experiment will be run.'''} )
       UpperCamelCase_   =		field(
           default=SCREAMING_SNAKE_CASE__   ,					metadata={
               '''help''': (
                   '''Instead of loading the model as defined in `config.architectures` if exists, just load the pretrain'''
                   ''' model weights.'''
               )
           }   ,					)
       def 							lowercase_							(     self       )     ->	str:





         """simple docstring"""




         warnings.warn(
             f'''The class {self.__class__} is deprecated. Hugging Face Benchmarking utils'''
             ''' are deprecated in general and it is advised to use external Benchmarking libraries '''
             ''' to benchmark Transformer models.''' ,				A_ ,				)
       def 							lowercase_							(     self       )     ->	Any:





         """simple docstring"""




         return json.dumps(dataclasses.asdict(self       ) ,				indent=2       )
       @property
       def 							lowercase_							(     self       )     ->	List[str]:





         """simple docstring"""




         if len(self.models       ) <= 0:
           raise ValueError(
               '''Please make sure you provide at least one model name / model identifier, *e.g.* `--models'''
               ''' bert-base-cased` or `args.models = [\'bert-base-cased\'].'''       )
         return self.models



       @property
       def 							lowercase_							(     self       )     ->	Dict:





         """simple docstring"""




         if not self.multi_process:
           return False
         elif self.is_tpu:
           logger.info('''Multiprocessing is currently not possible on TPU.'''       )
           return False
         else:
           return True


"""simple docstring"""




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

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


A__   :					str							=   logging.get_logger(__name__)

A__   :					Tuple							=   {
    'vocab_file': 'vocab.txt',
    'merges_file': 'bpe.codes',
}

A__   :					List[Any]							=   {
    'vocab_file': {
        'vinai/phobert-base': 'https://huggingface.co/vinai/phobert-base/resolve/main/vocab.txt',
        'vinai/phobert-large': 'https://huggingface.co/vinai/phobert-large/resolve/main/vocab.txt',
    },
    'merges_file': {
        'vinai/phobert-base': 'https://huggingface.co/vinai/phobert-base/resolve/main/bpe.codes',
        'vinai/phobert-large': 'https://huggingface.co/vinai/phobert-large/resolve/main/bpe.codes',
    },
}

A__   :					Any							=   {
    'vinai/phobert-base': 2_5_6,
    'vinai/phobert-large': 2_5_6,
}




def  _lowerCAmelCase		(		_UpperCamelCase						):






  """simple docstring"""



  _lowercase:			Optional[int]       =     set()
  _lowercase:			Union[str, Any]       =     word[0]
  for char in word[1:]:
    pairs.add((prev_char, char)						)
    _lowercase:			Tuple       =     char

  _lowercase:			Optional[Any]       =     set(_UpperCamelCase						)
  return pairs







class 			__magic_name__       (       SCREAMING_SNAKE_CASE__ ):
       UpperCamelCase_   =		VOCAB_FILES_NAMES
       UpperCamelCase_   =		PRETRAINED_VOCAB_FILES_MAP
       UpperCamelCase_   =		PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       def __init__(     self ,				A_ ,				A_ ,				A_="<s>" ,				A_="</s>" ,				A_="</s>" ,				A_="<s>" ,				A_="<unk>" ,				A_="<pad>" ,				A_="<mask>" ,				**A_ ,				)     ->	Dict:





         """simple docstring"""




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

         _lowercase:			List[Any]       =     vocab_file
         _lowercase:			Union[str, Any]       =     merges_file

         _lowercase:			int       =     {}
         _lowercase:			Optional[int]       =     0
         _lowercase:			Optional[Any]       =     1
         _lowercase:			List[str]       =     2
         _lowercase:			List[Any]       =     3

         self.add_from_file(A_       )

         _lowercase:			Tuple       =     {v: k for k, v in self.encoder.items()}

         with open(A_ ,				encoding='''utf-8'''       ) as merges_handle:
           _lowercase:			int       =     merges_handle.read().split('''\n'''       )[:-1]
         _lowercase:			Optional[int]       =     [tuple(merge.split()[:-1]       ) for merge in merges]
         _lowercase:			List[str]       =     dict(zip(A_ ,				range(len(A_       )       )       )       )
         _lowercase:			Union[str, Any]       =     {}
       def 							lowercase_							(     self ,				A_ ,				A_ = None       )     ->	List[int]:





         """simple docstring"""




         if token_ids_a is None:
           return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
         _lowercase:			Optional[Any]       =     [self.cls_token_id]
         _lowercase:			Tuple       =     [self.sep_token_id]
         return cls + token_ids_a + sep + sep + token_ids_a + sep
       def 							lowercase_							(     self ,				A_ ,				A_ = None ,				A_ = False       )     ->	List[int]:





         """simple docstring"""




         if already_has_special_tokens:
           return super().get_special_tokens_mask(
               token_ids_a=A_ ,				token_ids_a=A_ ,				already_has_special_tokens=A_       )

         if token_ids_a is None:
           return [1] + ([0] * len(A_       )) + [1]
         return [1] + ([0] * len(A_       )) + [1, 1] + ([0] * len(A_       )) + [1]
       def 							lowercase_							(     self ,				A_ ,				A_ = None       )     ->	List[int]:





         """simple docstring"""




         _lowercase:			Tuple       =     [self.sep_token_id]
         _lowercase:			List[Any]       =     [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 + sep + token_ids_a + sep       ) * [0]
       @property
       def 							lowercase_							(     self       )     ->	int:





         """simple docstring"""




         return len(self.encoder       )
       def 							lowercase_							(     self       )     ->	int:





         """simple docstring"""




         return dict(self.encoder ,				**self.added_tokens_encoder       )
       def 							lowercase_							(     self ,				A_       )     ->	Optional[Any]:





         """simple docstring"""




         if token in self.cache:
           return self.cache[token]
         _lowercase:			List[Any]       =     tuple(A_       )
         _lowercase:			Tuple       =     tuple(list(word[:-1]       ) + [word[-1] + '''</w>''']       )
         _lowercase:			List[Any]       =     get_pairs(A_       )

         if not pairs:
           return token

         while True:
           _lowercase:			List[str]       =     min(A_ ,				key=lambda A_       : self.bpe_ranks.get(A_ ,				float('''inf'''       )       )       )
           if bigram not in self.bpe_ranks:
             break
           _lowercase ,				_lowercase:			Optional[int]       =     bigram
           _lowercase:			Tuple       =     []
           _lowercase:			List[str]       =     0
           while i < len(A_       ):
             try:
               _lowercase:			Tuple       =     word.index(A_ ,				A_       )
             except ValueError:
               new_word.extend(word[i:]       )
               break
             else:
               new_word.extend(word[i:j]       )
               _lowercase:			List[Any]       =     j

             if word[i] == first and i < len(A_       ) - 1 and word[i + 1] == second:
               new_word.append(first + second       )
               i += 2
             else:
               new_word.append(word[i]       )
               i += 1
           _lowercase:			Union[str, Any]       =     tuple(A_       )
           _lowercase:			int       =     new_word
           if len(A_       ) == 1:
             break
           else:
             _lowercase:			List[Any]       =     get_pairs(A_       )
         _lowercase:			Tuple       =     '''@@ '''.join(A_       )
         _lowercase:			Dict       =     word[:-4]
         _lowercase:			Tuple       =     word
         return word
       def 							lowercase_							(     self ,				A_       )     ->	List[Any]:





         """simple docstring"""




         _lowercase:			Dict       =     []

         _lowercase:			str       =     re.findall(R'''\S+\n?''' ,				A_       )

         for token in words:
           split_tokens.extend(list(self.bpe(A_       ).split(''' '''       )       )       )
         return split_tokens
       def 							lowercase_							(     self ,				A_       )     ->	List[str]:





         """simple docstring"""




         return self.encoder.get(A_ ,				self.encoder.get(self.unk_token       )       )
       def 							lowercase_							(     self ,				A_       )     ->	Tuple:





         """simple docstring"""




         return self.decoder.get(A_ ,				self.unk_token       )
       def 							lowercase_							(     self ,				A_       )     ->	Union[str, Any]:





         """simple docstring"""




         _lowercase:			Union[str, Any]       =     ''' '''.join(A_       ).replace('''@@ ''' ,				''''''       ).strip()
         return out_string
       def 							lowercase_							(     self ,				A_ ,				A_ = None       )     ->	Tuple[str]:





         """simple docstring"""




         if not os.path.isdir(A_       ):
           logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''       )
           return
         _lowercase:			List[Any]       =     os.path.join(
             A_ ,				(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']       )
         _lowercase:			str       =     os.path.join(
             A_ ,				(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file''']       )

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

         if os.path.abspath(self.merges_file       ) != os.path.abspath(A_       ):
           copyfile(self.merges_file ,				A_       )

         return out_vocab_file, out_merge_file



       def 							lowercase_							(     self ,				A_       )     ->	str:





         """simple docstring"""




         if isinstance(A_ ,				A_       ):
           try:
             with open(A_ ,				'''r''' ,				encoding='''utf-8'''       ) as fd:
               self.add_from_file(A_       )
           except FileNotFoundError as fnfe:
             raise fnfe
           except UnicodeError:
             raise Exception(f'''Incorrect encoding detected in {f}, please rebuild the dataset'''       )
           return

         _lowercase:			Dict       =     f.readlines()
         for lineTmp in lines:
           _lowercase:			List[Any]       =     lineTmp.strip()
           _lowercase:			Optional[Any]       =     line.rfind(''' '''       )
           if idx == -1:
             raise ValueError('''Incorrect dictionary format, expected \'<token> <cnt>\''''       )
           _lowercase:			List[str]       =     line[:idx]
           _lowercase:			List[str]       =     len(self.encoder       )
