
"""simple docstring"""




import random
import unittest

import numpy as np

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionImgaImgPipeline,
    PNDMScheduler,
)
from diffusers.utils import floats_tensor
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
    import onnxruntime as ort







class   _lowercase						(       _lowercase	,   unittest.TestCase				):


     '''simple docstring'''





     _A								=							'''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline'''



     def  lowerCAmelCase__       (      self ,			__UpperCamelCase=0  )->					Dict:
          UpperCAmelCase__							: Dict 							=						floats_tensor((1, 3, 1_28, 1_28) ,			rng=random.Random(A_  )  )
          UpperCAmelCase__							: List[str] 							=						np.random.RandomState(A_  )
          UpperCAmelCase__							: Any 							=						{
              "prompt": "A painting of a squirrel eating a burger",
              "image": image,
              "generator": generator,
              "num_inference_steps": 3,
              "strength": 0.75,
              "guidance_scale": 7.5,
              "output_type": "numpy",
          }
          return inputs



     def  lowerCAmelCase__       (      self  )->					Optional[int]:
          UpperCAmelCase__							: Optional[Any] 							=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,			provider="CPUExecutionProvider"  )
          pipe.set_progress_bar_config(disable=A_  )

          UpperCAmelCase__							: List[Any] 							=						self.get_dummy_inputs()
          UpperCAmelCase__							: List[Any] 							=						pipe(**A_  ).images
          UpperCAmelCase__							: int 							=						image[0, -3:, -3:, -1].flatten()

          assert image.shape == (1, 1_28, 1_28, 3)
          UpperCAmelCase__							: Union[str, Any] 							=						np.array([0.6_9643, 0.5_8484, 0.5_0314, 0.5_8760, 0.5_5368, 0.5_9643, 0.5_1529, 0.4_1217, 0.4_9087]  )
          assert np.abs(image_slice - expected_slice  ).max() < 1E-1



     def  lowerCAmelCase__       (      self  )->					Union[str, Any]:
          UpperCAmelCase__							: List[str] 							=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,			provider="CPUExecutionProvider"  )
          UpperCAmelCase__							: Optional[int] 							=						PNDMScheduler.from_config(pipe.scheduler.config ,			skip_prk_steps=A_  )
          pipe.set_progress_bar_config(disable=A_  )

          UpperCAmelCase__							: Union[str, Any] 							=						self.get_dummy_inputs()
          UpperCAmelCase__							: List[Any] 							=						pipe(**A_  ).images
          UpperCAmelCase__							: List[Any] 							=						image[0, -3:, -3:, -1]

          assert image.shape == (1, 1_28, 1_28, 3)
          UpperCAmelCase__							: Optional[Any] 							=						np.array([0.6_1737, 0.5_4642, 0.5_3183, 0.5_4465, 0.5_2742, 0.6_0525, 0.4_9969, 0.4_0655, 0.4_8154]  )

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



     def  lowerCAmelCase__       (      self  )->					Dict:
          UpperCAmelCase__							: str 							=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,			provider="CPUExecutionProvider"  )
          UpperCAmelCase__							: str 							=						LMSDiscreteScheduler.from_config(pipe.scheduler.config  )
          pipe.set_progress_bar_config(disable=A_  )

          # warmup pass to apply optimizations
          UpperCAmelCase__							: Dict 							=						pipe(**self.get_dummy_inputs()  )

          UpperCAmelCase__							: str 							=						self.get_dummy_inputs()
          UpperCAmelCase__							: Dict 							=						pipe(**A_  ).images
          UpperCAmelCase__							: int 							=						image[0, -3:, -3:, -1]

          assert image.shape == (1, 1_28, 1_28, 3)
          UpperCAmelCase__							: str 							=						np.array([0.5_2761, 0.5_9977, 0.4_9033, 0.4_9619, 0.5_4282, 0.5_0311, 0.4_7600, 0.4_0918, 0.4_5203]  )

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



     def  lowerCAmelCase__       (      self  )->					Optional[int]:
          UpperCAmelCase__							: int 							=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,			provider="CPUExecutionProvider"  )
          UpperCAmelCase__							: Union[str, Any] 							=						EulerDiscreteScheduler.from_config(pipe.scheduler.config  )
          pipe.set_progress_bar_config(disable=A_  )

          UpperCAmelCase__							: Any 							=						self.get_dummy_inputs()
          UpperCAmelCase__							: Union[str, Any] 							=						pipe(**A_  ).images
          UpperCAmelCase__							: str 							=						image[0, -3:, -3:, -1]

          assert image.shape == (1, 1_28, 1_28, 3)
          UpperCAmelCase__							: Optional[int] 							=						np.array([0.5_2911, 0.6_0004, 0.4_9229, 0.4_9805, 0.5_4502, 0.5_0680, 0.4_7777, 0.4_1028, 0.4_5304]  )

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



     def  lowerCAmelCase__       (      self  )->					Optional[int]:
          UpperCAmelCase__							: List[str] 							=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,			provider="CPUExecutionProvider"  )
          UpperCAmelCase__							: Union[str, Any] 							=						EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config  )
          pipe.set_progress_bar_config(disable=A_  )

          UpperCAmelCase__							: int 							=						self.get_dummy_inputs()
          UpperCAmelCase__							: int 							=						pipe(**A_  ).images
          UpperCAmelCase__							: Tuple 							=						image[0, -3:, -3:, -1]

          assert image.shape == (1, 1_28, 1_28, 3)
          UpperCAmelCase__							: str 							=						np.array([0.5_2911, 0.6_0004, 0.4_9229, 0.4_9805, 0.5_4502, 0.5_0680, 0.4_7777, 0.4_1028, 0.4_5304]  )

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



     def  lowerCAmelCase__       (      self  )->					Optional[Any]:
          UpperCAmelCase__							: Dict 							=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint ,			provider="CPUExecutionProvider"  )
          UpperCAmelCase__							: Any 							=						DPMSolverMultistepScheduler.from_config(pipe.scheduler.config  )
          pipe.set_progress_bar_config(disable=A_  )

          UpperCAmelCase__							: Dict 							=						self.get_dummy_inputs()
          UpperCAmelCase__							: Dict 							=						pipe(**A_  ).images
          UpperCAmelCase__							: Any 							=						image[0, -3:, -3:, -1]

          assert image.shape == (1, 1_28, 1_28, 3)
          UpperCAmelCase__							: str 							=						np.array([0.6_5331, 0.5_8277, 0.4_8204, 0.5_6059, 0.5_3665, 0.5_6235, 0.5_0969, 0.4_0009, 0.4_6552]  )

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







