




import asyncio
import os
import re
import sys
import tempfile
import unittest
from contextlib import contextmanager
from copy import deepcopy
from distutils.util import strtobool
from enum import Enum
from importlib.util import find_spec
from pathlib import Path
from unittest.mock import patch

import pyarrow as pa
import pytest
import requests
from packaging import version

from datasets import config


if config.PY_VERSION < version.parse('3.8'):
       import importlib_metadata
else:
       import importlib.metadata as importlib_metadata




def 						SCREAMING_SNAKE_CASE__ (   lowercase						,lowercase=False					)  ->       Optional[Any]:
   try:
      snake_case				:    Optional[int]           =	os.environ[key]
   except KeyError:
      # KEY isn't set, default to `default`.
      snake_case				:    Any           =	default
   else:
      # KEY is set, convert it to True or False.
      try:
         snake_case				:    Optional[Any]           =	strtobool(lowercase					)
      except ValueError:
         # More values are supported, but let's keep the message simple.
         raise ValueError(f"""If set, {key} must be yes or no."""					)
   return _value


lowerCamelCase	:	Optional[Any]				=   parse_flag_from_env('RUN_SLOW', default=False)
lowerCamelCase	:	List[Any]				=   parse_flag_from_env('RUN_REMOTE', default=False)
lowerCamelCase	:	List[Any]				=   parse_flag_from_env('RUN_LOCAL', default=True)
lowerCamelCase	:	Dict				=   parse_flag_from_env('RUN_PACKAGED', default=True)

# Compression
lowerCamelCase	:	Optional[Any]				=   pytest.mark.skipif(not config.LZ4_AVAILABLE, reason='test requires lz4')
lowerCamelCase	:	Optional[Any]				=   pytest.mark.skipif(not config.PY7ZR_AVAILABLE, reason='test requires py7zr')
lowerCamelCase	:	Dict				=   pytest.mark.skipif(not config.ZSTANDARD_AVAILABLE, reason='test requires zstandard')

# Audio
lowerCamelCase	:	List[Any]				=   pytest.mark.skipif(
    # On Windows and OS X, soundfile installs sndfile
    find_spec('soundfile') is None or version.parse(importlib_metadata.version('soundfile')) < version.parse('0.12.0'),
    reason='test requires sndfile>=0.12.1: \'pip install \"soundfile>=0.12.1\"\'; ',
)

# Beam
lowerCamelCase	:	Optional[int]				=   pytest.mark.skipif(
    not config.BEAM_AVAILABLE or config.DILL_VERSION >= version.parse('0.3.2'),
    reason='test requires apache-beam and a compatible dill version',
)

# Dill-cloudpickle compatibility
lowerCamelCase	:	Tuple				=   pytest.mark.skipif(
    config.DILL_VERSION <= version.parse('0.3.2'),
    reason='test requires dill>0.3.2 for cloudpickle compatibility',
)

