



"""simple docstring"""
import gc
import random
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()




class 			snake_case_						(						lowercase__     ,lowercase__     ,unittest.TestCase				):
							__lowerCAmelCase    					=					StableDiffusionXLImgaImgPipeline
							__lowerCAmelCase    					=					TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"}
							__lowerCAmelCase    					=					PipelineTesterMixin.required_optional_params - {"latents"}
							__lowerCAmelCase    					=					TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
							__lowerCAmelCase    					=					IMAGE_TO_IMAGE_IMAGE_PARAMS
							__lowerCAmelCase    					=					IMAGE_TO_IMAGE_IMAGE_PARAMS






							def snake_case_  (   self      ):
									torch.manual_seed(0      )
									a_     :      List[Any] 						=     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")			,     attention_head_dim=(2, 4)			,     use_linear_projection=a_			,     addition_embed_type="text_time"			,     addition_time_embed_dim=8			,     transformer_layers_per_block=(1, 2)			,     projection_class_embeddings_input_dim=8_0			,     cross_attention_dim=6_4			,     )
									a_     :      str 						=     EulerDiscreteScheduler(
									    beta_start=0.00_085			,     beta_end=0.012			,     steps_offset=1			,     beta_schedule="scaled_linear"			,     timestep_spacing="leading"			,     )
									torch.manual_seed(0      )
									a_     :      Tuple 						=     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			,     sample_size=1_2_8			,     )
									torch.manual_seed(0      )
									a_     :      int 						=     CLIPTextConfig(
									    bos_token_id=0			,     eos_token_id=2			,     hidden_size=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=1_0_0_0			,     hidden_act="gelu"			,     projection_dim=3_2			,     )
									a_     :      Tuple 						=     CLIPTextModel(a_      )
									a_     :      Union[str, Any] 						=     CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"			,     local_files_only=a_      )

									a_     :      Union[str, Any] 						=     CLIPTextModelWithProjection(a_      )
									a_     :      str 						=     CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"			,     local_files_only=a_      )

									a_     :      str 						=     {
									    "unet": unet,
									    "scheduler": scheduler,
									    "vae": vae,
									    "text_encoder": text_encoder,
									    "tokenizer": tokenizer,
									    "text_encoder_2": text_encoder_a,
									    "tokenizer_2": tokenizer_a,
									    # "safety_checker": None,
									    # "feature_extractor": None,
									}
									return components






							def snake_case_  (   self			,     a_			,     a_=0      ):
									a_     :      Optional[int] 						=     floats_tensor((1, 3, 3_2, 3_2)			,     rng=random.Random(a_      )      ).to(a_      )
									a_     :      Optional[int] 						=     image / 2 + 0.5
									if str(a_      ).startswith("mps"      ):
											a_     :      Tuple 						=     torch.manual_seed(a_      )
									else:
											a_     :      Optional[Any] 						=     torch.Generator(device=a_      ).manual_seed(a_      )
									a_     :      int 						=     {
									    "prompt": "A painting of a squirrel eating a burger",
									    "image": image,
									    "generator": generator,
									    "num_inference_steps": 2,
									    "guidance_scale": 5.0,
									    "output_type": "numpy",
									    "strength": 0.75,
									}
									return inputs






							def snake_case_  (   self      ):
									a_     :      Optional[int] 						=     "cpu"  # ensure determinism for the device-dependent torch.Generator
									a_     :      int 						=     self.get_dummy_components()
									a_     :      str 						=     StableDiffusionXLImgaImgPipeline(**a_      )
									a_     :      str 						=     sd_pipe.to(a_      )
									sd_pipe.set_progress_bar_config(disable=a_      )

									a_     :      Optional[int] 						=     self.get_dummy_inputs(a_      )
									a_     :      Union[str, Any] 						=     sd_pipe(**a_      ).images
									a_     :      Tuple 						=     image[0, -3:, -3:, -1]

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

									a_     :      List[Any] 						=     np.array([0.4_656, 0.4_840, 0.4_439, 0.6_698, 0.5_574, 0.4_524, 0.5_799, 0.5_943, 0.5_165]      )

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






							def snake_case_  (   self      ):
									super().test_attention_slicing_forward_pass(expected_max_diff=3e-3      )






							def snake_case_  (   self      ):
									super().test_inference_batch_single_identical(expected_max_diff=3e-3      )






							def snake_case_  (   self      ):
									pass






							def snake_case_  (   self      ):
									a_     :      List[Any] 						=     self.get_dummy_components()
									a_     :      Optional[int] 						=     StableDiffusionXLImgaImgPipeline(**a_      )
									a_     :      str 						=     sd_pipe.to(a_      )
									a_     :      Optional[Any] 						=     sd_pipe.to(a_      )
									sd_pipe.set_progress_bar_config(disable=a_      )

									# forward without prompt embeds
									a_     :      Union[str, Any] 						=     self.get_dummy_inputs(a_      )
									a_     :      Any 						=     3 * ["this is a negative prompt"]
									a_     :      Dict 						=     negative_prompt
									a_     :      str 						=     3 * [inputs["prompt"]]

									a_     :      Optional[int] 						=     sd_pipe(**a_      )
									a_     :      Union[str, Any] 						=     output.images[0, -3:, -3:, -1]

									# forward with prompt embeds
									a_     :      List[str] 						=     self.get_dummy_inputs(a_      )
									a_     :      List[Any] 						=     3 * ["this is a negative prompt"]
									a_     :      List[str] 						=     3 * [inputs.pop("prompt"      )]

									(
									    a_							
									)     :      Optional[Any] 						=     sd_pipe.encode_prompt(a_			,     negative_prompt=a_      )

									a_     :      Tuple 						=     sd_pipe(
									    **a_			,     prompt_embeds=a_			,     negative_prompt_embeds=a_			,     pooled_prompt_embeds=a_			,     negative_pooled_prompt_embeds=a_			,     )
									a_     :      Union[str, Any] 						=     output.images[0, -3:, -3:, -1]

									# make sure that it's equal
									assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()      ).max() < 1e-4




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






							def snake_case_  (   self      ):
									super().tearDown()
									gc.collect()
									torch.cuda.empty_cache()






							def snake_case_  (   self			,     a_			,     a_="cpu"			,     a_=torch.floataa			,     a_=0      ):
									a_     :      int 						=     torch.Generator(device=a_      ).manual_seed(a_      )
									a_     :      str 						=     np.random.RandomState(a_      ).standard_normal((1, 4, 6_4, 6_4)      )
									a_     :      Optional[int] 						=     torch.from_numpy(a_      ).to(device=a_			,     dtype=a_      )
									a_     :      Any 						=     {
									    "prompt": "a photograph of an astronaut riding a horse",
									    "latents": latents,
									    "generator": generator,
									    "num_inference_steps": 3,
									    "guidance_scale": 7.5,
									    "output_type": "numpy",
									}
									return inputs






							def snake_case_  (   self      ):
									a_     :      Dict 						=     DiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-base"      )
									pipe.to(a_      )
									pipe.set_progress_bar_config(disable=a_      )

									a_     :      List[str] 						=     self.get_inputs(a_      )
									a_     :      List[Any] 						=     pipe(**a_      ).images
									a_     :      str 						=     image[0, -3:, -3:, -1].flatten()

									assert image.shape == (1, 5_1_2, 5_1_2, 3)
									a_     :      Union[str, Any] 						=     np.array([0.49_493, 0.47_896, 0.40_798, 0.54_214, 0.53_212, 0.48_202, 0.47_656, 0.46_329, 0.48_506]      )
									assert np.abs(image_slice - expected_slice      ).max() < 7e-3




