



"""simple docstring"""





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





		"""simple docstring"""






		_lowerCamelCase      	=							IFPipeline
		_lowerCamelCase      	=							TEXT_TO_IMAGE_PARAMS - {'''width''', '''height''', '''latents'''}
		_lowerCamelCase      	=							TEXT_TO_IMAGE_BATCH_PARAMS
		_lowerCamelCase      	=							PipelineTesterMixin.required_optional_params - {'''latents'''}





		def  UpperCAmelCase__				(       self )			->    List[Any]:







								'''simple docstring'''

								return self._get_dummy_components()





		def  UpperCAmelCase__				(       self				,     _lowercase				,     _lowercase=0 )			->    List[str]:







								'''simple docstring'''

								if str(_lowercase ).startswith("""mps""" ):
														snake_case_ :			Optional[Any]            =      torch.manual_seed(_lowercase )
								else:
														snake_case_ :			int            =      torch.Generator(device=_lowercase ).manual_seed(_lowercase )

								snake_case_ :			str            =      {
								    """prompt""": """A painting of a squirrel eating a burger""",
								    """generator""": generator,
								    """num_inference_steps""": 2,
								    """output_type""": """numpy""",
								}

								return inputs





		def  UpperCAmelCase__				(       self )			->    Optional[int]:







								'''simple docstring'''

								self._test_save_load_optional_components()





		@unittest.skipIf(torch_device != """cuda"""				,     reason="""float16 requires CUDA""" )
		def  UpperCAmelCase__				(       self )			->    int:







								'''simple docstring'''

								super().test_save_load_floataa(expected_max_diff=1E-1 )





		def  UpperCAmelCase__				(       self )			->    int:







								'''simple docstring'''

								self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 )





		def  UpperCAmelCase__				(       self )			->    Optional[int]:







								'''simple docstring'''

								self._test_save_load_local()





		def  UpperCAmelCase__				(       self )			->    Dict:







								'''simple docstring'''

								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  UpperCAmelCase__				(       self )			->    List[str]:







								'''simple docstring'''

								self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 )




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





		"""simple docstring"""






		def  UpperCAmelCase__				(       self )			->    int:







								'''simple docstring'''

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





		def  UpperCAmelCase__				(       self )			->    Optional[Any]:







								'''simple docstring'''

								snake_case_ :			Union[str, Any]            =      IFPipeline.from_pretrained("""DeepFloyd/IF-I-XL-v1.0"""				,     variant="""fp16"""				,     torch_dtype=torch.floataa )

								snake_case_ :			Optional[int]            =      IFSuperResolutionPipeline.from_pretrained(
								    """DeepFloyd/IF-II-L-v1.0"""				,     variant="""fp16"""				,     torch_dtype=torch.floataa				,     text_encoder=_lowercase				,     tokenizer=_lowercase )

								# pre compute text embeddings and remove T5 to save memory

								pipe_a.text_encoder.to("""cuda""" )

								snake_case_      ,		snake_case_ :			int            =      pipe_a.encode_prompt("""anime turtle"""				,     device="""cuda""" )

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

								snake_case_ :			Union[str, Any]            =      None
								snake_case_ :			int            =      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(_lowercase				,     _lowercase				,     _lowercase				,     _lowercase )

								pipe_a.remove_all_hooks()
								pipe_a.remove_all_hooks()

								# img2img

								snake_case_ :			int            =      IFImgaImgPipeline(**pipe_a.components )
								snake_case_ :			int            =      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(_lowercase				,     _lowercase				,     _lowercase				,     _lowercase )

								pipe_a.remove_all_hooks()
								pipe_a.remove_all_hooks()

								# inpainting

								snake_case_ :			int            =      IFInpaintingPipeline(**pipe_a.components )
								snake_case_ :			List[str]            =      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(_lowercase				,     _lowercase				,     _lowercase				,     _lowercase )





		def  UpperCAmelCase__				(       self				,     _lowercase				,     _lowercase				,     _lowercase				,     _lowercase )			->    List[str]:







								'''simple docstring'''

								_start_torch_memory_measurement()

								snake_case_ :			Union[str, Any]            =      torch.Generator(device="""cpu""" ).manual_seed(0 )
								snake_case_ :			int            =      pipe_a(
								    prompt_embeds=_lowercase				,     negative_prompt_embeds=_lowercase				,     num_inference_steps=2				,     generator=_lowercase				,     output_type="""np"""				,     )

								snake_case_ :			Dict            =      output.images[0]

								assert image.shape == (6_4, 6_4, 3)

								snake_case_ :			Any            =      torch.cuda.max_memory_allocated()
								assert mem_bytes < 1_3 * 1_0**9

								snake_case_ :			Dict            =      load_numpy(
								    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy""" )
								assert_mean_pixel_difference(_lowercase				,     _lowercase )

								# pipeline 2

								_start_torch_memory_measurement()

								snake_case_ :			Union[str, Any]            =      torch.Generator(device="""cpu""" ).manual_seed(0 )

								snake_case_ :			Optional[int]            =      floats_tensor((1, 3, 6_4, 6_4)				,     rng=random.Random(0 ) ).to(_lowercase )

								snake_case_ :			str            =      pipe_a(
								    prompt_embeds=_lowercase				,     negative_prompt_embeds=_lowercase				,     image=_lowercase				,     generator=_lowercase				,     num_inference_steps=2				,     output_type="""np"""				,     )

								snake_case_ :			Union[str, Any]            =      output.images[0]

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

								snake_case_ :			Optional[Any]            =      torch.cuda.max_memory_allocated()
								assert mem_bytes < 4 * 1_0**9

								snake_case_ :			Any            =      load_numpy(
								    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy""" )
								assert_mean_pixel_difference(_lowercase				,     _lowercase )





		def  UpperCAmelCase__				(       self				,     _lowercase				,     _lowercase				,     _lowercase				,     _lowercase )			->    Any:







								'''simple docstring'''

								_start_torch_memory_measurement()

								snake_case_ :			List[str]            =      floats_tensor((1, 3, 6_4, 6_4)				,     rng=random.Random(0 ) ).to(_lowercase )

								snake_case_ :			str            =      torch.Generator(device="""cpu""" ).manual_seed(0 )

								snake_case_ :			Union[str, Any]            =      pipe_a(
								    prompt_embeds=_lowercase				,     negative_prompt_embeds=_lowercase				,     image=_lowercase				,     num_inference_steps=2				,     generator=_lowercase				,     output_type="""np"""				,     )

								snake_case_ :			List[str]            =      output.images[0]

								assert image.shape == (6_4, 6_4, 3)

								snake_case_ :			str            =      torch.cuda.max_memory_allocated()
								assert mem_bytes < 1_0 * 1_0**9

								snake_case_ :			Dict            =      load_numpy(
								    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy""" )
								assert_mean_pixel_difference(_lowercase				,     _lowercase )

								# pipeline 2

								_start_torch_memory_measurement()

								snake_case_ :			Optional[int]            =      torch.Generator(device="""cpu""" ).manual_seed(0 )

								snake_case_ :			Union[str, Any]            =      floats_tensor((1, 3, 2_5_6, 2_5_6)				,     rng=random.Random(0 ) ).to(_lowercase )
								snake_case_ :			Optional[int]            =      floats_tensor((1, 3, 6_4, 6_4)				,     rng=random.Random(0 ) ).to(_lowercase )

								snake_case_ :			Union[str, Any]            =      pipe_a(
								    prompt_embeds=_lowercase				,     negative_prompt_embeds=_lowercase				,     image=_lowercase				,     original_image=_lowercase				,     generator=_lowercase				,     num_inference_steps=2				,     output_type="""np"""				,     )

								snake_case_ :			Optional[int]            =      output.images[0]

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

								snake_case_ :			int            =      torch.cuda.max_memory_allocated()
								assert mem_bytes < 4 * 1_0**9

								snake_case_ :			str            =      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(_lowercase				,     _lowercase )





		def  UpperCAmelCase__				(       self				,     _lowercase				,     _lowercase				,     _lowercase				,     _lowercase )			->    List[str]:







								'''simple docstring'''

								_start_torch_memory_measurement()

								snake_case_ :			List[Any]            =      floats_tensor((1, 3, 6_4, 6_4)				,     rng=random.Random(0 ) ).to(_lowercase )
								snake_case_ :			List[str]            =      floats_tensor((1, 3, 6_4, 6_4)				,     rng=random.Random(1 ) ).to(_lowercase )

								snake_case_ :			Optional[Any]            =      torch.Generator(device="""cpu""" ).manual_seed(0 )
								snake_case_ :			int            =      pipe_a(
								    prompt_embeds=_lowercase				,     negative_prompt_embeds=_lowercase				,     image=_lowercase				,     mask_image=_lowercase				,     num_inference_steps=2				,     generator=_lowercase				,     output_type="""np"""				,     )

								snake_case_ :			Any            =      output.images[0]

								assert image.shape == (6_4, 6_4, 3)

								snake_case_ :			List[Any]            =      torch.cuda.max_memory_allocated()
								assert mem_bytes < 1_0 * 1_0**9

								snake_case_ :			Any            =      load_numpy(
								    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy""" )
								assert_mean_pixel_difference(_lowercase				,     _lowercase )

								# pipeline 2

								_start_torch_memory_measurement()

								snake_case_ :			Optional[int]            =      torch.Generator(device="""cpu""" ).manual_seed(0 )

								snake_case_ :			Optional[int]            =      floats_tensor((1, 3, 6_4, 6_4)				,     rng=random.Random(0 ) ).to(_lowercase )
								snake_case_ :			Dict            =      floats_tensor((1, 3, 2_5_6, 2_5_6)				,     rng=random.Random(0 ) ).to(_lowercase )
								snake_case_ :			List[Any]            =      floats_tensor((1, 3, 2_5_6, 2_5_6)				,     rng=random.Random(1 ) ).to(_lowercase )

								snake_case_ :			int            =      pipe_a(
								    prompt_embeds=_lowercase				,     negative_prompt_embeds=_lowercase				,     image=_lowercase				,     mask_image=_lowercase				,     original_image=_lowercase				,     generator=_lowercase				,     num_inference_steps=2				,     output_type="""np"""				,     )

								snake_case_ :			Dict            =      output.images[0]

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

								snake_case_ :			List[str]            =      torch.cuda.max_memory_allocated()
								assert mem_bytes < 4 * 1_0**9

								snake_case_ :			Optional[Any]            =      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(_lowercase				,     _lowercase )




