

import unittest

from transformers import FunnelConfig, FunnelTokenizer, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device

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


if is_torch_available():
					import torch

					from transformers import (
					    MODEL_FOR_PRETRAINING_MAPPING,
					    FunnelBaseModel,
					    FunnelForMaskedLM,
					    FunnelForMultipleChoice,
					    FunnelForPreTraining,
					    FunnelForQuestionAnswering,
					    FunnelForSequenceClassification,
					    FunnelForTokenClassification,
					    FunnelModel,
					)





class      snake_case_       :







			'''simple docstring'''

			def __init__(					self			:    int							,       _UpperCamelCase			:    List[Any]							,       _UpperCamelCase			:    Union[str, Any]=1_3							,       _UpperCamelCase			:    Dict=7							,       _UpperCamelCase			:    Tuple=True							,       _UpperCamelCase			:    Any=True							,       _UpperCamelCase			:    List[str]=True							,       _UpperCamelCase			:    List[Any]=True							,       _UpperCamelCase			:    Tuple=9_9							,       _UpperCamelCase			:    str=[1, 1, 2]							,       _UpperCamelCase			:    List[str]=1							,       _UpperCamelCase			:    Optional[Any]=3_2							,       _UpperCamelCase			:    Tuple=4							,       _UpperCamelCase			:    Any=8							,       _UpperCamelCase			:    int=3_7							,       _UpperCamelCase			:    Tuple="gelu_new"							,       _UpperCamelCase			:    Union[str, Any]=0.1							,       _UpperCamelCase			:    List[Any]=0.1							,       _UpperCamelCase			:    List[Any]=0.0							,       _UpperCamelCase			:    int=5_1_2							,       _UpperCamelCase			:    List[Any]=3							,       _UpperCamelCase			:    List[str]=0.02							,       _UpperCamelCase			:    Dict=3							,       _UpperCamelCase			:    Optional[Any]=4							,       _UpperCamelCase			:    int=None							,       _UpperCamelCase			:    List[str]=False							,       )				->Optional[int]:
									snake_case_       =     parent
									snake_case_       =     batch_size
									snake_case_       =     seq_length
									snake_case_       =     is_training
									snake_case_       =     use_input_mask
									snake_case_       =     use_token_type_ids
									snake_case_       =     use_labels
									snake_case_       =     vocab_size
									snake_case_       =     block_sizes
									snake_case_       =     num_decoder_layers
									snake_case_       =     d_model
									snake_case_       =     n_head
									snake_case_       =     d_head
									snake_case_       =     d_inner
									snake_case_       =     hidden_act
									snake_case_       =     hidden_dropout
									snake_case_       =     attention_dropout
									snake_case_       =     activation_dropout
									snake_case_       =     max_position_embeddings
									snake_case_       =     type_vocab_size
									snake_case_       =     2
									snake_case_       =     num_labels
									snake_case_       =     num_choices
									snake_case_       =     scope
									snake_case_       =     initializer_std

									# Used in the tests to check the size of the first attention layer
									snake_case_       =     n_head
									# Used in the tests to check the size of the first hidden state
									snake_case_       =     self.d_model
									# Used in the tests to check the number of output hidden states/attentions
									snake_case_       =     sum(self.block_sizes							) + (0 if base else self.num_decoder_layers)
									# FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with
									# the last hidden state of the first block (which is the first hidden state of the decoder).
									if not base:
															snake_case_       =     self.num_hidden_layers + 2







			def     snake_case__(					self			:    Union[str, Any]							)				->int:
									snake_case_       =     ids_tensor([self.batch_size, self.seq_length]							,       self.vocab_size							)

									snake_case_       =     None
									if self.use_input_mask:
															snake_case_       =     ids_tensor([self.batch_size, self.seq_length]							,       vocab_size=2							)

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

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

									snake_case_       =     self.get_config()

									return (
									    config,
									    input_ids,
									    token_type_ids,
									    input_mask,
									    sequence_labels,
									    token_labels,
									    choice_labels,
									    fake_token_labels,
									)







			def     snake_case__(					self			:    str							)				->Any:
									return FunnelConfig(
									    vocab_size=self.vocab_size							,       block_sizes=self.block_sizes							,       num_decoder_layers=self.num_decoder_layers							,       d_model=self.d_model							,       n_head=self.n_head							,       d_head=self.d_head							,       d_inner=self.d_inner							,       hidden_act=self.hidden_act							,       hidden_dropout=self.hidden_dropout							,       attention_dropout=self.attention_dropout							,       activation_dropout=self.activation_dropout							,       max_position_embeddings=self.max_position_embeddings							,       type_vocab_size=self.type_vocab_size							,       initializer_std=self.initializer_std							,       )







			def     snake_case__(					self			:    List[str]							,       _UpperCamelCase			:    Optional[int]							,       _UpperCamelCase			:    int							,       _UpperCamelCase			:    str							,       _UpperCamelCase			:    List[str]							,       _UpperCamelCase			:    Any							,       _UpperCamelCase			:    Dict							,       _UpperCamelCase			:    Optional[Any]							,       _UpperCamelCase			:    int							,       )				->Any:
									snake_case_       =     FunnelModel(config=_UpperCamelCase							)
									model.to(_UpperCamelCase							)
									model.eval()
									snake_case_       =     model(_UpperCamelCase							,       attention_mask=_UpperCamelCase							,       token_type_ids=_UpperCamelCase							)
									snake_case_       =     model(_UpperCamelCase							,       token_type_ids=_UpperCamelCase							)
									snake_case_       =     model(_UpperCamelCase							)
									self.parent.assertEqual(result.last_hidden_state.shape							,       (self.batch_size, self.seq_length, self.d_model)							)

									snake_case_       =     False
									snake_case_       =     model(_UpperCamelCase							)
									self.parent.assertEqual(result.last_hidden_state.shape							,       (self.batch_size, self.seq_length, self.d_model)							)

									snake_case_       =     False
									snake_case_       =     model(_UpperCamelCase							)
									self.parent.assertEqual(result.last_hidden_state.shape							,       (self.batch_size, self.seq_length, self.d_model)							)







			def     snake_case__(					self			:    Optional[int]							,       _UpperCamelCase			:    Optional[int]							,       _UpperCamelCase			:    List[str]							,       _UpperCamelCase			:    Optional[Any]							,       _UpperCamelCase			:    Any							,       _UpperCamelCase			:    Any							,       _UpperCamelCase			:    str							,       _UpperCamelCase			:    Dict							,       _UpperCamelCase			:    Optional[Any]							,       )				->Optional[int]:
									snake_case_       =     FunnelBaseModel(config=_UpperCamelCase							)
									model.to(_UpperCamelCase							)
									model.eval()
									snake_case_       =     model(_UpperCamelCase							,       attention_mask=_UpperCamelCase							,       token_type_ids=_UpperCamelCase							)
									snake_case_       =     model(_UpperCamelCase							,       token_type_ids=_UpperCamelCase							)
									snake_case_       =     model(_UpperCamelCase							)
									self.parent.assertEqual(result.last_hidden_state.shape							,       (self.batch_size, 2, self.d_model)							)

									snake_case_       =     False
									snake_case_       =     model(_UpperCamelCase							)
									self.parent.assertEqual(result.last_hidden_state.shape							,       (self.batch_size, 3, self.d_model)							)

									snake_case_       =     False
									snake_case_       =     model(_UpperCamelCase							)
									self.parent.assertEqual(result.last_hidden_state.shape							,       (self.batch_size, 2, self.d_model)							)







			def     snake_case__(					self			:    int							,       _UpperCamelCase			:    Tuple							,       _UpperCamelCase			:    Union[str, Any]							,       _UpperCamelCase			:    List[Any]							,       _UpperCamelCase			:    Union[str, Any]							,       _UpperCamelCase			:    Any							,       _UpperCamelCase			:    Any							,       _UpperCamelCase			:    Dict							,       _UpperCamelCase			:    Union[str, Any]							,       )				->List[Any]:
									snake_case_       =     self.num_labels
									snake_case_       =     FunnelForPreTraining(config=_UpperCamelCase							)
									model.to(_UpperCamelCase							)
									model.eval()
									snake_case_       =     model(_UpperCamelCase							,       attention_mask=_UpperCamelCase							,       token_type_ids=_UpperCamelCase							,       labels=_UpperCamelCase							)
									self.parent.assertEqual(result.logits.shape							,       (self.batch_size, self.seq_length)							)







			def     snake_case__(					self			:    Optional[Any]							,       _UpperCamelCase			:    List[str]							,       _UpperCamelCase			:    Optional[Any]							,       _UpperCamelCase			:    Dict							,       _UpperCamelCase			:    str							,       _UpperCamelCase			:    Any							,       _UpperCamelCase			:    Union[str, Any]							,       _UpperCamelCase			:    Any							,       _UpperCamelCase			:    List[str]							,       )				->List[Any]:
									snake_case_       =     FunnelForMaskedLM(config=_UpperCamelCase							)
									model.to(_UpperCamelCase							)
									model.eval()
									snake_case_       =     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			:    List[Any]							,       _UpperCamelCase			:    List[Any]							,       _UpperCamelCase			:    Union[str, Any]							,       _UpperCamelCase			:    List[Any]							,       _UpperCamelCase			:    str							,       _UpperCamelCase			:    Tuple							,       _UpperCamelCase			:    int							,       _UpperCamelCase			:    List[str]							,       _UpperCamelCase			:    Optional[int]							,       )				->int:
									snake_case_       =     self.num_labels
									snake_case_       =     FunnelForSequenceClassification(_UpperCamelCase							)
									model.to(_UpperCamelCase							)
									model.eval()
									snake_case_       =     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			:    Union[str, Any]							,       _UpperCamelCase			:    List[str]							,       _UpperCamelCase			:    Optional[int]							,       _UpperCamelCase			:    Dict							,       _UpperCamelCase			:    Optional[int]							,       _UpperCamelCase			:    Optional[Any]							,       _UpperCamelCase			:    int							,       _UpperCamelCase			:    Union[str, Any]							,       _UpperCamelCase			:    int							,       )				->List[str]:
									snake_case_       =     self.num_choices
									snake_case_       =     FunnelForMultipleChoice(config=_UpperCamelCase							)
									model.to(_UpperCamelCase							)
									model.eval()
									snake_case_       =     input_ids.unsqueeze(1							).expand(-1							,       self.num_choices							,       -1							).contiguous()
									snake_case_       =     token_type_ids.unsqueeze(1							).expand(-1							,       self.num_choices							,       -1							).contiguous()
									snake_case_       =     input_mask.unsqueeze(1							).expand(-1							,       self.num_choices							,       -1							).contiguous()
									snake_case_       =     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							,       _UpperCamelCase			:    Any							,       _UpperCamelCase			:    Union[str, Any]							,       _UpperCamelCase			:    Dict							,       _UpperCamelCase			:    Tuple							,       _UpperCamelCase			:    List[str]							,       _UpperCamelCase			:    int							,       _UpperCamelCase			:    Union[str, Any]							,       _UpperCamelCase			:    Dict							,       )				->Any:
									snake_case_       =     self.num_labels
									snake_case_       =     FunnelForTokenClassification(config=_UpperCamelCase							)
									model.to(_UpperCamelCase							)
									model.eval()
									snake_case_       =     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			:    Optional[int]							,       _UpperCamelCase			:    Dict							,       _UpperCamelCase			:    Optional[int]							,       _UpperCamelCase			:    Tuple							,       _UpperCamelCase			:    Dict							,       _UpperCamelCase			:    List[str]							,       _UpperCamelCase			:    Union[str, Any]							,       _UpperCamelCase			:    List[Any]							,       _UpperCamelCase			:    Union[str, Any]							,       )				->Tuple:
									snake_case_       =     FunnelForQuestionAnswering(config=_UpperCamelCase							)
									model.to(_UpperCamelCase							)
									model.eval()
									snake_case_       =     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			:    Optional[int]							)				->Dict:
									snake_case_       =     self.prepare_config_and_inputs()
									(
									    (
									    snake_case_
									),   (
									    snake_case_
									),   (
									    snake_case_
									),   (
									    snake_case_
									),   (
									    snake_case_
									),   (
									    snake_case_
									),   (
									    snake_case_
									),   (
									    snake_case_
									),   
									)       =     config_and_inputs
									snake_case_       =     {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
									return config, inputs_dict






@require_torch
class      snake_case_       (		__A     ,	__A     ,	unittest.TestCase ):







			'''simple docstring'''

			SCREAMING_SNAKE_CASE					:       Dict						      =    False
			SCREAMING_SNAKE_CASE					:       Dict						      =    False
			SCREAMING_SNAKE_CASE					:       Dict						      =    (
			    (
			        FunnelModel,
			        FunnelForMaskedLM,
			        FunnelForPreTraining,
			        FunnelForQuestionAnswering,
			        FunnelForTokenClassification,
			    )
			    if is_torch_available()
			    else ()
			)
			SCREAMING_SNAKE_CASE					:       int						      =    (
			    {
			        "feature-extraction": (FunnelBaseModel, FunnelModel),
			        "fill-mask": FunnelForMaskedLM,
			        "question-answering": FunnelForQuestionAnswering,
			        "text-classification": FunnelForSequenceClassification,
			        "token-classification": FunnelForTokenClassification,
			        "zero-shot": FunnelForSequenceClassification,
			    }
			    if is_torch_available()
			    else {}
			)







			def     snake_case__(					self			:    Dict							,       _UpperCamelCase			:    List[str]							,       _UpperCamelCase			:    Optional[int]							,       _UpperCamelCase			:    str=False							)				->int:
									snake_case_       =     super()._prepare_for_class(_UpperCamelCase							,       _UpperCamelCase							,       return_labels=_UpperCamelCase							)

									if return_labels:
															if model_class in get_values(_UpperCamelCase							):
																					snake_case_       =     torch.zeros(
																					    (self.model_tester.batch_size, self.model_tester.seq_length)							,       dtype=torch.long							,       device=_UpperCamelCase							)
									return inputs_dict







			def     snake_case__(					self			:    Optional[Any]							)				->Tuple:
									snake_case_       =     FunnelModelTester(self							)
									snake_case_       =     ConfigTester(self							,       config_class=_UpperCamelCase							)







			def     snake_case__(					self			:    str							)				->Any:
									self.config_tester.run_common_tests()







			def     snake_case__(					self			:    int							)				->Any:
									snake_case_       =     self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*_UpperCamelCase							)







			def     snake_case__(					self			:    Optional[int]							)				->List[str]:
									snake_case_       =     self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_pretraining(*_UpperCamelCase							)







			def     snake_case__(					self			:    List[str]							)				->int:
									snake_case_       =     self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_masked_lm(*_UpperCamelCase							)







			def     snake_case__(					self			:    Dict							)				->Any:
									snake_case_       =     self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_token_classification(*_UpperCamelCase							)







			def     snake_case__(					self			:    Dict							)				->List[Any]:
									snake_case_       =     self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_question_answering(*_UpperCamelCase							)







			def     snake_case__(					self			:    str							,       _UpperCamelCase			:    Optional[int]							)				->Optional[Any]:
									if hasattr(_UpperCamelCase							,       '''weight'''							) and module.weight is not None:
															module.weight.data.fill_(3							)
									if hasattr(_UpperCamelCase							,       '''bias'''							) and module.bias is not None:
															module.bias.data.fill_(3							)

									for param in ["r_w_bias", "r_r_bias", "r_kernel", "r_s_bias", "seg_embed"]:
															if hasattr(_UpperCamelCase							,       _UpperCamelCase							) and getattr(_UpperCamelCase							,       _UpperCamelCase							) is not None:
																					snake_case_       =     getattr(_UpperCamelCase							,       _UpperCamelCase							)
																					weight.data.fill_(3							)






