

'''simple docstring'''






import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)


def 						_A	(       A__	,							A__=False ):






 """simple docstring"""



 try:
  __lowercase				    =					os.environ[key]
 except KeyError:
  # KEY isn't set, default to `default`.
  __lowercase				    =					default
 else:
  # KEY is set, convert it to True or False.
  try:
   __lowercase				    =					strtobool(UpperCAmelCase__ )
  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__   		=      parse_flag_from_env('''RUN_SLOW''', default=False)


def 						_A	(       A__ ):






 """simple docstring"""



 return unittest.skip('''Test was skipped''' )(UpperCAmelCase__ )


def 						_A	(       A__ ):






 """simple docstring"""



 return unittest.skipUnless(_run_slow_tests	,							'''test is slow''' )(UpperCAmelCase__ )


def 						_A	(       A__ ):






 """simple docstring"""



 return unittest.skipUnless(not torch.cuda.is_available()	,							'''test requires only a CPU''' )(UpperCAmelCase__ )


def 						_A	(       A__ ):






 """simple docstring"""



 return unittest.skipUnless(torch.cuda.is_available()	,							'''test requires a GPU''' )(UpperCAmelCase__ )


def 						_A	(       A__ ):






 """simple docstring"""



 return unittest.skipUnless(is_xpu_available()	,							'''test requires a XPU''' )(UpperCAmelCase__ )


def 						_A	(       A__ ):






 """simple docstring"""



 return unittest.skipUnless(is_mps_available()	,							'''test requires a `mps` backend support in `torch`''' )(UpperCAmelCase__ )


def 						_A	(       A__ ):






 """simple docstring"""



 return unittest.skipUnless(
     is_transformers_available() and is_datasets_available()	,							'''test requires the Hugging Face suite''' )(UpperCAmelCase__ )


def 						_A	(       A__ ):






 """simple docstring"""



 return unittest.skipUnless(is_bnb_available()	,							'''test requires the bitsandbytes library''' )(UpperCAmelCase__ )


def 						_A	(       A__ ):






 """simple docstring"""



 return unittest.skipUnless(is_tpu_available()	,							'''test requires TPU''' )(UpperCAmelCase__ )


def 						_A	(       A__ ):






 """simple docstring"""



 return unittest.skipUnless(torch.cuda.device_count() == 1	,							'''test requires a GPU''' )(UpperCAmelCase__ )


def 						_A	(       A__ ):






 """simple docstring"""



 return unittest.skipUnless(torch.xpu.device_count() == 1	,							'''test requires a XPU''' )(UpperCAmelCase__ )


def 						_A	(       A__ ):






 """simple docstring"""



 return unittest.skipUnless(torch.cuda.device_count() > 1	,							'''test requires multiple GPUs''' )(UpperCAmelCase__ )


def 						_A	(       A__ ):






 """simple docstring"""



 return unittest.skipUnless(torch.xpu.device_count() > 1	,							'''test requires multiple XPUs''' )(UpperCAmelCase__ )


def 						_A	(       A__ ):






 """simple docstring"""



 return unittest.skipUnless(is_safetensors_available()	,							'''test requires safetensors''' )(UpperCAmelCase__ )


def 						_A	(       A__ ):






 """simple docstring"""



 return unittest.skipUnless(is_deepspeed_available()	,							'''test requires DeepSpeed''' )(UpperCAmelCase__ )


def 						_A	(       A__ ):






 """simple docstring"""



 return unittest.skipUnless(is_torch_version('''>='''	,							'''1.12.0''' )	,							'''test requires torch version >= 1.12.0''' )(UpperCAmelCase__ )


def 						_A	(       A__=None	,							A__=None ):






 """simple docstring"""



 if test_case is None:
  return partial(UpperCAmelCase__	,							version=UpperCAmelCase__ )
 return unittest.skipUnless(is_torch_version('''>='''	,							UpperCAmelCase__ )	,							F"test requires torch version >= {version}" )(UpperCAmelCase__ )


def 						_A	(       A__ ):






 """simple docstring"""



 return unittest.skipUnless(is_tensorboard_available()	,							'''test requires Tensorboard''' )(UpperCAmelCase__ )


