


from __future__ import annotations

import random
import unittest

from transformers import TransfoXLConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
      import tensorflow as tf

      from transformers import (
          TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST,
          TFTransfoXLForSequenceClassification,
          TFTransfoXLLMHeadModel,
          TFTransfoXLModel,
      )





class   SCREAMING_SNAKE_CASE_			:




       '''simple docstring'''



       def __init__(						self				:				str		,				__a				:				str		,				)					->Optional[Any]:
          lowerCamelCase_						:   List[str]		= parent
          lowerCamelCase_						:   str		= 13
          lowerCamelCase_						:   Union[str, Any]		= 7
          lowerCamelCase_						:   int		= 30
          lowerCamelCase_						:   int		= self.seq_length + self.mem_len
          lowerCamelCase_						:   str		= 15
          lowerCamelCase_						:   Dict		= True
          lowerCamelCase_						:   List[str]		= True
          lowerCamelCase_						:   Dict		= 99
          lowerCamelCase_						:   Tuple		= [10, 50, 80]
          lowerCamelCase_						:   Optional[Any]		= 32
          lowerCamelCase_						:   Union[str, Any]		= 32
          lowerCamelCase_						:   Optional[Any]		= 4
          lowerCamelCase_						:   Union[str, Any]		= 8
          lowerCamelCase_						:   Optional[int]		= 128
          lowerCamelCase_						:   Tuple		= 2
          lowerCamelCase_						:   List[str]		= 2
          lowerCamelCase_						:   Union[str, Any]		= None
          lowerCamelCase_						:   Union[str, Any]		= 1
          lowerCamelCase_						:   Any		= 0
          lowerCamelCase_						:   Optional[Any]		= 3
          lowerCamelCase_						:   Optional[int]		= self.vocab_size - 1
          lowerCamelCase_						:   str		= 0.01



       def 				_lowerCAmelCase							(						self				:				List[str]							)					->List[str]:
          lowerCamelCase_						:   List[Any]		= ids_tensor([self.batch_size, self.seq_length]		,				self.vocab_size							)
          lowerCamelCase_						:   List[Any]		= ids_tensor([self.batch_size, self.seq_length]		,				self.vocab_size							)

          lowerCamelCase_						:   int		= None
          if self.use_labels:
             lowerCamelCase_						:   List[str]		= ids_tensor([self.batch_size, self.seq_length]		,				self.vocab_size							)

          lowerCamelCase_						:   int		= TransfoXLConfig(
              vocab_size=self.vocab_size		,				mem_len=self.mem_len		,				clamp_len=self.clamp_len		,				cutoffs=self.cutoffs		,				d_model=self.hidden_size		,				d_embed=self.d_embed		,				n_head=self.num_attention_heads		,				d_head=self.d_head		,				d_inner=self.d_inner		,				div_val=self.div_val		,				n_layer=self.num_hidden_layers		,				eos_token_id=self.eos_token_id		,				pad_token_id=self.vocab_size - 1		,				init_range=self.init_range		,				num_labels=self.num_labels		,				)

          return (config, input_ids_a, input_ids_a, lm_labels)



       def 				_lowerCAmelCase							(						self				:				Any							)					->str:
          random.seed(self.seed							)
          tf.random.set_seed(self.seed							)



       def 				_lowerCAmelCase							(						self				:				Union[str, Any]		,				__a				:				Dict		,				__a				:				Tuple		,				__a				:				List[str]		,				__a				:				Any							)					->List[str]:
          lowerCamelCase_						:   Any		= TFTransfoXLModel(__a							)

          lowerCamelCase_,	lowerCamelCase_						:   Dict		= model(__a							).to_tuple()

          lowerCamelCase_						:   Optional[Any]		= {"""input_ids""": input_ids_a, """mems""": mems_a}

          lowerCamelCase_,	lowerCamelCase_						:   List[Any]		= model(__a							).to_tuple()

          self.parent.assertEqual(hidden_states_a.shape		,				(self.batch_size, self.seq_length, self.hidden_size)							)
          self.parent.assertEqual(hidden_states_a.shape		,				(self.batch_size, self.seq_length, self.hidden_size)							)
          self.parent.assertListEqual(
              [mem.shape for mem in mems_a]		,				[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers		,				)
          self.parent.assertListEqual(
              [mem.shape for mem in mems_a]		,				[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers		,				)



       def 				_lowerCAmelCase							(						self				:				str		,				__a				:				Any		,				__a				:				str		,				__a				:				Dict		,				__a				:				List[str]							)					->Optional[Any]:
          lowerCamelCase_						:   Tuple		= TFTransfoXLLMHeadModel(__a							)

          lowerCamelCase_,	lowerCamelCase_						:   List[str]		= model(__a							).to_tuple()

          lowerCamelCase_						:   int		= {"""input_ids""": input_ids_a, """labels""": lm_labels}
          lowerCamelCase_,	lowerCamelCase_						:   Any		= model(__a							).to_tuple()

          lowerCamelCase_,	lowerCamelCase_						:   int		= model([input_ids_a, mems_a]							).to_tuple()

          lowerCamelCase_						:   Dict		= {"""input_ids""": input_ids_a, """mems""": mems_a, """labels""": lm_labels}

          lowerCamelCase_,	lowerCamelCase_						:   int		= model(__a							).to_tuple()

          self.parent.assertEqual(lm_logits_a.shape		,				(self.batch_size, self.seq_length, self.vocab_size)							)
          self.parent.assertListEqual(
              [mem.shape for mem in mems_a]		,				[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers		,				)

          self.parent.assertEqual(lm_logits_a.shape		,				(self.batch_size, self.seq_length, self.vocab_size)							)
          self.parent.assertListEqual(
              [mem.shape for mem in mems_a]		,				[(self.mem_len, self.batch_size, self.hidden_size)] * self.num_hidden_layers		,				)



       def 				_lowerCAmelCase							(						self				:				Optional[int]		,				__a				:				int		,				__a				:				Dict		,				__a				:				List[Any]		,				__a				:				List[str]							)					->Optional[int]:
          lowerCamelCase_						:   Any		= TFTransfoXLForSequenceClassification(__a							)
          lowerCamelCase_						:   str		= model(__a							)
          self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.num_labels)							)




       def 				_lowerCAmelCase							(						self				:				Any							)					->List[str]:
          lowerCamelCase_						:   List[str]		= self.prepare_config_and_inputs()
          ((lowerCamelCase_),	(lowerCamelCase_),	(lowerCamelCase_),	(lowerCamelCase_))						:   Any		= config_and_inputs
          lowerCamelCase_						:   int		= {"""input_ids""": input_ids_a}
          return config, inputs_dict







@require_tf
class   SCREAMING_SNAKE_CASE_			(a__						,       a__						,       unittest.TestCase						):




       '''simple docstring'''



       _a   							=							(
           (TFTransfoXLModel, TFTransfoXLLMHeadModel, TFTransfoXLForSequenceClassification) if is_tf_available() else ()
       )
       _a   							=							() if is_tf_available() else ()
       _a   							=							(
           {
               "feature-extraction": TFTransfoXLModel,
               "text-classification": TFTransfoXLForSequenceClassification,
               "text-generation": TFTransfoXLLMHeadModel,
               "zero-shot": TFTransfoXLForSequenceClassification,
           }
           if is_tf_available()
           else {}
       )
       # TODO: add this test when TFTransfoXLLMHead has a linear output layer implemented
       _a   							=							False
       _a   							=							False
       _a   							=							False
       _a   							=							False



       def 				_lowerCAmelCase							(						self				:				Any		,				__a				:				Union[str, Any]		,				__a				:				Optional[Any]		,				__a				:				Dict		,				__a				:				Dict		,				__a				:				Optional[Any]							)					->Tuple:
          if pipeline_test_casse_name == "TextGenerationPipelineTests":
             # Get `ValueError: AttributeError: 'NoneType' object has no attribute 'new_ones'` or `AssertionError`.
             # `TransfoXLConfig` was never used in pipeline tests: cannot create a simple
             # tokenizer.
             return True

          return False



       def 				_lowerCAmelCase							(						self				:				Any							)					->Dict:
          lowerCamelCase_						:   List[Any]		= TFTransfoXLModelTester(self							)
          lowerCamelCase_						:   int		= ConfigTester(self		,				config_class=__a		,				d_embed=37							)



       def 				_lowerCAmelCase							(						self				:				Optional[int]							)					->str:
          self.config_tester.run_common_tests()



       def 				_lowerCAmelCase							(						self				:				Optional[Any]							)					->Dict:
          self.model_tester.set_seed()
          lowerCamelCase_						:   Dict		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_transfo_xl_model(*__a							)



       def 				_lowerCAmelCase							(						self				:				Union[str, Any]							)					->Dict:
          self.model_tester.set_seed()
          lowerCamelCase_						:   List[Any]		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_transfo_xl_lm_head(*__a							)



       def 				_lowerCAmelCase							(						self				:				Dict							)					->Dict:
          lowerCamelCase_						:   Any		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_transfo_xl_for_sequence_classification(*__a							)



       def 				_lowerCAmelCase							(						self				:				str							)					->List[Any]:
          lowerCamelCase_,	lowerCamelCase_						:   str		= self.model_tester.prepare_config_and_inputs_for_common()
          lowerCamelCase_						:   List[Any]		= [TFTransfoXLForSequenceClassification]

          for model_class in self.all_model_classes:
             lowerCamelCase_						:   List[str]		= model_class(__a							)
             assert isinstance(model.get_input_embeddings()		,				tf.keras.layers.Layer							)
             if model_class in list_other_models_with_output_ebd:
                lowerCamelCase_						:   Optional[int]		= model.get_output_embeddings()
                assert isinstance(__a		,				tf.keras.layers.Layer							)
                lowerCamelCase_						:   Optional[Any]		= model.get_bias()
                assert name is None
             else:
                lowerCamelCase_						:   Optional[Any]		= model.get_output_embeddings()
                assert x is None
                lowerCamelCase_						:   str		= model.get_bias()
                assert name is None



       def 				_lowerCAmelCase							(						self				:				Optional[Any]							)					->Any:
          # TODO JP: Make TransfoXL XLA compliant
          pass



       @slow
       def 				_lowerCAmelCase							(						self				:				int							)					->int:
          for model_name in TF_TRANSFO_XL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             lowerCamelCase_						:   List[Any]		= TFTransfoXLModel.from_pretrained(__a							)
             self.assertIsNotNone(__a							)




       @unittest.skip(reason="""This model doesn't play well with fit() due to not returning a single loss."""							)
       def 				_lowerCAmelCase							(						self				:				Dict							)					->Dict:
          pass







@require_tf
class   SCREAMING_SNAKE_CASE_			(unittest.TestCase						):




       '''simple docstring'''



       @unittest.skip("""Skip test until #12651 is resolved."""							)
       @slow
       def 				_lowerCAmelCase							(						self				:				Tuple							)					->Optional[Any]:
          lowerCamelCase_						:   Tuple		= TFTransfoXLLMHeadModel.from_pretrained("""transfo-xl-wt103"""							)
          # fmt: off
          lowerCamelCase_						:   int		= tf.convert_to_tensor([[33,1_297,2,1,1_009,4,1_109,11_739,4_762,358,5,25,245,22,1_706,17,20_098,5,3_215,21,37,1_110,3,13,1_041,4,24,603,490,2,71_477,20_098,104_447,2,20_961,1,2_604,4,1,329,3,6_224,831,16_002,2,8,603,78_967,29_546,23,803,20,25,416,5,8,232,4,277,6,1_855,4_601,3,29_546,54,8,3_609,5,57_211,49,4,1,277,18,8,1_755,15_691,3,341,25,416,693,42_573,71,17,401,94,31,17_919,2,29_546,7_873,18,1,435,23,11_011,755,5,5_167,3,7_983,98,84,2,29_546,3_267,8,3_609,4,1,4_865,1_075,2,6_087,71,6,346,8,5_854,3,29_546,824,1_400,1_868,2,19,160,2,311,8,5_496,2,20_920,17,25,15_097,3,24,24,0]]		,				dtype=tf.intaa							)  # noqa: E231
          # fmt: on
          #  In 1991 , the remains of Russian Tsar Nicholas II and his family
          #  ( except for Alexei and Maria ) are discovered .
          #  The voice of Nicholas's young son , Tsarevich Alexei Nikolaevich , narrates the
          #  remainder of the story . 1883 Western Siberia ,
          #  a young Grigori Rasputin is asked by his father and a group of men to perform magic .
          #  Rasputin has a vision and denounces one of the men as a horse thief . Although his
          #  father initially slaps him for making such an accusation , Rasputin watches as the
          #  man is chased outside and beaten . Twenty years later , Rasputin sees a vision of
          #  the Virgin Mary , prompting him to become a priest . Rasputin quickly becomes famous ,
          #  with people , even a bishop , begging for his blessing . <eod> </s> <eos>

          # fmt: off
          lowerCamelCase_						:   Any		= [33,1_297,2,1,1_009,4,1_109,11_739,4_762,358,5,25,245,22,1_706,17,20_098,5,3_215,21,37,1_110,3,13,1_041,4,24,603,490,2,71_477,20_098,104_447,2,20_961,1,2_604,4,1,329,3,6_224,831,16_002,2,8,603,78_967,29_546,23,803,20,25,416,5,8,232,4,277,6,1_855,4_601,3,29_546,54,8,3_609,5,57_211,49,4,1,277,18,8,1_755,15_691,3,341,25,416,693,42_573,71,17,401,94,31,17_919,2,29_546,7_873,18,1,435,23,11_011,755,5,5_167,3,7_983,98,84,2,29_546,3_267,8,3_609,4,1,4_865,1_075,2,6_087,71,6,346,8,5_854,3,29_546,824,1_400,1_868,2,19,160,2,311,8,5_496,2,20_920,17,25,15_097,3,24,24,0,33,1,1_857,2,1,1_009,4,1_109,11_739,4_762,358,5,25,245,28,1_110,3,13,1_041,4,24,603,490,2,71_477,20_098,104_447,2,20_961,1,2_604,4,1,329,3,0]  # noqa: E231
          # fmt: on
          #  In 1991, the remains of Russian Tsar Nicholas II and his family (
          #  except for Alexei and Maria ) are discovered. The voice of young son,
          #  Tsarevich Alexei Nikolaevich, narrates the remainder of the story.
          #  1883 Western Siberia, a young Grigori Rasputin is asked by his father
          #  and a group of men to perform magic. Rasputin has a vision and
          #  denounces one of the men as a horse thief. Although his father initially
          #  slaps him for making such an accusation, Rasputin watches as the man
          #  is chased outside and beaten. Twenty years later, Rasputin sees a vision
          #  of the Virgin Mary, prompting him to become a priest.
          #  Rasputin quickly becomes famous, with people, even a bishop, begging for
          #  his blessing. <unk> <unk> <eos> In the 1990s, the remains of Russian Tsar
          # Nicholas II and his family were discovered. The voice of <unk> young son,
          # Tsarevich Alexei Nikolaevich, narrates the remainder of the story.<eos>

          lowerCamelCase_						:   str		= model.generate(__a		,				max_length=200		,				do_sample=__a							)
          self.assertListEqual(output_ids[0].numpy().tolist()		,				__a							)









import unittest

from transformers import MobileBertConfig, 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, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import (
          MODEL_FOR_PRETRAINING_MAPPING,
          MobileBertForMaskedLM,
          MobileBertForMultipleChoice,
          MobileBertForNextSentencePrediction,
          MobileBertForPreTraining,
          MobileBertForQuestionAnswering,
          MobileBertForSequenceClassification,
          MobileBertForTokenClassification,
          MobileBertModel,
      )





class   SCREAMING_SNAKE_CASE_			:




       '''simple docstring'''



       def __init__(						self				:				Optional[Any]		,				__a				:				int		,				__a				:				str=13		,				__a				:				Tuple=7		,				__a				:				int=True		,				__a				:				int=True		,				__a				:				Dict=True		,				__a				:				str=True		,				__a				:				List[str]=99		,				__a				:				Dict=64		,				__a				:				Optional[Any]=32		,				__a				:				List[Any]=5		,				__a				:				Optional[int]=4		,				__a				:				str=37		,				__a				:				str="gelu"		,				__a				:				Optional[Any]=0.1		,				__a				:				Union[str, Any]=0.1		,				__a				:				int=512		,				__a				:				Optional[Any]=16		,				__a				:				Any=2		,				__a				:				Dict=0.02		,				__a				:				str=3		,				__a				:				List[Any]=4		,				__a				:				List[str]=None		,				)					->Optional[int]:
          lowerCamelCase_						:   Dict		= parent
          lowerCamelCase_						:   Optional[Any]		= batch_size
          lowerCamelCase_						:   Any		= seq_length
          lowerCamelCase_						:   Union[str, Any]		= is_training
          lowerCamelCase_						:   int		= use_input_mask
          lowerCamelCase_						:   int		= use_token_type_ids
          lowerCamelCase_						:   int		= use_labels
          lowerCamelCase_						:   List[str]		= vocab_size
          lowerCamelCase_						:   Any		= hidden_size
          lowerCamelCase_						:   Any		= embedding_size
          lowerCamelCase_						:   int		= num_hidden_layers
          lowerCamelCase_						:   Union[str, Any]		= num_attention_heads
          lowerCamelCase_						:   Optional[Any]		= intermediate_size
          lowerCamelCase_						:   Optional[int]		= hidden_act
          lowerCamelCase_						:   Dict		= hidden_dropout_prob
          lowerCamelCase_						:   Any		= attention_probs_dropout_prob
          lowerCamelCase_						:   Optional[int]		= max_position_embeddings
          lowerCamelCase_						:   Dict		= type_vocab_size
          lowerCamelCase_						:   List[str]		= type_sequence_label_size
          lowerCamelCase_						:   Any		= initializer_range
          lowerCamelCase_						:   Union[str, Any]		= num_labels
          lowerCamelCase_						:   List[Any]		= num_choices
          lowerCamelCase_						:   Dict		= scope



       def 				_lowerCAmelCase							(						self				:				int							)					->str:
          lowerCamelCase_						:   Dict		= ids_tensor([self.batch_size, self.seq_length]		,				self.vocab_size							)

          lowerCamelCase_						:   Tuple		= None
          if self.use_input_mask:
             lowerCamelCase_						:   Any		= random_attention_mask([self.batch_size, self.seq_length]							)

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

          lowerCamelCase_						:   List[Any]		= None
          lowerCamelCase_						:   Tuple		= None
          lowerCamelCase_						:   Optional[int]		= None
          if self.use_labels:
             lowerCamelCase_						:   str		= ids_tensor([self.batch_size]		,				self.type_sequence_label_size							)
             lowerCamelCase_						:   Optional[int]		= ids_tensor([self.batch_size, self.seq_length]		,				self.num_labels							)
             lowerCamelCase_						:   Any		= ids_tensor([self.batch_size]		,				self.num_choices							)

          lowerCamelCase_						:   str		= self.get_config()

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



       def 				_lowerCAmelCase							(						self				:				Tuple							)					->Optional[Any]:
          return MobileBertConfig(
              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		,				embedding_size=self.embedding_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=__a		,				initializer_range=self.initializer_range		,				)



       def 				_lowerCAmelCase							(						self				:				Tuple		,				__a				:				int		,				__a				:				List[str]		,				__a				:				Tuple		,				__a				:				Any		,				__a				:				Union[str, Any]		,				__a				:				int		,				__a				:				Any							)					->Tuple:
          lowerCamelCase_						:   Tuple		= MobileBertModel(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Dict		= model(__a		,				attention_mask=__a		,				token_type_ids=__a							)
          lowerCamelCase_						:   Optional[int]		= model(__a		,				token_type_ids=__a							)
          lowerCamelCase_						:   Tuple		= model(__a							)

          self.parent.assertEqual(result.last_hidden_state.shape		,				(self.batch_size, self.seq_length, self.hidden_size)							)
          self.parent.assertEqual(result.pooler_output.shape		,				(self.batch_size, self.hidden_size)							)



       def 				_lowerCAmelCase							(						self				:				List[str]		,				__a				:				str		,				__a				:				Union[str, Any]		,				__a				:				int		,				__a				:				List[Any]		,				__a				:				Dict		,				__a				:				List[Any]		,				__a				:				List[str]							)					->Tuple:
          lowerCamelCase_						:   List[Any]		= MobileBertForMaskedLM(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Union[str, Any]		= model(__a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a							)
          self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.seq_length, self.vocab_size)							)



       def 				_lowerCAmelCase							(						self				:				Optional[Any]		,				__a				:				Tuple		,				__a				:				Tuple		,				__a				:				Dict		,				__a				:				Tuple		,				__a				:				Optional[Any]		,				__a				:				Union[str, Any]		,				__a				:				Dict							)					->int:
          lowerCamelCase_						:   Tuple		= MobileBertForNextSentencePrediction(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Any		= model(
              __a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a		,				)
          self.parent.assertEqual(result.logits.shape		,				(self.batch_size, 2)							)



       def 				_lowerCAmelCase							(						self				:				str		,				__a				:				Optional[Any]		,				__a				:				int		,				__a				:				Optional[int]		,				__a				:				Optional[int]		,				__a				:				Optional[int]		,				__a				:				Optional[int]		,				__a				:				Dict							)					->List[Any]:
          lowerCamelCase_						:   Optional[int]		= MobileBertForPreTraining(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   List[Any]		= model(
              __a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a		,				next_sentence_label=__a		,				)
          self.parent.assertEqual(result.prediction_logits.shape		,				(self.batch_size, self.seq_length, self.vocab_size)							)
          self.parent.assertEqual(result.seq_relationship_logits.shape		,				(self.batch_size, 2)							)



       def 				_lowerCAmelCase							(						self				:				List[str]		,				__a				:				Tuple		,				__a				:				int		,				__a				:				Optional[Any]		,				__a				:				Optional[Any]		,				__a				:				Tuple		,				__a				:				Optional[Any]		,				__a				:				Any							)					->List[str]:
          lowerCamelCase_						:   Dict		= MobileBertForQuestionAnswering(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Tuple		= model(
              __a		,				attention_mask=__a		,				token_type_ids=__a		,				start_positions=__a		,				end_positions=__a		,				)
          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 				_lowerCAmelCase							(						self				:				Optional[Any]		,				__a				:				List[Any]		,				__a				:				str		,				__a				:				int		,				__a				:				Dict		,				__a				:				Dict		,				__a				:				List[Any]		,				__a				:				str							)					->Tuple:
          lowerCamelCase_						:   Dict		= self.num_labels
          lowerCamelCase_						:   Optional[Any]		= MobileBertForSequenceClassification(__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   str		= model(__a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a							)
          self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.num_labels)							)



       def 				_lowerCAmelCase							(						self				:				List[str]		,				__a				:				str		,				__a				:				List[str]		,				__a				:				Optional[int]		,				__a				:				int		,				__a				:				str		,				__a				:				str		,				__a				:				Optional[Any]							)					->Tuple:
          lowerCamelCase_						:   int		= self.num_labels
          lowerCamelCase_						:   List[str]		= MobileBertForTokenClassification(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Optional[Any]		= model(__a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a							)
          self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.seq_length, self.num_labels)							)



       def 				_lowerCAmelCase							(						self				:				Union[str, Any]		,				__a				:				Any		,				__a				:				Tuple		,				__a				:				Dict		,				__a				:				Dict		,				__a				:				List[Any]		,				__a				:				Optional[int]		,				__a				:				Optional[Any]							)					->List[str]:
          lowerCamelCase_						:   Any		= self.num_choices
          lowerCamelCase_						:   int		= MobileBertForMultipleChoice(config=__a							)
          model.to(__a							)
          model.eval()
          lowerCamelCase_						:   Tuple		= input_ids.unsqueeze(1							).expand(-1		,				self.num_choices		,				-1							).contiguous()
          lowerCamelCase_						:   Tuple		= token_type_ids.unsqueeze(1							).expand(-1		,				self.num_choices		,				-1							).contiguous()
          lowerCamelCase_						:   Any		= input_mask.unsqueeze(1							).expand(-1		,				self.num_choices		,				-1							).contiguous()
          lowerCamelCase_						:   Tuple		= model(
              __a		,				attention_mask=__a		,				token_type_ids=__a		,				labels=__a		,				)
          self.parent.assertEqual(result.logits.shape		,				(self.batch_size, self.num_choices)							)




       def 				_lowerCAmelCase							(						self				:				List[str]							)					->int:
          lowerCamelCase_						:   Optional[Any]		= self.prepare_config_and_inputs()
          (
              (
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	(
              lowerCamelCase_
          ),	
          )						:   Optional[Any]		= config_and_inputs
          lowerCamelCase_						:   List[Any]		= {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
          return config, inputs_dict







@require_torch
class   SCREAMING_SNAKE_CASE_			(a__						,       a__						,       unittest.TestCase						):




       '''simple docstring'''



       _a   							=							(
           (
               MobileBertModel,
               MobileBertForMaskedLM,
               MobileBertForMultipleChoice,
               MobileBertForNextSentencePrediction,
               MobileBertForPreTraining,
               MobileBertForQuestionAnswering,
               MobileBertForSequenceClassification,
               MobileBertForTokenClassification,
           )
           if is_torch_available()
           else ()
       )
       _a   							=							(
           {
               "feature-extraction": MobileBertModel,
               "fill-mask": MobileBertForMaskedLM,
               "question-answering": MobileBertForQuestionAnswering,
               "text-classification": MobileBertForSequenceClassification,
               "token-classification": MobileBertForTokenClassification,
               "zero-shot": MobileBertForSequenceClassification,
           }
           if is_torch_available()
           else {}
       )
       _a   							=							True



       def 				_lowerCAmelCase							(						self				:				Optional[int]		,				__a				:				Union[str, Any]		,				__a				:				Dict		,				__a				:				str=False							)					->Any:
          lowerCamelCase_						:   Optional[int]		= super()._prepare_for_class(__a		,				__a		,				return_labels=__a							)

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



       def 				_lowerCAmelCase							(						self				:				Union[str, Any]							)					->Union[str, Any]:
          lowerCamelCase_						:   List[Any]		= MobileBertModelTester(self							)
          lowerCamelCase_						:   int		= ConfigTester(self		,				config_class=__a		,				hidden_size=37							)



       def 				_lowerCAmelCase							(						self				:				Union[str, Any]							)					->List[Any]:
          self.config_tester.run_common_tests()



       def 				_lowerCAmelCase							(						self				:				str							)					->Any:
          lowerCamelCase_						:   Union[str, Any]		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_model(*__a							)



       def 				_lowerCAmelCase							(						self				:				List[str]							)					->Tuple:
          lowerCamelCase_						:   List[str]		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_masked_lm(*__a							)



       def 				_lowerCAmelCase							(						self				:				Optional[Any]							)					->Tuple:
          lowerCamelCase_						:   Union[str, Any]		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_multiple_choice(*__a							)



       def 				_lowerCAmelCase							(						self				:				Any							)					->List[Any]:
          lowerCamelCase_						:   Any		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*__a							)



       def 				_lowerCAmelCase							(						self				:				Optional[int]							)					->str:
          lowerCamelCase_						:   List[str]		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_pretraining(*__a							)



       def 				_lowerCAmelCase							(						self				:				str							)					->Optional[Any]:
          lowerCamelCase_						:   int		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_question_answering(*__a							)



       def 				_lowerCAmelCase							(						self				:				List[str]							)					->int:
          lowerCamelCase_						:   Dict		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_sequence_classification(*__a							)




       def 				_lowerCAmelCase							(						self				:				List[Any]							)					->Union[str, Any]:
          lowerCamelCase_						:   Dict		= self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_mobilebert_for_token_classification(*__a							)







def    __lowerCamelCase   (      A__						: List[str]					)     ->    Optional[int]:
   return torch.tensor(
       A__						,						dtype=torch.long						,						device=A__						,						)


snake_case__				:	List[str]					       =					1e-3





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




       '''simple docstring'''



       @slow
       def 				_lowerCAmelCase							(						self				:				List[Any]							)					->List[str]:
          lowerCamelCase_						:   Any		= MobileBertModel.from_pretrained("""google/mobilebert-uncased"""							).to(__a							)
          lowerCamelCase_						:   int		= _long_tensor([[101, 7_110, 1_005, 1_056, 2_023, 11_333, 17_413, 1_029, 102]]							)
          with torch.no_grad():
             lowerCamelCase_						:   Optional[Any]		= model(__a							)[0]
          lowerCamelCase_						:   Any		= torch.Size((1, 9, 512)							)
          self.assertEqual(output.shape		,				__a							)
          lowerCamelCase_						:   str		= torch.tensor(
              [
                  [
                      [-2.4_73_65_26e07, 8.2_69_16_56e04, 1.6_52_18_38e05],
                      [-5.7_54_17_04e-01, 3.9_05_60_22e00, 4.4_01_15_07e00],
                      [2.6_04_73_59e00, 1.5_67_76_52e00, -1.7_32_41_88e-01],
                  ]
              ]		,				device=__a		,				)

          # MobileBERT results range from 10e0 to 10e8. Even a 0.0000001% difference with a value of 10e8 results in a
          # ~1 difference, it's therefore not a good idea to measure using addition.
          # Here, we instead divide the expected result with the result in order to obtain ~1. We then check that the
          # result is held between bounds: 1 - TOLERANCE < expected_result / result < 1 + TOLERANCE
          lowerCamelCase_						:   str		= torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE							)
          lowerCamelCase_						:   Tuple		= torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE							)

          self.assertTrue(lower_bound and upper_bound							)





