




'''simple docstring'''



import inspect
import unittest

from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
      import torch

      from transformers import ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
      from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import AutoImageProcessor






class 							_a				:





       '''simple docstring'''






       def __init__(      self,							A,							A=13,							A=32,							A=3,							A=4,							A=[10, 20, 30, 40],							A=[2, 2, 3, 2],							A=True,							A=True,							A=37,							A="gelu",							A=10,							A=0.02,							A=["stage2", "stage3", "stage4"],							A=[2, 3, 4],							A=None,							):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      str    					=						parent
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						batch_size
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						image_size
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						num_channels
             SCREAMING_SNAKE_CASE   :      str    					=						num_stages
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						hidden_sizes
             SCREAMING_SNAKE_CASE   :      List[str]    					=						depths
             SCREAMING_SNAKE_CASE   :      Tuple    					=						is_training
             SCREAMING_SNAKE_CASE   :      Any    					=						use_labels
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						intermediate_size
             SCREAMING_SNAKE_CASE   :      int    					=						hidden_act
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						num_labels
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						initializer_range
             SCREAMING_SNAKE_CASE   :      int    					=						out_features
             SCREAMING_SNAKE_CASE   :      Any    					=						out_indices
             SCREAMING_SNAKE_CASE   :      Dict    					=						scope







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						None
             if self.use_labels:
                   SCREAMING_SNAKE_CASE   :      Optional[int]    					=						ids_tensor([self.batch_size],							self.num_labels  )

             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						self.get_config()

             return config, pixel_values, labels







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             return ConvNextVaConfig(
                 num_channels=self.num_channels,							hidden_sizes=self.hidden_sizes,							depths=self.depths,							num_stages=self.num_stages,							hidden_act=self.hidden_act,							is_decoder=A,							initializer_range=self.initializer_range,							out_features=self.out_features,							out_indices=self.out_indices,							num_labels=self.num_labels,							)







       def        UpperCamelCase_							(      self,							A,							A,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						ConvNextVaModel(config=A  )
             model.to(A  )
             model.eval()
             SCREAMING_SNAKE_CASE   :      str    					=						model(A  )
             # expected last hidden states: B, C, H // 32, W // 32
             self.parent.assertEqual(
                 result.last_hidden_state.shape,							(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32),							)







       def        UpperCamelCase_							(      self,							A,							A,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Dict    					=						ConvNextVaForImageClassification(A  )
             model.to(A  )
             model.eval()
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						model(A,							labels=A  )
             self.parent.assertEqual(result.logits.shape,							(self.batch_size, self.num_labels)  )







       def        UpperCamelCase_							(      self,							A,							A,							A  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      int    					=						ConvNextVaBackbone(config=A  )
             model.to(A  )
             model.eval()
             SCREAMING_SNAKE_CASE   :      int    					=						model(A  )

             # verify hidden states
             self.parent.assertEqual(len(result.feature_maps  ),							len(config.out_features  )  )
             self.parent.assertListEqual(list(result.feature_maps[0].shape  ),							[self.batch_size, self.hidden_sizes[1], 4, 4]  )

             # verify channels
             self.parent.assertEqual(len(model.channels  ),							len(config.out_features  )  )
             self.parent.assertListEqual(model.channels,							config.hidden_sizes[1:]  )

             # verify backbone works with out_features=None
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						None
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						ConvNextVaBackbone(config=A  )
             model.to(A  )
             model.eval()
             SCREAMING_SNAKE_CASE   :      List[str]    					=						model(A  )

             # verify feature maps
             self.parent.assertEqual(len(result.feature_maps  ),							1  )
             self.parent.assertListEqual(list(result.feature_maps[0].shape  ),							[self.batch_size, self.hidden_sizes[-1], 1, 1]  )

             # verify channels
             self.parent.assertEqual(len(model.channels  ),							1  )
             self.parent.assertListEqual(model.channels,							[config.hidden_sizes[-1]]  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      List[str]    					=						self.prepare_config_and_inputs()
             SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						config_and_inputs
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						{'pixel_values': pixel_values}
             return config, inputs_dict







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Dict    					=						self.prepare_config_and_inputs()
             SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      Dict    					=						config_and_inputs
             SCREAMING_SNAKE_CASE   :      List[str]    					=						{'pixel_values': pixel_values, 'labels': labels}
             return config, inputs_dict






@require_torch
class 							_a				(			SCREAMING_SNAKE_CASE ,      SCREAMING_SNAKE_CASE ,      unittest.TestCase ):





       '''simple docstring'''






       A						:				Any        =						(
           (
               ConvNextVaModel,
               ConvNextVaForImageClassification,
               ConvNextVaBackbone,
           )
           if is_torch_available()
           else ()
       )
       A						:				List[str]        =						(
           {'''feature-extraction''': ConvNextVaModel, '''image-classification''': ConvNextVaForImageClassification}
           if is_torch_available()
           else {}
       )

       A						:				Any        =						False
       A						:				Tuple        =						False
       A						:				Union[str, Any]        =						False
       A						:				Any        =						False
       A						:				List[Any]        =						False







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      int    					=						ConvNextVaModelTester(self  )
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						ConfigTester(self,							config_class=A,							has_text_modality=A,							hidden_size=37  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             self.create_and_test_config_common_properties()
             self.config_tester.create_and_test_config_to_json_string()
             self.config_tester.create_and_test_config_to_json_file()
             self.config_tester.create_and_test_config_from_and_save_pretrained()
             self.config_tester.create_and_test_config_with_num_labels()
             self.config_tester.check_config_can_be_init_without_params()
             self.config_tester.check_config_arguments_init()







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             return







       @unittest.skip(reason='ConvNextV2 does not use inputs_embeds'  )
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             pass







       @unittest.skip(reason='ConvNextV2 does not support input and output embeddings'  )
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             pass







       @unittest.skip(reason='ConvNextV2 does not use feedforward chunking'  )
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             pass







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             if not self.model_tester.is_training:
                   return

             for model_class in self.all_model_classes:
                   SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      Any    					=						self.model_tester.prepare_config_and_inputs_with_labels()
                   SCREAMING_SNAKE_CASE   :      Tuple    					=						True

                   if model_class.__name__ in [
                       *get_values(A  ),
                       *get_values(A  ),
                   ]:
                         continue

                   SCREAMING_SNAKE_CASE   :      Optional[int]    					=						model_class(A  )
                   model.to(A  )
                   model.train()
                   SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						self._prepare_for_class(A,							A,							return_labels=A  )
                   SCREAMING_SNAKE_CASE   :      int    					=						model(**A  ).loss
                   loss.backward()







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             if not self.model_tester.is_training:
                   return

             for model_class in self.all_model_classes:
                   SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      List[Any]    					=						self.model_tester.prepare_config_and_inputs_with_labels()
                   SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						False
                   SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						True

                   if (
                       model_class.__name__
                       in [*get_values(A  ), *get_values(A  )]
                       or not model_class.supports_gradient_checkpointing
                   ):
                         continue

                   SCREAMING_SNAKE_CASE   :      List[Any]    					=						model_class(A  )
                   model.to(A  )
                   model.gradient_checkpointing_enable()
                   model.train()
                   SCREAMING_SNAKE_CASE   :      List[Any]    					=						self._prepare_for_class(A,							A,							return_labels=A  )
                   SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						model(**A  ).loss
                   loss.backward()







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      str    					=						self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   SCREAMING_SNAKE_CASE   :      int    					=						model_class(A  )
                   SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						inspect.signature(model.forward  )
                   # signature.parameters is an OrderedDict => so arg_names order is deterministic
                   SCREAMING_SNAKE_CASE   :      Any    					=						[*signature.parameters.keys()]

                   SCREAMING_SNAKE_CASE   :      Optional[int]    					=						['pixel_values']
                   self.assertListEqual(arg_names[:1],							A  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      str    					=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*A  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             def check_hidden_states_output(A,							A,							A  ):
                   SCREAMING_SNAKE_CASE   :      Optional[int]    					=						model_class(A  )
                   model.to(A  )
                   model.eval()

                   with torch.no_grad():
                         SCREAMING_SNAKE_CASE   :      List[Any]    					=						model(**self._prepare_for_class(A,							A  )  )

                   SCREAMING_SNAKE_CASE   :      List[Any]    					=						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                   SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						self.model_tester.num_stages
                   self.assertEqual(len(A  ),							expected_num_stages + 1  )

                   # ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width)
                   self.assertListEqual(
                       list(hidden_states[0].shape[-2:]  ),							[self.model_tester.image_size // 4, self.model_tester.image_size // 4],							)

             SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                   SCREAMING_SNAKE_CASE   :      Any    					=						True
                   check_hidden_states_output(A,							A,							A  )

                   # check that output_hidden_states also work using config
                   del inputs_dict["output_hidden_states"]
                   SCREAMING_SNAKE_CASE   :      str    					=						True

                   check_hidden_states_output(A,							A,							A  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      List[str]    					=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*A  )







       @slow
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                   SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						ConvNextVaModel.from_pretrained(A  )
                   self.assertIsNotNone(A  )




def   lowercase__(			):

      """simple docstring"""






      SCREAMING_SNAKE_CASE   :      Tuple    					=						Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'    )
      return image






@require_torch
@require_vision
class 							_a				(			unittest.TestCase ):





       '''simple docstring'''






       @cached_property
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             return AutoImageProcessor.from_pretrained('facebook/convnextv2-tiny-1k-224'  ) if is_vision_available() else None







       @slow
       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						ConvNextVaForImageClassification.from_pretrained('facebook/convnextv2-tiny-1k-224'  ).to(A  )

             SCREAMING_SNAKE_CASE   :      int    					=						self.default_image_processor
             SCREAMING_SNAKE_CASE   :      Any    					=						prepare_img()
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						preprocessor(images=A,							return_tensors='pt'  ).to(A  )

             # forward pass
             with torch.no_grad():
                   SCREAMING_SNAKE_CASE   :      List[Any]    					=						model(**A  )

             # verify the logits
             SCREAMING_SNAKE_CASE   :      int    					=						torch.Size((1, 1_000)  )
             self.assertEqual(outputs.logits.shape,							A  )

             SCREAMING_SNAKE_CASE   :      str    					=						torch.tensor([0.99_96, 0.19_66, -0.43_86]  ).to(A  )
             self.assertTrue(torch.allclose(outputs.logits[0, :3],							A,							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 							_a				(			SCREAMING_SNAKE_CASE ,      SCREAMING_SNAKE_CASE ,      unittest.TestCase ):





       '''simple docstring'''






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







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             torch.manual_seed(0  )
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						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=A,							)
             SCREAMING_SNAKE_CASE   :      int    					=						DDIMScheduler(
                 beta_start=0.0_00_85,							beta_end=0.0_12,							beta_schedule='scaled_linear',							clip_sample=A,							set_alpha_to_one=A,							)
             SCREAMING_SNAKE_CASE   :      str    					=						DDIMInverseScheduler(
                 beta_start=0.0_00_85,							beta_end=0.0_12,							beta_schedule='scaled_linear',							clip_sample=A,							set_alpha_to_zero=A,							)
             torch.manual_seed(0  )
             SCREAMING_SNAKE_CASE   :      Dict    					=						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  )
             SCREAMING_SNAKE_CASE   :      Tuple    					=						CLIPTextConfig(
                 bos_token_id=0,							eos_token_id=2,							hidden_size=32,							intermediate_size=37,							layer_norm_eps=1E-05,							num_attention_heads=4,							num_hidden_layers=5,							pad_token_id=1,							vocab_size=1_000,							hidden_act='gelu',							projection_dim=512,							)
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						CLIPTextModel(A  )
             SCREAMING_SNAKE_CASE   :      str    					=						CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'  )

             SCREAMING_SNAKE_CASE   :      int    					=						{
                 '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        UpperCamelCase_							(      self,							A,							A=0  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						floats_tensor((1, 16, 16),							rng=random.Random(A  )  ).to(A  )
             SCREAMING_SNAKE_CASE   :      List[str]    					=						floats_tensor((1, 2, 4, 16, 16),							rng=random.Random(A  )  ).to(A  )
             if str(A  ).startswith('mps'  ):
                   SCREAMING_SNAKE_CASE   :      List[str]    					=						torch.manual_seed(A  )
             else:
                   SCREAMING_SNAKE_CASE   :      Tuple    					=						torch.Generator(device=A  ).manual_seed(A  )
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						{
                 '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        UpperCamelCase_							(      self,							A,							A=0  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      str    					=						floats_tensor((1, 3, 32, 32),							rng=random.Random(A  )  ).to(A  )
             SCREAMING_SNAKE_CASE   :      Any    					=						image.cpu().permute(0,							2,							3,							1  )[0]
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						Image.fromarray(np.uinta(A  )  ).convert('RGB'  )
             if str(A  ).startswith('mps'  ):
                   SCREAMING_SNAKE_CASE   :      Tuple    					=						torch.manual_seed(A  )
             else:
                   SCREAMING_SNAKE_CASE   :      int    					=						torch.Generator(device=A  ).manual_seed(A  )
             SCREAMING_SNAKE_CASE   :      Dict    					=						{
                 '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        UpperCamelCase_							(      self,							A,							A=0  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Any    					=						floats_tensor((1, 3, 32, 32),							rng=random.Random(A  )  ).to(A  )
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						image.cpu().permute(0,							2,							3,							1  )[0]
             SCREAMING_SNAKE_CASE   :      int    					=						Image.fromarray(np.uinta(A  )  ).convert('RGB'  )
             if str(A  ).startswith('mps'  ):
                   SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						torch.manual_seed(A  )
             else:
                   SCREAMING_SNAKE_CASE   :      Any    					=						torch.Generator(device=A  ).manual_seed(A  )
             SCREAMING_SNAKE_CASE   :      Any    					=						{
                 '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        UpperCamelCase_							(      self  ):







             '''simple docstring'''







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

             SCREAMING_SNAKE_CASE   :      Tuple    					=						self.get_dummy_components()
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						self.pipeline_class(**A  )
             pipe.to(A  )
             pipe.set_progress_bar_config(disable=A  )

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

             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						self.get_dummy_inputs(A  )
             SCREAMING_SNAKE_CASE   :      Dict    					=						pipe(**A  )[0]

             with tempfile.TemporaryDirectory() as tmpdir:
                   pipe.save_pretrained(A  )
                   SCREAMING_SNAKE_CASE   :      List[Any]    					=						self.pipeline_class.from_pretrained(A  )
                   pipe_loaded.to(A  )
                   pipe_loaded.set_progress_bar_config(disable=A  )

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

             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						self.get_dummy_inputs(A  )
             SCREAMING_SNAKE_CASE   :      Tuple    					=						pipe_loaded(**A  )[0]

             SCREAMING_SNAKE_CASE   :      List[str]    					=						np.abs(output - output_loaded  ).max()
             self.assertLess(A,							1E-4  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      str    					=						'cpu'

             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						self.get_dummy_components()
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						self.pipeline_class(**A  )
             pipe.to(A  )
             pipe.set_progress_bar_config(disable=A  )

             SCREAMING_SNAKE_CASE   :      str    					=						self.get_dummy_mask_inputs(A  )
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						pipe.generate_mask(**A  )
             SCREAMING_SNAKE_CASE   :      Dict    					=						mask[0, -3:, -3:]

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







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Tuple    					=						'cpu'

             SCREAMING_SNAKE_CASE   :      Dict    					=						self.get_dummy_components()
             SCREAMING_SNAKE_CASE   :      Dict    					=						self.pipeline_class(**A  )
             pipe.to(A  )
             pipe.set_progress_bar_config(disable=A  )

             SCREAMING_SNAKE_CASE   :      Tuple    					=						self.get_dummy_inversion_inputs(A  )
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						pipe.invert(**A  ).images
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						image[0, -1, -3:, -3:]

             self.assertEqual(image.shape,							(2, 32, 32, 3)  )
             SCREAMING_SNAKE_CASE   :      Tuple    					=						np.array(
                 [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99],							)
             SCREAMING_SNAKE_CASE   :      Dict    					=						np.abs(image_slice.flatten() - expected_slice  ).max()
             self.assertLessEqual(A,							1E-3  )







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







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







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Tuple    					=						'cpu'

             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						self.get_dummy_components()

             SCREAMING_SNAKE_CASE   :      Dict    					=						{'beta_start': 0.0_00_85, 'beta_end': 0.0_12, 'beta_schedule': 'scaled_linear'}
             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						DPMSolverMultistepScheduler(**A  )
             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						DPMSolverMultistepInverseScheduler(**A  )

             SCREAMING_SNAKE_CASE   :      Tuple    					=						self.pipeline_class(**A  )
             pipe.to(A  )
             pipe.set_progress_bar_config(disable=A  )

             SCREAMING_SNAKE_CASE   :      Tuple    					=						self.get_dummy_inversion_inputs(A  )
             SCREAMING_SNAKE_CASE   :      List[str]    					=						pipe.invert(**A  ).images
             SCREAMING_SNAKE_CASE   :      Optional[Any]    					=						image[0, -1, -3:, -3:]

             self.assertEqual(image.shape,							(2, 32, 32, 3)  )
             SCREAMING_SNAKE_CASE   :      Tuple    					=						np.array(
                 [0.51_50, 0.51_34, 0.50_43, 0.53_76, 0.46_94, 0.5_10_50, 0.50_15, 0.44_07, 0.47_99],							)
             SCREAMING_SNAKE_CASE   :      Any    					=						np.abs(image_slice.flatten() - expected_slice  ).max()
             self.assertLessEqual(A,							1E-3  )






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





       '''simple docstring'''






       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







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







       @classmethod
       def        UpperCamelCase_							(      cls  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						load_image(
                 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png'  )

             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						raw_image.convert('RGB'  ).resize((768, 768)  )

             SCREAMING_SNAKE_CASE   :      List[str]    					=						raw_image







       def        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Tuple    					=						torch.manual_seed(0  )

             SCREAMING_SNAKE_CASE   :      Dict    					=						StableDiffusionDiffEditPipeline.from_pretrained(
                 'stabilityai/stable-diffusion-2-1',							safety_checker=A,							torch_dtype=torch.floataa  )
             SCREAMING_SNAKE_CASE   :      List[Any]    					=						DDIMScheduler.from_config(pipe.scheduler.config  )
             SCREAMING_SNAKE_CASE   :      int    					=						DDIMInverseScheduler.from_config(pipe.scheduler.config  )
             pipe.enable_model_cpu_offload()
             pipe.set_progress_bar_config(disable=A  )

             SCREAMING_SNAKE_CASE   :      List[Any]    					=						'a bowl of fruit'
             SCREAMING_SNAKE_CASE   :      List[str]    					=						'a bowl of pears'

             SCREAMING_SNAKE_CASE   :      Dict    					=						pipe.generate_mask(
                 image=self.raw_image,							source_prompt=A,							target_prompt=A,							generator=A,							)

             SCREAMING_SNAKE_CASE   :      Optional[int]    					=						pipe.invert(
                 prompt=A,							image=self.raw_image,							inpaint_strength=0.7,							generator=A  ).latents

             SCREAMING_SNAKE_CASE   :      List[str]    					=						pipe(
                 prompt=A,							mask_image=A,							image_latents=A,							generator=A,							negative_prompt=A,							inpaint_strength=0.7,							output_type='numpy',							).images[0]

             SCREAMING_SNAKE_CASE   :      List[Any]    					=						(
                 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        UpperCamelCase_							(      self  ):







             '''simple docstring'''







             SCREAMING_SNAKE_CASE   :      Dict    					=						torch.manual_seed(0  )

             SCREAMING_SNAKE_CASE   :      int    					=						StableDiffusionDiffEditPipeline.from_pretrained(
                 'stabilityai/stable-diffusion-2-1',							safety_checker=A,							torch_dtype=torch.floataa  )
             SCREAMING_SNAKE_CASE   :      List[str]    					=						DPMSolverMultistepScheduler.from_config(pipe.scheduler.config  )
             SCREAMING_SNAKE_CASE   :      List[str]    					=						DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config  )
             pipe.enable_model_cpu_offload()
             pipe.set_progress_bar_config(disable=A  )

             SCREAMING_SNAKE_CASE   :      str    					=						'a bowl of fruit'
             SCREAMING_SNAKE_CASE   :      Tuple    					=						'a bowl of pears'

             SCREAMING_SNAKE_CASE   :      List[Any]    					=						pipe.generate_mask(
                 image=self.raw_image,							source_prompt=A,							target_prompt=A,							generator=A,							)

             SCREAMING_SNAKE_CASE   :      Union[str, Any]    					=						pipe.invert(
                 prompt=A,							image=self.raw_image,							inpaint_strength=0.7,							generator=A,							num_inference_steps=25,							).latents

             SCREAMING_SNAKE_CASE   :      str    					=						pipe(
                 prompt=A,							mask_image=A,							image_latents=A,							generator=A,							negative_prompt=A,							inpaint_strength=0.7,							num_inference_steps=25,							output_type='numpy',							).images[0]

             SCREAMING_SNAKE_CASE   :      Tuple    					=						(
                 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