def 						_A	(       A__ ):






 """simple docstring"""



 return unittest.skipUnless(is_wandb_available()	,							'''test requires wandb''' )(UpperCAmelCase__ )


def 						_A	(       A__ ):






 """simple docstring"""



 return unittest.skipUnless(is_comet_ml_available()	,							'''test requires comet_ml''' )(UpperCAmelCase__ )


lowerCAmelCase__   		=      (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)


def 						_A	(       A__ ):






 """simple docstring"""



 return unittest.skipUnless(
     _atleast_one_tracker_available	,							'''test requires at least one tracker to be available and for `comet_ml` to not be installed'''	,							)(UpperCAmelCase__ )






class      lowercase_      (unittest.TestCase ):




  """simple docstring"""




  SCREAMING_SNAKE_CASE       :    Tuple							     =     True






  @classmethod
  def    SCREAMING_SNAKE_CASE ( cls  :	int     ):
   __lowercase				    =					tempfile.mkdtemp()






  @classmethod
  def    SCREAMING_SNAKE_CASE ( cls  :	List[Any]     ):



   if os.path.exists(cls.tmpdir     ):
    shutil.rmtree(cls.tmpdir     )






  def    SCREAMING_SNAKE_CASE ( self  :	Optional[Any]     ):



   if self.clear_on_setup:
    for path in Path(self.tmpdir     ).glob('''**/*'''     ):
     if path.is_file():
      path.unlink()
     elif path.is_dir():
      shutil.rmtree(__a     )






class      lowercase_      (unittest.TestCase ):




  """simple docstring"""




  def    SCREAMING_SNAKE_CASE ( self  :	Union[str, Any]     ):
   super().tearDown()
   # Reset the state of the AcceleratorState singleton.
   AcceleratorState._reset_state()
   PartialState._reset_state()






class      lowercase_      (unittest.TestCase ):




  """simple docstring"""




  def    SCREAMING_SNAKE_CASE ( self  :	List[Any]   ,lowercase__  :	str     ):
   __lowercase				    =					mocks if isinstance(__a   ,(tuple, list)     ) else [mocks]
   for m in self.mocks:
    m.start()
    self.addCleanup(m.stop     )


def 						_A	(       A__ ):






 """simple docstring"""



 __lowercase				    =					AcceleratorState()
 __lowercase				    =					tensor[None].clone().to(state.device )
 __lowercase				    =					gather(UpperCAmelCase__ ).cpu()
 __lowercase				    =					tensor[0].cpu()
 for i in range(tensors.shape[0] ):
  if not torch.equal(tensors[i]	,							UpperCAmelCase__ ):
   return False
 return True






class      lowercase_      :




  """simple docstring"""




  def __init__( self  :	List[str]   ,lowercase__  :	Dict   ,lowercase__  :	Optional[Any]   ,lowercase__  :	Union[str, Any]     ):
   __lowercase				    =					returncode
   __lowercase				    =					stdout
   __lowercase				    =					stderr


async def 						_A	(       A__	,							A__ ):






 """simple docstring"""



 while True:
  __lowercase				    =					await stream.readline()
  if line:
   callback(UpperCAmelCase__ )
  else:
   break


async def 						_A	(       A__	,							A__=None	,							A__=None	,							A__=None	,							A__=False	,							A__=False ):






 """simple docstring"""



 if echo:
  print('''\nRunning: '''	,							''' '''.join(UpperCAmelCase__ ) )

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

 # 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)

 __lowercase				    =					[]
 __lowercase				    =					[]

 def tee(A__	,							A__	,							A__	,							A__="" ):
  __lowercase				    =					line.decode('''utf-8''' ).rstrip()
  sink.append(UpperCAmelCase__ )
  if not quiet:
   print(UpperCAmelCase__	,							UpperCAmelCase__	,							file=UpperCAmelCase__ )

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


