





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


snake_case_       :    int          =					namedtuple("ExampleNamedTuple", "a b c")


class    __a (unittest.TestCase       ):

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







													"""simple docstring"""
													UpperCAmelCase_     : Optional[Any]         =					torch.randn(5    ,       2				)
													UpperCAmelCase_     : Tuple         =					torch.device('''cuda'''				) if torch.cuda.is_available() else torch.device('''cpu'''				)

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

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

													UpperCAmelCase_     : Dict         =					send_to_device({'''a''': tensor, '''b''': [tensor, tensor], '''c''': 1}    ,       __magic_name__				)
													self.assertIsInstance(__magic_name__    ,       __magic_name__				)
													self.assertTrue(torch.equal(resulta['''a'''].cpu()    ,       __magic_name__				)				)
													self.assertIsInstance(resulta['''b''']    ,       __magic_name__				)
													self.assertTrue(torch.equal(resulta['''b'''][0].cpu()    ,       __magic_name__				)				)
													self.assertTrue(torch.equal(resulta['''b'''][1].cpu()    ,       __magic_name__				)				)
													self.assertEqual(resulta['''c''']    ,       1				)

													UpperCAmelCase_     : Dict         =					send_to_device(ExampleNamedTuple(a=__magic_name__    ,       b=[tensor, tensor]    ,       c=1				)    ,       __magic_name__				)
													self.assertIsInstance(__magic_name__    ,       __magic_name__				)
													self.assertTrue(torch.equal(resulta.a.cpu()    ,       __magic_name__				)				)
													self.assertIsInstance(resulta.b    ,       __magic_name__				)
													self.assertTrue(torch.equal(resulta.b[0].cpu()    ,       __magic_name__				)				)
													self.assertTrue(torch.equal(resulta.b[1].cpu()    ,       __magic_name__				)				)
													self.assertEqual(resulta.c    ,       1				)

													UpperCAmelCase_     : int         =					send_to_device(UserDict({'''a''': tensor, '''b''': [tensor, tensor], '''c''': 1}				)    ,       __magic_name__				)
													self.assertIsInstance(__magic_name__    ,       __magic_name__				)
													self.assertTrue(torch.equal(resulta['''a'''].cpu()    ,       __magic_name__				)				)
													self.assertIsInstance(resulta['''b''']    ,       __magic_name__				)
													self.assertTrue(torch.equal(resulta['''b'''][0].cpu()    ,       __magic_name__				)				)
													self.assertTrue(torch.equal(resulta['''b'''][1].cpu()    ,       __magic_name__				)				)
													self.assertEqual(resulta['''c''']    ,       1				)

							def       UpperCAmelCase__		(							self							:       List[Any]				)   ->    List[Any]:







													"""simple docstring"""
													with self.assertRaises(__magic_name__				) as cm:
																			UpperCAmelCase_     : Optional[int]         =					recursively_apply(torch.tensor    ,       (torch.tensor(1				), 1)    ,       error_on_other_type=__magic_name__				)
													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       UpperCAmelCase__		(							self							:       Any				)   ->    Union[str, Any]:







													"""simple docstring"""
													UpperCAmelCase_     : str         =					torch.tensor([1, 2, 3, 4, 5]				)
													self.assertEqual(listify(__magic_name__				)    ,       [1, 2, 3, 4, 5]				)

													UpperCAmelCase_     : str         =					torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]				)
													self.assertEqual(listify(__magic_name__				)    ,       [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]				)

													UpperCAmelCase_     : int         =					torch.tensor([[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]]				)
													self.assertEqual(
													    listify(__magic_name__				)    ,       [[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]]				)

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







													"""simple docstring"""
													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       UpperCAmelCase__		(							self							:       Union[str, Any]				)   ->    Optional[int]:







													"""simple docstring"""
													UpperCAmelCase_     : List[str]         =					RegressionModel()
													UpperCAmelCase_     : List[Any]         =					model.forward
													UpperCAmelCase_     : List[Any]         =					convert_outputs_to_fpaa(model.forward				)
													UpperCAmelCase_     : List[Any]         =					extract_model_from_parallel(__magic_name__    ,       keep_fpaa_wrapper=__magic_name__				)
													UpperCAmelCase_     : Tuple         =					pickle.dumps(__magic_name__				)

							@require_cuda
							def       UpperCAmelCase__		(							self							:       List[str]				)   ->    Tuple:







													"""simple docstring"""
													UpperCAmelCase_     : int         =					RegressionModel()
													UpperCAmelCase_     : Tuple         =					model.forward
													UpperCAmelCase_     : int         =					torch.cuda.amp.autocast(dtype=torch.floataa				)(model.forward				)
													UpperCAmelCase_     : Optional[Any]         =					convert_outputs_to_fpaa(model.forward				)
													UpperCAmelCase_     : str         =					extract_model_from_parallel(__magic_name__    ,       keep_fpaa_wrapper=__magic_name__				)
													UpperCAmelCase_     : Optional[Any]         =					pickle.dumps(__magic_name__				)

							@require_cuda
							@require_torch_min_version(version='''2.0'''				)
							def       UpperCAmelCase__		(							self							:       Union[str, Any]				)   ->    Optional[Any]:







													"""simple docstring"""
													UpperCAmelCase_     : Tuple         =					RegressionModel()
													UpperCAmelCase_     : Any         =					model.forward
													UpperCAmelCase_     : List[str]         =					torch.cuda.amp.autocast(dtype=torch.floataa				)(model.forward				)
													UpperCAmelCase_     : int         =					convert_outputs_to_fpaa(model.forward				)
													UpperCAmelCase_     : Union[str, Any]         =					torch.compile(model.forward    ,       backend='''inductor'''				)
													UpperCAmelCase_     : Union[str, Any]         =					torch.randn(4    ,       10				).cuda()
													UpperCAmelCase_     : Dict         =					model(__magic_name__				)

							def       UpperCAmelCase__		(							self							:       List[Any]				)   ->    Dict:







													"""simple docstring"""
													UpperCAmelCase_     : 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(__magic_name__				)
													UpperCAmelCase_     : Tuple         =					extract_model_from_parallel(__magic_name__				)

													self.assertEqual(__magic_name__    ,       __magic_name__				)

							@require_torch_min_version(version='''2.0'''				)
							def       UpperCAmelCase__		(							self							:       int				)   ->    Any:







													"""simple docstring"""
													UpperCAmelCase_     : Optional[Any]         =					RegressionModel()
													UpperCAmelCase_     : int         =					torch.compile(__magic_name__				)

													# could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
													UpperCAmelCase_     : Dict         =					torch.nn.parallel.DataParallel(__magic_name__				)
													UpperCAmelCase_     : Dict         =					torch.compile(__magic_name__				)
													UpperCAmelCase_     : Optional[Any]         =					extract_model_from_parallel(__magic_name__				)

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



							def       UpperCAmelCase__		(							self							:       Optional[int]				)   ->    Optional[Any]:







													"""simple docstring"""
													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''']				)				)












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


class    __a (unittest.TestCase       ):

							def __init__(							self							:       Dict    ,       __magic_name__							:       List[str]    ,       __magic_name__							:       str=7    ,       __magic_name__							:       Optional[int]=3    ,       __magic_name__							:       Union[str, Any]=18    ,       __magic_name__							:       Dict=30    ,       __magic_name__							:       List[Any]=4_00    ,       __magic_name__							:       Dict=True    ,       __magic_name__							:       Union[str, Any]=None    ,       __magic_name__							:       Optional[Any]=0.8_7_5    ,       __magic_name__							:       List[Any]=True    ,       __magic_name__							:       Optional[int]=[0.5, 0.5, 0.5]    ,       __magic_name__							:       Optional[int]=[0.5, 0.5, 0.5]    ,       )   ->    Optional[Any]:







													"""simple docstring"""
													UpperCAmelCase_     : str         =					size if size is not None else {'''shortest_edge''': 20}
													UpperCAmelCase_     : Optional[Any]         =					parent
													UpperCAmelCase_     : Any         =					batch_size
													UpperCAmelCase_     : Optional[Any]         =					num_channels
													UpperCAmelCase_     : Optional[Any]         =					image_size
													UpperCAmelCase_     : Optional[int]         =					min_resolution
													UpperCAmelCase_     : Optional[Any]         =					max_resolution
													UpperCAmelCase_     : Optional[int]         =					do_resize
													UpperCAmelCase_     : Optional[Any]         =					size
													UpperCAmelCase_     : int         =					crop_pct
													UpperCAmelCase_     : Optional[int]         =					do_normalize
													UpperCAmelCase_     : Dict         =					image_mean
													UpperCAmelCase_     : int         =					image_std



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







													"""simple docstring"""
													return {
													    "image_mean": self.image_mean,
													    "image_std": self.image_std,
													    "do_normalize": self.do_normalize,
													    "do_resize": self.do_resize,
													    "size": self.size,
													    "crop_pct": self.crop_pct,
													}





@require_torch
@require_vision
class    __a (lowerCamelCase    ,						unittest.TestCase       ):
							__a   :				Dict       =    ConvNextImageProcessor if is_vision_available() else None

							def       UpperCAmelCase__		(							self							:       Optional[int]				)   ->    Dict:







													"""simple docstring"""
													UpperCAmelCase_     : str         =					ConvNextImageProcessingTester(self				)

							@property
							def       UpperCAmelCase__		(							self							:       List[Any]				)   ->    Any:







													"""simple docstring"""
													return self.image_processor_tester.prepare_image_processor_dict()

							def       UpperCAmelCase__		(							self							:       List[Any]				)   ->    Tuple:







													"""simple docstring"""
													UpperCAmelCase_     : Dict         =					self.image_processing_class(**self.image_processor_dict				)
													self.assertTrue(hasattr(__magic_name__    ,       '''do_resize'''				)				)
													self.assertTrue(hasattr(__magic_name__    ,       '''size'''				)				)
													self.assertTrue(hasattr(__magic_name__    ,       '''crop_pct'''				)				)
													self.assertTrue(hasattr(__magic_name__    ,       '''do_normalize'''				)				)
													self.assertTrue(hasattr(__magic_name__    ,       '''image_mean'''				)				)
													self.assertTrue(hasattr(__magic_name__    ,       '''image_std'''				)				)

							def       UpperCAmelCase__		(							self							:       Dict				)   ->    List[Any]:







													"""simple docstring"""
													UpperCAmelCase_     : List[str]         =					self.image_processing_class.from_dict(self.image_processor_dict				)
													self.assertEqual(image_processor.size    ,       {'''shortest_edge''': 20}				)

													UpperCAmelCase_     : List[Any]         =					self.image_processing_class.from_dict(self.image_processor_dict    ,       size=42				)
													self.assertEqual(image_processor.size    ,       {'''shortest_edge''': 42}				)

							def       UpperCAmelCase__		(							self							:       str				)   ->    Optional[int]:







													"""simple docstring"""
													pass

							def       UpperCAmelCase__		(							self							:       List[str]				)   ->    int:







													"""simple docstring"""
													# Initialize image_processing
													UpperCAmelCase_     : int         =					self.image_processing_class(**self.image_processor_dict				)
													# create random PIL images
													UpperCAmelCase_     : List[Any]         =					prepare_image_inputs(self.image_processor_tester    ,       equal_resolution=__magic_name__				)
													for image in image_inputs:
																			self.assertIsInstance(__magic_name__    ,       Image.Image				)

													# 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.size['''shortest_edge'''],
													        self.image_processor_tester.size['''shortest_edge'''],
													    )    ,       )

													# Test batched
													UpperCAmelCase_     : Tuple         =					image_processing(__magic_name__    ,       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.size['''shortest_edge'''],
													        self.image_processor_tester.size['''shortest_edge'''],
													    )    ,       )

							def       UpperCAmelCase__		(							self							:       str				)   ->    Optional[int]:







													"""simple docstring"""
													# Initialize image_processing
													UpperCAmelCase_     : Optional[Any]         =					self.image_processing_class(**self.image_processor_dict				)
													# create random numpy tensors
													UpperCAmelCase_     : Tuple         =					prepare_image_inputs(self.image_processor_tester    ,       equal_resolution=__magic_name__    ,       numpify=__magic_name__				)
													for image in image_inputs:
																			self.assertIsInstance(__magic_name__    ,       np.ndarray				)

													# 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.size['''shortest_edge'''],
													        self.image_processor_tester.size['''shortest_edge'''],
													    )    ,       )

													# Test batched
													UpperCAmelCase_     : Union[str, Any]         =					image_processing(__magic_name__    ,       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.size['''shortest_edge'''],
													        self.image_processor_tester.size['''shortest_edge'''],
													    )    ,       )



							def       UpperCAmelCase__		(							self							:       str				)   ->    int:







													"""simple docstring"""
													# Initialize image_processing
													UpperCAmelCase_     : Union[str, Any]         =					self.image_processing_class(**self.image_processor_dict				)
													# create random PyTorch tensors
													UpperCAmelCase_     : List[Any]         =					prepare_image_inputs(self.image_processor_tester    ,       equal_resolution=__magic_name__    ,       torchify=__magic_name__				)
													for image in image_inputs:
																			self.assertIsInstance(__magic_name__    ,       torch.Tensor				)

													# Test not batched input
													UpperCAmelCase_     : List[Any]         =					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.size['''shortest_edge'''],
													        self.image_processor_tester.size['''shortest_edge'''],
													    )    ,       )

													# Test batched
													UpperCAmelCase_     : str         =					image_processing(__magic_name__    ,       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.size['''shortest_edge'''],
													        self.image_processor_tester.size['''shortest_edge'''],
													    )    ,       )





