


from __future__ import annotations

import unittest

from transformers import MPNetConfig, 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.mpnet.modeling_tf_mpnet import (
        TFMPNetForMaskedLM,
        TFMPNetForMultipleChoice,
        TFMPNetForQuestionAnswering,
        TFMPNetForSequenceClassification,
        TFMPNetForTokenClassification,
        TFMPNetModel,
    )







class       _lowercase			:


       """simple docstring"""




       def __init__(       self							:      int ,				__lowerCamelCase							:      Optional[Any] ,				__lowerCamelCase							:      str=13 ,				__lowerCamelCase							:      str=7 ,				__lowerCamelCase							:      str=True ,				__lowerCamelCase							:      List[Any]=True ,				__lowerCamelCase							:      Dict=False ,				__lowerCamelCase							:      str=True ,				__lowerCamelCase							:      Any=99 ,				__lowerCamelCase							:      Optional[int]=64 ,				__lowerCamelCase							:      Any=2 ,				__lowerCamelCase							:      Dict=4 ,				__lowerCamelCase							:      List[Any]=64 ,				__lowerCamelCase							:      Tuple="gelu" ,				__lowerCamelCase							:      str=0.1 ,				__lowerCamelCase							:      List[Any]=0.1 ,				__lowerCamelCase							:      List[str]=512 ,				__lowerCamelCase							:      Optional[Any]=16 ,				__lowerCamelCase							:      Optional[Any]=2 ,				__lowerCamelCase							:      str=0.0_2 ,				__lowerCamelCase							:      Any=3 ,				__lowerCamelCase							:      int=4 ,				__lowerCamelCase							:      Union[str, Any]=None ,				):


             '''simple docstring'''



             lowerCamelCase__		:    Optional[Any]   =  parent
             lowerCamelCase__		:    Tuple   =  batch_size
             lowerCamelCase__		:    Union[str, Any]   =  seq_length
             lowerCamelCase__		:    Dict   =  is_training
             lowerCamelCase__		:    Optional[Any]   =  use_input_mask
             lowerCamelCase__		:    Union[str, Any]   =  use_token_type_ids
             lowerCamelCase__		:    List[Any]   =  use_labels
             lowerCamelCase__		:    Optional[int]   =  vocab_size
             lowerCamelCase__		:    Dict   =  hidden_size
             lowerCamelCase__		:    Optional[int]   =  num_hidden_layers
             lowerCamelCase__		:    Dict   =  num_attention_heads
             lowerCamelCase__		:    Optional[Any]   =  intermediate_size
             lowerCamelCase__		:    Dict   =  hidden_act
             lowerCamelCase__		:    str   =  hidden_dropout_prob
             lowerCamelCase__		:    int   =  attention_probs_dropout_prob
             lowerCamelCase__		:    Dict   =  max_position_embeddings
             lowerCamelCase__		:    List[str]   =  type_vocab_size
             lowerCamelCase__		:    List[str]   =  type_sequence_label_size
             lowerCamelCase__		:    Any   =  initializer_range
             lowerCamelCase__		:    int   =  num_labels
             lowerCamelCase__		:    str   =  num_choices
             lowerCamelCase__		:    Optional[Any]   =  scope





       def 						lowerCAmelCase					(       self							:      str	):


             '''simple docstring'''



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

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

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

             lowerCamelCase__		:    Dict   =  MPNetConfig(
                 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 ,				initializer_range=self.initializer_range ,				)
             return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels





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


             '''simple docstring'''



             lowerCamelCase__		:    Union[str, Any]   =  TFMPNetModel(config=__lowerCamelCase	)
             lowerCamelCase__		:    Tuple   =  {"input_ids": input_ids, "attention_mask": input_mask}
             lowerCamelCase__		:    str   =  model(__lowerCamelCase	)
             lowerCamelCase__		:    Dict   =  [input_ids, input_mask]
             lowerCamelCase__		:    Union[str, 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							:      int ,				__lowerCamelCase							:      Tuple ,				__lowerCamelCase							:      int ,				__lowerCamelCase							:      Any ,				__lowerCamelCase							:      str	):


             '''simple docstring'''



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





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


             '''simple docstring'''



             lowerCamelCase__		:    Dict   =  TFMPNetForQuestionAnswering(config=__lowerCamelCase	)
             lowerCamelCase__		:    Optional[Any]   =  {
                 "input_ids": input_ids,
                 "attention_mask": input_mask,
             }
             lowerCamelCase__		:    int   =  model(__lowerCamelCase	)
             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							:      Optional[int] ,				__lowerCamelCase							:      int ,				__lowerCamelCase							:      Union[str, Any] ,				__lowerCamelCase							:      Tuple ,				__lowerCamelCase							:      Dict ,				__lowerCamelCase							:      Tuple ,				__lowerCamelCase							:      Optional[Any]	):


             '''simple docstring'''



             lowerCamelCase__		:    Any   =  self.num_labels
             lowerCamelCase__		:    str   =  TFMPNetForSequenceClassification(__lowerCamelCase	)
             lowerCamelCase__		:    Dict   =  {"input_ids": input_ids, "attention_mask": input_mask}
             lowerCamelCase__		:    List[str]   =  model(__lowerCamelCase	)
             self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.num_labels)	)





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


             '''simple docstring'''



             lowerCamelCase__		:    List[str]   =  self.num_choices
             lowerCamelCase__		:    Optional[int]   =  TFMPNetForMultipleChoice(__lowerCamelCase	)
             lowerCamelCase__		:    List[Any]   =  tf.tile(tf.expand_dims(__lowerCamelCase ,				1	) ,				(1, self.num_choices, 1)	)
             lowerCamelCase__		:    Dict   =  tf.tile(tf.expand_dims(__lowerCamelCase ,				1	) ,				(1, self.num_choices, 1)	)
             lowerCamelCase__		:    List[Any]   =  {
                 "input_ids": multiple_choice_inputs_ids,
                 "attention_mask": multiple_choice_input_mask,
             }
             lowerCamelCase__		:    Any   =  model(__lowerCamelCase	)
             self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.num_choices)	)





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


             '''simple docstring'''



             lowerCamelCase__		:    int   =  self.num_labels
             lowerCamelCase__		:    Optional[Any]   =  TFMPNetForTokenClassification(__lowerCamelCase	)
             lowerCamelCase__		:    List[str]   =  {"input_ids": input_ids, "attention_mask": input_mask}
             lowerCamelCase__		:    Union[str, Any]   =  model(__lowerCamelCase	)
             self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.seq_length, self.num_labels)	)





       def 						lowerCAmelCase					(       self							:      Optional[Any]	):


             '''simple docstring'''



             lowerCamelCase__		:    Union[str, Any]   =  self.prepare_config_and_inputs()
             ((lowerCamelCase__)   ,       (lowerCamelCase__)   ,       (lowerCamelCase__)   ,       (lowerCamelCase__)   ,       (lowerCamelCase__)   ,       (lowerCamelCase__))		:    int   =  config_and_inputs
             lowerCamelCase__		:    Dict   =  {"input_ids": input_ids, "attention_mask": input_mask}
             return config, inputs_dict







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


       """simple docstring"""




       A__ 						=      (
           (
               TFMPNetForMaskedLM,
               TFMPNetForMultipleChoice,
               TFMPNetForQuestionAnswering,
               TFMPNetForSequenceClassification,
               TFMPNetForTokenClassification,
               TFMPNetModel,
           )
           if is_tf_available()
           else ()
       )
       A__ 						=      (
           {
               "feature-extraction": TFMPNetModel,
               "fill-mask": TFMPNetForMaskedLM,
               "question-answering": TFMPNetForQuestionAnswering,
               "text-classification": TFMPNetForSequenceClassification,
               "token-classification": TFMPNetForTokenClassification,
               "zero-shot": TFMPNetForSequenceClassification,
           }
           if is_tf_available()
           else {}
       )
       A__ 						=      False
       A__ 						=      False





       def 						lowerCAmelCase					(       self							:      str	):


             '''simple docstring'''



             lowerCamelCase__		:    Optional[Any]   =  TFMPNetModelTester(self	)
             lowerCamelCase__		:    Any   =  ConfigTester(self ,				config_class=__lowerCamelCase ,				hidden_size=37	)





       def 						lowerCAmelCase					(       self							:      Any	):


             '''simple docstring'''



             self.config_tester.run_common_tests()





       def 						lowerCAmelCase					(       self							:      Optional[Any]	):


             '''simple docstring'''



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





       def 						lowerCAmelCase					(       self							:      str	):


             '''simple docstring'''



             lowerCamelCase__		:    List[Any]   =  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_mpnet_for_masked_lm(*__lowerCamelCase	)





       def 						lowerCAmelCase					(       self							:      str	):


             '''simple docstring'''



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





       def 						lowerCAmelCase					(       self							:      Optional[int]	):


             '''simple docstring'''



             lowerCamelCase__		:    str   =  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_mpnet_for_sequence_classification(*__lowerCamelCase	)





       def 						lowerCAmelCase					(       self							:      int	):


             '''simple docstring'''



             lowerCamelCase__		:    List[Any]   =  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_mpnet_for_multiple_choice(*__lowerCamelCase	)





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


             '''simple docstring'''



             lowerCamelCase__		:    List[Any]   =  self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_mpnet_for_token_classification(*__lowerCamelCase	)





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


             '''simple docstring'''



             for model_name in ["microsoft/mpnet-base"]:
                   lowerCamelCase__		:    Optional[Any]   =  TFMPNetModel.from_pretrained(__lowerCamelCase	)
                   self.assertIsNotNone(__lowerCamelCase	)







