
'''simple docstring'''

import argparse
import inspect
import logging
from typing import Tuple

import numpy as np
import torch

from transformers import (
    AutoTokenizer,
    BloomForCausalLM,
    BloomTokenizerFast,
    CTRLLMHeadModel,
    CTRLTokenizer,
    GenerationMixin,
    GPTaLMHeadModel,
    GPTaTokenizer,
    GPTJForCausalLM,
    LlamaForCausalLM,
    LlamaTokenizer,
    OpenAIGPTLMHeadModel,
    OpenAIGPTTokenizer,
    OPTForCausalLM,
    TransfoXLLMHeadModel,
    TransfoXLTokenizer,
    XLMTokenizer,
    XLMWithLMHeadModel,
    XLNetLMHeadModel,
    XLNetTokenizer,
)
from transformers.modeling_outputs import CausalLMOutputWithPast


logging.basicConfig(
    format='''%(asctime)s - %(levelname)s - %(name)s - %(message)s''',
    datefmt='''%m/%d/%Y %H:%M:%S''',
    level=logging.INFO,
)
lowerCAmelCase_			:			Optional[int]			   =     logging.getLogger(__name__)

lowerCAmelCase_			:			Optional[Any]			   =     int(10000)  # Hardcoded max length to avoid infinite loop

lowerCAmelCase_			:			Optional[int]			   =     {
    '''gpt2''': (GPTaLMHeadModel, GPTaTokenizer),
    '''ctrl''': (CTRLLMHeadModel, CTRLTokenizer),
    '''openai-gpt''': (OpenAIGPTLMHeadModel, OpenAIGPTTokenizer),
    '''xlnet''': (XLNetLMHeadModel, XLNetTokenizer),
    '''transfo-xl''': (TransfoXLLMHeadModel, TransfoXLTokenizer),
    '''xlm''': (XLMWithLMHeadModel, XLMTokenizer),
    '''gptj''': (GPTJForCausalLM, AutoTokenizer),
    '''bloom''': (BloomForCausalLM, BloomTokenizerFast),
    '''llama''': (LlamaForCausalLM, LlamaTokenizer),
    '''opt''': (OPTForCausalLM, GPTaTokenizer),
}

# Padding text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia
# in https://github.com/rusiaaman/XLNet-gen#methodology
# and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e
lowerCAmelCase_			:			Optional[int]			   =     '''In 1991, the remains of Russian Tsar Nicholas II and his family
(except for Alexei and Maria) are discovered.
The voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the
remainder of the story. 1883 Western Siberia,
a young Grigori Rasputin is asked by his father and a group of men to perform magic.
Rasputin has a vision and denounces one of the men as a horse thief. Although his
father initially slaps him for making such an accusation, Rasputin watches as the
man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous,
with people, even a bishop, begging for his blessing. <eod> </s> <eos>'''







def __A  (    lowerCAmelCase_       ):
     np.random.seed(args.seed       )
     torch.manual_seed(args.seed       )
     if args.n_gpu > 0:
          torch.cuda.manual_seed_all(args.seed       )







def __A  (    lowerCAmelCase_ ,       lowerCAmelCase_ ,       lowerCAmelCase_ ,       lowerCAmelCase_       ):
     if args.temperature > 0.7:
          logger.info("""CTRL typically works better with lower temperatures (and lower top_k)."""       )

     _UpperCAmelCase					:  Dict         =    tokenizer.encode(lowerCAmelCase_ ,       add_special_tokens=lowerCAmelCase_       )
     if not any(encoded_prompt[0] == x for x in tokenizer.control_codes.values()       ):
          logger.info("""WARNING! You are not starting your generation from a control code so you won't get good results"""       )
     return prompt_text







