
'''simple docstring'''
import tempfile
import unittest

import numpy as np

from diffusers import (
    DDIMScheduler,
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionPipeline,
    PNDMScheduler,
)
from diffusers.utils.testing_utils import is_onnx_available, nightly, require_onnxruntime, require_torch_gpu

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
     import onnxruntime as ort







class  __A				( _SCREAMING_SNAKE_CASE    ,						unittest.TestCase			):
 lowerCamelCase				       ='''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline'''
 def 		lowercase_(   self			:    str				,   lowerCamelCase			:    str=0       ):



   """simple docstring"""





   __A		:     str												=		np.random.RandomState(lowerCamelCase       )
   __A		:     int												=		{
       """prompt""": """A painting of a squirrel eating a burger""",
       """generator""": generator,
       """num_inference_steps""": 2,
       """guidance_scale""": 7.5,
       """output_type""": """numpy""",
   }
   return inputs
 def 		lowercase_(   self			:    Tuple       ):



   """simple docstring"""





   __A		:     Optional[int]												=		OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint				,   provider="""CPUExecutionProvider"""       )
   pipe.set_progress_bar_config(disable=lowerCamelCase       )

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

   assert image.shape == (1, 1_28, 1_28, 3)
   __A		:     Union[str, Any]												=		np.array([0.65_072, 0.58_492, 0.48_219, 0.55_521, 0.53_180, 0.55_939, 0.50_697, 0.39_800, 0.46_455]       )

   assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-2
 def 		lowercase_(   self			:    Any       ):



   """simple docstring"""





   __A		:     List[Any]												=		OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint				,   provider="""CPUExecutionProvider"""       )
   __A		:     List[Any]												=		PNDMScheduler.from_config(pipe.scheduler.config				,   skip_prk_steps=lowerCamelCase       )
   pipe.set_progress_bar_config(disable=lowerCamelCase       )

   __A		:     Optional[Any]												=		self.get_dummy_inputs()
   __A		:     str												=		pipe(**lowerCamelCase       ).images
   __A		:     Optional[int]												=		image[0, -3:, -3:, -1]

   assert image.shape == (1, 1_28, 1_28, 3)
   __A		:     Optional[int]												=		np.array([0.65_863, 0.59_425, 0.49_326, 0.56_313, 0.53_875, 0.56_627, 0.51_065, 0.39_777, 0.46_330]       )

   assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-2
 def 		lowercase_(   self			:    Dict       ):



   """simple docstring"""





   __A		:     Dict												=		OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint				,   provider="""CPUExecutionProvider"""       )
   __A		:     List[str]												=		LMSDiscreteScheduler.from_config(pipe.scheduler.config       )
   pipe.set_progress_bar_config(disable=lowerCamelCase       )

   __A		:     List[str]												=		self.get_dummy_inputs()
   __A		:     Optional[int]												=		pipe(**lowerCamelCase       ).images
   __A		:     List[str]												=		image[0, -3:, -3:, -1]

   assert image.shape == (1, 1_28, 1_28, 3)
   __A		:     int												=		np.array([0.53_755, 0.60_786, 0.47_402, 0.49_488, 0.51_869, 0.49_819, 0.47_985, 0.38_957, 0.44_279]       )

   assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-2
 def 		lowercase_(   self			:    Any       ):



   """simple docstring"""





   __A		:     Optional[Any]												=		OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint				,   provider="""CPUExecutionProvider"""       )
   __A		:     List[str]												=		EulerDiscreteScheduler.from_config(pipe.scheduler.config       )
   pipe.set_progress_bar_config(disable=lowerCamelCase       )

   __A		:     int												=		self.get_dummy_inputs()
   __A		:     List[str]												=		pipe(**lowerCamelCase       ).images
   __A		:     List[Any]												=		image[0, -3:, -3:, -1]

   assert image.shape == (1, 1_28, 1_28, 3)
   __A		:     Optional[Any]												=		np.array([0.53_755, 0.60_786, 0.47_402, 0.49_488, 0.51_869, 0.49_819, 0.47_985, 0.38_957, 0.44_279]       )

   assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-2
 def 		lowercase_(   self			:    Optional[Any]       ):



   """simple docstring"""





   __A		:     Optional[int]												=		OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint				,   provider="""CPUExecutionProvider"""       )
   __A		:     int												=		EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config       )
   pipe.set_progress_bar_config(disable=lowerCamelCase       )

   __A		:     int												=		self.get_dummy_inputs()
   __A		:     Any												=		pipe(**lowerCamelCase       ).images
   __A		:     Optional[Any]												=		image[0, -3:, -3:, -1]

   assert image.shape == (1, 1_28, 1_28, 3)
   __A		:     Tuple												=		np.array([0.53_817, 0.60_812, 0.47_384, 0.49_530, 0.51_894, 0.49_814, 0.47_984, 0.38_958, 0.44_271]       )

   assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-2
 def 		lowercase_(   self			:    Any       ):



   """simple docstring"""





   __A		:     List[Any]												=		OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint				,   provider="""CPUExecutionProvider"""       )
   __A		:     str												=		DPMSolverMultistepScheduler.from_config(pipe.scheduler.config       )
   pipe.set_progress_bar_config(disable=lowerCamelCase       )

   __A		:     Tuple												=		self.get_dummy_inputs()
   __A		:     Tuple												=		pipe(**lowerCamelCase       ).images
   __A		:     Tuple												=		image[0, -3:, -3:, -1]

   assert image.shape == (1, 1_28, 1_28, 3)
   __A		:     Union[str, Any]												=		np.array([0.53_895, 0.60_808, 0.47_933, 0.49_608, 0.51_886, 0.49_950, 0.48_053, 0.38_957, 0.44_200]       )

   assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-2
 def 		lowercase_(   self			:    str       ):



   """simple docstring"""





   __A		:     Tuple												=		OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint				,   provider="""CPUExecutionProvider"""       )
   pipe.set_progress_bar_config(disable=lowerCamelCase       )

   __A		:     Union[str, Any]												=		self.get_dummy_inputs()
   __A		:     Optional[int]												=		3 * [inputs["""prompt"""]]

   # forward
   __A		:     List[str]												=		pipe(**lowerCamelCase       )
   __A		:     List[str]												=		output.images[0, -3:, -3:, -1]

   __A		:     List[Any]												=		self.get_dummy_inputs()
   __A		:     Optional[int]												=		3 * [inputs.pop("""prompt"""       )]

   __A		:     List[Any]												=		pipe.tokenizer(
       lowerCamelCase				,   padding="""max_length"""				,   max_length=pipe.tokenizer.model_max_length				,   truncation=lowerCamelCase				,   return_tensors="""np"""				,   )
   __A		:     Dict												=		text_inputs["""input_ids"""]

   __A		:     Optional[Any]												=		pipe.text_encoder(input_ids=text_inputs.astype(np.intaa       )       )[0]

   __A		:     int												=		prompt_embeds

   # forward
   __A		:     List[str]												=		pipe(**lowerCamelCase       )
   __A		:     List[Any]												=		output.images[0, -3:, -3:, -1]

   assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()       ).max() < 1e-4






 def 		lowercase_(   self			:    List[Any]       ):



   """simple docstring"""





   __A		:     str												=		OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint				,   provider="""CPUExecutionProvider"""       )
   pipe.set_progress_bar_config(disable=lowerCamelCase       )

   __A		:     Dict												=		self.get_dummy_inputs()
   __A		:     Tuple												=		3 * ["""this is a negative prompt"""]
   __A		:     Tuple												=		negative_prompt
   __A		:     Union[str, Any]												=		3 * [inputs["""prompt"""]]

   # forward
   __A		:     str												=		pipe(**lowerCamelCase       )
   __A		:     Optional[Any]												=		output.images[0, -3:, -3:, -1]

   __A		:     Dict												=		self.get_dummy_inputs()
   __A		:     str												=		3 * [inputs.pop("""prompt"""       )]

   __A		:     Optional[Any]												=		[]
   for p in [prompt, negative_prompt]:
     __A		:     Union[str, Any]												=		pipe.tokenizer(
         lowerCamelCase				,   padding="""max_length"""				,   max_length=pipe.tokenizer.model_max_length				,   truncation=lowerCamelCase				,   return_tensors="""np"""				,   )
     __A		:     List[str]												=		text_inputs["""input_ids"""]

     embeds.append(pipe.text_encoder(input_ids=text_inputs.astype(np.intaa       )       )[0]       )

   __A							,					__A		:     Any												=		embeds

   # forward
   __A		:     Union[str, Any]												=		pipe(**lowerCamelCase       )
   __A		:     Dict												=		output.images[0, -3:, -3:, -1]

   assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()       ).max() < 1e-4







