



"""simple docstring"""







import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


UpperCamelCase     =							False






class       UpperCamelCase__			(   unittest.TestCase      ):

			"""simple docstring"""


			pass






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

			"""simple docstring"""


			def   snake_case__	(      self		)      ->	Optional[Any]:
				super().tearDown()
				gc.collect()
				torch.cuda.empty_cache()


			def   snake_case__	(      self		)      ->	Tuple:
				A__											=					VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion"						,	torch_dtype=torch.floataa		)
				pipe.to(snake_case__		)
				pipe.set_progress_bar_config(disable=snake_case__		)

				A__											=					load_image(
				    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg"		)

				A__											=					torch.manual_seed(0		)
				A__											=					pipe.dual_guided(
				    prompt="first prompt"						,	image=snake_case__						,	text_to_image_strength=0.7_5						,	generator=snake_case__						,	guidance_scale=7.5						,	num_inference_steps=2						,	output_type="numpy"						,	).images

				with tempfile.TemporaryDirectory() as tmpdirname:
					pipe.save_pretrained(snake_case__		)
					A__											=					VersatileDiffusionPipeline.from_pretrained(snake_case__						,	torch_dtype=torch.floataa		)
				pipe.to(snake_case__		)
				pipe.set_progress_bar_config(disable=snake_case__		)

				A__											=					generator.manual_seed(0		)
				A__											=					pipe.dual_guided(
				    prompt="first prompt"						,	image=snake_case__						,	text_to_image_strength=0.7_5						,	generator=snake_case__						,	guidance_scale=7.5						,	num_inference_steps=2						,	output_type="numpy"						,	).images

				assert np.abs(image - new_image		).sum() < 1e-5, "Models don't have the same forward pass"







			def   snake_case__	(      self		)      ->	Dict:
				A__											=					VersatileDiffusionPipeline.from_pretrained("shi-labs/versatile-diffusion"						,	torch_dtype=torch.floataa		)
				pipe.to(snake_case__		)
				pipe.set_progress_bar_config(disable=snake_case__		)

				A__											=					"cyberpunk 2077"
				A__											=					load_image(
				    "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg"		)
				A__											=					torch.manual_seed(0		)
				A__											=					pipe.dual_guided(
				    prompt=snake_case__						,	image=snake_case__						,	text_to_image_strength=0.7_5						,	generator=snake_case__						,	guidance_scale=7.5						,	num_inference_steps=50						,	output_type="numpy"						,	).images

				A__											=					image[0, 253:256, 253:256, -1]

				assert image.shape == (1, 512, 512, 3)
				A__											=					np.array([0.1_4_4_8, 0.1_6_1_9, 0.1_7_4_1, 0.1_0_8_6, 0.1_1_4_7, 0.1_1_2_8, 0.1_1_9_9, 0.1_1_6_5, 0.1_0_0_1]		)

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

				A__											=					"A painting of a squirrel eating a burger "
				A__											=					torch.manual_seed(0		)
				A__											=					pipe.text_to_image(
				    prompt=snake_case__						,	generator=snake_case__						,	guidance_scale=7.5						,	num_inference_steps=50						,	output_type="numpy"		).images

				A__											=					image[0, 253:256, 253:256, -1]

				assert image.shape == (1, 512, 512, 3)
				A__											=					np.array([0.3_3_6_7, 0.3_1_6_9, 0.2_6_5_6, 0.3_8_7_0, 0.4_7_9_0, 0.3_7_9_6, 0.4_0_0_9, 0.4_8_7_8, 0.4_7_7_8]		)

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

				A__											=					pipe.image_variation(snake_case__						,	generator=snake_case__						,	output_type="numpy"		).images

				A__											=					image[0, 253:256, 253:256, -1]

				assert image.shape == (1, 512, 512, 3)
				A__											=					np.array([0.3_0_7_6, 0.3_1_2_3, 0.3_2_8_4, 0.3_7_8_2, 0.3_7_7_0, 0.3_8_9_4, 0.4_2_9_7, 0.4_3_3_1, 0.4_4_5_6]		)

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










import torch

from diffusers import KDPMaDiscreteScheduler
from diffusers.utils import torch_device

from .test_schedulers import SchedulerCommonTest



class    lowercase_		(SCREAMING_SNAKE_CASE__ ):
						lowerCAmelCase__			      =(KDPMaDiscreteScheduler,)
						lowerCAmelCase__			      =10



						def 	__a					(			self	:   Dict					,							**snake_case__	:   str  ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							{
								    'num_train_timesteps': 11_00,
								    'beta_start': 0.00_01,
								    'beta_end': 0.02,
								    'beta_schedule': 'linear',
								}

								config.update(**snake_case__  )
								return config



						def 	__a					(			self	:   str  ):

								"""simple docstring"""

								for timesteps in [10, 50, 1_00, 10_00]:
										self.check_over_configs(num_train_timesteps=snake_case__  )



						def 	__a					(			self	:   List[Any]  ):

								"""simple docstring"""

								for beta_start, beta_end in zip([0.0_00_01, 0.00_01, 0.0_01]					,							[0.00_02, 0.0_02, 0.02]  ):
										self.check_over_configs(beta_start=snake_case__					,							beta_end=snake_case__  )



						def 	__a					(			self	:   Optional[int]  ):

								"""simple docstring"""

								for schedule in ["linear", "scaled_linear"]:
										self.check_over_configs(beta_schedule=snake_case__  )



						def 	__a					(			self	:   Optional[Any]  ):

								"""simple docstring"""

								for prediction_type in ["epsilon", "v_prediction"]:
										self.check_over_configs(prediction_type=snake_case__  )



						def 	__a					(			self	:   Optional[Any]  ):

								"""simple docstring"""

								SCREAMING_SNAKE_CASE_					      =							self.scheduler_classes[0]
								SCREAMING_SNAKE_CASE_					      =							self.get_scheduler_config(prediction_type='v_prediction'  )
								SCREAMING_SNAKE_CASE_					      =							scheduler_class(**snake_case__  )

								scheduler.set_timesteps(self.num_inference_steps  )

								SCREAMING_SNAKE_CASE_					      =							self.dummy_model()
								SCREAMING_SNAKE_CASE_					      =							self.dummy_sample_deter * scheduler.init_noise_sigma
								SCREAMING_SNAKE_CASE_					      =							sample.to(snake_case__  )

								for i, t in enumerate(scheduler.timesteps  ):
										SCREAMING_SNAKE_CASE_					      =							scheduler.scale_model_input(snake_case__					,							snake_case__  )

										SCREAMING_SNAKE_CASE_					      =							model(snake_case__					,							snake_case__  )

										SCREAMING_SNAKE_CASE_					      =							scheduler.step(snake_case__					,							snake_case__					,							snake_case__  )
										SCREAMING_SNAKE_CASE_					      =							output.prev_sample

								SCREAMING_SNAKE_CASE_					      =							torch.sum(torch.abs(snake_case__  )  )
								SCREAMING_SNAKE_CASE_					      =							torch.mean(torch.abs(snake_case__  )  )

								if torch_device in ["cpu", "mps"]:
										assert abs(result_sum.item() - 4.69_34e-07  ) < 1e-2
										assert abs(result_mean.item() - 6.11_12e-10  ) < 1e-3
								else:
										# CUDA
										assert abs(result_sum.item() - 4.6_93_42_86_50_17_09_72e-07  ) < 1e-2
										assert abs(result_mean.item() - 0.00_02  ) < 1e-3



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

								"""simple docstring"""

								if torch_device == "mps":
										return
								SCREAMING_SNAKE_CASE_					      =							self.scheduler_classes[0]
								SCREAMING_SNAKE_CASE_					      =							self.get_scheduler_config()
								SCREAMING_SNAKE_CASE_					      =							scheduler_class(**snake_case__  )

								scheduler.set_timesteps(self.num_inference_steps  )

								SCREAMING_SNAKE_CASE_					      =							self.dummy_model()
								SCREAMING_SNAKE_CASE_					      =							self.dummy_sample_deter * scheduler.init_noise_sigma
								SCREAMING_SNAKE_CASE_					      =							sample.to(snake_case__  )

								for i, t in enumerate(scheduler.timesteps  ):
										SCREAMING_SNAKE_CASE_					      =							scheduler.scale_model_input(snake_case__					,							snake_case__  )

										SCREAMING_SNAKE_CASE_					      =							model(snake_case__					,							snake_case__  )

										SCREAMING_SNAKE_CASE_					      =							scheduler.step(snake_case__					,							snake_case__					,							snake_case__  )
										SCREAMING_SNAKE_CASE_					      =							output.prev_sample

								SCREAMING_SNAKE_CASE_					      =							torch.sum(torch.abs(snake_case__  )  )
								SCREAMING_SNAKE_CASE_					      =							torch.mean(torch.abs(snake_case__  )  )

								if torch_device in ["cpu", "mps"]:
										assert abs(result_sum.item() - 20.41_25  ) < 1e-2
										assert abs(result_mean.item() - 0.02_66  ) < 1e-3
								else:
										# CUDA
										assert abs(result_sum.item() - 20.41_25  ) < 1e-2
										assert abs(result_mean.item() - 0.02_66  ) < 1e-3






						def 	__a					(			self	:   Optional[int]  ):

								"""simple docstring"""

								if torch_device == "mps":
										return
								SCREAMING_SNAKE_CASE_					      =							self.scheduler_classes[0]
								SCREAMING_SNAKE_CASE_					      =							self.get_scheduler_config()
								SCREAMING_SNAKE_CASE_					      =							scheduler_class(**snake_case__  )

								scheduler.set_timesteps(self.num_inference_steps					,							device=snake_case__  )

								SCREAMING_SNAKE_CASE_					      =							self.dummy_model()
								SCREAMING_SNAKE_CASE_					      =							self.dummy_sample_deter.to(snake_case__  ) * scheduler.init_noise_sigma

								for t in scheduler.timesteps:
										SCREAMING_SNAKE_CASE_					      =							scheduler.scale_model_input(snake_case__					,							snake_case__  )

										SCREAMING_SNAKE_CASE_					      =							model(snake_case__					,							snake_case__  )

										SCREAMING_SNAKE_CASE_					      =							scheduler.step(snake_case__					,							snake_case__					,							snake_case__  )
										SCREAMING_SNAKE_CASE_					      =							output.prev_sample

								SCREAMING_SNAKE_CASE_					      =							torch.sum(torch.abs(snake_case__  )  )
								SCREAMING_SNAKE_CASE_					      =							torch.mean(torch.abs(snake_case__  )  )

								if str(snake_case__  ).startswith('cpu'  ):
										# The following sum varies between 148 and 156 on mps. Why?
										assert abs(result_sum.item() - 20.41_25  ) < 1e-2
										assert abs(result_mean.item() - 0.02_66  ) < 1e-3
								else:
										# CUDA
										assert abs(result_sum.item() - 20.41_25  ) < 1e-2
										assert abs(result_mean.item() - 0.02_66  ) < 1e-3