def __A  (    lowerCAmelCase_ ,       lowerCAmelCase_ ,       lowerCAmelCase_ ,       lowerCAmelCase_       ):
     # kwargs = {"language": None, "mask_token_id": None}

     # Set the language
     _UpperCAmelCase					:  str         =    hasattr(model.config ,       """use_lang_emb"""       ) and model.config.use_lang_emb
     if hasattr(model.config ,       """lang2id"""       ) and use_lang_emb:
          _UpperCAmelCase					:  List[Any]         =    model.config.langaid.keys()
          if args.xlm_language in available_languages:
               _UpperCAmelCase					:  List[str]         =    args.xlm_language
          else:
               _UpperCAmelCase					:  Tuple         =    None
               while language not in available_languages:
                    _UpperCAmelCase					:  Union[str, Any]         =    input("""Using XLM. Select language in """ + str(list(lowerCAmelCase_       )       ) + """ >>> """       )

          _UpperCAmelCase					:  int         =    model.config.langaid[language]
          # kwargs["language"] = tokenizer.lang2id[language]

     # TODO fix mask_token_id setup when configurations will be synchronized between models and tokenizers
     # XLM masked-language modeling (MLM) models need masked token
     # is_xlm_mlm = "mlm" in args.model_name_or_path
     # if is_xlm_mlm:
     #     kwargs["mask_token_id"] = tokenizer.mask_token_id

     return prompt_text







def __A  (    lowerCAmelCase_ ,       lowerCAmelCase_ ,       lowerCAmelCase_ ,       lowerCAmelCase_       ):
     _UpperCAmelCase					:  Optional[int]         =    args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
     _UpperCAmelCase					:  str         =    prefix + prompt_text
     return prompt_text







def __A  (    lowerCAmelCase_ ,       lowerCAmelCase_ ,       lowerCAmelCase_ ,       lowerCAmelCase_       ):
     _UpperCAmelCase					:  Any         =    args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
     _UpperCAmelCase					:  int         =    prefix + prompt_text
     return prompt_text


lowerCAmelCase_			:			Union[str, Any]			   =     {
    '''ctrl''': prepare_ctrl_input,
    '''xlm''': prepare_xlm_input,
    '''xlnet''': prepare_xlnet_input,
    '''transfo-xl''': prepare_transfoxl_input,
}







def __A  (    lowerCAmelCase_ ,       lowerCAmelCase_       ):
     if length < 0 and max_sequence_length > 0:
          _UpperCAmelCase					:  str         =    max_sequence_length
     elif 0 < max_sequence_length < length:
          _UpperCAmelCase					:  Dict         =    max_sequence_length  # No generation bigger than model size
     elif length < 0:
          _UpperCAmelCase					:  Dict         =    MAX_LENGTH  # avoid infinite loop
     return length







def __A  (    lowerCAmelCase_       ):
     _UpperCAmelCase					:  Dict         =    None
     if hasattr(lowerCAmelCase_ ,       """hidden_size"""       ):
          _UpperCAmelCase					:  str         =    model_config.hidden_size
     elif hasattr(lowerCAmelCase_ ,       """n_embed"""       ):
          _UpperCAmelCase					:  List[Any]         =    model_config.n_embed
     elif hasattr(lowerCAmelCase_ ,       """n_embd"""       ):
          _UpperCAmelCase					:  Any         =    model_config.n_embd

     _UpperCAmelCase					:  Optional[Any]         =    None
     if hasattr(lowerCAmelCase_ ,       """num_attention_heads"""       ):
          _UpperCAmelCase					:  Union[str, Any]         =    model_config.num_attention_heads
     elif hasattr(lowerCAmelCase_ ,       """n_head"""       ):
          _UpperCAmelCase					:  Any         =    model_config.n_head

     if embedding_size is None or num_head is None or num_head == 0:
          raise ValueError("""Check the model config"""       )

     _UpperCAmelCase					:  Union[str, Any]         =    int(embedding_size / num_head       )
     if hasattr(lowerCAmelCase_ ,       """n_layer"""       ):
          _UpperCAmelCase					:  Union[str, Any]         =    model_config.n_layer
     elif hasattr(lowerCAmelCase_ ,       """num_hidden_layers"""       ):
          _UpperCAmelCase					:  int         =    model_config.num_hidden_layers
     else:
          raise ValueError("""Number of hidden layers couldn't be determined from the model config"""       )

     return num_layer, num_head, num_embedding_size_per_head







