






"""simple docstring"""






import tempfile

import torch

from diffusers import PNDMScheduler

from .test_schedulers import SchedulerCommonTest




class 							lowerCAmelCase__				(			UpperCAmelCase__ ):






      '''simple docstring'''

      __UpperCamelCase	 =  (PNDMScheduler,)
      __UpperCamelCase	 =  (("num_inference_steps", 5_0),)
      def _SCREAMING_SNAKE_CASE (						self     :  Any						,	**lowercase_     :  Optional[Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Any    						=		{
              '''num_train_timesteps''': 1000,
              '''beta_start''': 0.00_01,
              '''beta_end''': 0.02,
              '''beta_schedule''': '''linear''',
          }

          config.update(**lowercase_)
          return config
      def _SCREAMING_SNAKE_CASE (						self     :  Optional[Any]						,	lowercase_     :  List[str]=0						,	**lowercase_     :  Union[str, Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  List[Any]    						=		dict(self.forward_default_kwargs)
          SCREAMING_SNAKE_CASE_      :  List[str]    						=		kwargs.pop('''num_inference_steps'''						,	lowercase_)
          SCREAMING_SNAKE_CASE_      :  Tuple    						=		self.dummy_sample
          SCREAMING_SNAKE_CASE_      :  List[Any]    						=		0.1 * sample
          SCREAMING_SNAKE_CASE_      :  Dict    						=		[residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]

          for scheduler_class in self.scheduler_classes:
              SCREAMING_SNAKE_CASE_      :  Tuple    						=		self.get_scheduler_config(**lowercase_)
              SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		scheduler_class(**lowercase_)
              scheduler.set_timesteps(lowercase_)
              # copy over dummy past residuals
              SCREAMING_SNAKE_CASE_      :  Dict    						=		dummy_past_residuals[:]

              with tempfile.TemporaryDirectory() as tmpdirname:
                  scheduler.save_config(lowercase_)
                  SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		scheduler_class.from_pretrained(lowercase_)
                  new_scheduler.set_timesteps(lowercase_)
                  # copy over dummy past residuals
                  SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		dummy_past_residuals[:]

              SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		scheduler.step_prk(lowercase_						,	lowercase_						,	lowercase_						,	**lowercase_).prev_sample
              SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		new_scheduler.step_prk(lowercase_						,	lowercase_						,	lowercase_						,	**lowercase_).prev_sample

              assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical"

              SCREAMING_SNAKE_CASE_      :  List[str]    						=		scheduler.step_plms(lowercase_						,	lowercase_						,	lowercase_						,	**lowercase_).prev_sample
              SCREAMING_SNAKE_CASE_      :  Dict    						=		new_scheduler.step_plms(lowercase_						,	lowercase_						,	lowercase_						,	**lowercase_).prev_sample

              assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical"
      def _SCREAMING_SNAKE_CASE (						self     :  Any):




          '''simple docstring'''


          pass
      def _SCREAMING_SNAKE_CASE (						self     :  List[Any]						,	lowercase_     :  List[str]=0						,	**lowercase_     :  List[str]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		dict(self.forward_default_kwargs)
          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		kwargs.pop('''num_inference_steps'''						,	lowercase_)
          SCREAMING_SNAKE_CASE_      :  List[str]    						=		self.dummy_sample
          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		0.1 * sample
          SCREAMING_SNAKE_CASE_      :  int    						=		[residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]

          for scheduler_class in self.scheduler_classes:
              SCREAMING_SNAKE_CASE_      :  Dict    						=		self.get_scheduler_config()
              SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		scheduler_class(**lowercase_)
              scheduler.set_timesteps(lowercase_)

              # copy over dummy past residuals (must be after setting timesteps)
              SCREAMING_SNAKE_CASE_      :  Dict    						=		dummy_past_residuals[:]

              with tempfile.TemporaryDirectory() as tmpdirname:
                  scheduler.save_config(lowercase_)
                  SCREAMING_SNAKE_CASE_      :  str    						=		scheduler_class.from_pretrained(lowercase_)
                  # copy over dummy past residuals
                  new_scheduler.set_timesteps(lowercase_)

                  # copy over dummy past residual (must be after setting timesteps)
                  SCREAMING_SNAKE_CASE_      :  Any    						=		dummy_past_residuals[:]

              SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		scheduler.step_prk(lowercase_						,	lowercase_						,	lowercase_						,	**lowercase_).prev_sample
              SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		new_scheduler.step_prk(lowercase_						,	lowercase_						,	lowercase_						,	**lowercase_).prev_sample

              assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical"

              SCREAMING_SNAKE_CASE_      :  List[str]    						=		scheduler.step_plms(lowercase_						,	lowercase_						,	lowercase_						,	**lowercase_).prev_sample
              SCREAMING_SNAKE_CASE_      :  Tuple    						=		new_scheduler.step_plms(lowercase_						,	lowercase_						,	lowercase_						,	**lowercase_).prev_sample

              assert torch.sum(torch.abs(output - new_output)) < 1e-5, "Scheduler outputs are not identical"
      def _SCREAMING_SNAKE_CASE (						self     :  str						,	**lowercase_     :  str):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Tuple    						=		self.scheduler_classes[0]
          SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		self.get_scheduler_config(**lowercase_)
          SCREAMING_SNAKE_CASE_      :  List[Any]    						=		scheduler_class(**lowercase_)

          SCREAMING_SNAKE_CASE_      :  Dict    						=		10
          SCREAMING_SNAKE_CASE_      :  List[Any]    						=		self.dummy_model()
          SCREAMING_SNAKE_CASE_      :  str    						=		self.dummy_sample_deter
          scheduler.set_timesteps(lowercase_)

          for i, t in enumerate(scheduler.prk_timesteps):
              SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		model(lowercase_						,	lowercase_)
              SCREAMING_SNAKE_CASE_      :  str    						=		scheduler.step_prk(lowercase_						,	lowercase_						,	lowercase_).prev_sample

          for i, t in enumerate(scheduler.plms_timesteps):
              SCREAMING_SNAKE_CASE_      :  List[Any]    						=		model(lowercase_						,	lowercase_)
              SCREAMING_SNAKE_CASE_      :  List[str]    						=		scheduler.step_plms(lowercase_						,	lowercase_						,	lowercase_).prev_sample

          return sample
      def _SCREAMING_SNAKE_CASE (						self     :  Dict):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Any    						=		dict(self.forward_default_kwargs)

          SCREAMING_SNAKE_CASE_      :  Dict    						=		kwargs.pop('''num_inference_steps'''						,	lowercase_)

          for scheduler_class in self.scheduler_classes:
              SCREAMING_SNAKE_CASE_      :  Tuple    						=		self.get_scheduler_config()
              SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		scheduler_class(**lowercase_)

              SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		self.dummy_sample
              SCREAMING_SNAKE_CASE_      :  Any    						=		0.1 * sample

              if num_inference_steps is not None and hasattr(lowercase_						,	'''set_timesteps'''):
                  scheduler.set_timesteps(lowercase_)
              elif num_inference_steps is not None and not hasattr(lowercase_						,	'''set_timesteps'''):
                  SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		num_inference_steps

              # copy over dummy past residuals (must be done after set_timesteps)
              SCREAMING_SNAKE_CASE_      :  str    						=		[residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]
              SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		dummy_past_residuals[:]

              SCREAMING_SNAKE_CASE_      :  Dict    						=		scheduler.step_prk(lowercase_						,	0						,	lowercase_						,	**lowercase_).prev_sample
              SCREAMING_SNAKE_CASE_      :  List[Any]    						=		scheduler.step_prk(lowercase_						,	1						,	lowercase_						,	**lowercase_).prev_sample

              self.assertEqual(output_a.shape						,	sample.shape)
              self.assertEqual(output_a.shape						,	output_a.shape)

              SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		scheduler.step_plms(lowercase_						,	0						,	lowercase_						,	**lowercase_).prev_sample
              SCREAMING_SNAKE_CASE_      :  Any    						=		scheduler.step_plms(lowercase_						,	1						,	lowercase_						,	**lowercase_).prev_sample

              self.assertEqual(output_a.shape						,	sample.shape)
              self.assertEqual(output_a.shape						,	output_a.shape)
      def _SCREAMING_SNAKE_CASE (						self     :  str):




          '''simple docstring'''


          for timesteps in [100, 1000]:
              self.check_over_configs(num_train_timesteps=lowercase_)
      def _SCREAMING_SNAKE_CASE (						self     :  Dict):




          '''simple docstring'''


          for steps_offset in [0, 1]:
              self.check_over_configs(steps_offset=lowercase_)

          SCREAMING_SNAKE_CASE_      :  Dict    						=		self.scheduler_classes[0]
          SCREAMING_SNAKE_CASE_      :  List[str]    						=		self.get_scheduler_config(steps_offset=1)
          SCREAMING_SNAKE_CASE_      :  Tuple    						=		scheduler_class(**lowercase_)
          scheduler.set_timesteps(10)
          assert torch.equal(
              scheduler.timesteps						,	torch.LongTensor(
                  [901, 851, 851, 801, 801, 751, 751, 701, 701, 651, 651, 601, 601, 501, 401, 301, 201, 101, 1])						,	)
      def _SCREAMING_SNAKE_CASE (						self     :  Any):




          '''simple docstring'''


          for beta_start, beta_end in zip([0.00_01, 0.0_01]						,	[0.0_02, 0.02]):
              self.check_over_configs(beta_start=lowercase_						,	beta_end=lowercase_)
      def _SCREAMING_SNAKE_CASE (						self     :  List[Any]):




          '''simple docstring'''


          for schedule in ["linear", "squaredcos_cap_v2"]:
              self.check_over_configs(beta_schedule=lowercase_)
      def _SCREAMING_SNAKE_CASE (						self     :  Any):




          '''simple docstring'''


          for prediction_type in ["epsilon", "v_prediction"]:
              self.check_over_configs(prediction_type=lowercase_)
      def _SCREAMING_SNAKE_CASE (						self     :  int):




          '''simple docstring'''


          for t in [1, 5, 10]:
              self.check_over_forward(time_step=lowercase_)
      def _SCREAMING_SNAKE_CASE (						self     :  Optional[Any]):




          '''simple docstring'''


          for t, num_inference_steps in zip([1, 5, 10]						,	[10, 50, 100]):
              self.check_over_forward(num_inference_steps=lowercase_)
      def _SCREAMING_SNAKE_CASE (						self     :  Any):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		27

          for scheduler_class in self.scheduler_classes:
              SCREAMING_SNAKE_CASE_      :  List[Any]    						=		self.dummy_sample
              SCREAMING_SNAKE_CASE_      :  str    						=		0.1 * sample

              SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		self.get_scheduler_config()
              SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		scheduler_class(**lowercase_)

              scheduler.set_timesteps(lowercase_)

              # before power of 3 fix, would error on first step, so we only need to do two
              for i, t in enumerate(scheduler.prk_timesteps[:2]):
                  SCREAMING_SNAKE_CASE_      :  int    						=		scheduler.step_prk(lowercase_						,	lowercase_						,	lowercase_).prev_sample
      def _SCREAMING_SNAKE_CASE (						self     :  List[Any]):




          '''simple docstring'''


          with self.assertRaises(lowercase_):
              SCREAMING_SNAKE_CASE_      :  int    						=		self.scheduler_classes[0]
              SCREAMING_SNAKE_CASE_      :  List[str]    						=		self.get_scheduler_config()
              SCREAMING_SNAKE_CASE_      :  Dict    						=		scheduler_class(**lowercase_)

              scheduler.step_plms(self.dummy_sample						,	1						,	self.dummy_sample).prev_sample
      def _SCREAMING_SNAKE_CASE (						self     :  Optional[int]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Any    						=		self.full_loop()
          SCREAMING_SNAKE_CASE_      :  List[Any]    						=		torch.sum(torch.abs(lowercase_))
          SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		torch.mean(torch.abs(lowercase_))

          assert abs(result_sum.item() - 1_98.13_18) < 1e-2
          assert abs(result_mean.item() - 0.25_80) < 1e-3
      def _SCREAMING_SNAKE_CASE (						self     :  Optional[int]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  str    						=		self.full_loop(prediction_type='''v_prediction''')
          SCREAMING_SNAKE_CASE_      :  str    						=		torch.sum(torch.abs(lowercase_))
          SCREAMING_SNAKE_CASE_      :  Any    						=		torch.mean(torch.abs(lowercase_))

          assert abs(result_sum.item() - 67.39_86) < 1e-2
          assert abs(result_mean.item() - 0.08_78) < 1e-3
      def _SCREAMING_SNAKE_CASE (						self     :  Optional[Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Tuple    						=		self.full_loop(set_alpha_to_one=lowercase_						,	beta_start=0.01)
          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		torch.sum(torch.abs(lowercase_))
          SCREAMING_SNAKE_CASE_      :  Any    						=		torch.mean(torch.abs(lowercase_))

          assert abs(result_sum.item() - 2_30.03_99) < 1e-2
          assert abs(result_mean.item() - 0.29_95) < 1e-3



      def _SCREAMING_SNAKE_CASE (						self     :  Optional[Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		self.full_loop(set_alpha_to_one=lowercase_						,	beta_start=0.01)
          SCREAMING_SNAKE_CASE_      :  int    						=		torch.sum(torch.abs(lowercase_))
          SCREAMING_SNAKE_CASE_      :  List[str]    						=		torch.mean(torch.abs(lowercase_))

          assert abs(result_sum.item() - 1_86.94_82) < 1e-2
          assert abs(result_mean.item() - 0.24_34) < 1e-3






"""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






