
'''simple docstring'''




import unittest
from pathlib import Path
from tempfile import TemporaryDirectory

from transformers import AutoConfig, TFAutoModel, is_tensorflow_text_available, is_tf_available
from transformers.models.bert.tokenization_bert import BertTokenizer
from transformers.testing_utils import require_tensorflow_text, require_tf, slow


if is_tf_available():
      import tensorflow as tf

if is_tensorflow_text_available():
      from transformers.models.bert import TFBertTokenizer


lowercase     :							Optional[int]       						=     ['bert-base-uncased', 'bert-base-cased']
lowercase     :							Optional[Any]       						=     'hf-internal-testing/tiny-bert-tf-only'

if is_tf_available():





      class 					A							(				tf.keras.Model		):





           def __init__(				self		,     SCREAMING_SNAKE_CASE      )					->							Any:






               """simple docstring"""






               super().__init__()
               A			:  str   =		tokenizer
               A			:  int   =		AutoConfig.from_pretrained(SCREAMING_SNAKE_CASE      )
               A			:  str   =		TFAutoModel.from_config(SCREAMING_SNAKE_CASE      )





           def 							__lowerCAmelCase				(				self		,     SCREAMING_SNAKE_CASE      )					->							Any:






               """simple docstring"""






               A			:  List[str]   =		self.tokenizer(SCREAMING_SNAKE_CASE      )
               A			:  List[Any]   =		self.bert(**SCREAMING_SNAKE_CASE      )
               return out["pooler_output"]





@require_tf
@require_tensorflow_text
class 					A							(				unittest.TestCase		):





     def 							__lowerCAmelCase				(				self      )					->							List[Any]:






         """simple docstring"""






         super().setUp()

         A			:  Union[str, Any]   =		[
             BertTokenizer.from_pretrained(SCREAMING_SNAKE_CASE      ) for checkpoint in (TOKENIZER_CHECKPOINTS * 2)
         ]  # repeat for when fast_bert_tokenizer=false
         A			:  List[str]   =		[TFBertTokenizer.from_pretrained(SCREAMING_SNAKE_CASE      ) for checkpoint in TOKENIZER_CHECKPOINTS] + [
             TFBertTokenizer.from_pretrained(SCREAMING_SNAKE_CASE		,     use_fast_bert_tokenizer=SCREAMING_SNAKE_CASE      )
             for checkpoint in TOKENIZER_CHECKPOINTS
         ]
         assert len(self.tokenizers      ) == len(self.tf_tokenizers      )

         A			:  Any   =		[
             '''This is a straightforward English test sentence.''',
             '''This one has some weird characters\rto\nsee\r\nif  those\u00E9break things.''',
             '''Now we\'re going to add some Chinese: 一 二 三 一二三''',
             '''And some much more rare Chinese: 齉 堃 齉堃''',
             '''Je vais aussi écrire en français pour tester les accents''',
             '''Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ''',
         ]
         A			:  List[Any]   =		list(zip(self.test_sentences		,     self.test_sentences[::-1]      )      )





     def 							__lowerCAmelCase				(				self      )					->							List[Any]:






         """simple docstring"""






         for tokenizer, tf_tokenizer in zip(self.tokenizers		,     self.tf_tokenizers      ):
             for test_inputs in (self.test_sentences, self.paired_sentences):
                 A			:  Dict   =		tokenizer(SCREAMING_SNAKE_CASE		,     return_tensors='''tf'''		,     padding='''longest'''      )
                 A			:  Union[str, Any]   =		tf_tokenizer(SCREAMING_SNAKE_CASE      )

                 for key in python_outputs.keys():
                     self.assertTrue(tf.reduce_all(python_outputs[key].shape == tf_outputs[key].shape      )      )
                     self.assertTrue(tf.reduce_all(tf.cast(python_outputs[key]		,     tf.intaa      ) == tf_outputs[key]      )      )





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






         """simple docstring"""






         for tf_tokenizer in self.tf_tokenizers:
             A			:  Tuple   =		tf_tokenizer(self.paired_sentences      )
             A			:  str   =		tf_tokenizer(
                 text=[sentence[0] for sentence in self.paired_sentences]		,     text_pair=[sentence[1] for sentence in self.paired_sentences]		,     )
             for key in merged_outputs.keys():
                 self.assertTrue(tf.reduce_all(tf.cast(merged_outputs[key]		,     tf.intaa      ) == separated_outputs[key]      )      )





     @slow
     def 							__lowerCAmelCase				(				self      )					->							Union[str, Any]:






         """simple docstring"""






         for tf_tokenizer in self.tf_tokenizers:
             A			:  str   =		tf.function(SCREAMING_SNAKE_CASE      )
             for test_inputs in (self.test_sentences, self.paired_sentences):
                 A			:  List[str]   =		tf.constant(SCREAMING_SNAKE_CASE      )
                 A			:  Tuple   =		compiled_tokenizer(SCREAMING_SNAKE_CASE      )
                 A			:  Union[str, Any]   =		tf_tokenizer(SCREAMING_SNAKE_CASE      )

                 for key in eager_outputs.keys():
                     self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key]      )      )





     @slow
     def 							__lowerCAmelCase				(				self      )					->							Dict:






         """simple docstring"""






         for tf_tokenizer in self.tf_tokenizers:
             A			:  List[str]   =		ModelToSave(tokenizer=SCREAMING_SNAKE_CASE      )
             A			:  int   =		tf.convert_to_tensor(self.test_sentences      )
             A			:  Any   =		model(SCREAMING_SNAKE_CASE      )  # Build model with some sample inputs
             with TemporaryDirectory() as tempdir:
                 A			:  Any   =		Path(SCREAMING_SNAKE_CASE      ) / '''saved.model'''
                 model.save(SCREAMING_SNAKE_CASE      )
                 A			:  Union[str, Any]   =		tf.keras.models.load_model(SCREAMING_SNAKE_CASE      )
             A			:  Union[str, Any]   =		loaded_model(SCREAMING_SNAKE_CASE      )
             # We may see small differences because the loaded model is compiled, so we need an epsilon for the test
             self.assertLessEqual(tf.reduce_max(tf.abs(out - loaded_output      )      )		,     1e-5      )






