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







						'''simple docstring'''



						def        SCREAMING_SNAKE_CASE(			self							:List[Any]     )  ->int:
										# clean up the VRAM after each test
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()





						@property
						def        SCREAMING_SNAKE_CASE(			self							:Dict     )  ->List[str]:
										lowercase         =      1
										lowercase         =      3
										lowercase         =      (32, 32)

										lowercase         =      floats_tensor((batch_size, num_channels) + sizes		,    rng=random.Random(0     )     ).to(lowerCAmelCase__     )
										return image





						@property
						def        SCREAMING_SNAKE_CASE(			self							:List[str]     )  ->Optional[int]:
										torch.manual_seed(0     )
										lowercase         =      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        SCREAMING_SNAKE_CASE(			self							:str     )  ->int:
										torch.manual_seed(0     )
										lowercase         =      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        SCREAMING_SNAKE_CASE(			self							:Optional[Any]     )  ->int:
										torch.manual_seed(0     )
										lowercase         =      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=5006		,    )
										return RobertaSeriesModelWithTransformation(lowerCAmelCase__     )





						@property
						def        SCREAMING_SNAKE_CASE(			self							:Any     )  ->Any:
										def extract(*lowerCAmelCase__							:str		,    **lowerCAmelCase__							:List[str]     ):





														class   UpperCamelCase_      :







																				'''simple docstring'''



																				def __init__(			self							:List[str]     )  ->List[str]:
																								lowercase         =      torch.ones([0]     )





																				def        SCREAMING_SNAKE_CASE(			self							:Optional[int]		,    lowerCAmelCase__							:Optional[int]     )  ->Tuple:
																								self.pixel_values.to(lowerCAmelCase__     )
																								return self




														return Out()

										return extract





						def        SCREAMING_SNAKE_CASE(			self							:Dict     )  ->Optional[int]:
										lowercase         =      "cpu"  # ensure determinism for the device-dependent torch.Generator
										lowercase         =      self.dummy_cond_unet
										lowercase         =      PNDMScheduler(skip_prk_steps=lowerCAmelCase__     )
										lowercase         =      self.dummy_vae
										lowercase         =      self.dummy_text_encoder
										lowercase         =      XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta"     )
										lowercase         =      77

										lowercase         =      self.dummy_image.to(lowerCAmelCase__     )
										lowercase         =      init_image / 2 + 0.5

										# make sure here that pndm scheduler skips prk
										lowercase         =      AltDiffusionImgaImgPipeline(
										    unet=lowerCAmelCase__		,    scheduler=lowerCAmelCase__		,    vae=lowerCAmelCase__		,    text_encoder=lowerCAmelCase__		,    tokenizer=lowerCAmelCase__		,    safety_checker=lowerCAmelCase__		,    feature_extractor=self.dummy_extractor		,    )
										lowercase         =      VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor		,    do_normalize=lowerCAmelCase__     )
										lowercase         =      alt_pipe.to(lowerCAmelCase__     )
										alt_pipe.set_progress_bar_config(disable=lowerCAmelCase__     )

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

										lowercase         =      output.images

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

										lowercase         =      image[0, -3:, -3:, -1]
										lowercase         =      image_from_tuple[0, -3:, -3:, -1]

										assert image.shape == (1, 32, 32, 3)
										lowercase         =      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        SCREAMING_SNAKE_CASE(			self							:str     )  ->Any:
										lowercase         =      self.dummy_cond_unet
										lowercase         =      PNDMScheduler(skip_prk_steps=lowerCAmelCase__     )
										lowercase         =      self.dummy_vae
										lowercase         =      self.dummy_text_encoder
										lowercase         =      XLMRobertaTokenizer.from_pretrained("hf-internal-testing/tiny-xlm-roberta"     )
										lowercase         =      77

										lowercase         =      self.dummy_image.to(lowerCAmelCase__     )

										# put models in fp16
										lowercase         =      unet.half()
										lowercase         =      vae.half()
										lowercase         =      bert.half()

										# make sure here that pndm scheduler skips prk
										lowercase         =      AltDiffusionImgaImgPipeline(
										    unet=lowerCAmelCase__		,    scheduler=lowerCAmelCase__		,    vae=lowerCAmelCase__		,    text_encoder=lowerCAmelCase__		,    tokenizer=lowerCAmelCase__		,    safety_checker=lowerCAmelCase__		,    feature_extractor=self.dummy_extractor		,    )
										lowercase         =      VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor		,    do_normalize=lowerCAmelCase__     )
										lowercase         =      alt_pipe.to(lowerCAmelCase__     )
										alt_pipe.set_progress_bar_config(disable=lowerCAmelCase__     )

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

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





						@unittest.skipIf(torch_device != "cuda"		,    "This test requires a GPU"     )
						def        SCREAMING_SNAKE_CASE(			self							:Optional[int]     )  ->Optional[int]:
										lowercase         =      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         =      init_image.resize((760, 504)     )

										lowercase         =      "BAAI/AltDiffusion"
										lowercase         =      AltDiffusionImgaImgPipeline.from_pretrained(
										    lowerCAmelCase__		,    safety_checker=lowerCAmelCase__		,    )
										pipe.to(lowerCAmelCase__     )
										pipe.set_progress_bar_config(disable=lowerCAmelCase__     )
										pipe.enable_attention_slicing()

										lowercase         =      "A fantasy landscape, trending on artstation"

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

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

										assert image.shape == (504, 760, 3)
										lowercase         =      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   UpperCamelCase_      (      unittest.TestCase		):







						'''simple docstring'''



						def        SCREAMING_SNAKE_CASE(			self							:Optional[int]     )  ->Optional[Any]:
										# clean up the VRAM after each test
										super().tearDown()
										gc.collect()
										torch.cuda.empty_cache()





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

										lowercase         =      "BAAI/AltDiffusion"
										lowercase         =      AltDiffusionImgaImgPipeline.from_pretrained(
										    lowerCAmelCase__		,    safety_checker=lowerCAmelCase__		,    )
										pipe.to(lowerCAmelCase__     )
										pipe.set_progress_bar_config(disable=lowerCAmelCase__     )
										pipe.enable_attention_slicing()

										lowercase         =      "A fantasy landscape, trending on artstation"

										lowercase         =      torch.manual_seed(0     )
										lowercase         =      pipe(
										    prompt=lowerCAmelCase__		,    image=lowerCAmelCase__		,    strength=0.75		,    guidance_scale=7.5		,    generator=lowerCAmelCase__		,    output_type="np"		,    )
										lowercase         =      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


def  __snake_case							(	__magic_name__						):







				'''simple docstring'''


				lowercase         =      set()
				# To detect a back edge, keep track of vertices currently in the recursion stack
				lowercase         =      set()
				return any(
				    node not in visited and depth_first_search(__magic_name__		,    __magic_name__		,    __magic_name__		,    __magic_name__						)
				    for node in graph						)

def  __snake_case							(	__magic_name__		,    __magic_name__		,    __magic_name__		,    __magic_name__						):







				'''simple docstring'''


				visited.add(__magic_name__						)
				rec_stk.add(__magic_name__						)

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

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


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

						testmod()
