



def      __lowercase(						UpperCAmelCase__ , UpperCAmelCase__ = False			):


      """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 > 3317044064679887385961981 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             =		[
          2047,
          1373653,
          25326001,
          3215031751,
          2152302898747,
          3474749660383,
          341550071728321,
          1,
          3825123056546413051,
          1,
          1,
          318665857834031151167461,
          3317044064679887385961981,
      ]

      lowerCamelCase             =		[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41]
      for idx, _p in enumerate(UpperCAmelCase__ , 1			):
            if n < _p:
                  # then we have our last prime to check
                  lowerCamelCase             =		primes[:idx]
                  break
      lowerCamelCase      ,				lowerCamelCase             =		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             =		False
            for r in range(UpperCAmelCase__			):
                  lowerCamelCase             =		pow(UpperCAmelCase__ , d * 2**r , UpperCAmelCase__			)
                  # see article for analysis explanation for m
                  if (r == 0 and m == 1) or ((m + 1) % n == 0):
                        lowerCamelCase             =		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      __lowercase(						):


      """simple docstring"""



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

      assert not miller_rabin(838201			)
      assert miller_rabin(838207			)
      # 1_373_653

      assert not miller_rabin(17316001			)
      assert miller_rabin(17316017			)
      # 25_326_001

      assert not miller_rabin(3078386641			)
      assert miller_rabin(3078386653			)
      # 3_215_031_751

      assert not miller_rabin(1713045574801			)
      assert miller_rabin(1713045574819			)
      # 2_152_302_898_747

      assert not miller_rabin(2779799728307			)
      assert miller_rabin(2779799728327			)
      # 3_474_749_660_383

      assert not miller_rabin(113850023909441			)
      assert miller_rabin(113850023909527			)
      # 341_550_071_728_321

      assert not miller_rabin(1275041018848804351			)
      assert miller_rabin(1275041018848804391			)
      # 3_825_123_056_546_413_051

      assert not miller_rabin(79666464458507787791867			)
      assert miller_rabin(79666464458507787791951			)
      # 318_665_857_834_031_151_167_461

      assert not miller_rabin(552840677446647897660333			)
      assert miller_rabin(552840677446647897660359			)
      # 3_317_044_064_679_887_385_961_981
      # upper limit for probabilistic test


if __name__ == "__main__":
     test_miller_rabin()




import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()





class  lowerCamelCase__	(    unittest.TestCase):
     """simple docstring"""



     def     _a   (self     ):






           '''simple docstring'''



           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()







     @property
     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		1
           lowerCamelCase             =		3
           lowerCamelCase             =		(32, 32)

           lowerCamelCase             =		floats_tensor((batch_size, num_channels) + sizes					,      rng=random.Random(0     )     ).to(__a     )
           return image







     @property
     def     _a   (self     ):






           '''simple docstring'''



           torch.manual_seed(0     )
           lowerCamelCase             =		UNetaDConditionModel(
               block_out_channels=(32, 32, 64)					,      layers_per_block=2					,      sample_size=32					,      in_channels=7					,      out_channels=4					,      down_block_types=("DownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D")					,      up_block_types=("CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "UpBlock2D")					,      cross_attention_dim=32					,      attention_head_dim=8					,      use_linear_projection=__a					,      only_cross_attention=(True, True, False)					,      num_class_embeds=1_00					,      )
           return model







     @property
     def     _a   (self     ):






           '''simple docstring'''



           torch.manual_seed(0     )
           lowerCamelCase             =		AutoencoderKL(
               block_out_channels=[32, 32, 64]					,      in_channels=3					,      out_channels=3					,      down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D"]					,      up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"]					,      latent_channels=4					,      )
           return model







     @property
     def     _a   (self     ):






           '''simple docstring'''



           torch.manual_seed(0     )
           lowerCamelCase             =		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=5_12					,      )
           return CLIPTextModel(__a     )







     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		"cpu"  # ensure determinism for the device-dependent torch.Generator
           lowerCamelCase             =		self.dummy_cond_unet_upscale
           lowerCamelCase             =		DDPMScheduler()
           lowerCamelCase             =		DDIMScheduler(prediction_type="v_prediction"     )
           lowerCamelCase             =		self.dummy_vae
           lowerCamelCase             =		self.dummy_text_encoder
           lowerCamelCase             =		CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"     )

           lowerCamelCase             =		self.dummy_image.cpu().permute(0					,      2					,      3					,      1     )[0]
           lowerCamelCase             =		Image.fromarray(np.uinta(__a     )     ).convert("RGB"     ).resize((64, 64)     )

           # make sure here that pndm scheduler skips prk
           lowerCamelCase             =		StableDiffusionUpscalePipeline(
               unet=__a					,      low_res_scheduler=__a					,      scheduler=__a					,      vae=__a					,      text_encoder=__a					,      tokenizer=__a					,      max_noise_level=3_50					,      )
           lowerCamelCase             =		sd_pipe.to(__a     )
           sd_pipe.set_progress_bar_config(disable=__a     )

           lowerCamelCase             =		"A painting of a squirrel eating a burger"
           lowerCamelCase             =		torch.Generator(device=__a     ).manual_seed(0     )
           lowerCamelCase             =		sd_pipe(
               [prompt]					,      image=__a					,      generator=__a					,      guidance_scale=6.0					,      noise_level=20					,      num_inference_steps=2					,      output_type="np"					,      )

           lowerCamelCase             =		output.images

           lowerCamelCase             =		torch.Generator(device=__a     ).manual_seed(0     )
           lowerCamelCase             =		sd_pipe(
               [prompt]					,      image=__a					,      generator=__a					,      guidance_scale=6.0					,      noise_level=20					,      num_inference_steps=2					,      output_type="np"					,      return_dict=__a					,      )[0]

           lowerCamelCase             =		image[0, -3:, -3:, -1]
           lowerCamelCase             =		image_from_tuple[0, -3:, -3:, -1]

           lowerCamelCase             =		low_res_image.size[0] * 4
           assert image.shape == (1, expected_height_width, expected_height_width, 3)
           lowerCamelCase             =		np.array([0.3113, 0.3910, 0.4272, 0.4859, 0.5061, 0.4652, 0.5362, 0.5715, 0.5661]     )

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







     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		"cpu"  # ensure determinism for the device-dependent torch.Generator
           lowerCamelCase             =		self.dummy_cond_unet_upscale
           lowerCamelCase             =		DDPMScheduler()
           lowerCamelCase             =		DDIMScheduler(prediction_type="v_prediction"     )
           lowerCamelCase             =		self.dummy_vae
           lowerCamelCase             =		self.dummy_text_encoder
           lowerCamelCase             =		CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"     )

           lowerCamelCase             =		self.dummy_image.cpu().permute(0					,      2					,      3					,      1     )[0]
           lowerCamelCase             =		Image.fromarray(np.uinta(__a     )     ).convert("RGB"     ).resize((64, 64)     )

           # make sure here that pndm scheduler skips prk
           lowerCamelCase             =		StableDiffusionUpscalePipeline(
               unet=__a					,      low_res_scheduler=__a					,      scheduler=__a					,      vae=__a					,      text_encoder=__a					,      tokenizer=__a					,      max_noise_level=3_50					,      )
           lowerCamelCase             =		sd_pipe.to(__a     )
           sd_pipe.set_progress_bar_config(disable=__a     )

           lowerCamelCase             =		"A painting of a squirrel eating a burger"
           lowerCamelCase             =		sd_pipe(
               2 * [prompt]					,      image=2 * [low_res_image]					,      guidance_scale=6.0					,      noise_level=20					,      num_inference_steps=2					,      output_type="np"					,      )
           lowerCamelCase             =		output.images
           assert image.shape[0] == 2

           lowerCamelCase             =		torch.Generator(device=__a     ).manual_seed(0     )
           lowerCamelCase             =		sd_pipe(
               [prompt]					,      image=__a					,      generator=__a					,      num_images_per_prompt=2					,      guidance_scale=6.0					,      noise_level=20					,      num_inference_steps=2					,      output_type="np"					,      )
           lowerCamelCase             =		output.images
           assert image.shape[0] == 2







     @unittest.skipIf(torch_device != "cuda"					,      "This test requires a GPU"     )
     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		self.dummy_cond_unet_upscale
           lowerCamelCase             =		DDPMScheduler()
           lowerCamelCase             =		DDIMScheduler(prediction_type="v_prediction"     )
           lowerCamelCase             =		self.dummy_vae
           lowerCamelCase             =		self.dummy_text_encoder
           lowerCamelCase             =		CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"     )

           lowerCamelCase             =		self.dummy_image.cpu().permute(0					,      2					,      3					,      1     )[0]
           lowerCamelCase             =		Image.fromarray(np.uinta(__a     )     ).convert("RGB"     ).resize((64, 64)     )

           # put models in fp16, except vae as it overflows in fp16
           lowerCamelCase             =		unet.half()
           lowerCamelCase             =		text_encoder.half()

           # make sure here that pndm scheduler skips prk
           lowerCamelCase             =		StableDiffusionUpscalePipeline(
               unet=__a					,      low_res_scheduler=__a					,      scheduler=__a					,      vae=__a					,      text_encoder=__a					,      tokenizer=__a					,      max_noise_level=3_50					,      )
           lowerCamelCase             =		sd_pipe.to(__a     )
           sd_pipe.set_progress_bar_config(disable=__a     )

           lowerCamelCase             =		"A painting of a squirrel eating a burger"
           lowerCamelCase             =		torch.manual_seed(0     )
           lowerCamelCase             =		sd_pipe(
               [prompt]					,      image=__a					,      generator=__a					,      num_inference_steps=2					,      output_type="np"					,      ).images

           lowerCamelCase             =		low_res_image.size[0] * 4
           assert image.shape == (1, expected_height_width, expected_height_width, 3)





@slow
@require_torch_gpu
class  lowerCamelCase__	(    unittest.TestCase):
     """simple docstring"""



     def     _a   (self     ):






           '''simple docstring'''



           super().tearDown()
           gc.collect()
           torch.cuda.empty_cache()







     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		load_image(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
               "/sd2-upscale/low_res_cat.png"     )
           lowerCamelCase             =		load_numpy(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale"
               "/upsampled_cat.npy"     )

           lowerCamelCase             =		"stabilityai/stable-diffusion-x4-upscaler"
           lowerCamelCase             =		StableDiffusionUpscalePipeline.from_pretrained(__a     )
           pipe.to(__a     )
           pipe.set_progress_bar_config(disable=__a     )
           pipe.enable_attention_slicing()

           lowerCamelCase             =		"a cat sitting on a park bench"

           lowerCamelCase             =		torch.manual_seed(0     )
           lowerCamelCase             =		pipe(
               prompt=__a					,      image=__a					,      generator=__a					,      output_type="np"					,      )
           lowerCamelCase             =		output.images[0]

           assert image.shape == (5_12, 5_12, 3)
           assert np.abs(expected_image - image     ).max() < 1E-3







     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		load_image(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
               "/sd2-upscale/low_res_cat.png"     )
           lowerCamelCase             =		load_numpy(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale"
               "/upsampled_cat_fp16.npy"     )

           lowerCamelCase             =		"stabilityai/stable-diffusion-x4-upscaler"
           lowerCamelCase             =		StableDiffusionUpscalePipeline.from_pretrained(
               __a					,      torch_dtype=torch.floataa					,      )
           pipe.to(__a     )
           pipe.set_progress_bar_config(disable=__a     )
           pipe.enable_attention_slicing()

           lowerCamelCase             =		"a cat sitting on a park bench"

           lowerCamelCase             =		torch.manual_seed(0     )
           lowerCamelCase             =		pipe(
               prompt=__a					,      image=__a					,      generator=__a					,      output_type="np"					,      )
           lowerCamelCase             =		output.images[0]

           assert image.shape == (5_12, 5_12, 3)
           assert np.abs(expected_image - image     ).max() < 5E-1







     def     _a   (self     ):






           '''simple docstring'''



           torch.cuda.empty_cache()
           torch.cuda.reset_max_memory_allocated()
           torch.cuda.reset_peak_memory_stats()

           lowerCamelCase             =		load_image(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
               "/sd2-upscale/low_res_cat.png"     )

           lowerCamelCase             =		"stabilityai/stable-diffusion-x4-upscaler"
           lowerCamelCase             =		StableDiffusionUpscalePipeline.from_pretrained(
               __a					,      torch_dtype=torch.floataa					,      )
           pipe.to(__a     )
           pipe.set_progress_bar_config(disable=__a     )
           pipe.enable_attention_slicing(1     )
           pipe.enable_sequential_cpu_offload()

           lowerCamelCase             =		"a cat sitting on a park bench"

           lowerCamelCase             =		torch.manual_seed(0     )
           lowerCamelCase             =		pipe(
               prompt=__a					,      image=__a					,      generator=__a					,      num_inference_steps=5					,      output_type="np"					,      )

           lowerCamelCase             =		torch.cuda.max_memory_allocated()
           # make sure that less than 2.9 GB is allocated
           assert mem_bytes < 2.9 * 10**9