'''simple docstring'''




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


lowercase     :							List[str]       						=     logging.get_logger(__name__)

lowercase     :							Optional[int]       						=     {
    'google/switch-base-8': 'https://huggingface.co/google/switch-base-8/blob/main/config.json',
}





class 					A							(				__snake_case		):
     __magic_name__          =						'''switch_transformers'''
     __magic_name__          =						['''past_key_values''']
     __magic_name__          =						{'''hidden_size''': '''d_model''', '''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''}





     def __init__(				self		,     SCREAMING_SNAKE_CASE=32128		,     SCREAMING_SNAKE_CASE=768		,     SCREAMING_SNAKE_CASE=64		,     SCREAMING_SNAKE_CASE=2048		,     SCREAMING_SNAKE_CASE=64		,     SCREAMING_SNAKE_CASE=12		,     SCREAMING_SNAKE_CASE=3		,     SCREAMING_SNAKE_CASE=12		,     SCREAMING_SNAKE_CASE=3		,     SCREAMING_SNAKE_CASE=12		,     SCREAMING_SNAKE_CASE=8		,     SCREAMING_SNAKE_CASE=False		,     SCREAMING_SNAKE_CASE=0.01		,     SCREAMING_SNAKE_CASE="float32"		,     SCREAMING_SNAKE_CASE=False		,     SCREAMING_SNAKE_CASE=32		,     SCREAMING_SNAKE_CASE=128		,     SCREAMING_SNAKE_CASE=0.1		,     SCREAMING_SNAKE_CASE=1e-6		,     SCREAMING_SNAKE_CASE=0.001		,     SCREAMING_SNAKE_CASE=0.001		,     SCREAMING_SNAKE_CASE=1.0		,     SCREAMING_SNAKE_CASE="relu"		,     SCREAMING_SNAKE_CASE=True		,     SCREAMING_SNAKE_CASE=False		,     SCREAMING_SNAKE_CASE=True		,     SCREAMING_SNAKE_CASE=0		,     SCREAMING_SNAKE_CASE=1		,     **SCREAMING_SNAKE_CASE		,     )					->							List[Any]:






         """simple docstring"""






         A			:  Union[str, Any]   =		vocab_size
         A			:  Any   =		d_model
         A			:  Dict   =		d_kv
         A			:  Optional[Any]   =		d_ff

         A			:  List[Any]   =		num_sparse_encoder_layers

         A			:  List[Any]   =		num_layers
         A			:  Optional[int]   =		(
             num_decoder_layers if num_decoder_layers is not None else self.num_layers
         )  # default = symmetry
         A			:  List[str]   =		num_sparse_decoder_layers

         # This tells us, each how many encoder layer we'll have to set a sparse layer.
         if self.num_sparse_encoder_layers > 0:
             A			:  int   =		self.num_layers // self.num_sparse_encoder_layers
         else:
             A			:  int   =		self.num_layers  # HACK: this will create 0 sparse layers

         # This tells us, each how many encoder layer we'll have to set a sparse layer.
         if self.num_sparse_decoder_layers > 0:
             A			:  str   =		self.num_decoder_layers // self.num_sparse_decoder_layers
         else:
             A			:  Dict   =		self.num_decoder_layers  # HACK: this will create 0 sparse layers

         A			:  List[Any]   =		num_heads
         A			:  str   =		num_experts
         A			:  Dict   =		expert_capacity
         A			:  Optional[int]   =		router_bias
         A			:  Any   =		router_jitter_noise
         if router_dtype not in ["float32", "float16", "bfloat16"]:
             raise ValueError(F'`router_dtype` must be one of \'float32\', \'float16\' or \'bfloat16\', got {router_dtype}'      )
         A			:  Dict   =		router_dtype

         A			:  int   =		router_ignore_padding_tokens
         A			:  List[Any]   =		relative_attention_num_buckets
         A			:  Dict   =		relative_attention_max_distance

         A			:  Optional[int]   =		dropout_rate
         A			:  Dict   =		layer_norm_epsilon
         A			:  Optional[int]   =		initializer_factor
         A			:  Union[str, Any]   =		feed_forward_proj
         A			:  Any   =		use_cache
         A			:  Tuple   =		add_router_probs

         A			:  List[str]   =		router_z_loss_coef
         A			:  str   =		router_aux_loss_coef

         A			:  Union[str, Any]   =		self.feed_forward_proj.split('''-'''      )
         A			:  Optional[Any]   =		act_info[-1]
         A			:  Union[str, Any]   =		act_info[0] == '''gated'''

         if len(SCREAMING_SNAKE_CASE      ) > 1 and act_info[0] != "gated" or len(SCREAMING_SNAKE_CASE      ) > 2:
             raise ValueError(
                 F'`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.'
                 '''Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. '''
                 '''\'gated-gelu\' or \'relu\''''      )

         # for backwards compatibility
         if feed_forward_proj == "gated-gelu":
             A			:  str   =		'''gelu_new'''

         super().__init__(
             pad_token_id=SCREAMING_SNAKE_CASE		,     eos_token_id=SCREAMING_SNAKE_CASE		,     is_encoder_decoder=SCREAMING_SNAKE_CASE		,     **SCREAMING_SNAKE_CASE		,     )




