






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  __UpperCAmelCase      (							self       )     ->							List[str]:
							# clean up the VRAM after each test
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()



		@property
		def  __UpperCAmelCase      (							self       )     ->							Tuple:
							UpperCAmelCase_   :				str						=						1
							UpperCAmelCase_   :				int						=						3
							UpperCAmelCase_   :				Dict						=						(3_2, 3_2)

							UpperCAmelCase_   :				Dict						=						floats_tensor((batch_size, num_channels) + sizes    ,		rng=random.Random(0       )       ).to(_UpperCamelCase       )
							return image



		@property
		def  __UpperCAmelCase      (							self       )     ->							List[Any]:
							torch.manual_seed(0       )
							UpperCAmelCase_   :				Any						=						UNetaDConditionModel(
							    block_out_channels=(3_2, 3_2, 6_4)    ,		layers_per_block=2    ,		sample_size=3_2    ,		in_channels=7    ,		out_channels=4    ,		down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D', 'CrossAttnDownBlock2D')    ,		up_block_types=('CrossAttnUpBlock2D', 'CrossAttnUpBlock2D', 'UpBlock2D')    ,		cross_attention_dim=3_2    ,		attention_head_dim=8    ,		use_linear_projection=_UpperCamelCase    ,		only_cross_attention=(True, True, False)    ,		num_class_embeds=1_0_0    ,		)
							return model



		@property
		def  __UpperCAmelCase      (							self       )     ->							Union[str, Any]:
							torch.manual_seed(0       )
							UpperCAmelCase_   :				List[Any]						=						AutoencoderKL(
							    block_out_channels=[3_2, 3_2, 6_4]    ,		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  __UpperCAmelCase      (							self       )     ->							Union[str, Any]:
							torch.manual_seed(0       )
							UpperCAmelCase_   :				Dict						=						CLIPTextConfig(
							    bos_token_id=0    ,		eos_token_id=2    ,		hidden_size=3_2    ,		intermediate_size=3_7    ,		layer_norm_eps=1E-05    ,		num_attention_heads=4    ,		num_hidden_layers=5    ,		pad_token_id=1    ,		vocab_size=1_0_0_0    ,		hidden_act='gelu'    ,		projection_dim=5_1_2    ,		)
							return CLIPTextModel(_UpperCamelCase       )



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

							UpperCAmelCase_   :				Union[str, Any]						=						self.dummy_image.cpu().permute(0    ,		2    ,		3    ,		1       )[0]
							UpperCAmelCase_   :				Tuple						=						Image.fromarray(np.uinta(_UpperCamelCase       )       ).convert('RGB'       ).resize((6_4, 6_4)       )

							# make sure here that pndm scheduler skips prk
							UpperCAmelCase_   :				Tuple						=						StableDiffusionUpscalePipeline(
							    unet=_UpperCamelCase    ,		low_res_scheduler=_UpperCamelCase    ,		scheduler=_UpperCamelCase    ,		vae=_UpperCamelCase    ,		text_encoder=_UpperCamelCase    ,		tokenizer=_UpperCamelCase    ,		max_noise_level=3_5_0    ,		)
							UpperCAmelCase_   :				int						=						sd_pipe.to(_UpperCamelCase       )
							sd_pipe.set_progress_bar_config(disable=_UpperCamelCase       )

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

							UpperCAmelCase_   :				Optional[Any]						=						output.images

							UpperCAmelCase_   :				Dict						=						torch.Generator(device=_UpperCamelCase       ).manual_seed(0       )
							UpperCAmelCase_   :				Optional[Any]						=						sd_pipe(
							    [prompt]    ,		image=_UpperCamelCase    ,		generator=_UpperCamelCase    ,		guidance_scale=6.0    ,		noise_level=2_0    ,		num_inference_steps=2    ,		output_type='np'    ,		return_dict=_UpperCamelCase    ,		)[0]

							UpperCAmelCase_   :				str						=						image[0, -3:, -3:, -1]
							UpperCAmelCase_   :				Dict						=						image_from_tuple[0, -3:, -3:, -1]

							UpperCAmelCase_   :				List[str]						=						low_res_image.size[0] * 4
							assert image.shape == (1, expected_height_width, expected_height_width, 3)
							UpperCAmelCase_   :				Tuple						=						np.array([0.31_13, 0.39_10, 0.42_72, 0.48_59, 0.50_61, 0.46_52, 0.53_62, 0.57_15, 0.56_61]       )

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

							UpperCAmelCase_   :				Optional[Any]						=						self.dummy_image.cpu().permute(0    ,		2    ,		3    ,		1       )[0]
							UpperCAmelCase_   :				Tuple						=						Image.fromarray(np.uinta(_UpperCamelCase       )       ).convert('RGB'       ).resize((6_4, 6_4)       )

							# make sure here that pndm scheduler skips prk
							UpperCAmelCase_   :				Optional[Any]						=						StableDiffusionUpscalePipeline(
							    unet=_UpperCamelCase    ,		low_res_scheduler=_UpperCamelCase    ,		scheduler=_UpperCamelCase    ,		vae=_UpperCamelCase    ,		text_encoder=_UpperCamelCase    ,		tokenizer=_UpperCamelCase    ,		max_noise_level=3_5_0    ,		)
							UpperCAmelCase_   :				List[str]						=						sd_pipe.to(_UpperCamelCase       )
							sd_pipe.set_progress_bar_config(disable=_UpperCamelCase       )

							UpperCAmelCase_   :				Dict						=						'A painting of a squirrel eating a burger'
							UpperCAmelCase_   :				Optional[int]						=						sd_pipe(
							    2 * [prompt]    ,		image=2 * [low_res_image]    ,		guidance_scale=6.0    ,		noise_level=2_0    ,		num_inference_steps=2    ,		output_type='np'    ,		)
							UpperCAmelCase_   :				Optional[Any]						=						output.images
							assert image.shape[0] == 2

							UpperCAmelCase_   :				List[Any]						=						torch.Generator(device=_UpperCamelCase       ).manual_seed(0       )
							UpperCAmelCase_   :				Dict						=						sd_pipe(
							    [prompt]    ,		image=_UpperCamelCase    ,		generator=_UpperCamelCase    ,		num_images_per_prompt=2    ,		guidance_scale=6.0    ,		noise_level=2_0    ,		num_inference_steps=2    ,		output_type='np'    ,		)
							UpperCAmelCase_   :				Tuple						=						output.images
							assert image.shape[0] == 2



		@unittest.skipIf(torch_device != 'cuda'    ,		'This test requires a GPU'       )
		def  __UpperCAmelCase      (							self       )     ->							Optional[int]:
							UpperCAmelCase_   :				Dict						=						self.dummy_cond_unet_upscale
							UpperCAmelCase_   :				Tuple						=						DDPMScheduler()
							UpperCAmelCase_   :				Optional[int]						=						DDIMScheduler(prediction_type='v_prediction'       )
							UpperCAmelCase_   :				Any						=						self.dummy_vae
							UpperCAmelCase_   :				Optional[int]						=						self.dummy_text_encoder
							UpperCAmelCase_   :				Optional[Any]						=						CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'       )

							UpperCAmelCase_   :				Dict						=						self.dummy_image.cpu().permute(0    ,		2    ,		3    ,		1       )[0]
							UpperCAmelCase_   :				Any						=						Image.fromarray(np.uinta(_UpperCamelCase       )       ).convert('RGB'       ).resize((6_4, 6_4)       )

							# put models in fp16, except vae as it overflows in fp16
							UpperCAmelCase_   :				Any						=						unet.half()
							UpperCAmelCase_   :				int						=						text_encoder.half()

							# make sure here that pndm scheduler skips prk
							UpperCAmelCase_   :				List[Any]						=						StableDiffusionUpscalePipeline(
							    unet=_UpperCamelCase    ,		low_res_scheduler=_UpperCamelCase    ,		scheduler=_UpperCamelCase    ,		vae=_UpperCamelCase    ,		text_encoder=_UpperCamelCase    ,		tokenizer=_UpperCamelCase    ,		max_noise_level=3_5_0    ,		)
							UpperCAmelCase_   :				int						=						sd_pipe.to(_UpperCamelCase       )
							sd_pipe.set_progress_bar_config(disable=_UpperCamelCase       )

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

							UpperCAmelCase_   :				List[str]						=						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  __UpperCAmelCase      (							self       )     ->							Union[str, Any]:
							# clean up the VRAM after each test
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()



		def  __UpperCAmelCase      (							self       )     ->							int:
							UpperCAmelCase_   :				str						=						load_image(
							    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
							    '/sd2-upscale/low_res_cat.png'       )
							UpperCAmelCase_   :				Optional[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_   :				Optional[int]						=						StableDiffusionUpscalePipeline.from_pretrained(_UpperCamelCase       )
							pipe.to(_UpperCamelCase       )
							pipe.set_progress_bar_config(disable=_UpperCamelCase       )
							pipe.enable_attention_slicing()

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

							UpperCAmelCase_   :				Optional[Any]						=						torch.manual_seed(0       )
							UpperCAmelCase_   :				str						=						pipe(
							    prompt=_UpperCamelCase    ,		image=_UpperCamelCase    ,		generator=_UpperCamelCase    ,		output_type='np'    ,		)
							UpperCAmelCase_   :				Union[str, Any]						=						output.images[0]

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



		def  __UpperCAmelCase      (							self       )     ->							Optional[int]:
							UpperCAmelCase_   :				Optional[Any]						=						load_image(
							    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
							    '/sd2-upscale/low_res_cat.png'       )
							UpperCAmelCase_   :				Union[str, Any]						=						load_numpy(
							    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale'
							    '/upsampled_cat_fp16.npy'       )

							UpperCAmelCase_   :				List[str]						=						'stabilityai/stable-diffusion-x4-upscaler'
							UpperCAmelCase_   :				List[str]						=						StableDiffusionUpscalePipeline.from_pretrained(
							    _UpperCamelCase    ,		torch_dtype=torch.floataa    ,		)
							pipe.to(_UpperCamelCase       )
							pipe.set_progress_bar_config(disable=_UpperCamelCase       )
							pipe.enable_attention_slicing()

							UpperCAmelCase_   :				int						=						'a cat sitting on a park bench'

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

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



		def  __UpperCAmelCase      (							self       )     ->							Optional[int]:
							torch.cuda.empty_cache()
							torch.cuda.reset_max_memory_allocated()
							torch.cuda.reset_peak_memory_stats()

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

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

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

							UpperCAmelCase_   :				List[Any]						=						torch.manual_seed(0       )
							UpperCAmelCase_   :				Union[str, Any]						=						pipe(
							    prompt=_UpperCamelCase    ,		image=_UpperCamelCase    ,		generator=_UpperCamelCase    ,		num_inference_steps=5    ,		output_type='np'    ,		)

							UpperCAmelCase_   :				Optional[int]						=						torch.cuda.max_memory_allocated()
							# make sure that less than 2.9 GB is allocated
							assert mem_bytes < 2.9 * 1_0**9














def 					lowercase__				(					__snake_case   :							List[str]					,	__snake_case   :							List[str]					,	__snake_case   :							Union[str, Any]					,	__snake_case   :							Optional[int]					,	__snake_case   :							str					,	__snake_case   :							Optional[Any]  ):


					'''simple docstring'''


					if index == r:
										for j in range(__snake_case  ):
															print(data[j]					,	end=' '  )
										print(' '  )
										return
					#  When no more elements are there to put in data[]
					if i >= n:
										return
					# current is included, put next at next location
					UpperCAmelCase_   :				int						=						arr[i]
					combination_util(__snake_case					,	__snake_case					,	__snake_case					,	index + 1					,	__snake_case					,	i + 1  )
					# current is excluded, replace it with
					# next (Note that i+1 is passed, but
					# index is not changed)
					combination_util(__snake_case					,	__snake_case					,	__snake_case					,	__snake_case					,	__snake_case					,	i + 1  )
					# The main function that prints all combinations
					# of size r in arr[] of size n. This function
					# mainly uses combinationUtil()




def 					lowercase__				(					__snake_case   :							List[Any]					,	__snake_case   :							List[Any]					,	__snake_case   :							str  ):


					'''simple docstring'''


					UpperCAmelCase_   :				Union[str, Any]						=						[0] * r
					# Print all combination using temporary array 'data[]'
					combination_util(__snake_case					,	__snake_case					,	__snake_case					,	0					,	__snake_case					,	0  )


if __name__ == "__main__":
		# Driver code to check the function above
		__UpperCAmelCase     							=						[10, 20, 30, 40, 50]
		print_combination(arr, len(arr), 3)
		# This code is contributed by Ambuj sahu






