'''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__ :






     def __init__(					self						:						int    ,							a						:						Optional[int]    ,							a						:						Optional[int]=13    ,							a						:						Tuple=32    ,							a						:						Optional[Any]=3    ,							a						:						Tuple=4    ,							a						:						List[Any]=[10, 20, 30, 40]    ,							a						:						Dict=[2, 2, 3, 2]    ,							a						:						Union[str, Any]=True    ,							a						:						Union[str, Any]=True    ,							a						:						List[str]=37    ,							a						:						List[Any]="gelu"    ,							a						:						Union[str, Any]=10    ,							a						:						int=0.02    ,							a						:						str=["stage2", "stage3", "stage4"]    ,							a						:						int=[2, 3, 4]    ,							a						:						List[Any]=None    ,							):





         """simple docstring"""



         __lowerCamelCase            =    parent
         __lowerCamelCase            =    batch_size
         __lowerCamelCase            =    image_size
         __lowerCamelCase            =    num_channels
         __lowerCamelCase            =    num_stages
         __lowerCamelCase            =    hidden_sizes
         __lowerCamelCase            =    depths
         __lowerCamelCase            =    is_training
         __lowerCamelCase            =    use_labels
         __lowerCamelCase            =    intermediate_size
         __lowerCamelCase            =    hidden_act
         __lowerCamelCase            =    num_labels
         __lowerCamelCase            =    initializer_range
         __lowerCamelCase            =    out_features
         __lowerCamelCase            =    out_indices
         __lowerCamelCase            =    scope






     def   SCREAMING_SNAKE_CASE__  (					self						:						Tuple       ):





         """simple docstring"""



         __lowerCamelCase            =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

         __lowerCamelCase            =    None
         if self.use_labels:
             __lowerCamelCase            =    ids_tensor([self.batch_size]    ,							self.num_labels       )

         __lowerCamelCase            =    self.get_config()

         return config, pixel_values, labels






     def   SCREAMING_SNAKE_CASE__  (					self						:						Any       ):





         """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=snake_case__    ,							initializer_range=self.initializer_range    ,							out_features=self.out_features    ,							out_indices=self.out_indices    ,							num_labels=self.num_labels    ,							)






     def   SCREAMING_SNAKE_CASE__  (					self						:						Optional[Any]    ,							a						:						str    ,							a						:						int    ,							a						:						List[Any]       ):





         """simple docstring"""



         __lowerCamelCase            =    ConvNextVaModel(config=snake_case__       )
         model.to(snake_case__       )
         model.eval()
         __lowerCamelCase            =    model(snake_case__       )
         # 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   SCREAMING_SNAKE_CASE__  (					self						:						Union[str, Any]    ,							a						:						Optional[Any]    ,							a						:						str    ,							a						:						List[Any]       ):





         """simple docstring"""



         __lowerCamelCase            =    ConvNextVaForImageClassification(snake_case__       )
         model.to(snake_case__       )
         model.eval()
         __lowerCamelCase            =    model(snake_case__    ,							labels=snake_case__       )
         self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, self.num_labels)       )






     def   SCREAMING_SNAKE_CASE__  (					self						:						Optional[Any]    ,							a						:						Dict    ,							a						:						int    ,							a						:						Optional[int]       ):





         """simple docstring"""



         __lowerCamelCase            =    ConvNextVaBackbone(config=snake_case__       )
         model.to(snake_case__       )
         model.eval()
         __lowerCamelCase            =    model(snake_case__       )

         # 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
         __lowerCamelCase            =    None
         __lowerCamelCase            =    ConvNextVaBackbone(config=snake_case__       )
         model.to(snake_case__       )
         model.eval()
         __lowerCamelCase            =    model(snake_case__       )

         # 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   SCREAMING_SNAKE_CASE__  (					self						:						Optional[int]       ):





         """simple docstring"""



         __lowerCamelCase            =    self.prepare_config_and_inputs()
         __lowerCamelCase            =    config_and_inputs
         __lowerCamelCase            =    {"pixel_values": pixel_values}
         return config, inputs_dict






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





         """simple docstring"""



         __lowerCamelCase            =    self.prepare_config_and_inputs()
         __lowerCamelCase            =    config_and_inputs
         __lowerCamelCase            =    {"pixel_values": pixel_values, "labels": labels}
         return config, inputs_dict




@require_torch
class        a__ (  A_				,  A_				,  unittest.TestCase					):
     lowerCamelCase    :	Tuple				=(
         (
             ConvNextVaModel,
             ConvNextVaForImageClassification,
             ConvNextVaBackbone,
         )
         if is_torch_available()
         else ()
     )
     lowerCamelCase    :	int				=(
         {"feature-extraction": ConvNextVaModel, "image-classification": ConvNextVaForImageClassification}
         if is_torch_available()
         else {}
     )

     lowerCamelCase    :	str				=False
     lowerCamelCase    :	Dict				=False
     lowerCamelCase    :	Optional[int]				=False
     lowerCamelCase    :	List[Any]				=False
     lowerCamelCase    :	str				=False






     def   SCREAMING_SNAKE_CASE__  (					self						:						Optional[Any]       ):





         """simple docstring"""



         __lowerCamelCase            =    ConvNextVaModelTester(self       )
         __lowerCamelCase            =    ConfigTester(self    ,							config_class=snake_case__    ,							has_text_modality=snake_case__    ,							hidden_size=37       )






     def   SCREAMING_SNAKE_CASE__  (					self						:						str       ):





         """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   SCREAMING_SNAKE_CASE__  (					self						:						int       ):





         """simple docstring"""



         return






     @unittest.skip(reason='''ConvNextV2 does not use inputs_embeds'''       )
     def   SCREAMING_SNAKE_CASE__  (					self						:						List[Any]       ):





         """simple docstring"""



         pass






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





         """simple docstring"""



         pass






     @unittest.skip(reason='''ConvNextV2 does not use feedforward chunking'''       )
     def   SCREAMING_SNAKE_CASE__  (					self						:						Optional[int]       ):





         """simple docstring"""



         pass






     def   SCREAMING_SNAKE_CASE__  (					self						:						Tuple       ):





         """simple docstring"""



         if not self.model_tester.is_training:
             return

         for model_class in self.all_model_classes:
             __lowerCamelCase            =    self.model_tester.prepare_config_and_inputs_with_labels()
             __lowerCamelCase            =    True

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

             __lowerCamelCase            =    model_class(snake_case__       )
             model.to(snake_case__       )
             model.train()
             __lowerCamelCase            =    self._prepare_for_class(snake_case__    ,							snake_case__    ,							return_labels=snake_case__       )
             __lowerCamelCase            =    model(**snake_case__       ).loss
             loss.backward()






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





         """simple docstring"""



         if not self.model_tester.is_training:
             return

         for model_class in self.all_model_classes:
             __lowerCamelCase            =    self.model_tester.prepare_config_and_inputs_with_labels()
             __lowerCamelCase            =    False
             __lowerCamelCase            =    True

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

             __lowerCamelCase            =    model_class(snake_case__       )
             model.to(snake_case__       )
             model.gradient_checkpointing_enable()
             model.train()
             __lowerCamelCase            =    self._prepare_for_class(snake_case__    ,							snake_case__    ,							return_labels=snake_case__       )
             __lowerCamelCase            =    model(**snake_case__       ).loss
             loss.backward()






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





         """simple docstring"""



         __lowerCamelCase            =    self.model_tester.prepare_config_and_inputs_for_common()

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

             __lowerCamelCase            =    ["pixel_values"]
             self.assertListEqual(arg_names[:1]    ,							snake_case__       )






     def   SCREAMING_SNAKE_CASE__  (					self						:						Optional[int]       ):





         """simple docstring"""



         __lowerCamelCase            =    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*snake_case__       )






     def   SCREAMING_SNAKE_CASE__  (					self						:						Optional[int]       ):





         """simple docstring"""



         def check_hidden_states_output(a						:						Dict    ,							a						:						List[Any]    ,							a						:						Dict       ):
             __lowerCamelCase            =    model_class(snake_case__       )
             model.to(snake_case__       )
             model.eval()

             with torch.no_grad():
                 __lowerCamelCase            =    model(**self._prepare_for_class(snake_case__    ,							snake_case__       )       )

             __lowerCamelCase            =    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

             __lowerCamelCase            =    self.model_tester.num_stages
             self.assertEqual(len(snake_case__       )    ,							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]    ,							)

         __lowerCamelCase            =    self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             __lowerCamelCase            =    True
             check_hidden_states_output(snake_case__    ,							snake_case__    ,							snake_case__       )

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             __lowerCamelCase            =    True

             check_hidden_states_output(snake_case__    ,							snake_case__    ,							snake_case__       )






     def   SCREAMING_SNAKE_CASE__  (					self						:						Optional[Any]       ):





         """simple docstring"""



         __lowerCamelCase            =    self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*snake_case__       )






     @slow
     def   SCREAMING_SNAKE_CASE__  (					self						:						Dict       ):





         """simple docstring"""



         for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             __lowerCamelCase            =    ConvNextVaModel.from_pretrained(snake_case__       )
             self.assertIsNotNone(snake_case__       )






def __lowerCAmelCase					(				)      ->       Union[str, Any]:
    __lowerCamelCase            =    Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''							)
    return image




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






     @cached_property
     def   SCREAMING_SNAKE_CASE__  (					self						:						Tuple       ):





         """simple docstring"""



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






     @slow
     def   SCREAMING_SNAKE_CASE__  (					self						:						Tuple       ):





         """simple docstring"""



         __lowerCamelCase            =    ConvNextVaForImageClassification.from_pretrained('''facebook/convnextv2-tiny-1k-224'''       ).to(snake_case__       )

         __lowerCamelCase            =    self.default_image_processor
         __lowerCamelCase            =    prepare_img()
         __lowerCamelCase            =    preprocessor(images=snake_case__    ,							return_tensors='''pt'''       ).to(snake_case__       )

         # forward pass
         with torch.no_grad():
             __lowerCamelCase            =    model(**snake_case__       )

         # verify the logits
         __lowerCamelCase            =    torch.Size((1, 10_00)       )
         self.assertEqual(outputs.logits.shape    ,							snake_case__       )

         __lowerCamelCase            =    torch.tensor([0.99_96, 0.19_66, -0.43_86]       ).to(snake_case__       )
         self.assertTrue(torch.allclose(outputs.logits[0, :3]    ,							snake_case__    ,							atol=1e-4       )       )


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     UpperCAmelCase						(		A_			,A_			,unittest.TestCase					):
   A__   :						Dict			=	StableDiffusionDiffEditPipeline
   A__   :						str			=	TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"height", "width", "image"} | {"image_latents"}
   A__   :						List[Any]			=	TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {"image"} | {"image_latents"}
   A__   :						Optional[Any]			=	frozenset(
       []					)  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
   A__   :						int			=	frozenset([]					)



   def 							_SCREAMING_SNAKE_CASE  (self						:   Tuple					)						->      Optional[Any]:


          '''simple docstring'''


          torch.manual_seed(0					)
          snake_case			:  Dict     							= 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=snake_case__       ,		)
          snake_case			:  str     							= DDIMScheduler(
              beta_start=0.00085       ,		beta_end=0.012       ,		beta_schedule="scaled_linear"       ,		clip_sample=snake_case__       ,		set_alpha_to_one=snake_case__       ,		)
          snake_case			:  List[Any]     							= DDIMInverseScheduler(
              beta_start=0.00085       ,		beta_end=0.012       ,		beta_schedule="scaled_linear"       ,		clip_sample=snake_case__       ,		set_alpha_to_zero=snake_case__       ,		)
          torch.manual_seed(0					)
          snake_case			:  Any     							= 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=1_28       ,		)
          torch.manual_seed(0					)
          snake_case			:  Union[str, Any]     							= 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=10_00       ,		hidden_act="gelu"       ,		projection_dim=5_12       ,		)
          snake_case			:  str     							= CLIPTextModel(snake_case__					)
          snake_case			:  Optional[Any]     							= CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"					)

          snake_case			:  List[str]     							= {
              "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 							_SCREAMING_SNAKE_CASE  (self						:   List[str]       ,		snake_case__						:   Dict       ,		snake_case__						:   Union[str, Any]=0					)						->      Optional[Any]:


          '''simple docstring'''


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


          '''simple docstring'''


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


          '''simple docstring'''


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


          '''simple docstring'''


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

          snake_case			:  int     							= self.get_dummy_components()
          snake_case			:  Optional[int]     							= self.pipeline_class(**snake_case__					)
          pipe.to(snake_case__					)
          pipe.set_progress_bar_config(disable=snake_case__					)

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

          snake_case			:  Dict     							= self.get_dummy_inputs(snake_case__					)
          snake_case			:  int     							= pipe(**snake_case__					)[0]

          with tempfile.TemporaryDirectory() as tmpdir:
                 pipe.save_pretrained(snake_case__					)
                 snake_case			:  Any     							= self.pipeline_class.from_pretrained(snake_case__					)
                 pipe_loaded.to(snake_case__					)
                 pipe_loaded.set_progress_bar_config(disable=snake_case__					)

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

          snake_case			:  Optional[int]     							= self.get_dummy_inputs(snake_case__					)
          snake_case			:  int     							= pipe_loaded(**snake_case__					)[0]

          snake_case			:  int     							= np.abs(output - output_loaded					).max()
          self.assertLess(snake_case__       ,		1e-4					)



   def 							_SCREAMING_SNAKE_CASE  (self						:   str					)						->      int:


          '''simple docstring'''


          snake_case			:  Union[str, Any]     							= "cpu"

          snake_case			:  int     							= self.get_dummy_components()
          snake_case			:  Any     							= self.pipeline_class(**snake_case__					)
          pipe.to(snake_case__					)
          pipe.set_progress_bar_config(disable=snake_case__					)

          snake_case			:  Any     							= self.get_dummy_mask_inputs(snake_case__					)
          snake_case			:  Union[str, Any]     							= pipe.generate_mask(**snake_case__					)
          snake_case			:  List[Any]     							= mask[0, -3:, -3:]

          self.assertEqual(mask.shape       ,		(1, 16, 16)					)
          snake_case			:  int     							= np.array([0] * 9					)
          snake_case			:  str     							= np.abs(mask_slice.flatten() - expected_slice					).max()
          self.assertLessEqual(snake_case__       ,		1e-3					)
          self.assertEqual(mask[0, -3, -4]       ,		0					)



   def 							_SCREAMING_SNAKE_CASE  (self						:   str					)						->      str:


          '''simple docstring'''


          snake_case			:  Any     							= "cpu"

          snake_case			:  List[Any]     							= self.get_dummy_components()
          snake_case			:  Optional[int]     							= self.pipeline_class(**snake_case__					)
          pipe.to(snake_case__					)
          pipe.set_progress_bar_config(disable=snake_case__					)

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

          self.assertEqual(image.shape       ,		(2, 32, 32, 3)					)
          snake_case			:  int     							= np.array(
              [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799]       ,		)
          snake_case			:  Optional[Any]     							= np.abs(image_slice.flatten() - expected_slice					).max()
          self.assertLessEqual(snake_case__       ,		1e-3					)



   def 							_SCREAMING_SNAKE_CASE  (self						:   int					)						->      Any:


          '''simple docstring'''


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



   def 							_SCREAMING_SNAKE_CASE  (self						:   str					)						->      Any:


          '''simple docstring'''


          snake_case			:  Any     							= "cpu"

          snake_case			:  int     							= self.get_dummy_components()

          snake_case			:  Tuple     							= {"beta_start": 0.00085, "beta_end": 0.012, "beta_schedule": "scaled_linear"}
          snake_case			:  int     							= DPMSolverMultistepScheduler(**snake_case__					)
          snake_case			:  Optional[Any]     							= DPMSolverMultistepInverseScheduler(**snake_case__					)

          snake_case			:  Any     							= self.pipeline_class(**snake_case__					)
          pipe.to(snake_case__					)
          pipe.set_progress_bar_config(disable=snake_case__					)

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

          self.assertEqual(image.shape       ,		(2, 32, 32, 3)					)
          snake_case			:  int     							= np.array(
              [0.5150, 0.5134, 0.5043, 0.5376, 0.4694, 0.51050, 0.5015, 0.4407, 0.4799]       ,		)
          snake_case			:  Any     							= np.abs(image_slice.flatten() - expected_slice					).max()
          self.assertLessEqual(snake_case__       ,		1e-3					)






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



   def 							_SCREAMING_SNAKE_CASE  (self						:   List[Any]					)						->      int:


          '''simple docstring'''


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



   @classmethod
   def 							_SCREAMING_SNAKE_CASE  (cls						:   Optional[int]					)						->      Optional[int]:


          '''simple docstring'''


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

          snake_case			:  Tuple     							= raw_image.convert("RGB"					).resize((7_68, 7_68)					)

          snake_case			:  Tuple     							= raw_image



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


          '''simple docstring'''


          snake_case			:  Optional[int]     							= torch.manual_seed(0					)

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

          snake_case			:  Union[str, Any]     							= "a bowl of fruit"
          snake_case			:  int     							= "a bowl of pears"

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

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

          snake_case			:  List[str]     							= pipe(
              prompt=snake_case__       ,		mask_image=snake_case__       ,		image_latents=snake_case__       ,		generator=snake_case__       ,		negative_prompt=snake_case__       ,		inpaint_strength=0.7       ,		output_type="numpy"       ,		).images[0]

          snake_case			:  Dict     							= (
              np.array(
                  load_image(
                      "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
                      "/diffedit/pears.png"					).resize((7_68, 7_68)					)					)
              / 2_55
          )
          assert np.abs((expected_image - image).max()					) < 5e-1



   def 							_SCREAMING_SNAKE_CASE  (self						:   Union[str, Any]					)						->      Tuple:


          '''simple docstring'''


          snake_case			:  int     							= torch.manual_seed(0					)

          snake_case			:  Tuple     							= StableDiffusionDiffEditPipeline.from_pretrained(
              "stabilityai/stable-diffusion-2-1"       ,		safety_checker=snake_case__       ,		torch_dtype=torch.floataa					)
          snake_case			:  Union[str, Any]     							= DPMSolverMultistepScheduler.from_config(pipe.scheduler.config					)
          snake_case			:  Optional[int]     							= DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config					)
          pipe.enable_model_cpu_offload()
          pipe.set_progress_bar_config(disable=snake_case__					)

          snake_case			:  str     							= "a bowl of fruit"
          snake_case			:  Optional[int]     							= "a bowl of pears"

          snake_case			:  Optional[Any]     							= pipe.generate_mask(
              image=self.raw_image       ,		source_prompt=snake_case__       ,		target_prompt=snake_case__       ,		generator=snake_case__       ,		)

          snake_case			:  List[str]     							= pipe.invert(
              prompt=snake_case__       ,		image=self.raw_image       ,		inpaint_strength=0.7       ,		generator=snake_case__       ,		num_inference_steps=25       ,		).latents

          snake_case			:  Dict     							= pipe(
              prompt=snake_case__       ,		mask_image=snake_case__       ,		image_latents=snake_case__       ,		generator=snake_case__       ,		negative_prompt=snake_case__       ,		inpaint_strength=0.7       ,		num_inference_steps=25       ,		output_type="numpy"       ,		).images[0]

          snake_case			:  int     							= (
              np.array(
                  load_image(
                      "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
                      "/diffedit/pears.png"					).resize((7_68, 7_68)					)					)
              / 2_55
          )
          assert np.abs((expected_image - image).max()					) < 5e-1





