


"""simple docstring"""







import shutil
import tempfile
import unittest

from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available
from transformers.testing_utils import (
    get_tests_dir,
    nested_simplify,
    require_sentencepiece,
    require_tokenizers,
    require_torch,
)

from ...test_tokenization_common import TokenizerTesterMixin


__lowercase    					=      get_tests_dir("""fixtures/test_sentencepiece.model""")


if is_torch_available():
 from transformers.models.mbart.modeling_mbart import shift_tokens_right

__lowercase    					=      250004
__lowercase    					=      250020






@require_sentencepiece
@require_tokenizers
class 						_A  (  _a    ,unittest.TestCase  ):







    """simple docstring"""




    UpperCAmelCase       :							Optional[Any]	=       MBartTokenizer
    UpperCAmelCase       :							Dict	=       MBartTokenizerFast
    UpperCAmelCase       :							Optional[Any]	=       True
    UpperCAmelCase       :							str	=       True






    def 	__snake_case							(					self				:    List[Any]):
      super().setUp()

      # We have a SentencePiece fixture for testing
      a						:		Any      							=			MBartTokenizer(__UpperCAmelCase				, keep_accents=__UpperCAmelCase)
      tokenizer.save_pretrained(self.tmpdirname)






    def 	__snake_case							(					self				:    List[Any]):
      a						:		str      							=			MBartTokenizer(__UpperCAmelCase				, keep_accents=__UpperCAmelCase)

      a						:		Union[str, Any]      							=			tokenizer.tokenize("This is a test")
      self.assertListEqual(__UpperCAmelCase				, ["▁This", "▁is", "▁a", "▁t", "est"])

      self.assertListEqual(
          tokenizer.convert_tokens_to_ids(__UpperCAmelCase)				, [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]]				, )

      a						:		int      							=			tokenizer.tokenize("I was born in 92000, and this is falsé.")
      self.assertListEqual(
          __UpperCAmelCase				, [
              SPIECE_UNDERLINE + "I",
              SPIECE_UNDERLINE + "was",
              SPIECE_UNDERLINE + "b",
              "or",
              "n",
              SPIECE_UNDERLINE + "in",
              SPIECE_UNDERLINE + "",
              "9",
              "2",
              "0",
              "0",
              "0",
              ",",
              SPIECE_UNDERLINE + "and",
              SPIECE_UNDERLINE + "this",
              SPIECE_UNDERLINE + "is",
              SPIECE_UNDERLINE + "f",
              "al",
              "s",
              "é",
              ".",
          ]				, )
      a						:		Optional[Any]      							=			tokenizer.convert_tokens_to_ids(__UpperCAmelCase)
      self.assertListEqual(
          __UpperCAmelCase				, [
              value + tokenizer.fairseq_offset
              for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4]
              #                                       ^ unk: 2 + 1 = 3                  unk: 2 + 1 = 3 ^
          ]				, )

      a						:		Tuple      							=			tokenizer.convert_ids_to_tokens(__UpperCAmelCase)
      self.assertListEqual(
          __UpperCAmelCase				, [
              SPIECE_UNDERLINE + "I",
              SPIECE_UNDERLINE + "was",
              SPIECE_UNDERLINE + "b",
              "or",
              "n",
              SPIECE_UNDERLINE + "in",
              SPIECE_UNDERLINE + "",
              "<unk>",
              "2",
              "0",
              "0",
              "0",
              ",",
              SPIECE_UNDERLINE + "and",
              SPIECE_UNDERLINE + "this",
              SPIECE_UNDERLINE + "is",
              SPIECE_UNDERLINE + "f",
              "al",
              "s",
              "<unk>",
              ".",
          ]				, )






    def 	__snake_case							(					self				:    Any):
      if not self.test_slow_tokenizer:
        # as we don't have a slow version, we can't compare the outputs between slow and fast versions
        return

      a						:		Optional[Any]      							=			(self.rust_tokenizer_class, "hf-internal-testing/tiny-random-mbart", {})
      for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
        with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})'''):
          a						:		Dict      							=			self.rust_tokenizer_class.from_pretrained(__UpperCAmelCase				, **__UpperCAmelCase)
          a						:		List[Any]      							=			self.tokenizer_class.from_pretrained(__UpperCAmelCase				, **__UpperCAmelCase)

          a						:		Optional[int]      							=			tempfile.mkdtemp()

          a						:		Optional[int]      							=			tokenizer_r.save_pretrained(__UpperCAmelCase)
          a						:		List[Any]      							=			tokenizer_p.save_pretrained(__UpperCAmelCase)

          # Checks it save with the same files + the tokenizer.json file for the fast one
          self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files))
          a						:		Optional[int]      							=			tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f)
          self.assertSequenceEqual(__UpperCAmelCase				, __UpperCAmelCase)

          # Checks everything loads correctly in the same way
          a						:		Dict      							=			tokenizer_r.from_pretrained(__UpperCAmelCase)
          a						:		int      							=			tokenizer_p.from_pretrained(__UpperCAmelCase)

          # Check special tokens are set accordingly on Rust and Python
          for key in tokenizer_pp.special_tokens_map:
            self.assertTrue(hasattr(__UpperCAmelCase				, __UpperCAmelCase))
            # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key))
            # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id"))

          shutil.rmtree(__UpperCAmelCase)

          # Save tokenizer rust, legacy_format=True
          a						:		Optional[Any]      							=			tempfile.mkdtemp()

          a						:		Tuple      							=			tokenizer_r.save_pretrained(__UpperCAmelCase				, legacy_format=__UpperCAmelCase)
          a						:		List[str]      							=			tokenizer_p.save_pretrained(__UpperCAmelCase)

          # Checks it save with the same files
          self.assertSequenceEqual(__UpperCAmelCase				, __UpperCAmelCase)

          # Checks everything loads correctly in the same way
          a						:		Dict      							=			tokenizer_r.from_pretrained(__UpperCAmelCase)
          a						:		Optional[Any]      							=			tokenizer_p.from_pretrained(__UpperCAmelCase)

          # Check special tokens are set accordingly on Rust and Python
          for key in tokenizer_pp.special_tokens_map:
            self.assertTrue(hasattr(__UpperCAmelCase				, __UpperCAmelCase))

          shutil.rmtree(__UpperCAmelCase)

          # Save tokenizer rust, legacy_format=False
          a						:		Dict      							=			tempfile.mkdtemp()

          a						:		List[str]      							=			tokenizer_r.save_pretrained(__UpperCAmelCase				, legacy_format=__UpperCAmelCase)
          a						:		Optional[int]      							=			tokenizer_p.save_pretrained(__UpperCAmelCase)

          # Checks it saved the tokenizer.json file
          self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files))

          # Checks everything loads correctly in the same way
          a						:		Any      							=			tokenizer_r.from_pretrained(__UpperCAmelCase)
          a						:		Any      							=			tokenizer_p.from_pretrained(__UpperCAmelCase)

          # Check special tokens are set accordingly on Rust and Python
          for key in tokenizer_pp.special_tokens_map:
            self.assertTrue(hasattr(__UpperCAmelCase				, __UpperCAmelCase))

          shutil.rmtree(__UpperCAmelCase)






@require_torch
@require_sentencepiece
@require_tokenizers
class 						_A  (  unittest.TestCase  ):







    """simple docstring"""




    UpperCAmelCase       :							List[str]	=       """facebook/mbart-large-en-ro"""
    UpperCAmelCase       :							Optional[Any]	=       [
        """ UN Chief Says There Is No Military Solution in Syria""",
        """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.""",
    ]
    UpperCAmelCase       :							str	=       [
        """Şeful ONU declară că nu există o soluţie militară în Siria""",
        """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei"""
        """ pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor"""
        """ face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""",
    ]
    UpperCAmelCase       :							str	=       [8_2_7_4, 1_2_7_8_7_3, 2_5_9_1_6, 7, 8_6_2_2, 2_0_7_1, 4_3_8, 6_7_4_8_5, 5_3, 1_8_7_8_9_5, 2_3, 5_1_7_1_2, 2, EN_CODE]






    @classmethod
    def 	__snake_case							(					cls				:    str):
      a						:		MBartTokenizer      							=			MBartTokenizer.from_pretrained(
          cls.checkpoint_name				, src_lang="en_XX"				, tgt_lang="ro_RO")
      a						:		Optional[int]      							=			1
      return cls






    def 	__snake_case							(					self				:    Optional[Any]):
      self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ar_AR"]				, 250001)
      self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["en_EN"]				, 250004)
      self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["ro_RO"]				, 250020)






    def 	__snake_case							(					self				:    Union[str, Any]):
      a						:		Union[str, Any]      							=			self.tokenizer.batch_encode_plus(self.src_text).input_ids[0]
      self.assertListEqual(self.expected_src_tokens				, __UpperCAmelCase)






    def 	__snake_case							(					self				:    int):
      self.assertIn(__UpperCAmelCase				, self.tokenizer.all_special_ids)
      a						:		Tuple      							=			[RO_CODE, 884, 9019, 96, 9, 916, 86792, 36, 18743, 15596, 5, 2]
      a						:		List[Any]      							=			self.tokenizer.decode(__UpperCAmelCase				, skip_special_tokens=__UpperCAmelCase)
      a						:		List[str]      							=			self.tokenizer.decode(generated_ids[1:]				, skip_special_tokens=__UpperCAmelCase)
      self.assertEqual(__UpperCAmelCase				, __UpperCAmelCase)
      self.assertNotIn(self.tokenizer.eos_token				, __UpperCAmelCase)






    def 	__snake_case							(					self				:    List[str]):
      a						:		List[Any]      							=			["this is gunna be a long sentence " * 20]
      assert isinstance(src_text[0]				, __UpperCAmelCase)
      a						:		Tuple      							=			10
      a						:		Dict      							=			self.tokenizer(__UpperCAmelCase				, max_length=__UpperCAmelCase				, truncation=__UpperCAmelCase).input_ids[0]
      self.assertEqual(ids[-2]				, 2)
      self.assertEqual(ids[-1]				, __UpperCAmelCase)
      self.assertEqual(len(__UpperCAmelCase)				, __UpperCAmelCase)






    def 	__snake_case							(					self				:    List[str]):
      self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["<mask>", "ar_AR"])				, [250026, 250001])






    def 	__snake_case							(					self				:    str):
      a						:		List[str]      							=			tempfile.mkdtemp()
      a						:		Optional[int]      							=			self.tokenizer.fairseq_tokens_to_ids
      self.tokenizer.save_pretrained(__UpperCAmelCase)
      a						:		Dict      							=			MBartTokenizer.from_pretrained(__UpperCAmelCase)
      self.assertDictEqual(new_tok.fairseq_tokens_to_ids				, __UpperCAmelCase)






    @require_torch
    def 	__snake_case							(					self				:    Dict):
      a						:		Union[str, Any]      							=			self.tokenizer(self.src_text				, text_target=self.tgt_text				, padding=__UpperCAmelCase				, return_tensors="pt")
      a						:		Tuple      							=			shift_tokens_right(batch["labels"]				, self.tokenizer.pad_token_id)

      # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4
      assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE]
      assert batch.decoder_input_ids[1][0].tolist() == RO_CODE
      assert batch.decoder_input_ids[1][-1] == 2
      assert batch.labels[1][-2:].tolist() == [2, RO_CODE]






    @require_torch
    def 	__snake_case							(					self				:    List[Any]):
      a						:		List[Any]      							=			self.tokenizer(
          self.src_text				, text_target=self.tgt_text				, padding=__UpperCAmelCase				, truncation=__UpperCAmelCase				, max_length=len(self.expected_src_tokens)				, return_tensors="pt"				, )

      a						:		Dict      							=			shift_tokens_right(batch["labels"]				, self.tokenizer.pad_token_id)

      self.assertIsInstance(__UpperCAmelCase				, __UpperCAmelCase)

      self.assertEqual((2, 14)				, batch.input_ids.shape)
      self.assertEqual((2, 14)				, batch.attention_mask.shape)
      a						:		Tuple      							=			batch.input_ids.tolist()[0]
      self.assertListEqual(self.expected_src_tokens				, __UpperCAmelCase)
      self.assertEqual(2				, batch.decoder_input_ids[0, -1])  # EOS
      # Test that special tokens are reset
      self.assertEqual(self.tokenizer.prefix_tokens				, [])
      self.assertEqual(self.tokenizer.suffix_tokens				, [self.tokenizer.eos_token_id, EN_CODE])






    def 	__snake_case							(					self				:    Optional[int]):
      a						:		List[str]      							=			self.tokenizer(self.src_text				, padding=__UpperCAmelCase				, truncation=__UpperCAmelCase				, max_length=3				, return_tensors="pt")
      a						:		List[str]      							=			self.tokenizer(
          text_target=self.tgt_text				, padding=__UpperCAmelCase				, truncation=__UpperCAmelCase				, max_length=10				, return_tensors="pt")
      a						:		str      							=			targets["input_ids"]
      a						:		Optional[Any]      							=			shift_tokens_right(__UpperCAmelCase				, self.tokenizer.pad_token_id)

      self.assertEqual(batch.input_ids.shape[1]				, 3)
      self.assertEqual(batch.decoder_input_ids.shape[1]				, 10)






    @require_torch
    def 	__snake_case							(					self				:    Any):
      a						:		Tuple      							=			self.tokenizer._build_translation_inputs(
          "A test"				, return_tensors="pt"				, src_lang="en_XX"				, tgt_lang="ar_AR")

      self.assertEqual(
          nested_simplify(__UpperCAmelCase)				, {
              # A, test, EOS, en_XX
              "input_ids": [[62, 3034, 2, 250004]],
              "attention_mask": [[1, 1, 1, 1]],
              # ar_AR
              "forced_bos_token_id": 250001,
          }				, )










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






