





'''simple docstring'''

import unittest

from transformers import AutoTokenizer, NystromformerConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
   import torch

   from transformers import (
       NystromformerForMaskedLM,
       NystromformerForMultipleChoice,
       NystromformerForQuestionAnswering,
       NystromformerForSequenceClassification,
       NystromformerForTokenClassification,
       NystromformerModel,
   )
   from transformers.models.nystromformer.modeling_nystromformer import NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST
class 							__lowerCAmelCase	:






       """simple docstring"""





       def __init__(				self  :						Optional[int]			,					lowerCAmelCase__  :						Optional[int]			,					lowerCAmelCase__  :						int=13			,					lowerCAmelCase__  :						List[Any]=7			,					lowerCAmelCase__  :						Any=True			,					lowerCAmelCase__  :						Tuple=True			,					lowerCAmelCase__  :						int=True			,					lowerCAmelCase__  :						List[Any]=True			,					lowerCAmelCase__  :						Optional[int]=99			,					lowerCAmelCase__  :						str=32			,					lowerCAmelCase__  :						Tuple=5			,					lowerCAmelCase__  :						str=4			,					lowerCAmelCase__  :						Any=37			,					lowerCAmelCase__  :						Tuple="gelu"			,					lowerCAmelCase__  :						Optional[int]=0.1			,					lowerCAmelCase__  :						str=0.1			,					lowerCAmelCase__  :						Optional[Any]=512			,					lowerCAmelCase__  :						List[str]=16			,					lowerCAmelCase__  :						str=2			,					lowerCAmelCase__  :						Dict=0.02			,					lowerCAmelCase__  :						Optional[Any]=3			,					lowerCAmelCase__  :						int=4			,					lowerCAmelCase__  :						Any=None			,					)       ->	List[Any]:

            '''simple docstring'''




            _UpperCamelCase							       =			parent
            _UpperCamelCase							       =			batch_size
            _UpperCamelCase							       =			seq_length
            _UpperCamelCase							       =			is_training
            _UpperCamelCase							       =			use_input_mask
            _UpperCamelCase							       =			use_token_type_ids
            _UpperCamelCase							       =			use_labels
            _UpperCamelCase							       =			vocab_size
            _UpperCamelCase							       =			hidden_size
            _UpperCamelCase							       =			num_hidden_layers
            _UpperCamelCase							       =			num_attention_heads
            _UpperCamelCase							       =			intermediate_size
            _UpperCamelCase							       =			hidden_act
            _UpperCamelCase							       =			hidden_dropout_prob
            _UpperCamelCase							       =			attention_probs_dropout_prob
            _UpperCamelCase							       =			max_position_embeddings
            _UpperCamelCase							       =			type_vocab_size
            _UpperCamelCase							       =			type_sequence_label_size
            _UpperCamelCase							       =			initializer_range
            _UpperCamelCase							       =			num_labels
            _UpperCamelCase							       =			num_choices
            _UpperCamelCase							       =			scope





       def snake_case__		(				self  :						int	)       ->	int:

            '''simple docstring'''




            _UpperCamelCase							       =			ids_tensor([self.batch_size, self.seq_length]			,					self.vocab_size	)

            _UpperCamelCase							       =			None
            if self.use_input_mask:
                 _UpperCamelCase							       =			random_attention_mask([self.batch_size, self.seq_length]	)

            _UpperCamelCase							       =			None
            if self.use_token_type_ids:
                 _UpperCamelCase							       =			ids_tensor([self.batch_size, self.seq_length]			,					self.type_vocab_size	)

            _UpperCamelCase							       =			None
            _UpperCamelCase							       =			None
            _UpperCamelCase							       =			None
            if self.use_labels:
                 _UpperCamelCase							       =			ids_tensor([self.batch_size]			,					self.type_sequence_label_size	)
                 _UpperCamelCase							       =			ids_tensor([self.batch_size, self.seq_length]			,					self.num_labels	)
                 _UpperCamelCase							       =			ids_tensor([self.batch_size]			,					self.num_choices	)

            _UpperCamelCase							       =			self.get_config()

            return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels





       def snake_case__		(				self  :						Optional[int]	)       ->	Any:

            '''simple docstring'''




            return NystromformerConfig(
                vocab_size=self.vocab_size			,					hidden_size=self.hidden_size			,					num_hidden_layers=self.num_hidden_layers			,					num_attention_heads=self.num_attention_heads			,					intermediate_size=self.intermediate_size			,					hidden_act=self.hidden_act			,					hidden_dropout_prob=self.hidden_dropout_prob			,					attention_probs_dropout_prob=self.attention_probs_dropout_prob			,					max_position_embeddings=self.max_position_embeddings			,					type_vocab_size=self.type_vocab_size			,					is_decoder=__UpperCamelCase			,					initializer_range=self.initializer_range			,					)





       def snake_case__		(				self  :						Any			,					lowerCAmelCase__  :						Any			,					lowerCAmelCase__  :						List[str]			,					lowerCAmelCase__  :						Union[str, Any]			,					lowerCAmelCase__  :						Optional[Any]			,					lowerCAmelCase__  :						str			,					lowerCAmelCase__  :						Optional[int]			,					lowerCAmelCase__  :						Optional[Any]	)       ->	str:

            '''simple docstring'''




            _UpperCamelCase							       =			NystromformerModel(config=__UpperCamelCase	)
            model.to(__UpperCamelCase	)
            model.eval()
            _UpperCamelCase							       =			model(__UpperCamelCase			,					attention_mask=__UpperCamelCase			,					token_type_ids=__UpperCamelCase	)
            _UpperCamelCase							       =			model(__UpperCamelCase			,					token_type_ids=__UpperCamelCase	)
            _UpperCamelCase							       =			model(__UpperCamelCase	)
            self.parent.assertEqual(result.last_hidden_state.shape			,					(self.batch_size, self.seq_length, self.hidden_size)	)





       def snake_case__		(				self  :						List[Any]			,					lowerCAmelCase__  :						List[Any]			,					lowerCAmelCase__  :						Dict			,					lowerCAmelCase__  :						Optional[int]			,					lowerCAmelCase__  :						List[str]			,					lowerCAmelCase__  :						int			,					lowerCAmelCase__  :						List[Any]			,					lowerCAmelCase__  :						Union[str, Any]	)       ->	Optional[Any]:

            '''simple docstring'''




            _UpperCamelCase							       =			NystromformerForMaskedLM(config=__UpperCamelCase	)
            model.to(__UpperCamelCase	)
            model.eval()
            _UpperCamelCase							       =			model(__UpperCamelCase			,					attention_mask=__UpperCamelCase			,					token_type_ids=__UpperCamelCase			,					labels=__UpperCamelCase	)
            self.parent.assertEqual(result.logits.shape			,					(self.batch_size, self.seq_length, self.vocab_size)	)





       def snake_case__		(				self  :						int			,					lowerCAmelCase__  :						str			,					lowerCAmelCase__  :						Tuple			,					lowerCAmelCase__  :						Dict			,					lowerCAmelCase__  :						str			,					lowerCAmelCase__  :						Any			,					lowerCAmelCase__  :						int			,					lowerCAmelCase__  :						Dict	)       ->	Optional[int]:

            '''simple docstring'''




            _UpperCamelCase							       =			NystromformerForQuestionAnswering(config=__UpperCamelCase	)
            model.to(__UpperCamelCase	)
            model.eval()
            _UpperCamelCase							       =			model(
                __UpperCamelCase			,					attention_mask=__UpperCamelCase			,					token_type_ids=__UpperCamelCase			,					start_positions=__UpperCamelCase			,					end_positions=__UpperCamelCase			,					)
            self.parent.assertEqual(result.start_logits.shape			,					(self.batch_size, self.seq_length)	)
            self.parent.assertEqual(result.end_logits.shape			,					(self.batch_size, self.seq_length)	)





       def snake_case__		(				self  :						Any			,					lowerCAmelCase__  :						Any			,					lowerCAmelCase__  :						Any			,					lowerCAmelCase__  :						Optional[Any]			,					lowerCAmelCase__  :						List[str]			,					lowerCAmelCase__  :						List[Any]			,					lowerCAmelCase__  :						Optional[int]			,					lowerCAmelCase__  :						str	)       ->	Tuple:

            '''simple docstring'''




            _UpperCamelCase							       =			self.num_labels
            _UpperCamelCase							       =			NystromformerForSequenceClassification(__UpperCamelCase	)
            model.to(__UpperCamelCase	)
            model.eval()
            _UpperCamelCase							       =			model(__UpperCamelCase			,					attention_mask=__UpperCamelCase			,					token_type_ids=__UpperCamelCase			,					labels=__UpperCamelCase	)
            self.parent.assertEqual(result.logits.shape			,					(self.batch_size, self.num_labels)	)





       def snake_case__		(				self  :						List[Any]			,					lowerCAmelCase__  :						str			,					lowerCAmelCase__  :						Optional[Any]			,					lowerCAmelCase__  :						Dict			,					lowerCAmelCase__  :						Optional[int]			,					lowerCAmelCase__  :						List[Any]			,					lowerCAmelCase__  :						Optional[int]			,					lowerCAmelCase__  :						List[str]	)       ->	Dict:

            '''simple docstring'''




            _UpperCamelCase							       =			self.num_labels
            _UpperCamelCase							       =			NystromformerForTokenClassification(config=__UpperCamelCase	)
            model.to(__UpperCamelCase	)
            model.eval()
            _UpperCamelCase							       =			model(__UpperCamelCase			,					attention_mask=__UpperCamelCase			,					token_type_ids=__UpperCamelCase			,					labels=__UpperCamelCase	)
            self.parent.assertEqual(result.logits.shape			,					(self.batch_size, self.seq_length, self.num_labels)	)





       def snake_case__		(				self  :						Union[str, Any]			,					lowerCAmelCase__  :						List[str]			,					lowerCAmelCase__  :						Tuple			,					lowerCAmelCase__  :						Optional[Any]			,					lowerCAmelCase__  :						Union[str, Any]			,					lowerCAmelCase__  :						Optional[Any]			,					lowerCAmelCase__  :						str			,					lowerCAmelCase__  :						List[str]	)       ->	str:

            '''simple docstring'''




            _UpperCamelCase							       =			self.num_choices
            _UpperCamelCase							       =			NystromformerForMultipleChoice(config=__UpperCamelCase	)
            model.to(__UpperCamelCase	)
            model.eval()
            _UpperCamelCase							       =			input_ids.unsqueeze(1	).expand(-1			,					self.num_choices			,					-1	).contiguous()
            _UpperCamelCase							       =			token_type_ids.unsqueeze(1	).expand(-1			,					self.num_choices			,					-1	).contiguous()
            _UpperCamelCase							       =			input_mask.unsqueeze(1	).expand(-1			,					self.num_choices			,					-1	).contiguous()
            _UpperCamelCase							       =			model(
                __UpperCamelCase			,					attention_mask=__UpperCamelCase			,					token_type_ids=__UpperCamelCase			,					labels=__UpperCamelCase			,					)
            self.parent.assertEqual(result.logits.shape			,					(self.batch_size, self.num_choices)	)







       def snake_case__		(				self  :						Tuple	)       ->	str:

            '''simple docstring'''




            _UpperCamelCase							       =			self.prepare_config_and_inputs()
            (
                (
                _UpperCamelCase   
            )       ,							(
                _UpperCamelCase   
            )       ,							(
                _UpperCamelCase   
            )       ,							(
                _UpperCamelCase   
            )       ,							(
                _UpperCamelCase   
            )       ,							(
                _UpperCamelCase   
            )       ,							(
                _UpperCamelCase   
            )       ,							   
            )							       =			config_and_inputs
            _UpperCamelCase							       =			{'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
            return config, inputs_dict

@require_torch
class 							__lowerCAmelCase	(       _lowerCamelCase		,		_lowerCamelCase		,		unittest.TestCase					):






       """simple docstring"""
       _snake_case      :	Optional[Any]									=       (
           (
               NystromformerModel,
               NystromformerForMaskedLM,
               NystromformerForMultipleChoice,
               NystromformerForQuestionAnswering,
               NystromformerForSequenceClassification,
               NystromformerForTokenClassification,
           )
           if is_torch_available()
           else ()
       )
       _snake_case      :	Optional[Any]									=       (
           {
               'feature-extraction': NystromformerModel,
               'fill-mask': NystromformerForMaskedLM,
               'question-answering': NystromformerForQuestionAnswering,
               'text-classification': NystromformerForSequenceClassification,
               'token-classification': NystromformerForTokenClassification,
               'zero-shot': NystromformerForSequenceClassification,
           }
           if is_torch_available()
           else {}
       )
       _snake_case      :	Dict									=       False
       _snake_case      :	int									=       False





       def snake_case__		(				self  :						Dict	)       ->	int:

            '''simple docstring'''




            _UpperCamelCase							       =			NystromformerModelTester(self	)
            _UpperCamelCase							       =			ConfigTester(self			,					config_class=__UpperCamelCase			,					hidden_size=37	)





       def snake_case__		(				self  :						List[Any]	)       ->	Tuple:

            '''simple docstring'''




            self.config_tester.run_common_tests()





       def snake_case__		(				self  :						Tuple	)       ->	str:

            '''simple docstring'''




            _UpperCamelCase							       =			self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*__UpperCamelCase	)





       def snake_case__		(				self  :						str	)       ->	Any:

            '''simple docstring'''




            _UpperCamelCase							       =			self.model_tester.prepare_config_and_inputs()
            for type in ["absolute", "relative_key", "relative_key_query"]:
                 _UpperCamelCase							       =			type
                 self.model_tester.create_and_check_model(*__UpperCamelCase	)





       def snake_case__		(				self  :						Optional[Any]	)       ->	Dict:

            '''simple docstring'''




            _UpperCamelCase							       =			self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_masked_lm(*__UpperCamelCase	)





       def snake_case__		(				self  :						Optional[Any]	)       ->	List[Any]:

            '''simple docstring'''




            _UpperCamelCase							       =			self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_multiple_choice(*__UpperCamelCase	)





       def snake_case__		(				self  :						Dict	)       ->	List[str]:

            '''simple docstring'''




            _UpperCamelCase							       =			self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_question_answering(*__UpperCamelCase	)





       def snake_case__		(				self  :						Tuple	)       ->	str:

            '''simple docstring'''




            _UpperCamelCase							       =			self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_sequence_classification(*__UpperCamelCase	)





       def snake_case__		(				self  :						List[str]	)       ->	Optional[int]:

            '''simple docstring'''




            _UpperCamelCase							       =			self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_token_classification(*__UpperCamelCase	)







       @slow
       def snake_case__		(				self  :						int	)       ->	Optional[int]:

            '''simple docstring'''




            for model_name in NYSTROMFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 _UpperCamelCase							       =			NystromformerModel.from_pretrained(__UpperCamelCase	)
                 self.assertIsNotNone(__UpperCamelCase	)

