





'''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        UpperCamelCase__				(		lowerCAmelCase							,     lowerCAmelCase=False  ):





      """simple docstring"""


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


A__    :       Union[str, Any]              =parse_flag_from_env('''RUN_SLOW''', default=False)
def        UpperCamelCase__				(		lowerCAmelCase  ):





      """simple docstring"""


      return unittest.skip("""Test was skipped"""  )(A__  )
def        UpperCamelCase__				(		lowerCAmelCase  ):





      """simple docstring"""


      return unittest.skipUnless(_run_slow_tests							,     """test is slow"""  )(A__  )
def        UpperCamelCase__				(		lowerCAmelCase  ):





      """simple docstring"""


      return unittest.skipUnless(not torch.cuda.is_available()							,     """test requires only a CPU"""  )(A__  )
def        UpperCamelCase__				(		lowerCAmelCase  ):





      """simple docstring"""


      return unittest.skipUnless(torch.cuda.is_available()							,     """test requires a GPU"""  )(A__  )
def        UpperCamelCase__				(		lowerCAmelCase  ):





      """simple docstring"""


      return unittest.skipUnless(is_xpu_available()							,     """test requires a XPU"""  )(A__  )
def        UpperCamelCase__				(		lowerCAmelCase  ):





      """simple docstring"""


      return unittest.skipUnless(is_mps_available()							,     """test requires a `mps` backend support in `torch`"""  )(A__  )
def        UpperCamelCase__				(		lowerCAmelCase  ):





      """simple docstring"""


      return unittest.skipUnless(
          is_transformers_available() and is_datasets_available()							,     """test requires the Hugging Face suite"""  )(A__  )
def        UpperCamelCase__				(		lowerCAmelCase  ):





      """simple docstring"""


      return unittest.skipUnless(is_bnb_available()							,     """test requires the bitsandbytes library"""  )(A__  )
def        UpperCamelCase__				(		lowerCAmelCase  ):





      """simple docstring"""


      return unittest.skipUnless(is_tpu_available()							,     """test requires TPU"""  )(A__  )
def        UpperCamelCase__				(		lowerCAmelCase  ):





      """simple docstring"""


      return unittest.skipUnless(torch.cuda.device_count() == 1							,     """test requires a GPU"""  )(A__  )
def        UpperCamelCase__				(		lowerCAmelCase  ):





      """simple docstring"""


      return unittest.skipUnless(torch.xpu.device_count() == 1							,     """test requires a XPU"""  )(A__  )
def        UpperCamelCase__				(		lowerCAmelCase  ):





      """simple docstring"""


      return unittest.skipUnless(torch.cuda.device_count() > 1							,     """test requires multiple GPUs"""  )(A__  )
def        UpperCamelCase__				(		lowerCAmelCase  ):





      """simple docstring"""


      return unittest.skipUnless(torch.xpu.device_count() > 1							,     """test requires multiple XPUs"""  )(A__  )
def        UpperCamelCase__				(		lowerCAmelCase  ):





      """simple docstring"""


      return unittest.skipUnless(is_safetensors_available()							,     """test requires safetensors"""  )(A__  )
def        UpperCamelCase__				(		lowerCAmelCase  ):





      """simple docstring"""


      return unittest.skipUnless(is_deepspeed_available()							,     """test requires DeepSpeed"""  )(A__  )
def        UpperCamelCase__				(		lowerCAmelCase  ):





      """simple docstring"""


      return unittest.skipUnless(is_torch_version(""">="""							,     """1.12.0"""  )							,     """test requires torch version >= 1.12.0"""  )(A__  )
def        UpperCamelCase__				(		lowerCAmelCase=None							,     lowerCAmelCase=None  ):





      """simple docstring"""


      if test_case is None:
            return partial(A__							,     version=A__  )
      return unittest.skipUnless(is_torch_version(""">="""							,     A__  )							,     f"test requires torch version >= {version}"  )(A__  )
def        UpperCamelCase__				(		lowerCAmelCase  ):





      """simple docstring"""


      return unittest.skipUnless(is_tensorboard_available()							,     """test requires Tensorboard"""  )(A__  )
def        UpperCamelCase__				(		lowerCAmelCase  ):





      """simple docstring"""


      return unittest.skipUnless(is_wandb_available()							,     """test requires wandb"""  )(A__  )
def        UpperCamelCase__				(		lowerCAmelCase  ):





      """simple docstring"""


      return unittest.skipUnless(is_comet_ml_available()							,     """test requires comet_ml"""  )(A__  )


A__    :       List[Any]              =(
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)
def        UpperCamelCase__				(		lowerCAmelCase  ):





      """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"""							,     )(A__  )




class 			UpperCAmelCase					(      unittest.TestCase       ):
      _lowercase:      List[Any]											=       True




      @classmethod
      def     lowercase__   (      cls      :			int  )    ->				Optional[int]:
            _lowerCAmelCase												=							tempfile.mkdtemp()




      @classmethod
      def     lowercase__   (      cls      :			Any  )    ->				Any:
            if os.path.exists(cls.tmpdir  ):
                  shutil.rmtree(cls.tmpdir  )




      def     lowercase__   (      self      :			Any  )    ->				Union[str, 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(UpperCamelCase_  )




class 			UpperCAmelCase					(      unittest.TestCase       ):




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




class 			UpperCAmelCase					(      unittest.TestCase       ):




      def     lowercase__   (      self      :			Tuple      ,      __snake_case      :			Union[mock.Mock, List[mock.Mock]]  )    ->				Any:
            _lowerCAmelCase												=							mocks if isinstance(UpperCamelCase_      ,      (tuple, list)  ) else [mocks]
            for m in self.mocks:
                  m.start()
                  self.addCleanup(m.stop  )




def        UpperCamelCase__				(		lowerCAmelCase  ):





      """simple docstring"""


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




class 			UpperCAmelCase					:




      def __init__(      self      :			Union[str, Any]      ,      __snake_case      :			Dict      ,      __snake_case      :			Any      ,      __snake_case      :			Any  )    ->				Optional[int]:
            _lowerCAmelCase												=							returncode
            _lowerCAmelCase												=							stdout
            _lowerCAmelCase												=							stderr




async def        UpperCamelCase__				(		lowerCAmelCase							,     lowerCAmelCase  ):





      """simple docstring"""


      while True:
            _lowerCAmelCase												=							await stream.readline()
            if line:
                  callback(A__  )
            else:
                  break
async def        UpperCamelCase__				(		lowerCAmelCase							,     lowerCAmelCase=None							,     lowerCAmelCase=None							,     lowerCAmelCase=None							,     lowerCAmelCase=False							,     lowerCAmelCase=False  ):





      """simple docstring"""


      if echo:
            print("""\nRunning: """							,     """ """.join(A__  )  )

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

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

      _lowerCAmelCase												=							[]
      _lowerCAmelCase												=							[]

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

    # XXX: the timeout doesn't seem to make any difference here
      await asyncio.wait(
          [
              asyncio.create_task(_read_stream(p.stdout							,     lambda lowerCAmelCase  : tee(A__							,     A__							,     sys.stdout							,     label="""stdout:"""  )  )  ),
              asyncio.create_task(_read_stream(p.stderr							,     lambda lowerCAmelCase  : tee(A__							,     A__							,     sys.stderr							,     label="""stderr:"""  )  )  ),
          ]							,     timeout=A__							,     )
      return _RunOutput(await p.wait()							,     A__							,     A__  )
def        UpperCamelCase__				(		lowerCAmelCase							,     lowerCAmelCase=None							,     lowerCAmelCase=None							,     lowerCAmelCase=1_80							,     lowerCAmelCase=False							,     lowerCAmelCase=True  ):





      """simple docstring"""


      _lowerCAmelCase												=							asyncio.get_event_loop()
      _lowerCAmelCase												=							loop.run_until_complete(
          _stream_subprocess(A__							,     env=A__							,     stdin=A__							,     timeout=A__							,     quiet=A__							,     echo=A__  )  )

      _lowerCAmelCase												=							""" """.join(A__  )
      if result.returncode > 0:
            _lowerCAmelCase												=							"""\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 			UpperCAmelCase					(      __lowerCamelCase       ):
      pass




def        UpperCamelCase__				(		lowerCAmelCase							,     lowerCAmelCase=False  ):





      """simple docstring"""


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






'''simple docstring'''






from typing import Any, Callable, Dict, List, Optional, Union

import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DiffusionPipeline,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker


A__    :       Optional[int]              ='''CompVis/stable-diffusion-v1-1'''
A__    :       Optional[int]              ='''CompVis/stable-diffusion-v1-2'''
A__    :       List[str]              ='''CompVis/stable-diffusion-v1-3'''
A__    :       Optional[int]              ='''CompVis/stable-diffusion-v1-4'''




class 			UpperCAmelCase					(      snake_case_       ):




      def __init__(      self      :			Any      ,      __snake_case      :			AutoencoderKL      ,      __snake_case      :			CLIPTextModel      ,      __snake_case      :			CLIPTokenizer      ,      __snake_case      :			UNetaDConditionModel      ,      __snake_case      :			Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]      ,      __snake_case      :			StableDiffusionSafetyChecker      ,      __snake_case      :			CLIPImageProcessor      ,      __snake_case      :			bool = True      ,      )    ->				Any:
            super()._init_()

            _lowerCAmelCase												=							StableDiffusionPipeline.from_pretrained(__snake_case  )
            _lowerCAmelCase												=							StableDiffusionPipeline.from_pretrained(__snake_case  )
            _lowerCAmelCase												=							StableDiffusionPipeline.from_pretrained(__snake_case  )
            _lowerCAmelCase												=							StableDiffusionPipeline(
                vae=__snake_case      ,      text_encoder=__snake_case      ,      tokenizer=__snake_case      ,      unet=__snake_case      ,      scheduler=__snake_case      ,      safety_checker=__snake_case      ,      feature_extractor=__snake_case      ,      requires_safety_checker=__snake_case      ,      )

            self.register_modules(pipelinea=self.pipea      ,      pipelinea=self.pipea      ,      pipelinea=self.pipea      ,      pipelinea=self.pipea  )




      @property
      def     lowercase__   (      self      :			List[Any]  )    ->				Dict[str, Any]:
            return {k: getattr(self      ,      __snake_case  ) for k in self.config.keys() if not k.startswith("""_"""  )}




      def     lowercase__   (      self      :			List[Any]      ,      __snake_case      :			Optional[Union[str, int]] = "auto"  )    ->				Tuple:
            if slice_size == "auto":
                  # half the attention head size is usually a good trade-off between
                  # speed and memory
                  _lowerCAmelCase												=							self.unet.config.attention_head_dim // 2
            self.unet.set_attention_slice(__snake_case  )




      def     lowercase__   (      self      :			str  )    ->				int:
            self.enable_attention_slicing(__snake_case  )




      @torch.no_grad()
      def     lowercase__   (      self      :			Any      ,      __snake_case      :			Union[str, List[str]]      ,      __snake_case      :			int = 5_12      ,      __snake_case      :			int = 5_12      ,      __snake_case      :			int = 50      ,      __snake_case      :			float = 7.5      ,      __snake_case      :			Optional[Union[str, List[str]]] = None      ,      __snake_case      :			Optional[int] = 1      ,      __snake_case      :			float = 0.0      ,      __snake_case      :			Optional[torch.Generator] = None      ,      __snake_case      :			Optional[torch.FloatTensor] = None      ,      __snake_case      :			Optional[str] = "pil"      ,      __snake_case      :			bool = True      ,      __snake_case      :			Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,      __snake_case      :			int = 1      ,      **__snake_case      :			Tuple      ,      )    ->				Tuple:
            return self.pipea(
                prompt=__snake_case      ,      height=__snake_case      ,      width=__snake_case      ,      num_inference_steps=__snake_case      ,      guidance_scale=__snake_case      ,      negative_prompt=__snake_case      ,      num_images_per_prompt=__snake_case      ,      eta=__snake_case      ,      generator=__snake_case      ,      latents=__snake_case      ,      output_type=__snake_case      ,      return_dict=__snake_case      ,      callback=__snake_case      ,      callback_steps=__snake_case      ,      **__snake_case      ,      )




      @torch.no_grad()
      def     lowercase__   (      self      :			Dict      ,      __snake_case      :			Union[str, List[str]]      ,      __snake_case      :			int = 5_12      ,      __snake_case      :			int = 5_12      ,      __snake_case      :			int = 50      ,      __snake_case      :			float = 7.5      ,      __snake_case      :			Optional[Union[str, List[str]]] = None      ,      __snake_case      :			Optional[int] = 1      ,      __snake_case      :			float = 0.0      ,      __snake_case      :			Optional[torch.Generator] = None      ,      __snake_case      :			Optional[torch.FloatTensor] = None      ,      __snake_case      :			Optional[str] = "pil"      ,      __snake_case      :			bool = True      ,      __snake_case      :			Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,      __snake_case      :			int = 1      ,      **__snake_case      :			int      ,      )    ->				List[Any]:
            return self.pipea(
                prompt=__snake_case      ,      height=__snake_case      ,      width=__snake_case      ,      num_inference_steps=__snake_case      ,      guidance_scale=__snake_case      ,      negative_prompt=__snake_case      ,      num_images_per_prompt=__snake_case      ,      eta=__snake_case      ,      generator=__snake_case      ,      latents=__snake_case      ,      output_type=__snake_case      ,      return_dict=__snake_case      ,      callback=__snake_case      ,      callback_steps=__snake_case      ,      **__snake_case      ,      )




      @torch.no_grad()
      def     lowercase__   (      self      :			Any      ,      __snake_case      :			Union[str, List[str]]      ,      __snake_case      :			int = 5_12      ,      __snake_case      :			int = 5_12      ,      __snake_case      :			int = 50      ,      __snake_case      :			float = 7.5      ,      __snake_case      :			Optional[Union[str, List[str]]] = None      ,      __snake_case      :			Optional[int] = 1      ,      __snake_case      :			float = 0.0      ,      __snake_case      :			Optional[torch.Generator] = None      ,      __snake_case      :			Optional[torch.FloatTensor] = None      ,      __snake_case      :			Optional[str] = "pil"      ,      __snake_case      :			bool = True      ,      __snake_case      :			Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,      __snake_case      :			int = 1      ,      **__snake_case      :			Tuple      ,      )    ->				Dict:
            return self.pipea(
                prompt=__snake_case      ,      height=__snake_case      ,      width=__snake_case      ,      num_inference_steps=__snake_case      ,      guidance_scale=__snake_case      ,      negative_prompt=__snake_case      ,      num_images_per_prompt=__snake_case      ,      eta=__snake_case      ,      generator=__snake_case      ,      latents=__snake_case      ,      output_type=__snake_case      ,      return_dict=__snake_case      ,      callback=__snake_case      ,      callback_steps=__snake_case      ,      **__snake_case      ,      )




      @torch.no_grad()
      def     lowercase__   (      self      :			Dict      ,      __snake_case      :			Union[str, List[str]]      ,      __snake_case      :			int = 5_12      ,      __snake_case      :			int = 5_12      ,      __snake_case      :			int = 50      ,      __snake_case      :			float = 7.5      ,      __snake_case      :			Optional[Union[str, List[str]]] = None      ,      __snake_case      :			Optional[int] = 1      ,      __snake_case      :			float = 0.0      ,      __snake_case      :			Optional[torch.Generator] = None      ,      __snake_case      :			Optional[torch.FloatTensor] = None      ,      __snake_case      :			Optional[str] = "pil"      ,      __snake_case      :			bool = True      ,      __snake_case      :			Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,      __snake_case      :			int = 1      ,      **__snake_case      :			str      ,      )    ->				List[Any]:
            return self.pipea(
                prompt=__snake_case      ,      height=__snake_case      ,      width=__snake_case      ,      num_inference_steps=__snake_case      ,      guidance_scale=__snake_case      ,      negative_prompt=__snake_case      ,      num_images_per_prompt=__snake_case      ,      eta=__snake_case      ,      generator=__snake_case      ,      latents=__snake_case      ,      output_type=__snake_case      ,      return_dict=__snake_case      ,      callback=__snake_case      ,      callback_steps=__snake_case      ,      **__snake_case      ,      )




      @torch.no_grad()
      def     lowercase__   (      self      :			Optional[int]      ,      __snake_case      :			Union[str, List[str]]      ,      __snake_case      :			int = 5_12      ,      __snake_case      :			int = 5_12      ,      __snake_case      :			int = 50      ,      __snake_case      :			float = 7.5      ,      __snake_case      :			Optional[Union[str, List[str]]] = None      ,      __snake_case      :			Optional[int] = 1      ,      __snake_case      :			float = 0.0      ,      __snake_case      :			Optional[torch.Generator] = None      ,      __snake_case      :			Optional[torch.FloatTensor] = None      ,      __snake_case      :			Optional[str] = "pil"      ,      __snake_case      :			bool = True      ,      __snake_case      :			Optional[Callable[[int, int, torch.FloatTensor], None]] = None      ,      __snake_case      :			int = 1      ,      **__snake_case      :			Tuple      ,      )    ->				Optional[Any]:
            _lowerCAmelCase												=							"""cuda""" if torch.cuda.is_available() else """cpu"""
            self.to(__snake_case  )

            # Checks if the height and width are divisible by 8 or not
            if height % 8 != 0 or width % 8 != 0:
                  raise ValueError(f"`height` and `width` must be divisible by 8 but are {height} and {width}."  )

            # Get first result from Stable Diffusion Checkpoint v1.1
            _lowerCAmelCase												=							self.textaimg_sda_a(
                prompt=__snake_case      ,      height=__snake_case      ,      width=__snake_case      ,      num_inference_steps=__snake_case      ,      guidance_scale=__snake_case      ,      negative_prompt=__snake_case      ,      num_images_per_prompt=__snake_case      ,      eta=__snake_case      ,      generator=__snake_case      ,      latents=__snake_case      ,      output_type=__snake_case      ,      return_dict=__snake_case      ,      callback=__snake_case      ,      callback_steps=__snake_case      ,      **__snake_case      ,      )

            # Get first result from Stable Diffusion Checkpoint v1.2
            _lowerCAmelCase												=							self.textaimg_sda_a(
                prompt=__snake_case      ,      height=__snake_case      ,      width=__snake_case      ,      num_inference_steps=__snake_case      ,      guidance_scale=__snake_case      ,      negative_prompt=__snake_case      ,      num_images_per_prompt=__snake_case      ,      eta=__snake_case      ,      generator=__snake_case      ,      latents=__snake_case      ,      output_type=__snake_case      ,      return_dict=__snake_case      ,      callback=__snake_case      ,      callback_steps=__snake_case      ,      **__snake_case      ,      )

            # Get first result from Stable Diffusion Checkpoint v1.3
            _lowerCAmelCase												=							self.textaimg_sda_a(
                prompt=__snake_case      ,      height=__snake_case      ,      width=__snake_case      ,      num_inference_steps=__snake_case      ,      guidance_scale=__snake_case      ,      negative_prompt=__snake_case      ,      num_images_per_prompt=__snake_case      ,      eta=__snake_case      ,      generator=__snake_case      ,      latents=__snake_case      ,      output_type=__snake_case      ,      return_dict=__snake_case      ,      callback=__snake_case      ,      callback_steps=__snake_case      ,      **__snake_case      ,      )

            # Get first result from Stable Diffusion Checkpoint v1.4
            _lowerCAmelCase												=							self.textaimg_sda_a(
                prompt=__snake_case      ,      height=__snake_case      ,      width=__snake_case      ,      num_inference_steps=__snake_case      ,      guidance_scale=__snake_case      ,      negative_prompt=__snake_case      ,      num_images_per_prompt=__snake_case      ,      eta=__snake_case      ,      generator=__snake_case      ,      latents=__snake_case      ,      output_type=__snake_case      ,      return_dict=__snake_case      ,      callback=__snake_case      ,      callback_steps=__snake_case      ,      **__snake_case      ,      )

            # Get all result images into a single list and pass it via StableDiffusionPipelineOutput for final result
            return StableDiffusionPipelineOutput([resa[0], resa[0], resa[0], resa[0]]  )






