




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:					List[Any]       ,			UpperCamelCase_:					Any       ,			UpperCamelCase_:					str=13       ,			UpperCamelCase_:					Union[str, Any]=7       ,			UpperCamelCase_:					Dict=True       ,			UpperCamelCase_:					int=True       ,			UpperCamelCase_:					Union[str, Any]=True       ,			UpperCamelCase_:					Any=99       ,			UpperCamelCase_:					Any=32       ,			UpperCamelCase_:					Dict=5       ,			UpperCamelCase_:					List[Any]=4       ,			UpperCamelCase_:					Optional[Any]=37       ,			UpperCamelCase_:					Union[str, Any]="gelu"       ,			UpperCamelCase_:					Optional[int]=0.1       ,			UpperCamelCase_:					str=0.1       ,			UpperCamelCase_:					List[str]=5_12       ,			UpperCamelCase_:					Optional[int]=16       ,			UpperCamelCase_:					str=2       ,			UpperCamelCase_:					Tuple=0.02       ,			UpperCamelCase_:					Union[str, Any]=3       ,			UpperCamelCase_:					Dict=4       ,			UpperCamelCase_:					List[Any]=None       ,			):
             __lowerCamelCase  =		parent
             __lowerCamelCase  =		batch_size
             __lowerCamelCase  =		seq_length
             __lowerCamelCase  =		is_training
             __lowerCamelCase  =		use_input_mask
             __lowerCamelCase  =		use_labels
             __lowerCamelCase  =		vocab_size
             __lowerCamelCase  =		hidden_size
             __lowerCamelCase  =		num_hidden_layers
             __lowerCamelCase  =		num_attention_heads
             __lowerCamelCase  =		intermediate_size
             __lowerCamelCase  =		hidden_act
             __lowerCamelCase  =		hidden_dropout_prob
             __lowerCamelCase  =		attention_probs_dropout_prob
             __lowerCamelCase  =		max_position_embeddings
             __lowerCamelCase  =		type_vocab_size
             __lowerCamelCase  =		type_sequence_label_size
             __lowerCamelCase  =		initializer_range
             __lowerCamelCase  =		num_labels
             __lowerCamelCase  =		num_choices
             __lowerCamelCase  =		scope
      def      lowerCAmelCase__		(							self:					Optional[Any]  ):
             __lowerCamelCase  =		ids_tensor([self.batch_size, self.seq_length]       ,			self.vocab_size  )

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

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

             __lowerCamelCase  =		self.get_config()

             return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
      def      lowerCAmelCase__		(							self:					str  ):
             __lowerCamelCase  =		ids_tensor([self.batch_size, self.seq_length]       ,			self.vocab_size  )

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

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

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




      def      lowerCAmelCase__		(							self:					Tuple  ):
             __lowerCamelCase  =		self.prepare_config_and_inputs()
             (
                 (
                 __lowerCamelCase
             ),  (
                 __lowerCamelCase
             ),  (
                 __lowerCamelCase
             ),  (
                 __lowerCamelCase
             ),  (
                 __lowerCamelCase
             ),  (
                 __lowerCamelCase
             ),  
             )  =		config_and_inputs
             __lowerCamelCase  =		{"""input_ids""": input_ids, """attention_mask""": input_mask}
             return config, inputs_dict





