



from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCAmelCase_          =				logging.get_logger(__name__)

UpperCAmelCase_          =				{
    "google/reformer-crime-and-punishment": (
        "https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/config.json"
    ),
    "google/reformer-enwik8": "https://huggingface.co/google/reformer-enwik8/resolve/main/config.json",
}





class 		UpperCAmelCase    (    snake_case_					):
   SCREAMING_SNAKE_CASE__					      =  '''reformer'''
   SCREAMING_SNAKE_CASE__					      =  ['''past_buckets_states''']
   SCREAMING_SNAKE_CASE__					      =  {}





   def __init__(						self							,  _lowerCAmelCase=64							,  _lowerCAmelCase=["local", "lsh", "local", "lsh", "local", "lsh"]							,  _lowerCAmelCase=1.0							,  _lowerCAmelCase=True							,  _lowerCAmelCase=[64, 64]							,  _lowerCAmelCase=[64, 192]							,  _lowerCAmelCase=0							,  _lowerCAmelCase=2							,  _lowerCAmelCase=512							,  _lowerCAmelCase=None							,  _lowerCAmelCase="relu"							,  _lowerCAmelCase=0.05							,  _lowerCAmelCase=256							,  _lowerCAmelCase=0.02							,  _lowerCAmelCase=False							,  _lowerCAmelCase=1E-12							,  _lowerCAmelCase=1							,  _lowerCAmelCase=0							,  _lowerCAmelCase=0.05							,  _lowerCAmelCase=64							,  _lowerCAmelCase=64							,  _lowerCAmelCase=0.0							,  _lowerCAmelCase=1							,  _lowerCAmelCase=0							,  _lowerCAmelCase=4_096							,  _lowerCAmelCase=12							,  _lowerCAmelCase=None							,  _lowerCAmelCase=1							,  _lowerCAmelCase=0							,  _lowerCAmelCase=320							,  _lowerCAmelCase=False							,  _lowerCAmelCase=True							,  _lowerCAmelCase=None							,  **_lowerCAmelCase							,  ):
         _lowerCAmelCase			      =	hash_seed
         _lowerCAmelCase			      =	vocab_size
         _lowerCAmelCase			      =	attention_head_size
         _lowerCAmelCase			      =	hidden_size
         _lowerCAmelCase			      =	num_attention_heads
         _lowerCAmelCase			      =	num_hashes
         _lowerCAmelCase			      =	len(_lowerCAmelCase      )
         _lowerCAmelCase			      =	tuple(_lowerCAmelCase      ) if isinstance(_lowerCAmelCase							,  _lowerCAmelCase      ) else num_buckets
         _lowerCAmelCase			      =	lsh_attn_chunk_length
         _lowerCAmelCase			      =	local_attn_chunk_length
         _lowerCAmelCase			      =	lsh_num_chunks_after
         _lowerCAmelCase			      =	lsh_num_chunks_before
         _lowerCAmelCase			      =	local_num_chunks_after
         _lowerCAmelCase			      =	local_num_chunks_before
         _lowerCAmelCase			      =	hidden_act
         _lowerCAmelCase			      =	feed_forward_size
         _lowerCAmelCase			      =	hidden_dropout_prob
         _lowerCAmelCase			      =	lsh_attention_probs_dropout_prob
         _lowerCAmelCase			      =	local_attention_probs_dropout_prob
         _lowerCAmelCase			      =	max_position_embeddings
         _lowerCAmelCase			      =	initializer_range
         _lowerCAmelCase			      =	layer_norm_eps
         _lowerCAmelCase			      =	axial_pos_embds
         _lowerCAmelCase			      =	tuple(_lowerCAmelCase      )
         _lowerCAmelCase			      =	tuple(_lowerCAmelCase      )
         _lowerCAmelCase			      =	axial_norm_std
         _lowerCAmelCase			      =	chunk_size_lm_head
         _lowerCAmelCase			      =	attn_layers
         _lowerCAmelCase			      =	use_cache
         _lowerCAmelCase			      =	classifier_dropout
         super().__init__(
             pad_token_id=_lowerCAmelCase							,  eos_token_id=_lowerCAmelCase							,  is_decoder=_lowerCAmelCase							,  tie_word_embeddings=_lowerCAmelCase							,  **_lowerCAmelCase							,  )




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 		UpperCAmelCase    (    snake_case_							,unittest.TestCase					):
   SCREAMING_SNAKE_CASE__					      =  PreTrainedTokenizerFast
   SCREAMING_SNAKE_CASE__					      =  False
   SCREAMING_SNAKE_CASE__					      =  True
   SCREAMING_SNAKE_CASE__					      =  '''tokenizer_file'''





   def 						__lowerCAmelCase				(						self      ):
         _lowerCAmelCase			      =	False  # because we don't have pretrained_vocab_files_map
         super().setUp()
         _lowerCAmelCase			      =	True

         _lowerCAmelCase			      =	['''robot-test/dummy-tokenizer-fast''', '''robot-test/dummy-tokenizer-wordlevel''']
         _lowerCAmelCase			      =	'''SaulLu/dummy-tokenizer-bytelevel-bpe'''

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

         _lowerCAmelCase			      =	PreTrainedTokenizerFast.from_pretrained(model_paths[0]      )
         tokenizer.save_pretrained(self.tmpdirname      )





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





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





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





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





   def 						__lowerCAmelCase				(						self      ):
         _lowerCAmelCase			      =	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:
                           _lowerCAmelCase			      =	tempfile.mkdtemp()
                           _lowerCAmelCase			      =	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      )
                           _lowerCAmelCase			      =	tmpdirname_orig





   def 						__lowerCAmelCase				(						self      ):
         _lowerCAmelCase			      =	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:
                           _lowerCAmelCase			      =	tempfile.mkdtemp()
                           _lowerCAmelCase			      =	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      )
                           _lowerCAmelCase			      =	tmpdirname_orig





   def 						__lowerCAmelCase				(						self      ):
         _lowerCAmelCase			      =	self.rust_tokenizer_class.from_pretrained(self.bytelevel_bpe_model_name      )

         _lowerCAmelCase			      =	('''a''' for _ in range(1_000      ))
         _lowerCAmelCase			      =	tokenizer.train_new_from_iterator(text_iterator=_lowerCAmelCase							,  length=1_000							,  vocab_size=50      )

         _lowerCAmelCase			      =	new_tokenizer.encode('''a🤗'''      )
         self.assertEqual(_lowerCAmelCase							,  [64, 172, 253, 97, 245]      )






