





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 		SCREAMING_SNAKE_CASE__				(       unittest.TestCase  ):


      def    a (self       :      Union[str, Any]      ):





         """simple docstring"""



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


      @property
      def    a (self       :      str      ):





         """simple docstring"""



         __snake_case							       =   1
         __snake_case							       =   3
         __snake_case							       =   (32, 32)

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


      @property
      def    a (self       :      str      ):





         """simple docstring"""



         torch.manual_seed(0      )
         __snake_case							       =   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    a (self       :      Any      ):





         """simple docstring"""



         torch.manual_seed(0      )
         __snake_case							       =   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    a (self       :      Tuple      ):





         """simple docstring"""



         torch.manual_seed(0      )
         __snake_case							       =   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(__lowercase      )


      @property
      def    a (self       :      Optional[int]      ):





         """simple docstring"""



         def extract(*a__       :      str				,			**a__       :      Any      ):

            class 		SCREAMING_SNAKE_CASE__				:


                  def __init__(self       :      List[str]      ):





                     """simple docstring"""



                     __snake_case							       =   torch.ones([0]      )


                  def    a (self       :      Tuple				,			a__       :      str      ):





                     """simple docstring"""



                     self.pixel_values.to(__lowercase      )
                     return self






            return Out()

         return extract


      def    a (self       :      Dict      ):





         """simple docstring"""



         __snake_case							       =   '''cpu'''  # ensure determinism for the device-dependent torch.Generator
         __snake_case							       =   self.dummy_cond_unet
         __snake_case							       =   PNDMScheduler(skip_prk_steps=__lowercase      )
         __snake_case							       =   self.dummy_vae
         __snake_case							       =   self.dummy_text_encoder
         __snake_case							       =   XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta'''      )
         __snake_case							       =   77

         __snake_case							       =   self.dummy_image.to(__lowercase      )
         __snake_case							       =   init_image / 2 + 0.5

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

         __snake_case							       =   '''A painting of a squirrel eating a burger'''
         __snake_case							       =   torch.Generator(device=__lowercase      ).manual_seed(0      )
         __snake_case							       =   alt_pipe(
             [prompt]				,			generator=__lowercase				,			guidance_scale=6.0				,			num_inference_steps=2				,			output_type='''np'''				,			image=__lowercase				,			)

         __snake_case							       =   output.images

         __snake_case							       =   torch.Generator(device=__lowercase      ).manual_seed(0      )
         __snake_case							       =   alt_pipe(
             [prompt]				,			generator=__lowercase				,			guidance_scale=6.0				,			num_inference_steps=2				,			output_type='''np'''				,			image=__lowercase				,			return_dict=__lowercase				,			)[0]

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

         assert image.shape == (1, 32, 32, 3)
         __snake_case							       =   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    a (self       :      int      ):





         """simple docstring"""



         __snake_case							       =   self.dummy_cond_unet
         __snake_case							       =   PNDMScheduler(skip_prk_steps=__lowercase      )
         __snake_case							       =   self.dummy_vae
         __snake_case							       =   self.dummy_text_encoder
         __snake_case							       =   XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta'''      )
         __snake_case							       =   77

         __snake_case							       =   self.dummy_image.to(__lowercase      )

         # put models in fp16
         __snake_case							       =   unet.half()
         __snake_case							       =   vae.half()
         __snake_case							       =   bert.half()

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

         __snake_case							       =   '''A painting of a squirrel eating a burger'''
         __snake_case							       =   torch.manual_seed(0      )
         __snake_case							       =   alt_pipe(
             [prompt]				,			generator=__lowercase				,			num_inference_steps=2				,			output_type='''np'''				,			image=__lowercase				,			).images

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


      @unittest.skipIf(torch_device != '''cuda'''				,			'''This test requires a GPU'''      )
      def    a (self       :      List[Any]      ):





         """simple docstring"""



         __snake_case							       =   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
         __snake_case							       =   init_image.resize((760, 504)      )

         __snake_case							       =   '''BAAI/AltDiffusion'''
         __snake_case							       =   AltDiffusionImgaImgPipeline.from_pretrained(
             __lowercase				,			safety_checker=__lowercase				,			)
         pipe.to(__lowercase      )
         pipe.set_progress_bar_config(disable=__lowercase      )
         pipe.enable_attention_slicing()

         __snake_case							       =   '''A fantasy landscape, trending on artstation'''

         __snake_case							       =   torch.manual_seed(0      )
         __snake_case							       =   pipe(
             prompt=__lowercase				,			image=__lowercase				,			strength=0.7_5				,			guidance_scale=7.5				,			generator=__lowercase				,			output_type='''np'''				,			)
         __snake_case							       =   output.images[0]

         __snake_case							       =   image[255:258, 383:386, -1]

         assert image.shape == (504, 760, 3)
         __snake_case							       =   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 		SCREAMING_SNAKE_CASE__				(       unittest.TestCase  ):


      def    a (self       :      Optional[int]      ):





         """simple docstring"""



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


      def    a (self       :      Optional[int]      ):





         """simple docstring"""



         __snake_case							       =   load_image(
             '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
             '''/img2img/sketch-mountains-input.jpg'''      )
         __snake_case							       =   init_image.resize((768, 512)      )
         __snake_case							       =   load_numpy(
             '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy'''      )

         __snake_case							       =   '''BAAI/AltDiffusion'''
         __snake_case							       =   AltDiffusionImgaImgPipeline.from_pretrained(
             __lowercase				,			safety_checker=__lowercase				,			)
         pipe.to(__lowercase      )
         pipe.set_progress_bar_config(disable=__lowercase      )
         pipe.enable_attention_slicing()

         __snake_case							       =   '''A fantasy landscape, trending on artstation'''

         __snake_case							       =   torch.manual_seed(0      )
         __snake_case							       =   pipe(
             prompt=__lowercase				,			image=__lowercase				,			strength=0.7_5				,			guidance_scale=7.5				,			generator=__lowercase				,			output_type='''np'''				,			)
         __snake_case							       =   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





def 	lowerCAmelCase       (						lowerCAmelCase_ = 10**9       )->       int:
				lowerCAmelCase_       :					List[Any]			 = 1
				lowerCAmelCase_       :					Optional[int]			 = 2

				lowerCAmelCase_       :					Any			 = 0
				lowerCAmelCase_       :					str			 = 0
				lowerCAmelCase_       :					str			 = 0
				while perimeter <= max_perimeter:
								perimeters_sum += perimeter

								prev_value += 2 * value
								value += prev_value

								lowerCAmelCase_       :					Any			 = 2 * value + 2 if i % 2 == 0 else 2 * value - 2
								i += 1

				return perimeters_sum


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