




"""simple docstring"""

import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPImageProcessor, CLIPVisionConfig, CLIPVisionModelWithProjection

from diffusers import (
    AutoencoderKL,
    DPMSolverMultistepScheduler,
    PNDMScheduler,
    StableDiffusionImageVariationPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, nightly, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()

class 							lowercase   (     __UpperCAmelCase  ,						__UpperCAmelCase  ,						__UpperCAmelCase  ,						unittest.TestCase):
				__lowerCAmelCase     :     Optional[int]								= StableDiffusionImageVariationPipeline
				__lowerCAmelCase     :     Dict								= IMAGE_VARIATION_PARAMS
				__lowerCAmelCase     :     Union[str, Any]								= IMAGE_VARIATION_BATCH_PARAMS
				__lowerCAmelCase     :     List[str]								= frozenset([])
				# TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
				__lowerCAmelCase     :     Optional[int]								= frozenset([])







				def        a_	(				self :       str							):



					"""simple docstring"""

					torch.manual_seed(0							)
					A_	:					int						 =		UNetaDConditionModel(
					    block_out_channels=(32, 64)   ,  layers_per_block=2   ,  sample_size=32   ,  in_channels=4   ,  out_channels=4   ,  down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')   ,  up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')   ,  cross_attention_dim=32   ,  )
					A_	:					Tuple						 =		PNDMScheduler(skip_prk_steps=_lowerCamelCase							)
					torch.manual_seed(0							)
					A_	:					str						 =		AutoencoderKL(
					    block_out_channels=[32, 64]   ,  in_channels=3   ,  out_channels=3   ,  down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']   ,  up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']   ,  latent_channels=4   ,  )
					torch.manual_seed(0							)
					A_	:					int						 =		CLIPVisionConfig(
					    hidden_size=32   ,  projection_dim=32   ,  intermediate_size=37   ,  layer_norm_eps=1E-05   ,  num_attention_heads=4   ,  num_hidden_layers=5   ,  image_size=32   ,  patch_size=4   ,  )
					A_	:					List[Any]						 =		CLIPVisionModelWithProjection(_lowerCamelCase							)
					A_	:					Optional[Any]						 =		CLIPImageProcessor(crop_size=32   ,  size=32							)

					A_	:					int						 =		{
					    '''unet''': unet,
					    '''scheduler''': scheduler,
					    '''vae''': vae,
					    '''image_encoder''': image_encoder,
					    '''feature_extractor''': feature_extractor,
					    '''safety_checker''': None,
					}
					return components







				def        a_	(				self :       Dict   ,  _lowerCamelCase :       str   ,  _lowerCamelCase :       Any=0							):



					"""simple docstring"""

					A_	:					List[Any]						 =		floats_tensor((1, 3, 32, 32)   ,  rng=random.Random(_lowerCamelCase							)							)
					A_	:					Dict						 =		image.cpu().permute(0   ,  2   ,  3   ,  1							)[0]
					A_	:					Any						 =		Image.fromarray(np.uinta(_lowerCamelCase							)							).convert('''RGB'''							).resize((32, 32)							)
					if str(_lowerCamelCase							).startswith('''mps'''							):
						A_	:					Optional[Any]						 =		torch.manual_seed(_lowerCamelCase							)
					else:
						A_	:					Tuple						 =		torch.Generator(device=_lowerCamelCase							).manual_seed(_lowerCamelCase							)
					A_	:					Optional[int]						 =		{
					    '''image''': image,
					    '''generator''': generator,
					    '''num_inference_steps''': 2,
					    '''guidance_scale''': 6.0,
					    '''output_type''': '''numpy''',
					}
					return inputs







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



					"""simple docstring"""

					A_	:					int						 =		'''cpu'''  # ensure determinism for the device-dependent torch.Generator
					A_	:					int						 =		self.get_dummy_components()
					A_	:					Any						 =		StableDiffusionImageVariationPipeline(**_lowerCamelCase							)
					A_	:					Dict						 =		sd_pipe.to(_lowerCamelCase							)
					sd_pipe.set_progress_bar_config(disable=_lowerCamelCase							)

					A_	:					Optional[int]						 =		self.get_dummy_inputs(_lowerCamelCase							)
					A_	:					List[str]						 =		sd_pipe(**_lowerCamelCase							).images
					A_	:					Optional[Any]						 =		image[0, -3:, -3:, -1]

					assert image.shape == (1, 64, 64, 3)
					A_	:					int						 =		np.array([0.5239, 0.5723, 0.4796, 0.5049, 0.5550, 0.4685, 0.5329, 0.4891, 0.4921]							)

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







				def        a_	(				self :       Tuple							):



					"""simple docstring"""

					A_	:					int						 =		'''cpu'''  # ensure determinism for the device-dependent torch.Generator
					A_	:					Optional[Any]						 =		self.get_dummy_components()
					A_	:					Optional[Any]						 =		StableDiffusionImageVariationPipeline(**_lowerCamelCase							)
					A_	:					str						 =		sd_pipe.to(_lowerCamelCase							)
					sd_pipe.set_progress_bar_config(disable=_lowerCamelCase							)

					A_	:					Any						 =		self.get_dummy_inputs(_lowerCamelCase							)
					A_	:					Any						 =		2 * [inputs['''image''']]
					A_	:					List[str]						 =		sd_pipe(**_lowerCamelCase							)

					A_	:					Dict						 =		output.images

					A_	:					List[str]						 =		image[-1, -3:, -3:, -1]

					assert image.shape == (2, 64, 64, 3)
					A_	:					str						 =		np.array([0.6892, 0.5637, 0.5836, 0.5771, 0.6254, 0.6409, 0.5580, 0.5569, 0.5289]							)

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







				def        a_	(				self :       Any							):



					"""simple docstring"""

					super().test_inference_batch_single_identical(expected_max_diff=3E-3							)