@require_torch
class        lowerCamelCase__(   __lowerCamelCase					,	__lowerCamelCase					,	unittest.TestCase):
      UpperCAmelCase__ :      int       						=  (
          (
              ErnieMModel,
              ErnieMForMultipleChoice,
              ErnieMForQuestionAnswering,
              ErnieMForSequenceClassification,
              ErnieMForTokenClassification,
          )
          if is_torch_available()
          else ()
      )
      UpperCAmelCase__ :      Any       						=  ()
      UpperCAmelCase__ :      Tuple       						=  (
          {
              'feature-extraction': ErnieMModel,
              'question-answering': ErnieMForQuestionAnswering,
              'text-classification': ErnieMForSequenceClassification,
              'token-classification': ErnieMForTokenClassification,
              'zero-shot': ErnieMForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )
      UpperCAmelCase__ :      str       						=  False
      def      lowerCAmelCase__		(							self:					Union[str, Any]       ,			UpperCamelCase_:					Optional[Any]       ,			UpperCamelCase_:					List[Any]       ,			UpperCamelCase_:					List[Any]       ,			UpperCamelCase_:					List[str]       ,			UpperCamelCase_:					Optional[Any]  ):
             if pipeline_test_casse_name == "QAPipelineTests":
                    return True

             return False
      def      lowerCAmelCase__		(							self:					Union[str, Any]  ):
             __lowerCamelCase  =		ErnieMModelTester(self  )
             __lowerCamelCase  =		ConfigTester(self       ,			config_class=UpperCamelCase_       ,			hidden_size=37  )
      def      lowerCAmelCase__		(							self:					Optional[Any]  ):
             self.config_tester.run_common_tests()
      def      lowerCAmelCase__		(							self:					Optional[int]  ):
             __lowerCamelCase  =		self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*UpperCamelCase_  )
      def      lowerCAmelCase__		(							self:					Optional[Any]  ):
             __lowerCamelCase  =		self.model_tester.prepare_config_and_inputs()
             for type in ["absolute", "relative_key", "relative_key_query"]:
                    __lowerCamelCase  =		type
                    self.model_tester.create_and_check_model(*UpperCamelCase_  )
      def      lowerCAmelCase__		(							self:					Tuple  ):
             __lowerCamelCase  =		self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_multiple_choice(*UpperCamelCase_  )
      def      lowerCAmelCase__		(							self:					Tuple  ):
             __lowerCamelCase  =		self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_question_answering(*UpperCamelCase_  )
      def      lowerCAmelCase__		(							self:					Optional[Any]  ):
             __lowerCamelCase  =		self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase_  )
      def      lowerCAmelCase__		(							self:					Optional[Any]  ):
             __lowerCamelCase  =		self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_information_extraction(*UpperCamelCase_  )
      def      lowerCAmelCase__		(							self:					str  ):
             __lowerCamelCase  =		self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_token_classification(*UpperCamelCase_  )




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





@require_torch
class        lowerCamelCase__(   unittest.TestCase):
      @slow
      def      lowerCAmelCase__		(							self:					Optional[Any]  ):
             __lowerCamelCase  =		ErnieMModel.from_pretrained("""susnato/ernie-m-base_pytorch"""  )
             model.eval()
             __lowerCamelCase  =		torch.tensor([[0, 1, 2, 3, 4, 5]]  )
             __lowerCamelCase  =		model(UpperCamelCase_  )[0]

             # TODO Replace vocab size
             __lowerCamelCase  =		7_68

             __lowerCamelCase  =		torch.Size((1, 6, hidden_size)  )
             self.assertEqual(output.shape       ,			UpperCamelCase_  )

             __lowerCamelCase  =		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 __future__ import annotations

from collections.abc import Iterable





class        lowerCamelCase__:
      def __init__(							self:					Dict       ,			UpperCamelCase_:					int       ,			UpperCamelCase_:					str  ):
             __lowerCamelCase,  __lowerCamelCase  =		float(UpperCamelCase_  ), float(UpperCamelCase_  )
      def __eq__(							self:					List[Any]       ,			UpperCamelCase_:					List[str]  ):
             return self.x == other.x and self.y == other.y
      def __ne__(							self:					Tuple       ,			UpperCamelCase_:					Dict  ):
             return not self == other
      def __gt__(							self:					List[Any]       ,			UpperCamelCase_:					List[Any]  ):
             if self.x > other.x:
                    return True
             elif self.x == other.x:
                    return self.y > other.y
             return False
      def __lt__(							self:					str       ,			UpperCamelCase_:					int  ):
             return not self > other
      def __ge__(							self:					Dict       ,			UpperCamelCase_:					Any  ):
             if self.x > other.x:
                    return True
             elif self.x == other.x:
                    return self.y >= other.y
             return False
      def __le__(							self:					Union[str, Any]       ,			UpperCamelCase_:					Optional[Any]  ):
             if self.x < other.x:
                    return True
             elif self.x == other.x:
                    return self.y <= other.y
             return False
      def __repr__(							self:					Union[str, Any]  ):
             return F'({self.x}, {self.y})'




      def __hash__(							self:					List[Any]  ):
             return hash(self.x  )




