

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        _UpperCAmelCase :
  '''simple docstring'''







  def __init__( self	: Optional[Any]		,						UpperCamelCase__	: Tuple		,						UpperCamelCase__	: Union[str, Any]=13		,						UpperCamelCase__	: int=7		,						UpperCamelCase__	: Optional[int]=True		,						UpperCamelCase__	: Tuple=True		,						UpperCamelCase__	: str=True		,						UpperCamelCase__	: int=99		,						UpperCamelCase__	: Optional[Any]=32		,						UpperCamelCase__	: Optional[int]=5		,						UpperCamelCase__	: List[Any]=4		,						UpperCamelCase__	: Tuple=37		,						UpperCamelCase__	: List[str]="gelu"		,						UpperCamelCase__	: Optional[Any]=0.1		,						UpperCamelCase__	: List[str]=0.1		,						UpperCamelCase__	: Any=512		,						UpperCamelCase__	: Optional[int]=16		,						UpperCamelCase__	: Dict=2		,						UpperCamelCase__	: List[Any]=0.02		,						UpperCamelCase__	: Optional[Any]=3		,						UpperCamelCase__	: Tuple=4		,						UpperCamelCase__	: Optional[int]=None		,						):
        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 	UpperCamelCase       ( self	: Any ):
        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 	UpperCamelCase       ( self	: int ):
        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 	UpperCamelCase       ( self	: int ):
        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 	UpperCamelCase       ( self	: int		,						UpperCamelCase__	: Union[str, Any]		,						UpperCamelCase__	: str		,						UpperCamelCase__	: List[Any]		,						UpperCamelCase__	: int		,						UpperCamelCase__	: Any		,						UpperCamelCase__	: List[Any] ):
        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 	UpperCamelCase       ( self	: List[str]		,						UpperCamelCase__	: Dict		,						UpperCamelCase__	: Tuple		,						UpperCamelCase__	: Any		,						UpperCamelCase__	: List[Any]		,						UpperCamelCase__	: int		,						UpperCamelCase__	: List[str] ):
        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 	UpperCamelCase       ( self	: List[str]		,						UpperCamelCase__	: Union[str, Any]		,						UpperCamelCase__	: Union[str, Any]		,						UpperCamelCase__	: Optional[int]		,						UpperCamelCase__	: List[Any]		,						UpperCamelCase__	: List[str]		,						UpperCamelCase__	: List[Any] ):
        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 	UpperCamelCase       ( self	: Optional[int]		,						UpperCamelCase__	: Tuple		,						UpperCamelCase__	: Optional[int]		,						UpperCamelCase__	: str		,						UpperCamelCase__	: Union[str, Any]		,						UpperCamelCase__	: Any		,						UpperCamelCase__	: List[str] ):
        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 	UpperCamelCase       ( self	: List[Any]		,						UpperCamelCase__	: Optional[int]		,						UpperCamelCase__	: str		,						UpperCamelCase__	: List[str]		,						UpperCamelCase__	: Tuple		,						UpperCamelCase__	: str		,						UpperCamelCase__	: Any ):
        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 	UpperCamelCase       ( self	: str		,						UpperCamelCase__	: Union[str, Any]		,						UpperCamelCase__	: Optional[int]		,						UpperCamelCase__	: Any		,						UpperCamelCase__	: Optional[Any]		,						UpperCamelCase__	: Tuple		,						UpperCamelCase__	: int ):
        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 	UpperCamelCase       ( self	: Tuple ):
        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        _UpperCAmelCase (   __lowercase     ,				__lowercase     ,				unittest.TestCase			):
  '''simple docstring'''







  SCREAMING_SNAKE_CASE							:				Optional[Any]					      =				(
      (
          ErnieMModel,
          ErnieMForMultipleChoice,
          ErnieMForQuestionAnswering,
          ErnieMForSequenceClassification,
          ErnieMForTokenClassification,
      )
      if is_torch_available()
      else ()
  )
  SCREAMING_SNAKE_CASE							:				Tuple					      =				()
  SCREAMING_SNAKE_CASE							:				Optional[int]					      =				(
      {
          '''feature-extraction''': ErnieMModel,
          '''question-answering''': ErnieMForQuestionAnswering,
          '''text-classification''': ErnieMForSequenceClassification,
          '''token-classification''': ErnieMForTokenClassification,
          '''zero-shot''': ErnieMForSequenceClassification,
      }
      if is_torch_available()
      else {}
  )
  SCREAMING_SNAKE_CASE							:				List[str]					      =				False







  def 	UpperCamelCase       ( self	: Dict		,						UpperCamelCase__	: List[Any]		,						UpperCamelCase__	: Union[str, Any]		,						UpperCamelCase__	: List[Any]		,						UpperCamelCase__	: int		,						UpperCamelCase__	: Optional[Any] ):
        if pipeline_test_casse_name == "QAPipelineTests":
              return True

        return False







  def 	UpperCamelCase       ( self	: Optional[int] ):
        A    =				ErnieMModelTester(self )
        A    =				ConfigTester(self		,						config_class=UpperCamelCase__		,						hidden_size=37 )







  def 	UpperCamelCase       ( self	: Tuple ):
        self.config_tester.run_common_tests()







  def 	UpperCamelCase       ( self	: Any ):
        A    =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*UpperCamelCase__ )







  def 	UpperCamelCase       ( self	: Any ):
        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 	UpperCamelCase       ( self	: Optional[int] ):
        A    =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_multiple_choice(*UpperCamelCase__ )







  def 	UpperCamelCase       ( self	: int ):
        A    =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__ )







  def 	UpperCamelCase       ( self	: Optional[Any] ):
        A    =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase__ )







  def 	UpperCamelCase       ( self	: Optional[Any] ):
        A    =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_information_extraction(*UpperCamelCase__ )







  def 	UpperCamelCase       ( self	: Optional[int] ):
        A    =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__ )







  @slow
  def 	UpperCamelCase       ( self	: str ):
        for model_name in ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              A    =				ErnieMModel.from_pretrained(UpperCamelCase__ )
              self.assertIsNotNone(UpperCamelCase__ )



