


'''simple docstring'''
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      ):






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


          '''simple docstring'''


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






      @property
      def lowercase_							(					self				:    int ):


          '''simple docstring'''


          UpperCAmelCase__			:		Any													=				1
          UpperCAmelCase__			:		str													=				3
          UpperCAmelCase__			:		Tuple													=				(32, 32)

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






      @property
      def lowercase_							(					self				:    Dict ):


          '''simple docstring'''


          torch.manual_seed(0 )
          UpperCAmelCase__			:		Tuple													=				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=100						,						)
          return model






      @property
      def lowercase_							(					self				:    Dict ):


          '''simple docstring'''


          torch.manual_seed(0 )
          UpperCAmelCase__			:		Optional[Any]													=				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 lowercase_							(					self				:    Dict ):


          '''simple docstring'''


          torch.manual_seed(0 )
          UpperCAmelCase__			:		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=512						,						)
          return CLIPTextModel(_A )






      def lowercase_							(					self				:    int ):


          '''simple docstring'''


          UpperCAmelCase__			:		Union[str, Any]													=				'''cpu'''  # ensure determinism for the device-dependent torch.Generator
          UpperCAmelCase__			:		Union[str, Any]													=				self.dummy_cond_unet_upscale
          UpperCAmelCase__			:		Any													=				DDPMScheduler()
          UpperCAmelCase__			:		List[Any]													=				DDIMScheduler(prediction_type='''v_prediction''' )
          UpperCAmelCase__			:		int													=				self.dummy_vae
          UpperCAmelCase__			:		Tuple													=				self.dummy_text_encoder
          UpperCAmelCase__			:		Optional[Any]													=				CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' )

          UpperCAmelCase__			:		str													=				self.dummy_image.cpu().permute(0						,						2						,						3						,						1 )[0]
          UpperCAmelCase__			:		List[str]													=				Image.fromarray(np.uinta(_A ) ).convert('''RGB''' ).resize((64, 64) )

          # make sure here that pndm scheduler skips prk
          UpperCAmelCase__			:		Tuple													=				StableDiffusionUpscalePipeline(
              unet=_A						,						low_res_scheduler=_A						,						scheduler=_A						,						vae=_A						,						text_encoder=_A						,						tokenizer=_A						,						max_noise_level=350						,						)
          UpperCAmelCase__			:		Union[str, Any]													=				sd_pipe.to(_A )
          sd_pipe.set_progress_bar_config(disable=_A )

          UpperCAmelCase__			:		List[str]													=				'''A painting of a squirrel eating a burger'''
          UpperCAmelCase__			:		Dict													=				torch.Generator(device=_A ).manual_seed(0 )
          UpperCAmelCase__			:		List[Any]													=				sd_pipe(
              [prompt]						,						image=_A						,						generator=_A						,						guidance_scale=6.0						,						noise_level=20						,						num_inference_steps=2						,						output_type='''np'''						,						)

          UpperCAmelCase__			:		Any													=				output.images

          UpperCAmelCase__			:		str													=				torch.Generator(device=_A ).manual_seed(0 )
          UpperCAmelCase__			:		Optional[Any]													=				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]

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

          UpperCAmelCase__			:		Tuple													=				low_res_image.size[0] * 4
          assert image.shape == (1, expected_height_width, expected_height_width, 3)
          UpperCAmelCase__			:		Optional[int]													=				np.array([0.3_1_1_3, 0.3_9_1_0, 0.4_2_7_2, 0.4_8_5_9, 0.5_0_6_1, 0.4_6_5_2, 0.5_3_6_2, 0.5_7_1_5, 0.5_6_6_1] )

          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 lowercase_							(					self				:    Optional[int] ):


          '''simple docstring'''


          UpperCAmelCase__			:		Dict													=				'''cpu'''  # ensure determinism for the device-dependent torch.Generator
          UpperCAmelCase__			:		List[Any]													=				self.dummy_cond_unet_upscale
          UpperCAmelCase__			:		List[Any]													=				DDPMScheduler()
          UpperCAmelCase__			:		Tuple													=				DDIMScheduler(prediction_type='''v_prediction''' )
          UpperCAmelCase__			:		Optional[Any]													=				self.dummy_vae
          UpperCAmelCase__			:		List[str]													=				self.dummy_text_encoder
          UpperCAmelCase__			:		str													=				CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' )

          UpperCAmelCase__			:		Dict													=				self.dummy_image.cpu().permute(0						,						2						,						3						,						1 )[0]
          UpperCAmelCase__			:		int													=				Image.fromarray(np.uinta(_A ) ).convert('''RGB''' ).resize((64, 64) )

          # make sure here that pndm scheduler skips prk
          UpperCAmelCase__			:		Optional[Any]													=				StableDiffusionUpscalePipeline(
              unet=_A						,						low_res_scheduler=_A						,						scheduler=_A						,						vae=_A						,						text_encoder=_A						,						tokenizer=_A						,						max_noise_level=350						,						)
          UpperCAmelCase__			:		Union[str, Any]													=				sd_pipe.to(_A )
          sd_pipe.set_progress_bar_config(disable=_A )

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

          UpperCAmelCase__			:		Optional[Any]													=				torch.Generator(device=_A ).manual_seed(0 )
          UpperCAmelCase__			:		str													=				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'''						,						)
          UpperCAmelCase__			:		Union[str, Any]													=				output.images
          assert image.shape[0] == 2






      @unittest.skipIf(torch_device != '''cuda'''						,						'''This test requires a GPU''' )
      def lowercase_							(					self				:    int ):


          '''simple docstring'''


          UpperCAmelCase__			:		List[Any]													=				self.dummy_cond_unet_upscale
          UpperCAmelCase__			:		Dict													=				DDPMScheduler()
          UpperCAmelCase__			:		int													=				DDIMScheduler(prediction_type='''v_prediction''' )
          UpperCAmelCase__			:		Union[str, Any]													=				self.dummy_vae
          UpperCAmelCase__			:		int													=				self.dummy_text_encoder
          UpperCAmelCase__			:		Optional[int]													=				CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' )

          UpperCAmelCase__			:		Dict													=				self.dummy_image.cpu().permute(0						,						2						,						3						,						1 )[0]
          UpperCAmelCase__			:		List[str]													=				Image.fromarray(np.uinta(_A ) ).convert('''RGB''' ).resize((64, 64) )

          # put models in fp16, except vae as it overflows in fp16
          UpperCAmelCase__			:		Optional[Any]													=				unet.half()
          UpperCAmelCase__			:		Tuple													=				text_encoder.half()

          # make sure here that pndm scheduler skips prk
          UpperCAmelCase__			:		List[Any]													=				StableDiffusionUpscalePipeline(
              unet=_A						,						low_res_scheduler=_A						,						scheduler=_A						,						vae=_A						,						text_encoder=_A						,						tokenizer=_A						,						max_noise_level=350						,						)
          UpperCAmelCase__			:		str													=				sd_pipe.to(_A )
          sd_pipe.set_progress_bar_config(disable=_A )

          UpperCAmelCase__			:		Any													=				'''A painting of a squirrel eating a burger'''
          UpperCAmelCase__			:		Tuple													=				torch.manual_seed(0 )
          UpperCAmelCase__			:		Union[str, Any]													=				sd_pipe(
              [prompt]						,						image=_A						,						generator=_A						,						num_inference_steps=2						,						output_type='''np'''						,						).images

          UpperCAmelCase__			:		Optional[Any]													=				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      ):






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


          '''simple docstring'''


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






      def lowercase_							(					self				:    str ):


          '''simple docstring'''


          UpperCAmelCase__			:		Union[str, Any]													=				load_image(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
              '''/sd2-upscale/low_res_cat.png''' )
          UpperCAmelCase__			:		int													=				load_numpy(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale'''
              '''/upsampled_cat.npy''' )

          UpperCAmelCase__			:		Dict													=				'''stabilityai/stable-diffusion-x4-upscaler'''
          UpperCAmelCase__			:		str													=				StableDiffusionUpscalePipeline.from_pretrained(_A )
          pipe.to(_A )
          pipe.set_progress_bar_config(disable=_A )
          pipe.enable_attention_slicing()

          UpperCAmelCase__			:		Dict													=				'''a cat sitting on a park bench'''

          UpperCAmelCase__			:		int													=				torch.manual_seed(0 )
          UpperCAmelCase__			:		Tuple													=				pipe(
              prompt=_A						,						image=_A						,						generator=_A						,						output_type='''np'''						,						)
          UpperCAmelCase__			:		Tuple													=				output.images[0]

          assert image.shape == (512, 512, 3)
          assert np.abs(expected_image - image ).max() < 1e-3






      def lowercase_							(					self				:    Optional[int] ):


          '''simple docstring'''


          UpperCAmelCase__			:		List[Any]													=				load_image(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
              '''/sd2-upscale/low_res_cat.png''' )
          UpperCAmelCase__			:		List[Any]													=				load_numpy(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale'''
              '''/upsampled_cat_fp16.npy''' )

          UpperCAmelCase__			:		Optional[Any]													=				'''stabilityai/stable-diffusion-x4-upscaler'''
          UpperCAmelCase__			:		List[Any]													=				StableDiffusionUpscalePipeline.from_pretrained(
              _A						,						torch_dtype=torch.floataa						,						)
          pipe.to(_A )
          pipe.set_progress_bar_config(disable=_A )
          pipe.enable_attention_slicing()

          UpperCAmelCase__			:		Any													=				'''a cat sitting on a park bench'''

          UpperCAmelCase__			:		List[str]													=				torch.manual_seed(0 )
          UpperCAmelCase__			:		List[Any]													=				pipe(
              prompt=_A						,						image=_A						,						generator=_A						,						output_type='''np'''						,						)
          UpperCAmelCase__			:		str													=				output.images[0]

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






      def lowercase_							(					self				:    int ):


          '''simple docstring'''


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

          UpperCAmelCase__			:		Union[str, Any]													=				load_image(
              '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
              '''/sd2-upscale/low_res_cat.png''' )

          UpperCAmelCase__			:		Optional[int]													=				'''stabilityai/stable-diffusion-x4-upscaler'''
          UpperCAmelCase__			:		Optional[Any]													=				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()

          UpperCAmelCase__			:		List[str]													=				'''a cat sitting on a park bench'''

          UpperCAmelCase__			:		List[str]													=				torch.manual_seed(0 )
          UpperCAmelCase__			:		str													=				pipe(
              prompt=_A						,						image=_A						,						generator=_A						,						num_inference_steps=5						,						output_type='''np'''						,						)

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




'''simple docstring'''
def 					a__       (					lowerCAmelCase__						)    ->	int:
    if a < 0:
        raise ValueError('''Input value must be a positive integer'''						)
    elif isinstance(lowerCAmelCase__  ,					lowerCAmelCase__						):
        raise TypeError('''Input value must be a \'int\' type'''						)
    return bin(lowerCAmelCase__						).count('''1'''						)


if __name__ == "__main__":
  import doctest

  doctest.testmod()
