






"""simple docstring"""




from __future__ import annotations

from collections.abc import Iterable




class  lowercase_     :






      def __init__(     self  ,  a_  ,  a_						)						->Tuple:







        '''simple docstring'''


        _a					      =						float(_UpperCAmelCase						), float(_UpperCAmelCase						)






      def __eq__(     self  ,  a_						)						->int:







        '''simple docstring'''


        return self.x == other.x and self.y == other.y






      def __ne__(     self  ,  a_						)						->int:







        '''simple docstring'''


        return not self == other






      def __gt__(     self  ,  a_						)						->str:







        '''simple docstring'''


        if self.x > other.x:
          return True
        elif self.x == other.x:
          return self.y > other.y
        return False






      def __lt__(     self  ,  a_						)						->List[Any]:







        '''simple docstring'''


        return not self > other






      def __ge__(     self  ,  a_						)						->Optional[int]:







        '''simple docstring'''


        if self.x > other.x:
          return True
        elif self.x == other.x:
          return self.y >= other.y
        return False






      def __le__(     self  ,  a_						)						->Optional[Any]:







        '''simple docstring'''


        if self.x < other.x:
          return True
        elif self.x == other.x:
          return self.y <= other.y
        return False






      def __repr__(     self						)						->Dict:







        '''simple docstring'''


        return f'''({self.x}, {self.y})'''






      def __hash__(     self						)						->Union[str, Any]:







        '''simple docstring'''


        return hash(self.x						)







def 							lowerCAmelCase			(   UpperCamelCase_:				str  ,			)							->				Any:







  '''simple docstring'''







  _a					      =						[]
  if list_of_tuples:
    for p in list_of_tuples:
      if isinstance(snake_case__  ,			snake_case__       ):
        points.append(snake_case__       )
      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			(   UpperCamelCase_:				int       )							->				str:







  '''simple docstring'''







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

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

  return _construct_points(snake_case__       )






def 							lowerCAmelCase			(   UpperCamelCase_:				Any  ,			UpperCamelCase_:				Any  ,			UpperCamelCase_:				Optional[Any]       )							->				Union[str, Any]:







  '''simple docstring'''







  _a					      =						(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			(   UpperCamelCase_:				Any       )							->				str:







  '''simple docstring'''







  _a					      =						sorted(_validate_input(snake_case__       )       )
  _a					      =						len(snake_case__       )
  _a					      =						set()

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

          if det_k > 0:
            _a					      =						True
          elif det_k < 0:
            _a					      =						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]:
              _a					      =						False
              break

        if points_left_of_ij and points_right_of_ij:
          _a					      =						False
          break

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

  return sorted(snake_case__       )






def 							lowerCAmelCase			(   UpperCamelCase_:				Dict       )							->				List[Any]:







  '''simple docstring'''







  _a					      =						sorted(_validate_input(snake_case__       )       )
  _a					      =						len(snake_case__       )

  # 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

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

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

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

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

  _construct_hull(snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__       )
  _construct_hull(snake_case__  ,			snake_case__  ,			snake_case__  ,			snake_case__       )

  return sorted(snake_case__       )






def 							lowerCAmelCase			(   UpperCamelCase_:				Dict  ,			UpperCamelCase_:				Dict  ,			UpperCamelCase_:				Dict  ,			UpperCamelCase_:				Union[str, Any]       )							->				Optional[Any]:







  '''simple docstring'''







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

    for p in points:
      _a					      =						_det(snake_case__  ,			snake_case__  ,			snake_case__       )

      if det > 0:
        candidate_points.append(snake_case__       )

        if det > extreme_point_distance:
          _a					      =						det
          _a					      =						p

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






def 							lowerCAmelCase			(   UpperCamelCase_:				str       )							->				Optional[Any]:







  '''simple docstring'''







  _a					      =						sorted(_validate_input(snake_case__       )       )
  _a					      =						len(snake_case__       )

  _a					      =						points[:2]
  for i in range(2  ,			snake_case__       ):
    _a					      =						_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:
      _a					      =						points[i]
  i += 1

  for j in range(snake_case__  ,			snake_case__       ):
    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(snake_case__       ) > 3 else convex_hull       )






def 							lowerCAmelCase			(   )							->				Dict:







  '''simple docstring'''







  _a					      =						[
      (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)]
  _a					      =						convex_hull_bf(snake_case__       )

  _a					      =						convex_hull_recursive(snake_case__       )
  assert results_bf == results_recursive

  _a					      =						convex_hull_melkman(snake_case__       )
  assert results_bf == results_melkman

  print(snake_case__       )


if __name__ == "__main__":
     main()








'''simple docstring'''






import os
import pickle
import unittest
from collections import UserDict, namedtuple

import torch

