






import unittest

from transformers import ErnieMConfig, is_torch_available
from transformers.testing_utils import 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 (
         ErnieMForInformationExtraction,
         ErnieMForMultipleChoice,
         ErnieMForQuestionAnswering,
         ErnieMForSequenceClassification,
         ErnieMForTokenClassification,
         ErnieMModel,
     )
     from transformers.models.ernie_m.modeling_ernie_m import ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST






class 	lowercase_      :






      '''simple docstring'''




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




       """simple docstring"""


       a							=   parent
       a							=   batch_size
       a							=   seq_length
       a							=   is_training
       a							=   use_input_mask
       a							=   use_labels
       a							=   vocab_size
       a							=   hidden_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    __lowerCAmelCase      (   self   :		Tuple						)					->Any:




       """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
       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, input_mask, sequence_labels, token_labels, choice_labels







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




       """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							=   self.get_config()

       return config, input_ids, input_mask







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




       """simple docstring"""


       return ErnieMConfig(
           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				,      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				,      initializer_range=self.initializer_range				,      )







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




       """simple docstring"""


       a							=   ErnieMModel(config=__UpperCAmelCase						)
       model.to(__UpperCAmelCase						)
       model.eval()
       a							=   model(__UpperCAmelCase				,      return_dict=__UpperCAmelCase						)
       self.parent.assertEqual(result.last_hidden_state.shape				,      (self.batch_size, self.seq_length, self.hidden_size)						)







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




       """simple docstring"""


       a							=   ErnieMForQuestionAnswering(config=__UpperCAmelCase						)
       model.to(__UpperCAmelCase						)
       model.eval()
       a							=   model(
           __UpperCAmelCase				,      attention_mask=__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    __lowerCAmelCase      (   self   :		List[str]				,      __UpperCAmelCase   :		Optional[int]				,      __UpperCAmelCase   :		Any				,      __UpperCAmelCase   :		Dict				,      __UpperCAmelCase   :		List[Any]				,      __UpperCAmelCase   :		int				,      __UpperCAmelCase   :		Optional[int]						)					->Optional[int]:




       """simple docstring"""


       a							=   ErnieMForInformationExtraction(config=__UpperCAmelCase						)
       model.to(__UpperCAmelCase						)
       model.eval()
       a							=   torch.ones_like(__UpperCAmelCase				,      dtype=torch.floataa						)
       a							=   model(
           __UpperCAmelCase				,      attention_mask=__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    __lowerCAmelCase      (   self   :		str				,      __UpperCAmelCase   :		int				,      __UpperCAmelCase   :		int				,      __UpperCAmelCase   :		str				,      __UpperCAmelCase   :		Union[str, Any]				,      __UpperCAmelCase   :		Optional[Any]				,      __UpperCAmelCase   :		int						)					->List[str]:




       """simple docstring"""


       a							=   self.num_labels
       a							=   ErnieMForSequenceClassification(__UpperCAmelCase						)
       model.to(__UpperCAmelCase						)
       model.eval()
       a							=   model(__UpperCAmelCase				,      attention_mask=__UpperCAmelCase				,      labels=__UpperCAmelCase						)
       self.parent.assertEqual(result.logits.shape				,      (self.batch_size, self.num_labels)						)







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




       """simple docstring"""


       a							=   self.num_labels
       a							=   ErnieMForTokenClassification(config=__UpperCAmelCase						)
       model.to(__UpperCAmelCase						)
       model.eval()
       input_ids.to(__UpperCAmelCase						)
       input_mask.to(__UpperCAmelCase						)
       token_labels.to(__UpperCAmelCase						)

       a							=   model(__UpperCAmelCase				,      attention_mask=__UpperCAmelCase				,      labels=__UpperCAmelCase						)

       self.parent.assertEqual(result.logits.shape				,      (self.batch_size, self.seq_length, self.num_labels)						)







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




       """simple docstring"""


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







      def    __lowerCAmelCase      (   self   :		Optional[Any]						)					->Tuple:




       """simple docstring"""


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






@require_torch
class 	lowercase_      (			lowercase				,						lowercase				,						unittest.TestCase     ):






      '''simple docstring'''




      __snake_case  						=						(
          (
              ErnieMModel,
              ErnieMForMultipleChoice,
              ErnieMForQuestionAnswering,
              ErnieMForSequenceClassification,
              ErnieMForTokenClassification,
          )
          if is_torch_available()
          else ()
      )
      __snake_case  						=						()
      __snake_case  						=						(
          {
              '''feature-extraction''': ErnieMModel,
              '''question-answering''': ErnieMForQuestionAnswering,
              '''text-classification''': ErnieMForSequenceClassification,
              '''token-classification''': ErnieMForTokenClassification,
              '''zero-shot''': ErnieMForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )
      __snake_case  						=						False







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




       """simple docstring"""


       if pipeline_test_casse_name == "QAPipelineTests":
        return True

       return False







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




       """simple docstring"""


       a							=   ErnieMModelTester(self						)
       a							=   ConfigTester(self				,      config_class=__UpperCAmelCase				,      hidden_size=37						)







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




       """simple docstring"""


       self.config_tester.run_common_tests()







      def    __lowerCAmelCase      (   self   :		Dict						)					->Any:




       """simple docstring"""


       a							=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*__UpperCAmelCase						)







      def    __lowerCAmelCase      (   self   :		List[str]						)					->Tuple:




       """simple docstring"""


       a							=   self.model_tester.prepare_config_and_inputs()
       for type in ["absolute", "relative_key", "relative_key_query"]:
        a							=   type
        self.model_tester.create_and_check_model(*__UpperCAmelCase						)







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




       """simple docstring"""


       a							=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_multiple_choice(*__UpperCAmelCase						)







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




       """simple docstring"""


       a							=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_question_answering(*__UpperCAmelCase						)







      def    __lowerCAmelCase      (   self   :		Any						)					->Tuple:




       """simple docstring"""


       a							=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_sequence_classification(*__UpperCAmelCase						)







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




       """simple docstring"""


       a							=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_information_extraction(*__UpperCAmelCase						)







      def    __lowerCAmelCase      (   self   :		Optional[Any]						)					->Dict:




       """simple docstring"""


       a							=   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_token_classification(*__UpperCAmelCase						)







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




       """simple docstring"""


       for model_name in ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        a							=   ErnieMModel.from_pretrained(__UpperCAmelCase						)
        self.assertIsNotNone(__UpperCAmelCase						)






@require_torch
class 	lowercase_      (			unittest.TestCase     ):






      '''simple docstring'''




      @slow
      def    __lowerCAmelCase      (   self   :		str						)					->str:




       """simple docstring"""


       a							=   ErnieMModel.from_pretrained('''susnato/ernie-m-base_pytorch'''						)
       model.eval()
       a							=   torch.tensor([[0, 1, 2, 3, 4, 5]]						)
       a							=   model(__UpperCAmelCase						)[0]

       # TODO Replace vocab size
       a							=   768

       a							=   torch.Size((1, 6, hidden_size)						)
       self.assertEqual(output.shape				,      __UpperCAmelCase						)

       a							=   torch.tensor(
           [[[-0.0012, 0.1245, -0.0214], [-0.0742, 0.0244, -0.0771], [-0.0333, 0.1164, -0.1554]]]						)

       self.assertTrue(torch.allclose(output[:, :3, :3]				,      __UpperCAmelCase				,      atol=1e-3						)						)










from collections import namedtuple

UpperCAmelCase__            =	namedtuple("from_to", "from_ to")

UpperCAmelCase__            =	{
    "atm": from_to(1, 1),
    "pascal": from_to(0.000_0098, 101325),
    "bar": from_to(0.98_6923, 1.0_1325),
    "kilopascal": from_to(0.0098_6923, 101.325),
    "megapascal": from_to(9.8_6923, 0.10_1325),
    "psi": from_to(0.06_8046, 14.6959),
    "inHg": from_to(0.033_4211, 29.9213),
    "torr": from_to(0.0013_1579, 760),
}
def 		_a					(   a				:float			,							a				:str			,							a				:str				)							->    float:
 if from_type not in PRESSURE_CONVERSION:
  raise ValueError(
      F"""Invalid 'from_type' value: {from_type!r}  Supported values are:\n"""
      + ''', '''.join(a				)				)
 if to_type not in PRESSURE_CONVERSION:
  raise ValueError(
      F"""Invalid 'to_type' value: {to_type!r}.  Supported values are:\n"""
      + ''', '''.join(a				)				)
 return (
     value * PRESSURE_CONVERSION[from_type].from_ * PRESSURE_CONVERSION[to_type].to
 )


if __name__ == "__main__":
     import doctest

     doctest.testmod()