@require_torch
class      snake_case_       (		__A     ,	unittest.TestCase ):







			'''simple docstring'''

			SCREAMING_SNAKE_CASE					:       Optional[int]						      =    False
			SCREAMING_SNAKE_CASE					:       str						      =    False
			SCREAMING_SNAKE_CASE					:       int						      =    (
			    (FunnelBaseModel, FunnelForMultipleChoice, FunnelForSequenceClassification) if is_torch_available() else ()
			)







			def     snake_case__(					self			:    Any							)				->Tuple:
									snake_case_       =     FunnelModelTester(self							,       base=_UpperCamelCase							)
									snake_case_       =     ConfigTester(self							,       config_class=_UpperCamelCase							)







			def     snake_case__(					self			:    Dict							)				->int:
									self.config_tester.run_common_tests()







			def     snake_case__(					self			:    List[str]							)				->Optional[int]:
									snake_case_       =     self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_base_model(*_UpperCamelCase							)







			def     snake_case__(					self			:    List[Any]							)				->Union[str, Any]:
									snake_case_       =     self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_sequence_classification(*_UpperCamelCase							)







			def     snake_case__(					self			:    Union[str, Any]							)				->List[Any]:
									snake_case_       =     self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_multiple_choice(*_UpperCamelCase							)







			def     snake_case__(					self			:    List[Any]							)				->List[Any]:
									snake_case_,   snake_case_       =     self.model_tester.prepare_config_and_inputs_for_common()
									snake_case_       =     True

									for model_class in self.all_model_classes:
															if model_class.__name__ == "FunnelBaseModel":
																					continue
															snake_case_       =     model_class(_UpperCamelCase							)
															model.to(_UpperCamelCase							)
															model.train()
															snake_case_       =     self._prepare_for_class(_UpperCamelCase							,       _UpperCamelCase							,       return_labels=_UpperCamelCase							)
															snake_case_       =     model(**_UpperCamelCase							).loss
															loss.backward()







			def     snake_case__(					self			:    Tuple							,       _UpperCamelCase			:    Dict							)				->str:
									if hasattr(_UpperCamelCase							,       '''weight'''							) and module.weight is not None:
															module.weight.data.fill_(3							)
									if hasattr(_UpperCamelCase							,       '''bias'''							) and module.bias is not None:
															module.bias.data.fill_(3							)

									for param in ["r_w_bias", "r_r_bias", "r_kernel", "r_s_bias", "seg_embed"]:
															if hasattr(_UpperCamelCase							,       _UpperCamelCase							) and getattr(_UpperCamelCase							,       _UpperCamelCase							) is not None:
																					snake_case_       =     getattr(_UpperCamelCase							,       _UpperCamelCase							)
																					weight.data.fill_(3							)






