

import gc
import unittest

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

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()

class 							UpperCAmelCase_						(     __lowercase							,			unittest.TestCase  ):
							"""simple docstring"""







							UpperCAmelCase__			:		str             =       LDMTextToImagePipeline
							UpperCAmelCase__			:		Tuple             =       TEXT_TO_IMAGE_PARAMS - {
							    "negative_prompt",
							    "negative_prompt_embeds",
							    "cross_attention_kwargs",
							    "prompt_embeds",
							}
							UpperCAmelCase__			:		Any             =       PipelineTesterMixin.required_optional_params - {
							    "num_images_per_prompt",
							    "callback",
							    "callback_steps",
							}
							UpperCAmelCase__			:		Dict             =       TEXT_TO_IMAGE_BATCH_PARAMS
							UpperCAmelCase__			:		Tuple             =       False


							def 							__lowercase							(     self			)       ->       Dict:
												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''')			,				cross_attention_dim=3_2			,				)
												_a      :       int   =						DDIMScheduler(
												    beta_start=0.0_0085			,				beta_end=0.012			,				beta_schedule='''scaled_linear'''			,				clip_sample=_a			,				set_alpha_to_one=_a			,				)
												torch.manual_seed(0			)
												_a      :       List[Any]   =						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			,				)
												torch.manual_seed(0			)
												_a      :       Union[str, Any]   =						CLIPTextConfig(
												    bos_token_id=0			,				eos_token_id=2			,				hidden_size=3_2			,				intermediate_size=3_7			,				layer_norm_eps=1e-0_5			,				num_attention_heads=4			,				num_hidden_layers=5			,				pad_token_id=1			,				vocab_size=1_0_0_0			,				)
												_a      :       int   =						CLIPTextModel(_a			)
												_a      :       Dict   =						CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''			)

												_a      :       List[Any]   =						{
												    '''unet''': unet,
												    '''scheduler''': scheduler,
												    '''vqvae''': vae,
												    '''bert''': text_encoder,
												    '''tokenizer''': tokenizer,
												}
												return components


							def 							__lowercase							(     self			,				_a			,				_a=0			)       ->       Optional[int]:
												if str(_a			).startswith('''mps'''			):
																	_a      :       List[str]   =						torch.manual_seed(_a			)
												else:
																	_a      :       int   =						torch.Generator(device=_a			).manual_seed(_a			)
												_a      :       Optional[int]   =						{
												    '''prompt''': '''A painting of a squirrel eating a burger''',
												    '''generator''': generator,
												    '''num_inference_steps''': 2,
												    '''guidance_scale''': 6.0,
												    '''output_type''': '''numpy''',
												}
												return inputs




							def 							__lowercase							(     self			)       ->       Any:
												_a      :       Optional[Any]   =						'''cpu'''  # ensure determinism for the device-dependent torch.Generator

												_a      :       int   =						self.get_dummy_components()
												_a      :       Any   =						LDMTextToImagePipeline(**_a			)
												pipe.to(_a			)
												pipe.set_progress_bar_config(disable=_a			)

												_a      :       Optional[Any]   =						self.get_dummy_inputs(_a			)
												_a      :       List[str]   =						pipe(**_a			).images
												_a      :       Dict   =						image[0, -3:, -3:, -1]

												assert image.shape == (1, 1_6, 1_6, 3)
												_a      :       List[Any]   =						np.array([0.6101, 0.6156, 0.5622, 0.4895, 0.6661, 0.3804, 0.5748, 0.6136, 0.5014]			)

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



@slow
@require_torch_gpu
class 							UpperCAmelCase_						(     unittest.TestCase  ):
							"""simple docstring"""







							def 							__lowercase							(     self			)       ->       str:
												super().tearDown()
												gc.collect()
												torch.cuda.empty_cache()


							def 							__lowercase							(     self			,				_a			,				_a=torch.floataa			,				_a=0			)       ->       str:
												_a      :       Any   =						torch.manual_seed(_a			)
												_a      :       Dict   =						np.random.RandomState(_a			).standard_normal((1, 4, 3_2, 3_2)			)
												_a      :       List[Any]   =						torch.from_numpy(_a			).to(device=_a			,				dtype=_a			)
												_a      :       Union[str, Any]   =						{
												    '''prompt''': '''A painting of a squirrel eating a burger''',
												    '''latents''': latents,
												    '''generator''': generator,
												    '''num_inference_steps''': 3,
												    '''guidance_scale''': 6.0,
												    '''output_type''': '''numpy''',
												}
												return inputs




							def 							__lowercase							(     self			)       ->       str:
												_a      :       Any   =						LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256'''			).to(_a			)
												pipe.set_progress_bar_config(disable=_a			)

												_a      :       Optional[int]   =						self.get_inputs(_a			)
												_a      :       Optional[Any]   =						pipe(**_a			).images
												_a      :       Union[str, Any]   =						image[0, -3:, -3:, -1].flatten()

												assert image.shape == (1, 2_5_6, 2_5_6, 3)
												_a      :       List[str]   =						np.array([0.5_1825, 0.5_2850, 0.5_2543, 0.5_4258, 0.5_2304, 0.5_2569, 0.5_4363, 0.5_5276, 0.5_6878]			)
												_a      :       List[Any]   =						np.abs(expected_slice - image_slice			).max()
												assert max_diff < 1e-3



