


import unittest

from transformers import MraConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_torch_available():
						import torch

						from transformers import (
						    MraForMaskedLM,
						    MraForMultipleChoice,
						    MraForQuestionAnswering,
						    MraForSequenceClassification,
						    MraForTokenClassification,
						    MraModel,
						)
						from transformers.models.mra.modeling_mra import MRA_PRETRAINED_MODEL_ARCHIVE_LIST







class        snake_case_   :
					def __init__(      self   :Optional[int]			,__snake_case   :List[str]			,__snake_case   :Optional[Any]=2			,__snake_case   :Any=8			,__snake_case   :str=True			,__snake_case   :str=True			,__snake_case   :Tuple=True			,__snake_case   :Optional[int]=True			,__snake_case   :Tuple=99			,__snake_case   :Any=16			,__snake_case   :Dict=5			,__snake_case   :Optional[Any]=2			,__snake_case   :Dict=36			,__snake_case   :Union[str, Any]="gelu"			,__snake_case   :Tuple=0.0			,__snake_case   :int=0.0			,__snake_case   :Optional[Any]=5_12			,__snake_case   :Optional[Any]=16			,__snake_case   :str=2			,__snake_case   :List[Any]=0.02			,__snake_case   :Tuple=3			,__snake_case   :Optional[Any]=4			,__snake_case   :List[str]=None			,)					->    Dict:
												a__             =     parent
												a__             =     batch_size
												a__             =     seq_length
												a__             =     is_training
												a__             =     use_input_mask
												a__             =     use_token_type_ids
												a__             =     use_labels
												a__             =     vocab_size
												a__             =     hidden_size
												a__             =     num_hidden_layers
												a__             =     num_attention_heads
												a__             =     intermediate_size
												a__             =     hidden_act
												a__             =     hidden_dropout_prob
												a__             =     attention_probs_dropout_prob
												a__             =     max_position_embeddings
												a__             =     type_vocab_size
												a__             =     type_sequence_label_size
												a__             =     initializer_range
												a__             =     num_labels
												a__             =     num_choices
												a__             =     scope
					def  lowerCamelCase__(      self   :List[str]      )					->    Union[str, Any]:
												a__             =     ids_tensor([self.batch_size, self.seq_length]			,self.vocab_size      )

												a__             =     None
												if self.use_input_mask:
																			a__             =     random_attention_mask([self.batch_size, self.seq_length]      )

												a__             =     None
												if self.use_token_type_ids:
																			a__             =     ids_tensor([self.batch_size, self.seq_length]			,self.type_vocab_size      )

												a__             =     None
												a__             =     None
												a__             =     None
												if self.use_labels:
																			a__             =     ids_tensor([self.batch_size]			,self.type_sequence_label_size      )
																			a__             =     ids_tensor([self.batch_size, self.seq_length]			,self.num_labels      )
																			a__             =     ids_tensor([self.batch_size]			,self.num_choices      )

												a__             =     self.get_config()

												return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
					def  lowerCamelCase__(      self   :List[Any]      )					->    Dict:
												return MraConfig(
												    vocab_size=self.vocab_size			,hidden_size=self.hidden_size			,num_hidden_layers=self.num_hidden_layers			,num_attention_heads=self.num_attention_heads			,intermediate_size=self.intermediate_size			,hidden_act=self.hidden_act			,hidden_dropout_prob=self.hidden_dropout_prob			,attention_probs_dropout_prob=self.attention_probs_dropout_prob			,max_position_embeddings=self.max_position_embeddings			,type_vocab_size=self.type_vocab_size			,is_decoder=__snake_case			,initializer_range=self.initializer_range			,)
					def  lowerCamelCase__(      self   :Any      )					->    List[str]:
												a__             =     self.get_config()
												a__             =     3_00
												return config
					def  lowerCamelCase__(      self   :Optional[int]      )					->    List[str]:
												(
												    (
												    a__
												)      ,					(
												    a__
												)      ,					(
												    a__
												)      ,					(
												    a__
												)      ,					(
												    a__
												)      ,					(
												    a__
												)      ,					(
												    a__
												)      ,					
												)             =     self.prepare_config_and_inputs()

												a__             =     True
												a__             =     floats_tensor([self.batch_size, self.seq_length, self.hidden_size]      )
												a__             =     ids_tensor([self.batch_size, self.seq_length]			,vocab_size=2      )

												return (
												    config,
												    input_ids,
												    token_type_ids,
												    input_mask,
												    sequence_labels,
												    token_labels,
												    choice_labels,
												    encoder_hidden_states,
												    encoder_attention_mask,
												)
					def  lowerCamelCase__(      self   :str			,__snake_case   :str			,__snake_case   :List[Any]			,__snake_case   :List[Any]			,__snake_case   :List[Any]			,__snake_case   :str			,__snake_case   :Dict			,__snake_case   :List[str]      )					->    str:
												a__             =     MraModel(config=__snake_case      )
												model.to(__snake_case      )
												model.eval()
												a__             =     model(__snake_case			,attention_mask=__snake_case			,token_type_ids=__snake_case      )
												a__             =     model(__snake_case			,token_type_ids=__snake_case      )
												a__             =     model(__snake_case      )
												self.parent.assertEqual(result.last_hidden_state.shape			,(self.batch_size, self.seq_length, self.hidden_size)      )
					def  lowerCamelCase__(      self   :str			,__snake_case   :Optional[Any]			,__snake_case   :Union[str, Any]			,__snake_case   :List[Any]			,__snake_case   :Tuple			,__snake_case   :Tuple			,__snake_case   :List[str]			,__snake_case   :str			,__snake_case   :int			,__snake_case   :Optional[int]			,)					->    Any:
												a__             =     True
												a__             =     MraModel(__snake_case      )
												model.to(__snake_case      )
												model.eval()
												a__             =     model(
												    __snake_case			,attention_mask=__snake_case			,token_type_ids=__snake_case			,encoder_hidden_states=__snake_case			,encoder_attention_mask=__snake_case			,)
												a__             =     model(
												    __snake_case			,attention_mask=__snake_case			,token_type_ids=__snake_case			,encoder_hidden_states=__snake_case			,)
												a__             =     model(__snake_case			,attention_mask=__snake_case			,token_type_ids=__snake_case      )
												self.parent.assertEqual(result.last_hidden_state.shape			,(self.batch_size, self.seq_length, self.hidden_size)      )
					def  lowerCamelCase__(      self   :Dict			,__snake_case   :Tuple			,__snake_case   :Optional[Any]			,__snake_case   :Any			,__snake_case   :Dict			,__snake_case   :Any			,__snake_case   :List[str]			,__snake_case   :str      )					->    str:
												a__             =     MraForMaskedLM(config=__snake_case      )
												model.to(__snake_case      )
												model.eval()
												a__             =     model(__snake_case			,attention_mask=__snake_case			,token_type_ids=__snake_case			,labels=__snake_case      )
												self.parent.assertEqual(result.logits.shape			,(self.batch_size, self.seq_length, self.vocab_size)      )
					def  lowerCamelCase__(      self   :int			,__snake_case   :Optional[Any]			,__snake_case   :int			,__snake_case   :Optional[Any]			,__snake_case   :List[str]			,__snake_case   :Dict			,__snake_case   :Any			,__snake_case   :Dict      )					->    List[str]:
												a__             =     MraForQuestionAnswering(config=__snake_case      )
												model.to(__snake_case      )
												model.eval()
												a__             =     model(
												    __snake_case			,attention_mask=__snake_case			,token_type_ids=__snake_case			,start_positions=__snake_case			,end_positions=__snake_case			,)
												self.parent.assertEqual(result.start_logits.shape			,(self.batch_size, self.seq_length)      )
												self.parent.assertEqual(result.end_logits.shape			,(self.batch_size, self.seq_length)      )
					def  lowerCamelCase__(      self   :Any			,__snake_case   :List[Any]			,__snake_case   :Any			,__snake_case   :Tuple			,__snake_case   :List[Any]			,__snake_case   :str			,__snake_case   :Tuple			,__snake_case   :Any      )					->    Dict:
												a__             =     self.num_labels
												a__             =     MraForSequenceClassification(__snake_case      )
												model.to(__snake_case      )
												model.eval()
												a__             =     model(__snake_case			,attention_mask=__snake_case			,token_type_ids=__snake_case			,labels=__snake_case      )
												self.parent.assertEqual(result.logits.shape			,(self.batch_size, self.num_labels)      )
					def  lowerCamelCase__(      self   :Dict			,__snake_case   :str			,__snake_case   :Union[str, Any]			,__snake_case   :Optional[Any]			,__snake_case   :str			,__snake_case   :List[str]			,__snake_case   :Tuple			,__snake_case   :Union[str, Any]      )					->    List[Any]:
												a__             =     self.num_labels
												a__             =     MraForTokenClassification(config=__snake_case      )
												model.to(__snake_case      )
												model.eval()
												a__             =     model(__snake_case			,attention_mask=__snake_case			,token_type_ids=__snake_case			,labels=__snake_case      )
												self.parent.assertEqual(result.logits.shape			,(self.batch_size, self.seq_length, self.num_labels)      )
					def  lowerCamelCase__(      self   :str			,__snake_case   :List[Any]			,__snake_case   :Optional[Any]			,__snake_case   :List[Any]			,__snake_case   :Tuple			,__snake_case   :Optional[int]			,__snake_case   :Union[str, Any]			,__snake_case   :Tuple      )					->    Tuple:
												a__             =     self.num_choices
												a__             =     MraForMultipleChoice(config=__snake_case      )
												model.to(__snake_case      )
												model.eval()
												a__             =     input_ids.unsqueeze(1      ).expand(-1			,self.num_choices			,-1      ).contiguous()
												a__             =     token_type_ids.unsqueeze(1      ).expand(-1			,self.num_choices			,-1      ).contiguous()
												a__             =     input_mask.unsqueeze(1      ).expand(-1			,self.num_choices			,-1      ).contiguous()
												a__             =     model(
												    __snake_case			,attention_mask=__snake_case			,token_type_ids=__snake_case			,labels=__snake_case			,)
												self.parent.assertEqual(result.logits.shape			,(self.batch_size, self.num_choices)      )



					def  lowerCamelCase__(      self   :Tuple      )					->    Dict:
												a__             =     self.prepare_config_and_inputs()
												(
												    (
												    a__
												)      ,					(
												    a__
												)      ,					(
												    a__
												)      ,					(
												    a__
												)      ,					(
												    a__
												)      ,					(
												    a__
												)      ,					(
												    a__
												)      ,					
												)             =     config_and_inputs
												a__             =     {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
												return config, inputs_dict







@require_torch
class        snake_case_   (lowerCamelCase_	,						unittest.TestCase      ):
					UpperCAmelCase__					:    List[str]          =			(
					    (
					        MraModel,
					        MraForMaskedLM,
					        MraForMultipleChoice,
					        MraForQuestionAnswering,
					        MraForSequenceClassification,
					        MraForTokenClassification,
					    )
					    if is_torch_available()
					    else ()
					)
					UpperCAmelCase__					:    Any          =			False
					UpperCAmelCase__					:    Any          =			False
					UpperCAmelCase__					:    Tuple          =			False
					UpperCAmelCase__					:    Dict          =			False

					UpperCAmelCase__					:    List[Any]          =			()
					def  lowerCamelCase__(      self   :Optional[int]      )					->    List[str]:
												a__             =     MraModelTester(self      )
												a__             =     ConfigTester(self			,config_class=__snake_case			,hidden_size=37      )
					def  lowerCamelCase__(      self   :Optional[int]      )					->    Tuple:
												self.config_tester.run_common_tests()
					def  lowerCamelCase__(      self   :Union[str, Any]      )					->    Union[str, Any]:
												a__             =     self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*__snake_case      )
					def  lowerCamelCase__(      self   :Any      )					->    Dict:
												a__             =     self.model_tester.prepare_config_and_inputs()
												for type in ["absolute", "relative_key", "relative_key_query"]:
																			a__             =     type
																			self.model_tester.create_and_check_model(*__snake_case      )
					def  lowerCamelCase__(      self   :Dict      )					->    Any:
												a__             =     self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_masked_lm(*__snake_case      )
					def  lowerCamelCase__(      self   :List[Any]      )					->    int:
												a__             =     self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_multiple_choice(*__snake_case      )
					def  lowerCamelCase__(      self   :Dict      )					->    str:
												a__             =     self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_question_answering(*__snake_case      )
					def  lowerCamelCase__(      self   :Any      )					->    str:
												a__             =     self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_sequence_classification(*__snake_case      )
					def  lowerCamelCase__(      self   :List[str]      )					->    Any:
												a__             =     self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_token_classification(*__snake_case      )
					@slow
					def  lowerCamelCase__(      self   :Optional[int]      )					->    str:
												for model_name in MRA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			a__             =     MraModel.from_pretrained(__snake_case      )
																			self.assertIsNotNone(__snake_case      )



					@unittest.skip(reason='MRA does not output attentions'      )
					def  lowerCamelCase__(      self   :Any      )					->    List[Any]:
												return







