




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



class    A						(					unittest.TestCase						):




				'''simple docstring'''





				def __init__(self					,    _UpperCAmelCase					,    _UpperCAmelCase=7					,    _UpperCAmelCase=3					,    _UpperCAmelCase=1_8					,    _UpperCAmelCase=3_0					,    _UpperCAmelCase=4_0_0					,    _UpperCAmelCase=True					,    _UpperCAmelCase=None					,    _UpperCAmelCase=True					,    _UpperCAmelCase=None					,    )      ->			int:
							__UpperCamelCase :     Union[str, Any]										=  size if size is not None else {"shortest_edge": 2_0}
							__UpperCamelCase :     Union[str, Any]										=  crop_size if crop_size is not None else {"height": 1_8, "width": 1_8}
							__UpperCamelCase :     Dict										=  parent
							__UpperCamelCase :     Optional[int]										=  batch_size
							__UpperCamelCase :     str										=  num_channels
							__UpperCamelCase :     int										=  image_size
							__UpperCamelCase :     str										=  min_resolution
							__UpperCamelCase :     int										=  max_resolution
							__UpperCamelCase :     Tuple										=  do_resize
							__UpperCamelCase :     Tuple										=  size
							__UpperCamelCase :     List[Any]										=  do_center_crop
							__UpperCamelCase :     Dict										=  crop_size





				def 			a_			(self     )      ->			Optional[int]:
							return {
							    "do_resize": self.do_resize,
							    "size": self.size,
							    "do_center_crop": self.do_center_crop,
							    "crop_size": self.crop_size,
							}







@require_torch
@require_vision
class    A						(					SCREAMING_SNAKE_CASE__     ,				unittest.TestCase						):




				'''simple docstring'''





				A       =							MobileNetVaImageProcessor if is_vision_available() else None
				def 			a_			(self     )      ->			str:
							__UpperCamelCase :     Tuple										=  MobileNetVaImageProcessingTester(self     )
				@property
				def 			a_			(self     )      ->			int:
							return self.image_processor_tester.prepare_image_processor_dict()
				def 			a_			(self     )      ->			List[Any]:
							__UpperCamelCase :     Optional[int]										=  self.image_processing_class(**self.image_processor_dict     )
							self.assertTrue(hasattr(_UpperCAmelCase					,    "do_resize"     )     )
							self.assertTrue(hasattr(_UpperCAmelCase					,    "size"     )     )
							self.assertTrue(hasattr(_UpperCAmelCase					,    "do_center_crop"     )     )
							self.assertTrue(hasattr(_UpperCAmelCase					,    "center_crop"     )     )
				def 			a_			(self     )      ->			Optional[int]:
							__UpperCamelCase :     Union[str, Any]										=  self.image_processing_class.from_dict(self.image_processor_dict     )
							self.assertEqual(image_processor.size					,    {"shortest_edge": 2_0}     )
							self.assertEqual(image_processor.crop_size					,    {"height": 1_8, "width": 1_8}     )

							__UpperCamelCase :     List[str]										=  self.image_processing_class.from_dict(self.image_processor_dict					,    size=4_2					,    crop_size=8_4     )
							self.assertEqual(image_processor.size					,    {"shortest_edge": 4_2}     )
							self.assertEqual(image_processor.crop_size					,    {"height": 8_4, "width": 8_4}     )
				def 			a_			(self     )      ->			Optional[Any]:
							pass
				def 			a_			(self     )      ->			int:
							# Initialize image_processing
							__UpperCamelCase :     Optional[Any]										=  self.image_processing_class(**self.image_processor_dict     )
							# create random PIL images
							__UpperCamelCase :     Union[str, Any]										=  prepare_image_inputs(self.image_processor_tester					,    equal_resolution=_UpperCAmelCase     )
							for image in image_inputs:
										self.assertIsInstance(_UpperCAmelCase					,    Image.Image     )

							# Test not batched input
							__UpperCamelCase :     Optional[int]										=  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
							__UpperCamelCase :     str										=  image_processing(_UpperCAmelCase					,    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 			a_			(self     )      ->			Tuple:
							# Initialize image_processing
							__UpperCamelCase :     Optional[Any]										=  self.image_processing_class(**self.image_processor_dict     )
							# create random numpy tensors
							__UpperCamelCase :     int										=  prepare_image_inputs(self.image_processor_tester					,    equal_resolution=_UpperCAmelCase					,    numpify=_UpperCAmelCase     )
							for image in image_inputs:
										self.assertIsInstance(_UpperCAmelCase					,    np.ndarray     )

							# Test not batched input
							__UpperCamelCase :     Optional[int]										=  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
							__UpperCamelCase :     Union[str, Any]										=  image_processing(_UpperCAmelCase					,    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 			a_			(self     )      ->			int:
							# Initialize image_processing
							__UpperCamelCase :     List[str]										=  self.image_processing_class(**self.image_processor_dict     )
							# create random PyTorch tensors
							__UpperCamelCase :     Dict										=  prepare_image_inputs(self.image_processor_tester					,    equal_resolution=_UpperCAmelCase					,    torchify=_UpperCAmelCase     )
							for image in image_inputs:
										self.assertIsInstance(_UpperCAmelCase					,    torch.Tensor     )

							# Test not batched input
							__UpperCamelCase :     int										=  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
							__UpperCamelCase :     Tuple										=  image_processing(_UpperCAmelCase					,    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 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"]     )     )