@require_torch
class        _UpperCAmelCase (   unittest.TestCase			):
  '''simple docstring'''







  @slow
  def 	UpperCamelCase       ( self	: Dict ):
        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.0_012, 0.1_245, -0.0_214], [-0.0_742, 0.0_244, -0.0_771], [-0.0_333, 0.1_164, -0.1_554]]] )

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






from typing import Optional, Tuple

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_openai import OpenAIGPTTokenizer


_UpperCAmelCase    	=			logging.get_logger(__name__)

_UpperCAmelCase    	=			{"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}

_UpperCAmelCase    	=			{
    "vocab_file": {"openai-gpt": "https://huggingface.co/openai-gpt/resolve/main/vocab.json"},
    "merges_file": {"openai-gpt": "https://huggingface.co/openai-gpt/resolve/main/merges.txt"},
    "tokenizer_file": {"openai-gpt": "https://huggingface.co/openai-gpt/resolve/main/tokenizer.json"},
}

_UpperCAmelCase    	=			{
    "openai-gpt": 512,
}



class        _UpperCAmelCase (   __lowercase			):
  '''simple docstring'''







  SCREAMING_SNAKE_CASE							:				Union[str, Any]					      =				VOCAB_FILES_NAMES
  SCREAMING_SNAKE_CASE							:				Any					      =				PRETRAINED_VOCAB_FILES_MAP
  SCREAMING_SNAKE_CASE							:				Dict					      =				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  SCREAMING_SNAKE_CASE							:				List[str]					      =				['''input_ids''', '''attention_mask''']
  SCREAMING_SNAKE_CASE							:				Tuple					      =				OpenAIGPTTokenizer







  def __init__( self	: Dict		,						UpperCamelCase__	: List[Any]=None		,						UpperCamelCase__	: Union[str, Any]=None		,						UpperCamelCase__	: Optional[int]=None		,						UpperCamelCase__	: Tuple="<unk>"		,						**UpperCamelCase__	: Union[str, Any] ):
        super().__init__(UpperCamelCase__		,						UpperCamelCase__		,						tokenizer_file=UpperCamelCase__		,						unk_token=UpperCamelCase__		,						**UpperCamelCase__ )







  @property
  def 	UpperCamelCase       ( self	: Optional[Any] ):
        return True







  def 	UpperCamelCase       ( self	: Dict		,						UpperCamelCase__	: str		,						UpperCamelCase__	: Optional[str] = None ):
        A    =				self._tokenizer.model.save(UpperCamelCase__		,						name=UpperCamelCase__ )
        return tuple(UpperCamelCase__ )