def __A  (    lowerCAmelCase_ ,       lowerCAmelCase_ ,       lowerCAmelCase_       ):
     _UpperCAmelCase  ,     _UpperCAmelCase  ,     _UpperCAmelCase					:  Optional[int]         =    sparse_model_config(model.config       )
     if model.config.model_type == "bloom":
          _UpperCAmelCase					:  Union[str, Any]         =    tuple(
              (
                  torch.empty(int(num_attention_heads * batch_size       ) ,       lowerCAmelCase_ ,       lowerCAmelCase_       )
                  .to(model.dtype       )
                  .to(model.device       ),
                  torch.empty(int(num_attention_heads * batch_size       ) ,       lowerCAmelCase_ ,       lowerCAmelCase_       )
                  .to(model.dtype       )
                  .to(model.device       ),
              )
              for _ in range(lowerCAmelCase_       )       )
     else:
          _UpperCAmelCase					:  Any         =    tuple(
              (
                  torch.empty(lowerCAmelCase_ ,       lowerCAmelCase_ ,       lowerCAmelCase_ ,       lowerCAmelCase_       )
                  .to(model.dtype       )
                  .to(model.device       ),
                  torch.empty(lowerCAmelCase_ ,       lowerCAmelCase_ ,       lowerCAmelCase_ ,       lowerCAmelCase_       )
                  .to(model.dtype       )
                  .to(model.device       ),
              )
              for _ in range(lowerCAmelCase_       )       )
     return past_key_values







def __A  (    lowerCAmelCase_ ,       lowerCAmelCase_ ,       lowerCAmelCase_       ):
     _UpperCAmelCase					:  str         =    len(lowerCAmelCase_       )
     _UpperCAmelCase					:  Union[str, Any]         =    tokenizer.batch_encode_plus(lowerCAmelCase_ ,       return_tensors="""pt"""       )
     _UpperCAmelCase					:  Dict         =    dummy_input.to(model.device       )
     if model.config.use_cache:
          _UpperCAmelCase					:  str         =    generate_past_key_values(lowerCAmelCase_ ,       lowerCAmelCase_ ,       1       )
     _UpperCAmelCase					:  Any         =    torch.cat(
         [
             torch.zeros(dummy_input["""attention_mask"""].shape[0] ,       1       )
             .to(dummy_input["""attention_mask"""].dtype       )
             .to(model.device       ),
             dummy_input["""attention_mask"""],
         ] ,       -1 ,       )
     return dummy_input







class 	__lowerCAmelCase    (  __a				):
     snake_case   :    Union[str, Any]							      =      ("""_optimized""", """_default""")



     def __init__(self						,	lowerCAmelCase__						,	lowerCAmelCase__	):
          _UpperCAmelCase					:  Dict         =    optimized
          _UpperCAmelCase					:  int         =    default



     def __call__(self						,	*lowerCAmelCase__						,	**lowerCAmelCase__	):
          if kwargs["past_key_values"] is None and self._default.config.use_cache:
               _UpperCAmelCase					:  Any         =    generate_past_key_values(self._default						,	kwargs["""input_ids"""].shape[0]						,	0	)
          kwargs.pop("""position_ids"""						,	lowerCAmelCase__	)
          for k in list(kwargs.keys()	):
               if kwargs[k] is None or isinstance(kwargs[k]						,	lowerCAmelCase__	):
                    kwargs.pop(lowerCAmelCase__	)
          _UpperCAmelCase					:  Tuple         =    self._optimized(**lowerCAmelCase__	)
          _UpperCAmelCase					:  Optional[Any]         =    outputs[0]
          _UpperCAmelCase					:  int         =    outputs[1]
          _UpperCAmelCase					:  Optional[Any]         =    CausalLMOutputWithPast(
              loss=lowerCAmelCase__						,	logits=lowerCAmelCase__						,	past_key_values=lowerCAmelCase__						,	hidden_states=lowerCAmelCase__						,	attentions=lowerCAmelCase__						,	)
          return fixed_output



     def __getattr__(self						,	lowerCAmelCase__	):
          return getattr(self._default						,	lowerCAmelCase__	)



     def     snake_case_ (self						,	lowerCAmelCase__						,	lowerCAmelCase__=None						,	lowerCAmelCase__=None						,	lowerCAmelCase__=None						,	**lowerCAmelCase__	):
          return self._default.prepare_inputs_for_generation(
              lowerCAmelCase__						,	past_key_values=lowerCAmelCase__						,	inputs_embeds=lowerCAmelCase__						,	use_cache=lowerCAmelCase__						,	**lowerCAmelCase__	)



     def     snake_case_ (self						,	lowerCAmelCase__						,	lowerCAmelCase__	):
          return self._default._reorder_cache(lowerCAmelCase__						,	lowerCAmelCase__	)







