




"""simple docstring"""




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 				lowerCamelCase		:







   def __init__(				self     ,   SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_=13     ,   SCREAMING_SNAKE_CASE_=7     ,   SCREAMING_SNAKE_CASE_=True     ,   SCREAMING_SNAKE_CASE_=True     ,   SCREAMING_SNAKE_CASE_=True     ,   SCREAMING_SNAKE_CASE_=99     ,   SCREAMING_SNAKE_CASE_=32     ,   SCREAMING_SNAKE_CASE_=5     ,   SCREAMING_SNAKE_CASE_=4     ,   SCREAMING_SNAKE_CASE_=37     ,   SCREAMING_SNAKE_CASE_="gelu"     ,   SCREAMING_SNAKE_CASE_=0.1     ,   SCREAMING_SNAKE_CASE_=0.1     ,   SCREAMING_SNAKE_CASE_=512     ,   SCREAMING_SNAKE_CASE_=16     ,   SCREAMING_SNAKE_CASE_=2     ,   SCREAMING_SNAKE_CASE_=0.02     ,   SCREAMING_SNAKE_CASE_=3     ,   SCREAMING_SNAKE_CASE_=4     ,   SCREAMING_SNAKE_CASE_=None     ,   ):
       UpperCamelCase					: Union[str, Any] 							=				parent
       UpperCamelCase					: List[Any] 							=				batch_size
       UpperCamelCase					: Union[str, Any] 							=				seq_length
       UpperCamelCase					: Union[str, Any] 							=				is_training
       UpperCamelCase					: Any 							=				use_token_type_ids
       UpperCamelCase					: List[str] 							=				use_labels
       UpperCamelCase					: Optional[int] 							=				vocab_size
       UpperCamelCase					: List[str] 							=				hidden_size
       UpperCamelCase					: Union[str, Any] 							=				num_hidden_layers
       UpperCamelCase					: List[str] 							=				num_attention_heads
       UpperCamelCase					: Union[str, Any] 							=				intermediate_size
       UpperCamelCase					: Optional[Any] 							=				hidden_act
       UpperCamelCase					: Optional[int] 							=				hidden_dropout_prob
       UpperCamelCase					: Optional[int] 							=				attention_probs_dropout_prob
       UpperCamelCase					: Optional[int] 							=				max_position_embeddings
       UpperCamelCase					: Optional[Any] 							=				type_vocab_size
       UpperCamelCase					: Tuple 							=				type_sequence_label_size
       UpperCamelCase					: Union[str, Any] 							=				initializer_range
       UpperCamelCase					: Tuple 							=				num_labels
       UpperCamelCase					: Optional[int] 							=				num_choices
       UpperCamelCase					: Optional[Any] 							=				scope
       UpperCamelCase					: List[str] 							=				self.vocab_size - 1







   def    a_				(				self			):
       UpperCamelCase					: List[str] 							=				ids_tensor([self.batch_size, self.seq_length]     ,   self.vocab_size			)

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

       UpperCamelCase					: List[Any] 							=				None
       UpperCamelCase					: Optional[int] 							=				None
       UpperCamelCase					: Dict 							=				None
       if self.use_labels:
           UpperCamelCase					: Optional[int] 							=				ids_tensor([self.batch_size]     ,   self.type_sequence_label_size			)
           UpperCamelCase					: str 							=				ids_tensor([self.batch_size, self.seq_length]     ,   self.num_labels			)
           UpperCamelCase					: Optional[int] 							=				ids_tensor([self.batch_size]     ,   self.num_choices			)

       UpperCamelCase					: List[Any] 							=				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					: Any 							=				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    a_				(				self     ,   SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_     ,   *SCREAMING_SNAKE_CASE_			):
       UpperCamelCase					: str 							=				OpenAIGPTModel(config=_snake_case			)
       model.to(_snake_case			)
       model.eval()

       UpperCamelCase					: Any 							=				model(_snake_case     ,   token_type_ids=_snake_case     ,   head_mask=_snake_case			)
       UpperCamelCase					: Optional[int] 							=				model(_snake_case     ,   token_type_ids=_snake_case			)
       UpperCamelCase					: Union[str, Any] 							=				model(_snake_case			)

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







   def    a_				(				self     ,   SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_     ,   *SCREAMING_SNAKE_CASE_			):
       UpperCamelCase					: int 							=				OpenAIGPTLMHeadModel(_snake_case			)
       model.to(_snake_case			)
       model.eval()

       UpperCamelCase					: Any 							=				model(_snake_case     ,   token_type_ids=_snake_case     ,   labels=_snake_case			)
       self.parent.assertEqual(result.loss.shape     ,   ()			)
       self.parent.assertEqual(result.logits.shape     ,   (self.batch_size, self.seq_length, self.vocab_size)			)







   def    a_				(				self     ,   SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_     ,   *SCREAMING_SNAKE_CASE_			):
       UpperCamelCase					: int 							=				OpenAIGPTDoubleHeadsModel(_snake_case			)
       model.to(_snake_case			)
       model.eval()

       UpperCamelCase					: Dict 							=				model(_snake_case     ,   token_type_ids=_snake_case     ,   labels=_snake_case			)
       self.parent.assertEqual(result.loss.shape     ,   ()			)
       self.parent.assertEqual(result.logits.shape     ,   (self.batch_size, self.seq_length, self.vocab_size)			)







   def    a_				(				self     ,   SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_     ,   *SCREAMING_SNAKE_CASE_			):
       UpperCamelCase					: Dict 							=				self.num_labels
       UpperCamelCase					: Any 							=				OpenAIGPTForSequenceClassification(_snake_case			)
       model.to(_snake_case			)
       model.eval()

       UpperCamelCase					: Any 							=				ids_tensor([self.batch_size]     ,   self.type_sequence_label_size			)
       UpperCamelCase					: Any 							=				model(_snake_case     ,   token_type_ids=_snake_case     ,   labels=_snake_case			)
       self.parent.assertEqual(result.logits.shape     ,   (self.batch_size, self.num_labels)			)







   def    a_				(				self			):
       UpperCamelCase					: Any 							=				self.prepare_config_and_inputs()
       (
           (
           UpperCamelCase
       )							,				(
           UpperCamelCase
       )							,				(
           UpperCamelCase
       )							,				(
           UpperCamelCase
       )							,				(
           UpperCamelCase
       )							,				(
           UpperCamelCase
       )							,				(
           UpperCamelCase
       )							,				
       )					: List[str] 							=				config_and_inputs
       UpperCamelCase					: int 							=				{
           """input_ids""": input_ids,
           """token_type_ids""": token_type_ids,
           """head_mask""": head_mask,
       }

       return config, inputs_dict







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







   def    a_				(				self     ,   SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_			):






       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    a_				(				self     ,   SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_     ,   SCREAMING_SNAKE_CASE_=False			):
       UpperCamelCase					: Any 							=				super()._prepare_for_class(_snake_case     ,   _snake_case     ,   return_labels=_snake_case			)

       if return_labels:
           if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
               UpperCamelCase					: Union[str, Any] 							=				torch.zeros(
                   (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)     ,   dtype=torch.long     ,   device=_snake_case     ,   )
               UpperCamelCase					: int 							=				inputs_dict["""labels"""]
               UpperCamelCase					: Tuple 							=				inputs_dict["""labels"""]
               UpperCamelCase					: int 							=				torch.zeros(
                   (self.model_tester.batch_size, self.model_tester.num_choices)     ,   dtype=torch.long     ,   device=_snake_case     ,   )
               UpperCamelCase					: List[str] 							=				torch.zeros(
                   self.model_tester.batch_size     ,   dtype=torch.long     ,   device=_snake_case			)
       return inputs_dict







   def    a_				(				self			):
       UpperCamelCase					: Union[str, Any] 							=				OpenAIGPTModelTester(self			)
       UpperCamelCase					: int 							=				ConfigTester(self     ,   config_class=_snake_case     ,   n_embd=37			)







   def    a_				(				self			):
       self.config_tester.run_common_tests()







   def    a_				(				self			):
       UpperCamelCase					: int 							=				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_openai_gpt_model(*_snake_case			)







   def    a_				(				self			):
       UpperCamelCase					: Optional[Any] 							=				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_lm_head_model(*_snake_case			)







   def    a_				(				self			):
       UpperCamelCase					: int 							=				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_double_lm_head_model(*_snake_case			)







   def    a_				(				self			):
       UpperCamelCase					: str 							=				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*_snake_case			)







   @slow
   def    a_				(				self			):






       for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           UpperCamelCase					: str 							=				OpenAIGPTModel.from_pretrained(_snake_case			)
           self.assertIsNotNone(_snake_case			)







