
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       _snake_case					:







			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						,   ):
				__magic_name__		:		Union[str, Any]	   =     parent
				__magic_name__		:		Optional[int]	   =     batch_size
				__magic_name__		:		str	   =     image_size
				__magic_name__		:		List[Any]	   =     num_channels
				__magic_name__		:		List[str]	   =     num_stages
				__magic_name__		:		Optional[int]	   =     hidden_sizes
				__magic_name__		:		List[Any]	   =     depths
				__magic_name__		:		int	   =     is_training
				__magic_name__		:		Optional[int]	   =     use_labels
				__magic_name__		:		str	   =     intermediate_size
				__magic_name__		:		str	   =     hidden_act
				__magic_name__		:		int	   =     num_labels
				__magic_name__		:		Tuple	   =     initializer_range
				__magic_name__		:		Optional[Any]	   =     out_features
				__magic_name__		:		List[Any]	   =     out_indices
				__magic_name__		:		Union[str, Any]	   =     scope







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

				__magic_name__		:		str	   =     None
				if self.use_labels:
					__magic_name__		:		Any	   =     ids_tensor([self.batch_size]						,   self.num_labels		)

				__magic_name__		:		Optional[Any]	   =     self.get_config()

				return config, pixel_values, labels







			def 			SCREAMING_SNAKE_CASE    (				self		):
				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=__UpperCAmelCase						,   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						,   _a						,   _a						,   _a		):
				__magic_name__		:		int	   =     ConvNextVaModel(config=__UpperCAmelCase		)
				model.to(__UpperCAmelCase		)
				model.eval()
				__magic_name__		:		List[str]	   =     model(__UpperCAmelCase		)
				# 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						,   _a						,   _a						,   _a		):
				__magic_name__		:		Optional[Any]	   =     ConvNextVaForImageClassification(__UpperCAmelCase		)
				model.to(__UpperCAmelCase		)
				model.eval()
				__magic_name__		:		List[str]	   =     model(__UpperCAmelCase						,   labels=__UpperCAmelCase		)
				self.parent.assertEqual(result.logits.shape						,   (self.batch_size, self.num_labels)		)







			def 			SCREAMING_SNAKE_CASE    (				self						,   _a						,   _a						,   _a		):
				__magic_name__		:		Optional[int]	   =     ConvNextVaBackbone(config=__UpperCAmelCase		)
				model.to(__UpperCAmelCase		)
				model.eval()
				__magic_name__		:		List[Any]	   =     model(__UpperCAmelCase		)

				# 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
				__magic_name__		:		Any	   =     None
				__magic_name__		:		Optional[int]	   =     ConvNextVaBackbone(config=__UpperCAmelCase		)
				model.to(__UpperCAmelCase		)
				model.eval()
				__magic_name__		:		Optional[Any]	   =     model(__UpperCAmelCase		)

				# 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		):
				__magic_name__		:		str	   =     self.prepare_config_and_inputs()
				__magic_name__		:		Any	   =     config_and_inputs
				__magic_name__		:		List[Any]	   =     {"pixel_values": pixel_values}
				return config, inputs_dict







			def 			SCREAMING_SNAKE_CASE    (				self		):
				__magic_name__		:		int	   =     self.prepare_config_and_inputs()
				__magic_name__		:		Optional[int]	   =     config_and_inputs
				__magic_name__		:		Optional[int]	   =     {"pixel_values": pixel_values, "labels": labels}
				return config, inputs_dict







