






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			:





							"""simple docstring"""






							def __init__(							self	,   UpperCAmelCase	,   UpperCAmelCase=13	,   UpperCAmelCase=7	,   UpperCAmelCase=True	,   UpperCAmelCase=True	,   UpperCAmelCase=True	,   UpperCAmelCase=99	,   UpperCAmelCase=32	,   UpperCAmelCase=5	,   UpperCAmelCase=4	,   UpperCAmelCase=37	,   UpperCAmelCase="gelu"	,   UpperCAmelCase=0.1	,   UpperCAmelCase=0.1	,   UpperCAmelCase=512	,   UpperCAmelCase=16	,   UpperCAmelCase=2	,   UpperCAmelCase=0.02	,   UpperCAmelCase=3	,   UpperCAmelCase=4	,   UpperCAmelCase=None	,   ):
													"""simple docstring"""







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

							def 	UpperCamelCase   (							self   ):
													"""simple docstring"""







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

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

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

													_UpperCAmelCase     =      self.get_config()

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

							def 	UpperCamelCase   (							self   ):
													"""simple docstring"""







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

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

													return config, input_ids, input_mask

							def 	UpperCamelCase   (							self   ):
													"""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 	UpperCamelCase   (							self	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase   ):
													"""simple docstring"""







													_UpperCAmelCase     =      ErnieMModel(config=UpperCAmelCase   )
													model.to(UpperCAmelCase   )
													model.eval()
													_UpperCAmelCase     =      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	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase   ):
													"""simple docstring"""







													_UpperCAmelCase     =      ErnieMForQuestionAnswering(config=UpperCAmelCase   )
													model.to(UpperCAmelCase   )
													model.eval()
													_UpperCAmelCase     =      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	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase   ):
													"""simple docstring"""







													_UpperCAmelCase     =      ErnieMForInformationExtraction(config=UpperCAmelCase   )
													model.to(UpperCAmelCase   )
													model.eval()
													_UpperCAmelCase     =      torch.ones_like(UpperCAmelCase	,   dtype=torch.floataa   )
													_UpperCAmelCase     =      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	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase   ):
													"""simple docstring"""







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

							def 	UpperCamelCase   (							self	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase   ):
													"""simple docstring"""







													_UpperCAmelCase     =      self.num_labels
													_UpperCAmelCase     =      ErnieMForTokenClassification(config=UpperCAmelCase   )
													model.to(UpperCAmelCase   )
													model.eval()
													input_ids.to(UpperCAmelCase   )
													input_mask.to(UpperCAmelCase   )
													token_labels.to(UpperCAmelCase   )

													_UpperCAmelCase     =      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	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase   ):
													"""simple docstring"""







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

							def 	UpperCamelCase   (							self   ):
													"""simple docstring"""







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





@require_torch
class __lowerCamelCase			(				snake_case__					,	snake_case__					,	unittest.TestCase):





							"""simple docstring"""






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

							def 	UpperCamelCase   (							self	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase   ):
													"""simple docstring"""







													if pipeline_test_casse_name == "QAPipelineTests":
																			return True

													return False

							def 	UpperCamelCase   (							self   ):
													"""simple docstring"""







													_UpperCAmelCase     =      ErnieMModelTester(self   )
													_UpperCAmelCase     =      ConfigTester(self	,   config_class=UpperCAmelCase	,   hidden_size=37   )

							def 	UpperCamelCase   (							self   ):
													"""simple docstring"""







													self.config_tester.run_common_tests()

							def 	UpperCamelCase   (							self   ):
													"""simple docstring"""







													_UpperCAmelCase     =      self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*UpperCAmelCase   )

							def 	UpperCamelCase   (							self   ):
													"""simple docstring"""







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

							def 	UpperCamelCase   (							self   ):
													"""simple docstring"""







													_UpperCAmelCase     =      self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_multiple_choice(*UpperCAmelCase   )

							def 	UpperCamelCase   (							self   ):
													"""simple docstring"""







													_UpperCAmelCase     =      self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase   )

							def 	UpperCamelCase   (							self   ):
													"""simple docstring"""







													_UpperCAmelCase     =      self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase   )

							def 	UpperCamelCase   (							self   ):
													"""simple docstring"""







													_UpperCAmelCase     =      self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_information_extraction(*UpperCAmelCase   )

							def 	UpperCamelCase   (							self   ):
													"""simple docstring"""







													_UpperCAmelCase     =      self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase   )

							@slow
							def 	UpperCamelCase   (							self   ):
													"""simple docstring"""







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





@require_torch
class __lowerCamelCase			(				unittest.TestCase):





							"""simple docstring"""






							@slow
							def 	UpperCamelCase   (							self   ):
													"""simple docstring"""







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

													# TODO Replace vocab size
													_UpperCAmelCase     =      768

													_UpperCAmelCase     =      torch.Size((1, 6, hidden_size)   )
													self.assertEqual(output.shape	,   UpperCAmelCase   )

													_UpperCAmelCase     =      torch.tensor(
													    [[[-0.00_12, 0.12_45, -0.02_14], [-0.07_42, 0.02_44, -0.07_71], [-0.03_33, 0.11_64, -0.15_54]]]   )

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








import unittest

import pytest

from transformers import (
    MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
    MBartaaTokenizerFast,
    MBartConfig,
    MBartForConditionalGeneration,
    TranslationPipeline,
    pipeline,
)
from transformers.testing_utils import is_pipeline_test, require_tf, require_torch, slow

from .test_pipelines_common import ANY





@is_pipeline_test
class __lowerCamelCase			(				unittest.TestCase):





	"""simple docstring"""






	UpperCamelCase__								=				MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING
	UpperCamelCase__								=				TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING

	def 	UpperCamelCase   (							self	,   UpperCAmelCase	,   UpperCAmelCase	,   UpperCAmelCase   ):
							"""simple docstring"""







							if isinstance(model.config	,   UpperCAmelCase   ):
													_UpperCAmelCase ,			_UpperCAmelCase     =      list(tokenizer.lang_code_to_id.keys()   )[:2]
													_UpperCAmelCase     =      TranslationPipeline(model=UpperCAmelCase	,   tokenizer=UpperCAmelCase	,   src_lang=UpperCAmelCase	,   tgt_lang=UpperCAmelCase   )
							else:
													_UpperCAmelCase     =      TranslationPipeline(model=UpperCAmelCase	,   tokenizer=UpperCAmelCase   )
							return translator, ["Some string", "Some other text"]

	def 	UpperCamelCase   (							self	,   UpperCAmelCase	,   UpperCAmelCase   ):
							"""simple docstring"""







							_UpperCAmelCase     =      translator('Some string'   )
							self.assertEqual(UpperCAmelCase	,   [{'translation_text': ANY(UpperCAmelCase   )}]   )

							_UpperCAmelCase     =      translator(['Some string']   )
							self.assertEqual(UpperCAmelCase	,   [{'translation_text': ANY(UpperCAmelCase   )}]   )

							_UpperCAmelCase     =      translator(['Some string', 'other string']   )
							self.assertEqual(UpperCAmelCase	,   [{'translation_text': ANY(UpperCAmelCase   )}, {'translation_text': ANY(UpperCAmelCase   )}]   )

	@require_torch
	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							_UpperCAmelCase     =      pipeline('translation_en_to_ro'	,   model='patrickvonplaten/t5-tiny-random'	,   framework='pt'   )
							_UpperCAmelCase     =      translator('This is a test string'	,   max_length=20   )
							self.assertEqual(
							    UpperCAmelCase	,   [
							        {
							            'translation_text': (
							                'Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide'
							                ' Beide Beide'
							            )
							        }
							    ]	,   )

	@require_tf
	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							_UpperCAmelCase     =      pipeline('translation_en_to_ro'	,   model='patrickvonplaten/t5-tiny-random'	,   framework='tf'   )
							_UpperCAmelCase     =      translator('This is a test string'	,   max_length=20   )
							self.assertEqual(
							    UpperCAmelCase	,   [
							        {
							            'translation_text': (
							                'Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide Beide'
							                ' Beide Beide'
							            )
							        }
							    ]	,   )

	@require_torch
	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							_UpperCAmelCase     =      pipeline('translation_en_to_de'	,   model='patrickvonplaten/t5-tiny-random'	,   framework='pt'   )
							_UpperCAmelCase     =      translator('This is a test string'	,   max_length=20   )
							self.assertEqual(
							    UpperCAmelCase	,   [
							        {
							            'translation_text': (
							                'monoton monoton monoton monoton monoton monoton monoton monoton monoton monoton urine urine'
							                ' urine urine urine urine urine urine urine'
							            )
							        }
							    ]	,   )

	@require_tf
	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							_UpperCAmelCase     =      pipeline('translation_en_to_de'	,   model='patrickvonplaten/t5-tiny-random'	,   framework='tf'   )
							_UpperCAmelCase     =      translator('This is a test string'	,   max_length=20   )
							self.assertEqual(
							    UpperCAmelCase	,   [
							        {
							            'translation_text': (
							                'monoton monoton monoton monoton monoton monoton monoton monoton monoton monoton urine urine'
							                ' urine urine urine urine urine urine urine'
							            )
							        }
							    ]	,   )





class __lowerCamelCase			(				unittest.TestCase):





	"""simple docstring"""






	@require_torch
	@slow
	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							with self.assertRaises(UpperCAmelCase   ):
													pipeline(task='translation_cn_to_ar'   )

							# but we do for this one
							_UpperCAmelCase     =      pipeline(task='translation_en_to_de'   )
							self.assertEqual(translator._preprocess_params['src_lang']	,   'en'   )
							self.assertEqual(translator._preprocess_params['tgt_lang']	,   'de'   )

	@require_torch
	@slow
	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							_UpperCAmelCase     =      MBartForConditionalGeneration.from_pretrained('facebook/mbart-large-50-many-to-many-mmt'   )
							_UpperCAmelCase     =      MBartaaTokenizerFast.from_pretrained('facebook/mbart-large-50-many-to-many-mmt'   )

							_UpperCAmelCase     =      pipeline(task='translation'	,   model=UpperCAmelCase	,   tokenizer=UpperCAmelCase   )
							# Missing src_lang, tgt_lang
							with self.assertRaises(UpperCAmelCase   ):
													translator('This is a test'   )

							_UpperCAmelCase     =      translator('This is a test'	,   src_lang='en_XX'	,   tgt_lang='ar_AR'   )
							self.assertEqual(UpperCAmelCase	,   [{'translation_text': 'هذا إختبار'}]   )

							_UpperCAmelCase     =      translator('This is a test'	,   src_lang='en_XX'	,   tgt_lang='hi_IN'   )
							self.assertEqual(UpperCAmelCase	,   [{'translation_text': 'यह एक परीक्षण है'}]   )

							# src_lang, tgt_lang can be defined at pipeline call time
							_UpperCAmelCase     =      pipeline(task='translation'	,   model=UpperCAmelCase	,   tokenizer=UpperCAmelCase	,   src_lang='en_XX'	,   tgt_lang='ar_AR'   )
							_UpperCAmelCase     =      translator('This is a test'   )
							self.assertEqual(UpperCAmelCase	,   [{'translation_text': 'هذا إختبار'}]   )

	@require_torch
	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							_UpperCAmelCase     =      'patrickvonplaten/t5-tiny-random'
							_UpperCAmelCase     =      pipeline(task='translation_cn_to_ar'	,   model=UpperCAmelCase   )
							self.assertEqual(translator._preprocess_params['src_lang']	,   'cn'   )
							self.assertEqual(translator._preprocess_params['tgt_lang']	,   'ar'   )

	@require_torch
	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							_UpperCAmelCase     =      'patrickvonplaten/t5-tiny-random'
							with pytest.warns(UpperCAmelCase	,   match=R'.*translation_en_to_de.*'   ):
													_UpperCAmelCase     =      pipeline(task='translation'	,   model=UpperCAmelCase   )
							self.assertEqual(translator.task	,   'translation_en_to_de'   )
							self.assertEqual(translator._preprocess_params['src_lang']	,   'en'   )
							self.assertEqual(translator._preprocess_params['tgt_lang']	,   'de'   )

	@require_torch
	def 	UpperCamelCase   (							self   ):
							"""simple docstring"""







							with self.assertRaises(UpperCAmelCase   ):
													pipeline(task='translation'   )
