
"""simple docstring"""




import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
						import torch

if is_vision_available():
						from PIL import Image

						from transformers import LevitImageProcessor





class  snake_case     (							unittest.TestCase   ):

							def __init__(self       ,       SCREAMING_SNAKE_CASE_       ,       SCREAMING_SNAKE_CASE_=7       ,       SCREAMING_SNAKE_CASE_=3       ,       SCREAMING_SNAKE_CASE_=18       ,       SCREAMING_SNAKE_CASE_=30       ,       SCREAMING_SNAKE_CASE_=4_00       ,       SCREAMING_SNAKE_CASE_=True       ,       SCREAMING_SNAKE_CASE_=None       ,       SCREAMING_SNAKE_CASE_=True       ,       SCREAMING_SNAKE_CASE_=None       ,       SCREAMING_SNAKE_CASE_=True       ,       SCREAMING_SNAKE_CASE_=[0.5, 0.5, 0.5]       ,       SCREAMING_SNAKE_CASE_=[0.5, 0.5, 0.5]       ,       ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = size if size is not None else {'''shortest_edge''': 18}
									SCREAMING_SNAKE_CASE_						 = crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}
									SCREAMING_SNAKE_CASE_						 = parent
									SCREAMING_SNAKE_CASE_						 = batch_size
									SCREAMING_SNAKE_CASE_						 = num_channels
									SCREAMING_SNAKE_CASE_						 = image_size
									SCREAMING_SNAKE_CASE_						 = min_resolution
									SCREAMING_SNAKE_CASE_						 = max_resolution
									SCREAMING_SNAKE_CASE_						 = do_resize
									SCREAMING_SNAKE_CASE_						 = size
									SCREAMING_SNAKE_CASE_						 = do_center_crop
									SCREAMING_SNAKE_CASE_						 = crop_size
									SCREAMING_SNAKE_CASE_						 = do_normalize
									SCREAMING_SNAKE_CASE_						 = image_mean
									SCREAMING_SNAKE_CASE_						 = image_std







							def _lowercase					(self    ):

									"""simple docstring"""







									return {
									    "image_mean": self.image_mean,
									    "image_std": self.image_std,
									    "do_normalize": self.do_normalize,
									    "do_resize": self.do_resize,
									    "do_center_crop": self.do_center_crop,
									    "size": self.size,
									    "crop_size": self.crop_size,
									}