@require_tf
class       _lowercase			(							unittest.TestCase):


       """simple docstring"""




       @slow
       def 						lowerCAmelCase					(       self							:      Any	):


             '''simple docstring'''



             lowerCamelCase__		:    Union[str, Any]   =  TFMPNetModel.from_pretrained("microsoft/mpnet-base"	)
             lowerCamelCase__		:    int   =  tf.constant([[0, 1, 2, 3, 4, 5]]	)
             lowerCamelCase__		:    Any   =  model(__lowerCamelCase	)[0]

             lowerCamelCase__		:    Optional[int]   =  [1, 6, 768]
             self.assertEqual(output.shape ,				__lowerCamelCase	)

             lowerCamelCase__		:    Union[str, Any]   =  tf.constant(
                 [
                     [
                         [-0.1_0_6_7_1_7_2, 0.0_8_2_1_6_4_7_3, 0.0_0_2_4_5_4_3],
                         [-0.0_3_4_6_5_8_7_9, 0.8_3_5_4_1_1_8, -0.0_3_2_5_2_2_8_8],
                         [-0.0_6_5_6_9_4_7_6, -0.1_2_4_2_4_1_1_1, -0.0_4_9_4_4_3_6],
                     ]
                 ]	)
             tf.debugging.assert_near(output[:, :3, :3] ,				__lowerCamelCase ,				atol=1E-4	)






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 ,				)


