

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




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




	def 					lowerCAmelCase_					(    self	:    Any       ):
		__A   : Tuple								= ids_tensor([self.batch_size, self.seq_length]				,			self.vocab_size       )

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

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

		__A   : Optional[Any]								= self.get_config()

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




	def 					lowerCAmelCase_					(    self	:    Dict       ):
		__A   : Optional[int]								= ids_tensor([self.batch_size, self.seq_length]				,			self.vocab_size       )

		__A   : Optional[Any]								= None
		if self.use_input_mask:
			__A   : Dict								= random_attention_mask([self.batch_size, self.seq_length]       )
		__A   : List[Any]								= self.get_config()

		return config, input_ids, input_mask




	def 					lowerCAmelCase_					(    self	:    Union[str, Any]       ):
		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	:    Any				,			__A	:    List[str]				,			__A	:    int				,			__A	:    Union[str, Any]				,			__A	:    Optional[int]				,			__A	:    Tuple				,			__A	:    Dict       ):
		__A   : int								= ErnieMModel(config=__A       )
		model.to(__A       )
		model.eval()
		__A   : Optional[Any]								= model(__A				,			return_dict=__A       )
		self.parent.assertEqual(result.last_hidden_state.shape				,			(self.batch_size, self.seq_length, self.hidden_size)       )




	def 					lowerCAmelCase_					(    self	:    List[str]				,			__A	:    Tuple				,			__A	:    Union[str, Any]				,			__A	:    Union[str, Any]				,			__A	:    str				,			__A	:    List[str]				,			__A	:    List[str]       ):
		__A   : Optional[int]								= ErnieMForQuestionAnswering(config=__A       )
		model.to(__A       )
		model.eval()
		__A   : List[Any]								= model(
		    __A				,			attention_mask=__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	:    Union[str, Any]				,			__A	:    int				,			__A	:    List[Any]				,			__A	:    Any				,			__A	:    int				,			__A	:    int				,			__A	:    Union[str, Any]       ):
		__A   : List[str]								= ErnieMForInformationExtraction(config=__A       )
		model.to(__A       )
		model.eval()
		__A   : Optional[Any]								= torch.ones_like(__A				,			dtype=torch.floataa       )
		__A   : Any								= model(
		    __A				,			attention_mask=__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	:    str				,			__A	:    str				,			__A	:    Any				,			__A	:    Optional[int]				,			__A	:    List[str]				,			__A	:    int				,			__A	:    str       ):
		__A   : List[Any]								= self.num_labels
		__A   : Any								= ErnieMForSequenceClassification(__A       )
		model.to(__A       )
		model.eval()
		__A   : Any								= model(__A				,			attention_mask=__A				,			labels=__A       )
		self.parent.assertEqual(result.logits.shape				,			(self.batch_size, self.num_labels)       )




	def 					lowerCAmelCase_					(    self	:    Tuple				,			__A	:    List[Any]				,			__A	:    int				,			__A	:    Any				,			__A	:    Tuple				,			__A	:    Optional[int]				,			__A	:    int       ):
		__A   : Dict								= self.num_labels
		__A   : Optional[int]								= ErnieMForTokenClassification(config=__A       )
		model.to(__A       )
		model.eval()
		input_ids.to(__A       )
		input_mask.to(__A       )
		token_labels.to(__A       )

		__A   : List[Any]								= model(__A				,			attention_mask=__A				,			labels=__A       )

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




	def 					lowerCAmelCase_					(    self	:    List[str]				,			__A	:    Union[str, Any]				,			__A	:    List[Any]				,			__A	:    str				,			__A	:    str				,			__A	:    Optional[int]				,			__A	:    str       ):
		__A   : Tuple								= self.num_choices
		__A   : Any								= ErnieMForMultipleChoice(config=__A       )
		model.to(__A       )
		model.eval()
		__A   : List[Any]								= input_ids.unsqueeze(1       ).expand(-1				,			self.num_choices				,			-1       ).contiguous()
		__A   : str								= input_mask.unsqueeze(1       ).expand(-1				,			self.num_choices				,			-1       ).contiguous()
		__A   : int								= model(
		    __A				,			attention_mask=__A				,			labels=__A				,			)
		self.parent.assertEqual(result.logits.shape				,			(self.batch_size, self.num_choices)       )




	def 					lowerCAmelCase_					(    self	:    Optional[Any]       ):
		__A   : Union[str, Any]								= self.prepare_config_and_inputs()
		(
		    (
		    __A
		)						,							(
		    __A
		)						,							(
		    __A
		)						,							(
		    __A
		)						,							(
		    __A
		)						,							(
		    __A
		)						,							
		)   : Dict								= config_and_inputs
		__A   : Any								= {"""input_ids""": input_ids, """attention_mask""": input_mask}
		return config, inputs_dict






