


from __future__ import annotations

import unittest

from transformers import OpenAIGPTConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
    import tensorflow as tf

    from transformers.models.openai.modeling_tf_openai import (
        TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
        TFOpenAIGPTDoubleHeadsModel,
        TFOpenAIGPTForSequenceClassification,
        TFOpenAIGPTLMHeadModel,
        TFOpenAIGPTModel,
    )







class       _lowercase			:


       """simple docstring"""




       def __init__(       self							:      List[Any] ,				__lowerCamelCase							:      Union[str, Any] ,				):


             '''simple docstring'''



             lowerCamelCase__		:    Optional[int]   =  parent
             lowerCamelCase__		:    Optional[Any]   =  13
             lowerCamelCase__		:    Tuple   =  7
             lowerCamelCase__		:    Union[str, Any]   =  True
             lowerCamelCase__		:    Tuple   =  True
             lowerCamelCase__		:    Any   =  True
             lowerCamelCase__		:    Tuple   =  True
             lowerCamelCase__		:    List[str]   =  True
             lowerCamelCase__		:    Dict   =  99
             lowerCamelCase__		:    str   =  32
             lowerCamelCase__		:    int   =  2
             lowerCamelCase__		:    Tuple   =  4
             lowerCamelCase__		:    Optional[Any]   =  37
             lowerCamelCase__		:    Optional[int]   =  "gelu"
             lowerCamelCase__		:    Union[str, Any]   =  0.1
             lowerCamelCase__		:    List[str]   =  0.1
             lowerCamelCase__		:    int   =  512
             lowerCamelCase__		:    Any   =  16
             lowerCamelCase__		:    Any   =  2
             lowerCamelCase__		:    Any   =  0.0_2
             lowerCamelCase__		:    List[str]   =  3
             lowerCamelCase__		:    str   =  4
             lowerCamelCase__		:    Any   =  None
             lowerCamelCase__		:    Union[str, Any]   =  self.vocab_size - 1





       def 						lowerCAmelCase					(       self							:      Optional[int]	):


             '''simple docstring'''



             lowerCamelCase__		:    List[str]   =  ids_tensor([self.batch_size, self.seq_length] ,				self.vocab_size	)

             lowerCamelCase__		:    List[str]   =  None
             if self.use_input_mask:
                   lowerCamelCase__		:    Any   =  random_attention_mask([self.batch_size, self.seq_length]	)

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

             lowerCamelCase__		:    Any   =  None
             if self.use_mc_token_ids:
                   lowerCamelCase__		:    Union[str, Any]   =  ids_tensor([self.batch_size, self.num_choices] ,				self.seq_length	)

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

             lowerCamelCase__		:    str   =  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 ,				)

             lowerCamelCase__		:    List[str]   =  ids_tensor([self.num_hidden_layers, self.num_attention_heads] ,				2	)

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





       def 						lowerCAmelCase					(       self							:      Dict ,				__lowerCamelCase							:      List[str] ,				__lowerCamelCase							:      Tuple ,				__lowerCamelCase							:      Dict ,				__lowerCamelCase							:      Tuple ,				__lowerCamelCase							:      Tuple ,				*__lowerCamelCase							:      Optional[Any]	):


             '''simple docstring'''



             lowerCamelCase__		:    List[Any]   =  TFOpenAIGPTModel(config=__lowerCamelCase	)
             lowerCamelCase__		:    str   =  {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
             lowerCamelCase__		:    Any   =  model(__lowerCamelCase	)

             lowerCamelCase__		:    Optional[Any]   =  [input_ids, input_mask]
             lowerCamelCase__		:    Any   =  model(__lowerCamelCase	)

             lowerCamelCase__		:    Optional[Any]   =  model(__lowerCamelCase	)

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





       def 						lowerCAmelCase					(       self							:      Optional[int] ,				__lowerCamelCase							:      Optional[int] ,				__lowerCamelCase							:      Union[str, Any] ,				__lowerCamelCase							:      int ,				__lowerCamelCase							:      Tuple ,				__lowerCamelCase							:      Any ,				*__lowerCamelCase							:      Any	):


             '''simple docstring'''



             lowerCamelCase__		:    Optional[Any]   =  TFOpenAIGPTLMHeadModel(config=__lowerCamelCase	)
             lowerCamelCase__		:    str   =  {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
             lowerCamelCase__		:    Any   =  model(__lowerCamelCase	)
             self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.seq_length, self.vocab_size)	)





       def 						lowerCAmelCase					(       self							:      Optional[Any] ,				__lowerCamelCase							:      Any ,				__lowerCamelCase							:      List[str] ,				__lowerCamelCase							:      int ,				__lowerCamelCase							:      str ,				__lowerCamelCase							:      List[Any] ,				__lowerCamelCase							:      int ,				*__lowerCamelCase							:      List[str]	):


             '''simple docstring'''



             lowerCamelCase__		:    Dict   =  TFOpenAIGPTDoubleHeadsModel(config=__lowerCamelCase	)

             lowerCamelCase__		:    Union[str, Any]   =  tf.tile(tf.expand_dims(__lowerCamelCase ,				1	) ,				(1, self.num_choices, 1)	)
             lowerCamelCase__		:    Any   =  tf.tile(tf.expand_dims(__lowerCamelCase ,				1	) ,				(1, self.num_choices, 1)	)
             lowerCamelCase__		:    int   =  tf.tile(tf.expand_dims(__lowerCamelCase ,				1	) ,				(1, self.num_choices, 1)	)

             lowerCamelCase__		:    Any   =  {
                 "input_ids": multiple_choice_inputs_ids,
                 "mc_token_ids": mc_token_ids,
                 "attention_mask": multiple_choice_input_mask,
                 "token_type_ids": multiple_choice_token_type_ids,
             }
             lowerCamelCase__		:    Union[str, Any]   =  model(__lowerCamelCase	)
             self.parent.assertEqual(
                 result.logits.shape ,				(self.batch_size, self.num_choices, self.seq_length, self.vocab_size)	)
             self.parent.assertEqual(result.mc_logits.shape ,				(self.batch_size, self.num_choices)	)





       def 						lowerCAmelCase					(       self							:      Union[str, Any] ,				__lowerCamelCase							:      int ,				__lowerCamelCase							:      Dict ,				__lowerCamelCase							:      List[Any] ,				__lowerCamelCase							:      Optional[int] ,				__lowerCamelCase							:      str ,				*__lowerCamelCase							:      Optional[int]	):


             '''simple docstring'''



             lowerCamelCase__		:    Optional[int]   =  self.num_labels
             lowerCamelCase__		:    Tuple   =  ids_tensor([self.batch_size] ,				self.type_sequence_label_size	)
             lowerCamelCase__		:    Optional[int]   =  {
                 "input_ids": input_ids,
                 "attention_mask": input_mask,
                 "token_type_ids": token_type_ids,
                 "labels": sequence_labels,
             }
             lowerCamelCase__		:    Optional[Any]   =  TFOpenAIGPTForSequenceClassification(__lowerCamelCase	)
             lowerCamelCase__		:    Optional[Any]   =  model(__lowerCamelCase	)
             self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.num_labels)	)





       def 						lowerCAmelCase					(       self							:      List[str]	):


             '''simple docstring'''



             lowerCamelCase__		:    int   =  self.prepare_config_and_inputs()

             (
                 lowerCamelCase__       
             )		:    List[Any]   =  config_and_inputs

             lowerCamelCase__		:    Optional[Any]   =  {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
             return config, inputs_dict







@require_tf
class       _lowercase			(							lowercase__							,  lowercase__							,  unittest.TestCase):


       """simple docstring"""




       A__ 						=      (
           (TFOpenAIGPTModel, TFOpenAIGPTLMHeadModel, TFOpenAIGPTDoubleHeadsModel, TFOpenAIGPTForSequenceClassification)
           if is_tf_available()
           else ()
       )
       A__ 						=      (
           (TFOpenAIGPTLMHeadModel,) if is_tf_available() else ()
       )  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
       A__ 						=      (
           {
               "feature-extraction": TFOpenAIGPTModel,
               "text-classification": TFOpenAIGPTForSequenceClassification,
               "text-generation": TFOpenAIGPTLMHeadModel,
               "zero-shot": TFOpenAIGPTForSequenceClassification,
           }
           if is_tf_available()
           else {}
       )
       A__ 						=      False
       A__ 						=      False





       def 						lowerCAmelCase					(       self							:      Tuple ,				__lowerCamelCase							:      int ,				__lowerCamelCase							:      int ,				__lowerCamelCase							:      Dict ,				__lowerCamelCase							:      List[Any] ,				__lowerCamelCase							:      Any	):


             '''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 						lowerCAmelCase					(       self							:      List[str]	):


             '''simple docstring'''



             lowerCamelCase__		:    Union[str, Any]   =  TFOpenAIGPTModelTester(self	)
             lowerCamelCase__		:    Dict   =  ConfigTester(self ,				config_class=__lowerCamelCase ,				n_embd=37	)





       def 						lowerCAmelCase					(       self							:      List[Any]	):


             '''simple docstring'''



             self.config_tester.run_common_tests()





       def 						lowerCAmelCase					(       self							:      List[Any]	):


             '''simple docstring'''



             lowerCamelCase__		:    Optional[int]   =  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_openai_gpt_model(*__lowerCamelCase	)





       def 						lowerCAmelCase					(       self							:      Union[str, Any]	):


             '''simple docstring'''



             lowerCamelCase__		:    Union[str, Any]   =  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_openai_gpt_lm_head(*__lowerCamelCase	)





       def 						lowerCAmelCase					(       self							:      str	):


             '''simple docstring'''



             lowerCamelCase__		:    Optional[int]   =  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_openai_gpt_double_head(*__lowerCamelCase	)





       def 						lowerCAmelCase					(       self							:      Dict	):


             '''simple docstring'''



             lowerCamelCase__		:    Union[str, Any]   =  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*__lowerCamelCase	)





       @slow
       def 						lowerCAmelCase					(       self							:      Union[str, Any]	):


             '''simple docstring'''



             for model_name in TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   lowerCamelCase__		:    str   =  TFOpenAIGPTModel.from_pretrained(__lowerCamelCase	)
                   self.assertIsNotNone(__lowerCamelCase	)







@require_tf
class       _lowercase			(							unittest.TestCase):


       """simple docstring"""




       @slow
       def 						lowerCAmelCase					(       self							:      int	):


             '''simple docstring'''



             lowerCamelCase__		:    int   =  TFOpenAIGPTLMHeadModel.from_pretrained("openai-gpt"	)
             lowerCamelCase__		:    Union[str, Any]   =  tf.convert_to_tensor([[481, 4735, 544]] ,				dtype=tf.intaa	)  # the president is
             lowerCamelCase__		:    Union[str, Any]   =  [
                 481,
                 4735,
                 544,
                 246,
                 963,
                 870,
                 762,
                 239,
                 244,
                 40477,
                 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

             lowerCamelCase__		:    int   =  model.generate(__lowerCamelCase ,				do_sample=__lowerCamelCase	)
             self.assertListEqual(output_ids[0].numpy().tolist() ,				__lowerCamelCase	)






from typing import Any, Callable, Dict, List, Optional, Union

import PIL.Image
import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionImgaImgPipeline,
    StableDiffusionInpaintPipelineLegacy,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.configuration_utils import FrozenDict
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.utils import deprecate, logging


A				:   str		= logging.get_logger(__name__)  # pylint: disable=invalid-name







class       _lowercase			(							lowercase__):


       """simple docstring"""




       A__ 						=      ["safety_checker", "feature_extractor"]





       def __init__(       self							:      Optional[Any] ,				__lowerCamelCase							:      AutoencoderKL ,				__lowerCamelCase							:      CLIPTextModel ,				__lowerCamelCase							:      CLIPTokenizer ,				__lowerCamelCase							:      UNetaDConditionModel ,				__lowerCamelCase							:      Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] ,				__lowerCamelCase							:      StableDiffusionSafetyChecker ,				__lowerCamelCase							:      CLIPImageProcessor ,				__lowerCamelCase							:      bool = True ,				):


             '''simple docstring'''



             super().__init__()
             if hasattr(scheduler.config ,				"steps_offset"	) and scheduler.config.steps_offset != 1:
                   lowerCamelCase__		:    List[str]   =  (
                       f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
                       f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
                       "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
                       " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
                       " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
                       " file"
                   )
                   deprecate("steps_offset!=1" ,				"1.0.0" ,				__lowerCamelCase ,				standard_warn=__lowerCamelCase	)
                   lowerCamelCase__		:    List[str]   =  dict(scheduler.config	)
                   lowerCamelCase__		:    Optional[Any]   =  1
                   lowerCamelCase__		:    Union[str, Any]   =  FrozenDict(__lowerCamelCase	)

             self.register_modules(
                 vae=__lowerCamelCase ,				text_encoder=__lowerCamelCase ,				tokenizer=__lowerCamelCase ,				unet=__lowerCamelCase ,				scheduler=__lowerCamelCase ,				safety_checker=__lowerCamelCase ,				feature_extractor=__lowerCamelCase ,				)
             self.register_to_config(requires_safety_checker=__lowerCamelCase	)





       @property
       def 						lowerCAmelCase					(       self							:      List[Any]	):


             '''simple docstring'''



             return {k: getattr(self ,				__lowerCamelCase	) for k in self.config.keys() if not k.startswith("_"	)}





       def 						lowerCAmelCase					(       self							:      List[Any] ,				__lowerCamelCase							:      Optional[Union[str, int]] = "auto"	):


             '''simple docstring'''



             if slice_size == "auto":
                   # half the attention head size is usually a good trade-off between
                   # speed and memory
                   lowerCamelCase__		:    Tuple   =  self.unet.config.attention_head_dim // 2
             self.unet.set_attention_slice(__lowerCamelCase	)





       def 						lowerCAmelCase					(       self							:      Optional[Any]	):


             '''simple docstring'''



             self.enable_attention_slicing(__lowerCamelCase	)





       @torch.no_grad()
       def 						lowerCAmelCase					(       self							:      Any ,				__lowerCamelCase							:      Union[str, List[str]] ,				__lowerCamelCase							:      Union[torch.FloatTensor, PIL.Image.Image] ,				__lowerCamelCase							:      Union[torch.FloatTensor, PIL.Image.Image] ,				__lowerCamelCase							:      float = 0.8 ,				__lowerCamelCase							:      Optional[int] = 50 ,				__lowerCamelCase							:      Optional[float] = 7.5 ,				__lowerCamelCase							:      Optional[Union[str, List[str]]] = None ,				__lowerCamelCase							:      Optional[int] = 1 ,				__lowerCamelCase							:      Optional[float] = 0.0 ,				__lowerCamelCase							:      Optional[torch.Generator] = None ,				__lowerCamelCase							:      Optional[str] = "pil" ,				__lowerCamelCase							:      bool = True ,				__lowerCamelCase							:      Optional[Callable[[int, int, torch.FloatTensor], None]] = None ,				__lowerCamelCase							:      int = 1 ,				):


             '''simple docstring'''



             return StableDiffusionInpaintPipelineLegacy(**self.components	)(
                 prompt=__lowerCamelCase ,				image=__lowerCamelCase ,				mask_image=__lowerCamelCase ,				strength=__lowerCamelCase ,				num_inference_steps=__lowerCamelCase ,				guidance_scale=__lowerCamelCase ,				negative_prompt=__lowerCamelCase ,				num_images_per_prompt=__lowerCamelCase ,				eta=__lowerCamelCase ,				generator=__lowerCamelCase ,				output_type=__lowerCamelCase ,				return_dict=__lowerCamelCase ,				callback=__lowerCamelCase ,				)





       @torch.no_grad()
       def 						lowerCAmelCase					(       self							:      Optional[int] ,				__lowerCamelCase							:      Union[str, List[str]] ,				__lowerCamelCase							:      Union[torch.FloatTensor, PIL.Image.Image] ,				__lowerCamelCase							:      float = 0.8 ,				__lowerCamelCase							:      Optional[int] = 50 ,				__lowerCamelCase							:      Optional[float] = 7.5 ,				__lowerCamelCase							:      Optional[Union[str, List[str]]] = None ,				__lowerCamelCase							:      Optional[int] = 1 ,				__lowerCamelCase							:      Optional[float] = 0.0 ,				__lowerCamelCase							:      Optional[torch.Generator] = None ,				__lowerCamelCase							:      Optional[str] = "pil" ,				__lowerCamelCase							:      bool = True ,				__lowerCamelCase							:      Optional[Callable[[int, int, torch.FloatTensor], None]] = None ,				__lowerCamelCase							:      int = 1 ,				**__lowerCamelCase							:      List[str] ,				):


             '''simple docstring'''



             return StableDiffusionImgaImgPipeline(**self.components	)(
                 prompt=__lowerCamelCase ,				image=__lowerCamelCase ,				strength=__lowerCamelCase ,				num_inference_steps=__lowerCamelCase ,				guidance_scale=__lowerCamelCase ,				negative_prompt=__lowerCamelCase ,				num_images_per_prompt=__lowerCamelCase ,				eta=__lowerCamelCase ,				generator=__lowerCamelCase ,				output_type=__lowerCamelCase ,				return_dict=__lowerCamelCase ,				callback=__lowerCamelCase ,				callback_steps=__lowerCamelCase ,				)





       @torch.no_grad()
       def 						lowerCAmelCase					(       self							:      List[Any] ,				__lowerCamelCase							:      Union[str, List[str]] ,				__lowerCamelCase							:      int = 512 ,				__lowerCamelCase							:      int = 512 ,				__lowerCamelCase							:      int = 50 ,				__lowerCamelCase							:      float = 7.5 ,				__lowerCamelCase							:      Optional[Union[str, List[str]]] = None ,				__lowerCamelCase							:      Optional[int] = 1 ,				__lowerCamelCase							:      float = 0.0 ,				__lowerCamelCase							:      Optional[torch.Generator] = None ,				__lowerCamelCase							:      Optional[torch.FloatTensor] = None ,				__lowerCamelCase							:      Optional[str] = "pil" ,				__lowerCamelCase							:      bool = True ,				__lowerCamelCase							:      Optional[Callable[[int, int, torch.FloatTensor], None]] = None ,				__lowerCamelCase							:      int = 1 ,				):


             '''simple docstring'''



             return StableDiffusionPipeline(**self.components	)(
                 prompt=__lowerCamelCase ,				height=__lowerCamelCase ,				width=__lowerCamelCase ,				num_inference_steps=__lowerCamelCase ,				guidance_scale=__lowerCamelCase ,				negative_prompt=__lowerCamelCase ,				num_images_per_prompt=__lowerCamelCase ,				eta=__lowerCamelCase ,				generator=__lowerCamelCase ,				latents=__lowerCamelCase ,				output_type=__lowerCamelCase ,				return_dict=__lowerCamelCase ,				callback=__lowerCamelCase ,				callback_steps=__lowerCamelCase ,				)