def __A  (    ):
     _UpperCAmelCase					:  Dict         =    argparse.ArgumentParser()
     parser.add_argument(
         """--model_type""" ,       default=lowerCAmelCase_ ,       type=lowerCAmelCase_ ,       required=lowerCAmelCase_ ,       help="""Model type selected in the list: """ + """, """.join(MODEL_CLASSES.keys()       ) ,       )
     parser.add_argument(
         """--model_name_or_path""" ,       default=lowerCAmelCase_ ,       type=lowerCAmelCase_ ,       required=lowerCAmelCase_ ,       help="""Path to pre-trained model or shortcut name selected in the list: """ + """, """.join(MODEL_CLASSES.keys()       ) ,       )

     parser.add_argument("""--prompt""" ,       type=lowerCAmelCase_ ,       default=""""""       )
     parser.add_argument("""--length""" ,       type=lowerCAmelCase_ ,       default=20       )
     parser.add_argument("""--stop_token""" ,       type=lowerCAmelCase_ ,       default=lowerCAmelCase_ ,       help="""Token at which text generation is stopped"""       )

     parser.add_argument(
         """--temperature""" ,       type=lowerCAmelCase_ ,       default=1.0 ,       help="""temperature of 1.0 has no effect, lower tend toward greedy sampling""" ,       )
     parser.add_argument(
         """--repetition_penalty""" ,       type=lowerCAmelCase_ ,       default=1.0 ,       help="""primarily useful for CTRL model; in that case, use 1.2"""       )
     parser.add_argument("""--k""" ,       type=lowerCAmelCase_ ,       default=0       )
     parser.add_argument("""--p""" ,       type=lowerCAmelCase_ ,       default=0.9       )

     parser.add_argument("""--prefix""" ,       type=lowerCAmelCase_ ,       default="""""" ,       help="""Text added prior to input."""       )
     parser.add_argument("""--padding_text""" ,       type=lowerCAmelCase_ ,       default="""""" ,       help="""Deprecated, the use of `--prefix` is preferred."""       )
     parser.add_argument("""--xlm_language""" ,       type=lowerCAmelCase_ ,       default="""""" ,       help="""Optional language when used with the XLM model."""       )

     parser.add_argument("""--seed""" ,       type=lowerCAmelCase_ ,       default=42 ,       help="""random seed for initialization"""       )
     parser.add_argument("""--no_cuda""" ,       action="""store_true""" ,       help="""Avoid using CUDA when available"""       )
     parser.add_argument("""--num_return_sequences""" ,       type=lowerCAmelCase_ ,       default=1 ,       help="""The number of samples to generate."""       )
     parser.add_argument(
         """--fp16""" ,       action="""store_true""" ,       help="""Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit""" ,       )
     parser.add_argument("""--jit""" ,       action="""store_true""" ,       help="""Whether or not to use jit trace to accelerate inference"""       )
     _UpperCAmelCase					:  List[str]         =    parser.parse_args()

     _UpperCAmelCase					:  Optional[int]         =    torch.device("""cuda""" if torch.cuda.is_available() and not args.no_cuda else """cpu"""       )
     _UpperCAmelCase					:  int         =    0 if args.no_cuda else torch.cuda.device_count()

     logger.warning(f"device: {args.device}, n_gpu: {args.n_gpu}, 16-bits training: {args.fpaa}"       )

     set_seed(lowerCAmelCase_       )

     # Initialize the model and tokenizer
     try:
          _UpperCAmelCase					:  List[str]         =    args.model_type.lower()
          _UpperCAmelCase  ,     _UpperCAmelCase					:  List[Any]         =    MODEL_CLASSES[args.model_type]
     except KeyError:
          raise KeyError("""the model {} you specified is not supported. You are welcome to add it and open a PR :)"""       )

     _UpperCAmelCase					:  Optional[int]         =    tokenizer_class.from_pretrained(args.model_name_or_path       )
     if tokenizer.pad_token is None:
          _UpperCAmelCase					:  Any         =    tokenizer.eos_token
     _UpperCAmelCase					:  int         =    model_class.from_pretrained(args.model_name_or_path       )
     model.to(args.device       )

     if args.fpaa:
          model.half()
     _UpperCAmelCase					:  Tuple         =    getattr(model.config ,       """max_position_embeddings""" ,       0       )
     _UpperCAmelCase					:  Dict         =    adjust_length_to_model(args.length ,       max_sequence_length=lowerCAmelCase_       )
     logger.info(lowerCAmelCase_       )

     _UpperCAmelCase					:  Dict         =    args.prompt if args.prompt else input("""Model prompt >>> """       )

     # Different models need different input formatting and/or extra arguments
     _UpperCAmelCase					:  Dict         =    args.model_type in PREPROCESSING_FUNCTIONS.keys()
     if requires_preprocessing:
          _UpperCAmelCase					:  Any         =    PREPROCESSING_FUNCTIONS.get(args.model_type       )
          _UpperCAmelCase					:  int         =    prepare_input(lowerCAmelCase_ ,       lowerCAmelCase_ ,       lowerCAmelCase_ ,       lowerCAmelCase_       )

          if model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
               _UpperCAmelCase					:  Union[str, Any]         =    {"""add_space_before_punct_symbol""": True}
          else:
               _UpperCAmelCase					:  Dict         =    {}

          _UpperCAmelCase					:  List[str]         =    tokenizer.encode(
              lowerCAmelCase_ ,       add_special_tokens=lowerCAmelCase_ ,       return_tensors="""pt""" ,       **lowerCAmelCase_       )
     else:
          _UpperCAmelCase					:  Tuple         =    args.prefix if args.prefix else args.padding_text
          _UpperCAmelCase					:  List[str]         =    tokenizer.encode(prefix + prompt_text ,       add_special_tokens=lowerCAmelCase_ ,       return_tensors="""pt"""       )
     _UpperCAmelCase					:  Union[str, Any]         =    encoded_prompt.to(args.device       )

     if encoded_prompt.size()[-1] == 0:
          _UpperCAmelCase					:  Union[str, Any]         =    None
     else:
          _UpperCAmelCase					:  str         =    encoded_prompt

     if args.jit:
          _UpperCAmelCase					:  Union[str, Any]         =    ["""enable jit"""]
          _UpperCAmelCase					:  Tuple         =    prepare_jit_inputs(lowerCAmelCase_ ,       lowerCAmelCase_ ,       lowerCAmelCase_       )
          torch._C._jit_set_texpr_fuser_enabled(lowerCAmelCase_       )
          _UpperCAmelCase					:  str         =    False
          if hasattr(lowerCAmelCase_ ,       """forward"""       ):
               _UpperCAmelCase					:  List[Any]         =    inspect.signature(model.forward       )
          else:
               _UpperCAmelCase					:  Dict         =    inspect.signature(model.__call__       )
          _UpperCAmelCase					:  Tuple         =    tuple(jit_inputs[key] for key in sig.parameters if jit_inputs.get(lowerCAmelCase_ ,       lowerCAmelCase_       ) is not None       )
          _UpperCAmelCase					:  Union[str, Any]         =    torch.jit.trace(lowerCAmelCase_ ,       lowerCAmelCase_ ,       strict=lowerCAmelCase_       )
          _UpperCAmelCase					:  List[str]         =    torch.jit.freeze(traced_model.eval()       )
          traced_model(*lowerCAmelCase_       )
          traced_model(*lowerCAmelCase_       )

          _UpperCAmelCase					:  List[str]         =    _ModelFallbackWrapper(lowerCAmelCase_ ,       lowerCAmelCase_       )

     _UpperCAmelCase					:  List[str]         =    model.generate(
         input_ids=lowerCAmelCase_ ,       max_length=args.length + len(encoded_prompt[0]       ) ,       temperature=args.temperature ,       top_k=args.k ,       top_p=args.p ,       repetition_penalty=args.repetition_penalty ,       do_sample=lowerCAmelCase_ ,       num_return_sequences=args.num_return_sequences ,       )

     # Remove the batch dimension when returning multiple sequences
     if len(output_sequences.shape       ) > 2:
          output_sequences.squeeze_()

     _UpperCAmelCase					:  Optional[int]         =    []

     for generated_sequence_idx, generated_sequence in enumerate(lowerCAmelCase_       ):
          print(f"=== GENERATED SEQUENCE {generated_sequence_idx + 1} ==="       )
          _UpperCAmelCase					:  str         =    generated_sequence.tolist()

          # Decode text
          _UpperCAmelCase					:  Tuple         =    tokenizer.decode(lowerCAmelCase_ ,       clean_up_tokenization_spaces=lowerCAmelCase_       )

          # Remove all text after the stop token
          _UpperCAmelCase					:  Tuple         =    text[: text.find(args.stop_token       ) if args.stop_token else None]

          # Add the prompt at the beginning of the sequence. Remove the excess text that was used for pre-processing
          _UpperCAmelCase					:  List[Any]         =    (
              prompt_text + text[len(tokenizer.decode(encoded_prompt[0] ,       clean_up_tokenization_spaces=lowerCAmelCase_       )       ) :]
          )

          generated_sequences.append(lowerCAmelCase_       )
          print(lowerCAmelCase_       )

     return generated_sequences


