



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




import gc
import unittest

import numpy as np
import torch

from diffusers import RePaintPipeline, RePaintScheduler, UNetaDModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_image,
    load_numpy,
    nightly,
    require_torch_gpu,
    skip_mps,
    torch_device,
)

from ..pipeline_params import IMAGE_INPAINTING_BATCH_PARAMS, IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()





class 			lowerCAmelCase__(     snake_case__     ,     unittest.TestCase    ):






    '''simple docstring'''





    A_	:  Tuple								=			RePaintPipeline
    A_	:  Tuple								=			IMAGE_INPAINTING_PARAMS - {'width', 'height', 'guidance_scale'}
    A_	:  str								=			PipelineTesterMixin.required_optional_params - {
        'latents',
        'num_images_per_prompt',
        'callback',
        'callback_steps',
    }
    A_	:  Optional[Any]								=			IMAGE_INPAINTING_BATCH_PARAMS
    A_	:  Union[str, Any]								=			False





    def        _lowerCamelCase			(						self					: Any						):





       '''simple docstring'''
       torch.manual_seed(0						)
       torch.manual_seed(0						)
       UpperCAmelCase_				:   int							= UNetaDModel(
           block_out_channels=(32, 64)							, layers_per_block=2							, sample_size=32							, in_channels=3							, out_channels=3							, down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''')							, up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''')							, )
       UpperCAmelCase_				:   str							= RePaintScheduler()
       UpperCAmelCase_				:   Optional[Any]							= {'''unet''': unet, '''scheduler''': scheduler}
       return components





    def        _lowerCamelCase			(						self					: List[str]							, __snake_case					: Optional[Any]							, __snake_case					: int=0						):





       '''simple docstring'''
       if str(__snake_case						).startswith('''mps'''						):
          UpperCAmelCase_				:   Optional[Any]							= torch.manual_seed(__snake_case						)
       else:
          UpperCAmelCase_				:   Optional[Any]							= torch.Generator(device=__snake_case						).manual_seed(__snake_case						)
       UpperCAmelCase_				:   Optional[Any]							= np.random.RandomState(__snake_case						).standard_normal((1, 3, 32, 32)						)
       UpperCAmelCase_				:   Optional[int]							= torch.from_numpy(__snake_case						).to(device=__snake_case							, dtype=torch.floataa						)
       UpperCAmelCase_				:   Any							= (image > 0).to(device=__snake_case							, dtype=torch.floataa						)
       UpperCAmelCase_				:   List[str]							= {
           '''image''': image,
           '''mask_image''': mask,
           '''generator''': generator,
           '''num_inference_steps''': 5,
           '''eta''': 0.0,
           '''jump_length''': 2,
           '''jump_n_sample''': 2,
           '''output_type''': '''numpy''',
       }
       return inputs





    def        _lowerCamelCase			(						self					: Union[str, Any]						):





       '''simple docstring'''
       UpperCAmelCase_				:   str							= '''cpu'''  # ensure determinism for the device-dependent torch.Generator
       UpperCAmelCase_				:   Optional[int]							= self.get_dummy_components()
       UpperCAmelCase_				:   Dict							= RePaintPipeline(**__snake_case						)
       UpperCAmelCase_				:   int							= sd_pipe.to(__snake_case						)
       sd_pipe.set_progress_bar_config(disable=__snake_case						)

       UpperCAmelCase_				:   List[Any]							= self.get_dummy_inputs(__snake_case						)
       UpperCAmelCase_				:   Union[str, Any]							= sd_pipe(**__snake_case						).images
       UpperCAmelCase_				:   Optional[Any]							= image[0, -3:, -3:, -1]

       assert image.shape == (1, 32, 32, 3)
       UpperCAmelCase_				:   Tuple							= np.array([1.0_000, 0.5_426, 0.5_497, 0.2_200, 1.0_000, 1.0_000, 0.5_623, 1.0_000, 0.6_274]						)

       assert np.abs(image_slice.flatten() - expected_slice						).max() < 1E-3





    @skip_mps
    def        _lowerCamelCase			(						self					: Optional[int]						):





       '''simple docstring'''
       return super().test_save_load_local()





    @unittest.skip('''non-deterministic pipeline'''						)
    def        _lowerCamelCase			(						self					: Optional[Any]						):





       '''simple docstring'''
       return super().test_inference_batch_single_identical()





    @skip_mps
    def        _lowerCamelCase			(						self					: Dict						):





       '''simple docstring'''
       return super().test_dict_tuple_outputs_equivalent()





    @skip_mps
    def        _lowerCamelCase			(						self					: int						):





       '''simple docstring'''
       return super().test_save_load_optional_components()





    @skip_mps
    def        _lowerCamelCase			(						self					: Union[str, Any]						):





       '''simple docstring'''
       return super().test_attention_slicing_forward_pass()





@nightly
@require_torch_gpu
class 			lowerCAmelCase__(     unittest.TestCase    ):






    '''simple docstring'''





    def        _lowerCamelCase			(						self					: Tuple						):





       '''simple docstring'''
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()





    def        _lowerCamelCase			(						self					: List[str]						):





       '''simple docstring'''
       UpperCAmelCase_				:   List[Any]							= load_image(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/'''
           '''repaint/celeba_hq_256.png'''						)
       UpperCAmelCase_				:   int							= load_image(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/repaint/mask_256.png'''						)
       UpperCAmelCase_				:   List[Any]							= load_numpy(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/'''
           '''repaint/celeba_hq_256_result.npy'''						)

       UpperCAmelCase_				:   List[str]							= '''google/ddpm-ema-celebahq-256'''
       UpperCAmelCase_				:   Union[str, Any]							= UNetaDModel.from_pretrained(__snake_case						)
       UpperCAmelCase_				:   Dict							= RePaintScheduler.from_pretrained(__snake_case						)

       UpperCAmelCase_				:   Optional[int]							= RePaintPipeline(unet=__snake_case							, scheduler=__snake_case						).to(__snake_case						)
       repaint.set_progress_bar_config(disable=__snake_case						)
       repaint.enable_attention_slicing()

       UpperCAmelCase_				:   Optional[int]							= torch.manual_seed(0						)
       UpperCAmelCase_				:   List[str]							= repaint(
           __snake_case							, __snake_case							, num_inference_steps=250							, eta=0.0							, jump_length=10							, jump_n_sample=10							, generator=__snake_case							, output_type='''np'''							, )
       UpperCAmelCase_				:   Tuple							= output.images[0]

       assert image.shape == (256, 256, 3)
       assert np.abs(expected_image - image						).mean() < 1E-2