






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   lowerCamelCase				(_snake_case			,  unittest.TestCase      ):







		'''simple docstring'''



		_snake_case   :   Tuple							=  ConsistencyModelPipeline
		_snake_case   :   int							=  UNCONDITIONAL_IMAGE_GENERATION_PARAMS
		_snake_case   :   Tuple							=  UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS

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



		@property
		def  __UpperCAmelCase      (							self       )     ->							Tuple:
							UpperCAmelCase_   :				Optional[Any]						=						UNetaDModel.from_pretrained(
							    'diffusers/consistency-models-test'    ,		subfolder='test_unet'    ,		)
							return unet



		@property
		def  __UpperCAmelCase      (							self       )     ->							List[Any]:
							UpperCAmelCase_   :				Any						=						UNetaDModel.from_pretrained(
							    'diffusers/consistency-models-test'    ,		subfolder='test_unet_class_cond'    ,		)
							return unet



		def  __UpperCAmelCase      (							self    ,		_UpperCamelCase=False       )     ->							Dict:
							if class_cond:
												UpperCAmelCase_   :				int						=						self.dummy_cond_unet
							else:
												UpperCAmelCase_   :				Optional[int]						=						self.dummy_uncond_unet

							# Default to CM multistep sampler
							UpperCAmelCase_   :				Optional[Any]						=						CMStochasticIterativeScheduler(
							    num_train_timesteps=4_0    ,		sigma_min=0.0_02    ,		sigma_max=80.0    ,		)

							UpperCAmelCase_   :				int						=						{
							    'unet': unet,
							    'scheduler': scheduler,
							}

							return components



		def  __UpperCAmelCase      (							self    ,		_UpperCamelCase    ,		_UpperCamelCase=0       )     ->							str:
							if str(_UpperCamelCase       ).startswith('mps'       ):
												UpperCAmelCase_   :				Tuple						=						torch.manual_seed(_UpperCamelCase       )
							else:
												UpperCAmelCase_   :				List[Any]						=						torch.Generator(device=_UpperCamelCase       ).manual_seed(_UpperCamelCase       )

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

							return inputs



		def  __UpperCAmelCase      (							self       )     ->							Optional[Any]:
							UpperCAmelCase_   :				str						=						'cpu'  # ensure determinism for the device-dependent torch.Generator
							UpperCAmelCase_   :				int						=						self.get_dummy_components()
							UpperCAmelCase_   :				Any						=						ConsistencyModelPipeline(**_UpperCamelCase       )
							UpperCAmelCase_   :				Optional[int]						=						pipe.to(_UpperCamelCase       )
							pipe.set_progress_bar_config(disable=_UpperCamelCase       )

							UpperCAmelCase_   :				Dict						=						self.get_dummy_inputs(_UpperCamelCase       )
							UpperCAmelCase_   :				Optional[int]						=						pipe(**_UpperCamelCase       ).images
							assert image.shape == (1, 3_2, 3_2, 3)

							UpperCAmelCase_   :				int						=						image[0, -3:, -3:, -1]
							UpperCAmelCase_   :				str						=						np.array([0.35_72, 0.62_73, 0.40_31, 0.39_61, 0.43_21, 0.57_30, 0.52_66, 0.47_80, 0.50_04]       )

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



		def  __UpperCAmelCase      (							self       )     ->							Optional[int]:
							UpperCAmelCase_   :				int						=						'cpu'  # ensure determinism for the device-dependent torch.Generator
							UpperCAmelCase_   :				List[str]						=						self.get_dummy_components(class_cond=_UpperCamelCase       )
							UpperCAmelCase_   :				str						=						ConsistencyModelPipeline(**_UpperCamelCase       )
							UpperCAmelCase_   :				Union[str, Any]						=						pipe.to(_UpperCamelCase       )
							pipe.set_progress_bar_config(disable=_UpperCamelCase       )

							UpperCAmelCase_   :				Union[str, Any]						=						self.get_dummy_inputs(_UpperCamelCase       )
							UpperCAmelCase_   :				str						=						0
							UpperCAmelCase_   :				Dict						=						pipe(**_UpperCamelCase       ).images
							assert image.shape == (1, 3_2, 3_2, 3)

							UpperCAmelCase_   :				str						=						image[0, -3:, -3:, -1]
							UpperCAmelCase_   :				str						=						np.array([0.35_72, 0.62_73, 0.40_31, 0.39_61, 0.43_21, 0.57_30, 0.52_66, 0.47_80, 0.50_04]       )

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



		def  __UpperCAmelCase      (							self       )     ->							Optional[Any]:
							UpperCAmelCase_   :				Union[str, Any]						=						'cpu'  # ensure determinism for the device-dependent torch.Generator
							UpperCAmelCase_   :				str						=						self.get_dummy_components()
							UpperCAmelCase_   :				List[str]						=						ConsistencyModelPipeline(**_UpperCamelCase       )
							UpperCAmelCase_   :				Union[str, Any]						=						pipe.to(_UpperCamelCase       )
							pipe.set_progress_bar_config(disable=_UpperCamelCase       )

							UpperCAmelCase_   :				Any						=						self.get_dummy_inputs(_UpperCamelCase       )
							UpperCAmelCase_   :				Optional[int]						=						1
							UpperCAmelCase_   :				Optional[int]						=						None
							UpperCAmelCase_   :				List[Any]						=						pipe(**_UpperCamelCase       ).images
							assert image.shape == (1, 3_2, 3_2, 3)

							UpperCAmelCase_   :				int						=						image[0, -3:, -3:, -1]
							UpperCAmelCase_   :				Any						=						np.array([0.50_04, 0.50_04, 0.49_94, 0.50_08, 0.49_76, 0.50_18, 0.49_90, 0.49_82, 0.49_87]       )

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



		def  __UpperCAmelCase      (							self       )     ->							Dict:
							UpperCAmelCase_   :				int						=						'cpu'  # ensure determinism for the device-dependent torch.Generator
							UpperCAmelCase_   :				Tuple						=						self.get_dummy_components(class_cond=_UpperCamelCase       )
							UpperCAmelCase_   :				Optional[int]						=						ConsistencyModelPipeline(**_UpperCamelCase       )
							UpperCAmelCase_   :				str						=						pipe.to(_UpperCamelCase       )
							pipe.set_progress_bar_config(disable=_UpperCamelCase       )

							UpperCAmelCase_   :				Optional[Any]						=						self.get_dummy_inputs(_UpperCamelCase       )
							UpperCAmelCase_   :				List[str]						=						1
							UpperCAmelCase_   :				List[Any]						=						None
							UpperCAmelCase_   :				Any						=						0
							UpperCAmelCase_   :				List[str]						=						pipe(**_UpperCamelCase       ).images
							assert image.shape == (1, 3_2, 3_2, 3)

							UpperCAmelCase_   :				List[Any]						=						image[0, -3:, -3:, -1]
							UpperCAmelCase_   :				str						=						np.array([0.50_04, 0.50_04, 0.49_94, 0.50_08, 0.49_76, 0.50_18, 0.49_90, 0.49_82, 0.49_87]       )

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





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







		'''simple docstring'''



		def  __UpperCAmelCase      (							self       )     ->							Dict:
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()



		def  __UpperCAmelCase      (							self    ,		_UpperCamelCase=0    ,		_UpperCamelCase=False    ,		_UpperCamelCase="cpu"    ,		_UpperCamelCase=torch.floataa    ,		_UpperCamelCase=(1, 3, 6_4, 6_4)       )     ->							List[Any]:
							UpperCAmelCase_   :				List[Any]						=						torch.manual_seed(_UpperCamelCase       )

							UpperCAmelCase_   :				Union[str, Any]						=						{
							    'num_inference_steps': None,
							    'timesteps': [2_2, 0],
							    'class_labels': 0,
							    'generator': generator,
							    'output_type': 'np',
							}

							if get_fixed_latents:
												UpperCAmelCase_   :				str						=						self.get_fixed_latents(seed=_UpperCamelCase    ,		device=_UpperCamelCase    ,		dtype=_UpperCamelCase    ,		shape=_UpperCamelCase       )
												UpperCAmelCase_   :				List[Any]						=						latents

							return inputs



		def  __UpperCAmelCase      (							self    ,		_UpperCamelCase=0    ,		_UpperCamelCase="cpu"    ,		_UpperCamelCase=torch.floataa    ,		_UpperCamelCase=(1, 3, 6_4, 6_4)       )     ->							Union[str, Any]:
							if type(_UpperCamelCase       ) == str:
												UpperCAmelCase_   :				Union[str, Any]						=						torch.device(_UpperCamelCase       )
							UpperCAmelCase_   :				Optional[Any]						=						torch.Generator(device=_UpperCamelCase       ).manual_seed(_UpperCamelCase       )
							UpperCAmelCase_   :				Optional[int]						=						randn_tensor(_UpperCamelCase    ,		generator=_UpperCamelCase    ,		device=_UpperCamelCase    ,		dtype=_UpperCamelCase       )
							return latents



		def  __UpperCAmelCase      (							self       )     ->							str:
							UpperCAmelCase_   :				Any						=						UNetaDModel.from_pretrained('diffusers/consistency_models'    ,		subfolder='diffusers_cd_imagenet64_l2'       )
							UpperCAmelCase_   :				List[str]						=						CMStochasticIterativeScheduler(
							    num_train_timesteps=4_0    ,		sigma_min=0.0_02    ,		sigma_max=80.0    ,		)
							UpperCAmelCase_   :				List[Any]						=						ConsistencyModelPipeline(unet=_UpperCamelCase    ,		scheduler=_UpperCamelCase       )
							pipe.to(torch_device=_UpperCamelCase       )
							pipe.set_progress_bar_config(disable=_UpperCamelCase       )

							UpperCAmelCase_   :				str						=						self.get_inputs()
							UpperCAmelCase_   :				Tuple						=						pipe(**_UpperCamelCase       ).images
							assert image.shape == (1, 6_4, 6_4, 3)

							UpperCAmelCase_   :				Optional[int]						=						image[0, -3:, -3:, -1]

							UpperCAmelCase_   :				Optional[int]						=						np.array([0.08_88, 0.08_81, 0.06_66, 0.04_79, 0.02_92, 0.01_95, 0.02_01, 0.01_63, 0.02_54]       )

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



		def  __UpperCAmelCase      (							self       )     ->							List[Any]:
							UpperCAmelCase_   :				Dict						=						UNetaDModel.from_pretrained('diffusers/consistency_models'    ,		subfolder='diffusers_cd_imagenet64_l2'       )
							UpperCAmelCase_   :				Any						=						CMStochasticIterativeScheduler(
							    num_train_timesteps=4_0    ,		sigma_min=0.0_02    ,		sigma_max=80.0    ,		)
							UpperCAmelCase_   :				Dict						=						ConsistencyModelPipeline(unet=_UpperCamelCase    ,		scheduler=_UpperCamelCase       )
							pipe.to(torch_device=_UpperCamelCase       )
							pipe.set_progress_bar_config(disable=_UpperCamelCase       )

							UpperCAmelCase_   :				List[str]						=						self.get_inputs()
							UpperCAmelCase_   :				Optional[Any]						=						1
							UpperCAmelCase_   :				Optional[int]						=						None
							UpperCAmelCase_   :				Any						=						pipe(**_UpperCamelCase       ).images
							assert image.shape == (1, 6_4, 6_4, 3)

							UpperCAmelCase_   :				str						=						image[0, -3:, -3:, -1]

							UpperCAmelCase_   :				Any						=						np.array([0.03_40, 0.01_52, 0.00_63, 0.02_67, 0.02_21, 0.01_07, 0.04_16, 0.01_86, 0.02_17]       )

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



		@require_torch_a
		def  __UpperCAmelCase      (							self       )     ->							int:
							UpperCAmelCase_   :				List[Any]						=						UNetaDModel.from_pretrained('diffusers/consistency_models'    ,		subfolder='diffusers_cd_imagenet64_l2'       )
							UpperCAmelCase_   :				Dict						=						CMStochasticIterativeScheduler(
							    num_train_timesteps=4_0    ,		sigma_min=0.0_02    ,		sigma_max=80.0    ,		)
							UpperCAmelCase_   :				Optional[int]						=						ConsistencyModelPipeline(unet=_UpperCamelCase    ,		scheduler=_UpperCamelCase       )
							pipe.to(torch_device=_UpperCamelCase    ,		torch_dtype=torch.floataa       )
							pipe.set_progress_bar_config(disable=_UpperCamelCase       )

							UpperCAmelCase_   :				Union[str, Any]						=						self.get_inputs(get_fixed_latents=_UpperCamelCase    ,		device=_UpperCamelCase       )
							# Ensure usage of flash attention in torch 2.0
							with sdp_kernel(enable_flash=_UpperCamelCase    ,		enable_math=_UpperCamelCase    ,		enable_mem_efficient=_UpperCamelCase       ):
												UpperCAmelCase_   :				Optional[Any]						=						pipe(**_UpperCamelCase       ).images
							assert image.shape == (1, 6_4, 6_4, 3)

							UpperCAmelCase_   :				Union[str, Any]						=						image[0, -3:, -3:, -1]

							UpperCAmelCase_   :				Optional[Any]						=						np.array([0.18_75, 0.14_28, 0.12_89, 0.21_51, 0.20_92, 0.14_77, 0.18_77, 0.16_41, 0.13_53]       )

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



		@require_torch_a
		def  __UpperCAmelCase      (							self       )     ->							List[Any]:
							UpperCAmelCase_   :				int						=						UNetaDModel.from_pretrained('diffusers/consistency_models'    ,		subfolder='diffusers_cd_imagenet64_l2'       )
							UpperCAmelCase_   :				Union[str, Any]						=						CMStochasticIterativeScheduler(
							    num_train_timesteps=4_0    ,		sigma_min=0.0_02    ,		sigma_max=80.0    ,		)
							UpperCAmelCase_   :				int						=						ConsistencyModelPipeline(unet=_UpperCamelCase    ,		scheduler=_UpperCamelCase       )
							pipe.to(torch_device=_UpperCamelCase    ,		torch_dtype=torch.floataa       )
							pipe.set_progress_bar_config(disable=_UpperCamelCase       )

							UpperCAmelCase_   :				Optional[int]						=						self.get_inputs(get_fixed_latents=_UpperCamelCase    ,		device=_UpperCamelCase       )
							UpperCAmelCase_   :				Tuple						=						1
							UpperCAmelCase_   :				Optional[Any]						=						None
							# Ensure usage of flash attention in torch 2.0
							with sdp_kernel(enable_flash=_UpperCamelCase    ,		enable_math=_UpperCamelCase    ,		enable_mem_efficient=_UpperCamelCase       ):
												UpperCAmelCase_   :				str						=						pipe(**_UpperCamelCase       ).images
							assert image.shape == (1, 6_4, 6_4, 3)

							UpperCAmelCase_   :				Union[str, Any]						=						image[0, -3:, -3:, -1]

							UpperCAmelCase_   :				Optional[Any]						=						np.array([0.16_63, 0.19_48, 0.22_75, 0.16_80, 0.12_04, 0.12_45, 0.18_58, 0.13_38, 0.20_95]       )

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