"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging


SCREAMING_SNAKE_CASE_				= logging.get_logger(__name__)

SCREAMING_SNAKE_CASE_				= {
    """uw-madison/mra-base-512-4""": """https://huggingface.co/uw-madison/mra-base-512-4/resolve/main/config.json""",
}




class 			snake_case_						(						a_				):
							__lowerCAmelCase    					=					"mra"






							def __init__(   self			,     a_=5_0_2_6_5			,     a_=7_6_8			,     a_=1_2			,     a_=1_2			,     a_=3_0_7_2			,     a_="gelu"			,     a_=0.1			,     a_=0.1			,     a_=5_1_2			,     a_=1			,     a_=0.02			,     a_=1e-5			,     a_="absolute"			,     a_=4			,     a_="full"			,     a_=0			,     a_=0			,     a_=1			,     a_=0			,     a_=2			,     **a_			,     ):
									super().__init__(pad_token_id=a_			,     bos_token_id=a_			,     eos_token_id=a_			,     **a_      )

									a_     :      Optional[int] 						=     vocab_size
									a_     :      Dict 						=     max_position_embeddings
									a_     :      str 						=     hidden_size
									a_     :      Optional[int] 						=     num_hidden_layers
									a_     :      List[Any] 						=     num_attention_heads
									a_     :      List[str] 						=     intermediate_size
									a_     :      Tuple 						=     hidden_act
									a_     :      List[Any] 						=     hidden_dropout_prob
									a_     :      List[str] 						=     attention_probs_dropout_prob
									a_     :      List[Any] 						=     initializer_range
									a_     :      Dict 						=     type_vocab_size
									a_     :      Union[str, Any] 						=     layer_norm_eps
									a_     :      List[str] 						=     position_embedding_type
									a_     :      Union[str, Any] 						=     block_per_row
									a_     :      Tuple 						=     approx_mode
									a_     :      Optional[Any] 						=     initial_prior_first_n_blocks
									a_     :      List[str] 						=     initial_prior_diagonal_n_blocks