

'''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 				_snake_case			(							unittest.TestCase    ):
   def      __UpperCamelCase    (			self      :   List[str]				):
     # clean up the VRAM after each test
     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()
   @property
   def      __UpperCamelCase    (			self      :   Dict				):
     SCREAMING_SNAKE_CASE:Any       =       1
     SCREAMING_SNAKE_CASE:Tuple       =       3
     SCREAMING_SNAKE_CASE:List[Any]       =       (32, 32)

     SCREAMING_SNAKE_CASE:Dict       =       floats_tensor((batch_size, num_channels) + sizes  ,rng=random.Random(0				)				).to(lowerCAmelCase_				)
     return image
   @property
   def      __UpperCamelCase    (			self      :   Union[str, Any]				):
     torch.manual_seed(0				)
     SCREAMING_SNAKE_CASE: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=lowerCAmelCase_  ,only_cross_attention=(True, True, False)  ,num_class_embeds=100  ,)
     return model
   @property
   def      __UpperCamelCase    (			self      :   int				):
     torch.manual_seed(0				)
     SCREAMING_SNAKE_CASE:List[str]       =       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      __UpperCamelCase    (			self      :   List[Any]				):
     torch.manual_seed(0				)
     SCREAMING_SNAKE_CASE:Dict       =       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(lowerCAmelCase_				)
   def      __UpperCamelCase    (			self      :   Any				):
     SCREAMING_SNAKE_CASE:Optional[int]       =       'cpu'  # ensure determinism for the device-dependent torch.Generator
     SCREAMING_SNAKE_CASE:List[Any]       =       self.dummy_cond_unet_upscale
     SCREAMING_SNAKE_CASE:Any       =       DDPMScheduler()
     SCREAMING_SNAKE_CASE:str       =       DDIMScheduler(prediction_type="v_prediction"				)
     SCREAMING_SNAKE_CASE:List[str]       =       self.dummy_vae
     SCREAMING_SNAKE_CASE:Optional[Any]       =       self.dummy_text_encoder
     SCREAMING_SNAKE_CASE:Optional[int]       =       CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"				)

     SCREAMING_SNAKE_CASE:Tuple       =       self.dummy_image.cpu().permute(0  ,2  ,3  ,1				)[0]
     SCREAMING_SNAKE_CASE:int       =       Image.fromarray(np.uinta(lowerCAmelCase_				)				).convert("RGB"				).resize((64, 64)				)

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

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

     SCREAMING_SNAKE_CASE:str       =       output.images

     SCREAMING_SNAKE_CASE:Dict       =       torch.Generator(device=lowerCAmelCase_				).manual_seed(0				)
     SCREAMING_SNAKE_CASE:List[Any]       =       sd_pipe(
         [prompt]  ,image=lowerCAmelCase_  ,generator=lowerCAmelCase_  ,guidance_scale=6.0  ,noise_level=20  ,num_inference_steps=2  ,output_type="np"  ,return_dict=lowerCAmelCase_  ,)[0]

     SCREAMING_SNAKE_CASE:Optional[int]       =       image[0, -3:, -3:, -1]
     SCREAMING_SNAKE_CASE:Optional[Any]       =       image_from_tuple[0, -3:, -3:, -1]

     SCREAMING_SNAKE_CASE:Any       =       low_res_image.size[0] * 4
     assert image.shape == (1, expected_height_width, expected_height_width, 3)
     SCREAMING_SNAKE_CASE:Tuple       =       np.array([0.3_113, 0.3_910, 0.4_272, 0.4_859, 0.5_061, 0.4_652, 0.5_362, 0.5_715, 0.5_661]				)

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

     SCREAMING_SNAKE_CASE:Union[str, Any]       =       self.dummy_image.cpu().permute(0  ,2  ,3  ,1				)[0]
     SCREAMING_SNAKE_CASE:Optional[Any]       =       Image.fromarray(np.uinta(lowerCAmelCase_				)				).convert("RGB"				).resize((64, 64)				)

     # make sure here that pndm scheduler skips prk
     SCREAMING_SNAKE_CASE:Dict       =       StableDiffusionUpscalePipeline(
         unet=lowerCAmelCase_  ,low_res_scheduler=lowerCAmelCase_  ,scheduler=lowerCAmelCase_  ,vae=lowerCAmelCase_  ,text_encoder=lowerCAmelCase_  ,tokenizer=lowerCAmelCase_  ,max_noise_level=350  ,)
     SCREAMING_SNAKE_CASE:Optional[int]       =       sd_pipe.to(lowerCAmelCase_				)
     sd_pipe.set_progress_bar_config(disable=lowerCAmelCase_				)

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

     SCREAMING_SNAKE_CASE:List[Any]       =       torch.Generator(device=lowerCAmelCase_				).manual_seed(0				)
     SCREAMING_SNAKE_CASE:List[str]       =       sd_pipe(
         [prompt]  ,image=lowerCAmelCase_  ,generator=lowerCAmelCase_  ,num_images_per_prompt=2  ,guidance_scale=6.0  ,noise_level=20  ,num_inference_steps=2  ,output_type="np"  ,)
     SCREAMING_SNAKE_CASE:Union[str, Any]       =       output.images
     assert image.shape[0] == 2







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

     SCREAMING_SNAKE_CASE:Union[str, Any]       =       self.dummy_image.cpu().permute(0  ,2  ,3  ,1				)[0]
     SCREAMING_SNAKE_CASE:Union[str, Any]       =       Image.fromarray(np.uinta(lowerCAmelCase_				)				).convert("RGB"				).resize((64, 64)				)

     # put models in fp16, except vae as it overflows in fp16
     SCREAMING_SNAKE_CASE:Union[str, Any]       =       unet.half()
     SCREAMING_SNAKE_CASE:List[Any]       =       text_encoder.half()

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

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

     SCREAMING_SNAKE_CASE:Union[str, Any]       =       low_res_image.size[0] * 4
     assert image.shape == (1, expected_height_width, expected_height_width, 3)





@slow
@require_torch_gpu
class 				_snake_case			(							unittest.TestCase    ):
   def      __UpperCamelCase    (			self      :   Dict				):
     # clean up the VRAM after each test
     super().tearDown()
     gc.collect()
     torch.cuda.empty_cache()
   def      __UpperCamelCase    (			self      :   List[str]				):
     SCREAMING_SNAKE_CASE:str       =       load_image(
         "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
         "/sd2-upscale/low_res_cat.png"				)
     SCREAMING_SNAKE_CASE:str       =       load_numpy(
         "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale"
         "/upsampled_cat.npy"				)

     SCREAMING_SNAKE_CASE:Union[str, Any]       =       'stabilityai/stable-diffusion-x4-upscaler'
     SCREAMING_SNAKE_CASE:Dict       =       StableDiffusionUpscalePipeline.from_pretrained(lowerCAmelCase_				)
     pipe.to(lowerCAmelCase_				)
     pipe.set_progress_bar_config(disable=lowerCAmelCase_				)
     pipe.enable_attention_slicing()

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

     SCREAMING_SNAKE_CASE:List[str]       =       torch.manual_seed(0				)
     SCREAMING_SNAKE_CASE:Dict       =       pipe(
         prompt=lowerCAmelCase_  ,image=lowerCAmelCase_  ,generator=lowerCAmelCase_  ,output_type="np"  ,)
     SCREAMING_SNAKE_CASE:List[Any]       =       output.images[0]

     assert image.shape == (512, 512, 3)
     assert np.abs(expected_image - image				).max() < 1e-3
   def      __UpperCamelCase    (			self      :   Optional[Any]				):
     SCREAMING_SNAKE_CASE:Any       =       load_image(
         "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
         "/sd2-upscale/low_res_cat.png"				)
     SCREAMING_SNAKE_CASE:Optional[Any]       =       load_numpy(
         "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale"
         "/upsampled_cat_fp16.npy"				)

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

     SCREAMING_SNAKE_CASE:Optional[Any]       =       'a cat sitting on a park bench'

     SCREAMING_SNAKE_CASE:List[Any]       =       torch.manual_seed(0				)
     SCREAMING_SNAKE_CASE:Union[str, Any]       =       pipe(
         prompt=lowerCAmelCase_  ,image=lowerCAmelCase_  ,generator=lowerCAmelCase_  ,output_type="np"  ,)
     SCREAMING_SNAKE_CASE:Tuple       =       output.images[0]

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







   def      __UpperCamelCase    (			self      :   List[Any]				):
     torch.cuda.empty_cache()
     torch.cuda.reset_max_memory_allocated()
     torch.cuda.reset_peak_memory_stats()

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

     SCREAMING_SNAKE_CASE:Tuple       =       'stabilityai/stable-diffusion-x4-upscaler'
     SCREAMING_SNAKE_CASE:Dict       =       StableDiffusionUpscalePipeline.from_pretrained(
         lowerCAmelCase_  ,torch_dtype=torch.floataa  ,)
     pipe.to(lowerCAmelCase_				)
     pipe.set_progress_bar_config(disable=lowerCAmelCase_				)
     pipe.enable_attention_slicing(1				)
     pipe.enable_sequential_cpu_offload()

     SCREAMING_SNAKE_CASE:str       =       'a cat sitting on a park bench'

     SCREAMING_SNAKE_CASE:List[Any]       =       torch.manual_seed(0				)
     SCREAMING_SNAKE_CASE:Union[str, Any]       =       pipe(
         prompt=lowerCAmelCase_  ,image=lowerCAmelCase_  ,generator=lowerCAmelCase_  ,num_inference_steps=5  ,output_type="np"  ,)

     SCREAMING_SNAKE_CASE:Optional[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"""
class _lowerCAmelCase						:







						def __init__(    self   ,				lowerCAmelCase_   ,				lowerCAmelCase_=None   ,				lowerCAmelCase_=None							)		->							int:
										_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    data
										_SCREAMING_SNAKE_CASE   :		Tuple       		=    previous
										_SCREAMING_SNAKE_CASE   :		Any       		=    next_node







						def __str__(    self							)		->							str:
										return F"""{self.data}"""







						def 			A      (    self							)		->							int:
										return self.data







						def 			A      (    self							)		->							Dict:
										return self.next







						def 			A      (    self							)		->							Union[str, Any]:
										return self.previous







class _lowerCAmelCase						:







						def __init__(    self   ,				lowerCAmelCase_							)		->							List[str]:
										_SCREAMING_SNAKE_CASE   :		List[Any]       		=    head







						def __iter__(    self							)		->							Any:
										return self







						def 			A      (    self							)		->							Dict:
										if not self.current:
														raise StopIteration
										else:
														_SCREAMING_SNAKE_CASE   :		Any       		=    self.current.get_data()
														_SCREAMING_SNAKE_CASE   :		Dict       		=    self.current.get_next()
														return value







class _lowerCAmelCase						:







						def __init__(    self							)		->							Dict:
										_SCREAMING_SNAKE_CASE   :		Dict       		=    None  # First node in list
										_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    None  # Last node in list







						def __str__(    self							)		->							Any:
										_SCREAMING_SNAKE_CASE   :		str       		=    self.head
										_SCREAMING_SNAKE_CASE   :		int       		=    []
										while current is not None:
														nodes.append(current.get_data()							)
														_SCREAMING_SNAKE_CASE   :		List[Any]       		=    current.get_next()
										return " ".join(str(lowerCAmelCase_							) for node in nodes							)







						def __contains__(    self   ,				lowerCAmelCase_							)		->							Any:
										_SCREAMING_SNAKE_CASE   :		Any       		=    self.head
										while current:
														if current.get_data() == value:
																		return True
														_SCREAMING_SNAKE_CASE   :		int       		=    current.get_next()
										return False







						def __iter__(    self							)		->							str:
										return LinkedListIterator(self.head							)







						def 			A      (    self							)		->							Dict:
										if self.head:
														return self.head.get_data()
										return None







						def 			A      (    self							)		->							List[Any]:
										if self.tail:
														return self.tail.get_data()
										return None







						def 			A      (    self   ,				lowerCAmelCase_							)		->							None:
										if self.head is None:
														_SCREAMING_SNAKE_CASE   :		List[Any]       		=    node
														_SCREAMING_SNAKE_CASE   :		Dict       		=    node
										else:
														self.insert_before_node(self.head   ,				lowerCAmelCase_							)







						def 			A      (    self   ,				lowerCAmelCase_							)		->							None:
										if self.head is None:
														self.set_head(lowerCAmelCase_							)
										else:
														self.insert_after_node(self.tail   ,				lowerCAmelCase_							)







						def 			A      (    self   ,				lowerCAmelCase_							)		->							None:
										_SCREAMING_SNAKE_CASE   :		Any       		=    Node(lowerCAmelCase_							)
										if self.head is None:
														self.set_head(lowerCAmelCase_							)
										else:
														self.set_tail(lowerCAmelCase_							)







						def 			A      (    self   ,				lowerCAmelCase_   ,				lowerCAmelCase_							)		->							None:
										_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    node
										_SCREAMING_SNAKE_CASE   :		List[Any]       		=    node.previous

										if node.get_previous() is None:
														_SCREAMING_SNAKE_CASE   :		List[Any]       		=    node_to_insert
										else:
														_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    node_to_insert

										_SCREAMING_SNAKE_CASE   :		Any       		=    node_to_insert







						def 			A      (    self   ,				lowerCAmelCase_   ,				lowerCAmelCase_							)		->							None:
										_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    node
										_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    node.next

										if node.get_next() is None:
														_SCREAMING_SNAKE_CASE   :		Tuple       		=    node_to_insert
										else:
														_SCREAMING_SNAKE_CASE   :		Any       		=    node_to_insert

										_SCREAMING_SNAKE_CASE   :		List[str]       		=    node_to_insert







						def 			A      (    self   ,				lowerCAmelCase_   ,				lowerCAmelCase_							)		->							None:
										_SCREAMING_SNAKE_CASE   :		List[Any]       		=    1
										_SCREAMING_SNAKE_CASE   :		str       		=    Node(lowerCAmelCase_							)
										_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    self.head
										while node:
														if current_position == position:
																		self.insert_before_node(lowerCAmelCase_   ,				lowerCAmelCase_							)
																		return
														current_position += 1
														_SCREAMING_SNAKE_CASE   :		List[str]       		=    node.next
										self.insert_after_node(self.tail   ,				lowerCAmelCase_							)







						def 			A      (    self   ,				lowerCAmelCase_							)		->							Node:
										_SCREAMING_SNAKE_CASE   :		Tuple       		=    self.head
										while node:
														if node.get_data() == item:
																		return node
														_SCREAMING_SNAKE_CASE   :		Dict       		=    node.get_next()
										raise Exception('Node not found'							)







						def 			A      (    self   ,				lowerCAmelCase_							)		->							int:
										if (node := self.get_node(lowerCAmelCase_							)) is not None:
														if node == self.head:
																		_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    self.head.get_next()

														if node == self.tail:
																		_SCREAMING_SNAKE_CASE   :		int       		=    self.tail.get_previous()

														self.remove_node_pointers(lowerCAmelCase_							)







						@staticmethod
						def 			A      (    lowerCAmelCase_							)		->							None:
										if node.get_next():
														_SCREAMING_SNAKE_CASE   :		List[Any]       		=    node.previous

										if node.get_previous():
														_SCREAMING_SNAKE_CASE   :		str       		=    node.next

										_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    None
										_SCREAMING_SNAKE_CASE   :		List[Any]       		=    None







						def 			A      (    self							)		->							List[str]:
										return self.head is None







def 				lowercase__		(					):
				pass


if __name__ == "__main__":
			import doctest

			doctest.testmod()