from accelerate.test_utils.testing import require_cuda, require_torch_min_version
from accelerate.test_utils.training import RegressionModel
from accelerate.utils import (
    convert_outputs_to_fpaa,
    extract_model_from_parallel,
    find_device,
    listify,
    patch_environment,
    recursively_apply,
    send_to_device,
)


_lowerCAmelCase       =   namedtuple('''ExampleNamedTuple''', '''a b c''')



class    A						(					unittest.TestCase						):




				'''simple docstring'''





				def 			a_			(self     )      ->			Tuple:
							__UpperCamelCase :     Optional[int]										=  torch.randn(5					,    2     )
							__UpperCamelCase :     List[str]										=  torch.device("cuda"     ) if torch.cuda.is_available() else torch.device("cpu"     )

							__UpperCamelCase :     Optional[Any]										=  send_to_device(_UpperCAmelCase					,    _UpperCAmelCase     )
							self.assertTrue(torch.equal(resulta.cpu()					,    _UpperCAmelCase     )     )

							__UpperCamelCase :     Any										=  send_to_device((tensor, [tensor, tensor], 1)					,    _UpperCAmelCase     )
							self.assertIsInstance(_UpperCAmelCase					,    _UpperCAmelCase     )
							self.assertTrue(torch.equal(resulta[0].cpu()					,    _UpperCAmelCase     )     )
							self.assertIsInstance(resulta[1]					,    _UpperCAmelCase     )
							self.assertTrue(torch.equal(resulta[1][0].cpu()					,    _UpperCAmelCase     )     )
							self.assertTrue(torch.equal(resulta[1][1].cpu()					,    _UpperCAmelCase     )     )
							self.assertEqual(resulta[2]					,    1     )

							__UpperCamelCase :     Optional[int]										=  send_to_device({"a": tensor, "b": [tensor, tensor], "c": 1}					,    _UpperCAmelCase     )
							self.assertIsInstance(_UpperCAmelCase					,    _UpperCAmelCase     )
							self.assertTrue(torch.equal(resulta["a"].cpu()					,    _UpperCAmelCase     )     )
							self.assertIsInstance(resulta["b"]					,    _UpperCAmelCase     )
							self.assertTrue(torch.equal(resulta["b"][0].cpu()					,    _UpperCAmelCase     )     )
							self.assertTrue(torch.equal(resulta["b"][1].cpu()					,    _UpperCAmelCase     )     )
							self.assertEqual(resulta["c"]					,    1     )

							__UpperCamelCase :     Optional[Any]										=  send_to_device(ExampleNamedTuple(a=_UpperCAmelCase					,    b=[tensor, tensor]					,    c=1     )					,    _UpperCAmelCase     )
							self.assertIsInstance(_UpperCAmelCase					,    _UpperCAmelCase     )
							self.assertTrue(torch.equal(resulta.a.cpu()					,    _UpperCAmelCase     )     )
							self.assertIsInstance(resulta.b					,    _UpperCAmelCase     )
							self.assertTrue(torch.equal(resulta.b[0].cpu()					,    _UpperCAmelCase     )     )
							self.assertTrue(torch.equal(resulta.b[1].cpu()					,    _UpperCAmelCase     )     )
							self.assertEqual(resulta.c					,    1     )

							__UpperCamelCase :     Dict										=  send_to_device(UserDict({"a": tensor, "b": [tensor, tensor], "c": 1}     )					,    _UpperCAmelCase     )
							self.assertIsInstance(_UpperCAmelCase					,    _UpperCAmelCase     )
							self.assertTrue(torch.equal(resulta["a"].cpu()					,    _UpperCAmelCase     )     )
							self.assertIsInstance(resulta["b"]					,    _UpperCAmelCase     )
							self.assertTrue(torch.equal(resulta["b"][0].cpu()					,    _UpperCAmelCase     )     )
							self.assertTrue(torch.equal(resulta["b"][1].cpu()					,    _UpperCAmelCase     )     )
							self.assertEqual(resulta["c"]					,    1     )
				def 			a_			(self     )      ->			Optional[Any]:
							with self.assertRaises(_UpperCAmelCase     ) as cm:
										__UpperCamelCase :     int										=  recursively_apply(torch.tensor					,    (torch.tensor(1     ), 1)					,    error_on_other_type=_UpperCAmelCase     )
							self.assertEqual(
							    str(cm.exception     )					,    "Unsupported types (<class 'int'>) passed to `tensor`. Only nested list/tuple/dicts of objects that are valid for `is_torch_tensor` should be passed."					,    )
				def 			a_			(self     )      ->			Union[str, Any]:
							__UpperCamelCase :     Dict										=  torch.tensor([1, 2, 3, 4, 5]     )
							self.assertEqual(listify(_UpperCAmelCase     )					,    [1, 2, 3, 4, 5]     )

							__UpperCamelCase :     int										=  torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 1_0]]     )
							self.assertEqual(listify(_UpperCAmelCase     )					,    [[1, 2, 3, 4, 5], [6, 7, 8, 9, 1_0]]     )

							__UpperCamelCase :     Dict										=  torch.tensor([[[1, 2, 3, 4, 5], [6, 7, 8, 9, 1_0]], [[1_1, 1_2, 1_3, 1_4, 1_5], [1_6, 1_7, 1_8, 1_9, 2_0]]]     )
							self.assertEqual(
							    listify(_UpperCAmelCase     )					,    [[[1, 2, 3, 4, 5], [6, 7, 8, 9, 1_0]], [[1_1, 1_2, 1_3, 1_4, 1_5], [1_6, 1_7, 1_8, 1_9, 2_0]]]     )
				def 			a_			(self     )      ->			Optional[Any]:
							with patch_environment(aa=1					,    BB=2     ):
										self.assertEqual(os.environ.get("AA"     )					,    "1"     )
										self.assertEqual(os.environ.get("BB"     )					,    "2"     )

							self.assertNotIn("AA"					,    os.environ     )
							self.assertNotIn("BB"					,    os.environ     )
				def 			a_			(self     )      ->			Dict:
							__UpperCamelCase :     Tuple										=  RegressionModel()
							__UpperCamelCase :     List[str]										=  model.forward
							__UpperCamelCase :     Any										=  convert_outputs_to_fpaa(model.forward     )
							__UpperCamelCase :     List[str]										=  extract_model_from_parallel(_UpperCAmelCase					,    keep_fpaa_wrapper=_UpperCAmelCase     )
							__UpperCamelCase :     Dict										=  pickle.dumps(_UpperCAmelCase     )
				@require_cuda
				def 			a_			(self     )      ->			str:
							__UpperCamelCase :     List[str]										=  RegressionModel()
							__UpperCamelCase :     List[Any]										=  model.forward
							__UpperCamelCase :     List[str]										=  torch.cuda.amp.autocast(dtype=torch.floataa     )(model.forward     )
							__UpperCamelCase :     str										=  convert_outputs_to_fpaa(model.forward     )
							__UpperCamelCase :     int										=  extract_model_from_parallel(_UpperCAmelCase					,    keep_fpaa_wrapper=_UpperCAmelCase     )
							__UpperCamelCase :     int										=  pickle.dumps(_UpperCAmelCase     )
				@require_cuda
				@require_torch_min_version(version="2.0"     )
				def 			a_			(self     )      ->			Tuple:
							__UpperCamelCase :     List[Any]										=  RegressionModel()
							__UpperCamelCase :     Tuple										=  model.forward
							__UpperCamelCase :     Optional[int]										=  torch.cuda.amp.autocast(dtype=torch.floataa     )(model.forward     )
							__UpperCamelCase :     List[Any]										=  convert_outputs_to_fpaa(model.forward     )
							__UpperCamelCase :     Union[str, Any]										=  torch.compile(model.forward					,    backend="inductor"     )
							__UpperCamelCase :     int										=  torch.randn(4					,    1_0     ).cuda()
							__UpperCamelCase :     int										=  model(_UpperCAmelCase     )
				def 			a_			(self     )      ->			Union[str, Any]:
							__UpperCamelCase :     List[Any]										=  RegressionModel()
							# could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
							__UpperCamelCase :     Optional[Any]										=  torch.nn.parallel.DataParallel(_UpperCAmelCase     )
							__UpperCamelCase :     Union[str, Any]										=  extract_model_from_parallel(_UpperCAmelCase     )

							self.assertEqual(_UpperCAmelCase					,    _UpperCAmelCase     )
				@require_torch_min_version(version="2.0"     )
				def 			a_			(self     )      ->			Union[str, Any]:
							__UpperCamelCase :     int										=  RegressionModel()
							__UpperCamelCase :     List[str]										=  torch.compile(_UpperCAmelCase     )

							# could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
							__UpperCamelCase :     Union[str, Any]										=  torch.nn.parallel.DataParallel(_UpperCAmelCase     )
							__UpperCamelCase :     List[str]										=  torch.compile(_UpperCAmelCase     )
							__UpperCamelCase :     Optional[int]										=  extract_model_from_parallel(_UpperCAmelCase     )

							self.assertEqual(compiled_model._orig_mod					,    compiled_model_unwrapped._orig_mod     )





				def 			a_			(self     )      ->			str:
							self.assertEqual(find_device([1, "a", torch.tensor([1, 2, 3]     )]     )					,    torch.device("cpu"     )     )
							self.assertEqual(find_device({"a": 1, "b": torch.tensor([1, 2, 3]     )}     )					,    torch.device("cpu"     )     )
							self.assertIsNone(find_device([1, "a"]     )     )