@nightly
@require_torch_gpu
class 							UpperCAmelCase_						(     unittest.TestCase  ):
							"""simple docstring"""







							def 							__lowercase							(     self			)       ->       Dict:
												super().tearDown()
												gc.collect()
												torch.cuda.empty_cache()


							def 							__lowercase							(     self			,				_a			,				_a=torch.floataa			,				_a=0			)       ->       int:
												_a      :       Union[str, Any]   =						torch.manual_seed(_a			)
												_a      :       str   =						np.random.RandomState(_a			).standard_normal((1, 4, 3_2, 3_2)			)
												_a      :       List[Any]   =						torch.from_numpy(_a			).to(device=_a			,				dtype=_a			)
												_a      :       Tuple   =						{
												    '''prompt''': '''A painting of a squirrel eating a burger''',
												    '''latents''': latents,
												    '''generator''': generator,
												    '''num_inference_steps''': 5_0,
												    '''guidance_scale''': 6.0,
												    '''output_type''': '''numpy''',
												}
												return inputs




							def 							__lowercase							(     self			)       ->       List[str]:
												_a      :       str   =						LDMTextToImagePipeline.from_pretrained('''CompVis/ldm-text2im-large-256'''			).to(_a			)
												pipe.set_progress_bar_config(disable=_a			)

												_a      :       List[str]   =						self.get_inputs(_a			)
												_a      :       int   =						pipe(**_a			).images[0]

												_a      :       Union[str, Any]   =						load_numpy(
												    '''https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy'''			)
												_a      :       Dict   =						np.abs(expected_image - image			).max()
												assert max_diff < 1e-3











'''simple docstring'''





import warnings

from ...configuration_utils import PretrainedConfig
from ...utils import logging


_UpperCamelCase						:						Optional[Any]  =					logging.get_logger(__name__)

_UpperCamelCase						:						Dict  =					{
    'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json',
}


class  snake_case__      (					UpperCamelCase):
					a_        =					"mvp"
					a_        =					["past_key_values"]
					a_        =					{"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}




					def __init__(  self  :		Any				, _A  :		List[str]=5_02_67				, _A  :		Dict=10_24				, _A  :		List[str]=12				, _A  :		Dict=40_96				, _A  :		Optional[int]=16				, _A  :		Optional[Any]=12				, _A  :		int=40_96				, _A  :		Dict=16				, _A  :		Union[str, Any]=0.0				, _A  :		Optional[Any]=0.0				, _A  :		int="gelu"				, _A  :		Union[str, Any]=10_24				, _A  :		int=0.1				, _A  :		Optional[Any]=0.0				, _A  :		Optional[Any]=0.0				, _A  :		Optional[Any]=0.02				, _A  :		Optional[Any]=0.0				, _A  :		str=False				, _A  :		List[Any]=True				, _A  :		Optional[int]=1				, _A  :		Tuple=0				, _A  :		Dict=2				, _A  :		Dict=True				, _A  :		int=2				, _A  :		Tuple=2				, _A  :		List[str]=False				, _A  :		Any=1_00				, _A  :		Union[str, Any]=8_00				, **_A  :		List[str]				, )    ->							int:
								UpperCAmelCase_      :       Union[str, Any]          =       vocab_size
								UpperCAmelCase_      :       int          =       max_position_embeddings
								UpperCAmelCase_      :       Dict          =       d_model
								UpperCAmelCase_      :       Dict          =       encoder_ffn_dim
								UpperCAmelCase_      :       Optional[Any]          =       encoder_layers
								UpperCAmelCase_      :       Tuple          =       encoder_attention_heads
								UpperCAmelCase_      :       List[Any]          =       decoder_ffn_dim
								UpperCAmelCase_      :       List[Any]          =       decoder_layers
								UpperCAmelCase_      :       Dict          =       decoder_attention_heads
								UpperCAmelCase_      :       str          =       dropout
								UpperCAmelCase_      :       Optional[Any]          =       attention_dropout
								UpperCAmelCase_      :       Optional[Any]          =       activation_dropout
								UpperCAmelCase_      :       Union[str, Any]          =       activation_function
								UpperCAmelCase_      :       Union[str, Any]          =       init_std
								UpperCAmelCase_      :       Optional[int]          =       encoder_layerdrop
								UpperCAmelCase_      :       Optional[int]          =       decoder_layerdrop
								UpperCAmelCase_      :       Dict          =       classifier_dropout
								UpperCAmelCase_      :       List[Any]          =       use_cache
								UpperCAmelCase_      :       Dict          =       encoder_layers
								UpperCAmelCase_      :       Tuple          =       scale_embedding  # scale factor will be sqrt(d_model) if True
								UpperCAmelCase_      :       int          =       use_prompt
								UpperCAmelCase_      :       Tuple          =       prompt_length
								UpperCAmelCase_      :       str          =       prompt_mid_dim

								super().__init__(
								    pad_token_id=_A				, bos_token_id=_A				, eos_token_id=_A				, is_encoder_decoder=_A				, decoder_start_token_id=_A				, forced_eos_token_id=_A				, **_A				, )

								if self.forced_bos_token_id is None and kwargs.get('''force_bos_token_to_be_generated'''				, _A      ):
											UpperCAmelCase_      :       Optional[Any]          =       self.bos_token_id
											warnings.warn(
											    F"Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. "
											    '''The config can simply be saved and uploaded again to be fixed.'''      )