@nightly
@require_onnxruntime
@require_torch_gpu
class  __A				( unittest.TestCase			):
 @property
 def 		lowercase_(   self			:    Optional[Any]       ):



   """simple docstring"""





   return (
       "CUDAExecutionProvider",
       {
           "gpu_mem_limit": "15000000000",  # 15GB
           "arena_extend_strategy": "kSameAsRequested",
       },
   )
 @property
 def 		lowercase_(   self			:    Dict       ):



   """simple docstring"""





   __A		:     List[Any]												=		ort.SessionOptions()
   __A		:     Union[str, Any]												=		False
   return options
 def 		lowercase_(   self			:    Any       ):



   """simple docstring"""





   __A		:     int												=		OnnxStableDiffusionPipeline.from_pretrained(
       """CompVis/stable-diffusion-v1-4"""				,   revision="""onnx"""				,   safety_checker=lowerCamelCase				,   feature_extractor=lowerCamelCase				,   provider=self.gpu_provider				,   sess_options=self.gpu_options				,   )
   sd_pipe.set_progress_bar_config(disable=lowerCamelCase       )

   __A		:     List[str]												=		"""A painting of a squirrel eating a burger"""
   np.random.seed(0       )
   __A		:     str												=		sd_pipe([prompt]				,   guidance_scale=6.0				,   num_inference_steps=10				,   output_type="""np"""       )
   __A		:     Dict												=		output.images

   __A		:     int												=		image[0, -3:, -3:, -1]

   assert image.shape == (1, 5_12, 5_12, 3)
   __A		:     str												=		np.array([0.0_452, 0.0_390, 0.0_087, 0.0_350, 0.0_617, 0.0_364, 0.0_544, 0.0_523, 0.0_720]       )

   assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-3
 def 		lowercase_(   self			:    List[Any]       ):



   """simple docstring"""





   __A		:     Union[str, Any]												=		DDIMScheduler.from_pretrained(
       """runwayml/stable-diffusion-v1-5"""				,   subfolder="""scheduler"""				,   revision="""onnx"""       )
   __A		:     List[str]												=		OnnxStableDiffusionPipeline.from_pretrained(
       """runwayml/stable-diffusion-v1-5"""				,   revision="""onnx"""				,   scheduler=lowerCamelCase				,   safety_checker=lowerCamelCase				,   feature_extractor=lowerCamelCase				,   provider=self.gpu_provider				,   sess_options=self.gpu_options				,   )
   sd_pipe.set_progress_bar_config(disable=lowerCamelCase       )

   __A		:     int												=		"""open neural network exchange"""
   __A		:     Optional[Any]												=		np.random.RandomState(0       )
   __A		:     List[str]												=		sd_pipe([prompt]				,   guidance_scale=7.5				,   num_inference_steps=10				,   generator=lowerCamelCase				,   output_type="""np"""       )
   __A		:     List[str]												=		output.images
   __A		:     Tuple												=		image[0, -3:, -3:, -1]

   assert image.shape == (1, 5_12, 5_12, 3)
   __A		:     List[str]												=		np.array([0.2_867, 0.1_974, 0.1_481, 0.7_294, 0.7_251, 0.6_667, 0.4_194, 0.5_642, 0.6_486]       )

   assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-3
 def 		lowercase_(   self			:    List[str]       ):



   """simple docstring"""





   __A		:     str												=		LMSDiscreteScheduler.from_pretrained(
       """runwayml/stable-diffusion-v1-5"""				,   subfolder="""scheduler"""				,   revision="""onnx"""       )
   __A		:     Dict												=		OnnxStableDiffusionPipeline.from_pretrained(
       """runwayml/stable-diffusion-v1-5"""				,   revision="""onnx"""				,   scheduler=lowerCamelCase				,   safety_checker=lowerCamelCase				,   feature_extractor=lowerCamelCase				,   provider=self.gpu_provider				,   sess_options=self.gpu_options				,   )
   sd_pipe.set_progress_bar_config(disable=lowerCamelCase       )

   __A		:     Tuple												=		"""open neural network exchange"""
   __A		:     List[Any]												=		np.random.RandomState(0       )
   __A		:     Optional[int]												=		sd_pipe([prompt]				,   guidance_scale=7.5				,   num_inference_steps=10				,   generator=lowerCamelCase				,   output_type="""np"""       )
   __A		:     List[str]												=		output.images
   __A		:     Optional[int]												=		image[0, -3:, -3:, -1]

   assert image.shape == (1, 5_12, 5_12, 3)
   __A		:     Union[str, Any]												=		np.array([0.2_306, 0.1_959, 0.1_593, 0.6_549, 0.6_394, 0.5_408, 0.5_065, 0.6_010, 0.6_161]       )

   assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-3
 def 		lowercase_(   self			:    Tuple       ):



   """simple docstring"""





   __A		:     Optional[int]												=		0

   def test_callback_fn(lowerCamelCase			:    int				,   lowerCamelCase			:    int				,   lowerCamelCase			:    np.ndarray       ) -> None:
     __A		:     Dict												=		True
     nonlocal number_of_steps
     number_of_steps += 1
     if step == 0:
       assert latents.shape == (1, 4, 64, 64)
       __A		:     str												=		latents[0, -3:, -3:, -1]
       __A		:     int												=		np.array(
           [-0.6_772, -0.3_835, -1.2_456, 0.1_905, -1.0_974, 0.6_967, -1.9_353, 0.0_178, 1.0_167]       )

       assert np.abs(latents_slice.flatten() - expected_slice       ).max() < 1e-3
     elif step == 5:
       assert latents.shape == (1, 4, 64, 64)
       __A		:     Any												=		latents[0, -3:, -3:, -1]
       __A		:     Dict												=		np.array(
           [-0.3_351, 0.2_241, -0.1_837, -0.2_325, -0.6_577, 0.3_393, -0.0_241, 0.5_899, 1.3_875]       )

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

   __A		:     Tuple												=		False

   __A		:     List[str]												=		OnnxStableDiffusionPipeline.from_pretrained(
       """runwayml/stable-diffusion-v1-5"""				,   revision="""onnx"""				,   safety_checker=lowerCamelCase				,   feature_extractor=lowerCamelCase				,   provider=self.gpu_provider				,   sess_options=self.gpu_options				,   )
   pipe.set_progress_bar_config(disable=lowerCamelCase       )

   __A		:     Optional[int]												=		"""Andromeda galaxy in a bottle"""

   __A		:     List[str]												=		np.random.RandomState(0       )
   pipe(
       prompt=lowerCamelCase				,   num_inference_steps=5				,   guidance_scale=7.5				,   generator=lowerCamelCase				,   callback=lowerCamelCase				,   callback_steps=1				,   )
   assert test_callback_fn.has_been_called
   assert number_of_steps == 6






 def 		lowercase_(   self			:    Dict       ):



   """simple docstring"""





   __A		:     Union[str, Any]												=		OnnxStableDiffusionPipeline.from_pretrained(
       """runwayml/stable-diffusion-v1-5"""				,   revision="""onnx"""				,   safety_checker=lowerCamelCase				,   feature_extractor=lowerCamelCase				,   provider=self.gpu_provider				,   sess_options=self.gpu_options				,   )
   assert isinstance(lowerCamelCase				,   lowerCamelCase       )
   assert pipe.safety_checker is None

   __A		:     int												=		pipe("""example prompt"""				,   num_inference_steps=2       ).images[0]
   assert image is not None

   # check that there's no error when saving a pipeline with one of the models being None
   with tempfile.TemporaryDirectory() as tmpdirname:
     pipe.save_pretrained(lowerCamelCase       )
     __A		:     str												=		OnnxStableDiffusionPipeline.from_pretrained(lowerCamelCase       )

   # sanity check that the pipeline still works
   assert pipe.safety_checker is None
   __A		:     int												=		pipe("""example prompt"""				,   num_inference_steps=2       ).images[0]
   assert image is not None





