





'''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        UpperCAmelCase     (	UpperCamelCase__      ,	unittest.TestCase    ):
 __lowercase       		=    """hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline"""
 def 					UpperCAmelCase_							(    self				:Union[str, Any]						,	lowercase_				:Tuple=0							)->							Any:
     A__    =      np.random.RandomState(lowercase_							)
     A__    =      {
         "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 					UpperCAmelCase_							(    self				:str							)->							Union[str, Any]:
     A__    =      OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"							)
     pipe.set_progress_bar_config(disable=lowercase_							)

     A__    =      self.get_dummy_inputs()
     A__    =      pipe(**lowercase_							).images
     A__    =      image[0, -3:, -3:, -1]

     assert image.shape == (1, 1_28, 1_28, 3)
     A__    =      np.array([0.6_5_0_7_2, 0.5_8_4_9_2, 0.4_8_2_1_9, 0.5_5_5_2_1, 0.5_3_1_8_0, 0.5_5_9_3_9, 0.5_0_6_9_7, 0.3_9_8_0_0, 0.4_6_4_5_5]							)

     assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-2
 def 					UpperCAmelCase_							(    self				:Union[str, Any]							)->							Dict:
     A__    =      OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"							)
     A__    =      PNDMScheduler.from_config(pipe.scheduler.config						,	skip_prk_steps=lowercase_							)
     pipe.set_progress_bar_config(disable=lowercase_							)

     A__    =      self.get_dummy_inputs()
     A__    =      pipe(**lowercase_							).images
     A__    =      image[0, -3:, -3:, -1]

     assert image.shape == (1, 1_28, 1_28, 3)
     A__    =      np.array([0.6_5_8_6_3, 0.5_9_4_2_5, 0.4_9_3_2_6, 0.5_6_3_1_3, 0.5_3_8_7_5, 0.5_6_6_2_7, 0.5_1_0_6_5, 0.3_9_7_7_7, 0.4_6_3_3_0]							)

     assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-2
 def 					UpperCAmelCase_							(    self				:List[Any]							)->							Dict:
     A__    =      OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"							)
     A__    =      LMSDiscreteScheduler.from_config(pipe.scheduler.config							)
     pipe.set_progress_bar_config(disable=lowercase_							)

     A__    =      self.get_dummy_inputs()
     A__    =      pipe(**lowercase_							).images
     A__    =      image[0, -3:, -3:, -1]

     assert image.shape == (1, 1_28, 1_28, 3)
     A__    =      np.array([0.5_3_7_5_5, 0.6_0_7_8_6, 0.4_7_4_0_2, 0.4_9_4_8_8, 0.5_1_8_6_9, 0.4_9_8_1_9, 0.4_7_9_8_5, 0.3_8_9_5_7, 0.4_4_2_7_9]							)

     assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-2
 def 					UpperCAmelCase_							(    self				:Any							)->							List[str]:
     A__    =      OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"							)
     A__    =      EulerDiscreteScheduler.from_config(pipe.scheduler.config							)
     pipe.set_progress_bar_config(disable=lowercase_							)

     A__    =      self.get_dummy_inputs()
     A__    =      pipe(**lowercase_							).images
     A__    =      image[0, -3:, -3:, -1]

     assert image.shape == (1, 1_28, 1_28, 3)
     A__    =      np.array([0.5_3_7_5_5, 0.6_0_7_8_6, 0.4_7_4_0_2, 0.4_9_4_8_8, 0.5_1_8_6_9, 0.4_9_8_1_9, 0.4_7_9_8_5, 0.3_8_9_5_7, 0.4_4_2_7_9]							)

     assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-2
 def 					UpperCAmelCase_							(    self				:Optional[Any]							)->							Optional[Any]:
     A__    =      OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"							)
     A__    =      EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config							)
     pipe.set_progress_bar_config(disable=lowercase_							)

     A__    =      self.get_dummy_inputs()
     A__    =      pipe(**lowercase_							).images
     A__    =      image[0, -3:, -3:, -1]

     assert image.shape == (1, 1_28, 1_28, 3)
     A__    =      np.array([0.5_3_8_1_7, 0.6_0_8_1_2, 0.4_7_3_8_4, 0.4_9_5_3_0, 0.5_1_8_9_4, 0.4_9_8_1_4, 0.4_7_9_8_4, 0.3_8_9_5_8, 0.4_4_2_7_1]							)

     assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-2
 def 					UpperCAmelCase_							(    self				:Union[str, Any]							)->							str:
     A__    =      OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"							)
     A__    =      DPMSolverMultistepScheduler.from_config(pipe.scheduler.config							)
     pipe.set_progress_bar_config(disable=lowercase_							)

     A__    =      self.get_dummy_inputs()
     A__    =      pipe(**lowercase_							).images
     A__    =      image[0, -3:, -3:, -1]

     assert image.shape == (1, 1_28, 1_28, 3)
     A__    =      np.array([0.5_3_8_9_5, 0.6_0_8_0_8, 0.4_7_9_3_3, 0.4_9_6_0_8, 0.5_1_8_8_6, 0.4_9_9_5_0, 0.4_8_0_5_3, 0.3_8_9_5_7, 0.4_4_2_0_0]							)

     assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-2
 def 					UpperCAmelCase_							(    self				:int							)->							Dict:
     A__    =      OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"							)
     pipe.set_progress_bar_config(disable=lowercase_							)

     A__    =      self.get_dummy_inputs()
     A__    =      3 * [inputs["prompt"]]

     # forward
     A__    =      pipe(**lowercase_							)
     A__    =      output.images[0, -3:, -3:, -1]

     A__    =      self.get_dummy_inputs()
     A__    =      3 * [inputs.pop("prompt"							)]

     A__    =      pipe.tokenizer(
         lowercase_						,	padding="max_length"						,	max_length=pipe.tokenizer.model_max_length						,	truncation=lowercase_						,	return_tensors="np"						,	)
     A__    =      text_inputs["input_ids"]

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

     A__    =      prompt_embeds

     # forward
     A__    =      pipe(**lowercase_							)
     A__    =      output.images[0, -3:, -3:, -1]

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



 def 					UpperCAmelCase_							(    self				:Any							)->							int:
     A__    =      OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint						,	provider="CPUExecutionProvider"							)
     pipe.set_progress_bar_config(disable=lowercase_							)

     A__    =      self.get_dummy_inputs()
     A__    =      3 * ["this is a negative prompt"]
     A__    =      negative_prompt
     A__    =      3 * [inputs["prompt"]]

     # forward
     A__    =      pipe(**lowercase_							)
     A__    =      output.images[0, -3:, -3:, -1]

     A__    =      self.get_dummy_inputs()
     A__    =      3 * [inputs.pop("prompt"							)]

     A__    =      []
     for p in [prompt, negative_prompt]:
         A__    =      pipe.tokenizer(
             lowercase_						,	padding="max_length"						,	max_length=pipe.tokenizer.model_max_length						,	truncation=lowercase_						,	return_tensors="np"						,	)
         A__    =      text_inputs["input_ids"]

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

     A__,     A__    =      embeds

     # forward
     A__    =      pipe(**lowercase_							)
     A__    =      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        UpperCAmelCase     (	unittest.TestCase    ):
 @property
 def 					UpperCAmelCase_							(    self				:int							)->							Dict:
     return (
         "CUDAExecutionProvider",
         {
             "gpu_mem_limit": "15000000000",  # 15GB
             "arena_extend_strategy": "kSameAsRequested",
         },
     )
 @property
 def 					UpperCAmelCase_							(    self				:Optional[Any]							)->							Any:
     A__    =      ort.SessionOptions()
     A__    =      False
     return options
 def 					UpperCAmelCase_							(    self				:Optional[int]							)->							Union[str, Any]:
     # using the PNDM scheduler by default
     A__    =      OnnxStableDiffusionPipeline.from_pretrained(
         "CompVis/stable-diffusion-v1-4"						,	revision="onnx"						,	safety_checker=lowercase_						,	feature_extractor=lowercase_						,	provider=self.gpu_provider						,	sess_options=self.gpu_options						,	)
     sd_pipe.set_progress_bar_config(disable=lowercase_							)

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

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

     assert image.shape == (1, 5_12, 5_12, 3)
     A__    =      np.array([0.0_4_5_2, 0.0_3_9_0, 0.0_0_8_7, 0.0_3_5_0, 0.0_6_1_7, 0.0_3_6_4, 0.0_5_4_4, 0.0_5_2_3, 0.0_7_2_0]							)

     assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-3
 def 					UpperCAmelCase_							(    self				:Dict							)->							Tuple:
     A__    =      DDIMScheduler.from_pretrained(
         "runwayml/stable-diffusion-v1-5"						,	subfolder="scheduler"						,	revision="onnx"							)
     A__    =      OnnxStableDiffusionPipeline.from_pretrained(
         "runwayml/stable-diffusion-v1-5"						,	revision="onnx"						,	scheduler=lowercase_						,	safety_checker=lowercase_						,	feature_extractor=lowercase_						,	provider=self.gpu_provider						,	sess_options=self.gpu_options						,	)
     sd_pipe.set_progress_bar_config(disable=lowercase_							)

     A__    =      "open neural network exchange"
     A__    =      np.random.RandomState(0							)
     A__    =      sd_pipe([prompt]						,	guidance_scale=7.5						,	num_inference_steps=10						,	generator=lowercase_						,	output_type="np"							)
     A__    =      output.images
     A__    =      image[0, -3:, -3:, -1]

     assert image.shape == (1, 5_12, 5_12, 3)
     A__    =      np.array([0.2_8_6_7, 0.1_9_7_4, 0.1_4_8_1, 0.7_2_9_4, 0.7_2_5_1, 0.6_6_6_7, 0.4_1_9_4, 0.5_6_4_2, 0.6_4_8_6]							)

     assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-3
 def 					UpperCAmelCase_							(    self				:Dict							)->							List[str]:
     A__    =      LMSDiscreteScheduler.from_pretrained(
         "runwayml/stable-diffusion-v1-5"						,	subfolder="scheduler"						,	revision="onnx"							)
     A__    =      OnnxStableDiffusionPipeline.from_pretrained(
         "runwayml/stable-diffusion-v1-5"						,	revision="onnx"						,	scheduler=lowercase_						,	safety_checker=lowercase_						,	feature_extractor=lowercase_						,	provider=self.gpu_provider						,	sess_options=self.gpu_options						,	)
     sd_pipe.set_progress_bar_config(disable=lowercase_							)

     A__    =      "open neural network exchange"
     A__    =      np.random.RandomState(0							)
     A__    =      sd_pipe([prompt]						,	guidance_scale=7.5						,	num_inference_steps=10						,	generator=lowercase_						,	output_type="np"							)
     A__    =      output.images
     A__    =      image[0, -3:, -3:, -1]

     assert image.shape == (1, 5_12, 5_12, 3)
     A__    =      np.array([0.2_3_0_6, 0.1_9_5_9, 0.1_5_9_3, 0.6_5_4_9, 0.6_3_9_4, 0.5_4_0_8, 0.5_0_6_5, 0.6_0_1_0, 0.6_1_6_1]							)

     assert np.abs(image_slice.flatten() - expected_slice							).max() < 1E-3
 def 					UpperCAmelCase_							(    self				:int							)->							Any:
     A__    =      0

     def test_callback_fn(lowercase_				:int						,	lowercase_				:int						,	lowercase_				:np.ndarray							) -> None:
         A__    =      True
         nonlocal number_of_steps
         number_of_steps += 1
         if step == 0:
             assert latents.shape == (1, 4, 64, 64)
             A__    =      latents[0, -3:, -3:, -1]
             A__    =      np.array(
                 [-0.6_7_7_2, -0.3_8_3_5, -1.2_4_5_6, 0.1_9_0_5, -1.0_9_7_4, 0.6_9_6_7, -1.9_3_5_3, 0.0_1_7_8, 1.0_1_6_7]							)

             assert np.abs(latents_slice.flatten() - expected_slice							).max() < 1E-3
         elif step == 5:
             assert latents.shape == (1, 4, 64, 64)
             A__    =      latents[0, -3:, -3:, -1]
             A__    =      np.array(
                 [-0.3_3_5_1, 0.2_2_4_1, -0.1_8_3_7, -0.2_3_2_5, -0.6_5_7_7, 0.3_3_9_3, -0.0_2_4_1, 0.5_8_9_9, 1.3_8_7_5]							)

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

     A__    =      False

     A__    =      OnnxStableDiffusionPipeline.from_pretrained(
         "runwayml/stable-diffusion-v1-5"						,	revision="onnx"						,	safety_checker=lowercase_						,	feature_extractor=lowercase_						,	provider=self.gpu_provider						,	sess_options=self.gpu_options						,	)
     pipe.set_progress_bar_config(disable=lowercase_							)

     A__    =      "Andromeda galaxy in a bottle"

     A__    =      np.random.RandomState(0							)
     pipe(
         prompt=lowercase_						,	num_inference_steps=5						,	guidance_scale=7.5						,	generator=lowercase_						,	callback=lowercase_						,	callback_steps=1						,	)
     assert test_callback_fn.has_been_called
     assert number_of_steps == 6



 def 					UpperCAmelCase_							(    self				:Dict							)->							Optional[int]:
     A__    =      OnnxStableDiffusionPipeline.from_pretrained(
         "runwayml/stable-diffusion-v1-5"						,	revision="onnx"						,	safety_checker=lowercase_						,	feature_extractor=lowercase_						,	provider=self.gpu_provider						,	sess_options=self.gpu_options						,	)
     assert isinstance(lowercase_						,	lowercase_							)
     assert pipe.safety_checker is None

     A__    =      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(lowercase_							)
         A__    =      OnnxStableDiffusionPipeline.from_pretrained(lowercase_							)

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










'''simple docstring'''

from __future__ import annotations

from math import gcd





def 						UpperCamelCase    (							_lowerCamelCase : int						,	_lowerCamelCase : int = 2						,	_lowerCamelCase : int = 1						,	_lowerCamelCase : int = 3						,	):
    # A value less than 2 can cause an infinite loop in the algorithm.
    if num < 2:
        raise ValueError("The input value cannot be less than 2"	)

    # Because of the relationship between ``f(f(x))`` and ``f(x)``, this
    # algorithm struggles to find factors that are divisible by two.
    # As a workaround, we specifically check for two and even inputs.
    #   See: https://math.stackexchange.com/a/2856214/165820
    if num > 2 and num % 2 == 0:
        return 2

    # Pollard's Rho algorithm requires a function that returns pseudorandom
    # values between 0 <= X < ``num``.  It doesn't need to be random in the
    # sense that the output value is cryptographically secure or difficult
    # to calculate, it only needs to be random in the sense that all output
    # values should be equally likely to appear.
    # For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num``
    # However, the success of Pollard's algorithm isn't guaranteed and is
    # determined in part by the initial seed and the chosen random function.
    # To make retries easier, we will instead use ``f(x) = (x**2 + C) % num``
    # where ``C`` is a value that we can modify between each attempt.
    def rand_fn(_lowerCamelCase : int						,	_lowerCamelCase : int						,	_lowerCamelCase : int	) -> int:
        return (pow(_lowerCamelCase						,	2	) + step) % modulus

    for _ in range(_lowerCamelCase	):
        # These track the position within the cycle detection logic.
        A__    =      seed
        A__    =      seed

        while True:
            # At each iteration, the tortoise moves one step and the hare moves two.
            A__    =      rand_fn(_lowerCamelCase						,	_lowerCamelCase						,	_lowerCamelCase	)
            A__    =      rand_fn(_lowerCamelCase						,	_lowerCamelCase						,	_lowerCamelCase	)
            A__    =      rand_fn(_lowerCamelCase						,	_lowerCamelCase						,	_lowerCamelCase	)

            # At some point both the tortoise and the hare will enter a cycle whose
            # length ``p`` is a divisor of ``num``.  Once in that cycle, at some point
            # the tortoise and hare will end up on the same value modulo ``p``.
            # We can detect when this happens because the position difference between
            # the tortoise and the hare will share a common divisor with ``num``.
            A__    =      gcd(hare - tortoise						,	_lowerCamelCase	)

            if divisor == 1:
                # No common divisor yet, just keep searching.
                continue
            else:
                # We found a common divisor!
                if divisor == num:
                    # Unfortunately, the divisor is ``num`` itself and is useless.
                    break
                else:
                    # The divisor is a nontrivial factor of ``num``!
                    return divisor

        # If we made it here, then this attempt failed.
        # We need to pick a new starting seed for the tortoise and hare
        # in addition to a new step value for the random function.
        # To keep this example implementation deterministic, the
        # new values will be generated based on currently available
        # values instead of using something like ``random.randint``.

        # We can use the hare's position as the new seed.
        # This is actually what Richard Brent's the "optimized" variant does.
        A__    =      hare

        # The new step value for the random function can just be incremented.
        # At first the results will be similar to what the old function would
        # have produced, but the value will quickly diverge after a bit.
        step += 1

    # We haven't found a divisor within the requested number of attempts.
    # We were unlucky or ``num`` itself is actually prime.
    return None


if __name__ == "__main__":
  import argparse

  __lowerCAmelCase							:     Optional[int]		     =argparse.ArgumentParser()
  parser.add_argument(
      "num",
      type=int,
      help="The value to find a divisor of",
  )
  parser.add_argument(
      "--attempts",
      type=int,
      default=3,
      help="The number of attempts before giving up",
  )
  __lowerCAmelCase							:     Optional[int]		     =parser.parse_args()

  __lowerCAmelCase							:     Dict		     =pollard_rho(args.num, attempts=args.attempts)
  if divisor is None:
    print(f"""{args.num} is probably prime""")
  else:
    __lowerCAmelCase							:     Optional[Any]		     =args.num // divisor
    print(f"""{args.num} = {divisor} * {quotient}""")