# Windows
lowerCamelCase	:	Tuple				=   pytest.mark.skipif(
    sys.platform == 'win32',
    reason='test should not be run on Windows',
)




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       int:
   try:
      import faiss  # noqa
   except ImportError:
      snake_case				:    int           =	unittest.skip("""test requires faiss"""					)(lowercase					)
   return test_case




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       List[str]:
   try:
      import regex  # noqa
   except ImportError:
      snake_case				:    str           =	unittest.skip("""test requires regex"""					)(lowercase					)
   return test_case




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       Dict:
   try:
      import elasticsearch  # noqa
   except ImportError:
      snake_case				:    Optional[Any]           =	unittest.skip("""test requires elasticsearch"""					)(lowercase					)
   return test_case




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       Tuple:
   try:
      import sqlalchemy  # noqa
   except ImportError:
      snake_case				:    int           =	unittest.skip("""test requires sqlalchemy"""					)(lowercase					)
   return test_case




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       List[Any]:
   if not config.TORCH_AVAILABLE:
      snake_case				:    Dict           =	unittest.skip("""test requires PyTorch"""					)(lowercase					)
   return test_case




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       str:
   if not config.TF_AVAILABLE:
      snake_case				:    Optional[int]           =	unittest.skip("""test requires TensorFlow"""					)(lowercase					)
   return test_case




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       List[str]:
   if not config.JAX_AVAILABLE:
      snake_case				:    List[Any]           =	unittest.skip("""test requires JAX"""					)(lowercase					)
   return test_case




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       List[Any]:
   if not config.PIL_AVAILABLE:
      snake_case				:    Dict           =	unittest.skip("""test requires Pillow"""					)(lowercase					)
   return test_case




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       Union[str, Any]:
   try:
      import transformers  # noqa F401
   except ImportError:
      return unittest.skip("""test requires transformers"""					)(lowercase					)
   else:
      return test_case




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       int:
   try:
      import tiktoken  # noqa F401
   except ImportError:
      return unittest.skip("""test requires tiktoken"""					)(lowercase					)
   else:
      return test_case




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       List[Any]:
   try:
      import spacy  # noqa F401
   except ImportError:
      return unittest.skip("""test requires spacy"""					)(lowercase					)
   else:
      return test_case




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       Tuple:

   def _require_spacy_model(lowercase					):
      try:
         import spacy  # noqa F401

         spacy.load(lowercase					)
      except ImportError:
         return unittest.skip("""test requires spacy"""					)(lowercase					)
      except OSError:
         return unittest.skip("""test requires spacy model '{}'""".format(lowercase					)					)(lowercase					)
      else:
         return test_case

   return _require_spacy_model




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       Any:
   try:
      import pyspark  # noqa F401
   except ImportError:
      return unittest.skip("""test requires pyspark"""					)(lowercase					)
   else:
      return test_case




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       Any:
   try:
      import joblibspark  # noqa F401
   except ImportError:
      return unittest.skip("""test requires joblibspark"""					)(lowercase					)
   else:
      return test_case




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       List[str]:
   if not _run_slow_tests or _run_slow_tests == 0:
      snake_case				:    int           =	unittest.skip("""test is slow"""					)(lowercase					)
   return test_case




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       Dict:
   if not _run_local_tests or _run_local_tests == 0:
      snake_case				:    Any           =	unittest.skip("""test is local"""					)(lowercase					)
   return test_case




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       Tuple:
   if not _run_packaged_tests or _run_packaged_tests == 0:
      snake_case				:    Union[str, Any]           =	unittest.skip("""test is packaged"""					)(lowercase					)
   return test_case




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       Any:
   if not _run_remote_tests or _run_remote_tests == 0:
      snake_case				:    Tuple           =	unittest.skip("""test requires remote"""					)(lowercase					)
   return test_case




def 						SCREAMING_SNAKE_CASE__ (   *lowercase					)  ->       List[Any]:
   def decorate(cls					):
      for name, fn in cls.__dict__.items():
         if callable(lowercase					) and name.startswith("""test"""					):
            for decorator in decorators:
               snake_case				:    Optional[Any]           =	decorator(lowercase					)
            setattr(cls						,lowercase						,lowercase					)
      return cls

   return decorate




class 						__lowercase		(UpperCamelCase__							):




      """simple docstring"""





      pass




class 						__lowercase		(UpperCamelCase__							):




      """simple docstring"""





      _snake_case												=						0
      _snake_case												=						1
      _snake_case												=						2




