



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       __lowerCAmelCase   (      SCREAMING_SNAKE_CASE__    ,						unittest.TestCase						):
			UpperCamelCase        =					LDMTextToImagePipeline
			UpperCamelCase        =					TEXT_TO_IMAGE_PARAMS - {
			    'negative_prompt',
			    'negative_prompt_embeds',
			    'cross_attention_kwargs',
			    'prompt_embeds',
			}
			UpperCamelCase        =					PipelineTesterMixin.required_optional_params - {
			    'num_images_per_prompt',
			    'callback',
			    'callback_steps',
			}
			UpperCamelCase        =					TEXT_TO_IMAGE_BATCH_PARAMS
			UpperCamelCase        =					False



			def    _lowerCamelCase	(						self       :  Optional[int])       ->   Tuple:



						"""simple docstring"""






						torch.manual_seed(0)
						_UpperCAmelCase			=       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			,		)
						_UpperCAmelCase			=       DDIMScheduler(
						    beta_start=0.0_0_0_8_5			,		beta_end=0.0_1_2			,		beta_schedule='scaled_linear'			,		clip_sample=_SCREAMING_SNAKE_CASE			,		set_alpha_to_one=_SCREAMING_SNAKE_CASE			,		)
						torch.manual_seed(0)
						_UpperCAmelCase			=       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			,		)
						torch.manual_seed(0)
						_UpperCAmelCase			=       CLIPTextConfig(
						    bos_token_id=0			,		eos_token_id=2			,		hidden_size=32			,		intermediate_size=37			,		layer_norm_eps=1E-05			,		num_attention_heads=4			,		num_hidden_layers=5			,		pad_token_id=1			,		vocab_size=10_00			,		)
						_UpperCAmelCase			=       CLIPTextModel(_SCREAMING_SNAKE_CASE)
						_UpperCAmelCase			=       CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip')

						_UpperCAmelCase			=       {
						    "unet": unet,
						    "scheduler": scheduler,
						    "vqvae": vae,
						    "bert": text_encoder,
						    "tokenizer": tokenizer,
						}
						return components



			def    _lowerCamelCase	(						self       :  Optional[Any]			,		A       :  List[str]			,		A       :  Tuple=0)       ->   Tuple:



						"""simple docstring"""






						if str(_SCREAMING_SNAKE_CASE).startswith('mps'):
									_UpperCAmelCase			=       torch.manual_seed(_SCREAMING_SNAKE_CASE)
						else:
									_UpperCAmelCase			=       torch.Generator(device=_SCREAMING_SNAKE_CASE).manual_seed(_SCREAMING_SNAKE_CASE)
						_UpperCAmelCase			=       {
						    "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    _lowerCamelCase	(						self       :  Dict)       ->   Tuple:



						"""simple docstring"""






						_UpperCAmelCase			=       "cpu"  # ensure determinism for the device-dependent torch.Generator

						_UpperCAmelCase			=       self.get_dummy_components()
						_UpperCAmelCase			=       LDMTextToImagePipeline(**_SCREAMING_SNAKE_CASE)
						pipe.to(_SCREAMING_SNAKE_CASE)
						pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

						_UpperCAmelCase			=       self.get_dummy_inputs(_SCREAMING_SNAKE_CASE)
						_UpperCAmelCase			=       pipe(**_SCREAMING_SNAKE_CASE).images
						_UpperCAmelCase			=       image[0, -3:, -3:, -1]

						assert image.shape == (1, 16, 16, 3)
						_UpperCAmelCase			=       np.array([0.6_1_0_1, 0.6_1_5_6, 0.5_6_2_2, 0.4_8_9_5, 0.6_6_6_1, 0.3_8_0_4, 0.5_7_4_8, 0.6_1_3_6, 0.5_0_1_4])

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







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



			def    _lowerCamelCase	(						self       :  Optional[int])       ->   Optional[int]:



						"""simple docstring"""






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



			def    _lowerCamelCase	(						self       :  List[str]			,		A       :  int			,		A       :  Optional[int]=torch.floataa			,		A       :  str=0)       ->   List[Any]:



						"""simple docstring"""






						_UpperCAmelCase			=       torch.manual_seed(_SCREAMING_SNAKE_CASE)
						_UpperCAmelCase			=       np.random.RandomState(_SCREAMING_SNAKE_CASE).standard_normal((1, 4, 32, 32))
						_UpperCAmelCase			=       torch.from_numpy(_SCREAMING_SNAKE_CASE).to(device=_SCREAMING_SNAKE_CASE			,		dtype=_SCREAMING_SNAKE_CASE)
						_UpperCAmelCase			=       {
						    "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    _lowerCamelCase	(						self       :  Optional[int])       ->   Optional[Any]:



						"""simple docstring"""






						_UpperCAmelCase			=       LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256').to(_SCREAMING_SNAKE_CASE)
						pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

						_UpperCAmelCase			=       self.get_inputs(_SCREAMING_SNAKE_CASE)
						_UpperCAmelCase			=       pipe(**_SCREAMING_SNAKE_CASE).images
						_UpperCAmelCase			=       image[0, -3:, -3:, -1].flatten()

						assert image.shape == (1, 2_56, 2_56, 3)
						_UpperCAmelCase			=       np.array([0.5_1_8_2_5, 0.5_2_8_5_0, 0.5_2_5_4_3, 0.5_4_2_5_8, 0.5_2_3_0_4, 0.5_2_5_6_9, 0.5_4_3_6_3, 0.5_5_2_7_6, 0.5_6_8_7_8])
						_UpperCAmelCase			=       np.abs(expected_slice - image_slice).max()
						assert max_diff < 1E-3







@nightly
@require_torch_gpu
class       __lowerCAmelCase   (      unittest.TestCase						):



			def    _lowerCamelCase	(						self       :  str)       ->   Tuple:



						"""simple docstring"""






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



			def    _lowerCamelCase	(						self       :  Union[str, Any]			,		A       :  List[Any]			,		A       :  Optional[int]=torch.floataa			,		A       :  str=0)       ->   List[str]:



						"""simple docstring"""






						_UpperCAmelCase			=       torch.manual_seed(_SCREAMING_SNAKE_CASE)
						_UpperCAmelCase			=       np.random.RandomState(_SCREAMING_SNAKE_CASE).standard_normal((1, 4, 32, 32))
						_UpperCAmelCase			=       torch.from_numpy(_SCREAMING_SNAKE_CASE).to(device=_SCREAMING_SNAKE_CASE			,		dtype=_SCREAMING_SNAKE_CASE)
						_UpperCAmelCase			=       {
						    "prompt": "A painting of a squirrel eating a burger",
						    "latents": latents,
						    "generator": generator,
						    "num_inference_steps": 50,
						    "guidance_scale": 6.0,
						    "output_type": "numpy",
						}
						return inputs



			def    _lowerCamelCase	(						self       :  Union[str, Any])       ->   Dict:



						"""simple docstring"""






						_UpperCAmelCase			=       LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256').to(_SCREAMING_SNAKE_CASE)
						pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

						_UpperCAmelCase			=       self.get_inputs(_SCREAMING_SNAKE_CASE)
						_UpperCAmelCase			=       pipe(**_SCREAMING_SNAKE_CASE).images[0]

						_UpperCAmelCase			=       load_numpy(
						    'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy')
						_UpperCAmelCase			=       np.abs(expected_image - image).max()
						assert max_diff < 1E-3




from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
)


UpperCAmelCase__       =	{
    "configuration_lxmert": ["LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP", "LxmertConfig"],
    "tokenization_lxmert": ["LxmertTokenizer"],
}

try:
							if not is_tokenizers_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							UpperCAmelCase__       =	["LxmertTokenizerFast"]

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							UpperCAmelCase__       =	[
							    "LxmertEncoder",
							    "LxmertForPreTraining",
							    "LxmertForQuestionAnswering",
							    "LxmertModel",
							    "LxmertPreTrainedModel",
							    "LxmertVisualFeatureEncoder",
							    "LxmertXLayer",
							]

try:
							if not is_tf_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							UpperCAmelCase__       =	[
							    "TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST",
							    "TFLxmertForPreTraining",
							    "TFLxmertMainLayer",
							    "TFLxmertModel",
							    "TFLxmertPreTrainedModel",
							    "TFLxmertVisualFeatureEncoder",
							]


if TYPE_CHECKING:
							from .configuration_lxmert import LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP, LxmertConfig
							from .tokenization_lxmert import LxmertTokenizer

							try:
														if not is_tokenizers_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .tokenization_lxmert_fast import LxmertTokenizerFast

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_lxmert import (
														    LxmertEncoder,
														    LxmertForPreTraining,
														    LxmertForQuestionAnswering,
														    LxmertModel,
														    LxmertPreTrainedModel,
														    LxmertVisualFeatureEncoder,
														    LxmertXLayer,
														)

							try:
														if not is_tf_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_tf_lxmert import (
														    TF_LXMERT_PRETRAINED_MODEL_ARCHIVE_LIST,
														    TFLxmertForPreTraining,
														    TFLxmertMainLayer,
														    TFLxmertModel,
														    TFLxmertPreTrainedModel,
														    TFLxmertVisualFeatureEncoder,
														)

else:
							import sys

							UpperCAmelCase__       =	_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