def 						_A	(       A__	,							A__=None	,							A__=None	,							A__=180	,							A__=False	,							A__=True ):






 """simple docstring"""



 __lowercase				    =					asyncio.get_event_loop()
 __lowercase				    =					loop.run_until_complete(
     _stream_subprocess(UpperCAmelCase__	,							env=UpperCAmelCase__	,							stdin=UpperCAmelCase__	,							timeout=UpperCAmelCase__	,							quiet=UpperCAmelCase__	,							echo=UpperCAmelCase__ ) )

 __lowercase				    =					''' '''.join(UpperCAmelCase__ )
 if result.returncode > 0:
  __lowercase				    =					'''\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}" )

 return result






class      lowercase_      (UpperCAmelCase_ ):




  """simple docstring"""




  pass


def 						_A	(       A__	,							A__=False ):






 """simple docstring"""



 try:
  __lowercase				    =					subprocess.check_output(UpperCAmelCase__	,							stderr=subprocess.STDOUT )
  if return_stdout:
   if hasattr(UpperCAmelCase__	,							'''decode''' ):
    __lowercase				    =					output.decode('''utf-8''' )
   return output
 except subprocess.CalledProcessError as e:
  raise SubprocessCallException(
      F"Command `{' '.join(UpperCAmelCase__ )}` failed with the following error:\n\n{e.output.decode()}" ) from e






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, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()





class  lowerCamelCase__	(    unittest.TestCase):
     """simple docstring"""



     def     _a   (self     ):






           '''simple docstring'''



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







     @property
     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		1
           lowerCamelCase             =		3
           lowerCamelCase             =		(32, 32)

           lowerCamelCase             =		floats_tensor((batch_size, num_channels) + sizes					,      rng=random.Random(0     )     ).to(__a     )
           return image







     @property
     def     _a   (self     ):






           '''simple docstring'''



           torch.manual_seed(0     )
           lowerCamelCase             =		UNetaDConditionModel(
               block_out_channels=(32, 32, 64)					,      layers_per_block=2					,      sample_size=32					,      in_channels=7					,      out_channels=4					,      down_block_types=("DownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D")					,      up_block_types=("CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "UpBlock2D")					,      cross_attention_dim=32					,      attention_head_dim=8					,      use_linear_projection=__a					,      only_cross_attention=(True, True, False)					,      num_class_embeds=1_00					,      )
           return model







     @property
     def     _a   (self     ):






           '''simple docstring'''



           torch.manual_seed(0     )
           lowerCamelCase             =		AutoencoderKL(
               block_out_channels=[32, 32, 64]					,      in_channels=3					,      out_channels=3					,      down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D"]					,      up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"]					,      latent_channels=4					,      )
           return model







     @property
     def     _a   (self     ):






           '''simple docstring'''



           torch.manual_seed(0     )
           lowerCamelCase             =		CLIPTextConfig(
               bos_token_id=0					,      eos_token_id=2					,      hidden_size=32					,      intermediate_size=37					,      layer_norm_eps=1E-05					,      num_attention_heads=4					,      num_hidden_layers=5					,      pad_token_id=1					,      vocab_size=10_00					,      hidden_act="gelu"					,      projection_dim=5_12					,      )
           return CLIPTextModel(__a     )







     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		"cpu"  # ensure determinism for the device-dependent torch.Generator
           lowerCamelCase             =		self.dummy_cond_unet_upscale
           lowerCamelCase             =		DDPMScheduler()
           lowerCamelCase             =		DDIMScheduler(prediction_type="v_prediction"     )
           lowerCamelCase             =		self.dummy_vae
           lowerCamelCase             =		self.dummy_text_encoder
           lowerCamelCase             =		CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"     )

           lowerCamelCase             =		self.dummy_image.cpu().permute(0					,      2					,      3					,      1     )[0]
           lowerCamelCase             =		Image.fromarray(np.uinta(__a     )     ).convert("RGB"     ).resize((64, 64)     )

           # make sure here that pndm scheduler skips prk
           lowerCamelCase             =		StableDiffusionUpscalePipeline(
               unet=__a					,      low_res_scheduler=__a					,      scheduler=__a					,      vae=__a					,      text_encoder=__a					,      tokenizer=__a					,      max_noise_level=3_50					,      )
           lowerCamelCase             =		sd_pipe.to(__a     )
           sd_pipe.set_progress_bar_config(disable=__a     )

           lowerCamelCase             =		"A painting of a squirrel eating a burger"
           lowerCamelCase             =		torch.Generator(device=__a     ).manual_seed(0     )
           lowerCamelCase             =		sd_pipe(
               [prompt]					,      image=__a					,      generator=__a					,      guidance_scale=6.0					,      noise_level=20					,      num_inference_steps=2					,      output_type="np"					,      )

           lowerCamelCase             =		output.images

           lowerCamelCase             =		torch.Generator(device=__a     ).manual_seed(0     )
           lowerCamelCase             =		sd_pipe(
               [prompt]					,      image=__a					,      generator=__a					,      guidance_scale=6.0					,      noise_level=20					,      num_inference_steps=2					,      output_type="np"					,      return_dict=__a					,      )[0]

           lowerCamelCase             =		image[0, -3:, -3:, -1]
           lowerCamelCase             =		image_from_tuple[0, -3:, -3:, -1]

           lowerCamelCase             =		low_res_image.size[0] * 4
           assert image.shape == (1, expected_height_width, expected_height_width, 3)
           lowerCamelCase             =		np.array([0.3113, 0.3910, 0.4272, 0.4859, 0.5061, 0.4652, 0.5362, 0.5715, 0.5661]     )

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







     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		"cpu"  # ensure determinism for the device-dependent torch.Generator
           lowerCamelCase             =		self.dummy_cond_unet_upscale
           lowerCamelCase             =		DDPMScheduler()
           lowerCamelCase             =		DDIMScheduler(prediction_type="v_prediction"     )
           lowerCamelCase             =		self.dummy_vae
           lowerCamelCase             =		self.dummy_text_encoder
           lowerCamelCase             =		CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"     )

           lowerCamelCase             =		self.dummy_image.cpu().permute(0					,      2					,      3					,      1     )[0]
           lowerCamelCase             =		Image.fromarray(np.uinta(__a     )     ).convert("RGB"     ).resize((64, 64)     )

           # make sure here that pndm scheduler skips prk
           lowerCamelCase             =		StableDiffusionUpscalePipeline(
               unet=__a					,      low_res_scheduler=__a					,      scheduler=__a					,      vae=__a					,      text_encoder=__a					,      tokenizer=__a					,      max_noise_level=3_50					,      )
           lowerCamelCase             =		sd_pipe.to(__a     )
           sd_pipe.set_progress_bar_config(disable=__a     )

           lowerCamelCase             =		"A painting of a squirrel eating a burger"
           lowerCamelCase             =		sd_pipe(
               2 * [prompt]					,      image=2 * [low_res_image]					,      guidance_scale=6.0					,      noise_level=20					,      num_inference_steps=2					,      output_type="np"					,      )
           lowerCamelCase             =		output.images
           assert image.shape[0] == 2

           lowerCamelCase             =		torch.Generator(device=__a     ).manual_seed(0     )
           lowerCamelCase             =		sd_pipe(
               [prompt]					,      image=__a					,      generator=__a					,      num_images_per_prompt=2					,      guidance_scale=6.0					,      noise_level=20					,      num_inference_steps=2					,      output_type="np"					,      )
           lowerCamelCase             =		output.images
           assert image.shape[0] == 2







     @unittest.skipIf(torch_device != "cuda"					,      "This test requires a GPU"     )
     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		self.dummy_cond_unet_upscale
           lowerCamelCase             =		DDPMScheduler()
           lowerCamelCase             =		DDIMScheduler(prediction_type="v_prediction"     )
           lowerCamelCase             =		self.dummy_vae
           lowerCamelCase             =		self.dummy_text_encoder
           lowerCamelCase             =		CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"     )

           lowerCamelCase             =		self.dummy_image.cpu().permute(0					,      2					,      3					,      1     )[0]
           lowerCamelCase             =		Image.fromarray(np.uinta(__a     )     ).convert("RGB"     ).resize((64, 64)     )

           # put models in fp16, except vae as it overflows in fp16
           lowerCamelCase             =		unet.half()
           lowerCamelCase             =		text_encoder.half()

           # make sure here that pndm scheduler skips prk
           lowerCamelCase             =		StableDiffusionUpscalePipeline(
               unet=__a					,      low_res_scheduler=__a					,      scheduler=__a					,      vae=__a					,      text_encoder=__a					,      tokenizer=__a					,      max_noise_level=3_50					,      )
           lowerCamelCase             =		sd_pipe.to(__a     )
           sd_pipe.set_progress_bar_config(disable=__a     )

           lowerCamelCase             =		"A painting of a squirrel eating a burger"
           lowerCamelCase             =		torch.manual_seed(0     )
           lowerCamelCase             =		sd_pipe(
               [prompt]					,      image=__a					,      generator=__a					,      num_inference_steps=2					,      output_type="np"					,      ).images

           lowerCamelCase             =		low_res_image.size[0] * 4
           assert image.shape == (1, expected_height_width, expected_height_width, 3)





@slow
@require_torch_gpu
class  lowerCamelCase__	(    unittest.TestCase):
     """simple docstring"""



     def     _a   (self     ):






           '''simple docstring'''



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







     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		load_image(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
               "/sd2-upscale/low_res_cat.png"     )
           lowerCamelCase             =		load_numpy(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale"
               "/upsampled_cat.npy"     )

           lowerCamelCase             =		"stabilityai/stable-diffusion-x4-upscaler"
           lowerCamelCase             =		StableDiffusionUpscalePipeline.from_pretrained(__a     )
           pipe.to(__a     )
           pipe.set_progress_bar_config(disable=__a     )
           pipe.enable_attention_slicing()

           lowerCamelCase             =		"a cat sitting on a park bench"

           lowerCamelCase             =		torch.manual_seed(0     )
           lowerCamelCase             =		pipe(
               prompt=__a					,      image=__a					,      generator=__a					,      output_type="np"					,      )
           lowerCamelCase             =		output.images[0]

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







     def     _a   (self     ):






           '''simple docstring'''



           lowerCamelCase             =		load_image(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
               "/sd2-upscale/low_res_cat.png"     )
           lowerCamelCase             =		load_numpy(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale"
               "/upsampled_cat_fp16.npy"     )

           lowerCamelCase             =		"stabilityai/stable-diffusion-x4-upscaler"
           lowerCamelCase             =		StableDiffusionUpscalePipeline.from_pretrained(
               __a					,      torch_dtype=torch.floataa					,      )
           pipe.to(__a     )
           pipe.set_progress_bar_config(disable=__a     )
           pipe.enable_attention_slicing()

           lowerCamelCase             =		"a cat sitting on a park bench"

           lowerCamelCase             =		torch.manual_seed(0     )
           lowerCamelCase             =		pipe(
               prompt=__a					,      image=__a					,      generator=__a					,      output_type="np"					,      )
           lowerCamelCase             =		output.images[0]

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







     def     _a   (self     ):






           '''simple docstring'''



           torch.cuda.empty_cache()
           torch.cuda.reset_max_memory_allocated()
           torch.cuda.reset_peak_memory_stats()

           lowerCamelCase             =		load_image(
               "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
               "/sd2-upscale/low_res_cat.png"     )

           lowerCamelCase             =		"stabilityai/stable-diffusion-x4-upscaler"
           lowerCamelCase             =		StableDiffusionUpscalePipeline.from_pretrained(
               __a					,      torch_dtype=torch.floataa					,      )
           pipe.to(__a     )
           pipe.set_progress_bar_config(disable=__a     )
           pipe.enable_attention_slicing(1     )
           pipe.enable_sequential_cpu_offload()

           lowerCamelCase             =		"a cat sitting on a park bench"

           lowerCamelCase             =		torch.manual_seed(0     )
           lowerCamelCase             =		pipe(
               prompt=__a					,      image=__a					,      generator=__a					,      num_inference_steps=5					,      output_type="np"					,      )

           lowerCamelCase             =		torch.cuda.max_memory_allocated()
           # make sure that less than 2.9 GB is allocated
           assert mem_bytes < 2.9 * 10**9