@require_torch
class 							__lowerCAmelCase	(       unittest.TestCase					):






       """simple docstring"""





       @slow
       def snake_case__		(				self  :						int	)       ->	Dict:

            '''simple docstring'''




            _UpperCamelCase							       =			NystromformerModel.from_pretrained('''uw-madison/nystromformer-512'''	)
            _UpperCamelCase							       =			torch.tensor([[0, 1, 2, 3, 4, 5]]	)

            with torch.no_grad():
                 _UpperCamelCase							       =			model(__UpperCamelCase	)[0]

            _UpperCamelCase							       =			torch.Size((1, 6, 768)	)
            self.assertEqual(output.shape			,					__UpperCamelCase	)

            _UpperCamelCase							       =			torch.tensor(
                [[[-0.4532, -0.0936, 0.5137], [-0.2676, 0.0628, 0.6186], [-0.3629, -0.1726, 0.4716]]]	)

            self.assertTrue(torch.allclose(output[:, :3, :3]			,					__UpperCamelCase			,					atol=1e-4	)	)







       @slow
       def snake_case__		(				self  :						List[Any]	)       ->	int:

            '''simple docstring'''




            _UpperCamelCase							       =			'''the [MASK] of Belgium is Brussels'''

            _UpperCamelCase							       =			AutoTokenizer.from_pretrained('''uw-madison/nystromformer-512'''	)
            _UpperCamelCase							       =			NystromformerForMaskedLM.from_pretrained('''uw-madison/nystromformer-512'''	)

            _UpperCamelCase							       =			tokenizer(__UpperCamelCase			,					return_tensors='''pt'''	)

            with torch.no_grad():
                 _UpperCamelCase							       =			model(encoding.input_ids	).logits

            _UpperCamelCase							       =			token_logits[:, 2, :].argmax(-1	)[0]

            self.assertEqual(tokenizer.decode(__UpperCamelCase	)			,					'''capital'''	)