@contextmanager
def 						SCREAMING_SNAKE_CASE__ (   lowercase=OfflineSimulationMode.CONNECTION_FAILS						,lowercase=1E-16					)  ->       str:
   snake_case				:    Optional[Any]           =	requests.Session().request

   def timeout_request(lowercase						,lowercase						,lowercase						,**lowercase					):
      # Change the url to an invalid url so that the connection hangs
      snake_case				:    Union[str, Any]           =	"""https://10.255.255.1"""
      if kwargs.get("""timeout"""					) is None:
         raise RequestWouldHangIndefinitelyError(
             f"""Tried a call to {url} in offline mode with no timeout set. Please set a timeout."""					)
      snake_case				:    Any           =	timeout
      try:
         return online_request(lowercase						,lowercase						,**lowercase					)
      except Exception as e:
         # The following changes in the error are just here to make the offline timeout error prettier
         snake_case				:    List[Any]           =	url
         snake_case				:    List[Any]           =	e.args[0]
         snake_case				:    int           =	(max_retry_error.args[0].replace("""10.255.255.1"""						,f"""OfflineMock[{url}]"""					),)
         snake_case				:    Optional[Any]           =	(max_retry_error,)
         raise

   def raise_connection_error(lowercase						,lowercase						,**lowercase					):
      raise requests.ConnectionError("""Offline mode is enabled."""						,request=lowercase					)

   if mode is OfflineSimulationMode.CONNECTION_FAILS:
      with patch("""requests.Session.send"""						,lowercase					):
         yield
   elif mode is OfflineSimulationMode.CONNECTION_TIMES_OUT:
      # inspired from https://stackoverflow.com/a/904609
      with patch("""requests.Session.request"""						,lowercase					):
         yield
   elif mode is OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1:
      with patch("""datasets.config.HF_DATASETS_OFFLINE"""						,lowercase					):
         yield
   else:
      raise ValueError("""Please use a value from the OfflineSimulationMode enum."""					)




@contextmanager
def 						SCREAMING_SNAKE_CASE__ (   *lowercase						,**lowercase					)  ->       Union[str, Any]:
   snake_case				:    List[str]           =	str(Path().resolve()					)
   with tempfile.TemporaryDirectory(*lowercase						,**lowercase					) as tmp_dir:
      try:
         os.chdir(lowercase					)
         yield
      finally:
         os.chdir(lowercase					)




@contextmanager
def 						SCREAMING_SNAKE_CASE__ (   )  ->       Tuple:
   import gc

   gc.collect()
   snake_case				:    Optional[Any]           =	pa.total_allocated_bytes()
   yield
   assert pa.total_allocated_bytes() - previous_allocated_memory > 0, "Arrow memory didn't increase."




@contextmanager
def 						SCREAMING_SNAKE_CASE__ (   )  ->       Union[str, Any]:
   import gc

   gc.collect()
   snake_case				:    Tuple           =	pa.total_allocated_bytes()
   yield
   assert pa.total_allocated_bytes() - previous_allocated_memory <= 0, "Arrow memory wasn't expected to increase."




def 						SCREAMING_SNAKE_CASE__ (   lowercase						,lowercase					)  ->       Union[str, Any]:
   return deepcopy(lowercase					).integers(0						,100						,10					).tolist() == deepcopy(lowercase					).integers(0						,100						,10					).tolist()




def 						SCREAMING_SNAKE_CASE__ (   lowercase					)  ->       int:
   import decorator
   from requests.exceptions import HTTPError

   def _wrapper(lowercase						,*lowercase						,**lowercase					):
      try:
         return func(*lowercase						,**lowercase					)
      except HTTPError as err:
         if str(lowercase					).startswith("""500"""					) or str(lowercase					).startswith("""502"""					):
            pytest.xfail(str(lowercase					)					)
         raise err

   return decorator.decorator(_wrapper						,lowercase					)




class 						__lowercase		:




      """simple docstring"""





      def __init__(				self    ,				A    ,				A    ,				A     )		->    List[str]:
         snake_case				:    int           =	returncode
         snake_case				:    Any           =	stdout
         snake_case				:    int           =	stderr