@require_torch
class       _snake_case					(     _a				,						_a				,						unittest.TestCase				):
			UpperCamelCase__          =    (
			    (
			        ConvNextVaModel,
			        ConvNextVaForImageClassification,
			        ConvNextVaBackbone,
			    )
			    if is_torch_available()
			    else ()
			)
			UpperCamelCase__          =    (
			    {"""feature-extraction""": ConvNextVaModel, """image-classification""": ConvNextVaForImageClassification}
			    if is_torch_available()
			    else {}
			)

			UpperCamelCase__          =    False
			UpperCamelCase__          =    False
			UpperCamelCase__          =    False
			UpperCamelCase__          =    False
			UpperCamelCase__          =    False







			def 			SCREAMING_SNAKE_CASE    (				self		):
				__magic_name__		:		Tuple	   =     ConvNextVaModelTester(self		)
				__magic_name__		:		str	   =     ConfigTester(self						,   config_class=__UpperCAmelCase						,   has_text_modality=__UpperCAmelCase						,   hidden_size=37		)







			def 			SCREAMING_SNAKE_CASE    (				self		):
				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		):
				return







			@unittest.skip(reason="ConvNextV2 does not use inputs_embeds"		)
			def 			SCREAMING_SNAKE_CASE    (				self		):
				pass







			@unittest.skip(reason="ConvNextV2 does not support input and output embeddings"		)
			def 			SCREAMING_SNAKE_CASE    (				self		):
				pass







			@unittest.skip(reason="ConvNextV2 does not use feedforward chunking"		)
			def 			SCREAMING_SNAKE_CASE    (				self		):
				pass







			def 			SCREAMING_SNAKE_CASE    (				self		):
				if not self.model_tester.is_training:
					return

				for model_class in self.all_model_classes:
					__magic_name__		:		Dict	   =     self.model_tester.prepare_config_and_inputs_with_labels()
					__magic_name__		:		Tuple	   =     True

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

					__magic_name__		:		int	   =     model_class(__UpperCAmelCase		)
					model.to(__UpperCAmelCase		)
					model.train()
					__magic_name__		:		Dict	   =     self._prepare_for_class(__UpperCAmelCase						,   __UpperCAmelCase						,   return_labels=__UpperCAmelCase		)
					__magic_name__		:		Optional[int]	   =     model(**__UpperCAmelCase		).loss
					loss.backward()







			def 			SCREAMING_SNAKE_CASE    (				self		):
				if not self.model_tester.is_training:
					return

				for model_class in self.all_model_classes:
					__magic_name__		:		Optional[Any]	   =     self.model_tester.prepare_config_and_inputs_with_labels()
					__magic_name__		:		Optional[int]	   =     False
					__magic_name__		:		Optional[Any]	   =     True

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

					__magic_name__		:		Tuple	   =     model_class(__UpperCAmelCase		)
					model.to(__UpperCAmelCase		)
					model.gradient_checkpointing_enable()
					model.train()
					__magic_name__		:		Union[str, Any]	   =     self._prepare_for_class(__UpperCAmelCase						,   __UpperCAmelCase						,   return_labels=__UpperCAmelCase		)
					__magic_name__		:		Optional[int]	   =     model(**__UpperCAmelCase		).loss
					loss.backward()







			def 			SCREAMING_SNAKE_CASE    (				self		):
				__magic_name__		:		Tuple	   =     self.model_tester.prepare_config_and_inputs_for_common()

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

					__magic_name__		:		Tuple	   =     ["pixel_values"]
					self.assertListEqual(arg_names[:1]						,   __UpperCAmelCase		)







			def 			SCREAMING_SNAKE_CASE    (				self		):
				__magic_name__		:		Any	   =     self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*__UpperCAmelCase		)







			def 			SCREAMING_SNAKE_CASE    (				self		):
				def check_hidden_states_output(_a						,   _a						,   _a		):
					__magic_name__		:		Optional[int]	   =     model_class(__UpperCAmelCase		)
					model.to(__UpperCAmelCase		)
					model.eval()

					with torch.no_grad():
						__magic_name__		:		Optional[Any]	   =     model(**self._prepare_for_class(__UpperCAmelCase						,   __UpperCAmelCase		)		)

					__magic_name__		:		Tuple	   =     outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

					__magic_name__		:		List[Any]	   =     self.model_tester.num_stages
					self.assertEqual(len(__UpperCAmelCase		)						,   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]						,   )

				__magic_name__		:		Union[str, Any]	   =     self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
					__magic_name__		:		List[Any]	   =     True
					check_hidden_states_output(__UpperCAmelCase						,   __UpperCAmelCase						,   __UpperCAmelCase		)

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

					check_hidden_states_output(__UpperCAmelCase						,   __UpperCAmelCase						,   __UpperCAmelCase		)







			def 			SCREAMING_SNAKE_CASE    (				self		):
				__magic_name__		:		Union[str, Any]	   =     self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*__UpperCAmelCase		)







			@slow
			def 			SCREAMING_SNAKE_CASE    (				self		):
				for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
					__magic_name__		:		Tuple	   =     ConvNextVaModel.from_pretrained(__UpperCAmelCase		)
					self.assertIsNotNone(__UpperCAmelCase		)