if __name__ == "__main__":
   main()




'''simple docstring'''

import concurrent.futures
import json
import os
import shutil
import tempfile
import unittest

from transformers import AutoTokenizer, PreTrainedTokenizerFast
from transformers.testing_utils import require_tokenizers

from ..test_tokenization_common import TokenizerTesterMixin







@require_tokenizers
class 	__lowerCAmelCase    (  __a       ,					unittest.TestCase				):
     snake_case   :    Dict							      =      PreTrainedTokenizerFast
     snake_case   :    Optional[Any]							      =      False
     snake_case   :    List[str]							      =      True
     snake_case   :    Any							      =      """tokenizer_file"""



     def     snake_case_ (self	):
          _UpperCAmelCase					:  Dict         =    False  # because we don't have pretrained_vocab_files_map
          super().setUp()
          _UpperCAmelCase					:  Optional[Any]         =    True

          _UpperCAmelCase					:  int         =    ["""robot-test/dummy-tokenizer-fast""", """robot-test/dummy-tokenizer-wordlevel"""]
          _UpperCAmelCase					:  Union[str, Any]         =    """SaulLu/dummy-tokenizer-bytelevel-bpe"""

          # Inclusion of 2 tokenizers to test different types of models (Unigram and WordLevel for the moment)
          _UpperCAmelCase					:  List[str]         =    [(PreTrainedTokenizerFast, model_path, {}) for model_path in model_paths]

          _UpperCAmelCase					:  Optional[Any]         =    PreTrainedTokenizerFast.from_pretrained(model_paths[0]	)
          tokenizer.save_pretrained(self.tmpdirname	)



     def     snake_case_ (self	):
          # We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
          # model
          pass



     def     snake_case_ (self	):
          # We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
          # model
          pass



     def     snake_case_ (self	):
          # We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
          # model
          pass



     def     snake_case_ (self	):
          # PreTrainedTokenizerFast doesn't have tokenizer_file in its signature
          pass



     def     snake_case_ (self	):
          _UpperCAmelCase					:  Optional[Any]         =    self.tmpdirname
          # Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
          for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
               with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})"	):
                    try:
                         _UpperCAmelCase					:  Optional[int]         =    tempfile.mkdtemp()
                         _UpperCAmelCase					:  Tuple         =    self.rust_tokenizer_class.from_pretrained(lowerCAmelCase__						,	**lowerCAmelCase__	)

                         tokenizer.save_pretrained(self.tmpdirname	)
                         super().test_training_new_tokenizer()
                    finally:
                         # Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
                         # is restored
                         shutil.rmtree(self.tmpdirname	)
                         _UpperCAmelCase					:  Optional[int]         =    tmpdirname_orig



     def     snake_case_ (self	):
          _UpperCAmelCase					:  int         =    self.tmpdirname
          # Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel.
          for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
               with self.subTest(F"{tokenizer.__class__.__name__} ({pretrained_name})"	):
                    try:
                         _UpperCAmelCase					:  Any         =    tempfile.mkdtemp()
                         _UpperCAmelCase					:  Union[str, Any]         =    self.rust_tokenizer_class.from_pretrained(lowerCAmelCase__						,	**lowerCAmelCase__	)

                         tokenizer.save_pretrained(self.tmpdirname	)
                         super().test_training_new_tokenizer_with_special_tokens_change()
                    finally:
                         # Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer
                         # is restored
                         shutil.rmtree(self.tmpdirname	)
                         _UpperCAmelCase					:  Dict         =    tmpdirname_orig



     def     snake_case_ (self	):
          _UpperCAmelCase					:  List[Any]         =    self.rust_tokenizer_class.from_pretrained(self.bytelevel_bpe_model_name	)

          _UpperCAmelCase					:  Dict         =    ("""a""" for _ in range(1_0_0_0	))
          _UpperCAmelCase					:  Optional[int]         =    tokenizer.train_new_from_iterator(text_iterator=lowerCAmelCase__						,	length=1_0_0_0						,	vocab_size=5_0	)

          _UpperCAmelCase					:  int         =    new_tokenizer.encode("""a🤗"""	)
          self.assertEqual(lowerCAmelCase__						,	[6_4, 1_7_2, 2_5_3, 9_7, 2_4_5]	)