def    lowerCamelCase__			(		A__			:   list[Point] | list[list[float]] | Iterable[list[float]]    ,     ):





       '''simple docstring'''



       __lowerCamelCase  =		[]
       if list_of_tuples:
              for p in list_of_tuples:
                     if isinstance(A__    ,     A__      ):
                            points.append(A__      )
                     else:
                            try:
                                   points.append(Point(p[0]    ,     p[1]      )      )
                            except (IndexError, TypeError):
                                   print(
                                       f'Ignoring deformed point {p}. All points'
                                       """ must have at least 2 coordinates."""      )
       return points




def    lowerCamelCase__			(		A__			:   list[Point] | list[list[float]]      ):





       '''simple docstring'''



       if not hasattr(A__    ,     """__iter__"""      ):
              __lowerCamelCase  =		f'Expecting an iterable object but got an non-iterable type {points}'
              raise ValueError(A__      )

       if not points:
              __lowerCamelCase  =		f'Expecting a list of points but got {points}'
              raise ValueError(A__      )

       return _construct_points(A__      )




def    lowerCamelCase__			(		A__			:   Point    ,     A__			:   Point    ,     A__			:   Point      ):





       '''simple docstring'''



       __lowerCamelCase  =		(a.x * b.y + b.x * c.y + c.x * a.y) - (a.y * b.x + b.y * c.x + c.y * a.x)
       return det




def    lowerCamelCase__			(		A__			:   list[Point]      ):





       '''simple docstring'''



       __lowerCamelCase  =		sorted(_validate_input(A__      )      )
       __lowerCamelCase  =		len(A__      )
       __lowerCamelCase  =		set()

       for i in range(n - 1      ):
              for j in range(i + 1    ,     A__      ):
                     __lowerCamelCase  =		__lowerCamelCase  =		False
                     __lowerCamelCase  =		True
                     for k in range(A__      ):
                            if k != i and k != j:
                                   __lowerCamelCase  =		_det(points[i]    ,     points[j]    ,     points[k]      )

                                   if det_k > 0:
                                          __lowerCamelCase  =		True
                                   elif det_k < 0:
                                          __lowerCamelCase  =		True
                                   else:
                                          # point[i], point[j], point[k] all lie on a straight line
                                          # if point[k] is to the left of point[i] or it's to the
                                          # right of point[j], then point[i], point[j] cannot be
                                          # part of the convex hull of A
                                          if points[k] < points[i] or points[k] > points[j]:
                                                 __lowerCamelCase  =		False
                                                 break

                            if points_left_of_ij and points_right_of_ij:
                                   __lowerCamelCase  =		False
                                   break

                     if ij_part_of_convex_hull:
                            convex_set.update([points[i], points[j]]      )

       return sorted(A__      )