def   lowerCAmelCase_						(					)				->		List[str]:







	'''simple docstring'''


	__magic_name__		:		int	   =     Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"   )
	return image





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







			@cached_property
			def 			SCREAMING_SNAKE_CASE    (				self		):
				return AutoImageProcessor.from_pretrained("facebook/convnextv2-tiny-1k-224"		) if is_vision_available() else None







			@slow
			def 			SCREAMING_SNAKE_CASE    (				self		):
				__magic_name__		:		Optional[int]	   =     ConvNextVaForImageClassification.from_pretrained("facebook/convnextv2-tiny-1k-224"		).to(__UpperCAmelCase		)

				__magic_name__		:		Any	   =     self.default_image_processor
				__magic_name__		:		Union[str, Any]	   =     prepare_img()
				__magic_name__		:		List[str]	   =     preprocessor(images=__UpperCAmelCase						,   return_tensors="pt"		).to(__UpperCAmelCase		)

				# forward pass
				with torch.no_grad():
					__magic_name__		:		Any	   =     model(**__UpperCAmelCase		)

				# verify the logits
				__magic_name__		:		str	   =     torch.Size((1, 1_000)		)
				self.assertEqual(outputs.logits.shape						,   __UpperCAmelCase		)

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




"""simple docstring"""







import gc
import random
import unittest

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

from diffusers import AutoencoderKL, PNDMScheduler, StableDiffusionInpaintPipeline, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu, slow

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


enable_full_determinism()