@require_torch
class        snake_case_   (unittest.TestCase      ):
					@slow
					def  lowerCamelCase__(      self   :str      )					->    Dict:
												a__             =     MraModel.from_pretrained('uw-madison/mra-base-512-4'      )
												a__             =     torch.arange(2_56      ).unsqueeze(0      )

												with torch.no_grad():
																			a__             =     model(__snake_case      )[0]

												a__             =     torch.Size((1, 2_56, 7_68)      )
												self.assertEqual(output.shape			,__snake_case      )

												a__             =     torch.tensor(
												    [[[-0.01_40, 0.08_30, -0.03_81], [0.15_46, 0.14_02, 0.02_20], [0.11_62, 0.08_51, 0.01_65]]]      )

												self.assertTrue(torch.allclose(output[:, :3, :3]			,__snake_case			,atol=1E-4      )      )
					@slow
					def  lowerCamelCase__(      self   :List[Any]      )					->    Optional[int]:
												a__             =     MraForMaskedLM.from_pretrained('uw-madison/mra-base-512-4'      )
												a__             =     torch.arange(2_56      ).unsqueeze(0      )

												with torch.no_grad():
																			a__             =     model(__snake_case      )[0]

												a__             =     5_02_65

												a__             =     torch.Size((1, 2_56, vocab_size)      )
												self.assertEqual(output.shape			,__snake_case      )

												a__             =     torch.tensor(
												    [[[9.25_95, -3.60_38, 11.88_19], [9.38_69, -3.26_93, 11.09_56], [11.85_24, -3.49_38, 13.12_10]]]      )

												self.assertTrue(torch.allclose(output[:, :3, :3]			,__snake_case			,atol=1E-4      )      )



					@slow
					def  lowerCamelCase__(      self   :Tuple      )					->    Optional[Any]:
												a__             =     MraForMaskedLM.from_pretrained('uw-madison/mra-base-4096-8-d3'      )
												a__             =     torch.arange(40_96      ).unsqueeze(0      )

												with torch.no_grad():
																			a__             =     model(__snake_case      )[0]

												a__             =     5_02_65

												a__             =     torch.Size((1, 40_96, vocab_size)      )
												self.assertEqual(output.shape			,__snake_case      )

												a__             =     torch.tensor(
												    [[[5.47_89, -2.35_64, 7.50_64], [7.90_67, -1.33_69, 9.96_68], [9.07_12, -1.81_06, 7.03_80]]]      )

												self.assertTrue(torch.allclose(output[:, :3, :3]			,__snake_case			,atol=1E-4      )      )








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