def    lowerCamelCase__			(		A__			:   list[Point]      ):





       '''simple docstring'''



       __lowerCamelCase  =		sorted(_validate_input(A__      )      )
       __lowerCamelCase  =		len(A__      )

       # divide all the points into an upper hull and a lower hull
       # the left most point and the right most point are definitely
       # members of the convex hull by definition.
       # use these two anchors to divide all the points into two hulls,
       # an upper hull and a lower hull.

       # all points to the left (above) the line joining the extreme points belong to the
       # upper hull
       # all points to the right (below) the line joining the extreme points below to the
       # lower hull
       # ignore all points on the line joining the extreme points since they cannot be
       # part of the convex hull

       __lowerCamelCase  =		points[0]
       __lowerCamelCase  =		points[n - 1]

       __lowerCamelCase  =		{left_most_point, right_most_point}
       __lowerCamelCase  =		[]
       __lowerCamelCase  =		[]

       for i in range(1    ,     n - 1      ):
              __lowerCamelCase  =		_det(A__    ,     A__    ,     points[i]      )

              if det > 0:
                     upper_hull.append(points[i]      )
              elif det < 0:
                     lower_hull.append(points[i]      )

       _construct_hull(A__    ,     A__    ,     A__    ,     A__      )
       _construct_hull(A__    ,     A__    ,     A__    ,     A__      )

       return sorted(A__      )




def    lowerCamelCase__			(		A__			:   list[Point]    ,     A__			:   Point    ,     A__			:   Point    ,     A__			:   set[Point]      ):





       '''simple docstring'''



       if points:
              __lowerCamelCase  =		None
              __lowerCamelCase  =		float("""-inf"""      )
              __lowerCamelCase  =		[]

              for p in points:
                     __lowerCamelCase  =		_det(A__    ,     A__    ,     A__      )

                     if det > 0:
                            candidate_points.append(A__      )

                            if det > extreme_point_distance:
                                   __lowerCamelCase  =		det
                                   __lowerCamelCase  =		p

              if extreme_point:
                     _construct_hull(A__    ,     A__    ,     A__    ,     A__      )
                     convex_set.add(A__      )
                     _construct_hull(A__    ,     A__    ,     A__    ,     A__      )




def    lowerCamelCase__			(		A__			:   list[Point]      ):





       '''simple docstring'''



       __lowerCamelCase  =		sorted(_validate_input(A__      )      )
       __lowerCamelCase  =		len(A__      )

       __lowerCamelCase  =		points[:2]
       for i in range(2    ,     A__      ):
              __lowerCamelCase  =		_det(convex_hull[1]    ,     convex_hull[0]    ,     points[i]      )
              if det > 0:
                     convex_hull.insert(0    ,     points[i]      )
                     break
              elif det < 0:
                     convex_hull.append(points[i]      )
                     break
              else:
                     __lowerCamelCase  =		points[i]
       i += 1

       for j in range(A__    ,     A__      ):
              if (
                  _det(convex_hull[0]    ,     convex_hull[-1]    ,     points[j]      ) > 0
                  and _det(convex_hull[-1]    ,     convex_hull[0]    ,     points[1]      ) < 0
              ):
                     # The point lies within the convex hull
                     continue

              convex_hull.insert(0    ,     points[j]      )
              convex_hull.append(points[j]      )
              while _det(convex_hull[0]    ,     convex_hull[1]    ,     convex_hull[2]      ) >= 0:
                     del convex_hull[1]
              while _det(convex_hull[-1]    ,     convex_hull[-2]    ,     convex_hull[-3]      ) <= 0:
                     del convex_hull[-2]

    # `convex_hull` is contains the convex hull in circular order
       return sorted(convex_hull[1:] if len(A__      ) > 3 else convex_hull      )




def    lowerCamelCase__			(		):





       '''simple docstring'''



       __lowerCamelCase  =		[
           (0, 3),
           (2, 2),
           (1, 1),
           (2, 1),
           (3, 0),
           (0, 0),
           (3, 3),
           (2, -1),
           (2, -4),
           (1, -3),
       ]
       # the convex set of points is
       # [(0, 0), (0, 3), (1, -3), (2, -4), (3, 0), (3, 3)]
       __lowerCamelCase  =		convex_hull_bf(A__      )

       __lowerCamelCase  =		convex_hull_recursive(A__      )
       assert results_bf == results_recursive

       __lowerCamelCase  =		convex_hull_melkman(A__      )
       assert results_bf == results_melkman

       print(A__      )


if __name__ == "__main__":
       main()