class 						_A  (  _a    ,_a    ,_a    ,unittest.TestCase  ):







    """simple docstring"""




    UpperCAmelCase       :							str	=       StableDiffusionInpaintPipeline
    UpperCAmelCase       :							Optional[Any]	=       TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
    UpperCAmelCase       :							Any	=       TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
    UpperCAmelCase       :							Union[str, Any]	=       frozenset(
        []  )  # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
    UpperCAmelCase       :							int	=       frozenset([]  )






    def 	__snake_case							(					self				:    Dict):
      torch.manual_seed(0)
      a						:		List[Any]      							=			UNetaDConditionModel(
          block_out_channels=(32, 64)				, layers_per_block=2				, sample_size=32				, in_channels=9				, 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=__UpperCAmelCase				, )
      a						:		Tuple      							=			PNDMScheduler(skip_prk_steps=__UpperCAmelCase)
      torch.manual_seed(0)
      a						:		str      							=			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)
      a						:		List[str]      							=			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				, )
      a						:		Any      							=			CLIPTextModel(__UpperCAmelCase)
      a						:		List[str]      							=			CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")

      a						:		Optional[Any]      							=			{
          "unet": unet,
          "scheduler": scheduler,
          "vae": vae,
          "text_encoder": text_encoder,
          "tokenizer": tokenizer,
          "safety_checker": None,
          "feature_extractor": None,
      }
      return components






    def 	__snake_case							(					self				:    Union[str, Any]				, __UpperCAmelCase				:    Any				, __UpperCAmelCase				:    Union[str, Any]=0):
      # TODO: use tensor inputs instead of PIL, this is here just to leave the old expected_slices untouched
      a						:		Dict      							=			floats_tensor((1, 3, 32, 32)				, rng=random.Random(__UpperCAmelCase)).to(__UpperCAmelCase)
      a						:		List[str]      							=			image.cpu().permute(0				, 2				, 3				, 1)[0]
      a						:		Union[str, Any]      							=			Image.fromarray(np.uinta(__UpperCAmelCase)).convert("RGB").resize((64, 64))
      a						:		Dict      							=			Image.fromarray(np.uinta(image + 4)).convert("RGB").resize((64, 64))
      if str(__UpperCAmelCase).startswith("mps"):
        a						:		Tuple      							=			torch.manual_seed(__UpperCAmelCase)
      else:
        a						:		Tuple      							=			torch.Generator(device=__UpperCAmelCase).manual_seed(__UpperCAmelCase)
      a						:		Optional[Any]      							=			{
          "prompt": "A painting of a squirrel eating a burger",
          "image": init_image,
          "mask_image": mask_image,
          "generator": generator,
          "num_inference_steps": 2,
          "guidance_scale": 6.0,
          "output_type": "numpy",
      }
      return inputs






    def 	__snake_case							(					self				:    List[str]):
      a						:		Union[str, Any]      							=			"cpu"  # ensure determinism for the device-dependent torch.Generator
      a						:		Tuple      							=			self.get_dummy_components()
      a						:		Optional[int]      							=			StableDiffusionInpaintPipeline(**__UpperCAmelCase)
      a						:		int      							=			sd_pipe.to(__UpperCAmelCase)
      sd_pipe.set_progress_bar_config(disable=__UpperCAmelCase)

      a						:		Any      							=			self.get_dummy_inputs(__UpperCAmelCase)
      a						:		Optional[int]      							=			sd_pipe(**__UpperCAmelCase).images
      a						:		Optional[int]      							=			image[0, -3:, -3:, -1]

      assert image.shape == (1, 64, 64, 3)
      a						:		int      							=			np.array([0.4_727, 0.5_735, 0.3_941, 0.5_446, 0.5_926, 0.4_394, 0.5_062, 0.4_654, 0.4_476])

      assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2






    def 	__snake_case							(					self				:    str):
      super().test_inference_batch_single_identical(expected_max_diff=3e-3)






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







    """simple docstring"""




    def 	__snake_case							(					self				:    Union[str, Any]):
      # clean up the VRAM after each test
      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()






    def 	__snake_case							(					self				:    Dict):
      a						:		str      							=			load_image(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
          "/sd2-inpaint/init_image.png")
      a						:		str      							=			load_image(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png")
      a						:		List[Any]      							=			load_numpy(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint"
          "/yellow_cat_sitting_on_a_park_bench.npy")

      a						:		Tuple      							=			"stabilityai/stable-diffusion-2-inpainting"
      a						:		Optional[Any]      							=			StableDiffusionInpaintPipeline.from_pretrained(__UpperCAmelCase				, safety_checker=__UpperCAmelCase)
      pipe.to(__UpperCAmelCase)
      pipe.set_progress_bar_config(disable=__UpperCAmelCase)
      pipe.enable_attention_slicing()

      a						:		Any      							=			"Face of a yellow cat, high resolution, sitting on a park bench"

      a						:		str      							=			torch.manual_seed(0)
      a						:		Union[str, Any]      							=			pipe(
          prompt=__UpperCAmelCase				, image=__UpperCAmelCase				, mask_image=__UpperCAmelCase				, generator=__UpperCAmelCase				, output_type="np"				, )
      a						:		List[str]      							=			output.images[0]

      assert image.shape == (512, 512, 3)
      assert np.abs(expected_image - image).max() < 9e-3






    def 	__snake_case							(					self				:    Any):
      a						:		str      							=			load_image(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
          "/sd2-inpaint/init_image.png")
      a						:		Optional[Any]      							=			load_image(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png")
      a						:		str      							=			load_numpy(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint"
          "/yellow_cat_sitting_on_a_park_bench_fp16.npy")

      a						:		Optional[Any]      							=			"stabilityai/stable-diffusion-2-inpainting"
      a						:		Any      							=			StableDiffusionInpaintPipeline.from_pretrained(
          __UpperCAmelCase				, torch_dtype=torch.floataa				, safety_checker=__UpperCAmelCase				, )
      pipe.to(__UpperCAmelCase)
      pipe.set_progress_bar_config(disable=__UpperCAmelCase)
      pipe.enable_attention_slicing()

      a						:		Optional[int]      							=			"Face of a yellow cat, high resolution, sitting on a park bench"

      a						:		Dict      							=			torch.manual_seed(0)
      a						:		List[Any]      							=			pipe(
          prompt=__UpperCAmelCase				, image=__UpperCAmelCase				, mask_image=__UpperCAmelCase				, generator=__UpperCAmelCase				, output_type="np"				, )
      a						:		Optional[Any]      							=			output.images[0]

      assert image.shape == (512, 512, 3)
      assert np.abs(expected_image - image).max() < 5e-1






    def 	__snake_case							(					self				:    int):
      torch.cuda.empty_cache()
      torch.cuda.reset_max_memory_allocated()
      torch.cuda.reset_peak_memory_stats()

      a						:		Tuple      							=			load_image(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
          "/sd2-inpaint/init_image.png")
      a						:		Optional[int]      							=			load_image(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-inpaint/mask.png")

      a						:		Optional[Any]      							=			"stabilityai/stable-diffusion-2-inpainting"
      a						:		Optional[int]      							=			PNDMScheduler.from_pretrained(__UpperCAmelCase				, subfolder="scheduler")
      a						:		int      							=			StableDiffusionInpaintPipeline.from_pretrained(
          __UpperCAmelCase				, safety_checker=__UpperCAmelCase				, scheduler=__UpperCAmelCase				, torch_dtype=torch.floataa				, )
      pipe.to(__UpperCAmelCase)
      pipe.set_progress_bar_config(disable=__UpperCAmelCase)
      pipe.enable_attention_slicing(1)
      pipe.enable_sequential_cpu_offload()

      a						:		Optional[int]      							=			"Face of a yellow cat, high resolution, sitting on a park bench"

      a						:		Optional[int]      							=			torch.manual_seed(0)
      a						:		str      							=			pipe(
          prompt=__UpperCAmelCase				, image=__UpperCAmelCase				, mask_image=__UpperCAmelCase				, generator=__UpperCAmelCase				, num_inference_steps=2				, output_type="np"				, )

      a						:		int      							=			torch.cuda.max_memory_allocated()
      # make sure that less than 2.65 GB is allocated
      assert mem_bytes < 2.65 * 10**9