@require_tokenizers
class 	__lowerCAmelCase    (  unittest.TestCase				):



     def     snake_case_ (self	):
          _UpperCAmelCase					:  Any         =    AutoTokenizer.from_pretrained("""bert-base-cased"""	)
          _UpperCAmelCase					:  Dict         =    json.loads(tokenizer._tokenizer.to_str()	)
          _UpperCAmelCase					:  List[Any]         =    len(lowerCAmelCase__	)

          with tempfile.TemporaryDirectory() as tmp_dir:
               # Hack to save this in the tokenizer_config.json
               _UpperCAmelCase					:  Union[str, Any]         =    ["""tokenizer.4.0.0.json"""]
               tokenizer.save_pretrained(lowerCAmelCase__	)
               json.dump(lowerCAmelCase__						,	open(os.path.join(lowerCAmelCase__						,	"""tokenizer.4.0.0.json"""	)						,	"""w"""	)	)

               # This should pick the new tokenizer file as the version of Transformers is > 4.0.0
               _UpperCAmelCase					:  Optional[int]         =    AutoTokenizer.from_pretrained(lowerCAmelCase__	)
               self.assertEqual(len(lowerCAmelCase__	)						,	len(lowerCAmelCase__	) + 1	)
               _UpperCAmelCase					:  Tuple         =    json.loads(new_tokenizer._tokenizer.to_str()	)
               self.assertIn("""huggingface"""						,	json_tokenizer["""model"""]["""vocab"""]	)

               # Will need to be adjusted if we reach v42 and this test is still here.
               # Should pick the old tokenizer file as the version of Transformers is < 4.0.0
               shutil.move(os.path.join(lowerCAmelCase__						,	"""tokenizer.4.0.0.json"""	)						,	os.path.join(lowerCAmelCase__						,	"""tokenizer.42.0.0.json"""	)	)
               _UpperCAmelCase					:  Tuple         =    ["""tokenizer.42.0.0.json"""]
               tokenizer.save_pretrained(lowerCAmelCase__	)
               _UpperCAmelCase					:  str         =    AutoTokenizer.from_pretrained(lowerCAmelCase__	)
               self.assertEqual(len(lowerCAmelCase__	)						,	len(lowerCAmelCase__	)	)
               _UpperCAmelCase					:  Union[str, Any]         =    json.loads(new_tokenizer._tokenizer.to_str()	)
               self.assertNotIn("""huggingface"""						,	json_tokenizer["""model"""]["""vocab"""]	)



     def     snake_case_ (self	):
          # This repo has two tokenizer files, one for v4.0.0 and above with an added token, one for versions lower.
          _UpperCAmelCase					:  List[Any]         =    """hf-internal-testing/test-two-tokenizers"""

          # This should pick the new tokenizer file as the version of Transformers is > 4.0.0
          _UpperCAmelCase					:  Dict         =    AutoTokenizer.from_pretrained(lowerCAmelCase__	)
          self.assertEqual(len(lowerCAmelCase__	)						,	2_8_9_9_7	)
          _UpperCAmelCase					:  List[str]         =    json.loads(tokenizer._tokenizer.to_str()	)
          self.assertIn("""huggingface"""						,	json_tokenizer["""model"""]["""vocab"""]	)

          # Testing an older version by monkey-patching the version in the module it's used.
          import transformers as old_transformers

          _UpperCAmelCase					:  Optional[Any]         =    """3.0.0"""
          _UpperCAmelCase					:  str         =    old_transformers.models.auto.AutoTokenizer.from_pretrained(lowerCAmelCase__	)
          self.assertEqual(len(lowerCAmelCase__	)						,	2_8_9_9_6	)
          _UpperCAmelCase					:  Optional[int]         =    json.loads(old_tokenizer._tokenizer.to_str()	)
          self.assertNotIn("""huggingface"""						,	json_tokenizer["""model"""]["""vocab"""]	)







@require_tokenizers
class 	__lowerCAmelCase    (  unittest.TestCase				):



     def     snake_case_ (self	):
          # See https://github.com/huggingface/transformers/pull/12550
          # and https://github.com/huggingface/tokenizers/issues/537
          _UpperCAmelCase					:  int         =    PreTrainedTokenizerFast.from_pretrained("""robot-test/dummy-tokenizer-wordlevel"""	)
          _UpperCAmelCase					:  str         =    """The Matrix is a 1999 science fiction action film."""

          with concurrent.futures.ThreadPoolExecutor() as executor:
               _UpperCAmelCase					:  List[Any]         =    [executor.submit(self.fetch						,	lowerCAmelCase__						,	lowerCAmelCase__	) for i in range(1_0	)]
               _UpperCAmelCase					:  Any         =    [future.result() for future in futures]
               self.assertEqual(lowerCAmelCase__						,	[[1, 1_0, 0, 8, 0, 1_8, 0, 0, 0, 2] for i in range(1_0	)]	)



     def     snake_case_ (self						,	lowerCAmelCase__						,	lowerCAmelCase__	):
          return tokenizer.encode(lowerCAmelCase__						,	truncation="""longest_first"""						,	padding="""longest"""	)