import os
import sys
import tempfile
import unittest
import unittest.mock as mock
from pathlib import Path

from huggingface_hub import HfFolder, delete_repo
from huggingface_hub.file_download import http_get
from requests.exceptions import HTTPError

from transformers import (
    AlbertTokenizer,
    AutoTokenizer,
    BertTokenizer,
    BertTokenizerFast,
    GPTaTokenizerFast,
    is_tokenizers_available,
)
from transformers.testing_utils import TOKEN, USER, is_staging_test, require_tokenizers
from transformers.tokenization_utils import Trie


sys.path.append(str(Path(__file__).parent.parent / 'utils'))

from test_module.custom_tokenization import CustomTokenizer  # noqa E402


if is_tokenizers_available():
				from test_module.custom_tokenization_fast import CustomTokenizerFast



class        lowerCAmelCase__					(  unittest.TestCase       ):


				def __UpperCamelCase						(							self      :  Any       )		->     Tuple:
											# A mock response for an HTTP head request to emulate server down
											A      						=    mock.Mock()
											A      						=    500
											A      						=    {}
											A      						=    HTTPError
											A      						=    {}

											# Download this model to make sure it's in the cache.
											A      						=    BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert'       )

											# Under the mock environment we get a 500 error when trying to reach the tokenizer.
											with mock.patch('requests.Session.request'						, return_value=__UpperCamelCase       ) as mock_head:
																		A      						=    BertTokenizer.from_pretrained('hf-internal-testing/tiny-random-bert'       )
																		# This check we did call the fake head request
																		mock_head.assert_called()


				@require_tokenizers
				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     Union[str, Any]:
											# A mock response for an HTTP head request to emulate server down
											A      						=    mock.Mock()
											A      						=    500
											A      						=    {}
											A      						=    HTTPError
											A      						=    {}

											# Download this model to make sure it's in the cache.
											A      						=    GPTaTokenizerFast.from_pretrained('gpt2'       )

											# Under the mock environment we get a 500 error when trying to reach the tokenizer.
											with mock.patch('requests.Session.request'						, return_value=__UpperCamelCase       ) as mock_head:
																		A      						=    GPTaTokenizerFast.from_pretrained('gpt2'       )
																		# This check we did call the fake head request
																		mock_head.assert_called()


				def __UpperCamelCase						(							self      :  Optional[Any]       )		->     List[str]:
											# This test is for deprecated behavior and can be removed in v5
											try:
																		A      						=    tempfile.mktemp()
																		with open(__UpperCamelCase						, 'wb'       ) as f:
																									http_get('https://huggingface.co/albert-base-v1/resolve/main/spiece.model'						, __UpperCamelCase       )

																		A      						=    AlbertTokenizer.from_pretrained(__UpperCamelCase       )
											finally:
																		os.remove(__UpperCamelCase       )

											# Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in
											# the current folder and have the right name.
											if os.path.isfile('tokenizer.json'       ):
																		# We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it.
																		return
											try:
																		with open('tokenizer.json'						, 'wb'       ) as f:
																									http_get('https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json'						, __UpperCamelCase       )
																		A      						=    AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2'       )
																		# The tiny random BERT has a vocab size of 1024, tiny gpt2 as a vocab size of 1000
																		self.assertEqual(tokenizer.vocab_size						, 1_000       )
																		# Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file.

											finally:
																		os.remove('tokenizer.json'       )


				def __UpperCamelCase						(							self      :  str       )		->     int:
											# This test is for deprecated behavior and can be removed in v5
											A      						=    AlbertTokenizer.from_pretrained('https://huggingface.co/albert-base-v1/resolve/main/spiece.model'       )





