





'''simple docstring'''


import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizer

from diffusers import (
    AltDiffusionImgaImgPipeline,
    AutoencoderKL,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
    RobertaSeriesConfig,
    RobertaSeriesModelWithTransformation,
)
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 				a_       (				unittest.TestCase							):





     def 							lowercase__				(			self		: Optional[int]						):





        """simple docstring"""




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





     @property
     def 							lowercase__				(			self		: int						):





        """simple docstring"""




        lowercase_      :int         =			1
        lowercase_      :List[str]         =			3
        lowercase_      :List[Any]         =			(32, 32)

        lowercase_      :Optional[int]         =			floats_tensor((batch_size, num_channels) + sizes     ,				rng=random.Random(0						)						).to(lowercase						)
        return image





     @property
     def 							lowercase__				(			self		: Any						):





        """simple docstring"""




        torch.manual_seed(0						)
        lowercase_      :str         =			UNetaDConditionModel(
            block_out_channels=(32, 64)     ,				layers_per_block=2     ,				sample_size=32     ,				in_channels=4     ,				out_channels=4     ,				down_block_types=("DownBlock2D", "CrossAttnDownBlock2D")     ,				up_block_types=("CrossAttnUpBlock2D", "UpBlock2D")     ,				cross_attention_dim=32     ,				)
        return model





     @property
     def 							lowercase__				(			self		: List[Any]						):





        """simple docstring"""




        torch.manual_seed(0						)
        lowercase_      :List[str]         =			AutoencoderKL(
            block_out_channels=[32, 64]     ,				in_channels=3     ,				out_channels=3     ,				down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"]     ,				up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"]     ,				latent_channels=4     ,				)
        return model





     @property
     def 							lowercase__				(			self		: Union[str, Any]						):





        """simple docstring"""




        torch.manual_seed(0						)
        lowercase_      :str         =			RobertaSeriesConfig(
            hidden_size=32     ,				project_dim=32     ,				intermediate_size=37     ,				layer_norm_eps=1e-0_5     ,				num_attention_heads=4     ,				num_hidden_layers=5     ,				pad_token_id=1     ,				vocab_size=5_006     ,				)
        return RobertaSeriesModelWithTransformation(lowercase						)





     @property
     def 							lowercase__				(			self		: int						):





        """simple docstring"""




        def extract(*lowercase		: int     ,				**lowercase		: List[Any]						):
           class 				a_       :





                def __init__(			self		: str						):





                   """simple docstring"""




                   lowercase_      :List[Any]         =			torch.ones([0]						)







                def 							lowercase__				(			self		: List[str]     ,				lowercase		: str						):





                   """simple docstring"""




                   self.pixel_values.to(lowercase						)
                   return self







           return Out()

        return extract





     def 							lowercase__				(			self		: Dict						):





        """simple docstring"""




        lowercase_      :Dict         =			"cpu"  # ensure determinism for the device-dependent torch.Generator
        lowercase_      :Dict         =			self.dummy_cond_unet
        lowercase_      :List[str]         =			PNDMScheduler(skip_prk_steps=lowercase						)
        lowercase_      :Any         =			self.dummy_vae
        lowercase_      :Union[str, Any]         =			self.dummy_text_encoder
        lowercase_      :int         =			XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta"						)
        lowercase_      :List[str]         =			77

        lowercase_      :List[Any]         =			self.dummy_image.to(lowercase						)
        lowercase_      :Dict         =			init_image / 2 + 0.5

        # make sure here that pndm scheduler skips prk
        lowercase_      :Union[str, Any]         =			AltDiffusionImgaImgPipeline(
            unet=lowercase     ,				scheduler=lowercase     ,				vae=lowercase     ,				text_encoder=lowercase     ,				tokenizer=lowercase     ,				safety_checker=lowercase     ,				feature_extractor=self.dummy_extractor     ,				)
        lowercase_      :List[str]         =			VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor     ,				do_normalize=lowercase						)
        lowercase_      :str         =			alt_pipe.to(lowercase						)
        alt_pipe.set_progress_bar_config(disable=lowercase						)

        lowercase_      :Optional[Any]         =			"A painting of a squirrel eating a burger"
        lowercase_      :Any         =			torch.Generator(device=lowercase						).manual_seed(0						)
        lowercase_      :int         =			alt_pipe(
            [prompt]     ,				generator=lowercase     ,				guidance_scale=6.0     ,				num_inference_steps=2     ,				output_type="np"     ,				image=lowercase     ,				)

        lowercase_      :Union[str, Any]         =			output.images

        lowercase_      :Tuple         =			torch.Generator(device=lowercase						).manual_seed(0						)
        lowercase_      :str         =			alt_pipe(
            [prompt]     ,				generator=lowercase     ,				guidance_scale=6.0     ,				num_inference_steps=2     ,				output_type="np"     ,				image=lowercase     ,				return_dict=lowercase     ,				)[0]

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

        assert image.shape == (1, 32, 32, 3)
        lowercase_      :List[str]         =			np.array([0.44_27, 0.37_31, 0.42_49, 0.49_41, 0.45_46, 0.41_48, 0.41_93, 0.46_66, 0.44_99]						)

        assert np.abs(image_slice.flatten() - expected_slice						).max() < 5e-3
        assert np.abs(image_from_tuple_slice.flatten() - expected_slice						).max() < 5e-3





     @unittest.skipIf(torch_device != "cuda"     ,				"This test requires a GPU"						)
     def 							lowercase__				(			self		: Union[str, Any]						):





        """simple docstring"""




        lowercase_      :Any         =			self.dummy_cond_unet
        lowercase_      :List[Any]         =			PNDMScheduler(skip_prk_steps=lowercase						)
        lowercase_      :Optional[int]         =			self.dummy_vae
        lowercase_      :str         =			self.dummy_text_encoder
        lowercase_      :List[str]         =			XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta"						)
        lowercase_      :int         =			77

        lowercase_      :Optional[Any]         =			self.dummy_image.to(lowercase						)

        # put models in fp16
        lowercase_      :List[str]         =			unet.half()
        lowercase_      :Any         =			vae.half()
        lowercase_      :List[str]         =			bert.half()

        # make sure here that pndm scheduler skips prk
        lowercase_      :Union[str, Any]         =			AltDiffusionImgaImgPipeline(
            unet=lowercase     ,				scheduler=lowercase     ,				vae=lowercase     ,				text_encoder=lowercase     ,				tokenizer=lowercase     ,				safety_checker=lowercase     ,				feature_extractor=self.dummy_extractor     ,				)
        lowercase_      :Optional[Any]         =			VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor     ,				do_normalize=lowercase						)
        lowercase_      :Tuple         =			alt_pipe.to(lowercase						)
        alt_pipe.set_progress_bar_config(disable=lowercase						)

        lowercase_      :Optional[Any]         =			"A painting of a squirrel eating a burger"
        lowercase_      :Any         =			torch.manual_seed(0						)
        lowercase_      :Any         =			alt_pipe(
            [prompt]     ,				generator=lowercase     ,				num_inference_steps=2     ,				output_type="np"     ,				image=lowercase     ,				).images

        assert image.shape == (1, 32, 32, 3)







     @unittest.skipIf(torch_device != "cuda"     ,				"This test requires a GPU"						)
     def 							lowercase__				(			self		: Any						):





        """simple docstring"""




        lowercase_      :Union[str, Any]         =			load_image(
            "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
            "/img2img/sketch-mountains-input.jpg"						)
        # resize to resolution that is divisible by 8 but not 16 or 32
        lowercase_      :int         =			init_image.resize((760, 504)						)

        lowercase_      :Union[str, Any]         =			"BAAI/AltDiffusion"
        lowercase_      :Union[str, Any]         =			AltDiffusionImgaImgPipeline.from_pretrained(
            lowercase     ,				safety_checker=lowercase     ,				)
        pipe.to(lowercase						)
        pipe.set_progress_bar_config(disable=lowercase						)
        pipe.enable_attention_slicing()

        lowercase_      :Union[str, Any]         =			"A fantasy landscape, trending on artstation"

        lowercase_      :str         =			torch.manual_seed(0						)
        lowercase_      :Dict         =			pipe(
            prompt=lowercase     ,				image=lowercase     ,				strength=0.75     ,				guidance_scale=7.5     ,				generator=lowercase     ,				output_type="np"     ,				)
        lowercase_      :Dict         =			output.images[0]

        lowercase_      :Any         =			image[255:258, 383:386, -1]

        assert image.shape == (504, 760, 3)
        lowercase_      :List[Any]         =			np.array([0.93_58, 0.93_97, 0.95_99, 0.99_01, 1.00_00, 1.00_00, 0.98_82, 1.00_00, 1.00_00]						)

        assert np.abs(image_slice.flatten() - expected_slice						).max() < 1e-2







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





     def 							lowercase__				(			self		: Optional[Any]						):





        """simple docstring"""




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







     def 							lowercase__				(			self		: Optional[int]						):





        """simple docstring"""




        lowercase_      :Union[str, Any]         =			load_image(
            "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
            "/img2img/sketch-mountains-input.jpg"						)
        lowercase_      :Union[str, Any]         =			init_image.resize((768, 512)						)
        lowercase_      :str         =			load_numpy(
            "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy"						)

        lowercase_      :Union[str, Any]         =			"BAAI/AltDiffusion"
        lowercase_      :Tuple         =			AltDiffusionImgaImgPipeline.from_pretrained(
            lowercase     ,				safety_checker=lowercase     ,				)
        pipe.to(lowercase						)
        pipe.set_progress_bar_config(disable=lowercase						)
        pipe.enable_attention_slicing()

        lowercase_      :Tuple         =			"A fantasy landscape, trending on artstation"

        lowercase_      :Dict         =			torch.manual_seed(0						)
        lowercase_      :List[str]         =			pipe(
            prompt=lowercase     ,				image=lowercase     ,				strength=0.75     ,				guidance_scale=7.5     ,				generator=lowercase     ,				output_type="np"     ,				)
        lowercase_      :Dict         =			output.images[0]

        assert image.shape == (512, 768, 3)
        # img2img is flaky across GPUs even in fp32, so using MAE here
        assert np.abs(expected_image - image						).max() < 1e-2









'''simple docstring'''


def 							UpperCAmelCase_  (						__lowerCamelCase : dict			):
   lowercase_      :set[int]         =			set()
   # To detect a back edge, keep track of vertices currently in the recursion stack
   lowercase_      :set[int]         =			set()
   return any(
       node not in visited and depth_first_search(__lowerCamelCase     ,__lowerCamelCase     ,__lowerCamelCase     ,__lowerCamelCase			)
       for node in graph			)
def 							UpperCAmelCase_  (						__lowerCamelCase : dict     ,__lowerCamelCase : int     ,__lowerCamelCase : set     ,__lowerCamelCase : set			):
   visited.add(__lowerCamelCase			)
   rec_stk.add(__lowerCamelCase			)

   for node in graph[vertex]:
      if node not in visited:
         if depth_first_search(__lowerCamelCase     ,__lowerCamelCase     ,__lowerCamelCase     ,__lowerCamelCase			):
            return True
      elif node in rec_stk:
         return True

    # The node needs to be removed from recursion stack before function ends
   rec_stk.remove(__lowerCamelCase			)
   return False


if __name__ == "__main__":
 from doctest import testmod

 testmod()


