





import gc
import random
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()
class     UpperCamelCase__					(     lowerCamelCase__				, lowerCamelCase__				, unittest.TestCase				):






		'''simple docstring'''






		__a       :       Dict       =	StableDiffusionXLImgaImgPipeline
		__a       :       Any       =	TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""}
		__a       :       int       =	PipelineTesterMixin.required_optional_params - {"""latents"""}
		__a       :       Any       =	TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
		__a       :       Dict       =	IMAGE_TO_IMAGE_IMAGE_PARAMS
		__a       :       str       =	IMAGE_TO_IMAGE_IMAGE_PARAMS






		def 						snake_case__				(							self  )       -> Any:






									"""simple docstring"""
									torch.manual_seed(0  )
									lowercase_	:   Optional[int]  				=     UNetaDConditionModel(
									    block_out_channels=(32, 64),   layers_per_block=2,   sample_size=32,   in_channels=4,   out_channels=4,   down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D"""),   up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D"""),   attention_head_dim=(2, 4),   use_linear_projection=snake_case__,   addition_embed_type="""text_time""",   addition_time_embed_dim=8,   transformer_layers_per_block=(1, 2),   projection_class_embeddings_input_dim=80,   cross_attention_dim=64,   )
									lowercase_	:   Any  				=     EulerDiscreteScheduler(
									    beta_start=0.00085,   beta_end=0.012,   steps_offset=1,   beta_schedule="""scaled_linear""",   timestep_spacing="""leading""",   )
									torch.manual_seed(0  )
									lowercase_	:   Any  				=     AutoencoderKL(
									    block_out_channels=[32, 64],   in_channels=3,   out_channels=3,   down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""],   up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""],   latent_channels=4,   sample_size=1_28,   )
									torch.manual_seed(0  )
									lowercase_	:   Optional[Any]  				=     CLIPTextConfig(
									    bos_token_id=0,   eos_token_id=2,   hidden_size=32,   intermediate_size=37,   layer_norm_eps=1E-05,   num_attention_heads=4,   num_hidden_layers=5,   pad_token_id=1,   vocab_size=10_00,   hidden_act="""gelu""",   projection_dim=32,   )
									lowercase_	:   List[Any]  				=     CLIPTextModel(snake_case__  )
									lowercase_	:   Optional[Any]  				=     CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""",   local_files_only=snake_case__  )

									lowercase_	:   Optional[Any]  				=     CLIPTextModelWithProjection(snake_case__  )
									lowercase_	:   Union[str, Any]  				=     CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""",   local_files_only=snake_case__  )

									lowercase_	:   List[str]  				=     {
									    """unet""": unet,
									    """scheduler""": scheduler,
									    """vae""": vae,
									    """text_encoder""": text_encoder,
									    """tokenizer""": tokenizer,
									    """text_encoder_2""": text_encoder_a,
									    """tokenizer_2""": tokenizer_a,
									    # "safety_checker": None,
									    # "feature_extractor": None,
									}
									return components






		def 						snake_case__				(							self,   snake_case__,   snake_case__=0  )       -> Optional[int]:






									"""simple docstring"""
									lowercase_	:   List[Any]  				=     floats_tensor((1, 3, 32, 32),   rng=random.Random(snake_case__  )  ).to(snake_case__  )
									lowercase_	:   List[str]  				=     image / 2 + 0.5
									if str(snake_case__  ).startswith("""mps"""  ):
																lowercase_	:   Dict  				=     torch.manual_seed(snake_case__  )
									else:
																lowercase_	:   str  				=     torch.Generator(device=snake_case__  ).manual_seed(snake_case__  )
									lowercase_	:   List[Any]  				=     {
									    """prompt""": """A painting of a squirrel eating a burger""",
									    """image""": image,
									    """generator""": generator,
									    """num_inference_steps""": 2,
									    """guidance_scale""": 5.0,
									    """output_type""": """numpy""",
									    """strength""": 0.75,
									}
									return inputs






		def 						snake_case__				(							self  )       -> Any:






									"""simple docstring"""
									lowercase_	:   List[Any]  				=     """cpu"""  # ensure determinism for the device-dependent torch.Generator
									lowercase_	:   List[str]  				=     self.get_dummy_components()
									lowercase_	:   Any  				=     StableDiffusionXLImgaImgPipeline(**snake_case__  )
									lowercase_	:   Optional[int]  				=     sd_pipe.to(snake_case__  )
									sd_pipe.set_progress_bar_config(disable=snake_case__  )

									lowercase_	:   List[Any]  				=     self.get_dummy_inputs(snake_case__  )
									lowercase_	:   int  				=     sd_pipe(**snake_case__  ).images
									lowercase_	:   Optional[Any]  				=     image[0, -3:, -3:, -1]

									assert image.shape == (1, 32, 32, 3)

									lowercase_	:   List[str]  				=     np.array([0.4656, 0.4840, 0.4439, 0.6698, 0.5574, 0.4524, 0.5799, 0.5943, 0.5165]  )

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






		def 						snake_case__				(							self  )       -> List[Any]:






									"""simple docstring"""
									super().test_attention_slicing_forward_pass(expected_max_diff=3E-3  )






		def 						snake_case__				(							self  )       -> Dict:






									"""simple docstring"""
									super().test_inference_batch_single_identical(expected_max_diff=3E-3  )






		def 						snake_case__				(							self  )       -> List[str]:






									"""simple docstring"""
									pass






		def 						snake_case__				(							self  )       -> Optional[int]:






									"""simple docstring"""
									lowercase_	:   str  				=     self.get_dummy_components()
									lowercase_	:   int  				=     StableDiffusionXLImgaImgPipeline(**snake_case__  )
									lowercase_	:   str  				=     sd_pipe.to(snake_case__  )
									lowercase_	:   List[Any]  				=     sd_pipe.to(snake_case__  )
									sd_pipe.set_progress_bar_config(disable=snake_case__  )

									# forward without prompt embeds
									lowercase_	:   Any  				=     self.get_dummy_inputs(snake_case__  )
									lowercase_	:   str  				=     3 * ["""this is a negative prompt"""]
									lowercase_	:   List[str]  				=     negative_prompt
									lowercase_	:   Dict  				=     3 * [inputs["""prompt"""]]

									lowercase_	:   Union[str, Any]  				=     sd_pipe(**snake_case__  )
									lowercase_	:   Union[str, Any]  				=     output.images[0, -3:, -3:, -1]

									# forward with prompt embeds
									lowercase_	:   Optional[int]  				=     self.get_dummy_inputs(snake_case__  )
									lowercase_	:   str  				=     3 * ["""this is a negative prompt"""]
									lowercase_	:   List[Any]  				=     3 * [inputs.pop("""prompt"""  )]

									(
									    (
									    lowercase_
									)				,		(
									    lowercase_
									)				,		(
									    lowercase_
									)				,		(
									    lowercase_
									)				,		
									)	:   Any  				=     sd_pipe.encode_prompt(snake_case__,   negative_prompt=snake_case__  )

									lowercase_	:   Any  				=     sd_pipe(
									    **snake_case__,   prompt_embeds=snake_case__,   negative_prompt_embeds=snake_case__,   pooled_prompt_embeds=snake_case__,   negative_pooled_prompt_embeds=snake_case__,   )
									lowercase_	:   Union[str, Any]  				=     output.images[0, -3:, -3:, -1]

									# make sure that it's equal
									assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()  ).max() < 1E-4




