



import gc
import random
import unittest

import torch

from diffusers import (
    IFImgaImgPipeline,
    IFImgaImgSuperResolutionPipeline,
    IFInpaintingPipeline,
    IFInpaintingSuperResolutionPipeline,
    IFPipeline,
    IFSuperResolutionPipeline,
)
from diffusers.models.attention_processor import AttnAddedKVProcessor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
from . import IFPipelineTesterMixin


@skip_mps
class 	lowerCamelCase__	(       _A							,  _A							,  unittest.TestCase):



 """simple docstring"""

 a__					: List[str] =  IFPipeline
 a__					: Optional[Any] =  TEXT_TO_IMAGE_PARAMS - {"width", "height", "latents"}
 a__					: Optional[int] =  TEXT_TO_IMAGE_BATCH_PARAMS
 a__					: Optional[Any] =  PipelineTesterMixin.required_optional_params - {"latents"}

 def     snake_case_      (    self					:					Dict      )   ->	Optional[Any]:
    return self._get_dummy_components()

 def     snake_case_      (    self					:					Any			,						__lowerCAmelCase					:					int			,						__lowerCAmelCase					:					Optional[Any]=0      )   ->	List[str]:
    if str(__lowerCAmelCase      ).startswith('''mps'''      ):
       _A      =       torch.manual_seed(__lowerCAmelCase      )
    else:
       _A      =       torch.Generator(device=__lowerCAmelCase      ).manual_seed(__lowerCAmelCase      )

    _A      =       {
        '''prompt''': '''A painting of a squirrel eating a burger''',
        '''generator''': generator,
        '''num_inference_steps''': 2,
        '''output_type''': '''numpy''',
    }

    return inputs

 def     snake_case_      (    self					:					str      )   ->	Tuple:
    self._test_save_load_optional_components()

 @unittest.skipIf(torch_device != '''cuda'''			,						reason='''float16 requires CUDA'''      )
 def     snake_case_      (    self					:					Union[str, Any]      )   ->	Any:
    # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
    super().test_save_load_floataa(expected_max_diff=1E-1      )

 def     snake_case_      (    self					:					Union[str, Any]      )   ->	List[Any]:
    self._test_attention_slicing_forward_pass(expected_max_diff=1E-2      )

 def     snake_case_      (    self					:					Union[str, Any]      )   ->	Union[str, Any]:
    self._test_save_load_local()

 def     snake_case_      (    self					:					Dict      )   ->	List[Any]:
    self._test_inference_batch_single_identical(
        expected_max_diff=1E-2			,						)

 @unittest.skipIf(
     torch_device != '''cuda''' or not is_xformers_available()			,						reason='''XFormers attention is only available with CUDA and `xformers` installed'''			,						)
 def     snake_case_      (    self					:					Dict      )   ->	List[Any]:
    self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3      )


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



 """simple docstring"""

 def     snake_case_      (    self					:					List[Any]      )   ->	Any:
    # clean up the VRAM after each test
    super().tearDown()
    gc.collect()
    torch.cuda.empty_cache()

 def     snake_case_      (    self					:					Tuple      )   ->	str:
    # if

    _A      =       IFPipeline.from_pretrained('''DeepFloyd/IF-I-XL-v1.0'''			,						variant='''fp16'''			,						torch_dtype=torch.floataa      )

    _A      =       IFSuperResolutionPipeline.from_pretrained(
        '''DeepFloyd/IF-II-L-v1.0'''			,						variant='''fp16'''			,						torch_dtype=torch.floataa			,						text_encoder=__lowerCAmelCase			,						tokenizer=__lowerCAmelCase      )

    # pre compute text embeddings and remove T5 to save memory

    pipe_a.text_encoder.to('''cuda'''      )

    _A  ,    _A      =       pipe_a.encode_prompt('''anime turtle'''			,						device='''cuda'''      )

    del pipe_a.tokenizer
    del pipe_a.text_encoder
    gc.collect()

    _A      =       None
    _A      =       None

    pipe_a.enable_model_cpu_offload()
    pipe_a.enable_model_cpu_offload()

    pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()      )
    pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()      )

    self._test_if(__lowerCAmelCase			,						__lowerCAmelCase			,						__lowerCAmelCase			,						__lowerCAmelCase      )

    pipe_a.remove_all_hooks()
    pipe_a.remove_all_hooks()

    # img2img

    _A      =       IFImgaImgPipeline(**pipe_a.components      )
    _A      =       IFImgaImgSuperResolutionPipeline(**pipe_a.components      )

    pipe_a.enable_model_cpu_offload()
    pipe_a.enable_model_cpu_offload()

    pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()      )
    pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()      )

    self._test_if_imgaimg(__lowerCAmelCase			,						__lowerCAmelCase			,						__lowerCAmelCase			,						__lowerCAmelCase      )

    pipe_a.remove_all_hooks()
    pipe_a.remove_all_hooks()

    # inpainting

    _A      =       IFInpaintingPipeline(**pipe_a.components      )
    _A      =       IFInpaintingSuperResolutionPipeline(**pipe_a.components      )

    pipe_a.enable_model_cpu_offload()
    pipe_a.enable_model_cpu_offload()

    pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()      )
    pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()      )

    self._test_if_inpainting(__lowerCAmelCase			,						__lowerCAmelCase			,						__lowerCAmelCase			,						__lowerCAmelCase      )

 def     snake_case_      (    self					:					str			,						__lowerCAmelCase					:					Tuple			,						__lowerCAmelCase					:					List[str]			,						__lowerCAmelCase					:					Optional[Any]			,						__lowerCAmelCase					:					List[Any]      )   ->	Tuple:
    # pipeline 1

    _start_torch_memory_measurement()

    _A      =       torch.Generator(device='''cpu'''      ).manual_seed(0      )
    _A      =       pipe_a(
        prompt_embeds=__lowerCAmelCase			,						negative_prompt_embeds=__lowerCAmelCase			,						num_inference_steps=2			,						generator=__lowerCAmelCase			,						output_type='''np'''			,						)

    _A      =       output.images[0]

    assert image.shape == (64, 64, 3)

    _A      =       torch.cuda.max_memory_allocated()
    assert mem_bytes < 13 * 10**9

    _A      =       load_numpy(
        '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy'''      )
    assert_mean_pixel_difference(__lowerCAmelCase			,						__lowerCAmelCase      )

    # pipeline 2

    _start_torch_memory_measurement()

    _A      =       torch.Generator(device='''cpu'''      ).manual_seed(0      )

    _A      =       floats_tensor((1, 3, 64, 64)			,						rng=random.Random(0      )      ).to(__lowerCAmelCase      )

    _A      =       pipe_a(
        prompt_embeds=__lowerCAmelCase			,						negative_prompt_embeds=__lowerCAmelCase			,						image=__lowerCAmelCase			,						generator=__lowerCAmelCase			,						num_inference_steps=2			,						output_type='''np'''			,						)

    _A      =       output.images[0]

    assert image.shape == (2_56, 2_56, 3)

    _A      =       torch.cuda.max_memory_allocated()
    assert mem_bytes < 4 * 10**9

    _A      =       load_numpy(
        '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy'''      )
    assert_mean_pixel_difference(__lowerCAmelCase			,						__lowerCAmelCase      )

 def     snake_case_      (    self					:					str			,						__lowerCAmelCase					:					Any			,						__lowerCAmelCase					:					Union[str, Any]			,						__lowerCAmelCase					:					List[str]			,						__lowerCAmelCase					:					Optional[Any]      )   ->	Dict:
    # pipeline 1

    _start_torch_memory_measurement()

    _A      =       floats_tensor((1, 3, 64, 64)			,						rng=random.Random(0      )      ).to(__lowerCAmelCase      )

    _A      =       torch.Generator(device='''cpu'''      ).manual_seed(0      )

    _A      =       pipe_a(
        prompt_embeds=__lowerCAmelCase			,						negative_prompt_embeds=__lowerCAmelCase			,						image=__lowerCAmelCase			,						num_inference_steps=2			,						generator=__lowerCAmelCase			,						output_type='''np'''			,						)

    _A      =       output.images[0]

    assert image.shape == (64, 64, 3)

    _A      =       torch.cuda.max_memory_allocated()
    assert mem_bytes < 10 * 10**9

    _A      =       load_numpy(
        '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy'''      )
    assert_mean_pixel_difference(__lowerCAmelCase			,						__lowerCAmelCase      )

    # pipeline 2

    _start_torch_memory_measurement()

    _A      =       torch.Generator(device='''cpu'''      ).manual_seed(0      )

    _A      =       floats_tensor((1, 3, 2_56, 2_56)			,						rng=random.Random(0      )      ).to(__lowerCAmelCase      )
    _A      =       floats_tensor((1, 3, 64, 64)			,						rng=random.Random(0      )      ).to(__lowerCAmelCase      )

    _A      =       pipe_a(
        prompt_embeds=__lowerCAmelCase			,						negative_prompt_embeds=__lowerCAmelCase			,						image=__lowerCAmelCase			,						original_image=__lowerCAmelCase			,						generator=__lowerCAmelCase			,						num_inference_steps=2			,						output_type='''np'''			,						)

    _A      =       output.images[0]

    assert image.shape == (2_56, 2_56, 3)

    _A      =       torch.cuda.max_memory_allocated()
    assert mem_bytes < 4 * 10**9

    _A      =       load_numpy(
        '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy'''      )
    assert_mean_pixel_difference(__lowerCAmelCase			,						__lowerCAmelCase      )

 def     snake_case_      (    self					:					str			,						__lowerCAmelCase					:					Optional[Any]			,						__lowerCAmelCase					:					Tuple			,						__lowerCAmelCase					:					Optional[int]			,						__lowerCAmelCase					:					Tuple      )   ->	Tuple:
    # pipeline 1

    _start_torch_memory_measurement()

    _A      =       floats_tensor((1, 3, 64, 64)			,						rng=random.Random(0      )      ).to(__lowerCAmelCase      )
    _A      =       floats_tensor((1, 3, 64, 64)			,						rng=random.Random(1      )      ).to(__lowerCAmelCase      )

    _A      =       torch.Generator(device='''cpu'''      ).manual_seed(0      )
    _A      =       pipe_a(
        prompt_embeds=__lowerCAmelCase			,						negative_prompt_embeds=__lowerCAmelCase			,						image=__lowerCAmelCase			,						mask_image=__lowerCAmelCase			,						num_inference_steps=2			,						generator=__lowerCAmelCase			,						output_type='''np'''			,						)

    _A      =       output.images[0]

    assert image.shape == (64, 64, 3)

    _A      =       torch.cuda.max_memory_allocated()
    assert mem_bytes < 10 * 10**9

    _A      =       load_numpy(
        '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy'''      )
    assert_mean_pixel_difference(__lowerCAmelCase			,						__lowerCAmelCase      )

    # pipeline 2

    _start_torch_memory_measurement()

    _A      =       torch.Generator(device='''cpu'''      ).manual_seed(0      )

    _A      =       floats_tensor((1, 3, 64, 64)			,						rng=random.Random(0      )      ).to(__lowerCAmelCase      )
    _A      =       floats_tensor((1, 3, 2_56, 2_56)			,						rng=random.Random(0      )      ).to(__lowerCAmelCase      )
    _A      =       floats_tensor((1, 3, 2_56, 2_56)			,						rng=random.Random(1      )      ).to(__lowerCAmelCase      )

    _A      =       pipe_a(
        prompt_embeds=__lowerCAmelCase			,						negative_prompt_embeds=__lowerCAmelCase			,						image=__lowerCAmelCase			,						mask_image=__lowerCAmelCase			,						original_image=__lowerCAmelCase			,						generator=__lowerCAmelCase			,						num_inference_steps=2			,						output_type='''np'''			,						)

    _A      =       output.images[0]

    assert image.shape == (2_56, 2_56, 3)

    _A      =       torch.cuda.max_memory_allocated()
    assert mem_bytes < 4 * 10**9

    _A      =       load_numpy(
        '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy'''      )
    assert_mean_pixel_difference(__lowerCAmelCase			,						__lowerCAmelCase      )

def 	SCREAMING_SNAKE_CASE_							(	)  ->     List[Any]:
   torch.cuda.empty_cache()
   torch.cuda.reset_max_memory_allocated()
   torch.cuda.reset_peak_memory_stats()





def 							SCREAMING_SNAKE_CASE_	(					UpperCAmelCase_	:     int = 1_0_0_0				)			->						int:
       SCREAMING_SNAKE_CASE_							:				int		=2**power
       SCREAMING_SNAKE_CASE_							:				Tuple		=0
       while n:
              SCREAMING_SNAKE_CASE_	,     SCREAMING_SNAKE_CASE_							:				Union[str, Any]		=r + n % 1_0, n // 1_0
       return r


if __name__ == "__main__":
 print(solution(int(str(input()).strip())))
