




'''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


if is_torch_available():
		import torch

if is_vision_available():
		from PIL import Image

		from transformers import SwinaSRImageProcessor
		from transformers.image_transforms import get_image_size






class 	SCREAMING_SNAKE_CASE(    unittest.TestCase					):

							def __init__(   self ,		lowerCamelCase__ ,		lowerCamelCase__=7 ,		lowerCamelCase__=3 ,		lowerCamelCase__=18 ,		lowerCamelCase__=30 ,		lowerCamelCase__=400 ,		lowerCamelCase__=True ,		lowerCamelCase__=1 / 255 ,		lowerCamelCase__=True ,		lowerCamelCase__=8 ,		)   -> List[str]:

											"""simple docstring"""



											__lowercase          =						parent
											__lowercase          =						batch_size
											__lowercase          =						num_channels
											__lowercase          =						image_size
											__lowercase          =						min_resolution
											__lowercase          =						max_resolution
											__lowercase          =						do_rescale
											__lowercase          =						rescale_factor
											__lowercase          =						do_pad
											__lowercase          =						pad_size

							def    snake_case__      (   self					)   -> Any:

											"""simple docstring"""



											return {
											    "do_rescale": self.do_rescale,
											    "rescale_factor": self.rescale_factor,
											    "do_pad": self.do_pad,
											    "pad_size": self.pad_size,
											}




							def    snake_case__      (   self ,		lowerCamelCase__=False ,		lowerCamelCase__=False ,		lowerCamelCase__=False					)   -> int:

											"""simple docstring"""



											assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

											if equal_resolution:
															__lowercase          =						[]
															for i in range(self.batch_size					):
																			image_inputs.append(
																			    np.random.randint(
																			        255 ,		size=(self.num_channels, self.max_resolution, self.max_resolution) ,		dtype=np.uinta					)					)
											else:
															__lowercase          =						[]
															for i in range(self.batch_size					):
																			__lowercase          =						np.random.choice(np.arange(self.min_resolution ,		self.max_resolution					) ,		2					)
																			image_inputs.append(np.random.randint(255 ,		size=(self.num_channels, width, height) ,		dtype=np.uinta					)					)

											if not numpify and not torchify:
															# PIL expects the channel dimension as last dimension
															__lowercase          =						[Image.fromarray(np.moveaxis(UpperCamelCase__ ,		0 ,		-1					)					) for x in image_inputs]

											if torchify:
															__lowercase          =						[torch.from_numpy(UpperCamelCase__					) for x in image_inputs]

											return image_inputs






@require_torch
@require_vision
class 	SCREAMING_SNAKE_CASE(    lowerCAmelCase__       ,				unittest.TestCase					):
							snake_case_			:					Tuple   = SwinaSRImageProcessor if is_vision_available() else None

							def    snake_case__      (   self					)   -> Optional[Any]:

											"""simple docstring"""



											__lowercase          =						SwinaSRImageProcessingTester(self					)

							@property
							def    snake_case__      (   self					)   -> List[str]:

											"""simple docstring"""



											return self.image_processor_tester.prepare_image_processor_dict()

							def    snake_case__      (   self					)   -> Any:

											"""simple docstring"""



											__lowercase          =						self.image_processing_class(**self.image_processor_dict					)
											self.assertTrue(hasattr(UpperCamelCase__ ,		"""do_rescale"""					)					)
											self.assertTrue(hasattr(UpperCamelCase__ ,		"""rescale_factor"""					)					)
											self.assertTrue(hasattr(UpperCamelCase__ ,		"""do_pad"""					)					)
											self.assertTrue(hasattr(UpperCamelCase__ ,		"""pad_size"""					)					)

							def    snake_case__      (   self					)   -> Optional[int]:

											"""simple docstring"""



											pass

							def    snake_case__      (   self ,		lowerCamelCase__					)   -> int:

											"""simple docstring"""



											__lowercase          =						get_image_size(UpperCamelCase__					)
											__lowercase          =						self.image_processor_tester.pad_size

											__lowercase          =						(old_height // size + 1) * size - old_height
											__lowercase          =						(old_width // size + 1) * size - old_width
											return old_height + pad_height, old_width + pad_width

							def    snake_case__      (   self					)   -> Any:

											"""simple docstring"""



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

											# Test not batched input
											__lowercase          =						image_processor(image_inputs[0] ,		return_tensors="""pt"""					).pixel_values
											__lowercase          =						self.calculate_expected_size(np.array(image_inputs[0]					)					)
											self.assertEqual(
											    encoded_images.shape ,		(
											        1,
											        self.image_processor_tester.num_channels,
											        expected_height,
											        expected_width,
											    ) ,		)

							def    snake_case__      (   self					)   -> Any:

											"""simple docstring"""



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

											# Test not batched input
											__lowercase          =						image_processor(image_inputs[0] ,		return_tensors="""pt"""					).pixel_values
											__lowercase          =						self.calculate_expected_size(image_inputs[0]					)
											self.assertEqual(
											    encoded_images.shape ,		(
											        1,
											        self.image_processor_tester.num_channels,
											        expected_height,
											        expected_width,
											    ) ,		)




							def    snake_case__      (   self					)   -> List[str]:

											"""simple docstring"""



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

											# Test not batched input
											__lowercase          =						image_processor(image_inputs[0] ,		return_tensors="""pt"""					).pixel_values
											__lowercase          =						self.calculate_expected_size(image_inputs[0]					)
											self.assertEqual(
											    encoded_images.shape ,		(
											        1,
											        self.image_processor_tester.num_channels,
											        expected_height,
											        expected_width,
											    ) ,		)










'''simple docstring'''
import random
from typing import List, Optional, Union

import numpy as np
import torch

from ..state import AcceleratorState
from .constants import CUDA_DISTRIBUTED_TYPES
from .dataclasses import DistributedType, RNGType
from .imports import is_npu_available, is_tpu_available, is_xpu_available


if is_tpu_available(check_device=False):
  import torch_xla.core.xla_model as xm
def     snake_case_  (       a__		:     int   ,a__		:     bool = False      ):



    """simple docstring"""




    if device_specific:
        seed += AcceleratorState().process_index
    random.seed(a__      )
    np.random.seed(a__      )
    torch.manual_seed(a__      )
    if is_xpu_available():
        torch.xpu.manual_seed_all(a__      )
    elif is_npu_available():
        torch.npu.manual_seed_all(a__      )
    else:
        torch.cuda.manual_seed_all(a__      )
    # ^^ safe to call this function even if cuda is not available
    if is_tpu_available():
        xm.set_rng_state(a__      )
def     snake_case_  (       a__		:     Optional[RNGType] = None   ,a__		:     Optional[torch.Generator] = None      ):



    """simple docstring"""




    if rng_type == RNGType.TORCH:
        __lowercase          =						torch.get_rng_state()
    elif rng_type == RNGType.CUDA:
        __lowercase          =						torch.cuda.get_rng_state()
    elif rng_type == RNGType.XLA:
        assert is_tpu_available(), "Can't synchronize XLA seeds on an environment without TPUs."
        __lowercase          =						torch.tensor(xm.get_rng_state()      )
    elif rng_type == RNGType.NPU:
        assert is_npu_available(), "Can't synchronize NPU seeds on an environment without NPUs."
        __lowercase          =						torch.npu.get_rng_state()
    elif rng_type == RNGType.XPU:
        assert is_xpu_available(), "Can't synchronize XPU seeds on an environment without XPUs."
        __lowercase          =						torch.xpu.get_rng_state()
    elif rng_type == RNGType.GENERATOR:
        assert generator is not None, "Need a generator to synchronize its seed."
        __lowercase          =						generator.get_state()

    # Broadcast the rng state from device 0 to other devices
    __lowercase          =						AcceleratorState()
    if state.distributed_type == DistributedType.TPU:
        __lowercase          =						rng_state.to(xm.xla_device()      )
        xm.collective_broadcast([rng_state]      )
        xm.mark_step()
        __lowercase          =						rng_state.cpu()
    elif (
        state.distributed_type in CUDA_DISTRIBUTED_TYPES
        or state.distributed_type == DistributedType.MULTI_NPU
        or state.distributed_type == DistributedType.MULTI_XPU
    ):
        __lowercase          =						rng_state.to(state.device      )
        torch.distributed.broadcast(a__   ,0      )
        __lowercase          =						rng_state.cpu()
    elif state.distributed_type == DistributedType.MULTI_CPU:
        torch.distributed.broadcast(a__   ,0      )

    # Set the broadcast rng state
    if rng_type == RNGType.TORCH:
        torch.set_rng_state(a__      )
    elif rng_type == RNGType.CUDA:
        torch.cuda.set_rng_state(a__      )
    elif rng_type == RNGType.NPU:
        torch.npu.set_rng_state(a__      )
    elif rng_type == RNGType.XPU:
        torch.xpu.set_rng_state(a__      )
    elif rng_type == RNGType.XLA:
        xm.set_rng_state(rng_state.item()      )
    elif rng_type == RNGType.GENERATOR:
        generator.set_state(a__      )



def     snake_case_  (       a__		:     List[Union[str, RNGType]]   ,a__		:     Optional[torch.Generator] = None      ):



    """simple docstring"""




    for rng_type in rng_types:
        synchronize_rng_state(RNGType(a__      )   ,generator=a__      )