@require_torch
@require_sentencepiece
@require_tokenizers
class      snake_case_       (		unittest.TestCase ):







			'''simple docstring'''

			def     snake_case__(					self			:    str							)				->Union[str, Any]:
									snake_case_       =     1_3
									snake_case_       =     7
									snake_case_       =     torch.arange(0							,       batch_size * sequence_length							).long().reshape(_UpperCamelCase							,       _UpperCamelCase							)
									snake_case_       =     [0, 1, 2, 3, 4, 5, 6, 4, 1, 3, 5, 0, 1]
									snake_case_       =     torch.tensor([[2] + [0] * a + [1] * (sequence_length - a - 1) for a in lengths]							)

									snake_case_       =     FunnelModel.from_pretrained('''sgugger/funnel-random-tiny'''							)
									snake_case_       =     model(_UpperCamelCase							,       token_type_ids=_UpperCamelCase							)[0].abs()

									snake_case_       =     torch.tensor(2344.8352							)
									snake_case_       =     torch.tensor(0.8052							)
									self.assertTrue(torch.allclose(output.sum()							,       _UpperCamelCase							,       atol=1e-4							)							)
									self.assertTrue(torch.allclose(output.mean()							,       _UpperCamelCase							,       atol=1e-4							)							)

									snake_case_       =     torch.tensor([[1] * 7, [1] * 4 + [0] * 3] * 6 + [[0, 1, 1, 0, 0, 1, 1]]							)
									snake_case_       =     model(_UpperCamelCase							,       attention_mask=_UpperCamelCase							,       token_type_ids=_UpperCamelCase							)[0].abs()

									snake_case_       =     torch.tensor(2343.8425							)
									snake_case_       =     torch.tensor(0.8049							)
									self.assertTrue(torch.allclose(output.sum()							,       _UpperCamelCase							,       atol=1e-4							)							)
									self.assertTrue(torch.allclose(output.mean()							,       _UpperCamelCase							,       atol=1e-4							)							)







			@slow
			def     snake_case__(					self			:    Any							)				->Dict:
									snake_case_       =     FunnelTokenizer.from_pretrained('''huggingface/funnel-small'''							)
									snake_case_       =     FunnelModel.from_pretrained('''huggingface/funnel-small'''							)
									snake_case_       =     tokenizer('''Hello! I am the Funnel Transformer model.'''							,       return_tensors='''pt'''							)
									snake_case_       =     model(**_UpperCamelCase							)[0]

									snake_case_       =     torch.tensor(235.7246							)
									snake_case_       =     torch.tensor(0.0256							)
									self.assertTrue(torch.allclose(output.sum()							,       _UpperCamelCase							,       atol=1e-4							)							)
									self.assertTrue(torch.allclose(output.mean()							,       _UpperCamelCase							,       atol=1e-4							)							)


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      snake_case_       (		__A     ,	unittest.TestCase ):







			'''simple docstring'''

			SCREAMING_SNAKE_CASE					:       str						      =    PreTrainedTokenizerFast
			SCREAMING_SNAKE_CASE					:       List[str]						      =    False
			SCREAMING_SNAKE_CASE					:       Tuple						      =    True
			SCREAMING_SNAKE_CASE					:       str						      =    "tokenizer_file"







			def     snake_case__(					self			:    Dict							)				->int:
									snake_case_       =     False  # because we don't have pretrained_vocab_files_map
									super().setUp()
									snake_case_       =     True

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

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

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







			def     snake_case__(					self			:    Union[str, Any]							)				->Dict:
									# We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
									# model
									pass







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







			def     snake_case__(					self			:    List[Any]							)				->str:
									# We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any
									# model
									pass







			def     snake_case__(					self			:    str							)				->List[Any]:
									# PreTrainedTokenizerFast doesn't have tokenizer_file in its signature
									pass







			def     snake_case__(					self			:    Any							)				->Union[str, Any]:
									snake_case_       =     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:
																											snake_case_       =     tempfile.mkdtemp()
																											snake_case_       =     self.rust_tokenizer_class.from_pretrained(_UpperCamelCase							,       **_UpperCamelCase							)

																											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							)
																											snake_case_       =     tmpdirname_orig







			def     snake_case__(					self			:    List[str]							)				->List[Any]:
									snake_case_       =     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:
																											snake_case_       =     tempfile.mkdtemp()
																											snake_case_       =     self.rust_tokenizer_class.from_pretrained(_UpperCamelCase							,       **_UpperCamelCase							)

																											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							)
																											snake_case_       =     tmpdirname_orig







			def     snake_case__(					self			:    Optional[int]							)				->Optional[Any]:
									snake_case_       =     self.rust_tokenizer_class.from_pretrained(self.bytelevel_bpe_model_name							)

									snake_case_       =     ('''a''' for _ in range(1_0_0_0							))
									snake_case_       =     tokenizer.train_new_from_iterator(text_iterator=_UpperCamelCase							,       length=1_0_0_0							,       vocab_size=5_0							)

									snake_case_       =     new_tokenizer.encode('''a🤗'''							)
									self.assertEqual(_UpperCamelCase							,       [6_4, 1_7_2, 2_5_3, 9_7, 2_4_5]							)






