





'''simple docstring'''

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 (						_lowercase			,       unittest.TestCase  ):
		UpperCAmelCase					:	str 			=		ConsistencyModelPipeline
		UpperCAmelCase					:	int 			=		UNCONDITIONAL_IMAGE_GENERATION_PARAMS
		UpperCAmelCase					:	Optional[Any] 			=		UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS

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




		@property
		def 				UpperCAmelCase__   (self      :	int				)					-> Dict:
						lowercase         = UNetaDModel.from_pretrained(
						    "diffusers/consistency-models-test"							,			subfolder="test_unet"							,			)
						return unet




		@property
		def 				UpperCAmelCase__   (self      :	List[str]				)					-> Optional[int]:
						lowercase         = UNetaDModel.from_pretrained(
						    "diffusers/consistency-models-test"							,			subfolder="test_unet_class_cond"							,			)
						return unet




		def 				UpperCAmelCase__   (self      :	Optional[Any]							,			A__      :	Union[str, Any]=False				)					-> Optional[Any]:







						if class_cond:
										lowercase         = self.dummy_cond_unet
						else:
										lowercase         = self.dummy_uncond_unet

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

						lowercase         = {
						    'unet': unet,
						    'scheduler': scheduler,
						}

						return components




		def 				UpperCAmelCase__   (self      :	int							,			A__      :	Optional[int]							,			A__      :	Any=0				)					-> Dict:







						if str(A__				).startswith("mps"				):
										lowercase         = torch.manual_seed(A__				)
						else:
										lowercase         = torch.Generator(device=A__				).manual_seed(A__				)

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

						return inputs




		def 				UpperCAmelCase__   (self      :	Optional[Any]				)					-> Optional[Any]:
						lowercase         = 'cpu'  # ensure determinism for the device-dependent torch.Generator
						lowercase         = self.get_dummy_components()
						lowercase         = ConsistencyModelPipeline(**A__				)
						lowercase         = pipe.to(A__				)
						pipe.set_progress_bar_config(disable=A__				)

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

						lowercase         = image[0, -3:, -3:, -1]
						lowercase         = 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 				UpperCAmelCase__   (self      :	List[str]				)					-> List[str]:
						lowercase         = 'cpu'  # ensure determinism for the device-dependent torch.Generator
						lowercase         = self.get_dummy_components(class_cond=A__				)
						lowercase         = ConsistencyModelPipeline(**A__				)
						lowercase         = pipe.to(A__				)
						pipe.set_progress_bar_config(disable=A__				)

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

						lowercase         = image[0, -3:, -3:, -1]
						lowercase         = 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 				UpperCAmelCase__   (self      :	Any				)					-> List[Any]:
						lowercase         = 'cpu'  # ensure determinism for the device-dependent torch.Generator
						lowercase         = self.get_dummy_components()
						lowercase         = ConsistencyModelPipeline(**A__				)
						lowercase         = pipe.to(A__				)
						pipe.set_progress_bar_config(disable=A__				)

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

						lowercase         = image[0, -3:, -3:, -1]
						lowercase         = 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 				UpperCAmelCase__   (self      :	Optional[Any]				)					-> List[str]:
						lowercase         = 'cpu'  # ensure determinism for the device-dependent torch.Generator
						lowercase         = self.get_dummy_components(class_cond=A__				)
						lowercase         = ConsistencyModelPipeline(**A__				)
						lowercase         = pipe.to(A__				)
						pipe.set_progress_bar_config(disable=A__				)

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

						lowercase         = image[0, -3:, -3:, -1]
						lowercase         = 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 				UpperCAmelCase__   (self      :	Optional[Any]				)					-> Union[str, Any]:
						super().tearDown()
						gc.collect()
						torch.cuda.empty_cache()




		def 				UpperCAmelCase__   (self      :	Optional[Any]							,			A__      :	Tuple=0							,			A__      :	Optional[Any]=False							,			A__      :	Optional[Any]="cpu"							,			A__      :	Union[str, Any]=torch.floataa							,			A__      :	Dict=(1, 3, 6_4, 6_4)				)					-> Tuple:
						lowercase         = torch.manual_seed(A__				)

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

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

						return inputs




		def 				UpperCAmelCase__   (self      :	str							,			A__      :	Tuple=0							,			A__      :	Tuple="cpu"							,			A__      :	Tuple=torch.floataa							,			A__      :	str=(1, 3, 6_4, 6_4)				)					-> Union[str, Any]:







						if type(A__				) == str:
										lowercase         = torch.device(A__				)
						lowercase         = torch.Generator(device=A__				).manual_seed(A__				)
						lowercase         = randn_tensor(A__							,			generator=A__							,			device=A__							,			dtype=A__				)
						return latents




		def 				UpperCAmelCase__   (self      :	str				)					-> Optional[int]:
						lowercase         = UNetaDModel.from_pretrained("diffusers/consistency_models"							,			subfolder="diffusers_cd_imagenet64_l2"				)
						lowercase         = CMStochasticIterativeScheduler(
						    num_train_timesteps=4_0							,			sigma_min=0.0_0_2							,			sigma_max=8_0.0							,			)
						lowercase         = ConsistencyModelPipeline(unet=A__							,			scheduler=A__				)
						pipe.to(torch_device=A__				)
						pipe.set_progress_bar_config(disable=A__				)

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

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

						lowercase         = 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 				UpperCAmelCase__   (self      :	str				)					-> Tuple:
						lowercase         = UNetaDModel.from_pretrained("diffusers/consistency_models"							,			subfolder="diffusers_cd_imagenet64_l2"				)
						lowercase         = CMStochasticIterativeScheduler(
						    num_train_timesteps=4_0							,			sigma_min=0.0_0_2							,			sigma_max=8_0.0							,			)
						lowercase         = ConsistencyModelPipeline(unet=A__							,			scheduler=A__				)
						pipe.to(torch_device=A__				)
						pipe.set_progress_bar_config(disable=A__				)

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

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

						lowercase         = 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 				UpperCAmelCase__   (self      :	List[str]				)					-> Dict:
						lowercase         = UNetaDModel.from_pretrained("diffusers/consistency_models"							,			subfolder="diffusers_cd_imagenet64_l2"				)
						lowercase         = CMStochasticIterativeScheduler(
						    num_train_timesteps=4_0							,			sigma_min=0.0_0_2							,			sigma_max=8_0.0							,			)
						lowercase         = ConsistencyModelPipeline(unet=A__							,			scheduler=A__				)
						pipe.to(torch_device=A__							,			torch_dtype=torch.floataa				)
						pipe.set_progress_bar_config(disable=A__				)

						lowercase         = 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__				):
										lowercase         = pipe(**A__				).images
						assert image.shape == (1, 6_4, 6_4, 3)

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

						lowercase         = 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 				UpperCAmelCase__   (self      :	Optional[int]				)					-> Tuple:
						lowercase         = UNetaDModel.from_pretrained("diffusers/consistency_models"							,			subfolder="diffusers_cd_imagenet64_l2"				)
						lowercase         = CMStochasticIterativeScheduler(
						    num_train_timesteps=4_0							,			sigma_min=0.0_0_2							,			sigma_max=8_0.0							,			)
						lowercase         = ConsistencyModelPipeline(unet=A__							,			scheduler=A__				)
						pipe.to(torch_device=A__							,			torch_dtype=torch.floataa				)
						pipe.set_progress_bar_config(disable=A__				)

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

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

						lowercase         = 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











'''simple docstring'''

# Algorithm for the pigeonhole sorting









def 							UpperCAmelCase_    (	lowerCAmelCase_							):

				"""simple docstring"""






				lowercase         = min(lowerCAmelCase_							)  # min() finds the minimum value
				lowercase         = max(lowerCAmelCase_							)  # max() finds the maximum value

				lowercase         = max_val - min_val + 1  # size is difference of max and min values plus one

				# list of pigeonholes of size equal to the variable size
				lowercase         = [0] * size

				# Populate the pigeonholes.
				for x in a:
								assert isinstance(lowerCAmelCase_		,							lowerCAmelCase_							), "integers only please"
								holes[x - min_val] += 1

				# Putting the elements back into the array in an order.
				lowercase         = 0
				for count in range(lowerCAmelCase_							):
								while holes[count] > 0:
												holes[count] -= 1
												lowercase         = count + min_val
												i += 1







def 							UpperCAmelCase_    (	):

				"""simple docstring"""






				lowercase         = [8, 3, 2, 7, 4, 6, 8]
				pigeonhole_sort(lowerCAmelCase_							)
				print("Sorted order is:"		,							" ".join(lowerCAmelCase_							)							)


if __name__ == "__main__":
			main()