snake_case							:       int     			=      False







@skip_mps
class        snake_case_   (lowerCamelCase_	,						lowerCamelCase_	,						lowerCamelCase_	,						unittest.TestCase      ):
					UpperCAmelCase__					:    Union[str, Any]          =			StableDiffusionAttendAndExcitePipeline
					UpperCAmelCase__					:    List[str]          =			False
					UpperCAmelCase__					:    int          =			TEXT_TO_IMAGE_PARAMS
					UpperCAmelCase__					:    List[Any]          =			TEXT_TO_IMAGE_BATCH_PARAMS.union({'''token_indices'''}      )
					UpperCAmelCase__					:    List[str]          =			TEXT_TO_IMAGE_IMAGE_PARAMS
					UpperCAmelCase__					:    str          =			TEXT_TO_IMAGE_IMAGE_PARAMS
					@classmethod
					def  lowerCamelCase__(      cls   :int      )					->    int:
												super().setUpClass()
												torch.use_deterministic_algorithms(__snake_case      )
					@classmethod
					def  lowerCamelCase__(      cls   :Optional[Any]      )					->    int:
												super().tearDownClass()
												torch.use_deterministic_algorithms(__snake_case      )
					def  lowerCamelCase__(      self   :Dict      )					->    Optional[Any]:
												torch.manual_seed(0      )
												a__             =     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=__snake_case			,)
												a__             =     DDIMScheduler(
												    beta_start=0.0_00_85			,beta_end=0.0_12			,beta_schedule='scaled_linear'			,clip_sample=__snake_case			,set_alpha_to_one=__snake_case			,)
												torch.manual_seed(0      )
												a__             =     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__             =     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__             =     CLIPTextModel(__snake_case      )
												a__             =     CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'      )

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

												return components
					def  lowerCamelCase__(      self   :Any			,__snake_case   :Union[str, Any]			,__snake_case   :Tuple=0      )					->    Any:
												if str(__snake_case      ).startswith('mps'      ):
																			a__             =     torch.manual_seed(__snake_case      )
												else:
																			a__             =     torch.Generator(device=__snake_case      ).manual_seed(__snake_case      )
												a__             =     a__             =     {
												    '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  lowerCamelCase__(      self   :Optional[int]      )					->    Any:
												a__             =     'cpu'

												a__             =     self.get_dummy_components()
												a__             =     self.pipeline_class(**__snake_case      )
												pipe.to(__snake_case      )
												pipe.set_progress_bar_config(disable=__snake_case      )

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

												self.assertEqual(image.shape			,(1, 64, 64, 3)      )
												a__             =     np.array(
												    [0.63_90_53_64, 0.62_89_73_07, 0.48_59_90_17, 0.5_13_36_24, 0.5_55_00_48, 0.45_76_95_16, 0.50_32_69_73, 0.5_02_31_39, 0.45_38_44_96]      )
												a__             =     np.abs(image_slice.flatten() - expected_slice      ).max()
												self.assertLessEqual(__snake_case			,1E-3      )
					def  lowerCamelCase__(      self   :Optional[Any]      )					->    List[str]:
												super().test_cpu_offload_forward_pass(expected_max_diff=5E-4      )
					def  lowerCamelCase__(      self   :Dict      )					->    List[str]:
												# NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
												self._test_inference_batch_consistent(batch_sizes=[1, 2]      )
					def  lowerCamelCase__(      self   :List[str]      )					->    Optional[int]:
												self._test_inference_batch_single_identical(batch_size=2			,expected_max_diff=7E-4      )
					def  lowerCamelCase__(      self   :Dict      )					->    Dict:
												super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3      )
					def  lowerCamelCase__(      self   :Dict      )					->    Union[str, Any]:
												super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5E-4      )
					def  lowerCamelCase__(      self   :Optional[Any]      )					->    Dict:
												super().test_save_load_local(expected_max_difference=5E-4      )



					def  lowerCamelCase__(      self   :List[Any]      )					->    List[Any]:
												super().test_save_load_optional_components(expected_max_difference=4E-4      )







