





import os
import tempfile
import unittest

import numpy as np

from diffusers.utils import is_flax_available
from diffusers.utils.testing_utils import require_flax, slow


if is_flax_available():
  import jax
  import jax.numpy as jnp
  from flax.jax_utils import replicate
  from flax.training.common_utils import shard

  from diffusers import FlaxDDIMScheduler, FlaxDiffusionPipeline, FlaxStableDiffusionPipeline






@require_flax
class        UpperCAmelCase     (	unittest.TestCase    ):
 def 					UpperCAmelCase_							(    self				:Dict							)->							Union[str, Any]:
     with tempfile.TemporaryDirectory() as tmpdirname:
         # pipeline has Flax weights
         A__    =      FlaxDiffusionPipeline.from_pretrained(
             "hf-internal-testing/tiny-stable-diffusion-pipe"						,	safety_checker=__lowercase						,	cache_dir=__lowercase							)

         A__    =      [t[-1] for t in os.walk(os.path.join(__lowercase						,	os.listdir(__lowercase							)[0]						,	"snapshots"							)							)]
         A__    =      [item for sublist in all_root_files for item in sublist]

         # None of the downloaded files should be a PyTorch file even if we have some here:
         # https://huggingface.co/hf-internal-testing/tiny-stable-diffusion-pipe/blob/main/unet/diffusion_pytorch_model.bin
         assert not any(f.endswith(".bin"							) for f in files							)