@nightly
@require_onnxruntime
@require_torch_gpu
class   _lowercase						(       unittest.TestCase				):


     '''simple docstring'''





     @property
     def  lowerCAmelCase__       (      self  )->					Union[str, Any]:
          return (
              "CUDAExecutionProvider",
              {
                  "gpu_mem_limit": "15000000000",  # 15GB
                  "arena_extend_strategy": "kSameAsRequested",
              },
          )



     @property
     def  lowerCAmelCase__       (      self  )->					str:
          UpperCAmelCase__							: List[Any] 							=						ort.SessionOptions()
          UpperCAmelCase__							: int 							=						False
          return options



     def  lowerCAmelCase__       (      self  )->					Tuple:
          UpperCAmelCase__							: Any 							=						load_image(
              "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
              "/img2img/sketch-mountains-input.jpg"  )
          UpperCAmelCase__							: List[Any] 							=						init_image.resize((7_68, 5_12)  )
          # using the PNDM scheduler by default
          UpperCAmelCase__							: int 							=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(
              "CompVis/stable-diffusion-v1-4" ,			revision="onnx" ,			safety_checker=A_ ,			feature_extractor=A_ ,			provider=self.gpu_provider ,			sess_options=self.gpu_options ,			)
          pipe.set_progress_bar_config(disable=A_  )

          UpperCAmelCase__							: Union[str, Any] 							=						"A fantasy landscape, trending on artstation"

          UpperCAmelCase__							: Any 							=						np.random.RandomState(0  )
          UpperCAmelCase__							: Any 							=						pipe(
              prompt=A_ ,			image=A_ ,			strength=0.75 ,			guidance_scale=7.5 ,			num_inference_steps=10 ,			generator=A_ ,			output_type="np" ,			)
          UpperCAmelCase__							: Optional[Any] 							=						output.images
          UpperCAmelCase__							: str 							=						images[0, 2_55:2_58, 3_83:3_86, -1]

          assert images.shape == (1, 5_12, 7_68, 3)
          UpperCAmelCase__							: Optional[int] 							=						np.array([0.4909, 0.5059, 0.5372, 0.4623, 0.4876, 0.5049, 0.4820, 0.4956, 0.5019]  )
          # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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



     def  lowerCAmelCase__       (      self  )->					Any:
          UpperCAmelCase__							: Union[str, Any] 							=						load_image(
              "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
              "/img2img/sketch-mountains-input.jpg"  )
          UpperCAmelCase__							: Tuple 							=						init_image.resize((7_68, 5_12)  )
          UpperCAmelCase__							: List[str] 							=						LMSDiscreteScheduler.from_pretrained(
              "runwayml/stable-diffusion-v1-5" ,			subfolder="scheduler" ,			revision="onnx"  )
          UpperCAmelCase__							: Optional[int] 							=						OnnxStableDiffusionImgaImgPipeline.from_pretrained(
              "runwayml/stable-diffusion-v1-5" ,			revision="onnx" ,			scheduler=A_ ,			safety_checker=A_ ,			feature_extractor=A_ ,			provider=self.gpu_provider ,			sess_options=self.gpu_options ,			)
          pipe.set_progress_bar_config(disable=A_  )

          UpperCAmelCase__							: Any 							=						"A fantasy landscape, trending on artstation"

          UpperCAmelCase__							: Union[str, Any] 							=						np.random.RandomState(0  )
          UpperCAmelCase__							: Union[str, Any] 							=						pipe(
              prompt=A_ ,			image=A_ ,			strength=0.75 ,			guidance_scale=7.5 ,			num_inference_steps=20 ,			generator=A_ ,			output_type="np" ,			)
          UpperCAmelCase__							: Optional[int] 							=						output.images
          UpperCAmelCase__							: Union[str, Any] 							=						images[0, 2_55:2_58, 3_83:3_86, -1]

          assert images.shape == (1, 5_12, 7_68, 3)
          UpperCAmelCase__							: str 							=						np.array([0.8043, 0.926, 0.9581, 0.8119, 0.8954, 0.913, 0.7209, 0.7463, 0.7431]  )
          # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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