import random
import sys

import numpy as np
from matplotlib import pyplot as plt
from matplotlib.colors import ListedColormap

__UpperCAmelCase     							=						'Usage of script: script_name <size_of_canvas:int>'

__UpperCAmelCase     							=						[0] * 100 + [1] * 10
random.shuffle(choice)




def 					lowercase__				(					__snake_case   :							int  ):


					'''simple docstring'''


					UpperCAmelCase_   :				Any						=						[[False for i in range(__snake_case  )] for j in range(__snake_case  )]
					return canvas




def 					lowercase__				(					__snake_case   :							list[list[bool]]  ):


					'''simple docstring'''


					for i, row in enumerate(__snake_case  ):
										for j, _ in enumerate(__snake_case  ):
															UpperCAmelCase_   :				Tuple						=						bool(random.getrandbits(1  )  )




def 					lowercase__				(					__snake_case   :							list[list[bool]]  ):


					'''simple docstring'''


					UpperCAmelCase_   :				List[Any]						=						np.array(__snake_case  )
					UpperCAmelCase_   :				Any						=						np.array(create_canvas(current_canvas.shape[0]  )  )
					for r, row in enumerate(__snake_case  ):
										for c, pt in enumerate(__snake_case  ):
															UpperCAmelCase_   :				Optional[int]						=						__judge_point(
															    __snake_case					,	current_canvas[r - 1 : r + 2, c - 1 : c + 2]  )

					UpperCAmelCase_   :				List[Any]						=						next_gen_canvas
					del next_gen_canvas  # cleaning memory as we move on.
					UpperCAmelCase_   :				list[list[bool]]						=						current_canvas.tolist()
					return return_canvas