@require_torch
class 				lowerCamelCase		(			unittest.TestCase					):







   @slow
   def    a_				(				self			):
       UpperCamelCase					: Any 							=				OpenAIGPTLMHeadModel.from_pretrained("""openai-gpt"""			)
       model.to(_snake_case			)
       UpperCamelCase					: Tuple 							=				torch.tensor([[481, 4735, 544]]     ,   dtype=torch.long     ,   device=_snake_case			)  # the president is
       UpperCamelCase					: Tuple 							=				[
           481,
           4735,
           544,
           246,
           963,
           870,
           762,
           239,
           244,
           4_0477,
           244,
           249,
           719,
           881,
           487,
           544,
           240,
           244,
           603,
           481,
       ]  # the president is a very good man. " \n " i\'m sure he is, " said the

       UpperCamelCase					: Optional[int] 							=				model.generate(_snake_case     ,   do_sample=_snake_case			)
       self.assertListEqual(output_ids[0].tolist()     ,   _snake_case			)











"""simple docstring"""
import random
import unittest

import torch

from diffusers import IFInpaintingPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin







@skip_mps
class       a							(   a__   , a__   , unittest.TestCase  ):
 snake_case__             =       IFInpaintingPipeline
 snake_case__             =       TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {'''width''', '''height'''}
 snake_case__             =       TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
 snake_case__             =       PipelineTesterMixin.required_optional_params - {'''latents'''}



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  return self._get_dummy_components()



 def    UpperCamelCase__  (     self				,       _snake_case				,       _snake_case=0     ):







  """simple docstring"""






  if str(_snake_case     ).startswith('mps'     ):
   lowerCAmelCase    				= torch.manual_seed(_snake_case     )
  else:
   lowerCAmelCase    				= torch.Generator(device=_snake_case     ).manual_seed(_snake_case     )

  lowerCAmelCase    				= floats_tensor((1, 3, 32, 32)				,       rng=random.Random(_snake_case     )     ).to(_snake_case     )
  lowerCAmelCase    				= floats_tensor((1, 3, 32, 32)				,       rng=random.Random(_snake_case     )     ).to(_snake_case     )

  lowerCAmelCase    				= {
      'prompt': 'A painting of a squirrel eating a burger',
      'image': image,
      'mask_image': mask_image,
      'generator': generator,
      'num_inference_steps': 2,
      'output_type': 'numpy',
  }

  return inputs



 @unittest.skipIf(
     torch_device != 'cuda' or not is_xformers_available()				,       reason='XFormers attention is only available with CUDA and `xformers` installed'				,       )
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  self._test_save_load_optional_components()



 @unittest.skipIf(torch_device != 'cuda'				,       reason='float16 requires CUDA'     )
 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  super().test_save_load_floataa(expected_max_diff=1E-1     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  self._test_attention_slicing_forward_pass(expected_max_diff=1E-2     )



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  self._test_save_load_local()



 def    UpperCamelCase__  (     self     ):







  """simple docstring"""






  self._test_inference_batch_single_identical(
      expected_max_diff=1E-2				,       )





