





"""simple docstring"""




from typing import Optional

import pyspark

from .. import Features, NamedSplit
from ..download import DownloadMode
from ..packaged_modules.spark.spark import Spark
from .abc import AbstractDatasetReader


class 			__magic_name__       (       _a ):
       def __init__(     self ,				A_ ,				A_ = None ,				A_ = None ,				A_ = True ,				A_ = None ,				A_ = False ,				A_ = None ,				A_ = True ,				A_ = "arrow" ,				**A_ ,				)     ->	int:





         """simple docstring"""




         super().__init__(
             split=_A ,				features=_A ,				cache_dir=_A ,				keep_in_memory=_A ,				streaming=_A ,				**_A ,				)
         _lowercase:			str       =     load_from_cache_file
         _lowercase:			Tuple       =     file_format
         _lowercase:			Dict       =     Spark(
             df=_A ,				features=_A ,				cache_dir=_A ,				working_dir=_A ,				**_A ,				)



       def 							lowercase_							(     self       )     ->	Union[str, Any]:





         """simple docstring"""




         if self.streaming:
           return self.builder.as_streaming_dataset(split=self.split       )
         _lowercase:			Dict       =     None if self._load_from_cache_file else DownloadMode.FORCE_REDOWNLOAD
         self.builder.download_and_prepare(
             download_mode=_A ,				file_format=self._file_format ,				)
         return self.builder.as_dataset(split=self.split       )