def 						__lowerCAmelCase    (		):


						'''simple docstring'''






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







class 			lowerCamelCase_				:


 '''simple docstring'''







 def __init__(				self    :						str		):
       SCREAMING_SNAKE_CASE_      		=     {}



 def  lowerCAmelCase_    (				self    :						List[str]		):
       print(self.vertex		)
       for i in self.vertex:
             print(_lowerCAmelCase							,							' -> '							,							' -> '.join([str(_lowerCAmelCase		) for j in self.vertex[i]]		)		)



 def  lowerCAmelCase_    (				self    :						Union[str, Any]							,							_lowerCAmelCase    :						int							,							_lowerCAmelCase    :						int		):
       # check if vertex is already present,
       if from_vertex in self.vertex:
             self.vertex[from_vertex].append(_lowerCAmelCase		)
       else:
             # else make a new vertex
             SCREAMING_SNAKE_CASE_      		=     [to_vertex]



 def  lowerCAmelCase_    (				self    :						Optional[Any]		):
       # visited array for storing already visited nodes
       SCREAMING_SNAKE_CASE_      		=     [False] * len(self.vertex		)

       # call the recursive helper function
       for i in range(len(self.vertex		)		):
             if not visited[i]:
                   self.dfs_recursive(_lowerCAmelCase							,							_lowerCAmelCase		)




 def  lowerCAmelCase_    (				self    :						Tuple							,							_lowerCAmelCase    :						int							,							_lowerCAmelCase    :						list		):
       # mark start vertex as visited
       SCREAMING_SNAKE_CASE_      		=     True

       print(_lowerCAmelCase							,							end=' '		)

       # Recur for all the vertices that are adjacent to this node
       for i in self.vertex:
             if not visited[i]:
                   self.dfs_recursive(_lowerCAmelCase							,							_lowerCAmelCase		)


if __name__ == "__main__":
   lowerCamelCase__					:  List[Any]      							=				Graph()
   g.add_edge(0, 1)
   g.add_edge(0, 2)
   g.add_edge(1, 2)
   g.add_edge(2, 0)
   g.add_edge(2, 3)
   g.add_edge(3, 3)

   g.print_graph()
   print('DFS:')
   g.dfs()

   # OUTPUT:
   # 0  ->  1 -> 2
   # 1  ->  2
   # 2  ->  0 -> 3
   # 3  ->  3
   # DFS:
   #  0 1 2 3