def 					lowercase__				(					__snake_case   :							bool					,	__snake_case   :							list[list[bool]]  ):


					'''simple docstring'''


					UpperCAmelCase_   :				Optional[int]						=						0
					UpperCAmelCase_   :				List[Any]						=						0
					# finding dead or alive neighbours count.
					for i in neighbours:
										for status in i:
															if status:
																				alive += 1
															else:
																				dead += 1

    # handling duplicate entry for focus pt.
					if pt:
										alive -= 1
					else:
										dead -= 1

					# running the rules of game here.
					UpperCAmelCase_   :				List[Any]						=						pt
					if pt:
										if alive < 2:
															UpperCAmelCase_   :				str						=						False
										elif alive == 2 or alive == 3:
															UpperCAmelCase_   :				int						=						True
										elif alive > 3:
															UpperCAmelCase_   :				List[Any]						=						False
					else:
										if alive == 3:
															UpperCAmelCase_   :				int						=						True

					return state


if __name__ == "__main__":
		if len(sys.argv) != 2:
				raise Exception(usage_doc)

		__UpperCAmelCase     							=						int(sys.argv[1])
		# main working structure of this module.
		__UpperCAmelCase     							=						create_canvas(canvas_size)
		seed(c)
		__UpperCAmelCase							,       __UpperCAmelCase     							=						plt.subplots()
		fig.show()
		__UpperCAmelCase     							=						ListedColormap(['w', 'k'])
		try:
				while True:
						__UpperCAmelCase     							=						run(c)
						ax.matshow(c, cmap=cmap)
						fig.canvas.draw()
						ax.cla()
		except KeyboardInterrupt:
				# do nothing.
				pass