'''simple docstring'''
def        A_     (						__SCREAMING_SNAKE_CASE						:  int			,     __SCREAMING_SNAKE_CASE						:  bool = False )				->       bool:





  """simple docstring"""

  if n == 2:
    return True
  if not n % 2 or n < 2:
    return False
  if n > 5 and n % 10 not in (1, 3, 7, 9):  # can quickly check last digit
    return False
  if n > 3_3170_4406_4679_8873_8596_1981 and not allow_probable:
    raise ValueError(
        """Warning: upper bound of deterministic test is exceeded. """
        """Pass allow_probable=True to allow probabilistic test. """
        """A return value of True indicates a probable prime.""" )
  # array bounds provided by analysis
  __A		:     Optional[int]												=		[
      2047,
      137_3653,
      2532_6001,
      32_1503_1751,
      2_1523_0289_8747,
      3_4747_4966_0383,
      341_5500_7172_8321,
      1,
      382_5123_0565_4641_3051,
      1,
      1,
      3186_6585_7834_0311_5116_7461,
      3_3170_4406_4679_8873_8596_1981,
  ]

  __A		:     Optional[int]												=		[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
  for idx, _p in enumerate(__SCREAMING_SNAKE_CASE			,     1 ):
    if n < _p:
      # then we have our last prime to check
      __A		:     Union[str, Any]												=		primes[:idx]
      break
  __A							,					__A		:     int												=		n - 1, 0
  # break up n -1 into a power of 2 (s) and
  # remaining odd component
  # essentially, solve for d * 2 ** s == n - 1
  while d % 2 == 0:
    d //= 2
    s += 1
  for prime in plist:
    __A		:     int												=		False
    for r in range(__SCREAMING_SNAKE_CASE ):
      __A		:     Optional[Any]												=		pow(__SCREAMING_SNAKE_CASE			,     d * 2**r			,     __SCREAMING_SNAKE_CASE )
      # see article for analysis explanation for m
      if (r == 0 and m == 1) or ((m + 1) % n == 0):
        __A		:     Optional[int]												=		True
        # this loop will not determine compositeness
        break
    if pr:
      continue
    # if pr is False, then the above loop never evaluated to true,
    # and the n MUST be composite
    return False
  return True







def        A_     (						)				->       None:





  """simple docstring"""

  assert not miller_rabin(561 )
  assert miller_rabin(563 )
  # 2047

  assert not miller_rabin(83_8201 )
  assert miller_rabin(83_8207 )
  # 1_373_653

  assert not miller_rabin(1731_6001 )
  assert miller_rabin(1731_6017 )
  # 25_326_001

  assert not miller_rabin(30_7838_6641 )
  assert miller_rabin(30_7838_6653 )
  # 3_215_031_751

  assert not miller_rabin(1_7130_4557_4801 )
  assert miller_rabin(1_7130_4557_4819 )
  # 2_152_302_898_747

  assert not miller_rabin(2_7797_9972_8307 )
  assert miller_rabin(2_7797_9972_8327 )
  # 3_474_749_660_383

  assert not miller_rabin(113_8500_2390_9441 )
  assert miller_rabin(113_8500_2390_9527 )
  # 341_550_071_728_321

  assert not miller_rabin(127_5041_0188_4880_4351 )
  assert miller_rabin(127_5041_0188_4880_4391 )
  # 3_825_123_056_546_413_051

  assert not miller_rabin(796_6646_4458_5077_8779_1867 )
  assert miller_rabin(796_6646_4458_5077_8779_1951 )
  # 318_665_857_834_031_151_167_461

  assert not miller_rabin(5528_4067_7446_6478_9766_0333 )
  assert miller_rabin(5528_4067_7446_6478_9766_0359 )
  # 3_317_044_064_679_887_385_961_981
  # upper limit for probabilistic test


if __name__ == "__main__":
     test_miller_rabin()



