






'''simple docstring'''





import unittest

from transformers import AlbertConfig, is_torch_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
 import torch

 from transformers import (
     MODEL_FOR_PRETRAINING_MAPPING,
     AlbertForMaskedLM,
     AlbertForMultipleChoice,
     AlbertForPreTraining,
     AlbertForQuestionAnswering,
     AlbertForSequenceClassification,
     AlbertForTokenClassification,
     AlbertModel,
 )
 from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST
class 				lowercase       :


    '''simple docstring'''

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

     '''simple docstring'''




     lowerCamelCase__  =     parent
     lowerCamelCase__  =     batch_size
     lowerCamelCase__  =     seq_length
     lowerCamelCase__  =     is_training
     lowerCamelCase__  =     use_input_mask
     lowerCamelCase__  =     use_token_type_ids
     lowerCamelCase__  =     use_labels
     lowerCamelCase__  =     vocab_size
     lowerCamelCase__  =     embedding_size
     lowerCamelCase__  =     hidden_size
     lowerCamelCase__  =     num_hidden_layers
     lowerCamelCase__  =     num_hidden_groups
     lowerCamelCase__  =     num_attention_heads
     lowerCamelCase__  =     intermediate_size
     lowerCamelCase__  =     hidden_act
     lowerCamelCase__  =     hidden_dropout_prob
     lowerCamelCase__  =     attention_probs_dropout_prob
     lowerCamelCase__  =     max_position_embeddings
     lowerCamelCase__  =     type_vocab_size
     lowerCamelCase__  =     type_sequence_label_size
     lowerCamelCase__  =     initializer_range
     lowerCamelCase__  =     num_labels
     lowerCamelCase__  =     num_choices
     lowerCamelCase__  =     scope

    def    a__				(					self     :     Union[str, Any]     )							->							Optional[Any]:

     '''simple docstring'''




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

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

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

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

     lowerCamelCase__  =     self.get_config()

     return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels

    def    a__				(					self     :     List[str]     )							->							Any:

     '''simple docstring'''




     return AlbertConfig(
         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				,     initializer_range=self.initializer_range				,     num_hidden_groups=self.num_hidden_groups				,     )

    def    a__				(					self     :     Any				,     __lowerCamelCase     :     Optional[int]				,     __lowerCamelCase     :     int				,     __lowerCamelCase     :     Dict				,     __lowerCamelCase     :     Union[str, Any]				,     __lowerCamelCase     :     Optional[Any]				,     __lowerCamelCase     :     Union[str, Any]				,     __lowerCamelCase     :     Tuple     )							->							List[Any]:

     '''simple docstring'''




     lowerCamelCase__  =     AlbertModel(config=_lowercase     )
     model.to(_lowercase     )
     model.eval()
     lowerCamelCase__  =     model(_lowercase				,     attention_mask=_lowercase				,     token_type_ids=_lowercase     )
     lowerCamelCase__  =     model(_lowercase				,     token_type_ids=_lowercase     )
     lowerCamelCase__  =     model(_lowercase     )
     self.parent.assertEqual(result.last_hidden_state.shape				,     (self.batch_size, self.seq_length, self.hidden_size)     )
     self.parent.assertEqual(result.pooler_output.shape				,     (self.batch_size, self.hidden_size)     )

    def    a__				(					self     :     List[Any]				,     __lowerCamelCase     :     Union[str, Any]				,     __lowerCamelCase     :     List[str]				,     __lowerCamelCase     :     Optional[Any]				,     __lowerCamelCase     :     str				,     __lowerCamelCase     :     List[str]				,     __lowerCamelCase     :     Tuple				,     __lowerCamelCase     :     List[str]     )							->							Dict:

     '''simple docstring'''




     lowerCamelCase__  =     AlbertForPreTraining(config=_lowercase     )
     model.to(_lowercase     )
     model.eval()
     lowerCamelCase__  =     model(
         _lowercase				,     attention_mask=_lowercase				,     token_type_ids=_lowercase				,     labels=_lowercase				,     sentence_order_label=_lowercase				,     )
     self.parent.assertEqual(result.prediction_logits.shape				,     (self.batch_size, self.seq_length, self.vocab_size)     )
     self.parent.assertEqual(result.sop_logits.shape				,     (self.batch_size, config.num_labels)     )

    def    a__				(					self     :     Dict				,     __lowerCamelCase     :     List[str]				,     __lowerCamelCase     :     Any				,     __lowerCamelCase     :     Any				,     __lowerCamelCase     :     Tuple				,     __lowerCamelCase     :     Optional[Any]				,     __lowerCamelCase     :     Union[str, Any]				,     __lowerCamelCase     :     Dict     )							->							Tuple:

     '''simple docstring'''




     lowerCamelCase__  =     AlbertForMaskedLM(config=_lowercase     )
     model.to(_lowercase     )
     model.eval()
     lowerCamelCase__  =     model(_lowercase				,     attention_mask=_lowercase				,     token_type_ids=_lowercase				,     labels=_lowercase     )
     self.parent.assertEqual(result.logits.shape				,     (self.batch_size, self.seq_length, self.vocab_size)     )

    def    a__				(					self     :     int				,     __lowerCamelCase     :     List[Any]				,     __lowerCamelCase     :     List[str]				,     __lowerCamelCase     :     str				,     __lowerCamelCase     :     str				,     __lowerCamelCase     :     Dict				,     __lowerCamelCase     :     Dict				,     __lowerCamelCase     :     List[str]     )							->							Optional[int]:

     '''simple docstring'''




     lowerCamelCase__  =     AlbertForQuestionAnswering(config=_lowercase     )
     model.to(_lowercase     )
     model.eval()
     lowerCamelCase__  =     model(
         _lowercase				,     attention_mask=_lowercase				,     token_type_ids=_lowercase				,     start_positions=_lowercase				,     end_positions=_lowercase				,     )
     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    a__				(					self     :     Optional[int]				,     __lowerCamelCase     :     List[str]				,     __lowerCamelCase     :     List[str]				,     __lowerCamelCase     :     str				,     __lowerCamelCase     :     List[Any]				,     __lowerCamelCase     :     int				,     __lowerCamelCase     :     int				,     __lowerCamelCase     :     Tuple     )							->							Optional[Any]:

     '''simple docstring'''




     lowerCamelCase__  =     self.num_labels
     lowerCamelCase__  =     AlbertForSequenceClassification(_lowercase     )
     model.to(_lowercase     )
     model.eval()
     lowerCamelCase__  =     model(_lowercase				,     attention_mask=_lowercase				,     token_type_ids=_lowercase				,     labels=_lowercase     )
     self.parent.assertEqual(result.logits.shape				,     (self.batch_size, self.num_labels)     )

    def    a__				(					self     :     List[str]				,     __lowerCamelCase     :     Tuple				,     __lowerCamelCase     :     int				,     __lowerCamelCase     :     Dict				,     __lowerCamelCase     :     Optional[Any]				,     __lowerCamelCase     :     Optional[Any]				,     __lowerCamelCase     :     str				,     __lowerCamelCase     :     List[str]     )							->							str:

     '''simple docstring'''




     lowerCamelCase__  =     self.num_labels
     lowerCamelCase__  =     AlbertForTokenClassification(config=_lowercase     )
     model.to(_lowercase     )
     model.eval()
     lowerCamelCase__  =     model(_lowercase				,     attention_mask=_lowercase				,     token_type_ids=_lowercase				,     labels=_lowercase     )
     self.parent.assertEqual(result.logits.shape				,     (self.batch_size, self.seq_length, self.num_labels)     )

    def    a__				(					self     :     Tuple				,     __lowerCamelCase     :     str				,     __lowerCamelCase     :     int				,     __lowerCamelCase     :     Dict				,     __lowerCamelCase     :     List[Any]				,     __lowerCamelCase     :     List[Any]				,     __lowerCamelCase     :     str				,     __lowerCamelCase     :     List[str]     )							->							Union[str, Any]:

     '''simple docstring'''




     lowerCamelCase__  =     self.num_choices
     lowerCamelCase__  =     AlbertForMultipleChoice(config=_lowercase     )
     model.to(_lowercase     )
     model.eval()
     lowerCamelCase__  =     input_ids.unsqueeze(1     ).expand(-1				,     self.num_choices				,     -1     ).contiguous()
     lowerCamelCase__  =     token_type_ids.unsqueeze(1     ).expand(-1				,     self.num_choices				,     -1     ).contiguous()
     lowerCamelCase__  =     input_mask.unsqueeze(1     ).expand(-1				,     self.num_choices				,     -1     ).contiguous()
     lowerCamelCase__  =     model(
         _lowercase				,     attention_mask=_lowercase				,     token_type_ids=_lowercase				,     labels=_lowercase				,     )
     self.parent.assertEqual(result.logits.shape				,     (self.batch_size, self.num_choices)     )




    def    a__				(					self     :     Dict     )							->							List[str]:

     '''simple docstring'''




     lowerCamelCase__  =     self.prepare_config_and_inputs()
     (
         lowerCamelCase__      
     )  =     config_and_inputs
     lowerCamelCase__  =     {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': input_mask}
     return config, inputs_dict


@require_torch
class 				lowercase       (							UpperCAmelCase_ ,       UpperCAmelCase_ ,       unittest.TestCase      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							(
        (
            AlbertModel,
            AlbertForPreTraining,
            AlbertForMaskedLM,
            AlbertForMultipleChoice,
            AlbertForSequenceClassification,
            AlbertForTokenClassification,
            AlbertForQuestionAnswering,
        )
        if is_torch_available()
        else ()
    )
    lowerCAmelCase__      				=							(
        {
            'feature-extraction': AlbertModel,
            'fill-mask': AlbertForMaskedLM,
            'question-answering': AlbertForQuestionAnswering,
            'text-classification': AlbertForSequenceClassification,
            'token-classification': AlbertForTokenClassification,
            'zero-shot': AlbertForSequenceClassification,
        }
        if is_torch_available()
        else {}
    )
    lowerCAmelCase__      				=							True

    def    a__				(					self     :     Tuple				,     __lowerCamelCase     :     Dict				,     __lowerCamelCase     :     List[str]				,     __lowerCamelCase     :     Optional[Any]=False     )							->							str:

     '''simple docstring'''




     lowerCamelCase__  =     super()._prepare_for_class(_lowercase				,     _lowercase				,     return_labels=_lowercase     )

     if return_labels:
      if model_class in get_values(_lowercase     ):
       lowerCamelCase__  =     torch.zeros(
           (self.model_tester.batch_size, self.model_tester.seq_length)				,     dtype=torch.long				,     device=_lowercase     )
       lowerCamelCase__  =     torch.zeros(
           self.model_tester.batch_size				,     dtype=torch.long				,     device=_lowercase     )
     return inputs_dict

    def    a__				(					self     :     Optional[Any]     )							->							Dict:

     '''simple docstring'''




     lowerCamelCase__  =     AlbertModelTester(self     )
     lowerCamelCase__  =     ConfigTester(self				,     config_class=_lowercase				,     hidden_size=37     )

    def    a__				(					self     :     Dict     )							->							Tuple:

     '''simple docstring'''




     self.config_tester.run_common_tests()

    def    a__				(					self     :     Union[str, Any]     )							->							Dict:

     '''simple docstring'''




     lowerCamelCase__  =     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*_lowercase     )

    def    a__				(					self     :     str     )							->							Optional[Any]:

     '''simple docstring'''




     lowerCamelCase__  =     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_pretraining(*_lowercase     )

    def    a__				(					self     :     List[Any]     )							->							Any:

     '''simple docstring'''




     lowerCamelCase__  =     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_masked_lm(*_lowercase     )

    def    a__				(					self     :     Optional[int]     )							->							Any:

     '''simple docstring'''




     lowerCamelCase__  =     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_multiple_choice(*_lowercase     )

    def    a__				(					self     :     Union[str, Any]     )							->							Dict:

     '''simple docstring'''




     lowerCamelCase__  =     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_question_answering(*_lowercase     )

    def    a__				(					self     :     str     )							->							str:

     '''simple docstring'''




     lowerCamelCase__  =     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_sequence_classification(*_lowercase     )

    def    a__				(					self     :     List[Any]     )							->							Union[str, Any]:

     '''simple docstring'''




     lowerCamelCase__  =     self.model_tester.prepare_config_and_inputs()
     for type in ["absolute", "relative_key", "relative_key_query"]:
      lowerCamelCase__  =     type
      self.model_tester.create_and_check_model(*_lowercase     )




    @slow
    def    a__				(					self     :     List[Any]     )							->							Union[str, Any]:

     '''simple docstring'''




     for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
      lowerCamelCase__  =     AlbertModel.from_pretrained(_lowercase     )
      self.assertIsNotNone(_lowercase     )


@require_torch
class 				lowercase       (							unittest.TestCase      ):


    '''simple docstring'''

    @slow
    def    a__				(					self     :     List[str]     )							->							Any:

     '''simple docstring'''




     lowerCamelCase__  =     AlbertModel.from_pretrained("albert-base-v2"     )
     lowerCamelCase__  =     torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]     )
     lowerCamelCase__  =     torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]     )
     with torch.no_grad():
      lowerCamelCase__  =     model(_lowercase				,     attention_mask=_lowercase     )[0]
     lowerCamelCase__  =     torch.Size((1, 11, 768)     )
     self.assertEqual(output.shape				,     _lowercase     )
     lowerCamelCase__  =     torch.tensor(
         [[[-0.6_5_1_3, 1.5_0_3_5, -0.2_7_6_6], [-0.6_5_1_5, 1.5_0_4_6, -0.2_7_8_0], [-0.6_5_1_2, 1.5_0_4_9, -0.2_7_8_4]]]     )

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









