





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      lowercase__    (							__A     ,					__A     ,					unittest.TestCase  ):
  __UpperCamelCase	     =  StableDiffusionXLImgaImgPipeline
  __UpperCamelCase	     =  TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""}
  __UpperCamelCase	     =  PipelineTesterMixin.required_optional_params - {"""latents"""}
  __UpperCamelCase	     =  TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
  __UpperCamelCase	     =  IMAGE_TO_IMAGE_IMAGE_PARAMS
  __UpperCamelCase	     =  IMAGE_TO_IMAGE_IMAGE_PARAMS







  def 	UpperCAmelCase__		(	self						):
       torch.manual_seed(0						)
       lowerCAmelCase_					:       List[Any]    =		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=_lowercase    ,						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    ,						)
       lowerCAmelCase_					:       List[Any]    =		EulerDiscreteScheduler(
           beta_start=0.0_0085    ,						beta_end=0.012    ,						steps_offset=1    ,						beta_schedule="""scaled_linear"""    ,						timestep_spacing="""leading"""    ,						)
       torch.manual_seed(0						)
       lowerCAmelCase_					:       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=128    ,						)
       torch.manual_seed(0						)
       lowerCAmelCase_					:       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=1_000    ,						hidden_act="""gelu"""    ,						projection_dim=32    ,						)
       lowerCAmelCase_					:       Dict    =		CLIPTextModel(_lowercase						)
       lowerCAmelCase_					:       Optional[Any]    =		CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""    ,						local_files_only=_lowercase						)

       lowerCAmelCase_					:       Optional[int]    =		CLIPTextModelWithProjection(_lowercase						)
       lowerCAmelCase_					:       List[Any]    =		CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip"""    ,						local_files_only=_lowercase						)

       lowerCAmelCase_					:       List[Any]    =		{
           """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 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase=0						):
       lowerCAmelCase_					:       List[Any]    =		floats_tensor((1, 3, 32, 32)    ,						rng=random.Random(_lowercase						)						).to(_lowercase						)
       lowerCAmelCase_					:       Optional[int]    =		image / 2 + 0.5
       if str(_lowercase						).startswith("""mps"""						):
            lowerCAmelCase_					:       Any    =		torch.manual_seed(_lowercase						)
       else:
            lowerCAmelCase_					:       str    =		torch.Generator(device=_lowercase						).manual_seed(_lowercase						)
       lowerCAmelCase_					:       Optional[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 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Union[str, Any]    =		"""cpu"""  # ensure determinism for the device-dependent torch.Generator
       lowerCAmelCase_					:       Any    =		self.get_dummy_components()
       lowerCAmelCase_					:       Any    =		StableDiffusionXLImgaImgPipeline(**_lowercase						)
       lowerCAmelCase_					:       List[str]    =		sd_pipe.to(_lowercase						)
       sd_pipe.set_progress_bar_config(disable=_lowercase						)

       lowerCAmelCase_					:       Dict    =		self.get_dummy_inputs(_lowercase						)
       lowerCAmelCase_					:       List[str]    =		sd_pipe(**_lowercase						).images
       lowerCAmelCase_					:       List[Any]    =		image[0, -3:, -3:, -1]

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

       lowerCAmelCase_					:       Optional[Any]    =		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 	UpperCAmelCase__		(	self						):
       super().test_attention_slicing_forward_pass(expected_max_diff=3e-3						)







  def 	UpperCAmelCase__		(	self						):
       super().test_inference_batch_single_identical(expected_max_diff=3e-3						)







  def 	UpperCAmelCase__		(	self						):
       pass







  def 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       Optional[Any]    =		self.get_dummy_components()
       lowerCAmelCase_					:       Optional[Any]    =		StableDiffusionXLImgaImgPipeline(**_lowercase						)
       lowerCAmelCase_					:       Union[str, Any]    =		sd_pipe.to(_lowercase						)
       lowerCAmelCase_					:       Union[str, Any]    =		sd_pipe.to(_lowercase						)
       sd_pipe.set_progress_bar_config(disable=_lowercase						)

       # forward without prompt embeds
       lowerCAmelCase_					:       str    =		self.get_dummy_inputs(_lowercase						)
       lowerCAmelCase_					:       Union[str, Any]    =		3 * ["""this is a negative prompt"""]
       lowerCAmelCase_					:       Tuple    =		negative_prompt
       lowerCAmelCase_					:       Dict    =		3 * [inputs["""prompt"""]]

       lowerCAmelCase_					:       Optional[int]    =		sd_pipe(**_lowercase						)
       lowerCAmelCase_					:       Tuple    =		output.images[0, -3:, -3:, -1]

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

       (
           (
           lowerCAmelCase_
       )   ,  (
           lowerCAmelCase_
       )   ,  (
           lowerCAmelCase_
       )   ,  (
           lowerCAmelCase_
       )   ,  
       )					:       Dict    =		sd_pipe.encode_prompt(_lowercase    ,						negative_prompt=_lowercase						)

       lowerCAmelCase_					:       Union[str, Any]    =		sd_pipe(
           **_lowercase    ,						prompt_embeds=_lowercase    ,						negative_prompt_embeds=_lowercase    ,						pooled_prompt_embeds=_lowercase    ,						negative_pooled_prompt_embeds=_lowercase    ,						)
       lowerCAmelCase_					:       Dict    =		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      lowercase__    (							unittest.TestCase  ):







  def 	UpperCAmelCase__		(	self						):
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()







  def 	UpperCAmelCase__		(	self    ,						_lowercase    ,						_lowercase="cpu"    ,						_lowercase=torch.floataa    ,						_lowercase=0						):
       lowerCAmelCase_					:       str    =		torch.Generator(device=_lowercase						).manual_seed(_lowercase						)
       lowerCAmelCase_					:       Optional[int]    =		np.random.RandomState(_lowercase						).standard_normal((1, 4, 64, 64)						)
       lowerCAmelCase_					:       List[str]    =		torch.from_numpy(_lowercase						).to(device=_lowercase    ,						dtype=_lowercase						)
       lowerCAmelCase_					:       Any    =		{
           """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 	UpperCAmelCase__		(	self						):
       lowerCAmelCase_					:       str    =		DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base"""						)
       pipe.to(_lowercase						)
       pipe.set_progress_bar_config(disable=_lowercase						)

       lowerCAmelCase_					:       Dict    =		self.get_inputs(_lowercase						)
       lowerCAmelCase_					:       List[str]    =		pipe(**_lowercase						).images
       lowerCAmelCase_					:       Optional[Any]    =		image[0, -3:, -3:, -1].flatten()

       assert image.shape == (1, 512, 512, 3)
       lowerCAmelCase_					:       int    =		np.array([0.4_9493, 0.4_7896, 0.4_0798, 0.5_4214, 0.5_3212, 0.4_8202, 0.4_7656, 0.4_6329, 0.4_8506]						)
       assert np.abs(image_slice - expected_slice						).max() < 7e-3







def 							_lowerCAmelCase (  _a   :					int					,   _a   :					bool = False			)	->			bool:
     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_31_70_44_06_46_79_88_73_85_96_19_81 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
     lowerCAmelCase_					:       Optional[int]    =		[
         20_47,
         1_37_36_53,
         25_32_60_01,
         32_15_03_17_51,
         2_15_23_02_89_87_47,
         3_47_47_49_66_03_83,
         3_41_55_00_71_72_83_21,
         1,
         3_82_51_23_05_65_46_41_30_51,
         1,
         1,
         31_86_65_85_78_34_03_11_51_16_74_61,
         3_31_70_44_06_46_79_88_73_85_96_19_81,
     ]

     lowerCAmelCase_					:       Dict    =		[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
     for idx, _p in enumerate(_a					,   1			):
          if n < _p:
               # then we have our last prime to check
               lowerCAmelCase_					:       str    =		primes[:idx]
               break
     lowerCAmelCase_   ,  lowerCAmelCase_					:       Optional[Any]    =		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:
          lowerCAmelCase_					:       Tuple    =		False
          for r in range(_a			):
               lowerCAmelCase_					:       Tuple    =		pow(_a					,   d * 2**r					,   _a			)
               # see article for analysis explanation for m
               if (r == 0 and m == 1) or ((m + 1) % n == 0):
                    lowerCAmelCase_					:       List[Any]    =		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 							_lowerCAmelCase (  )	->			None:
     assert not miller_rabin(5_61			)
     assert miller_rabin(5_63			)
     # 2047

     assert not miller_rabin(83_82_01			)
     assert miller_rabin(83_82_07			)
     # 1_373_653

     assert not miller_rabin(17_31_60_01			)
     assert miller_rabin(17_31_60_17			)
     # 25_326_001

     assert not miller_rabin(30_78_38_66_41			)
     assert miller_rabin(30_78_38_66_53			)
     # 3_215_031_751

     assert not miller_rabin(1_71_30_45_57_48_01			)
     assert miller_rabin(1_71_30_45_57_48_19			)
     # 2_152_302_898_747

     assert not miller_rabin(2_77_97_99_72_83_07			)
     assert miller_rabin(2_77_97_99_72_83_27			)
     # 3_474_749_660_383

     assert not miller_rabin(1_13_85_00_23_90_94_41			)
     assert miller_rabin(1_13_85_00_23_90_95_27			)
     # 341_550_071_728_321

     assert not miller_rabin(1_27_50_41_01_88_48_80_43_51			)
     assert miller_rabin(1_27_50_41_01_88_48_80_43_91			)
     # 3_825_123_056_546_413_051

     assert not miller_rabin(7_96_66_46_44_58_50_77_87_79_18_67			)
     assert miller_rabin(7_96_66_46_44_58_50_77_87_79_19_51			)
     # 318_665_857_834_031_151_167_461

     assert not miller_rabin(55_28_40_67_74_46_64_78_97_66_03_33			)
     assert miller_rabin(55_28_40_67_74_46_64_78_97_66_03_59			)
     # 3_317_044_064_679_887_385_961_981
     # upper limit for probabilistic test


if __name__ == "__main__":
      test_miller_rabin()