@is_staging_test
class        lowerCAmelCase__					(  unittest.TestCase       ):
				A_   :     str								=     ['[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'bla', 'blou']


				@classmethod
				def __UpperCamelCase						(							cls      :  Tuple       )		->     Dict:
											A      						=    TOKEN
											HfFolder.save_token(__UpperCamelCase       )


				@classmethod
				def __UpperCamelCase						(							cls      :  Any       )		->     Dict:
											try:
																		delete_repo(token=cls._token						, repo_id='test-tokenizer'       )
											except HTTPError:
																		pass

											try:
																		delete_repo(token=cls._token						, repo_id='valid_org/test-tokenizer-org'       )
											except HTTPError:
																		pass

											try:
																		delete_repo(token=cls._token						, repo_id='test-dynamic-tokenizer'       )
											except HTTPError:
																		pass


				def __UpperCamelCase						(							self      :  Optional[Any]       )		->     List[str]:
											with tempfile.TemporaryDirectory() as tmp_dir:
																		A      						=    os.path.join(__UpperCamelCase						, 'vocab.txt'       )
																		with open(__UpperCamelCase						, 'w'						, encoding='utf-8'       ) as vocab_writer:
																									vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens]       )       )
																		A      						=    BertTokenizer(__UpperCamelCase       )

											tokenizer.push_to_hub('test-tokenizer'						, use_auth_token=self._token       )
											A      						=    BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer'''       )
											self.assertDictEqual(new_tokenizer.vocab						, tokenizer.vocab       )

											# Reset repo
											delete_repo(token=self._token						, repo_id='test-tokenizer'       )

											# Push to hub via save_pretrained
											with tempfile.TemporaryDirectory() as tmp_dir:
																		tokenizer.save_pretrained(__UpperCamelCase						, repo_id='test-tokenizer'						, push_to_hub=__UpperCamelCase						, use_auth_token=self._token       )

											A      						=    BertTokenizer.from_pretrained(f'''{USER}/test-tokenizer'''       )
											self.assertDictEqual(new_tokenizer.vocab						, tokenizer.vocab       )


				def __UpperCamelCase						(							self      :  List[str]       )		->     Tuple:
											with tempfile.TemporaryDirectory() as tmp_dir:
																		A      						=    os.path.join(__UpperCamelCase						, 'vocab.txt'       )
																		with open(__UpperCamelCase						, 'w'						, encoding='utf-8'       ) as vocab_writer:
																									vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens]       )       )
																		A      						=    BertTokenizer(__UpperCamelCase       )

											tokenizer.push_to_hub('valid_org/test-tokenizer-org'						, use_auth_token=self._token       )
											A      						=    BertTokenizer.from_pretrained('valid_org/test-tokenizer-org'       )
											self.assertDictEqual(new_tokenizer.vocab						, tokenizer.vocab       )

											# Reset repo
											delete_repo(token=self._token						, repo_id='valid_org/test-tokenizer-org'       )

											# Push to hub via save_pretrained
											with tempfile.TemporaryDirectory() as tmp_dir:
																		tokenizer.save_pretrained(
																		    __UpperCamelCase						, repo_id='valid_org/test-tokenizer-org'						, push_to_hub=__UpperCamelCase						, use_auth_token=self._token       )

											A      						=    BertTokenizer.from_pretrained('valid_org/test-tokenizer-org'       )
											self.assertDictEqual(new_tokenizer.vocab						, tokenizer.vocab       )


				@require_tokenizers
				def __UpperCamelCase						(							self      :  Any       )		->     Union[str, Any]:
											CustomTokenizer.register_for_auto_class()
											with tempfile.TemporaryDirectory() as tmp_dir:
																		A      						=    os.path.join(__UpperCamelCase						, 'vocab.txt'       )
																		with open(__UpperCamelCase						, 'w'						, encoding='utf-8'       ) as vocab_writer:
																									vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens]       )       )
																		A      						=    CustomTokenizer(__UpperCamelCase       )

											# No fast custom tokenizer
											tokenizer.push_to_hub('test-dynamic-tokenizer'						, use_auth_token=self._token       )

											A      						=    AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer'''						, trust_remote_code=__UpperCamelCase       )
											# Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module
											self.assertEqual(tokenizer.__class__.__name__						, 'CustomTokenizer'       )

											# Fast and slow custom tokenizer
											CustomTokenizerFast.register_for_auto_class()
											with tempfile.TemporaryDirectory() as tmp_dir:
																		A      						=    os.path.join(__UpperCamelCase						, 'vocab.txt'       )
																		with open(__UpperCamelCase						, 'w'						, encoding='utf-8'       ) as vocab_writer:
																									vocab_writer.write(''.join([x + '\n' for x in self.vocab_tokens]       )       )

																		A      						=    BertTokenizerFast.from_pretrained(__UpperCamelCase       )
																		bert_tokenizer.save_pretrained(__UpperCamelCase       )
																		A      						=    CustomTokenizerFast.from_pretrained(__UpperCamelCase       )

											tokenizer.push_to_hub('test-dynamic-tokenizer'						, use_auth_token=self._token       )

											A      						=    AutoTokenizer.from_pretrained(f'''{USER}/test-dynamic-tokenizer'''						, trust_remote_code=__UpperCamelCase       )
											# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
											self.assertEqual(tokenizer.__class__.__name__						, 'CustomTokenizerFast'       )
											A      						=    AutoTokenizer.from_pretrained(
											    f'''{USER}/test-dynamic-tokenizer'''						, use_fast=__UpperCamelCase						, trust_remote_code=__UpperCamelCase       )
											# Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module
											self.assertEqual(tokenizer.__class__.__name__						, 'CustomTokenizer'       )