@slow
@require_flax
class        UpperCAmelCase     (	unittest.TestCase    ):
 def 					UpperCAmelCase_							(    self				:str							)->							List[Any]:
     A__    =      FlaxStableDiffusionPipeline.from_pretrained(
         "hf-internal-testing/tiny-stable-diffusion-pipe"						,	safety_checker=__lowercase							)

     A__    =      (
         '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of'''
         ''' field, close up, split lighting, cinematic'''
     )

     A__    =      jax.random.PRNGKey(0							)
     A__    =      4

     A__    =      jax.device_count()
     A__    =      num_samples * [prompt]
     A__    =      pipeline.prepare_inputs(__lowercase							)

     # shard inputs and rng
     A__    =      replicate(__lowercase							)
     A__    =      jax.random.split(__lowercase						,	__lowercase							)
     A__    =      shard(__lowercase							)

     A__    =      pipeline(__lowercase						,	__lowercase						,	__lowercase						,	__lowercase						,	jit=__lowercase							).images

     assert images.shape == (num_samples, 1, 64, 64, 3)
     if jax.device_count() == 8:
         assert np.abs(np.abs(images[0, 0, :2, :2, -2:]						,	dtype=np.floataa							).sum() - 4.1_5_1_4_7_4_5							) < 1E-3
         assert np.abs(np.abs(__lowercase						,	dtype=np.floataa							).sum() - 4_99_47.8_75							) < 5E-1

     A__    =      pipeline.numpy_to_pil(np.asarray(images.reshape((num_samples,) + images.shape[-3:]							)							)							)
     assert len(__lowercase							) == num_samples
 def 					UpperCAmelCase_							(    self				:Union[str, Any]							)->							Optional[Any]:
     A__    =      FlaxStableDiffusionPipeline.from_pretrained(
         "CompVis/stable-diffusion-v1-4"						,	revision="flax"						,	safety_checker=__lowercase							)

     A__    =      (
         '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of'''
         ''' field, close up, split lighting, cinematic'''
     )

     A__    =      jax.random.PRNGKey(0							)
     A__    =      50

     A__    =      jax.device_count()
     A__    =      num_samples * [prompt]
     A__    =      pipeline.prepare_inputs(__lowercase							)

     # shard inputs and rng
     A__    =      replicate(__lowercase							)
     A__    =      jax.random.split(__lowercase						,	__lowercase							)
     A__    =      shard(__lowercase							)

     A__    =      pipeline(__lowercase						,	__lowercase						,	__lowercase						,	__lowercase						,	jit=__lowercase							).images

     assert images.shape == (num_samples, 1, 5_12, 5_12, 3)
     if jax.device_count() == 8:
         assert np.abs((np.abs(images[0, 0, :2, :2, -2:]						,	dtype=np.floataa							).sum() - 0.0_5_6_5_2_4_0_1)							) < 1E-3
         assert np.abs((np.abs(__lowercase						,	dtype=np.floataa							).sum() - 2_38_38_08.2)							) < 5E-1
 def 					UpperCAmelCase_							(    self				:Tuple							)->							Optional[Any]:
     A__    =      FlaxStableDiffusionPipeline.from_pretrained(
         "CompVis/stable-diffusion-v1-4"						,	revision="bf16"						,	dtype=jnp.bfloataa						,	safety_checker=__lowercase							)

     A__    =      (
         '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of'''
         ''' field, close up, split lighting, cinematic'''
     )

     A__    =      jax.random.PRNGKey(0							)
     A__    =      50

     A__    =      jax.device_count()
     A__    =      num_samples * [prompt]
     A__    =      pipeline.prepare_inputs(__lowercase							)

     # shard inputs and rng
     A__    =      replicate(__lowercase							)
     A__    =      jax.random.split(__lowercase						,	__lowercase							)
     A__    =      shard(__lowercase							)

     A__    =      pipeline(__lowercase						,	__lowercase						,	__lowercase						,	__lowercase						,	jit=__lowercase							).images

     assert images.shape == (num_samples, 1, 5_12, 5_12, 3)
     if jax.device_count() == 8:
         assert np.abs((np.abs(images[0, 0, :2, :2, -2:]						,	dtype=np.floataa							).sum() - 0.0_4_0_0_3_9_0_6)							) < 1E-3
         assert np.abs((np.abs(__lowercase						,	dtype=np.floataa							).sum() - 2_37_35_16.75)							) < 5E-1
 def 					UpperCAmelCase_							(    self				:Optional[int]							)->							List[Any]:
     A__    =      FlaxStableDiffusionPipeline.from_pretrained(
         "CompVis/stable-diffusion-v1-4"						,	revision="bf16"						,	dtype=jnp.bfloataa							)

     A__    =      (
         '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of'''
         ''' field, close up, split lighting, cinematic'''
     )

     A__    =      jax.random.PRNGKey(0							)
     A__    =      50

     A__    =      jax.device_count()
     A__    =      num_samples * [prompt]
     A__    =      pipeline.prepare_inputs(__lowercase							)

     # shard inputs and rng
     A__    =      replicate(__lowercase							)
     A__    =      jax.random.split(__lowercase						,	__lowercase							)
     A__    =      shard(__lowercase							)

     A__    =      pipeline(__lowercase						,	__lowercase						,	__lowercase						,	__lowercase						,	jit=__lowercase							).images

     assert images.shape == (num_samples, 1, 5_12, 5_12, 3)
     if jax.device_count() == 8:
         assert np.abs((np.abs(images[0, 0, :2, :2, -2:]						,	dtype=np.floataa							).sum() - 0.0_4_0_0_3_9_0_6)							) < 1E-3
         assert np.abs((np.abs(__lowercase						,	dtype=np.floataa							).sum() - 2_37_35_16.75)							) < 5E-1
 def 					UpperCAmelCase_							(    self				:List[str]							)->							Optional[Any]:
     A__    =      FlaxDDIMScheduler(
         beta_start=0.0_0_0_8_5						,	beta_end=0.0_1_2						,	beta_schedule="scaled_linear"						,	set_alpha_to_one=__lowercase						,	steps_offset=1						,	)

     A__    =      FlaxStableDiffusionPipeline.from_pretrained(
         "CompVis/stable-diffusion-v1-4"						,	revision="bf16"						,	dtype=jnp.bfloataa						,	scheduler=__lowercase						,	safety_checker=__lowercase						,	)
     A__    =      scheduler.create_state()

     A__    =      scheduler_state

     A__    =      (
         '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of'''
         ''' field, close up, split lighting, cinematic'''
     )

     A__    =      jax.random.PRNGKey(0							)
     A__    =      50

     A__    =      jax.device_count()
     A__    =      num_samples * [prompt]
     A__    =      pipeline.prepare_inputs(__lowercase							)

     # shard inputs and rng
     A__    =      replicate(__lowercase							)
     A__    =      jax.random.split(__lowercase						,	__lowercase							)
     A__    =      shard(__lowercase							)

     A__    =      pipeline(__lowercase						,	__lowercase						,	__lowercase						,	__lowercase						,	jit=__lowercase							).images

     assert images.shape == (num_samples, 1, 5_12, 5_12, 3)
     if jax.device_count() == 8:
         assert np.abs((np.abs(images[0, 0, :2, :2, -2:]						,	dtype=np.floataa							).sum() - 0.0_4_5_0_4_3_9_4_5)							) < 1E-3
         assert np.abs((np.abs(__lowercase						,	dtype=np.floataa							).sum() - 2_34_76_93.5)							) < 5E-1



 def 					UpperCAmelCase_							(    self				:List[Any]							)->							List[str]:
     A__    =      (
         '''A cinematic film still of Morgan Freeman starring as Jimi Hendrix, portrait, 40mm lens, shallow depth of'''
         ''' field, close up, split lighting, cinematic'''
     )

     A__    =      jax.device_count()
     A__    =      num_samples * [prompt]
     A__    =      jax.random.split(jax.random.PRNGKey(0							)						,	__lowercase							)

     A__    =      FlaxStableDiffusionPipeline.from_pretrained(
         "CompVis/stable-diffusion-v1-4"						,	revision="bf16"						,	dtype=jnp.bfloataa						,	safety_checker=__lowercase						,	)

     A__    =      replicate(__lowercase							)
     A__    =      pipeline.prepare_inputs(__lowercase							)
     A__    =      shard(__lowercase							)
     A__    =      pipeline(__lowercase						,	__lowercase						,	__lowercase						,	jit=__lowercase							).images
     assert images.shape == (num_samples, 1, 5_12, 5_12, 3)
     A__    =      images[2, 0, 2_56, 10:17, 1]

     # With memory efficient attention
     A__    =      FlaxStableDiffusionPipeline.from_pretrained(
         "CompVis/stable-diffusion-v1-4"						,	revision="bf16"						,	dtype=jnp.bfloataa						,	safety_checker=__lowercase						,	use_memory_efficient_attention=__lowercase						,	)

     A__    =      replicate(__lowercase							)
     A__    =      pipeline.prepare_inputs(__lowercase							)
     A__    =      shard(__lowercase							)
     A__    =      pipeline(__lowercase						,	__lowercase						,	__lowercase						,	jit=__lowercase							).images
     assert images_eff.shape == (num_samples, 1, 5_12, 5_12, 3)
     A__    =      images[2, 0, 2_56, 10:17, 1]

     # I checked the results visually and they are very similar. However, I saw that the max diff is `1` and the `sum`
     # over the 8 images is exactly `256`, which is very suspicious. Testing a random slice for now.
     assert abs(slice_eff - slice							).max() < 1E-2










'''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}""")



