






import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
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 				UpperCAmelCase_  (		unittest.TestCase		):




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




     @property
     def   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  Optional[Any]				      =			1
          UpperCAmelCase__      :  Tuple				      =			3
          UpperCAmelCase__      :  List[str]				      =			(32, 32)

          UpperCAmelCase__      :  List[Any]				      =			floats_tensor((batch_size, num_channels) + sizes	,						rng=random.Random(0		)		).to(UpperCamelCase__		)
          return image




     @property
     def   __UpperCAmelCase  (				self		):
          torch.manual_seed(0		)
          UpperCAmelCase__      :  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""")	,						cross_attention_dim=32	,						)
          return model




     @property
     def   __UpperCAmelCase  (				self		):
          torch.manual_seed(0		)
          UpperCAmelCase__      :  List[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	,						)
          return model




     @property
     def   __UpperCAmelCase  (				self		):
          torch.manual_seed(0		)
          UpperCAmelCase__      :  Optional[int]				      =			RobertaSeriesConfig(
              hidden_size=32	,						project_dim=32	,						intermediate_size=37	,						layer_norm_eps=1e-05	,						num_attention_heads=4	,						num_hidden_layers=5	,						pad_token_id=1	,						vocab_size=5006	,						)
          return RobertaSeriesModelWithTransformation(UpperCamelCase__		)




     @property
     def   __UpperCAmelCase  (				self		):


          def extract(*_lowerCAmelCase	,						**_lowerCAmelCase		):







               class 				UpperCAmelCase_  :




                    def __init__(				self		):
                         UpperCAmelCase__      :  Any				      =			torch.ones([0]		)




                    def   __UpperCAmelCase  (				self	,						_lowerCAmelCase		):
                         self.pixel_values.to(UpperCamelCase__		)
                         return self



               return Out()

          return extract




     def   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  int				      =			"""cpu"""  # ensure determinism for the device-dependent torch.Generator
          UpperCAmelCase__      :  List[Any]				      =			self.dummy_cond_unet
          UpperCAmelCase__      :  Union[str, Any]				      =			PNDMScheduler(skip_prk_steps=UpperCamelCase__		)
          UpperCAmelCase__      :  List[Any]				      =			self.dummy_vae
          UpperCAmelCase__      :  List[Any]				      =			self.dummy_text_encoder
          UpperCAmelCase__      :  Union[str, Any]				      =			XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""		)
          UpperCAmelCase__      :  Any				      =			77

          UpperCAmelCase__      :  List[str]				      =			self.dummy_image.to(UpperCamelCase__		)
          UpperCAmelCase__      :  Dict				      =			init_image / 2 + 0.5

          # make sure here that pndm scheduler skips prk
          UpperCAmelCase__      :  str				      =			AltDiffusionImgaImgPipeline(
              unet=UpperCamelCase__	,						scheduler=UpperCamelCase__	,						vae=UpperCamelCase__	,						text_encoder=UpperCamelCase__	,						tokenizer=UpperCamelCase__	,						safety_checker=UpperCamelCase__	,						feature_extractor=self.dummy_extractor	,						)
          UpperCAmelCase__      :  Any				      =			VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor	,						do_normalize=UpperCamelCase__		)
          UpperCAmelCase__      :  str				      =			alt_pipe.to(UpperCamelCase__		)
          alt_pipe.set_progress_bar_config(disable=UpperCamelCase__		)

          UpperCAmelCase__      :  List[str]				      =			"""A painting of a squirrel eating a burger"""
          UpperCAmelCase__      :  List[str]				      =			torch.Generator(device=UpperCamelCase__		).manual_seed(0		)
          UpperCAmelCase__      :  Union[str, Any]				      =			alt_pipe(
              [prompt]	,						generator=UpperCamelCase__	,						guidance_scale=6.0	,						num_inference_steps=2	,						output_type="""np"""	,						image=UpperCamelCase__	,						)

          UpperCAmelCase__      :  List[str]				      =			output.images

          UpperCAmelCase__      :  List[str]				      =			torch.Generator(device=UpperCamelCase__		).manual_seed(0		)
          UpperCAmelCase__      :  List[Any]				      =			alt_pipe(
              [prompt]	,						generator=UpperCamelCase__	,						guidance_scale=6.0	,						num_inference_steps=2	,						output_type="""np"""	,						image=UpperCamelCase__	,						return_dict=UpperCamelCase__	,						)[0]

          UpperCAmelCase__      :  Dict				      =			image[0, -3:, -3:, -1]
          UpperCAmelCase__      :  Tuple				      =			image_from_tuple[0, -3:, -3:, -1]

          assert image.shape == (1, 32, 32, 3)
          UpperCAmelCase__      :  Tuple				      =			np.array([0.4_4_2_7, 0.3_7_3_1, 0.4_2_4_9, 0.4_9_4_1, 0.4_5_4_6, 0.4_1_4_8, 0.4_1_9_3, 0.4_6_6_6, 0.4_4_9_9]		)

          assert np.abs(image_slice.flatten() - expected_slice		).max() < 5e-3
          assert np.abs(image_from_tuple_slice.flatten() - expected_slice		).max() < 5e-3




     @unittest.skipIf(torch_device != """cuda"""	,						"""This test requires a GPU"""		)
     def   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  Optional[Any]				      =			self.dummy_cond_unet
          UpperCAmelCase__      :  str				      =			PNDMScheduler(skip_prk_steps=UpperCamelCase__		)
          UpperCAmelCase__      :  Dict				      =			self.dummy_vae
          UpperCAmelCase__      :  List[str]				      =			self.dummy_text_encoder
          UpperCAmelCase__      :  List[Any]				      =			XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta"""		)
          UpperCAmelCase__      :  int				      =			77

          UpperCAmelCase__      :  List[str]				      =			self.dummy_image.to(UpperCamelCase__		)

          # put models in fp16
          UpperCAmelCase__      :  Tuple				      =			unet.half()
          UpperCAmelCase__      :  List[str]				      =			vae.half()
          UpperCAmelCase__      :  Optional[int]				      =			bert.half()

          # make sure here that pndm scheduler skips prk
          UpperCAmelCase__      :  List[Any]				      =			AltDiffusionImgaImgPipeline(
              unet=UpperCamelCase__	,						scheduler=UpperCamelCase__	,						vae=UpperCamelCase__	,						text_encoder=UpperCamelCase__	,						tokenizer=UpperCamelCase__	,						safety_checker=UpperCamelCase__	,						feature_extractor=self.dummy_extractor	,						)
          UpperCAmelCase__      :  List[Any]				      =			VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor	,						do_normalize=UpperCamelCase__		)
          UpperCAmelCase__      :  List[Any]				      =			alt_pipe.to(UpperCamelCase__		)
          alt_pipe.set_progress_bar_config(disable=UpperCamelCase__		)

          UpperCAmelCase__      :  Tuple				      =			"""A painting of a squirrel eating a burger"""
          UpperCAmelCase__      :  Optional[int]				      =			torch.manual_seed(0		)
          UpperCAmelCase__      :  Any				      =			alt_pipe(
              [prompt]	,						generator=UpperCamelCase__	,						num_inference_steps=2	,						output_type="""np"""	,						image=UpperCamelCase__	,						).images

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




     @unittest.skipIf(torch_device != """cuda"""	,						"""This test requires a GPU"""		)
     def   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  Tuple				      =			load_image(
              """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
              """/img2img/sketch-mountains-input.jpg"""		)
          # resize to resolution that is divisible by 8 but not 16 or 32
          UpperCAmelCase__      :  List[str]				      =			init_image.resize((760, 504)		)

          UpperCAmelCase__      :  int				      =			"""BAAI/AltDiffusion"""
          UpperCAmelCase__      :  Optional[Any]				      =			AltDiffusionImgaImgPipeline.from_pretrained(
              UpperCamelCase__	,						safety_checker=UpperCamelCase__	,						)
          pipe.to(UpperCamelCase__		)
          pipe.set_progress_bar_config(disable=UpperCamelCase__		)
          pipe.enable_attention_slicing()

          UpperCAmelCase__      :  List[Any]				      =			"""A fantasy landscape, trending on artstation"""

          UpperCAmelCase__      :  Tuple				      =			torch.manual_seed(0		)
          UpperCAmelCase__      :  Optional[int]				      =			pipe(
              prompt=UpperCamelCase__	,						image=UpperCamelCase__	,						strength=0.7_5	,						guidance_scale=7.5	,						generator=UpperCamelCase__	,						output_type="""np"""	,						)
          UpperCAmelCase__      :  Tuple				      =			output.images[0]

          UpperCAmelCase__      :  Optional[Any]				      =			image[255:258, 383:386, -1]

          assert image.shape == (504, 760, 3)
          UpperCAmelCase__      :  str				      =			np.array([0.9_3_5_8, 0.9_3_9_7, 0.9_5_9_9, 0.9_9_0_1, 1.0_0_0_0, 1.0_0_0_0, 0.9_8_8_2, 1.0_0_0_0, 1.0_0_0_0]		)

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







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




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




     def   __UpperCAmelCase  (				self		):
          UpperCAmelCase__      :  Tuple				      =			load_image(
              """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
              """/img2img/sketch-mountains-input.jpg"""		)
          UpperCAmelCase__      :  int				      =			init_image.resize((768, 512)		)
          UpperCAmelCase__      :  List[str]				      =			load_numpy(
              """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy"""		)

          UpperCAmelCase__      :  Any				      =			"""BAAI/AltDiffusion"""
          UpperCAmelCase__      :  Any				      =			AltDiffusionImgaImgPipeline.from_pretrained(
              UpperCamelCase__	,						safety_checker=UpperCamelCase__	,						)
          pipe.to(UpperCamelCase__		)
          pipe.set_progress_bar_config(disable=UpperCamelCase__		)
          pipe.enable_attention_slicing()

          UpperCAmelCase__      :  Dict				      =			"""A fantasy landscape, trending on artstation"""

          UpperCAmelCase__      :  Union[str, Any]				      =			torch.manual_seed(0		)
          UpperCAmelCase__      :  Optional[Any]				      =			pipe(
              prompt=UpperCamelCase__	,						image=UpperCamelCase__	,						strength=0.7_5	,						guidance_scale=7.5	,						generator=UpperCamelCase__	,						output_type="""np"""	,						)
          UpperCAmelCase__      :  Dict				      =			output.images[0]

          assert image.shape == (512, 768, 3)
          # img2img is flaky across GPUs even in fp32, so using MAE here
          assert np.abs(expected_image - image		).max() < 1e-2














'''simple docstring'''







def       __UpperCamelCase					(      lowercase_       :  int = 1_000_000   ):
       """simple docstring"""




       a_						     =			set(range(3   ,       lowercase_   ,       2   )   )
       primes.add(2   )
       for p in range(3   ,       lowercase_   ,       2   ):
              if p not in primes:
                     continue
              primes.difference_update(set(range(p * p   ,       lowercase_   ,       lowercase_   )   )   )

       a_						     =			[float(lowercase_   ) for n in range(limit + 1   )]

       for p in primes:
              for n in range(lowercase_   ,       limit + 1   ,       lowercase_   ):
                     phi[n] *= 1 - 1 / p

       return int(sum(phi[2:]   )   )


if __name__ == "__main__":
  print(f"""{solution() = }""")




