





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




 """simple docstring"""



 def        _lowerCamelCase					(       self       :							List[str]	):
        # clean up the VRAM after each test
        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()






 @property
 def        _lowerCamelCase					(       self       :							Any	):
        __UpperCamelCase       =  1
        __UpperCamelCase       =  3
        __UpperCamelCase       =  (3_2, 3_2)

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






 @property
 def        _lowerCamelCase					(       self       :							int	):
        torch.manual_seed(0	)
        __UpperCamelCase       =  UNetaDConditionModel(
            block_out_channels=(3_2, 6_4)							,	layers_per_block=2							,	sample_size=3_2							,	in_channels=4							,	out_channels=4							,	down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')							,	up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')							,	cross_attention_dim=3_2							,	)
        return model






 @property
 def        _lowerCamelCase					(       self       :							int	):
        torch.manual_seed(0	)
        __UpperCamelCase       =  AutoencoderKL(
            block_out_channels=[3_2, 6_4]							,	in_channels=3							,	out_channels=3							,	down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']							,	up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']							,	latent_channels=4							,	)
        return model






 @property
 def        _lowerCamelCase					(       self       :							Any	):
        torch.manual_seed(0	)
        __UpperCamelCase       =  RobertaSeriesConfig(
            hidden_size=3_2							,	project_dim=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=5_0_0_6							,	)
        return RobertaSeriesModelWithTransformation(__A	)






 @property
 def        _lowerCamelCase					(       self       :							Any	):
        def extract(*__A       :							int							,	**__A       :							Dict	):

               class      snake_case     :




                """simple docstring"""



                def __init__(       self       :							int	):
                       __UpperCamelCase       =  torch.ones([0]	)






                def        _lowerCamelCase					(       self       :							int							,	__A       :							Union[str, Any]	):
                       self.pixel_values.to(__A	)
                       return self






               return Out()

        return extract






 def        _lowerCamelCase					(       self       :							Optional[Any]	):
        __UpperCamelCase       =  'cpu'  # ensure determinism for the device-dependent torch.Generator
        __UpperCamelCase       =  self.dummy_cond_unet
        __UpperCamelCase       =  PNDMScheduler(skip_prk_steps=__A	)
        __UpperCamelCase       =  self.dummy_vae
        __UpperCamelCase       =  self.dummy_text_encoder
        __UpperCamelCase       =  XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'	)
        __UpperCamelCase       =  7_7

        __UpperCamelCase       =  self.dummy_image.to(__A	)
        __UpperCamelCase       =  init_image / 2 + 0.5

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

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

        __UpperCamelCase       =  output.images

        __UpperCamelCase       =  torch.Generator(device=__A	).manual_seed(0	)
        __UpperCamelCase       =  alt_pipe(
            [prompt]							,	generator=__A							,	guidance_scale=6.0							,	num_inference_steps=2							,	output_type='np'							,	image=__A							,	return_dict=__A							,	)[0]

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

        assert image.shape == (1, 3_2, 3_2, 3)
        __UpperCamelCase       =  np.array([0.4427, 0.3731, 0.4249, 0.4941, 0.4546, 0.4148, 0.4193, 0.4666, 0.4499]	)

        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        _lowerCamelCase					(       self       :							int	):
        __UpperCamelCase       =  self.dummy_cond_unet
        __UpperCamelCase       =  PNDMScheduler(skip_prk_steps=__A	)
        __UpperCamelCase       =  self.dummy_vae
        __UpperCamelCase       =  self.dummy_text_encoder
        __UpperCamelCase       =  XLMRobertaTokenizer.from_pretrained('hf-internal-testing/tiny-xlm-roberta'	)
        __UpperCamelCase       =  7_7

        __UpperCamelCase       =  self.dummy_image.to(__A	)

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

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

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

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






 @unittest.skipIf(torch_device != 'cuda'							,	'This test requires a GPU'	)
 def        _lowerCamelCase					(       self       :							Tuple	):
        __UpperCamelCase       =  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
        __UpperCamelCase       =  init_image.resize((7_6_0, 5_0_4)	)

        __UpperCamelCase       =  'BAAI/AltDiffusion'
        __UpperCamelCase       =  AltDiffusionImgaImgPipeline.from_pretrained(
            __A							,	safety_checker=__A							,	)
        pipe.to(__A	)
        pipe.set_progress_bar_config(disable=__A	)
        pipe.enable_attention_slicing()

        __UpperCamelCase       =  'A fantasy landscape, trending on artstation'

        __UpperCamelCase       =  torch.manual_seed(0	)
        __UpperCamelCase       =  pipe(
            prompt=__A							,	image=__A							,	strength=0.75							,	guidance_scale=7.5							,	generator=__A							,	output_type='np'							,	)
        __UpperCamelCase       =  output.images[0]

        __UpperCamelCase       =  image[2_5_5:2_5_8, 3_8_3:3_8_6, -1]

        assert image.shape == (5_0_4, 7_6_0, 3)
        __UpperCamelCase       =  np.array([0.9358, 0.9397, 0.9599, 0.9901, 1.0000, 1.0000, 0.9882, 1.0000, 1.0000]	)

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






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




 """simple docstring"""



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






 def        _lowerCamelCase					(       self       :							Tuple	):
        __UpperCamelCase       =  load_image(
            'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
            '/img2img/sketch-mountains-input.jpg'	)
        __UpperCamelCase       =  init_image.resize((7_6_8, 5_1_2)	)
        __UpperCamelCase       =  load_numpy(
            'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy'	)

        __UpperCamelCase       =  'BAAI/AltDiffusion'
        __UpperCamelCase       =  AltDiffusionImgaImgPipeline.from_pretrained(
            __A							,	safety_checker=__A							,	)
        pipe.to(__A	)
        pipe.set_progress_bar_config(disable=__A	)
        pipe.enable_attention_slicing()

        __UpperCamelCase       =  'A fantasy landscape, trending on artstation'

        __UpperCamelCase       =  torch.manual_seed(0	)
        __UpperCamelCase       =  pipe(
            prompt=__A							,	image=__A							,	strength=0.75							,	guidance_scale=7.5							,	generator=__A							,	output_type='np'							,	)
        __UpperCamelCase       =  output.images[0]

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







'''simple docstring'''
from ...utils import (
    OptionalDependencyNotAvailable,
    is_torch_available,
    is_transformers_available,
    is_transformers_version,
)


try:
    if not (is_transformers_available() and is_torch_available() and is_transformers_version('''>=''', '''4.25.0''')):
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    from ...utils.dummy_torch_and_transformers_objects import (
        VersatileDiffusionDualGuidedPipeline,
        VersatileDiffusionImageVariationPipeline,
        VersatileDiffusionPipeline,
        VersatileDiffusionTextToImagePipeline,
    )
else:
    from .modeling_text_unet import UNetFlatConditionModel
    from .pipeline_versatile_diffusion import VersatileDiffusionPipeline
    from .pipeline_versatile_diffusion_dual_guided import VersatileDiffusionDualGuidedPipeline
    from .pipeline_versatile_diffusion_image_variation import VersatileDiffusionImageVariationPipeline
    from .pipeline_versatile_diffusion_text_to_image import VersatileDiffusionTextToImagePipeline
