



"""simple docstring"""







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							,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_=5_12							,UpperCAmelCase_=16							,UpperCAmelCase_=2							,UpperCAmelCase_=0.02							,UpperCAmelCase_=3							,UpperCAmelCase_=4							,UpperCAmelCase_=None							,):
			_lowercase							:      Union[str, Any]			=					parent
			_lowercase							:      str			=					batch_size
			_lowercase							:      Tuple			=					seq_length
			_lowercase							:      List[str]			=					is_training
			_lowercase							:      Optional[Any]			=					use_input_mask
			_lowercase							:      str			=					use_labels
			_lowercase							:      int			=					vocab_size
			_lowercase							:      Optional[int]			=					hidden_size
			_lowercase							:      List[str]			=					num_hidden_layers
			_lowercase							:      str			=					num_attention_heads
			_lowercase							:      str			=					intermediate_size
			_lowercase							:      Optional[Any]			=					hidden_act
			_lowercase							:      Union[str, Any]			=					hidden_dropout_prob
			_lowercase							:      List[Any]			=					attention_probs_dropout_prob
			_lowercase							:      Dict			=					max_position_embeddings
			_lowercase							:      Optional[Any]			=					type_vocab_size
			_lowercase							:      Any			=					type_sequence_label_size
			_lowercase							:      Any			=					initializer_range
			_lowercase							:      Any			=					num_labels
			_lowercase							:      Tuple			=					num_choices
			_lowercase							:      Any			=					scope






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      int			=					ids_tensor([self.batch_size, self.seq_length]							,self.vocab_size					)

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

			_lowercase							:      str			=					None
			_lowercase							:      Optional[Any]			=					None
			_lowercase							:      Optional[int]			=					None
			if self.use_labels:
					_lowercase							:      int			=					ids_tensor([self.batch_size]							,self.type_sequence_label_size					)
					_lowercase							:      Dict			=					ids_tensor([self.batch_size, self.seq_length]							,self.num_labels					)
					_lowercase							:      Any			=					ids_tensor([self.batch_size]							,self.num_choices					)

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

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






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      str			=					ids_tensor([self.batch_size, self.seq_length]							,self.vocab_size					)

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

			return config, input_ids, input_mask






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






	def 					lowerCamelCase__ (			self							,UpperCAmelCase_							,UpperCAmelCase_							,UpperCAmelCase_							,UpperCAmelCase_							,UpperCAmelCase_							,UpperCAmelCase_					):
			_lowercase							:      List[str]			=					self.num_labels
			_lowercase							:      str			=					ErnieMForTokenClassification(config=UpperCAmelCase_					)
			model.to(UpperCAmelCase_					)
			model.eval()
			input_ids.to(UpperCAmelCase_					)
			input_mask.to(UpperCAmelCase_					)
			token_labels.to(UpperCAmelCase_					)

			_lowercase							:      List[Any]			=					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							,UpperCAmelCase_							,UpperCAmelCase_							,UpperCAmelCase_							,UpperCAmelCase_							,UpperCAmelCase_							,UpperCAmelCase_					):
			_lowercase							:      Tuple			=					self.num_choices
			_lowercase							:      Optional[int]			=					ErnieMForMultipleChoice(config=UpperCAmelCase_					)
			model.to(UpperCAmelCase_					)
			model.eval()
			_lowercase							:      List[str]			=					input_ids.unsqueeze(1					).expand(-1							,self.num_choices							,-1					).contiguous()
			_lowercase							:      str			=					input_mask.unsqueeze(1					).expand(-1							,self.num_choices							,-1					).contiguous()
			_lowercase							:      Any			=					model(
			    UpperCAmelCase_							,attention_mask=UpperCAmelCase_							,labels=UpperCAmelCase_							,)
			self.parent.assertEqual(result.logits.shape							,(self.batch_size, self.num_choices)					)






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      Tuple			=					self.prepare_config_and_inputs()
			(
			    (
			    _lowercase					
			)			,   (
			    _lowercase					
			)			,   (
			    _lowercase					
			)			,   (
			    _lowercase					
			)			,   (
			    _lowercase					
			)			,   (
			    _lowercase					
			)			,   					
			)							:      Optional[int]			=					config_and_inputs
			_lowercase							:      int			=					{"""input_ids""": input_ids, """attention_mask""": input_mask}
			return config, inputs_dict