@require_torch_gpu
@slow
class        snake_case_   (unittest.TestCase      ):
					@classmethod
					def  lowerCamelCase__(      cls   :Optional[Any]      )					->    Tuple:
												super().setUpClass()
												torch.use_deterministic_algorithms(__snake_case      )
					@classmethod
					def  lowerCamelCase__(      cls   :Optional[int]      )					->    Tuple:
												super().tearDownClass()
												torch.use_deterministic_algorithms(__snake_case      )
					def  lowerCamelCase__(      self   :Tuple      )					->    Union[str, Any]:
												super().tearDown()
												gc.collect()
												torch.cuda.empty_cache()



					def  lowerCamelCase__(      self   :Optional[Any]      )					->    Tuple:
												a__             =     torch.manual_seed(51      )

												a__             =     StableDiffusionAttendAndExcitePipeline.from_pretrained(
												    'CompVis/stable-diffusion-v1-4'			,safety_checker=__snake_case			,torch_dtype=torch.floataa      )
												pipe.to('cuda'      )

												a__             =     'a painting of an elephant with glasses'
												a__             =     [5, 7]

												a__             =     pipe(
												    prompt=__snake_case			,token_indices=__snake_case			,guidance_scale=7.5			,generator=__snake_case			,num_inference_steps=5			,max_iter_to_alter=5			,output_type='numpy'			,).images[0]

												a__             =     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