'''simple docstring'''





import gc
import random
import tempfile
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMInverseScheduler,
    DDIMScheduler,
    DPMSolverMultistepInverseScheduler,
    DPMSolverMultistepScheduler,
    StableDiffusionDiffEditPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import load_image, slow
from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()
class 				lowercase       (							_lowerCamelCase ,       _lowerCamelCase ,       unittest.TestCase      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							StableDiffusionDiffEditPipeline
    lowerCAmelCase__      				=							TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"height", "width", "image"} | {"image_latents"}
    lowerCAmelCase__      				=							TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {"image"} | {"image_latents"}
    lowerCAmelCase__      				=							frozenset(
        []      )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
    lowerCAmelCase__      				=							frozenset([]      )

    def    a__				(					self     :     int     )							->							Dict:

     '''simple docstring'''




     torch.manual_seed(0     )
     lowerCamelCase__  =     UNetaDConditionModel(
         block_out_channels=(32, 64)				,     layers_per_block=2				,     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=__lowerCamelCase				,     )
     lowerCamelCase__  =     DDIMScheduler(
         beta_start=0.0_0_0_8_5				,     beta_end=0.0_1_2				,     beta_schedule="scaled_linear"				,     clip_sample=__lowerCamelCase				,     set_alpha_to_one=__lowerCamelCase				,     )
     lowerCamelCase__  =     DDIMInverseScheduler(
         beta_start=0.0_0_0_8_5				,     beta_end=0.0_1_2				,     beta_schedule="scaled_linear"				,     clip_sample=__lowerCamelCase				,     set_alpha_to_zero=__lowerCamelCase				,     )
     torch.manual_seed(0     )
     lowerCamelCase__  =     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__  =     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=1000				,     hidden_act="gelu"				,     projection_dim=512				,     )
     lowerCamelCase__  =     CLIPTextModel(__lowerCamelCase     )
     lowerCamelCase__  =     CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"     )

     lowerCamelCase__  =     {
         "unet": unet,
         "scheduler": scheduler,
         "inverse_scheduler": inverse_scheduler,
         "vae": vae,
         "text_encoder": text_encoder,
         "tokenizer": tokenizer,
         "safety_checker": None,
         "feature_extractor": None,
     }

     return components

    def    a__				(					self     :     List[Any]				,     __lowerCamelCase     :     Optional[Any]				,     __lowerCamelCase     :     Any=0     )							->							Tuple:

     '''simple docstring'''




     lowerCamelCase__  =     floats_tensor((1, 16, 16)				,     rng=random.Random(__lowerCamelCase     )     ).to(__lowerCamelCase     )
     lowerCamelCase__  =     floats_tensor((1, 2, 4, 16, 16)				,     rng=random.Random(__lowerCamelCase     )     ).to(__lowerCamelCase     )
     if str(__lowerCamelCase     ).startswith("mps"     ):
      lowerCamelCase__  =     torch.manual_seed(__lowerCamelCase     )
     else:
      lowerCamelCase__  =     torch.Generator(device=__lowerCamelCase     ).manual_seed(__lowerCamelCase     )
     lowerCamelCase__  =     {
         "prompt": "a dog and a newt",
         "mask_image": mask,
         "image_latents": latents,
         "generator": generator,
         "num_inference_steps": 2,
         "inpaint_strength": 1.0,
         "guidance_scale": 6.0,
         "output_type": "numpy",
     }

     return inputs

    def    a__				(					self     :     str				,     __lowerCamelCase     :     Optional[Any]				,     __lowerCamelCase     :     Optional[int]=0     )							->							Optional[Any]:

     '''simple docstring'''




     lowerCamelCase__  =     floats_tensor((1, 3, 32, 32)				,     rng=random.Random(__lowerCamelCase     )     ).to(__lowerCamelCase     )
     lowerCamelCase__  =     image.cpu().permute(0				,     2				,     3				,     1     )[0]
     lowerCamelCase__  =     Image.fromarray(np.uinta(__lowerCamelCase     )     ).convert("RGB"     )
     if str(__lowerCamelCase     ).startswith("mps"     ):
      lowerCamelCase__  =     torch.manual_seed(__lowerCamelCase     )
     else:
      lowerCamelCase__  =     torch.Generator(device=__lowerCamelCase     ).manual_seed(__lowerCamelCase     )
     lowerCamelCase__  =     {
         "image": image,
         "source_prompt": "a cat and a frog",
         "target_prompt": "a dog and a newt",
         "generator": generator,
         "num_inference_steps": 2,
         "num_maps_per_mask": 2,
         "mask_encode_strength": 1.0,
         "guidance_scale": 6.0,
         "output_type": "numpy",
     }

     return inputs

    def    a__				(					self     :     Optional[int]				,     __lowerCamelCase     :     Optional[int]				,     __lowerCamelCase     :     List[str]=0     )							->							List[Any]:

     '''simple docstring'''




     lowerCamelCase__  =     floats_tensor((1, 3, 32, 32)				,     rng=random.Random(__lowerCamelCase     )     ).to(__lowerCamelCase     )
     lowerCamelCase__  =     image.cpu().permute(0				,     2				,     3				,     1     )[0]
     lowerCamelCase__  =     Image.fromarray(np.uinta(__lowerCamelCase     )     ).convert("RGB"     )
     if str(__lowerCamelCase     ).startswith("mps"     ):
      lowerCamelCase__  =     torch.manual_seed(__lowerCamelCase     )
     else:
      lowerCamelCase__  =     torch.Generator(device=__lowerCamelCase     ).manual_seed(__lowerCamelCase     )
     lowerCamelCase__  =     {
         "image": image,
         "prompt": "a cat and a frog",
         "generator": generator,
         "num_inference_steps": 2,
         "inpaint_strength": 1.0,
         "guidance_scale": 6.0,
         "decode_latents": True,
         "output_type": "numpy",
     }
     return inputs

    def    a__				(					self     :     Tuple     )							->							str:

     '''simple docstring'''




     if not hasattr(self.pipeline_class				,     "_optional_components"     ):
      return

     lowerCamelCase__  =     self.get_dummy_components()
     lowerCamelCase__  =     self.pipeline_class(**__lowerCamelCase     )
     pipe.to(__lowerCamelCase     )
     pipe.set_progress_bar_config(disable=__lowerCamelCase     )

     # set all optional components to None and update pipeline config accordingly
     for optional_component in pipe._optional_components:
      setattr(__lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase     )
     pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components}     )

     lowerCamelCase__  =     self.get_dummy_inputs(__lowerCamelCase     )
     lowerCamelCase__  =     pipe(**__lowerCamelCase     )[0]

     with tempfile.TemporaryDirectory() as tmpdir:
      pipe.save_pretrained(__lowerCamelCase     )
      lowerCamelCase__  =     self.pipeline_class.from_pretrained(__lowerCamelCase     )
      pipe_loaded.to(__lowerCamelCase     )
      pipe_loaded.set_progress_bar_config(disable=__lowerCamelCase     )

     for optional_component in pipe._optional_components:
      self.assertTrue(
          getattr(__lowerCamelCase				,     __lowerCamelCase     ) is None				,     f'''`{optional_component}` did not stay set to None after loading.'''				,     )

     lowerCamelCase__  =     self.get_dummy_inputs(__lowerCamelCase     )
     lowerCamelCase__  =     pipe_loaded(**__lowerCamelCase     )[0]

     lowerCamelCase__  =     np.abs(output - output_loaded     ).max()
     self.assertLess(__lowerCamelCase				,     1E-4     )

    def    a__				(					self     :     List[str]     )							->							List[Any]:

     '''simple docstring'''




     lowerCamelCase__  =     "cpu"

     lowerCamelCase__  =     self.get_dummy_components()
     lowerCamelCase__  =     self.pipeline_class(**__lowerCamelCase     )
     pipe.to(__lowerCamelCase     )
     pipe.set_progress_bar_config(disable=__lowerCamelCase     )

     lowerCamelCase__  =     self.get_dummy_mask_inputs(__lowerCamelCase     )
     lowerCamelCase__  =     pipe.generate_mask(**__lowerCamelCase     )
     lowerCamelCase__  =     mask[0, -3:, -3:]

     self.assertEqual(mask.shape				,     (1, 16, 16)     )
     lowerCamelCase__  =     np.array([0] * 9     )
     lowerCamelCase__  =     np.abs(mask_slice.flatten() - expected_slice     ).max()
     self.assertLessEqual(__lowerCamelCase				,     1E-3     )
     self.assertEqual(mask[0, -3, -4]				,     0     )

    def    a__				(					self     :     List[str]     )							->							List[str]:

     '''simple docstring'''




     lowerCamelCase__  =     "cpu"

     lowerCamelCase__  =     self.get_dummy_components()
     lowerCamelCase__  =     self.pipeline_class(**__lowerCamelCase     )
     pipe.to(__lowerCamelCase     )
     pipe.set_progress_bar_config(disable=__lowerCamelCase     )

     lowerCamelCase__  =     self.get_dummy_inversion_inputs(__lowerCamelCase     )
     lowerCamelCase__  =     pipe.invert(**__lowerCamelCase     ).images
     lowerCamelCase__  =     image[0, -1, -3:, -3:]

     self.assertEqual(image.shape				,     (2, 32, 32, 3)     )
     lowerCamelCase__  =     np.array(
         [0.5_1_5_0, 0.5_1_3_4, 0.5_0_4_3, 0.5_3_7_6, 0.4_6_9_4, 0.5_1_0_5_0, 0.5_0_1_5, 0.4_4_0_7, 0.4_7_9_9]				,     )
     lowerCamelCase__  =     np.abs(image_slice.flatten() - expected_slice     ).max()
     self.assertLessEqual(__lowerCamelCase				,     1E-3     )

    def    a__				(					self     :     Tuple     )							->							Tuple:

     '''simple docstring'''




     super().test_inference_batch_single_identical(expected_max_diff=5E-3     )




    def    a__				(					self     :     Union[str, Any]     )							->							Dict:

     '''simple docstring'''




     lowerCamelCase__  =     "cpu"

     lowerCamelCase__  =     self.get_dummy_components()

     lowerCamelCase__  =     {"beta_start": 0.0_0_0_8_5, "beta_end": 0.0_1_2, "beta_schedule": "scaled_linear"}
     lowerCamelCase__  =     DPMSolverMultistepScheduler(**__lowerCamelCase     )
     lowerCamelCase__  =     DPMSolverMultistepInverseScheduler(**__lowerCamelCase     )

     lowerCamelCase__  =     self.pipeline_class(**__lowerCamelCase     )
     pipe.to(__lowerCamelCase     )
     pipe.set_progress_bar_config(disable=__lowerCamelCase     )

     lowerCamelCase__  =     self.get_dummy_inversion_inputs(__lowerCamelCase     )
     lowerCamelCase__  =     pipe.invert(**__lowerCamelCase     ).images
     lowerCamelCase__  =     image[0, -1, -3:, -3:]

     self.assertEqual(image.shape				,     (2, 32, 32, 3)     )
     lowerCamelCase__  =     np.array(
         [0.5_1_5_0, 0.5_1_3_4, 0.5_0_4_3, 0.5_3_7_6, 0.4_6_9_4, 0.5_1_0_5_0, 0.5_0_1_5, 0.4_4_0_7, 0.4_7_9_9]				,     )
     lowerCamelCase__  =     np.abs(image_slice.flatten() - expected_slice     ).max()
     self.assertLessEqual(__lowerCamelCase				,     1E-3     )
