





import torch

from diffusers import KDPMaDiscreteScheduler
from diffusers.utils import torch_device

from .test_schedulers import SchedulerCommonTest
class        SCREAMING_SNAKE_CASE     (UpperCAmelCase   ):
   _UpperCamelCase					:	Any				      = (KDPMaDiscreteScheduler,)
   _UpperCamelCase					:	int				      = 10


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[int]    ,  **a    :       Optional[Any] )->     Union[str, Any]:





     """simple docstring"""







     lowercase__			    =						{
         'num_train_timesteps': 1_100,
         'beta_start': 0.0001,
         'beta_end': 0.02,
         'beta_schedule': 'linear',
     }

     config.update(**a )
     return config


   def  SCREAMING_SNAKE_CASE_							(					self    :       List[Any] )->     Tuple:





     """simple docstring"""







     for timesteps in [10, 50, 100, 1_000]:
       self.check_over_configs(num_train_timesteps=a )


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





     """simple docstring"""







     for beta_start, beta_end in zip([0.00001, 0.0001, 0.001]    ,  [0.0002, 0.002, 0.02] ):
       self.check_over_configs(beta_start=a    ,  beta_end=a )


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[int] )->     Dict:





     """simple docstring"""







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


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





     """simple docstring"""







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


   def  SCREAMING_SNAKE_CASE_							(					self    :       List[Any] )->     Tuple:





     """simple docstring"""







     lowercase__			    =						self.scheduler_classes[0]
     lowercase__			    =						self.get_scheduler_config(prediction_type='v_prediction' )
     lowercase__			    =						scheduler_class(**a )

     scheduler.set_timesteps(self.num_inference_steps )

     lowercase__			    =						self.dummy_model()
     lowercase__			    =						self.dummy_sample_deter * scheduler.init_noise_sigma
     lowercase__			    =						sample.to(a )

     for i, t in enumerate(scheduler.timesteps ):
       lowercase__			    =						scheduler.scale_model_input(a    ,  a )

       lowercase__			    =						model(a    ,  a )

       lowercase__			    =						scheduler.step(a    ,  a    ,  a )
       lowercase__			    =						output.prev_sample

     lowercase__			    =						torch.sum(torch.abs(a ) )
     lowercase__			    =						torch.mean(torch.abs(a ) )

     if torch_device in ["cpu", "mps"]:
       assert abs(result_sum.item() - 4.6_9_3_4E-0_7 ) < 1E-2
       assert abs(result_mean.item() - 6.1_1_1_2E-1_0 ) < 1E-3
     else:
       # CUDA
       assert abs(result_sum.item() - 4.6_9_3_4_2_8_6_5_0_1_7_0_9_7_2E-0_7 ) < 1E-2
       assert abs(result_mean.item() - 0.0002 ) < 1E-3


   def  SCREAMING_SNAKE_CASE_							(					self    :       Optional[int] )->     List[Any]:





     """simple docstring"""







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

     scheduler.set_timesteps(self.num_inference_steps )

     lowercase__			    =						self.dummy_model()
     lowercase__			    =						self.dummy_sample_deter * scheduler.init_noise_sigma
     lowercase__			    =						sample.to(a )

     for i, t in enumerate(scheduler.timesteps ):
       lowercase__			    =						scheduler.scale_model_input(a    ,  a )

       lowercase__			    =						model(a    ,  a )

       lowercase__			    =						scheduler.step(a    ,  a    ,  a )
       lowercase__			    =						output.prev_sample

     lowercase__			    =						torch.sum(torch.abs(a ) )
     lowercase__			    =						torch.mean(torch.abs(a ) )

     if torch_device in ["cpu", "mps"]:
       assert abs(result_sum.item() - 20.4125 ) < 1E-2
       assert abs(result_mean.item() - 0.0266 ) < 1E-3
     else:
       # CUDA
       assert abs(result_sum.item() - 20.4125 ) < 1E-2
       assert abs(result_mean.item() - 0.0266 ) < 1E-3


   def  SCREAMING_SNAKE_CASE_							(					self    :       List[str] )->     Optional[Any]:





     """simple docstring"""







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

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

     lowercase__			    =						self.dummy_model()
     lowercase__			    =						self.dummy_sample_deter.to(a ) * scheduler.init_noise_sigma

     for t in scheduler.timesteps:
       lowercase__			    =						scheduler.scale_model_input(a    ,  a )

       lowercase__			    =						model(a    ,  a )

       lowercase__			    =						scheduler.step(a    ,  a    ,  a )
       lowercase__			    =						output.prev_sample

     lowercase__			    =						torch.sum(torch.abs(a ) )
     lowercase__			    =						torch.mean(torch.abs(a ) )

     if str(a ).startswith('cpu' ):
       # The following sum varies between 148 and 156 on mps. Why?
       assert abs(result_sum.item() - 20.4125 ) < 1E-2
       assert abs(result_mean.item() - 0.0266 ) < 1E-3
     else:
       # CUDA
       assert abs(result_sum.item() - 20.4125 ) < 1E-2
       assert abs(result_mean.item() - 0.0266 ) < 1E-3









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


lowercase_					     =	False
class        SCREAMING_SNAKE_CASE     (unittest.TestCase   ):
   pass






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


   def  SCREAMING_SNAKE_CASE_							(					self    :       str )->     Optional[int]:





     """simple docstring"""







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


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





     """simple docstring"""







     lowercase__			    =						VersatileDiffusionPipeline.from_pretrained('shi-labs/versatile-diffusion'    ,  torch_dtype=torch.floataa )
     pipe.to(a )
     pipe.set_progress_bar_config(disable=a )

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

     lowercase__			    =						torch.manual_seed(0 )
     lowercase__			    =						pipe.dual_guided(
         prompt='first prompt'    ,  image=a    ,  text_to_image_strength=0.75    ,  generator=a    ,  guidance_scale=7.5    ,  num_inference_steps=2    ,  output_type='numpy'    ,  ).images

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

     lowercase__			    =						generator.manual_seed(0 )
     lowercase__			    =						pipe.dual_guided(
         prompt='first prompt'    ,  image=a    ,  text_to_image_strength=0.75    ,  generator=a    ,  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  SCREAMING_SNAKE_CASE_							(					self    :       Tuple )->     List[str]:





     """simple docstring"""







     lowercase__			    =						VersatileDiffusionPipeline.from_pretrained('shi-labs/versatile-diffusion'    ,  torch_dtype=torch.floataa )
     pipe.to(a )
     pipe.set_progress_bar_config(disable=a )

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

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

     assert image.shape == (1, 512, 512, 3)
     lowercase__			    =						np.array([0.1448, 0.1619, 0.1741, 0.1086, 0.1147, 0.1128, 0.1199, 0.1165, 0.1001] )

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

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

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

     assert image.shape == (1, 512, 512, 3)
     lowercase__			    =						np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778] )

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

     lowercase__			    =						pipe.image_variation(a    ,  generator=a    ,  output_type='numpy' ).images

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

     assert image.shape == (1, 512, 512, 3)
     lowercase__			    =						np.array([0.3076, 0.3123, 0.3284, 0.3782, 0.3770, 0.3894, 0.4297, 0.4331, 0.4456] )

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


