




"""simple docstring"""

import gc
import unittest

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

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    StableDiffusionAttendAndExcitePipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_numpy, skip_mps, slow
from diffusers.utils.testing_utils import require_torch_gpu

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin


_lowerCamelCase  :			Tuple        =       False

@skip_mps
class        lowercase      (    __UpperCAmelCase     ,	__UpperCAmelCase     ,	__UpperCAmelCase     ,	unittest.TestCase):
				__lowerCAmelCase    :    List[Any]         =   StableDiffusionAttendAndExcitePipeline
				__lowerCAmelCase    :    Optional[int]         =   False
				__lowerCAmelCase    :    Dict         =   TEXT_TO_IMAGE_PARAMS
				__lowerCAmelCase    :    Any         =   TEXT_TO_IMAGE_BATCH_PARAMS.union({"""token_indices"""})
				__lowerCAmelCase    :    Dict         =   TEXT_TO_IMAGE_IMAGE_PARAMS
				__lowerCAmelCase    :    Union[str, Any]         =   TEXT_TO_IMAGE_IMAGE_PARAMS







				@classmethod
				def 					a_  (							cls   :					Dict       ):



					"""simple docstring"""

					super().setUpClass()
					torch.use_deterministic_algorithms(_lowerCamelCase       )







				@classmethod
				def 					a_  (							cls   :					Dict       ):



					"""simple docstring"""

					super().tearDownClass()
					torch.use_deterministic_algorithms(_lowerCamelCase       )







				def 					a_  (							self   :					List[Any]       ):



					"""simple docstring"""

					torch.manual_seed(0       )
					A_  :				List[str]	   =		UNetaDConditionModel(
					    block_out_channels=(32, 64)      ,     layers_per_block=1      ,     sample_size=32      ,     in_channels=4      ,     out_channels=4      ,     down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''')      ,     up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''')      ,     cross_attention_dim=32      ,     attention_head_dim=(2, 4)      ,     use_linear_projection=_lowerCamelCase      ,     )
					A_  :				List[str]	   =		DDIMScheduler(
					    beta_start=0.00085      ,     beta_end=0.012      ,     beta_schedule='''scaled_linear'''      ,     clip_sample=_lowerCamelCase      ,     set_alpha_to_one=_lowerCamelCase      ,     )
					torch.manual_seed(0       )
					A_  :				List[str]	   =		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      ,     sample_size=1_28      ,     )
					torch.manual_seed(0       )
					A_  :				Tuple	   =		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      ,     hidden_act='''gelu'''      ,     projection_dim=5_12      ,     )
					A_  :				Any	   =		CLIPTextModel(_lowerCamelCase       )
					A_  :				Any	   =		CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''       )

					A_  :				str	   =		{
					    '''unet''': unet,
					    '''scheduler''': scheduler,
					    '''vae''': vae,
					    '''text_encoder''': text_encoder,
					    '''tokenizer''': tokenizer,
					    '''safety_checker''': None,
					    '''feature_extractor''': None,
					}

					return components







				def 					a_  (							self   :					Any      ,     _lowerCamelCase   :					Union[str, Any]      ,     _lowerCamelCase   :					Dict=0       ):



					"""simple docstring"""

					if str(_lowerCamelCase       ).startswith('''mps'''       ):
						A_  :				List[Any]	   =		torch.manual_seed(_lowerCamelCase       )
					else:
						A_  :				str	   =		torch.Generator(device=_lowerCamelCase       ).manual_seed(_lowerCamelCase       )
					A_  :				Dict	   =		{
					    '''prompt''': '''a cat and a frog''',
					    '''token_indices''': [2, 5],
					    '''generator''': generator,
					    '''num_inference_steps''': 1,
					    '''guidance_scale''': 6.0,
					    '''output_type''': '''numpy''',
					    '''max_iter_to_alter''': 2,
					    '''thresholds''': {0: 0.7},
					}
					return inputs







				def 					a_  (							self   :					int       ):



					"""simple docstring"""

					A_  :				Any	   =		'''cpu'''

					A_  :				Dict	   =		self.get_dummy_components()
					A_  :				Optional[int]	   =		self.pipeline_class(**_lowerCamelCase       )
					pipe.to(_lowerCamelCase       )
					pipe.set_progress_bar_config(disable=_lowerCamelCase       )

					A_  :				Tuple	   =		self.get_dummy_inputs(_lowerCamelCase       )
					A_  :				Dict	   =		pipe(**_lowerCamelCase       ).images
					A_  :				List[str]	   =		image[0, -3:, -3:, -1]

					self.assertEqual(image.shape      ,     (1, 64, 64, 3)       )
					A_  :				List[str]	   =		np.array(
					    [0.63905364, 0.62897307, 0.48599017, 0.5133624, 0.5550048, 0.45769516, 0.50326973, 0.5023139, 0.45384496]       )
					A_  :				Optional[Any]	   =		np.abs(image_slice.flatten() - expected_slice       ).max()
					self.assertLessEqual(_lowerCamelCase      ,     1E-3       )







				def 					a_  (							self   :					Optional[Any]       ):



					"""simple docstring"""

					super().test_cpu_offload_forward_pass(expected_max_diff=5E-4       )







				def 					a_  (							self   :					Optional[int]       ):



					"""simple docstring"""

					self._test_inference_batch_consistent(batch_sizes=[1, 2]       )







				def 					a_  (							self   :					List[str]       ):



					"""simple docstring"""

					self._test_inference_batch_single_identical(batch_size=2      ,     expected_max_diff=7E-4       )







				def 					a_  (							self   :					List[str]       ):



					"""simple docstring"""

					super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3       )







				def 					a_  (							self   :					List[Any]       ):



					"""simple docstring"""

					super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5E-4       )







				def 					a_  (							self   :					Dict       ):



					"""simple docstring"""

					super().test_save_load_local(expected_max_difference=5E-4       )







				def 					a_  (							self   :					Optional[Any]       ):



					"""simple docstring"""

					super().test_save_load_optional_components(expected_max_difference=4E-4       )

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







				@classmethod
				def 					a_  (							cls   :					List[str]       ):



					"""simple docstring"""

					super().setUpClass()
					torch.use_deterministic_algorithms(_lowerCamelCase       )







				@classmethod
				def 					a_  (							cls   :					List[str]       ):



					"""simple docstring"""

					super().tearDownClass()
					torch.use_deterministic_algorithms(_lowerCamelCase       )







				def 					a_  (							self   :					int       ):



					"""simple docstring"""

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







				def 					a_  (							self   :					Optional[Any]       ):



					"""simple docstring"""

					A_  :				Tuple	   =		torch.manual_seed(51       )

					A_  :				Dict	   =		StableDiffusionAttendAndExcitePipeline.from_pretrained(
					    '''CompVis/stable-diffusion-v1-4'''      ,     safety_checker=_lowerCamelCase      ,     torch_dtype=torch.floataa       )
					pipe.to('''cuda'''       )

					A_  :				Any	   =		'''a painting of an elephant with glasses'''
					A_  :				List[Any]	   =		[5, 7]

					A_  :				Union[str, Any]	   =		pipe(
					    prompt=_lowerCamelCase      ,     token_indices=_lowerCamelCase      ,     guidance_scale=7.5      ,     generator=_lowerCamelCase      ,     num_inference_steps=5      ,     max_iter_to_alter=5      ,     output_type='''numpy'''      ,     ).images[0]

					A_  :				Any	   =		load_numpy(
					    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy'''       )
					assert np.abs((expected_image - image).max()       ) < 5E-1











"""simple docstring"""

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


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

_lowerCamelCase  :			Any        =       {
    'studio-ousia/luke-base': 'https://huggingface.co/studio-ousia/luke-base/resolve/main/config.json',
    'studio-ousia/luke-large': 'https://huggingface.co/studio-ousia/luke-large/resolve/main/config.json',
}

class        lowercase      (    __UpperCAmelCase):
				__lowerCAmelCase    :    Any         =   """luke"""







				def __init__(							self   :					List[str]      ,     _lowerCamelCase   :					Union[str, Any]=5_02_67      ,     _lowerCamelCase   :					Tuple=50_00_00      ,     _lowerCamelCase   :					int=7_68      ,     _lowerCamelCase   :					Union[str, Any]=2_56      ,     _lowerCamelCase   :					Dict=12      ,     _lowerCamelCase   :					str=12      ,     _lowerCamelCase   :					Dict=30_72      ,     _lowerCamelCase   :					Union[str, Any]="gelu"      ,     _lowerCamelCase   :					Optional[int]=0.1      ,     _lowerCamelCase   :					str=0.1      ,     _lowerCamelCase   :					Union[str, Any]=5_12      ,     _lowerCamelCase   :					int=2      ,     _lowerCamelCase   :					Optional[int]=0.02      ,     _lowerCamelCase   :					int=1E-12      ,     _lowerCamelCase   :					List[str]=True      ,     _lowerCamelCase   :					str=None      ,     _lowerCamelCase   :					Union[str, Any]=1      ,     _lowerCamelCase   :					str=0      ,     _lowerCamelCase   :					Dict=2      ,     **_lowerCamelCase   :					Optional[int]      ,     ):



					"""simple docstring"""

					super().__init__(pad_token_id=_lowerCamelCase      ,     bos_token_id=_lowerCamelCase      ,     eos_token_id=_lowerCamelCase      ,     **_lowerCamelCase       )

					A_  :				str	   =		vocab_size
					A_  :				Optional[Any]	   =		entity_vocab_size
					A_  :				Optional[Any]	   =		hidden_size
					A_  :				List[str]	   =		entity_emb_size
					A_  :				Union[str, Any]	   =		num_hidden_layers
					A_  :				Dict	   =		num_attention_heads
					A_  :				Union[str, Any]	   =		hidden_act
					A_  :				Dict	   =		intermediate_size
					A_  :				int	   =		hidden_dropout_prob
					A_  :				str	   =		attention_probs_dropout_prob
					A_  :				List[Any]	   =		max_position_embeddings
					A_  :				Optional[Any]	   =		type_vocab_size
					A_  :				Optional[int]	   =		initializer_range
					A_  :				str	   =		layer_norm_eps
					A_  :				List[str]	   =		use_entity_aware_attention
					A_  :				Optional[int]	   =		classifier_dropout