async def 						SCREAMING_SNAKE_CASE__ (   lowercase						,lowercase					)  ->       Optional[int]:
   while True:
      snake_case				:    List[str]           =	await stream.readline()
      if line:
         callback(lowercase					)
      else:
         break




async def 						SCREAMING_SNAKE_CASE__ (   lowercase						,lowercase=None						,lowercase=None						,lowercase=None						,lowercase=False						,lowercase=False					)  ->       _RunOutput:
   if echo:
      print("""\nRunning: """						,""" """.join(lowercase					)					)

   snake_case				:    Dict           =	await asyncio.create_subprocess_exec(
       cmd[0]						,*cmd[1:]						,stdin=lowercase						,stdout=asyncio.subprocess.PIPE						,stderr=asyncio.subprocess.PIPE						,env=lowercase						,)

   # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
   # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
   #
   # If it starts hanging, will need to switch to the following code. The problem is that no data
   # will be seen until it's done and if it hangs for example there will be no debug info.
   # out, err = await p.communicate()
   # return _RunOutput(p.returncode, out, err)

   snake_case				:    Optional[int]           =	[]
   snake_case				:    Optional[Any]           =	[]

   def tee(lowercase						,lowercase						,lowercase						,lowercase=""					):
      snake_case				:    List[Any]           =	line.decode("""utf-8"""					).rstrip()
      sink.append(lowercase					)
      if not quiet:
         print(lowercase						,lowercase						,file=lowercase					)

    # XXX: the timeout doesn't seem to make any difference here
   await asyncio.wait(
       [
           _read_stream(p.stdout						,lambda lowercase					: tee(lowercase						,lowercase						,sys.stdout						,label="""stdout:"""					)					),
           _read_stream(p.stderr						,lambda lowercase					: tee(lowercase						,lowercase						,sys.stderr						,label="""stderr:"""					)					),
       ]						,timeout=lowercase						,)
   return _RunOutput(await p.wait()						,lowercase						,lowercase					)




def 						SCREAMING_SNAKE_CASE__ (   lowercase						,lowercase=None						,lowercase=None						,lowercase=180						,lowercase=False						,lowercase=True					)  ->       _RunOutput:
   snake_case				:    Union[str, Any]           =	asyncio.get_event_loop()
   snake_case				:    Dict           =	loop.run_until_complete(
       _stream_subprocess(lowercase						,env=lowercase						,stdin=lowercase						,timeout=lowercase						,quiet=lowercase						,echo=lowercase					)					)

   snake_case				:    Any           =	""" """.join(lowercase					)
   if result.returncode > 0:
      snake_case				:    Tuple           =	"""\n""".join(result.stderr					)
      raise RuntimeError(
          f"""'{cmd_str}' failed with returncode {result.returncode}\n\n"""
          f"""The combined stderr from workers follows:\n{stderr}"""					)

   # check that the subprocess actually did run and produced some output, should the test rely on
   # the remote side to do the testing
   if not result.stdout and not result.stderr:
      raise RuntimeError(f"""'{cmd_str}' produced no output."""					)

   return result




def 						SCREAMING_SNAKE_CASE__ (   )  ->       List[str]:
   snake_case				:    Optional[Any]           =	os.environ.get("""PYTEST_XDIST_WORKER"""						,"""gw0"""					)
   snake_case				:    int           =	re.sub(R"""^gw"""						,""""""						,lowercase						,0						,re.M					)
   return int(lowercase					)




def 						SCREAMING_SNAKE_CASE__ (   )  ->       Any:
   snake_case				:    List[str]           =	29500
   snake_case				:    List[str]           =	pytest_xdist_worker_id()
   return port + uniq_delta











import gc
import random
import unittest

import torch

from diffusers import (
    IFImgaImgPipeline,
    IFImgaImgSuperResolutionPipeline,
    IFInpaintingPipeline,
    IFInpaintingSuperResolutionPipeline,
    IFPipeline,
    IFSuperResolutionPipeline,
)
from diffusers.models.attention_processor import AttnAddedKVProcessor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
from . import IFPipelineTesterMixin




