import unittest

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

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
      import torch

      from transformers import (
          OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
          OpenAIGPTConfig,
          OpenAIGPTDoubleHeadsModel,
          OpenAIGPTForSequenceClassification,
          OpenAIGPTLMHeadModel,
          OpenAIGPTModel,
      )





class      A							:


   def __init__(self     :						List[str]       ,  __UpperCAmelCase     :						str       ,  __UpperCAmelCase     :						Optional[int]=1_3       ,  __UpperCAmelCase     :						Optional[Any]=7       ,  __UpperCAmelCase     :						Tuple=True       ,  __UpperCAmelCase     :						Optional[Any]=True       ,  __UpperCAmelCase     :						List[Any]=True       ,  __UpperCAmelCase     :						Optional[Any]=9_9       ,  __UpperCAmelCase     :						Tuple=3_2       ,  __UpperCAmelCase     :						List[Any]=5       ,  __UpperCAmelCase     :						Optional[int]=4       ,  __UpperCAmelCase     :						Tuple=3_7       ,  __UpperCAmelCase     :						List[str]="gelu"       ,  __UpperCAmelCase     :						Dict=0.1       ,  __UpperCAmelCase     :						Optional[Any]=0.1       ,  __UpperCAmelCase     :						Tuple=5_1_2       ,  __UpperCAmelCase     :						Dict=1_6       ,  __UpperCAmelCase     :						Optional[int]=2       ,  __UpperCAmelCase     :						str=0.02       ,  __UpperCAmelCase     :						int=3       ,  __UpperCAmelCase     :						int=4       ,  __UpperCAmelCase     :						List[Any]=None       ,  )						->				List[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  parent
         UpperCAmelCase__								=  batch_size
         UpperCAmelCase__								=  seq_length
         UpperCAmelCase__								=  is_training
         UpperCAmelCase__								=  use_token_type_ids
         UpperCAmelCase__								=  use_labels
         UpperCAmelCase__								=  vocab_size
         UpperCAmelCase__								=  hidden_size
         UpperCAmelCase__								=  num_hidden_layers
         UpperCAmelCase__								=  num_attention_heads
         UpperCAmelCase__								=  intermediate_size
         UpperCAmelCase__								=  hidden_act
         UpperCAmelCase__								=  hidden_dropout_prob
         UpperCAmelCase__								=  attention_probs_dropout_prob
         UpperCAmelCase__								=  max_position_embeddings
         UpperCAmelCase__								=  type_vocab_size
         UpperCAmelCase__								=  type_sequence_label_size
         UpperCAmelCase__								=  initializer_range
         UpperCAmelCase__								=  num_labels
         UpperCAmelCase__								=  num_choices
         UpperCAmelCase__								=  scope
         UpperCAmelCase__								=  self.vocab_size - 1


   def 			lowercase_      (self     :						List[Any]		)						->				Optional[int]:
         """simple docstring"""



         UpperCAmelCase__								=  ids_tensor([self.batch_size, self.seq_length]       ,  self.vocab_size		)

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

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

         UpperCAmelCase__								=  OpenAIGPTConfig(
             vocab_size=self.vocab_size       ,  n_embd=self.hidden_size       ,  n_layer=self.num_hidden_layers       ,  n_head=self.num_attention_heads       ,  n_positions=self.max_position_embeddings       ,  pad_token_id=self.pad_token_id       ,  )

         UpperCAmelCase__								=  ids_tensor([self.num_hidden_layers, self.num_attention_heads]       ,  2		)

         return (
             config,
             input_ids,
             head_mask,
             token_type_ids,
             sequence_labels,
             token_labels,
             choice_labels,
         )


   def 			lowercase_      (self     :						List[str]       ,  __UpperCAmelCase     :						Optional[Any]       ,  __UpperCAmelCase     :						Optional[Any]       ,  __UpperCAmelCase     :						Union[str, Any]       ,  __UpperCAmelCase     :						Dict       ,  *__UpperCAmelCase     :						int		)						->				str:
         """simple docstring"""



         UpperCAmelCase__								=  OpenAIGPTModel(config=__UpperCAmelCase		)
         model.to(__UpperCAmelCase		)
         model.eval()

         UpperCAmelCase__								=  model(__UpperCAmelCase       ,  token_type_ids=__UpperCAmelCase       ,  head_mask=__UpperCAmelCase		)
         UpperCAmelCase__								=  model(__UpperCAmelCase       ,  token_type_ids=__UpperCAmelCase		)
         UpperCAmelCase__								=  model(__UpperCAmelCase		)

         self.parent.assertEqual(result.last_hidden_state.shape       ,  (self.batch_size, self.seq_length, self.hidden_size)		)


   def 			lowercase_      (self     :						Optional[int]       ,  __UpperCAmelCase     :						int       ,  __UpperCAmelCase     :						str       ,  __UpperCAmelCase     :						int       ,  __UpperCAmelCase     :						Union[str, Any]       ,  *__UpperCAmelCase     :						Optional[Any]		)						->				Optional[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  OpenAIGPTLMHeadModel(__UpperCAmelCase		)
         model.to(__UpperCAmelCase		)
         model.eval()

         UpperCAmelCase__								=  model(__UpperCAmelCase       ,  token_type_ids=__UpperCAmelCase       ,  labels=__UpperCAmelCase		)
         self.parent.assertEqual(result.loss.shape       ,  ()		)
         self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.seq_length, self.vocab_size)		)


   def 			lowercase_      (self     :						int       ,  __UpperCAmelCase     :						int       ,  __UpperCAmelCase     :						Optional[Any]       ,  __UpperCAmelCase     :						Any       ,  __UpperCAmelCase     :						Dict       ,  *__UpperCAmelCase     :						str		)						->				List[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  OpenAIGPTDoubleHeadsModel(__UpperCAmelCase		)
         model.to(__UpperCAmelCase		)
         model.eval()

         UpperCAmelCase__								=  model(__UpperCAmelCase       ,  token_type_ids=__UpperCAmelCase       ,  labels=__UpperCAmelCase		)
         self.parent.assertEqual(result.loss.shape       ,  ()		)
         self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.seq_length, self.vocab_size)		)


   def 			lowercase_      (self     :						List[Any]       ,  __UpperCAmelCase     :						List[Any]       ,  __UpperCAmelCase     :						List[str]       ,  __UpperCAmelCase     :						int       ,  __UpperCAmelCase     :						Optional[Any]       ,  *__UpperCAmelCase     :						Optional[Any]		)						->				int:
         """simple docstring"""



         UpperCAmelCase__								=  self.num_labels
         UpperCAmelCase__								=  OpenAIGPTForSequenceClassification(__UpperCAmelCase		)
         model.to(__UpperCAmelCase		)
         model.eval()

         UpperCAmelCase__								=  ids_tensor([self.batch_size]       ,  self.type_sequence_label_size		)
         UpperCAmelCase__								=  model(__UpperCAmelCase       ,  token_type_ids=__UpperCAmelCase       ,  labels=__UpperCAmelCase		)
         self.parent.assertEqual(result.logits.shape       ,  (self.batch_size, self.num_labels)		)





   def 			lowercase_      (self     :						List[str]		)						->				Optional[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  self.prepare_config_and_inputs()
         (
             (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      (
             UpperCAmelCase__
         )		,      
         )								=  config_and_inputs
         UpperCAmelCase__								=  {
             "input_ids": input_ids,
             "token_type_ids": token_type_ids,
             "head_mask": head_mask,
         }

         return config, inputs_dict





@require_torch
class      A							(				UpperCAmelCase_		,				UpperCAmelCase_		,				UpperCAmelCase_		,				unittest.TestCase     ):
   __UpperCAmelCase : Optional[Any]      =			(
       (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
       if is_torch_available()
       else ()
   )
   __UpperCAmelCase : List[Any]      =			(
       (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
   )  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
   __UpperCAmelCase : Optional[Any]      =			(
       {
           'feature-extraction': OpenAIGPTModel,
           'text-classification': OpenAIGPTForSequenceClassification,
           'text-generation': OpenAIGPTLMHeadModel,
           'zero-shot': OpenAIGPTForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )


   def 			lowercase_      (self     :						List[str]       ,  __UpperCAmelCase     :						Dict       ,  __UpperCAmelCase     :						Union[str, Any]       ,  __UpperCAmelCase     :						int       ,  __UpperCAmelCase     :						int       ,  __UpperCAmelCase     :						int		)						->				Tuple:
         """simple docstring"""



         if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
               # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
               # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a
               # tiny config could not be created.
               return True

         return False


   def 			lowercase_      (self     :						Dict       ,  __UpperCAmelCase     :						Optional[Any]       ,  __UpperCAmelCase     :						Union[str, Any]       ,  __UpperCAmelCase     :						str=False		)						->				Optional[Any]:
         """simple docstring"""



         UpperCAmelCase__								=  super()._prepare_for_class(__UpperCAmelCase       ,  __UpperCAmelCase       ,  return_labels=__UpperCAmelCase		)

         if return_labels:
               if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
                     UpperCAmelCase__								=  torch.zeros(
                         (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)       ,  dtype=torch.long       ,  device=__UpperCAmelCase       ,  )
                     UpperCAmelCase__								=  inputs_dict["labels"]
                     UpperCAmelCase__								=  inputs_dict["labels"]
                     UpperCAmelCase__								=  torch.zeros(
                         (self.model_tester.batch_size, self.model_tester.num_choices)       ,  dtype=torch.long       ,  device=__UpperCAmelCase       ,  )
                     UpperCAmelCase__								=  torch.zeros(
                         self.model_tester.batch_size       ,  dtype=torch.long       ,  device=__UpperCAmelCase		)
         return inputs_dict


   def 			lowercase_      (self     :						Union[str, Any]		)						->				Any:
         """simple docstring"""



         UpperCAmelCase__								=  OpenAIGPTModelTester(self		)
         UpperCAmelCase__								=  ConfigTester(self       ,  config_class=__UpperCAmelCase       ,  n_embd=3_7		)


   def 			lowercase_      (self     :						Union[str, Any]		)						->				Any:
         """simple docstring"""



         self.config_tester.run_common_tests()


   def 			lowercase_      (self     :						List[str]		)						->				Union[str, Any]:
         """simple docstring"""



         UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_openai_gpt_model(*__UpperCAmelCase		)


   def 			lowercase_      (self     :						Union[str, Any]		)						->				List[str]:
         """simple docstring"""



         UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_lm_head_model(*__UpperCAmelCase		)


   def 			lowercase_      (self     :						Union[str, Any]		)						->				str:
         """simple docstring"""



         UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_double_lm_head_model(*__UpperCAmelCase		)


   def 			lowercase_      (self     :						Tuple		)						->				Any:
         """simple docstring"""



         UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*__UpperCAmelCase		)





   @slow
   def 			lowercase_      (self     :						Optional[int]		)						->				Union[str, Any]:
         """simple docstring"""



         for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               UpperCAmelCase__								=  OpenAIGPTModel.from_pretrained(__UpperCAmelCase		)
               self.assertIsNotNone(__UpperCAmelCase		)





@require_torch
class      A							(				unittest.TestCase     ):


   @slow
   def 			lowercase_      (self     :						List[Any]		)						->				int:
         """simple docstring"""



         UpperCAmelCase__								=  OpenAIGPTLMHeadModel.from_pretrained("openai-gpt"		)
         model.to(__UpperCAmelCase		)
         UpperCAmelCase__								=  torch.tensor([[4_8_1, 4_7_3_5, 5_4_4]]       ,  dtype=torch.long       ,  device=__UpperCAmelCase		)  # the president is
         UpperCAmelCase__								=  [
             4_8_1,
             4_7_3_5,
             5_4_4,
             2_4_6,
             9_6_3,
             8_7_0,
             7_6_2,
             2_3_9,
             2_4_4,
             4_0_4_7_7,
             2_4_4,
             2_4_9,
             7_1_9,
             8_8_1,
             4_8_7,
             5_4_4,
             2_4_0,
             2_4_4,
             6_0_3,
             4_8_1,
         ]  # the president is a very good man. " \n " i\'m sure he is, " said the

         UpperCAmelCase__								=  model.generate(__UpperCAmelCase       ,  do_sample=__UpperCAmelCase		)
         self.assertListEqual(output_ids[0].tolist()       ,  __UpperCAmelCase		)





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__          =		False







@skip_mps
class      A__							(     __magic_name__						,   __magic_name__						,   __magic_name__						,   unittest.TestCase	):
				lowercase			    =  StableDiffusionAttendAndExcitePipeline
				lowercase			    =  False
				lowercase			    =  TEXT_TO_IMAGE_PARAMS
				lowercase			    =  TEXT_TO_IMAGE_BATCH_PARAMS.union({'token_indices'}	)
				lowercase			    =  TEXT_TO_IMAGE_IMAGE_PARAMS
				lowercase			    =  TEXT_TO_IMAGE_IMAGE_PARAMS






				@classmethod
				def 							_lowerCamelCase		(						cls					:      Tuple   ):






							'''simple docstring'''







							super().setUpClass()
							torch.use_deterministic_algorithms(a   )






				@classmethod
				def 							_lowerCamelCase		(						cls					:      Any   ):






							'''simple docstring'''







							super().tearDownClass()
							torch.use_deterministic_algorithms(a   )






				def 							_lowerCamelCase		(						self					:      Optional[Any]   ):






							'''simple docstring'''







							torch.manual_seed(0   )
							lowerCAmelCase__      :      Any         =		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=a    ,     )
							lowerCAmelCase__      :      Any         =		DDIMScheduler(
							    beta_start=0.0_0_0_8_5    ,     beta_end=0.0_1_2    ,     beta_schedule='scaled_linear'    ,     clip_sample=a    ,     set_alpha_to_one=a    ,     )
							torch.manual_seed(0   )
							lowerCAmelCase__      :      Union[str, Any]         =		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=128    ,     )
							torch.manual_seed(0   )
							lowerCAmelCase__      :      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=1_000    ,     hidden_act='gelu'    ,     projection_dim=512    ,     )
							lowerCAmelCase__      :      str         =		CLIPTextModel(a   )
							lowerCAmelCase__      :      Optional[Any]         =		CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'   )

							lowerCAmelCase__      :      Union[str, Any]         =		{
							    'unet': unet,
							    'scheduler': scheduler,
							    'vae': vae,
							    'text_encoder': text_encoder,
							    'tokenizer': tokenizer,
							    'safety_checker': None,
							    'feature_extractor': None,
							}

							return components






				def 							_lowerCamelCase		(						self					:      Union[str, Any]    ,     a					:      Tuple    ,     a					:      Union[str, Any]=0   ):






							'''simple docstring'''







							if str(a   ).startswith('mps'   ):
										lowerCAmelCase__      :      List[str]         =		torch.manual_seed(a   )
							else:
										lowerCAmelCase__      :      Any         =		torch.Generator(device=a   ).manual_seed(a   )
							lowerCAmelCase__      :      Optional[int]         =		{
							    '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]   ):






							'''simple docstring'''







							lowerCAmelCase__      :      Tuple         =		'cpu'

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

							lowerCAmelCase__      :      Union[str, Any]         =		self.get_dummy_inputs(a   )
							lowerCAmelCase__      :      Union[str, Any]         =		pipe(**a   ).images
							lowerCAmelCase__      :      Optional[int]         =		image[0, -3:, -3:, -1]

							self.assertEqual(image.shape    ,     (1, 64, 64, 3)   )
							lowerCAmelCase__      :      Dict         =		np.array(
							    [0.6_3_9_0_5_3_6_4, 0.6_2_8_9_7_3_0_7, 0.4_8_5_9_9_0_1_7, 0.5_1_3_3_6_2_4, 0.5_5_5_0_0_4_8, 0.4_5_7_6_9_5_1_6, 0.5_0_3_2_6_9_7_3, 0.5_0_2_3_1_3_9, 0.4_5_3_8_4_4_9_6]   )
							lowerCAmelCase__      :      Optional[int]         =		np.abs(image_slice.flatten() - expected_slice   ).max()
							self.assertLessEqual(a    ,     1E-3   )






				def 							_lowerCamelCase		(						self					:      Optional[Any]   ):






							'''simple docstring'''







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






				def 							_lowerCamelCase		(						self					:      List[str]   ):






							'''simple docstring'''







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






				def 							_lowerCamelCase		(						self					:      Tuple   ):






							'''simple docstring'''







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






				def 							_lowerCamelCase		(						self					:      List[Any]   ):






							'''simple docstring'''







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






				def 							_lowerCamelCase		(						self					:      List[str]   ):






							'''simple docstring'''







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






				def 							_lowerCamelCase		(						self					:      Any   ):






							'''simple docstring'''







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






				def 							_lowerCamelCase		(						self					:      Dict   ):






							'''simple docstring'''







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







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






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






							'''simple docstring'''







							super().setUpClass()
							torch.use_deterministic_algorithms(a   )






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






							'''simple docstring'''







							super().tearDownClass()
							torch.use_deterministic_algorithms(a   )






				def 							_lowerCamelCase		(						self					:      int   ):






							'''simple docstring'''







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






				def 							_lowerCamelCase		(						self					:      Tuple   ):






							'''simple docstring'''







							lowerCAmelCase__      :      List[str]         =		torch.manual_seed(51   )

							lowerCAmelCase__      :      Any         =		StableDiffusionAttendAndExcitePipeline.from_pretrained(
							    'CompVis/stable-diffusion-v1-4'    ,     safety_checker=a    ,     torch_dtype=torch.floataa   )
							pipe.to('cuda'   )

							lowerCAmelCase__      :      Optional[int]         =		'a painting of an elephant with glasses'
							lowerCAmelCase__      :      Any         =		[5, 7]

							lowerCAmelCase__      :      Optional[Any]         =		pipe(
							    prompt=a    ,     token_indices=a    ,     guidance_scale=7.5    ,     generator=a    ,     num_inference_steps=5    ,     max_iter_to_alter=5    ,     output_type='numpy'    ,     ).images[0]

							lowerCAmelCase__      :      str         =		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