@require_torch
class    UpperCamelCase     (			snake_case ,					snake_case ,					unittest.TestCase    ):




	"""simple docstring"""
	SCREAMING_SNAKE_CASE_				:    Optional[int]		    =   (
	    (
	        ErnieMModel,
	        ErnieMForMultipleChoice,
	        ErnieMForQuestionAnswering,
	        ErnieMForSequenceClassification,
	        ErnieMForTokenClassification,
	    )
	    if is_torch_available()
	    else ()
	)
	SCREAMING_SNAKE_CASE_				:    Union[str, Any]		    =   ()
	SCREAMING_SNAKE_CASE_				:    Union[str, Any]		    =   (
	    {
	        "feature-extraction": ErnieMModel,
	        "question-answering": ErnieMForQuestionAnswering,
	        "text-classification": ErnieMForSequenceClassification,
	        "token-classification": ErnieMForTokenClassification,
	        "zero-shot": ErnieMForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)
	SCREAMING_SNAKE_CASE_				:    str		    =   False






	def 					lowerCamelCase__ (			self							,UpperCAmelCase_							,UpperCAmelCase_							,UpperCAmelCase_							,UpperCAmelCase_							,UpperCAmelCase_					):
			if pipeline_test_casse_name == "QAPipelineTests":
					return True

			return False






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      List[Any]			=					ErnieMModelTester(self					)
			_lowercase							:      Optional[Any]			=					ConfigTester(self							,config_class=UpperCAmelCase_							,hidden_size=37					)






	def 					lowerCamelCase__ (			self					):
			self.config_tester.run_common_tests()






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      Union[str, Any]			=					self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*UpperCAmelCase_					)






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      int			=					self.model_tester.prepare_config_and_inputs()
			for type in ["absolute", "relative_key", "relative_key_query"]:
					_lowercase							:      Any			=					type
					self.model_tester.create_and_check_model(*UpperCAmelCase_					)






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      Union[str, Any]			=					self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_multiple_choice(*UpperCAmelCase_					)






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      Optional[Any]			=					self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_question_answering(*UpperCAmelCase_					)






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      int			=					self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_sequence_classification(*UpperCAmelCase_					)






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      List[str]			=					self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_information_extraction(*UpperCAmelCase_					)






	def 					lowerCamelCase__ (			self					):
			_lowercase							:      Optional[Any]			=					self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_token_classification(*UpperCAmelCase_					)






	@slow
	def 					lowerCamelCase__ (			self					):
			for model_name in ERNIE_M_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
					_lowercase							:      List[str]			=					ErnieMModel.from_pretrained(UpperCAmelCase_					)
					self.assertIsNotNone(UpperCAmelCase_					)







@require_torch
class    UpperCamelCase     (			unittest.TestCase    ):




	"""simple docstring"""






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

			# TODO Replace vocab size
			_lowercase							:      List[Any]			=					7_68

			_lowercase							:      int			=					torch.Size((1, 6, hidden_size)					)
			self.assertEqual(output.shape							,UpperCAmelCase_					)

			_lowercase							:      Any			=					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					)					)











"""simple docstring"""







from __future__ import annotations

from typing import Generic, TypeVar

_UpperCamelCase     			=  TypeVar("""T""")







class 					lowerCamelCase__					(       Generic[T] ):






    def __init__( self	,A					):
          UpperCAmelCase							=       data  # Assign data
          UpperCAmelCase							=       None  # Initialize next as null
          UpperCAmelCase							=       None  # Initialize prev as null







class 					lowerCamelCase__					(       Generic[T] ):






    def __init__( self					):
          UpperCAmelCase							=       None






    def 				_UpperCamelCase							( self	,A					):
          if self.head is None:
                UpperCAmelCase							=       Node(A					)
          else:
                UpperCAmelCase							=       Node(A					)
                UpperCAmelCase							=       new_node
                UpperCAmelCase							=       self.head
                UpperCAmelCase							=       None
                UpperCAmelCase							=       new_node






    def 				_UpperCamelCase							( self					):
          if self.head is None:
                return None
          else:
                assert self.head is not None
                UpperCAmelCase							=       self.head.data
                UpperCAmelCase							=       self.head.next
                if self.head is not None:
                      UpperCAmelCase							=       None
                return temp






    def 				_UpperCamelCase							( self					):
          return self.head.data if self.head is not None else None






    def __len__( self					):
          UpperCAmelCase							=       self.head
          UpperCAmelCase							=       0
          while temp is not None:
                count += 1
                UpperCAmelCase							=       temp.next
          return count






    def 				_UpperCamelCase							( self					):
          return self.head is None






    def 				_UpperCamelCase							( self					):
          print("""stack elements are:"""					)
          UpperCAmelCase							=       self.head
          while temp is not None:
                print(temp.data	,end="""->"""					)
                UpperCAmelCase							=       temp.next


# Code execution starts here
if __name__ == "__main__":
  # Start with the empty stack
  _UpperCamelCase     			=  Stack()

  # Insert 4 at the beginning. So stack becomes 4->None
  print("""Stack operations using Doubly LinkedList""")
  stack.push(4)

  # Insert 5 at the beginning. So stack becomes 4->5->None
  stack.push(5)

  # Insert 6 at the beginning. So stack becomes 4->5->6->None
  stack.push(6)

  # Insert 7 at the beginning. So stack becomes 4->5->6->7->None
  stack.push(7)

  # Print the stack
  stack.print_stack()

  # Print the top element
  print("""\nTop element is """, stack.top())

  # Print the stack size
  print("""Size of the stack is """, len(stack))

  # pop the top element
  stack.pop()

  # pop the top element
  stack.pop()

  # two elements have now been popped off
  stack.print_stack()

  # Print True if the stack is empty else False
  print("""\nstack is empty:""", stack.is_empty())



