



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


__a           =							namedtuple("ExampleNamedTuple", "a b c")
class 							lowerCamelCase    (     unittest.TestCase							):






					'''simple docstring'''





					def   lowerCAmelCase_							(			self:				Dict		)  ->      Any:
											snake_case_					:Tuple		=     torch.randn(5		,	2		)
											snake_case_					:Dict		=     torch.device("""cuda"""		) if torch.cuda.is_available() else torch.device("""cpu"""		)

											snake_case_					:Tuple		=     send_to_device(snake_case		,	snake_case		)
											self.assertTrue(torch.equal(resulta.cpu()		,	snake_case		)		)

											snake_case_					:List[str]		=     send_to_device((tensor, [tensor, tensor], 1)		,	snake_case		)
											self.assertIsInstance(snake_case		,	snake_case		)
											self.assertTrue(torch.equal(resulta[0].cpu()		,	snake_case		)		)
											self.assertIsInstance(resulta[1]		,	snake_case		)
											self.assertTrue(torch.equal(resulta[1][0].cpu()		,	snake_case		)		)
											self.assertTrue(torch.equal(resulta[1][1].cpu()		,	snake_case		)		)
											self.assertEqual(resulta[2]		,	1		)

											snake_case_					:List[str]		=     send_to_device({"""a""": tensor, """b""": [tensor, tensor], """c""": 1}		,	snake_case		)
											self.assertIsInstance(snake_case		,	snake_case		)
											self.assertTrue(torch.equal(resulta["""a"""].cpu()		,	snake_case		)		)
											self.assertIsInstance(resulta["""b"""]		,	snake_case		)
											self.assertTrue(torch.equal(resulta["""b"""][0].cpu()		,	snake_case		)		)
											self.assertTrue(torch.equal(resulta["""b"""][1].cpu()		,	snake_case		)		)
											self.assertEqual(resulta["""c"""]		,	1		)

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

											snake_case_					:Optional[Any]		=     send_to_device(UserDict({"""a""": tensor, """b""": [tensor, tensor], """c""": 1}		)		,	snake_case		)
											self.assertIsInstance(snake_case		,	snake_case		)
											self.assertTrue(torch.equal(resulta["""a"""].cpu()		,	snake_case		)		)
											self.assertIsInstance(resulta["""b"""]		,	snake_case		)
											self.assertTrue(torch.equal(resulta["""b"""][0].cpu()		,	snake_case		)		)
											self.assertTrue(torch.equal(resulta["""b"""][1].cpu()		,	snake_case		)		)
											self.assertEqual(resulta["""c"""]		,	1		)






					def   lowerCAmelCase_							(			self:				Any		)  ->      Optional[int]:
											with self.assertRaises(snake_case		) as cm:
																	snake_case_					:int		=     recursively_apply(torch.tensor		,	(torch.tensor(1		), 1)		,	error_on_other_type=snake_case		)
											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   lowerCAmelCase_							(			self:				str		)  ->      int:
											snake_case_					:Tuple		=     torch.tensor([1, 2, 3, 4, 5]		)
											self.assertEqual(listify(snake_case		)		,	[1, 2, 3, 4, 5]		)

											snake_case_					:int		=     torch.tensor([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]		)
											self.assertEqual(listify(snake_case		)		,	[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]		)

											snake_case_					:Any		=     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(snake_case		)		,	[[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]], [[11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]]		)






					def   lowerCAmelCase_							(			self:				Dict		)  ->      List[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   lowerCAmelCase_							(			self:				Optional[Any]		)  ->      List[Any]:
											snake_case_					:Any		=     RegressionModel()
											snake_case_					:Union[str, Any]		=     model.forward
											snake_case_					:int		=     convert_outputs_to_fpaa(model.forward		)
											snake_case_					:Optional[int]		=     extract_model_from_parallel(snake_case		,	keep_fpaa_wrapper=snake_case		)
											snake_case_					:str		=     pickle.dumps(snake_case		)






					@require_cuda
					def   lowerCAmelCase_							(			self:				Tuple		)  ->      str:
											snake_case_					:Union[str, Any]		=     RegressionModel()
											snake_case_					:Optional[Any]		=     model.forward
											snake_case_					:Tuple		=     torch.cuda.amp.autocast(dtype=torch.floataa		)(model.forward		)
											snake_case_					:Any		=     convert_outputs_to_fpaa(model.forward		)
											snake_case_					:List[str]		=     extract_model_from_parallel(snake_case		,	keep_fpaa_wrapper=snake_case		)
											snake_case_					:int		=     pickle.dumps(snake_case		)






					@require_cuda
					@require_torch_min_version(version="""2.0"""		)
					def   lowerCAmelCase_							(			self:				Union[str, Any]		)  ->      List[str]:
											snake_case_					:Tuple		=     RegressionModel()
											snake_case_					:Any		=     model.forward
											snake_case_					:Optional[Any]		=     torch.cuda.amp.autocast(dtype=torch.floataa		)(model.forward		)
											snake_case_					:str		=     convert_outputs_to_fpaa(model.forward		)
											snake_case_					:str		=     torch.compile(model.forward		,	backend="""inductor"""		)
											snake_case_					:Tuple		=     torch.randn(4		,	10		).cuda()
											snake_case_					:List[Any]		=     model(snake_case		)






					def   lowerCAmelCase_							(			self:				Any		)  ->      List[str]:
											snake_case_					:Optional[int]		=     RegressionModel()
											# could also do a test with DistributedDataParallel, but difficult to run on CPU or single GPU
											snake_case_					:int		=     torch.nn.parallel.DataParallel(snake_case		)
											snake_case_					:str		=     extract_model_from_parallel(snake_case		)

											self.assertEqual(snake_case		,	snake_case		)






					@require_torch_min_version(version="""2.0"""		)
					def   lowerCAmelCase_							(			self:				Dict		)  ->      Tuple:
											snake_case_					:Tuple		=     RegressionModel()
											snake_case_					:Optional[Any]		=     torch.compile(snake_case		)

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

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






					def   lowerCAmelCase_							(			self:				Union[str, Any]		)  ->      List[Any]:
											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 sys
from collections.abc import Mapping

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter






class        a__     (      TensorFormatter[Mapping, np.ndarray, Mapping]    ):
     '''simple docstring'''







     def __init__(self     :						Tuple					,					lowercase__     :						Dict=None					,					**lowercase__     :						List[Any]       )	->							str:
           super().__init__(features=lowercase__       )
           __A		 =   np_array_kwargs






     def      _UpperCamelCase (self     :						int					,					lowercase__     :						Tuple       )	->							List[Any]:
           if isinstance(lowercase__					,					lowercase__       ):
                 if column and all(
                     isinstance(lowercase__					,					np.ndarray       ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column       ):
                       return np.stack(lowercase__       )
                 else:
                       # don't use np.array(column, dtype=object)
                       # since it fails in certain cases
                       # see https://stackoverflow.com/q/51005699
                       __A		 =   np.empty(len(lowercase__       )					,					dtype=lowercase__       )
                       __A		 =   column
                       return out
           return column






     def      _UpperCamelCase (self     :						Optional[Any]					,					lowercase__     :						Optional[int]       )	->							Tuple:
           if isinstance(lowercase__					,					(str, bytes, type(lowercase__       ))       ):
                 return value
           elif isinstance(lowercase__					,					(np.character, np.ndarray)       ) and np.issubdtype(value.dtype					,					np.character       ):
                 return value
           elif isinstance(lowercase__					,					np.number       ):
                 return value

           __A		 =   {}

           if isinstance(lowercase__					,					np.ndarray       ) and np.issubdtype(value.dtype					,					np.integer       ):
                 __A		 =   {"dtype": np.intaa}
           elif isinstance(lowercase__					,					np.ndarray       ) and np.issubdtype(value.dtype					,					np.floating       ):
                 __A		 =   {"dtype": np.floataa}
           elif config.PIL_AVAILABLE and "PIL" in sys.modules:
                 import PIL.Image

                 if isinstance(lowercase__					,					PIL.Image.Image       ):
                       return np.asarray(lowercase__					,					**self.np_array_kwargs       )

           return np.asarray(lowercase__					,					**{**default_dtype, **self.np_array_kwargs}       )






     def      _UpperCamelCase (self     :						List[Any]					,					lowercase__     :						str       )	->							Optional[Any]:
           # support for torch, tf, jax etc.
           if config.TORCH_AVAILABLE and "torch" in sys.modules:
                 import torch

                 if isinstance(lowercase__					,					torch.Tensor       ):
                       return self._tensorize(data_struct.detach().cpu().numpy()[()]       )
           if hasattr(lowercase__					,					"__array__"       ) and not isinstance(lowercase__					,					(np.ndarray, np.character, np.number)       ):
                 __A		 =   data_struct.__array__()
           # support for nested types like struct of list of struct
           if isinstance(lowercase__					,					np.ndarray       ):
                 if data_struct.dtype == object:
                       return self._consolidate([self.recursive_tensorize(lowercase__       ) for substruct in data_struct]       )
           if isinstance(lowercase__					,					(list, tuple)       ):
                 return self._consolidate([self.recursive_tensorize(lowercase__       ) for substruct in data_struct]       )
           return self._tensorize(lowercase__       )






     def      _UpperCamelCase (self     :						Optional[Any]					,					lowercase__     :						dict       )	->							Dict:
           return map_nested(self._recursive_tensorize					,					lowercase__					,					map_list=lowercase__       )






     def      _UpperCamelCase (self     :						Optional[int]					,					lowercase__     :						pa.Table       )	->							Mapping:
           __A		 =   self.numpy_arrow_extractor().extract_row(lowercase__       )
           __A		 =   self.python_features_decoder.decode_row(lowercase__       )
           return self.recursive_tensorize(lowercase__       )






     def      _UpperCamelCase (self     :						List[Any]					,					lowercase__     :						pa.Table       )	->							np.ndarray:
           __A		 =   self.numpy_arrow_extractor().extract_column(lowercase__       )
           __A		 =   self.python_features_decoder.decode_column(lowercase__					,					pa_table.column_names[0]       )
           __A		 =   self.recursive_tensorize(lowercase__       )
           __A		 =   self._consolidate(lowercase__       )
           return column






     def      _UpperCamelCase (self     :						Optional[Any]					,					lowercase__     :						pa.Table       )	->							Mapping:
           __A		 =   self.numpy_arrow_extractor().extract_batch(lowercase__       )
           __A		 =   self.python_features_decoder.decode_batch(lowercase__       )
           __A		 =   self.recursive_tensorize(lowercase__       )
           for column_name in batch:
                 __A		 =   self._consolidate(batch[column_name]       )
           return batch