@require_torch
@require_vision
class  snake_case     (							__lowercase       ,			unittest.TestCase   ):
							UpperCAmelCase__						     =      LevitImageProcessor if is_vision_available() else None

							def _lowercase					(self    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = LevitImageProcessingTester(self    )

							@property
							def _lowercase					(self    ):

									"""simple docstring"""







									return self.image_processor_tester.prepare_image_processor_dict()

							def _lowercase					(self    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = self.image_processing_class(**self.image_processor_dict    )
									self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_       ,       '''image_mean'''    )    )
									self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_       ,       '''image_std'''    )    )
									self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_       ,       '''do_normalize'''    )    )
									self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_       ,       '''do_resize'''    )    )
									self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_       ,       '''do_center_crop'''    )    )
									self.assertTrue(hasattr(SCREAMING_SNAKE_CASE_       ,       '''size'''    )    )

							def _lowercase					(self    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = self.image_processing_class.from_dict(self.image_processor_dict    )
									self.assertEqual(image_processor.size       ,       {'''shortest_edge''': 18}    )
									self.assertEqual(image_processor.crop_size       ,       {'''height''': 18, '''width''': 18}    )

									SCREAMING_SNAKE_CASE_						 = self.image_processing_class.from_dict(self.image_processor_dict       ,       size=42       ,       crop_size=84    )
									self.assertEqual(image_processor.size       ,       {'''shortest_edge''': 42}    )
									self.assertEqual(image_processor.crop_size       ,       {'''height''': 84, '''width''': 84}    )

							def _lowercase					(self    ):

									"""simple docstring"""







									pass

							def _lowercase					(self    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = self.image_processing_class(**self.image_processor_dict    )
									# create random PIL images
									SCREAMING_SNAKE_CASE_						 = prepare_image_inputs(self.image_processor_tester       ,       equal_resolution=SCREAMING_SNAKE_CASE_    )
									for image in image_inputs:
											self.assertIsInstance(SCREAMING_SNAKE_CASE_       ,       Image.Image    )

									# Test not batched input
									SCREAMING_SNAKE_CASE_						 = image_processing(image_inputs[0]       ,       return_tensors='''pt'''    ).pixel_values
									self.assertEqual(
									    encoded_images.shape       ,       (
									        1,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )       ,       )

									# Test batched
									SCREAMING_SNAKE_CASE_						 = image_processing(SCREAMING_SNAKE_CASE_       ,       return_tensors='''pt'''    ).pixel_values
									self.assertEqual(
									    encoded_images.shape       ,       (
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )       ,       )

							def _lowercase					(self    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = self.image_processing_class(**self.image_processor_dict    )
									# create random numpy tensors
									SCREAMING_SNAKE_CASE_						 = prepare_image_inputs(self.image_processor_tester       ,       equal_resolution=SCREAMING_SNAKE_CASE_       ,       numpify=SCREAMING_SNAKE_CASE_    )
									for image in image_inputs:
											self.assertIsInstance(SCREAMING_SNAKE_CASE_       ,       np.ndarray    )

									# Test not batched input
									SCREAMING_SNAKE_CASE_						 = image_processing(image_inputs[0]       ,       return_tensors='''pt'''    ).pixel_values
									self.assertEqual(
									    encoded_images.shape       ,       (
									        1,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )       ,       )

									# Test batched
									SCREAMING_SNAKE_CASE_						 = image_processing(SCREAMING_SNAKE_CASE_       ,       return_tensors='''pt'''    ).pixel_values
									self.assertEqual(
									    encoded_images.shape       ,       (
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )       ,       )







							def _lowercase					(self    ):

									"""simple docstring"""







									SCREAMING_SNAKE_CASE_						 = self.image_processing_class(**self.image_processor_dict    )
									# create random PyTorch tensors
									SCREAMING_SNAKE_CASE_						 = prepare_image_inputs(self.image_processor_tester       ,       equal_resolution=SCREAMING_SNAKE_CASE_       ,       torchify=SCREAMING_SNAKE_CASE_    )
									for image in image_inputs:
											self.assertIsInstance(SCREAMING_SNAKE_CASE_       ,       torch.Tensor    )

									# Test not batched input
									SCREAMING_SNAKE_CASE_						 = image_processing(image_inputs[0]       ,       return_tensors='''pt'''    ).pixel_values
									self.assertEqual(
									    encoded_images.shape       ,       (
									        1,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )       ,       )

									# Test batched
									SCREAMING_SNAKE_CASE_						 = image_processing(SCREAMING_SNAKE_CASE_       ,       return_tensors='''pt'''    ).pixel_values
									self.assertEqual(
									    encoded_images.shape       ,       (
									        self.image_processor_tester.batch_size,
									        self.image_processor_tester.num_channels,
									        self.image_processor_tester.crop_size['''height'''],
									        self.image_processor_tester.crop_size['''width'''],
									    )       ,       )

"""simple docstring"""




import os
import socket
from contextlib import contextmanager

import torch

from ..commands.config.default import write_basic_config  # noqa: F401
from ..state import PartialState
from .dataclasses import DistributedType
from .imports import is_deepspeed_available, is_tpu_available
from .transformer_engine import convert_model
from .versions import is_torch_version


if is_deepspeed_available():
						from deepspeed import DeepSpeedEngine

if is_tpu_available(check_device=False):
						import torch_xla.core.xla_model as xm



def        _lowerCamelCase ( __a    ):
		if is_torch_version('''<''',							'''2.0.0'''    ) or not hasattr(__a,							'''_dynamo'''    ):
				return False
		return isinstance(__a,							torch._dynamo.eval_frame.OptimizedModule    )



def        _lowerCamelCase ( __a,							__a = True    ):
		SCREAMING_SNAKE_CASE_						 = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel)

		SCREAMING_SNAKE_CASE_						 = is_compiled_module(__a    )
		if is_compiled:
				SCREAMING_SNAKE_CASE_						 = model
				SCREAMING_SNAKE_CASE_						 = model._orig_mod

		if is_deepspeed_available():
				options += (DeepSpeedEngine,)

		while isinstance(__a,							__a    ):
				SCREAMING_SNAKE_CASE_						 = model.module

		if not keep_fpaa_wrapper:
				SCREAMING_SNAKE_CASE_						 = getattr(__a,							'''forward'''    )
				SCREAMING_SNAKE_CASE_						 = model.__dict__.pop('''_original_forward''',							__a    )
				if original_forward is not None:
						while hasattr(__a,							'''__wrapped__'''    ):
								SCREAMING_SNAKE_CASE_						 = forward.__wrapped__
								if forward == original_forward:
										break
						SCREAMING_SNAKE_CASE_						 = forward
				if getattr(__a,							'''_converted_to_transformer_engine''',							__a    ):
						convert_model(__a,							to_transformer_engine=__a    )

		if is_compiled:
				SCREAMING_SNAKE_CASE_						 = model
				SCREAMING_SNAKE_CASE_						 = compiled_model

		return model



def        _lowerCamelCase ( ):
		PartialState().wait_for_everyone()



def        _lowerCamelCase ( __a,							__a    ):
		if PartialState().distributed_type == DistributedType.TPU:
				xm.save(__a,							__a    )
		elif PartialState().local_process_index == 0:
				torch.save(__a,							__a    )



@contextmanager
def        _lowerCamelCase ( **__a    ):
		for key, value in kwargs.items():
				SCREAMING_SNAKE_CASE_						 = str(__a    )

		yield

		for key in kwargs:
				if key.upper() in os.environ:
						del os.environ[key.upper()]



def        _lowerCamelCase ( __a    ):
		if not hasattr(__a,							'''__qualname__'''    ) and not hasattr(__a,							'''__name__'''    ):
				SCREAMING_SNAKE_CASE_						 = getattr(__a,							'''__class__''',							__a    )
		if hasattr(__a,							'''__qualname__'''    ):
				return obj.__qualname__
		if hasattr(__a,							'''__name__'''    ):
				return obj.__name__
		return str(__a    )



def        _lowerCamelCase ( __a,							__a    ):
		for key, value in source.items():
				if isinstance(__a,							__a    ):
						SCREAMING_SNAKE_CASE_						 = destination.setdefault(__a,							{}    )
						merge_dicts(__a,							__a    )
				else:
						SCREAMING_SNAKE_CASE_						 = value

		return destination



def        _lowerCamelCase ( __a = None    ):
		if port is None:
				SCREAMING_SNAKE_CASE_						 = 29_500
		with socket.socket(socket.AF_INET,							socket.SOCK_STREAM    ) as s:
				return s.connect_ex(('''localhost''', port)    ) == 0