



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


A_		:     Any        =     logging.get_logger(__name__)

A_		:     Dict        =     {
    '''studio-ousia/luke-base''': '''https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json''',
    '''studio-ousia/luke-large''': '''https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json''',
}



class 		_lowercase		(       UpperCAmelCase__	):
   _UpperCAmelCase     	=			'''luke'''

   def __init__(      self			:       Tuple							,   __lowerCAmelCase			:       Dict=5_0267							,   __lowerCAmelCase			:       List[Any]=50_0000							,   __lowerCAmelCase			:       Optional[Any]=768							,   __lowerCAmelCase			:       Union[str, Any]=256							,   __lowerCAmelCase			:       str=12							,   __lowerCAmelCase			:       Dict=12							,   __lowerCAmelCase			:       List[str]=3072							,   __lowerCAmelCase			:       Union[str, Any]="gelu"							,   __lowerCAmelCase			:       Optional[int]=0.1							,   __lowerCAmelCase			:       Tuple=0.1							,   __lowerCAmelCase			:       Union[str, Any]=512							,   __lowerCAmelCase			:       str=2							,   __lowerCAmelCase			:       Any=0.0_2							,   __lowerCAmelCase			:       str=1E-12							,   __lowerCAmelCase			:       Optional[int]=True							,   __lowerCAmelCase			:       List[str]=None							,   __lowerCAmelCase			:       Any=1							,   __lowerCAmelCase			:       Optional[int]=0							,   __lowerCAmelCase			:       Dict=2							,   **__lowerCAmelCase			:       Tuple							,   )       ->				int:


    """simple docstring"""






    super().__init__(pad_token_id=__lowerCAmelCase							,   bos_token_id=__lowerCAmelCase							,   eos_token_id=__lowerCAmelCase							,   **__lowerCAmelCase							)

    a						=		vocab_size
    a						=		entity_vocab_size
    a						=		hidden_size
    a						=		entity_emb_size
    a						=		num_hidden_layers
    a						=		num_attention_heads
    a						=		hidden_act
    a						=		intermediate_size
    a						=		hidden_dropout_prob
    a						=		attention_probs_dropout_prob
    a						=		max_position_embeddings
    a						=		type_vocab_size
    a						=		initializer_range
    a						=		layer_norm_eps
    a						=		use_entity_aware_attention
    a						=		classifier_dropout






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 		_lowercase		:

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


    """simple docstring"""






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

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


    """simple docstring"""






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

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

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

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

    a						=		self.get_config()

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

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


    """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=__lowerCAmelCase							,   initializer_range=self.initializer_range							,   )

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


    """simple docstring"""






    a						=		MobileBertModel(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(__lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							)
    a						=		model(__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							)
    a						=		model(__lowerCAmelCase							)

    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 		A							(      self			:       List[Any]							,   __lowerCAmelCase			:       Optional[int]							,   __lowerCAmelCase			:       Tuple							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       List[Any]							,   __lowerCAmelCase			:       Optional[int]							,   __lowerCAmelCase			:       Any							,   __lowerCAmelCase			:       Any							)       ->				str:


    """simple docstring"""






    a						=		MobileBertForMaskedLM(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(__lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							,   labels=__lowerCAmelCase							)
    self.parent.assertEqual(result.logits.shape							,   (self.batch_size, self.seq_length, self.vocab_size)							)

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


    """simple docstring"""






    a						=		MobileBertForNextSentencePrediction(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(
        __lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							,   labels=__lowerCAmelCase							,   )
    self.parent.assertEqual(result.logits.shape							,   (self.batch_size, 2)							)

   def 		A							(      self			:       List[str]							,   __lowerCAmelCase			:       List[Any]							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       Tuple							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       List[str]							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       List[str]							)       ->				List[Any]:


    """simple docstring"""






    a						=		MobileBertForPreTraining(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(
        __lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							,   labels=__lowerCAmelCase							,   next_sentence_label=__lowerCAmelCase							,   )
    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 		A							(      self			:       Union[str, Any]							,   __lowerCAmelCase			:       Tuple							,   __lowerCAmelCase			:       Any							,   __lowerCAmelCase			:       Any							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       Tuple							,   __lowerCAmelCase			:       Optional[int]							,   __lowerCAmelCase			:       List[str]							)       ->				Any:


    """simple docstring"""






    a						=		MobileBertForQuestionAnswering(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(
        __lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							,   start_positions=__lowerCAmelCase							,   end_positions=__lowerCAmelCase							,   )
    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 		A							(      self			:       List[Any]							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       Optional[int]							,   __lowerCAmelCase			:       List[Any]							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       int							,   __lowerCAmelCase			:       Optional[Any]							)       ->				Optional[int]:


    """simple docstring"""






    a						=		self.num_labels
    a						=		MobileBertForSequenceClassification(__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(__lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							,   labels=__lowerCAmelCase							)
    self.parent.assertEqual(result.logits.shape							,   (self.batch_size, self.num_labels)							)

   def 		A							(      self			:       Tuple							,   __lowerCAmelCase			:       Optional[Any]							,   __lowerCAmelCase			:       List[str]							,   __lowerCAmelCase			:       str							,   __lowerCAmelCase			:       str							,   __lowerCAmelCase			:       List[Any]							,   __lowerCAmelCase			:       Tuple							,   __lowerCAmelCase			:       Any							)       ->				Optional[Any]:


    """simple docstring"""






    a						=		self.num_labels
    a						=		MobileBertForTokenClassification(config=__lowerCAmelCase							)
    model.to(__lowerCAmelCase							)
    model.eval()
    a						=		model(__lowerCAmelCase							,   attention_mask=__lowerCAmelCase							,   token_type_ids=__lowerCAmelCase							,   labels=__lowerCAmelCase							)
    self.parent.assertEqual(result.logits.shape							,   (self.batch_size, self.seq_length, self.num_labels)							)

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


    """simple docstring"""






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




   def 		A							(      self			:       List[Any]							)       ->				Dict:


    """simple docstring"""






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



@require_torch
class 		_lowercase		(       UpperCAmelCase__,   UpperCAmelCase__,   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 		A							(      self			:       Optional[int]							,   __lowerCAmelCase			:       Dict							,   __lowerCAmelCase			:       Union[str, Any]							,   __lowerCAmelCase			:       Any=False							)       ->				Any:


    """simple docstring"""






    a						=		super()._prepare_for_class(__lowerCAmelCase							,   __lowerCAmelCase							,   return_labels=__lowerCAmelCase							)

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

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


    """simple docstring"""






    a						=		MobileBertModelTester(self							)
    a						=		ConfigTester(self							,   config_class=__lowerCAmelCase							,   hidden_size=37							)

   def 		A							(      self			:       int							)       ->				Tuple:


    """simple docstring"""






    self.config_tester.run_common_tests()

   def 		A							(      self			:       str							)       ->				Dict:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_mobilebert_model(*__lowerCAmelCase							)

   def 		A							(      self			:       str							)       ->				str:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_mobilebert_for_masked_lm(*__lowerCAmelCase							)

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


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_mobilebert_for_multiple_choice(*__lowerCAmelCase							)

   def 		A							(      self			:       int							)       ->				Dict:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*__lowerCAmelCase							)

   def 		A							(      self			:       List[Any]							)       ->				int:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_mobilebert_for_pretraining(*__lowerCAmelCase							)

   def 		A							(      self			:       List[Any]							)       ->				Dict:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_mobilebert_for_question_answering(*__lowerCAmelCase							)

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


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_mobilebert_for_sequence_classification(*__lowerCAmelCase							)




   def 		A							(      self			:       int							)       ->				Tuple:


    """simple docstring"""






    a						=		self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_mobilebert_for_token_classification(*__lowerCAmelCase							)


def 	UpperCAmelCase__      (      UpperCAmelCase__ :Dict					):






 '''simple docstring'''

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


A_		:     Dict        =     1E-3




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

   @slow
   def 		A							(      self			:       Optional[Any]							)       ->				Optional[Any]:


    """simple docstring"""






    a						=		MobileBertModel.from_pretrained("google/mobilebert-uncased"							).to(__lowerCAmelCase							)
    a						=		_long_tensor([[101, 7110, 1005, 1056, 2023, 1_1333, 1_7413, 1029, 102]]							)
    with torch.no_grad():
     a						=		model(__lowerCAmelCase							)[0]
    a						=		torch.Size((1, 9, 512)							)
    self.assertEqual(output.shape							,   __lowerCAmelCase							)
    a						=		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=__lowerCAmelCase							,   )

    # 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
    a						=		torch.all((expected_slice / output[..., :3, :3]) >= 1 - TOLERANCE							)
    a						=		torch.all((expected_slice / output[..., :3, :3]) <= 1 + TOLERANCE							)

    self.assertTrue(lower_bound and upper_bound							)

