



import gc
import unittest

import numpy as np
import torch
from torch.backends.cuda import sdp_kernel

from diffusers import (
    CMStochasticIterativeScheduler,
    ConsistencyModelPipeline,
    UNetaDModel,
)
from diffusers.utils import randn_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_a, require_torch_gpu

from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()



class     _UpperCAmelCase			(       _UpperCamelCase			,      unittest.TestCase     ):
					UpperCamelCase__		    =				ConsistencyModelPipeline
					UpperCamelCase__		    =				UNCONDITIONAL_IMAGE_GENERATION_PARAMS
					UpperCamelCase__		    =				UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS

					# Override required_optional_params to remove num_images_per_prompt
					UpperCamelCase__		    =				frozenset(
					    [
					        '''num_inference_steps''',
					        '''generator''',
					        '''latents''',
					        '''output_type''',
					        '''return_dict''',
					        '''callback''',
					        '''callback_steps''',
					    ]     )




					@property
					def 		snake_case_		(				self):
									A__		 =					UNetaDModel.from_pretrained(
									    '''diffusers/consistency-models-test''' ,						subfolder='''test_unet''' ,						)
									return unet




					@property
					def 		snake_case_		(				self):
									A__		 =					UNetaDModel.from_pretrained(
									    '''diffusers/consistency-models-test''' ,						subfolder='''test_unet_class_cond''' ,						)
									return unet




					def 		snake_case_		(				self ,						a__=False):
									if class_cond:
													A__		 =					self.dummy_cond_unet
									else:
													A__		 =					self.dummy_uncond_unet

									# Default to CM multistep sampler
									A__		 =					CMStochasticIterativeScheduler(
									    num_train_timesteps=4_0 ,						sigma_min=0.0_0_2 ,						sigma_max=8_0.0 ,						)

									A__		 =					{
									    "unet": unet,
									    "scheduler": scheduler,
									}

									return components




					def 		snake_case_		(				self ,						a__ ,						a__=0):
									if str(__a).startswith('''mps'''):
													A__		 =					torch.manual_seed(__a)
									else:
													A__		 =					torch.Generator(device=__a).manual_seed(__a)

									A__		 =					{
									    "batch_size": 1,
									    "num_inference_steps": None,
									    "timesteps": [2_2, 0],
									    "generator": generator,
									    "output_type": "np",
									}

									return inputs




					def 		snake_case_		(				self):
									A__		 =					"cpu"  # ensure determinism for the device-dependent torch.Generator
									A__		 =					self.get_dummy_components()
									A__		 =					ConsistencyModelPipeline(**__a)
									A__		 =					pipe.to(__a)
									pipe.set_progress_bar_config(disable=__a)

									A__		 =					self.get_dummy_inputs(__a)
									A__		 =					pipe(**__a).images
									assert image.shape == (1, 3_2, 3_2, 3)

									A__		 =					image[0, -3:, -3:, -1]
									A__		 =					np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4])

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




					def 		snake_case_		(				self):
									A__		 =					"cpu"  # ensure determinism for the device-dependent torch.Generator
									A__		 =					self.get_dummy_components(class_cond=__a)
									A__		 =					ConsistencyModelPipeline(**__a)
									A__		 =					pipe.to(__a)
									pipe.set_progress_bar_config(disable=__a)

									A__		 =					self.get_dummy_inputs(__a)
									A__		 =					0
									A__		 =					pipe(**__a).images
									assert image.shape == (1, 3_2, 3_2, 3)

									A__		 =					image[0, -3:, -3:, -1]
									A__		 =					np.array([0.3_5_7_2, 0.6_2_7_3, 0.4_0_3_1, 0.3_9_6_1, 0.4_3_2_1, 0.5_7_3_0, 0.5_2_6_6, 0.4_7_8_0, 0.5_0_0_4])

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




					def 		snake_case_		(				self):
									A__		 =					"cpu"  # ensure determinism for the device-dependent torch.Generator
									A__		 =					self.get_dummy_components()
									A__		 =					ConsistencyModelPipeline(**__a)
									A__		 =					pipe.to(__a)
									pipe.set_progress_bar_config(disable=__a)

									A__		 =					self.get_dummy_inputs(__a)
									A__		 =					1
									A__		 =					None
									A__		 =					pipe(**__a).images
									assert image.shape == (1, 3_2, 3_2, 3)

									A__		 =					image[0, -3:, -3:, -1]
									A__		 =					np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7])

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




					def 		snake_case_		(				self):
									A__		 =					"cpu"  # ensure determinism for the device-dependent torch.Generator
									A__		 =					self.get_dummy_components(class_cond=__a)
									A__		 =					ConsistencyModelPipeline(**__a)
									A__		 =					pipe.to(__a)
									pipe.set_progress_bar_config(disable=__a)

									A__		 =					self.get_dummy_inputs(__a)
									A__		 =					1
									A__		 =					None
									A__		 =					0
									A__		 =					pipe(**__a).images
									assert image.shape == (1, 3_2, 3_2, 3)

									A__		 =					image[0, -3:, -3:, -1]
									A__		 =					np.array([0.5_0_0_4, 0.5_0_0_4, 0.4_9_9_4, 0.5_0_0_8, 0.4_9_7_6, 0.5_0_1_8, 0.4_9_9_0, 0.4_9_8_2, 0.4_9_8_7])

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







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




					def 		snake_case_		(				self):
									super().tearDown()
									gc.collect()
									torch.cuda.empty_cache()




					def 		snake_case_		(				self ,						a__=0 ,						a__=False ,						a__="cpu" ,						a__=torch.floataa ,						a__=(1, 3, 6_4, 6_4)):
									A__		 =					torch.manual_seed(__a)

									A__		 =					{
									    "num_inference_steps": None,
									    "timesteps": [2_2, 0],
									    "class_labels": 0,
									    "generator": generator,
									    "output_type": "np",
									}

									if get_fixed_latents:
													A__		 =					self.get_fixed_latents(seed=__a ,						device=__a ,						dtype=__a ,						shape=__a)
													A__		 =					latents

									return inputs




					def 		snake_case_		(				self ,						a__=0 ,						a__="cpu" ,						a__=torch.floataa ,						a__=(1, 3, 6_4, 6_4)):
									if type(__a) == str:
													A__		 =					torch.device(__a)
									A__		 =					torch.Generator(device=__a).manual_seed(__a)
									A__		 =					randn_tensor(__a ,						generator=__a ,						device=__a ,						dtype=__a)
									return latents




					def 		snake_case_		(				self):
									A__		 =					UNetaDModel.from_pretrained('''diffusers/consistency_models''' ,						subfolder='''diffusers_cd_imagenet64_l2''')
									A__		 =					CMStochasticIterativeScheduler(
									    num_train_timesteps=4_0 ,						sigma_min=0.0_0_2 ,						sigma_max=8_0.0 ,						)
									A__		 =					ConsistencyModelPipeline(unet=__a ,						scheduler=__a)
									pipe.to(torch_device=__a)
									pipe.set_progress_bar_config(disable=__a)

									A__		 =					self.get_inputs()
									A__		 =					pipe(**__a).images
									assert image.shape == (1, 6_4, 6_4, 3)

									A__		 =					image[0, -3:, -3:, -1]

									A__		 =					np.array([0.0_8_8_8, 0.0_8_8_1, 0.0_6_6_6, 0.0_4_7_9, 0.0_2_9_2, 0.0_1_9_5, 0.0_2_0_1, 0.0_1_6_3, 0.0_2_5_4])

									assert np.abs(image_slice.flatten() - expected_slice).max() < 2e-2




					def 		snake_case_		(				self):
									A__		 =					UNetaDModel.from_pretrained('''diffusers/consistency_models''' ,						subfolder='''diffusers_cd_imagenet64_l2''')
									A__		 =					CMStochasticIterativeScheduler(
									    num_train_timesteps=4_0 ,						sigma_min=0.0_0_2 ,						sigma_max=8_0.0 ,						)
									A__		 =					ConsistencyModelPipeline(unet=__a ,						scheduler=__a)
									pipe.to(torch_device=__a)
									pipe.set_progress_bar_config(disable=__a)

									A__		 =					self.get_inputs()
									A__		 =					1
									A__		 =					None
									A__		 =					pipe(**__a).images
									assert image.shape == (1, 6_4, 6_4, 3)

									A__		 =					image[0, -3:, -3:, -1]

									A__		 =					np.array([0.0_3_4_0, 0.0_1_5_2, 0.0_0_6_3, 0.0_2_6_7, 0.0_2_2_1, 0.0_1_0_7, 0.0_4_1_6, 0.0_1_8_6, 0.0_2_1_7])

									assert np.abs(image_slice.flatten() - expected_slice).max() < 2e-2




					@require_torch_a
					def 		snake_case_		(				self):
									A__		 =					UNetaDModel.from_pretrained('''diffusers/consistency_models''' ,						subfolder='''diffusers_cd_imagenet64_l2''')
									A__		 =					CMStochasticIterativeScheduler(
									    num_train_timesteps=4_0 ,						sigma_min=0.0_0_2 ,						sigma_max=8_0.0 ,						)
									A__		 =					ConsistencyModelPipeline(unet=__a ,						scheduler=__a)
									pipe.to(torch_device=__a ,						torch_dtype=torch.floataa)
									pipe.set_progress_bar_config(disable=__a)

									A__		 =					self.get_inputs(get_fixed_latents=__a ,						device=__a)
									# Ensure usage of flash attention in torch 2.0
									with sdp_kernel(enable_flash=__a ,						enable_math=__a ,						enable_mem_efficient=__a):
													A__		 =					pipe(**__a).images
									assert image.shape == (1, 6_4, 6_4, 3)

									A__		 =					image[0, -3:, -3:, -1]

									A__		 =					np.array([0.1_8_7_5, 0.1_4_2_8, 0.1_2_8_9, 0.2_1_5_1, 0.2_0_9_2, 0.1_4_7_7, 0.1_8_7_7, 0.1_6_4_1, 0.1_3_5_3])

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




					@require_torch_a
					def 		snake_case_		(				self):
									A__		 =					UNetaDModel.from_pretrained('''diffusers/consistency_models''' ,						subfolder='''diffusers_cd_imagenet64_l2''')
									A__		 =					CMStochasticIterativeScheduler(
									    num_train_timesteps=4_0 ,						sigma_min=0.0_0_2 ,						sigma_max=8_0.0 ,						)
									A__		 =					ConsistencyModelPipeline(unet=__a ,						scheduler=__a)
									pipe.to(torch_device=__a ,						torch_dtype=torch.floataa)
									pipe.set_progress_bar_config(disable=__a)

									A__		 =					self.get_inputs(get_fixed_latents=__a ,						device=__a)
									A__		 =					1
									A__		 =					None
									# Ensure usage of flash attention in torch 2.0
									with sdp_kernel(enable_flash=__a ,						enable_math=__a ,						enable_mem_efficient=__a):
													A__		 =					pipe(**__a).images
									assert image.shape == (1, 6_4, 6_4, 3)

									A__		 =					image[0, -3:, -3:, -1]

									A__		 =					np.array([0.1_6_6_3, 0.1_9_4_8, 0.2_2_7_5, 0.1_6_8_0, 0.1_2_0_4, 0.1_2_4_5, 0.1_8_5_8, 0.1_3_3_8, 0.2_0_9_5])

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





import numpy as np



def 		lowerCAmelCase__    (					UpperCamelCase_				:       np.array	)->  np.array:
    return 1 / (1 + np.exp(-vector	))



def 		lowerCAmelCase__    (					UpperCamelCase_				:       np.array	)->  np.array:
    return vector * sigmoid(1.702 * vector	)


if __name__ == "__main__":
   import doctest

   doctest.testmod()