class        lowerCAmelCase__					(  unittest.TestCase       ):


				def __UpperCamelCase						(							self      :  List[Any]       )		->     Any:
											A      						=    Trie()
											trie.add('Hello 友達'       )
											self.assertEqual(trie.data						, {'H': {'e': {'l': {'l': {'o': {' ': {'友': {'達': {'': 1}}}}}}}}}       )
											trie.add('Hello'       )
											trie.data
											self.assertEqual(trie.data						, {'H': {'e': {'l': {'l': {'o': {'': 1, ' ': {'友': {'達': {'': 1}}}}}}}}}       )


				def __UpperCamelCase						(							self      :  Dict       )		->     Tuple:
											A      						=    Trie()
											self.assertEqual(trie.split('[CLS] This is a extra_id_100'       )						, ['[CLS] This is a extra_id_100']       )
											trie.add('[CLS]'       )
											trie.add('extra_id_1'       )
											trie.add('extra_id_100'       )
											self.assertEqual(trie.split('[CLS] This is a extra_id_100'       )						, ['[CLS]', ' This is a ', 'extra_id_100']       )


				def __UpperCamelCase						(							self      :  Any       )		->     Optional[int]:
											A      						=    Trie()
											trie.add('A'       )
											self.assertEqual(trie.split('ABC'       )						, ['A', 'BC']       )
											self.assertEqual(trie.split('BCA'       )						, ['BC', 'A']       )


				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     str:
											A      						=    Trie()
											trie.add('TOKEN]'       )
											trie.add('[SPECIAL_TOKEN]'       )
											self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]'       )						, ['This is something ', '[SPECIAL_TOKEN]']       )


				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     Tuple:
											A      						=    Trie()
											trie.add('A'       )
											trie.add('P'       )
											trie.add('[SPECIAL_TOKEN]'       )
											self.assertEqual(trie.split('This is something [SPECIAL_TOKEN]'       )						, ['This is something ', '[SPECIAL_TOKEN]']       )


				def __UpperCamelCase						(							self      :  List[str]       )		->     Tuple:
											A      						=    Trie()
											trie.add('AB'       )
											trie.add('B'       )
											trie.add('C'       )
											self.assertEqual(trie.split('ABC'       )						, ['AB', 'C']       )


				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     List[Any]:
											A      						=    Trie()
											trie.add('ABC'       )
											trie.add('B'       )
											trie.add('CD'       )
											self.assertEqual(trie.split('ABCD'       )						, ['ABC', 'D']       )


				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     List[Any]:
											# Even if the offsets are wrong, we necessarily output correct string
											# parts.
											A      						=    Trie()
											A      						=    trie.cut_text('ABC'						, [0, 0, 2, 1, 2, 3]       )
											self.assertEqual(__UpperCamelCase						, ['AB', 'C']       )