@require_tokenizers
class      snake_case_       (		unittest.TestCase ):







			'''simple docstring'''

			def     snake_case__(					self			:    Optional[int]							)				->int:
									snake_case_       =     AutoTokenizer.from_pretrained('''bert-base-cased'''							)
									snake_case_       =     json.loads(tokenizer._tokenizer.to_str()							)
									snake_case_       =     len(_UpperCamelCase							)

									with tempfile.TemporaryDirectory() as tmp_dir:
															# Hack to save this in the tokenizer_config.json
															snake_case_       =     ['''tokenizer.4.0.0.json''']
															tokenizer.save_pretrained(_UpperCamelCase							)
															json.dump(_UpperCamelCase							,       open(os.path.join(_UpperCamelCase							,       '''tokenizer.4.0.0.json'''							)							,       '''w'''							)							)

															# This should pick the new tokenizer file as the version of Transformers is > 4.0.0
															snake_case_       =     AutoTokenizer.from_pretrained(_UpperCamelCase							)
															self.assertEqual(len(_UpperCamelCase							)							,       len(_UpperCamelCase							) + 1							)
															snake_case_       =     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(_UpperCamelCase							,       '''tokenizer.4.0.0.json'''							)							,       os.path.join(_UpperCamelCase							,       '''tokenizer.42.0.0.json'''							)							)
															snake_case_       =     ['''tokenizer.42.0.0.json''']
															tokenizer.save_pretrained(_UpperCamelCase							)
															snake_case_       =     AutoTokenizer.from_pretrained(_UpperCamelCase							)
															self.assertEqual(len(_UpperCamelCase							)							,       len(_UpperCamelCase							)							)
															snake_case_       =     json.loads(new_tokenizer._tokenizer.to_str()							)
															self.assertNotIn('''huggingface'''							,       json_tokenizer['''model''']['''vocab''']							)







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

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

									snake_case_       =     '''3.0.0'''
									snake_case_       =     old_transformers.models.auto.AutoTokenizer.from_pretrained(_UpperCamelCase							)
									self.assertEqual(len(_UpperCamelCase							)							,       2_8_9_9_6							)
									snake_case_       =     json.loads(old_tokenizer._tokenizer.to_str()							)
									self.assertNotIn('''huggingface'''							,       json_tokenizer['''model''']['''vocab''']							)






@require_tokenizers
class      snake_case_       (		unittest.TestCase ):







			'''simple docstring'''

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

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







			def     snake_case__(					self			:    Optional[int]							,       _UpperCamelCase			:    Dict							,       _UpperCamelCase			:    str							)				->Tuple:
									return tokenizer.encode(_UpperCamelCase							,       truncation='''longest_first'''							,       padding='''longest'''							)