@slow
@require_torch_gpu
class     UpperCamelCase__					(     unittest.TestCase				):






		'''simple docstring'''






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






									"""simple docstring"""
									super().tearDown()
									gc.collect()
									torch.cuda.empty_cache()






		def 						snake_case__				(							self,   snake_case__,   snake_case__="cpu",   snake_case__=torch.floataa,   snake_case__=0  )       -> List[str]:






									"""simple docstring"""
									lowercase_	:   List[Any]  				=     torch.Generator(device=snake_case__  ).manual_seed(snake_case__  )
									lowercase_	:   Optional[Any]  				=     np.random.RandomState(snake_case__  ).standard_normal((1, 4, 64, 64)  )
									lowercase_	:   Tuple  				=     torch.from_numpy(snake_case__  ).to(device=snake_case__,   dtype=snake_case__  )
									lowercase_	:   int  				=     {
									    """prompt""": """a photograph of an astronaut riding a horse""",
									    """latents""": latents,
									    """generator""": generator,
									    """num_inference_steps""": 3,
									    """guidance_scale""": 7.5,
									    """output_type""": """numpy""",
									}
									return inputs






		def 						snake_case__				(							self  )       -> Optional[Any]:






									"""simple docstring"""
									lowercase_	:   Optional[int]  				=     DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base"""  )
									pipe.to(snake_case__  )
									pipe.set_progress_bar_config(disable=snake_case__  )

									lowercase_	:   Union[str, Any]  				=     self.get_inputs(snake_case__  )
									lowercase_	:   Optional[int]  				=     pipe(**snake_case__  ).images
									lowercase_	:   Optional[Any]  				=     image[0, -3:, -3:, -1].flatten()

									assert image.shape == (1, 5_12, 5_12, 3)
									lowercase_	:   int  				=     np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506]  )
									assert np.abs(image_slice - expected_slice  ).max() < 7E-3






from __future__ import annotations

from math import gcd





def  __magic_name__  (				lowercase				,       lowercase = 2				,       lowercase = 1				,       lowercase = 3				,       )				-> int | None:

							"""simple docstring"""



							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(lowercase				,       lowercase				,       lowercase				) -> int:
														return (pow(lowercase				,       2				) + step) % modulus

							for _ in range(lowercase				):
														# These track the position within the cycle detection logic.
														lowercase_	:   List[Any]  				=     seed
														lowercase_	:   Any  				=     seed

														while True:
																					# At each iteration, the tortoise moves one step and the hare moves two.
																					lowercase_	:   List[str]  				=     rand_fn(lowercase				,       lowercase				,       lowercase				)
																					lowercase_	:   str  				=     rand_fn(lowercase				,       lowercase				,       lowercase				)
																					lowercase_	:   Any  				=     rand_fn(lowercase				,       lowercase				,       lowercase				)

																					# 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``.
																					lowercase_	:   Tuple  				=     gcd(hare - tortoise				,       lowercase				)

																					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.
														lowercase_	:   int  				=     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

							UpperCAmelCase_							=				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""",
							)
							UpperCAmelCase_							=				parser.parse_args()

							UpperCAmelCase_							=				pollard_rho(args.num, attempts=args.attempts)
							if divisor is None:
														print(F'''{args.num} is probably prime''')
							else:
														UpperCAmelCase_							=				args.num // divisor
														print(F'''{args.num} = {divisor} * {quotient}''')