@require_torch_gpu
@slow
class 				lowercase       (							unittest.TestCase      ):


    '''simple docstring'''

    def    a__				(					self     :     Optional[int]     )							->							int:

     '''simple docstring'''




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

    @classmethod
    def    a__				(					cls     :     int     )							->							List[Any]:

     '''simple docstring'''




     lowerCamelCase__  =     load_image(
         "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png"     )

     lowerCamelCase__  =     raw_image.convert("RGB"     ).resize((768, 768)     )

     lowerCamelCase__  =     raw_image

    def    a__				(					self     :     Optional[Any]     )							->							str:

     '''simple docstring'''




     lowerCamelCase__  =     torch.manual_seed(0     )

     lowerCamelCase__  =     StableDiffusionDiffEditPipeline.from_pretrained(
         "stabilityai/stable-diffusion-2-1"				,     safety_checker=__lowerCamelCase				,     torch_dtype=torch.floataa     )
     lowerCamelCase__  =     DDIMScheduler.from_config(pipe.scheduler.config     )
     lowerCamelCase__  =     DDIMInverseScheduler.from_config(pipe.scheduler.config     )
     pipe.enable_model_cpu_offload()
     pipe.set_progress_bar_config(disable=__lowerCamelCase     )

     lowerCamelCase__  =     "a bowl of fruit"
     lowerCamelCase__  =     "a bowl of pears"

     lowerCamelCase__  =     pipe.generate_mask(
         image=self.raw_image				,     source_prompt=__lowerCamelCase				,     target_prompt=__lowerCamelCase				,     generator=__lowerCamelCase				,     )

     lowerCamelCase__  =     pipe.invert(
         prompt=__lowerCamelCase				,     image=self.raw_image				,     inpaint_strength=0.7				,     generator=__lowerCamelCase     ).latents

     lowerCamelCase__  =     pipe(
         prompt=__lowerCamelCase				,     mask_image=__lowerCamelCase				,     image_latents=__lowerCamelCase				,     generator=__lowerCamelCase				,     negative_prompt=__lowerCamelCase				,     inpaint_strength=0.7				,     output_type="numpy"				,     ).images[0]

     lowerCamelCase__  =     (
         np.array(
             load_image(
                 "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
                 "/diffedit/pears.png"     ).resize((768, 768)     )     )
         / 255
     )
     assert np.abs((expected_image - image).max()     ) < 5E-1




    def    a__				(					self     :     List[str]     )							->							Dict:

     '''simple docstring'''




     lowerCamelCase__  =     torch.manual_seed(0     )

     lowerCamelCase__  =     StableDiffusionDiffEditPipeline.from_pretrained(
         "stabilityai/stable-diffusion-2-1"				,     safety_checker=__lowerCamelCase				,     torch_dtype=torch.floataa     )
     lowerCamelCase__  =     DPMSolverMultistepScheduler.from_config(pipe.scheduler.config     )
     lowerCamelCase__  =     DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config     )
     pipe.enable_model_cpu_offload()
     pipe.set_progress_bar_config(disable=__lowerCamelCase     )

     lowerCamelCase__  =     "a bowl of fruit"
     lowerCamelCase__  =     "a bowl of pears"

     lowerCamelCase__  =     pipe.generate_mask(
         image=self.raw_image				,     source_prompt=__lowerCamelCase				,     target_prompt=__lowerCamelCase				,     generator=__lowerCamelCase				,     )

     lowerCamelCase__  =     pipe.invert(
         prompt=__lowerCamelCase				,     image=self.raw_image				,     inpaint_strength=0.7				,     generator=__lowerCamelCase				,     num_inference_steps=25				,     ).latents

     lowerCamelCase__  =     pipe(
         prompt=__lowerCamelCase				,     mask_image=__lowerCamelCase				,     image_latents=__lowerCamelCase				,     generator=__lowerCamelCase				,     negative_prompt=__lowerCamelCase				,     inpaint_strength=0.7				,     num_inference_steps=25				,     output_type="numpy"				,     ).images[0]

     lowerCamelCase__  =     (
         np.array(
             load_image(
                 "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
                 "/diffedit/pears.png"     ).resize((768, 768)     )     )
         / 255
     )
     assert np.abs((expected_image - image).max()     ) < 5E-1