@require_torch
class     lowerCamelCase_			(  _lowercase	,			_lowercase	,			unittest.TestCase  ):
	_lowercase		:      Optional[Any]    				=							(
	    (
	        ErnieMModel,
	        ErnieMForMultipleChoice,
	        ErnieMForQuestionAnswering,
	        ErnieMForSequenceClassification,
	        ErnieMForTokenClassification,
	    )
	    if is_torch_available()
	    else ()
	)
	_lowercase		:      Tuple    				=							()
	_lowercase		:      List[str]    				=							(
	    {
	        '''feature-extraction''': ErnieMModel,
	        '''question-answering''': ErnieMForQuestionAnswering,
	        '''text-classification''': ErnieMForSequenceClassification,
	        '''token-classification''': ErnieMForTokenClassification,
	        '''zero-shot''': ErnieMForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)
	_lowercase		:      Tuple    				=							False




	def 					lowerCAmelCase_					(    self	:    Any				,			__A	:    str				,			__A	:    Tuple				,			__A	:    Tuple				,			__A	:    Optional[int]				,			__A	:    Union[str, Any]       ):
		if pipeline_test_casse_name == "QAPipelineTests":
			return True

		return False




	def 					lowerCAmelCase_					(    self	:    Tuple       ):
		__A   : Any								= ErnieMModelTester(self       )
		__A   : Optional[Any]								= ConfigTester(self				,			config_class=__A				,			hidden_size=37       )




	def 					lowerCAmelCase_					(    self	:    Any       ):
		self.config_tester.run_common_tests()




	def 					lowerCAmelCase_					(    self	:    Dict       ):
		__A   : Union[str, Any]								= self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_model(*__A       )




	def 					lowerCAmelCase_					(    self	:    List[str]       ):
		__A   : Optional[int]								= self.model_tester.prepare_config_and_inputs()
		for type in ["absolute", "relative_key", "relative_key_query"]:
			__A   : Optional[Any]								= type
			self.model_tester.create_and_check_model(*__A       )




	def 					lowerCAmelCase_					(    self	:    Optional[Any]       ):
		__A   : Tuple								= self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_for_multiple_choice(*__A       )




	def 					lowerCAmelCase_					(    self	:    List[str]       ):
		__A   : Tuple								= self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_for_question_answering(*__A       )




	def 					lowerCAmelCase_					(    self	:    Optional[Any]       ):
		__A   : str								= self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_for_sequence_classification(*__A       )




	def 					lowerCAmelCase_					(    self	:    List[str]       ):
		__A   : List[Any]								= self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_for_information_extraction(*__A       )




	def 					lowerCAmelCase_					(    self	:    Dict       ):
		__A   : Dict								= self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_for_token_classification(*__A       )




	@slow
	def 					lowerCAmelCase_					(    self	:    int       ):
		for model_name in ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
			__A   : int								= ErnieMModel.from_pretrained(__A       )
			self.assertIsNotNone(__A       )






@require_torch
class     lowerCamelCase_			(  unittest.TestCase  ):




	@slow
	def 					lowerCAmelCase_					(    self	:    List[Any]       ):
		__A   : str								= ErnieMModel.from_pretrained("""susnato/ernie-m-base_pytorch"""       )
		model.eval()
		__A   : Any								= torch.tensor([[0, 1, 2, 3, 4, 5]]       )
		__A   : Tuple								= model(__A       )[0]

		# TODO Replace vocab size
		__A   : Dict								= 768

		__A   : str								= torch.Size((1, 6, hidden_size)       )
		self.assertEqual(output.shape				,			__A       )

		__A   : int								= torch.tensor(
		    [[[-0.0_0_1_2, 0.1_2_4_5, -0.0_2_1_4], [-0.0_7_4_2, 0.0_2_4_4, -0.0_7_7_1], [-0.0_3_3_3, 0.1_1_6_4, -0.1_5_5_4]]]       )

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








import unittest
from pathlib import Path

from transformers import is_vision_available, load_tool
from transformers.testing_utils import get_tests_dir

from .test_tools_common import ToolTesterMixin


if is_vision_available():
			from PIL import Image






class     lowerCamelCase_			(  unittest.TestCase	,			_lowercase  ):




	def 					lowerCAmelCase_					(    self	:    Dict       ):
		__A   : str								= load_tool("""image-captioning"""       )
		self.tool.setup()
		__A   : Dict								= load_tool("""image-captioning"""				,			remote=__A       )




	def 					lowerCAmelCase_					(    self	:    Optional[int]       ):
		__A   : List[Any]								= Image.open(Path(get_tests_dir("""fixtures/tests_samples/COCO"""       )       ) / """000000039769.png"""       )
		__A   : Optional[Any]								= self.tool(__A       )
		self.assertEqual(__A				,			"""two cats sleeping on a couch"""       )




	def 					lowerCAmelCase_					(    self	:    Dict       ):
		__A   : Any								= Image.open(Path(get_tests_dir("""fixtures/tests_samples/COCO"""       )       ) / """000000039769.png"""       )
		__A   : List[str]								= self.remote_tool(__A       )
		self.assertEqual(__A				,			"""two cats sleeping on a couch"""       )




	def 					lowerCAmelCase_					(    self	:    Union[str, Any]       ):
		__A   : Optional[Any]								= Image.open(Path(get_tests_dir("""fixtures/tests_samples/COCO"""       )       ) / """000000039769.png"""       )
		__A   : str								= self.tool(image=__A       )
		self.assertEqual(__A				,			"""two cats sleeping on a couch"""       )




	def 					lowerCAmelCase_					(    self	:    str       ):
		__A   : Dict								= Image.open(Path(get_tests_dir("""fixtures/tests_samples/COCO"""       )       ) / """000000039769.png"""       )
		__A   : List[Any]								= self.remote_tool(image=__A       )
		self.assertEqual(__A				,			"""two cats sleeping on a couch"""       )