@slow
@require_torch_gpu
class 							lowercase   (     unittest.TestCase):







				def        a_	(				self :       int							):



					"""simple docstring"""

					super().tearDown()
					gc.collect()
					torch.cuda.empty_cache()







				def        a_	(				self :       Dict   ,  _lowerCamelCase :       str   ,  _lowerCamelCase :       Optional[int]="cpu"   ,  _lowerCamelCase :       Optional[Any]=torch.floataa   ,  _lowerCamelCase :       Union[str, Any]=0							):



					"""simple docstring"""

					A_	:					Tuple						 =		torch.Generator(device=_lowerCamelCase							).manual_seed(_lowerCamelCase							)
					A_	:					Dict						 =		load_image(
					    '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main'''
					    '''/stable_diffusion_imgvar/input_image_vermeer.png'''							)
					A_	:					List[str]						 =		np.random.RandomState(_lowerCamelCase							).standard_normal((1, 4, 64, 64)							)
					A_	:					Tuple						 =		torch.from_numpy(_lowerCamelCase							).to(device=_lowerCamelCase   ,  dtype=_lowerCamelCase							)
					A_	:					List[Any]						 =		{
					    '''image''': init_image,
					    '''latents''': latents,
					    '''generator''': generator,
					    '''num_inference_steps''': 3,
					    '''guidance_scale''': 7.5,
					    '''output_type''': '''numpy''',
					}
					return inputs







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



					"""simple docstring"""

					A_	:					str						 =		StableDiffusionImageVariationPipeline.from_pretrained(
					    '''lambdalabs/sd-image-variations-diffusers'''   ,  safety_checker=_lowerCamelCase							)
					A_	:					Tuple						 =		sd_pipe.to(_lowerCamelCase							)
					sd_pipe.set_progress_bar_config(disable=_lowerCamelCase							)

					A_	:					Optional[int]						 =		self.get_inputs(_lowerCamelCase							)
					A_	:					Union[str, Any]						 =		sd_pipe(**_lowerCamelCase							).images
					A_	:					List[Any]						 =		image[0, -3:, -3:, -1].flatten()

					assert image.shape == (1, 5_12, 5_12, 3)
					A_	:					Optional[Any]						 =		np.array([0.84491, 0.90789, 0.75708, 0.78734, 0.83485, 0.70099, 0.66938, 0.68727, 0.61379]							)
					assert np.abs(image_slice - expected_slice							).max() < 6E-3







				def        a_	(				self :       Any							):



					"""simple docstring"""

					A_	:					Union[str, Any]						 =		0

					def callback_fn(_lowerCamelCase :       int   ,  _lowerCamelCase :       int   ,  _lowerCamelCase :       torch.FloatTensor							) -> None:
						A_	:					Any						 =		True
						nonlocal number_of_steps
						number_of_steps += 1
						if step == 1:
							A_	:					str						 =		latents.detach().cpu().numpy()
							assert latents.shape == (1, 4, 64, 64)
							A_	:					List[str]						 =		latents[0, -3:, -3:, -1]
							A_	:					List[Any]						 =		np.array(
							    [-0.1621, 0.2837, -0.7979, -0.1221, -1.3057, 0.7681, -2.1191, 0.0464, 1.6309]							)

							assert np.abs(latents_slice.flatten() - expected_slice							).max() < 5E-2
						elif step == 2:
							A_	:					Tuple						 =		latents.detach().cpu().numpy()
							assert latents.shape == (1, 4, 64, 64)
							A_	:					Any						 =		latents[0, -3:, -3:, -1]
							A_	:					Union[str, Any]						 =		np.array([0.6299, 1.7500, 1.1992, -2.1582, -1.8994, 0.7334, -0.7090, 1.0137, 1.5273]							)

							assert np.abs(latents_slice.flatten() - expected_slice							).max() < 5E-2

					A_	:					str						 =		False

					A_	:					int						 =		StableDiffusionImageVariationPipeline.from_pretrained(
					    '''fusing/sd-image-variations-diffusers'''   ,  safety_checker=_lowerCamelCase   ,  torch_dtype=torch.floataa   ,  )
					pipe.to(_lowerCamelCase							)
					pipe.set_progress_bar_config(disable=_lowerCamelCase							)
					pipe.enable_attention_slicing()

					A_	:					Tuple						 =		self.get_inputs(_lowerCamelCase   ,  dtype=torch.floataa							)
					pipe(**_lowerCamelCase   ,  callback=_lowerCamelCase   ,  callback_steps=1							)
					assert callback_fn.has_been_called
					assert number_of_steps == inputs["num_inference_steps"]







				def        a_	(				self :       int							):



					"""simple docstring"""

					torch.cuda.empty_cache()
					torch.cuda.reset_max_memory_allocated()
					torch.cuda.reset_peak_memory_stats()

					A_	:					Union[str, Any]						 =		'''fusing/sd-image-variations-diffusers'''
					A_	:					Optional[Any]						 =		StableDiffusionImageVariationPipeline.from_pretrained(
					    _lowerCamelCase   ,  safety_checker=_lowerCamelCase   ,  torch_dtype=torch.floataa							)
					A_	:					List[str]						 =		pipe.to(_lowerCamelCase							)
					pipe.set_progress_bar_config(disable=_lowerCamelCase							)
					pipe.enable_attention_slicing(1							)
					pipe.enable_sequential_cpu_offload()

					A_	:					str						 =		self.get_inputs(_lowerCamelCase   ,  dtype=torch.floataa							)
					A_	:					Optional[int]						 =		pipe(**_lowerCamelCase							)

					A_	:					Dict						 =		torch.cuda.max_memory_allocated()
					# make sure that less than 2.6 GB is allocated
					assert mem_bytes < 2.6 * 10**9

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







				def        a_	(				self :       Tuple							):



					"""simple docstring"""

					super().tearDown()
					gc.collect()
					torch.cuda.empty_cache()







				def        a_	(				self :       Any   ,  _lowerCamelCase :       List[Any]   ,  _lowerCamelCase :       Optional[Any]="cpu"   ,  _lowerCamelCase :       List[Any]=torch.floataa   ,  _lowerCamelCase :       int=0							):



					"""simple docstring"""

					A_	:					Tuple						 =		torch.Generator(device=_lowerCamelCase							).manual_seed(_lowerCamelCase							)
					A_	:					Any						 =		load_image(
					    '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main'''
					    '''/stable_diffusion_imgvar/input_image_vermeer.png'''							)
					A_	:					Tuple						 =		np.random.RandomState(_lowerCamelCase							).standard_normal((1, 4, 64, 64)							)
					A_	:					Dict						 =		torch.from_numpy(_lowerCamelCase							).to(device=_lowerCamelCase   ,  dtype=_lowerCamelCase							)
					A_	:					Dict						 =		{
					    '''image''': init_image,
					    '''latents''': latents,
					    '''generator''': generator,
					    '''num_inference_steps''': 50,
					    '''guidance_scale''': 7.5,
					    '''output_type''': '''numpy''',
					}
					return inputs







				def        a_	(				self :       List[str]							):



					"""simple docstring"""

					A_	:					int						 =		StableDiffusionImageVariationPipeline.from_pretrained('''fusing/sd-image-variations-diffusers'''							)
					sd_pipe.to(_lowerCamelCase							)
					sd_pipe.set_progress_bar_config(disable=_lowerCamelCase							)

					A_	:					Union[str, Any]						 =		self.get_inputs(_lowerCamelCase							)
					A_	:					Dict						 =		sd_pipe(**_lowerCamelCase							).images[0]

					A_	:					str						 =		load_numpy(
					    '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main'''
					    '''/stable_diffusion_imgvar/lambdalabs_variations_pndm.npy'''							)
					A_	:					str						 =		np.abs(expected_image - image							).max()
					assert max_diff < 1E-3







				def        a_	(				self :       Optional[int]							):



					"""simple docstring"""

					A_	:					Dict						 =		StableDiffusionImageVariationPipeline.from_pretrained('''fusing/sd-image-variations-diffusers'''							)
					A_	:					Optional[int]						 =		DPMSolverMultistepScheduler.from_config(sd_pipe.scheduler.config							)
					sd_pipe.to(_lowerCamelCase							)
					sd_pipe.set_progress_bar_config(disable=_lowerCamelCase							)

					A_	:					str						 =		self.get_inputs(_lowerCamelCase							)
					A_	:					List[str]						 =		25
					A_	:					Dict						 =		sd_pipe(**_lowerCamelCase							).images[0]

					A_	:					str						 =		load_numpy(
					    '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main'''
					    '''/stable_diffusion_imgvar/lambdalabs_variations_dpm_multi.npy'''							)
					A_	:					List[str]						 =		np.abs(expected_image - image							).max()
					assert max_diff < 1E-3











"""simple docstring"""

def 		lowercase_   (		_UpperCAmelCase	,   _UpperCAmelCase						):




	"""simple docstring"""






	return a + b


if __name__ == "__main__":
		_lowerCamelCase	:      Tuple   =							5
		_lowerCamelCase	:      Union[str, Any]   =							6
		print(f'The sum of {a} + {b} is {add(a, b)}')





