
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 				SCREAMING_SNAKE_CASE__			(							SCREAMING_SNAKE_CASE_      ,						unittest.TestCase			):

							"""simple docstring"""






							_snake_case   						=     ConsistencyModelPipeline
							_snake_case   						=     UNCONDITIONAL_IMAGE_GENERATION_PARAMS
							_snake_case   						=     UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS

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



							@property
							def 			A__						(     self	)->      Dict:





													'''simple docstring'''






													__UpperCamelCase        =	UNetaDModel.from_pretrained(
													    '''diffusers/consistency-models-test'''   ,		subfolder='''test_unet'''   ,		)
													return unet



							@property
							def 			A__						(     self	)->      int:





													'''simple docstring'''






													__UpperCamelCase        =	UNetaDModel.from_pretrained(
													    '''diffusers/consistency-models-test'''   ,		subfolder='''test_unet_class_cond'''   ,		)
													return unet



							def 			A__						(     self   ,		SCREAMING_SNAKE_CASE_=False	)->      Any:





													'''simple docstring'''






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

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

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

													return components



							def 			A__						(     self   ,		SCREAMING_SNAKE_CASE_   ,		SCREAMING_SNAKE_CASE_=0	)->      str:





													'''simple docstring'''






													if str(__UpperCAmelCase	).startswith('''mps'''	):
																			__UpperCamelCase        =	torch.manual_seed(__UpperCAmelCase	)
													else:
																			__UpperCamelCase        =	torch.Generator(device=__UpperCAmelCase	).manual_seed(__UpperCAmelCase	)

													__UpperCamelCase        =	{
													    'batch_size': 1,
													    'num_inference_steps': None,
													    'timesteps': [22, 0],
													    'generator': generator,
													    'output_type': 'np',
													}

													return inputs



							def 			A__						(     self	)->      Union[str, Any]:





													'''simple docstring'''






													__UpperCamelCase        =	'cpu'  # ensure determinism for the device-dependent torch.Generator
													__UpperCamelCase        =	self.get_dummy_components()
													__UpperCamelCase        =	ConsistencyModelPipeline(**__UpperCAmelCase	)
													__UpperCamelCase        =	pipe.to(__UpperCAmelCase	)
													pipe.set_progress_bar_config(disable=__UpperCAmelCase	)

													__UpperCamelCase        =	self.get_dummy_inputs(__UpperCAmelCase	)
													__UpperCamelCase        =	pipe(**__UpperCAmelCase	).images
													assert image.shape == (1, 32, 32, 3)

													__UpperCamelCase        =	image[0, -3:, -3:, -1]
													__UpperCamelCase        =	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 			A__						(     self	)->      List[Any]:





													'''simple docstring'''






													__UpperCamelCase        =	'cpu'  # ensure determinism for the device-dependent torch.Generator
													__UpperCamelCase        =	self.get_dummy_components(class_cond=__UpperCAmelCase	)
													__UpperCamelCase        =	ConsistencyModelPipeline(**__UpperCAmelCase	)
													__UpperCamelCase        =	pipe.to(__UpperCAmelCase	)
													pipe.set_progress_bar_config(disable=__UpperCAmelCase	)

													__UpperCamelCase        =	self.get_dummy_inputs(__UpperCAmelCase	)
													__UpperCamelCase        =	0
													__UpperCamelCase        =	pipe(**__UpperCAmelCase	).images
													assert image.shape == (1, 32, 32, 3)

													__UpperCamelCase        =	image[0, -3:, -3:, -1]
													__UpperCamelCase        =	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 			A__						(     self	)->      Optional[Any]:





													'''simple docstring'''






													__UpperCamelCase        =	'cpu'  # ensure determinism for the device-dependent torch.Generator
													__UpperCamelCase        =	self.get_dummy_components()
													__UpperCamelCase        =	ConsistencyModelPipeline(**__UpperCAmelCase	)
													__UpperCamelCase        =	pipe.to(__UpperCAmelCase	)
													pipe.set_progress_bar_config(disable=__UpperCAmelCase	)

													__UpperCamelCase        =	self.get_dummy_inputs(__UpperCAmelCase	)
													__UpperCamelCase        =	1
													__UpperCamelCase        =	None
													__UpperCamelCase        =	pipe(**__UpperCAmelCase	).images
													assert image.shape == (1, 32, 32, 3)

													__UpperCamelCase        =	image[0, -3:, -3:, -1]
													__UpperCamelCase        =	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 			A__						(     self	)->      Optional[int]:





													'''simple docstring'''






													__UpperCamelCase        =	'cpu'  # ensure determinism for the device-dependent torch.Generator
													__UpperCamelCase        =	self.get_dummy_components(class_cond=__UpperCAmelCase	)
													__UpperCamelCase        =	ConsistencyModelPipeline(**__UpperCAmelCase	)
													__UpperCamelCase        =	pipe.to(__UpperCAmelCase	)
													pipe.set_progress_bar_config(disable=__UpperCAmelCase	)

													__UpperCamelCase        =	self.get_dummy_inputs(__UpperCAmelCase	)
													__UpperCamelCase        =	1
													__UpperCamelCase        =	None
													__UpperCamelCase        =	0
													__UpperCamelCase        =	pipe(**__UpperCAmelCase	).images
													assert image.shape == (1, 32, 32, 3)

													__UpperCamelCase        =	image[0, -3:, -3:, -1]
													__UpperCamelCase        =	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 				SCREAMING_SNAKE_CASE__			(							unittest.TestCase			):

							"""simple docstring"""






							def 			A__						(     self	)->      Union[str, Any]:





													'''simple docstring'''






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



							def 			A__						(     self   ,		SCREAMING_SNAKE_CASE_=0   ,		SCREAMING_SNAKE_CASE_=False   ,		SCREAMING_SNAKE_CASE_="cpu"   ,		SCREAMING_SNAKE_CASE_=torch.floataa   ,		SCREAMING_SNAKE_CASE_=(1, 3, 64, 64)	)->      str:





													'''simple docstring'''






													__UpperCamelCase        =	torch.manual_seed(__UpperCAmelCase	)

													__UpperCamelCase        =	{
													    'num_inference_steps': None,
													    'timesteps': [22, 0],
													    'class_labels': 0,
													    'generator': generator,
													    'output_type': 'np',
													}

													if get_fixed_latents:
																			__UpperCamelCase        =	self.get_fixed_latents(seed=__UpperCAmelCase   ,		device=__UpperCAmelCase   ,		dtype=__UpperCAmelCase   ,		shape=__UpperCAmelCase	)
																			__UpperCamelCase        =	latents

													return inputs



							def 			A__						(     self   ,		SCREAMING_SNAKE_CASE_=0   ,		SCREAMING_SNAKE_CASE_="cpu"   ,		SCREAMING_SNAKE_CASE_=torch.floataa   ,		SCREAMING_SNAKE_CASE_=(1, 3, 64, 64)	)->      Dict:





													'''simple docstring'''






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



							def 			A__						(     self	)->      Optional[int]:





													'''simple docstring'''






													__UpperCamelCase        =	UNetaDModel.from_pretrained('''diffusers/consistency_models'''   ,		subfolder='''diffusers_cd_imagenet64_l2'''	)
													__UpperCamelCase        =	CMStochasticIterativeScheduler(
													    num_train_timesteps=40   ,		sigma_min=0.0_0_2   ,		sigma_max=8_0.0   ,		)
													__UpperCamelCase        =	ConsistencyModelPipeline(unet=__UpperCAmelCase   ,		scheduler=__UpperCAmelCase	)
													pipe.to(torch_device=__UpperCAmelCase	)
													pipe.set_progress_bar_config(disable=__UpperCAmelCase	)

													__UpperCamelCase        =	self.get_inputs()
													__UpperCamelCase        =	pipe(**__UpperCAmelCase	).images
													assert image.shape == (1, 64, 64, 3)

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

													__UpperCamelCase        =	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 			A__						(     self	)->      str:





													'''simple docstring'''






													__UpperCamelCase        =	UNetaDModel.from_pretrained('''diffusers/consistency_models'''   ,		subfolder='''diffusers_cd_imagenet64_l2'''	)
													__UpperCamelCase        =	CMStochasticIterativeScheduler(
													    num_train_timesteps=40   ,		sigma_min=0.0_0_2   ,		sigma_max=8_0.0   ,		)
													__UpperCamelCase        =	ConsistencyModelPipeline(unet=__UpperCAmelCase   ,		scheduler=__UpperCAmelCase	)
													pipe.to(torch_device=__UpperCAmelCase	)
													pipe.set_progress_bar_config(disable=__UpperCAmelCase	)

													__UpperCamelCase        =	self.get_inputs()
													__UpperCamelCase        =	1
													__UpperCamelCase        =	None
													__UpperCamelCase        =	pipe(**__UpperCAmelCase	).images
													assert image.shape == (1, 64, 64, 3)

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

													__UpperCamelCase        =	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 			A__						(     self	)->      List[Any]:





													'''simple docstring'''






													__UpperCamelCase        =	UNetaDModel.from_pretrained('''diffusers/consistency_models'''   ,		subfolder='''diffusers_cd_imagenet64_l2'''	)
													__UpperCamelCase        =	CMStochasticIterativeScheduler(
													    num_train_timesteps=40   ,		sigma_min=0.0_0_2   ,		sigma_max=8_0.0   ,		)
													__UpperCamelCase        =	ConsistencyModelPipeline(unet=__UpperCAmelCase   ,		scheduler=__UpperCAmelCase	)
													pipe.to(torch_device=__UpperCAmelCase   ,		torch_dtype=torch.floataa	)
													pipe.set_progress_bar_config(disable=__UpperCAmelCase	)

													__UpperCamelCase        =	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        =	pipe(**__UpperCAmelCase	).images
													assert image.shape == (1, 64, 64, 3)

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

													__UpperCamelCase        =	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 			A__						(     self	)->      int:





													'''simple docstring'''






													__UpperCamelCase        =	UNetaDModel.from_pretrained('''diffusers/consistency_models'''   ,		subfolder='''diffusers_cd_imagenet64_l2'''	)
													__UpperCamelCase        =	CMStochasticIterativeScheduler(
													    num_train_timesteps=40   ,		sigma_min=0.0_0_2   ,		sigma_max=8_0.0   ,		)
													__UpperCamelCase        =	ConsistencyModelPipeline(unet=__UpperCAmelCase   ,		scheduler=__UpperCAmelCase	)
													pipe.to(torch_device=__UpperCAmelCase   ,		torch_dtype=torch.floataa	)
													pipe.set_progress_bar_config(disable=__UpperCAmelCase	)

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

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

													__UpperCamelCase        =	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"""





import tempfile
import unittest

from transformers import AutoModelForSeqaSeqLM, AutoTokenizer
from transformers.testing_utils import (
    is_torch_available,
    require_optimum,
    require_torch,
    slow,
)


if is_torch_available():
  import torch






@require_torch
@require_optimum
@slow
class 					_lowerCAmelCase   (     unittest.TestCase       ):
       """simple docstring"""




       def      snake_case						(    self      ):



         '''simple docstring'''

         lowerCAmelCase__			:Optional[Any]											=							'hf-internal-testing/tiny-random-t5'
         lowerCAmelCase__			:List[Any]											=							AutoTokenizer.from_pretrained(__UpperCAmelCase      )
         lowerCAmelCase__			:str											=							AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase      )

         lowerCAmelCase__			:Any											=							tokenizer('This is me'    , return_tensors='pt'      )

         lowerCAmelCase__			:Dict											=							model.to_bettertransformer()

         self.assertTrue(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules()      )      )

         lowerCAmelCase__			:Optional[Any]											=							model.generate(**__UpperCAmelCase      )

         lowerCAmelCase__			:List[Any]											=							model.reverse_bettertransformer()

         self.assertFalse(any('BetterTransformer' in mod.__class__.__name__ for _, mod in model.named_modules()      )      )

         with tempfile.TemporaryDirectory() as tmpdirname:
           model.save_pretrained(__UpperCAmelCase      )

           lowerCAmelCase__			:Any											=							AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase      )

           self.assertFalse(
               any('BetterTransformer' in mod.__class__.__name__ for _, mod in model_reloaded.named_modules()      )      )

           lowerCAmelCase__			:Union[str, Any]											=							model_reloaded.generate(**__UpperCAmelCase      )
           self.assertTrue(torch.allclose(__UpperCAmelCase    , __UpperCAmelCase      )      )






       def      snake_case						(    self      ):



         '''simple docstring'''

         lowerCAmelCase__			:int											=							'hf-internal-testing/tiny-random-t5'
         lowerCAmelCase__			:Union[str, Any]											=							AutoModelForSeqaSeqLM.from_pretrained(__UpperCAmelCase      )

         lowerCAmelCase__			:str											=							model.to_bettertransformer()

         with tempfile.TemporaryDirectory() as tmpdirname:
           with self.assertRaises(__UpperCAmelCase      ):
             model.save_pretrained(__UpperCAmelCase      )

           lowerCAmelCase__			:Optional[int]											=							model.reverse_bettertransformer()
           model.save_pretrained(__UpperCAmelCase      )