"""simple docstring"""




from timeit import timeit



def 							a__ (				lowerCAmelCase	:       int		):






     '''simple docstring'''
     if number < 0:
          raise ValueError("the value of input must not be negative"		)
     UpperCAmelCase__							: Tuple 							=						0
     while number:
          number &= number - 1
          result += 1
     return result



def 							a__ (				lowerCAmelCase	:       int		):






     '''simple docstring'''
     if number < 0:
          raise ValueError("the value of input must not be negative"		)
     UpperCAmelCase__							: Union[str, Any] 							=						0
     while number:
          if number % 2 == 1:
               result += 1
          number >>= 1
     return result



def 							a__ (				):






     '''simple docstring'''

     def do_benchmark(lowerCAmelCase	:       int		) -> None:
          UpperCAmelCase__							: Dict 							=						"import __main__ as z"
          print(F"Benchmark when {number = }:"		)
          print(F"{get_set_bits_count_using_modulo_operator(lowerCAmelCase		) = }"		)
          UpperCAmelCase__							: Tuple 							=						timeit("z.get_set_bits_count_using_modulo_operator(25)"       ,    setup=lowerCAmelCase		)
          print(F"timeit() runs in {timing} seconds"		)
          print(F"{get_set_bits_count_using_brian_kernighans_algorithm(lowerCAmelCase		) = }"		)
          UpperCAmelCase__							: Any 							=						timeit(
              "z.get_set_bits_count_using_brian_kernighans_algorithm(25)"       ,    setup=lowerCAmelCase       ,    )
          print(F"timeit() runs in {timing} seconds"		)

     for number in (25, 37, 58, 0):
          do_benchmark(lowerCAmelCase		)
          print()


if __name__ == "__main__":
    import doctest

    doctest.testmod()
    benchmark()