"""simple docstring"""




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 			__magic_name__       :
       def __init__(     self ,				A_ ,				A_=13 ,				A_=7 ,				A_=True ,				A_=True ,				A_=True ,				A_=True ,				A_=99 ,				A_=64 ,				A_=32 ,				A_=5 ,				A_=4 ,				A_=37 ,				A_="gelu" ,				A_=0.1 ,				A_=0.1 ,				A_=512 ,				A_=16 ,				A_=2 ,				A_=0.02 ,				A_=3 ,				A_=4 ,				A_=None ,				)     ->	Dict:





         """simple docstring"""




         _lowercase:			List[Any]       =     parent
         _lowercase:			str       =     batch_size
         _lowercase:			List[str]       =     seq_length
         _lowercase:			Any       =     is_training
         _lowercase:			Union[str, Any]       =     use_input_mask
         _lowercase:			Any       =     use_token_type_ids
         _lowercase:			int       =     use_labels
         _lowercase:			Any       =     vocab_size
         _lowercase:			Optional[int]       =     hidden_size
         _lowercase:			Optional[int]       =     embedding_size
         _lowercase:			Union[str, Any]       =     num_hidden_layers
         _lowercase:			Optional[int]       =     num_attention_heads
         _lowercase:			Optional[int]       =     intermediate_size
         _lowercase:			List[str]       =     hidden_act
         _lowercase:			Dict       =     hidden_dropout_prob
         _lowercase:			Any       =     attention_probs_dropout_prob
         _lowercase:			Tuple       =     max_position_embeddings
         _lowercase:			List[str]       =     type_vocab_size
         _lowercase:			Any       =     type_sequence_label_size
         _lowercase:			int       =     initializer_range
         _lowercase:			Any       =     num_labels
         _lowercase:			int       =     num_choices
         _lowercase:			List[str]       =     scope
       def 							lowercase_							(     self       )     ->	Optional[Any]:





         """simple docstring"""




         _lowercase:			Tuple       =     ids_tensor([self.batch_size, self.seq_length] ,				self.vocab_size       )

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

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

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

         _lowercase:			str       =     self.get_config()

         return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
       def 							lowercase_							(     self       )     ->	List[Any]:





         """simple docstring"""




         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 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )     ->	Any:





         """simple docstring"""




         _lowercase:			Tuple       =     MobileBertModel(config=A_       )
         model.to(A_       )
         model.eval()
         _lowercase:			Tuple       =     model(A_ ,				attention_mask=A_ ,				token_type_ids=A_       )
         _lowercase:			Dict       =     model(A_ ,				token_type_ids=A_       )
         _lowercase:			Optional[int]       =     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 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )     ->	int:





         """simple docstring"""




         _lowercase:			int       =     MobileBertForMaskedLM(config=A_       )
         model.to(A_       )
         model.eval()
         _lowercase:			Optional[int]       =     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 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )     ->	int:





         """simple docstring"""




         _lowercase:			Any       =     MobileBertForNextSentencePrediction(config=A_       )
         model.to(A_       )
         model.eval()
         _lowercase:			int       =     model(
             A_ ,				attention_mask=A_ ,				token_type_ids=A_ ,				labels=A_ ,				)
         self.parent.assertEqual(result.logits.shape ,				(self.batch_size, 2)       )
       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )     ->	Optional[int]:





         """simple docstring"""




         _lowercase:			str       =     MobileBertForPreTraining(config=A_       )
         model.to(A_       )
         model.eval()
         _lowercase:			List[str]       =     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 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )     ->	List[str]:





         """simple docstring"""




         _lowercase:			Optional[Any]       =     MobileBertForQuestionAnswering(config=A_       )
         model.to(A_       )
         model.eval()
         _lowercase:			Dict       =     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 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )     ->	List[Any]:





         """simple docstring"""




         _lowercase:			Optional[Any]       =     self.num_labels
         _lowercase:			int       =     MobileBertForSequenceClassification(A_       )
         model.to(A_       )
         model.eval()
         _lowercase:			List[Any]       =     model(A_ ,				attention_mask=A_ ,				token_type_ids=A_ ,				labels=A_       )
         self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.num_labels)       )
       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )     ->	Tuple:





         """simple docstring"""




         _lowercase:			Dict       =     self.num_labels
         _lowercase:			Optional[Any]       =     MobileBertForTokenClassification(config=A_       )
         model.to(A_       )
         model.eval()
         _lowercase:			Optional[int]       =     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 							lowercase_							(     self ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_ ,				A_       )     ->	List[str]:





         """simple docstring"""




         _lowercase:			Union[str, Any]       =     self.num_choices
         _lowercase:			List[Any]       =     MobileBertForMultipleChoice(config=A_       )
         model.to(A_       )
         model.eval()
         _lowercase:			Any       =     input_ids.unsqueeze(1       ).expand(-1 ,				self.num_choices ,				-1       ).contiguous()
         _lowercase:			Tuple       =     token_type_ids.unsqueeze(1       ).expand(-1 ,				self.num_choices ,				-1       ).contiguous()
         _lowercase:			List[str]       =     input_mask.unsqueeze(1       ).expand(-1 ,				self.num_choices ,				-1       ).contiguous()
         _lowercase:			Any       =     model(
             A_ ,				attention_mask=A_ ,				token_type_ids=A_ ,				labels=A_ ,				)
         self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.num_choices)       )



       def 							lowercase_							(     self       )     ->	Optional[int]:





         """simple docstring"""




         _lowercase:			Any       =     self.prepare_config_and_inputs()
         (
             (
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				(
             _lowercase
         ) ,				
         ):			Dict       =     config_and_inputs
         _lowercase:			int       =     {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
         return config, inputs_dict


@require_torch
class 			__magic_name__       (       SCREAMING_SNAKE_CASE__   ,					SCREAMING_SNAKE_CASE__   ,					unittest.TestCase ):
       UpperCamelCase_   =		(
           (
               MobileBertModel,
               MobileBertForMaskedLM,
               MobileBertForMultipleChoice,
               MobileBertForNextSentencePrediction,
               MobileBertForPreTraining,
               MobileBertForQuestionAnswering,
               MobileBertForSequenceClassification,
               MobileBertForTokenClassification,
           )
           if is_torch_available()
           else ()
       )
       UpperCamelCase_   =		(
           {
               '''feature-extraction''': MobileBertModel,
               '''fill-mask''': MobileBertForMaskedLM,
               '''question-answering''': MobileBertForQuestionAnswering,
               '''text-classification''': MobileBertForSequenceClassification,
               '''token-classification''': MobileBertForTokenClassification,
               '''zero-shot''': MobileBertForSequenceClassification,
           }
           if is_torch_available()
           else {}
       )
       UpperCamelCase_   =		True
       def 							lowercase_							(     self ,				A_ ,				A_ ,				A_=False       )     ->	str:





         """simple docstring"""




         _lowercase:			Optional[Any]       =     super()._prepare_for_class(A_ ,				A_ ,				return_labels=A_       )

         if return_labels:
           if model_class in get_values(A_       ):
             _lowercase:			Tuple       =     torch.zeros(
                 (self.model_tester.batch_size, self.model_tester.seq_length) ,				dtype=torch.long ,				device=A_       )
             _lowercase:			Tuple       =     torch.zeros(
                 self.model_tester.batch_size ,				dtype=torch.long ,				device=A_       )
         return inputs_dict
       def 							lowercase_							(     self       )     ->	Tuple:





         """simple docstring"""




         _lowercase:			Optional[Any]       =     MobileBertModelTester(self       )
         _lowercase:			str       =     ConfigTester(self ,				config_class=A_ ,				hidden_size=37       )
       def 							lowercase_							(     self       )     ->	Any:





         """simple docstring"""




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





         """simple docstring"""




         _lowercase:			str       =     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_mobilebert_model(*A_       )
       def 							lowercase_							(     self       )     ->	Optional[Any]:





         """simple docstring"""




         _lowercase:			Union[str, Any]       =     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_mobilebert_for_masked_lm(*A_       )
       def 							lowercase_							(     self       )     ->	Any:





         """simple docstring"""




         _lowercase:			List[str]       =     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_mobilebert_for_multiple_choice(*A_       )
       def 							lowercase_							(     self       )     ->	Union[str, Any]:





         """simple docstring"""




         _lowercase:			Any       =     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*A_       )
       def 							lowercase_							(     self       )     ->	Optional[Any]:





         """simple docstring"""




         _lowercase:			Optional[Any]       =     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_mobilebert_for_pretraining(*A_       )
       def 							lowercase_							(     self       )     ->	Tuple:





         """simple docstring"""




         _lowercase:			List[Any]       =     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_mobilebert_for_question_answering(*A_       )
       def 							lowercase_							(     self       )     ->	List[str]:





         """simple docstring"""




         _lowercase:			str       =     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_mobilebert_for_sequence_classification(*A_       )



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





         """simple docstring"""




         _lowercase:			Dict       =     self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_mobilebert_for_token_classification(*A_       )




def  _lowerCAmelCase		(		_UpperCamelCase						):






  """simple docstring"""



  return torch.tensor(
      _UpperCamelCase ,				dtype=torch.long ,				device=_UpperCamelCase ,				)


A__   :					Optional[Any]							=   1e-3







@require_torch
@require_sentencepiece
@require_tokenizers
class 			__magic_name__       (       unittest.TestCase ):
       @slow
       def 							lowercase_							(     self       )     ->	int:





         """simple docstring"""




         _lowercase:			Optional[int]       =     MobileBertModel.from_pretrained('''google/mobilebert-uncased'''       ).to(A_       )
         _lowercase:			str       =     _long_tensor([[101, 7110, 1005, 1056, 2023, 1_1333, 1_7413, 1029, 102]]       )
         with torch.no_grad():
           _lowercase:			Dict       =     model(A_       )[0]
         _lowercase:			List[Any]       =     torch.Size((1, 9, 512)       )
         self.assertEqual(output.shape ,				A_       )
         _lowercase:			Tuple       =     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
         _lowercase:			Tuple       =     torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE       )
         _lowercase:			Dict       =     torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE       )

         self.assertTrue(lower_bound and upper_bound       )