@skip_mps
class 						__lowercase		(UpperCamelCase__					,		UpperCamelCase__					,		unittest.TestCase							):




      """simple docstring"""





      _snake_case												=						IFPipeline
      _snake_case												=						TEXT_TO_IMAGE_PARAMS - {"""width""", """height""", """latents"""}
      _snake_case												=						TEXT_TO_IMAGE_BATCH_PARAMS
      _snake_case												=						PipelineTesterMixin.required_optional_params - {"""latents"""}

      def      UpperCAmelCase				(				self     )		->    Any:
         return self._get_dummy_components()

      def      UpperCAmelCase				(				self    ,				A    ,				A=0     )		->    Optional[int]:
         if str(A     ).startswith("""mps"""     ):
            snake_case				:    List[str]           =	torch.manual_seed(A     )
         else:
            snake_case				:    Optional[int]           =	torch.Generator(device=A     ).manual_seed(A     )

         snake_case				:    Optional[int]           =	{
             """prompt""": """A painting of a squirrel eating a burger""",
             """generator""": generator,
             """num_inference_steps""": 2,
             """output_type""": """numpy""",
         }

         return inputs

      def      UpperCAmelCase				(				self     )		->    Any:
         self._test_save_load_optional_components()

      @unittest.skipIf(torch_device != """cuda"""    ,				reason="""float16 requires CUDA"""     )
      def      UpperCAmelCase				(				self     )		->    List[str]:
         # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
         super().test_save_load_floataa(expected_max_diff=1e-1     )

      def      UpperCAmelCase				(				self     )		->    Dict:
         self._test_attention_slicing_forward_pass(expected_max_diff=1e-2     )

      def      UpperCAmelCase				(				self     )		->    List[str]:
         self._test_save_load_local()

      def      UpperCAmelCase				(				self     )		->    List[str]:
         self._test_inference_batch_single_identical(
             expected_max_diff=1e-2    ,				)

      @unittest.skipIf(
          torch_device != """cuda""" or not is_xformers_available()    ,				reason="""XFormers attention is only available with CUDA and `xformers` installed"""    ,				)
      def      UpperCAmelCase				(				self     )		->    List[str]:
         self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3     )




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




      """simple docstring"""





      def      UpperCAmelCase				(				self     )		->    Any:
         # clean up the VRAM after each test
         super().tearDown()
         gc.collect()
         torch.cuda.empty_cache()

      def      UpperCAmelCase				(				self     )		->    List[Any]:
         # if

         snake_case				:    Tuple           =	IFPipeline.from_pretrained("""DeepFloyd/IF-I-XL-v1.0"""    ,				variant="""fp16"""    ,				torch_dtype=torch.floataa     )

         snake_case				:    Tuple           =	IFSuperResolutionPipeline.from_pretrained(
             """DeepFloyd/IF-II-L-v1.0"""    ,				variant="""fp16"""    ,				torch_dtype=torch.floataa    ,				text_encoder=A    ,				tokenizer=A     )

         # pre compute text embeddings and remove T5 to save memory

         pipe_a.text_encoder.to("""cuda"""     )

         snake_case     , snake_case				:    Optional[int]           =	pipe_a.encode_prompt("""anime turtle"""    ,				device="""cuda"""     )

         del pipe_a.tokenizer
         del pipe_a.text_encoder
         gc.collect()

         snake_case				:    List[str]           =	None
         snake_case				:    List[Any]           =	None

         pipe_a.enable_model_cpu_offload()
         pipe_a.enable_model_cpu_offload()

         pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()     )
         pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()     )

         self._test_if(A    ,				A    ,				A    ,				A     )

         pipe_a.remove_all_hooks()
         pipe_a.remove_all_hooks()

         # img2img

         snake_case				:    Any           =	IFImgaImgPipeline(**pipe_a.components     )
         snake_case				:    Dict           =	IFImgaImgSuperResolutionPipeline(**pipe_a.components     )

         pipe_a.enable_model_cpu_offload()
         pipe_a.enable_model_cpu_offload()

         pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()     )
         pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()     )

         self._test_if_imgaimg(A    ,				A    ,				A    ,				A     )

         pipe_a.remove_all_hooks()
         pipe_a.remove_all_hooks()

         # inpainting

         snake_case				:    Optional[Any]           =	IFInpaintingPipeline(**pipe_a.components     )
         snake_case				:    Any           =	IFInpaintingSuperResolutionPipeline(**pipe_a.components     )

         pipe_a.enable_model_cpu_offload()
         pipe_a.enable_model_cpu_offload()

         pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()     )
         pipe_a.unet.set_attn_processor(AttnAddedKVProcessor()     )

         self._test_if_inpainting(A    ,				A    ,				A    ,				A     )

      def      UpperCAmelCase				(				self    ,				A    ,				A    ,				A    ,				A     )		->    str:
         # pipeline 1

         _start_torch_memory_measurement()

         snake_case				:    Tuple           =	torch.Generator(device="""cpu"""     ).manual_seed(0     )
         snake_case				:    Tuple           =	pipe_a(
             prompt_embeds=A    ,				negative_prompt_embeds=A    ,				num_inference_steps=2    ,				generator=A    ,				output_type="""np"""    ,				)

         snake_case				:    Optional[int]           =	output.images[0]

         assert image.shape == (6_4, 6_4, 3)

         snake_case				:    Tuple           =	torch.cuda.max_memory_allocated()
         assert mem_bytes < 1_3 * 1_0**9

         snake_case				:    Dict           =	load_numpy(
             """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy"""     )
         assert_mean_pixel_difference(A    ,				A     )

         # pipeline 2

         _start_torch_memory_measurement()

         snake_case				:    List[Any]           =	torch.Generator(device="""cpu"""     ).manual_seed(0     )

         snake_case				:    Optional[int]           =	floats_tensor((1, 3, 6_4, 6_4)    ,				rng=random.Random(0     )     ).to(A     )

         snake_case				:    str           =	pipe_a(
             prompt_embeds=A    ,				negative_prompt_embeds=A    ,				image=A    ,				generator=A    ,				num_inference_steps=2    ,				output_type="""np"""    ,				)

         snake_case				:    str           =	output.images[0]

         assert image.shape == (2_5_6, 2_5_6, 3)

         snake_case				:    Any           =	torch.cuda.max_memory_allocated()
         assert mem_bytes < 4 * 1_0**9

         snake_case				:    int           =	load_numpy(
             """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy"""     )
         assert_mean_pixel_difference(A    ,				A     )

      def      UpperCAmelCase				(				self    ,				A    ,				A    ,				A    ,				A     )		->    int:
         # pipeline 1

         _start_torch_memory_measurement()

         snake_case				:    Optional[Any]           =	floats_tensor((1, 3, 6_4, 6_4)    ,				rng=random.Random(0     )     ).to(A     )

         snake_case				:    List[str]           =	torch.Generator(device="""cpu"""     ).manual_seed(0     )

         snake_case				:    Union[str, Any]           =	pipe_a(
             prompt_embeds=A    ,				negative_prompt_embeds=A    ,				image=A    ,				num_inference_steps=2    ,				generator=A    ,				output_type="""np"""    ,				)

         snake_case				:    Optional[int]           =	output.images[0]

         assert image.shape == (6_4, 6_4, 3)

         snake_case				:    Tuple           =	torch.cuda.max_memory_allocated()
         assert mem_bytes < 1_0 * 1_0**9

         snake_case				:    Union[str, Any]           =	load_numpy(
             """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy"""     )
         assert_mean_pixel_difference(A    ,				A     )

         # pipeline 2

         _start_torch_memory_measurement()

         snake_case				:    int           =	torch.Generator(device="""cpu"""     ).manual_seed(0     )

         snake_case				:    int           =	floats_tensor((1, 3, 2_5_6, 2_5_6)    ,				rng=random.Random(0     )     ).to(A     )
         snake_case				:    Optional[Any]           =	floats_tensor((1, 3, 6_4, 6_4)    ,				rng=random.Random(0     )     ).to(A     )

         snake_case				:    int           =	pipe_a(
             prompt_embeds=A    ,				negative_prompt_embeds=A    ,				image=A    ,				original_image=A    ,				generator=A    ,				num_inference_steps=2    ,				output_type="""np"""    ,				)

         snake_case				:    List[Any]           =	output.images[0]

         assert image.shape == (2_5_6, 2_5_6, 3)

         snake_case				:    Tuple           =	torch.cuda.max_memory_allocated()
         assert mem_bytes < 4 * 1_0**9

         snake_case				:    Any           =	load_numpy(
             """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy"""     )
         assert_mean_pixel_difference(A    ,				A     )

      def      UpperCAmelCase				(				self    ,				A    ,				A    ,				A    ,				A     )		->    Any:
         # pipeline 1

         _start_torch_memory_measurement()

         snake_case				:    List[Any]           =	floats_tensor((1, 3, 6_4, 6_4)    ,				rng=random.Random(0     )     ).to(A     )
         snake_case				:    Union[str, Any]           =	floats_tensor((1, 3, 6_4, 6_4)    ,				rng=random.Random(1     )     ).to(A     )

         snake_case				:    Dict           =	torch.Generator(device="""cpu"""     ).manual_seed(0     )
         snake_case				:    Tuple           =	pipe_a(
             prompt_embeds=A    ,				negative_prompt_embeds=A    ,				image=A    ,				mask_image=A    ,				num_inference_steps=2    ,				generator=A    ,				output_type="""np"""    ,				)

         snake_case				:    Tuple           =	output.images[0]

         assert image.shape == (6_4, 6_4, 3)

         snake_case				:    List[str]           =	torch.cuda.max_memory_allocated()
         assert mem_bytes < 1_0 * 1_0**9

         snake_case				:    Dict           =	load_numpy(
             """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy"""     )
         assert_mean_pixel_difference(A    ,				A     )

         # pipeline 2

         _start_torch_memory_measurement()

         snake_case				:    Optional[int]           =	torch.Generator(device="""cpu"""     ).manual_seed(0     )

         snake_case				:    int           =	floats_tensor((1, 3, 6_4, 6_4)    ,				rng=random.Random(0     )     ).to(A     )
         snake_case				:    Any           =	floats_tensor((1, 3, 2_5_6, 2_5_6)    ,				rng=random.Random(0     )     ).to(A     )
         snake_case				:    str           =	floats_tensor((1, 3, 2_5_6, 2_5_6)    ,				rng=random.Random(1     )     ).to(A     )

         snake_case				:    List[str]           =	pipe_a(
             prompt_embeds=A    ,				negative_prompt_embeds=A    ,				image=A    ,				mask_image=A    ,				original_image=A    ,				generator=A    ,				num_inference_steps=2    ,				output_type="""np"""    ,				)

         snake_case				:    List[Any]           =	output.images[0]

         assert image.shape == (2_5_6, 2_5_6, 3)

         snake_case				:    Union[str, Any]           =	torch.cuda.max_memory_allocated()
         assert mem_bytes < 4 * 1_0**9

         snake_case				:    str           =	load_numpy(
             """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy"""     )
         assert_mean_pixel_difference(A    ,				A     )




def 						SCREAMING_SNAKE_CASE__ (   )  ->       str:
   torch.cuda.empty_cache()
   torch.cuda.reset_max_memory_allocated()
   torch.cuda.reset_peak_memory_stats()