@require_tokenizers
class 		UpperCAmelCase    (    unittest.TestCase					):





   def 						__lowerCAmelCase				(						self      ):
         _lowerCAmelCase			      =	AutoTokenizer.from_pretrained('''bert-base-cased'''      )
         _lowerCAmelCase			      =	json.loads(tokenizer._tokenizer.to_str()      )
         _lowerCAmelCase			      =	len(_lowerCAmelCase      )

         with tempfile.TemporaryDirectory() as tmp_dir:
               # Hack to save this in the tokenizer_config.json
               _lowerCAmelCase			      =	['''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
               _lowerCAmelCase			      =	AutoTokenizer.from_pretrained(_lowerCAmelCase      )
               self.assertEqual(len(_lowerCAmelCase      )							,  len(_lowerCAmelCase      ) + 1      )
               _lowerCAmelCase			      =	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'''      )      )
               _lowerCAmelCase			      =	['''tokenizer.42.0.0.json''']
               tokenizer.save_pretrained(_lowerCAmelCase      )
               _lowerCAmelCase			      =	AutoTokenizer.from_pretrained(_lowerCAmelCase      )
               self.assertEqual(len(_lowerCAmelCase      )							,  len(_lowerCAmelCase      )      )
               _lowerCAmelCase			      =	json.loads(new_tokenizer._tokenizer.to_str()      )
               self.assertNotIn('''huggingface'''							,  json_tokenizer['''model''']['''vocab''']      )





   def 						__lowerCAmelCase				(						self      ):
         # This repo has two tokenizer files, one for v4.0.0 and above with an added token, one for versions lower.
         _lowerCAmelCase			      =	'''hf-internal-testing/test-two-tokenizers'''

         # This should pick the new tokenizer file as the version of Transformers is > 4.0.0
         _lowerCAmelCase			      =	AutoTokenizer.from_pretrained(_lowerCAmelCase      )
         self.assertEqual(len(_lowerCAmelCase      )							,  28_997      )
         _lowerCAmelCase			      =	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

         _lowerCAmelCase			      =	'''3.0.0'''
         _lowerCAmelCase			      =	old_transformers.models.auto.AutoTokenizer.from_pretrained(_lowerCAmelCase      )
         self.assertEqual(len(_lowerCAmelCase      )							,  28_996      )
         _lowerCAmelCase			      =	json.loads(old_tokenizer._tokenizer.to_str()      )
         self.assertNotIn('''huggingface'''							,  json_tokenizer['''model''']['''vocab''']      )






@require_tokenizers
class 		UpperCAmelCase    (    unittest.TestCase					):





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

         with concurrent.futures.ThreadPoolExecutor() as executor:
               _lowerCAmelCase			      =	[executor.submit(self.fetch							,  _lowerCAmelCase							,  _lowerCAmelCase      ) for i in range(10      )]
               _lowerCAmelCase			      =	[future.result() for future in futures]
               self.assertEqual(_lowerCAmelCase							,  [[1, 10, 0, 8, 0, 18, 0, 0, 0, 2] for i in range(10      )]      )





   def 						__lowerCAmelCase				(						self							,  _lowerCAmelCase							,  _lowerCAmelCase      ):
         return tokenizer.encode(_lowerCAmelCase							,  truncation='''longest_first'''							,  padding='''longest'''      )