import inspect
import tempfile
from collections import OrderedDict, UserDict
from collections.abc import MutableMapping
from contextlib import ExitStack, contextmanager
from dataclasses import fields
from enum import Enum
from typing import Any, ContextManager, List, Tuple

import numpy as np

from .import_utils import is_flax_available, is_tf_available, is_torch_available, is_torch_fx_proxy


if is_flax_available():
      import jax.numpy as jnp





class      A							(				UpperCAmelCase_     ):


   def __get__(self     :						Optional[Any]       ,  __UpperCAmelCase     :						Union[str, Any]       ,  __UpperCAmelCase     :						str=None		)						->				str:
         """simple docstring"""



         if obj is None:
               return self
         if self.fget is None:
               raise AttributeError("unreadable attribute"		)
         UpperCAmelCase__								=  "__cached_" + self.fget.__name__
         UpperCAmelCase__								=  getattr(__UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase		)
         if cached is None:
               UpperCAmelCase__								=  self.fget(__UpperCAmelCase		)
               setattr(__UpperCAmelCase       ,  __UpperCAmelCase       ,  __UpperCAmelCase		)
         return cached




def    lowerCAmelCase_ (     __A							)     ->				Optional[Any]:







      '''simple docstring'''


      UpperCAmelCase__								=  val.lower()
      if val in {"y", "yes", "t", "true", "on", "1"}:
            return 1
      if val in {"n", "no", "f", "false", "off", "0"}:
            return 0
      raise ValueError(f"""invalid truth value {val!r}"""							)




def    lowerCAmelCase_ (     __A							)     ->				Optional[int]:







      '''simple docstring'''


      if is_torch_fx_proxy(__A							):
            return True
      if is_torch_available():
            import torch

            if isinstance(__A,  torch.Tensor							):
                  return True
      if is_tf_available():
            import tensorflow as tf

            if isinstance(__A,  tf.Tensor							):
                  return True

      if is_flax_available():
            import jax.numpy as jnp
            from jax.core import Tracer

            if isinstance(__A,  (jnp.ndarray, Tracer)							):
                  return True

      return isinstance(__A,  np.ndarray							)




def    lowerCAmelCase_ (     __A							)     ->				str:







      '''simple docstring'''


      return isinstance(__A,  np.ndarray							)




def    lowerCAmelCase_ (     __A							)     ->				List[str]:







      '''simple docstring'''


      return _is_numpy(__A							)




def    lowerCAmelCase_ (     __A							)     ->				Dict:







      '''simple docstring'''


      import torch

      return isinstance(__A,  torch.Tensor							)




def    lowerCAmelCase_ (     __A							)     ->				Optional[int]:







      '''simple docstring'''


      return False if not is_torch_available() else _is_torch(__A							)




def    lowerCAmelCase_ (     __A							)     ->				Union[str, Any]:







      '''simple docstring'''


      import torch

      return isinstance(__A,  torch.device							)




def    lowerCAmelCase_ (     __A							)     ->				Optional[int]:







      '''simple docstring'''


      return False if not is_torch_available() else _is_torch_device(__A							)




def    lowerCAmelCase_ (     __A							)     ->				Any:







      '''simple docstring'''


      import torch

      if isinstance(__A,  __A							):
            if hasattr(__A,  __A							):
                  UpperCAmelCase__								=  getattr(__A,  __A							)
            else:
                  return False
      return isinstance(__A,  torch.dtype							)




def    lowerCAmelCase_ (     __A							)     ->				Tuple:







      '''simple docstring'''


      return False if not is_torch_available() else _is_torch_dtype(__A							)




def    lowerCAmelCase_ (     __A							)     ->				Tuple:







      '''simple docstring'''


      import tensorflow as tf

      return isinstance(__A,  tf.Tensor							)




def    lowerCAmelCase_ (     __A							)     ->				Dict:







      '''simple docstring'''


      return False if not is_tf_available() else _is_tensorflow(__A							)




def    lowerCAmelCase_ (     __A							)     ->				Any:







      '''simple docstring'''


      import tensorflow as tf

      # the `is_symbolic_tensor` predicate is only available starting with TF 2.14
      if hasattr(__A,  "is_symbolic_tensor"							):
            return tf.is_symbolic_tensor(__A							)
      return type(__A							) == tf.Tensor




def    lowerCAmelCase_ (     __A							)     ->				List[str]:







      '''simple docstring'''


      return False if not is_tf_available() else _is_tf_symbolic_tensor(__A							)




def    lowerCAmelCase_ (     __A							)     ->				List[Any]:







      '''simple docstring'''


      import jax.numpy as jnp  # noqa: F811

      return isinstance(__A,  jnp.ndarray							)




def    lowerCAmelCase_ (     __A							)     ->				List[str]:







      '''simple docstring'''


      return False if not is_flax_available() else _is_jax(__A							)




def    lowerCAmelCase_ (     __A							)     ->				Tuple:







      '''simple docstring'''


      if isinstance(__A,  (dict, UserDict)							):
            return {k: to_py_obj(__A							) for k, v in obj.items()}
      elif isinstance(__A,  (list, tuple)							):
            return [to_py_obj(__A							) for o in obj]
      elif is_tf_tensor(__A							):
            return obj.numpy().tolist()
      elif is_torch_tensor(__A							):
            return obj.detach().cpu().tolist()
      elif is_jax_tensor(__A							):
            return np.asarray(__A							).tolist()
      elif isinstance(__A,  (np.ndarray, np.number)							):  # tolist also works on 0d np arrays
            return obj.tolist()
      else:
            return obj




def    lowerCAmelCase_ (     __A							)     ->				Tuple:







      '''simple docstring'''


      if isinstance(__A,  (dict, UserDict)							):
            return {k: to_numpy(__A							) for k, v in obj.items()}
      elif isinstance(__A,  (list, tuple)							):
            return np.array(__A							)
      elif is_tf_tensor(__A							):
            return obj.numpy()
      elif is_torch_tensor(__A							):
            return obj.detach().cpu().numpy()
      elif is_jax_tensor(__A							):
            return np.asarray(__A							)
      else:
            return obj





class      A							(				UpperCAmelCase_     ):


   def 			lowercase_      (self     :						List[Any]		)						->				str:
         """simple docstring"""



         UpperCAmelCase__								=  fields(self		)

         # Safety and consistency checks
         if not len(__UpperCAmelCase		):
               raise ValueError(f"""{self.__class__.__name__} has no fields."""		)
         if not all(field.default is None for field in class_fields[1:]		):
               raise ValueError(f"""{self.__class__.__name__} should not have more than one required field."""		)

         UpperCAmelCase__								=  getattr(self       ,  class_fields[0].name		)
         UpperCAmelCase__								=  all(getattr(self       ,  field.name		) is None for field in class_fields[1:]		)

         if other_fields_are_none and not is_tensor(__UpperCAmelCase		):
               if isinstance(__UpperCAmelCase       ,  __UpperCAmelCase		):
                     UpperCAmelCase__								=  first_field.items()
                     UpperCAmelCase__								=  True
               else:
                     try:
                           UpperCAmelCase__								=  iter(__UpperCAmelCase		)
                           UpperCAmelCase__								=  True
                     except TypeError:
                           UpperCAmelCase__								=  False

            # if we provided an iterator as first field and the iterator is a (key, value) iterator
            # set the associated fields
               if first_field_iterator:
                     for idx, element in enumerate(__UpperCAmelCase		):
                           if (
                               not isinstance(__UpperCAmelCase       ,  (list, tuple)		)
                               or not len(__UpperCAmelCase		) == 2
                               or not isinstance(element[0]       ,  __UpperCAmelCase		)
                           ):
                                 if idx == 0:
                                       # If we do not have an iterator of key/values, set it as attribute
                                       UpperCAmelCase__								=  first_field
                                 else:
                                       # If we have a mixed iterator, raise an error
                                       raise ValueError(
                                           f"""Cannot set key/value for {element}. It needs to be a tuple (key, value)."""		)
                                 break
                           setattr(self       ,  element[0]       ,  element[1]		)
                           if element[1] is not None:
                                 UpperCAmelCase__								=  element[1]
               elif first_field is not None:
                     UpperCAmelCase__								=  first_field
         else:
               for field in class_fields:
                     UpperCAmelCase__								=  getattr(self       ,  field.name		)
                     if v is not None:
                           UpperCAmelCase__								=  v


   def __delitem__(self     :						Any       ,  *__UpperCAmelCase     :						Union[str, Any]       ,  **__UpperCAmelCase     :						Optional[int]		)						->				Optional[int]:
         """simple docstring"""



         raise Exception(f"""You cannot use ``__delitem__`` on a {self.__class__.__name__} instance."""		)


   def 			lowercase_      (self     :						Any       ,  *__UpperCAmelCase     :						int       ,  **__UpperCAmelCase     :						List[Any]		)						->				Union[str, Any]:
         """simple docstring"""



         raise Exception(f"""You cannot use ``setdefault`` on a {self.__class__.__name__} instance."""		)


   def 			lowercase_      (self     :						str       ,  *__UpperCAmelCase     :						Any       ,  **__UpperCAmelCase     :						Optional[int]		)						->				Dict:
         """simple docstring"""



         raise Exception(f"""You cannot use ``pop`` on a {self.__class__.__name__} instance."""		)


   def 			lowercase_      (self     :						List[str]       ,  *__UpperCAmelCase     :						List[str]       ,  **__UpperCAmelCase     :						Any		)						->				Optional[int]:
         """simple docstring"""



         raise Exception(f"""You cannot use ``update`` on a {self.__class__.__name__} instance."""		)


   def __getitem__(self     :						List[str]       ,  __UpperCAmelCase     :						Optional[int]		)						->				Union[str, Any]:
         """simple docstring"""



         if isinstance(__UpperCAmelCase       ,  __UpperCAmelCase		):
               UpperCAmelCase__								=  dict(self.items()		)
               return inner_dict[k]
         else:
               return self.to_tuple()[k]


   def __setattr__(self     :						Dict       ,  __UpperCAmelCase     :						List[Any]       ,  __UpperCAmelCase     :						Optional[int]		)						->				Dict:
         """simple docstring"""



         if name in self.keys() and value is not None:
               # Don't call self.__setitem__ to avoid recursion errors
               super().__setitem__(__UpperCAmelCase       ,  __UpperCAmelCase		)
         super().__setattr__(__UpperCAmelCase       ,  __UpperCAmelCase		)


   def __setitem__(self     :						Dict       ,  __UpperCAmelCase     :						Optional[int]       ,  __UpperCAmelCase     :						List[str]		)						->				int:
         """simple docstring"""



         super().__setitem__(__UpperCAmelCase       ,  __UpperCAmelCase		)
         # Don't call self.__setattr__ to avoid recursion errors
         super().__setattr__(__UpperCAmelCase       ,  __UpperCAmelCase		)





   def 			lowercase_      (self     :						Any		)						->				Tuple[Any]:
         """simple docstring"""



         return tuple(self[k] for k in self.keys()		)





class      A							(				UpperCAmelCase_		,				UpperCAmelCase_     ):


   @classmethod
   def 			lowercase_      (cls     :						List[str]       ,  __UpperCAmelCase     :						int		)						->				Tuple:
         """simple docstring"""



         raise ValueError(
             f"""{value} is not a valid {cls.__name__}, please select one of {list(cls._valueamember_map_.keys()		)}"""		)





class      A							(				UpperCAmelCase_     ):
   __UpperCAmelCase : Optional[int]      =			'longest'
   __UpperCAmelCase : int      =			'max_length'
   __UpperCAmelCase : List[str]      =			'do_not_pad'





class      A							(				UpperCAmelCase_     ):
   __UpperCAmelCase : Dict      =			'pt'
   __UpperCAmelCase : Optional[int]      =			'tf'
   __UpperCAmelCase : int      =			'np'
   __UpperCAmelCase : int      =			'jax'





class      A							:


   def __init__(self     :						Union[str, Any]       ,  __UpperCAmelCase     :						List[ContextManager]		)						->				Any:
         """simple docstring"""



         UpperCAmelCase__								=  context_managers
         UpperCAmelCase__								=  ExitStack()


   def __enter__(self     :						Optional[Any]		)						->				List[str]:
         """simple docstring"""



         for context_manager in self.context_managers:
               self.stack.enter_context(__UpperCAmelCase		)





   def __exit__(self     :						List[Any]       ,  *__UpperCAmelCase     :						Tuple       ,  **__UpperCAmelCase     :						str		)						->				Tuple:
         """simple docstring"""



         self.stack.__exit__(*__UpperCAmelCase       ,  **__UpperCAmelCase		)




def    lowerCAmelCase_ (     __A							)     ->				Any:







      '''simple docstring'''


      UpperCAmelCase__								=  infer_framework(__A							)
      if framework == "tf":
            UpperCAmelCase__								=  inspect.signature(model_class.call							)  # TensorFlow models
      elif framework == "pt":
            UpperCAmelCase__								=  inspect.signature(model_class.forward							)  # PyTorch models
      else:
            UpperCAmelCase__								=  inspect.signature(model_class.__call__							)  # Flax models

      for p in signature.parameters:
            if p == "return_loss" and signature.parameters[p].default is True:
                  return True

      return False




def    lowerCAmelCase_ (     __A							)     ->				Dict:







      '''simple docstring'''


      UpperCAmelCase__								=  model_class.__name__
      UpperCAmelCase__								=  infer_framework(__A							)
      if framework == "tf":
            UpperCAmelCase__								=  inspect.signature(model_class.call							)  # TensorFlow models
      elif framework == "pt":
            UpperCAmelCase__								=  inspect.signature(model_class.forward							)  # PyTorch models
      else:
            UpperCAmelCase__								=  inspect.signature(model_class.__call__							)  # Flax models

      if "QuestionAnswering" in model_name:
            return [p for p in signature.parameters if "label" in p or p in ("start_positions", "end_positions")]
      else:
            return [p for p in signature.parameters if "label" in p]




def    lowerCAmelCase_ (     __A,  __A = "",  __A = "."							)     ->				Tuple:







      '''simple docstring'''


      def _flatten_dict(__A,  __A="",  __A="."							):
            for k, v in d.items():
                  UpperCAmelCase__								=  str(__A							) + delimiter + str(__A							) if parent_key else k
                  if v and isinstance(__A,  __A							):
                        yield from flatten_dict(__A,  __A,  delimiter=__A							).items()
                  else:
                        yield key, v

      return dict(_flatten_dict(__A,  __A,  __A							)							)




@contextmanager
def    lowerCAmelCase_ (     __A,  __A = False							)     ->				Dict:







      '''simple docstring'''


      if use_temp_dir:
            with tempfile.TemporaryDirectory() as tmp_dir:
                  yield tmp_dir
      else:
            yield working_dir




def    lowerCAmelCase_ (     __A,  __A=None							)     ->				int:







      '''simple docstring'''


      if is_numpy_array(__A							):
            return np.transpose(__A,  axes=__A							)
      elif is_torch_tensor(__A							):
            return array.T if axes is None else array.permute(*__A							)
      elif is_tf_tensor(__A							):
            import tensorflow as tf

            return tf.transpose(__A,  perm=__A							)
      elif is_jax_tensor(__A							):
            return jnp.transpose(__A,  axes=__A							)
      else:
            raise ValueError(f"""Type not supported for transpose: {type(__A							)}."""							)




def    lowerCAmelCase_ (     __A,  __A							)     ->				List[str]:







      '''simple docstring'''


      if is_numpy_array(__A							):
            return np.reshape(__A,  __A							)
      elif is_torch_tensor(__A							):
            return array.reshape(*__A							)
      elif is_tf_tensor(__A							):
            import tensorflow as tf

            return tf.reshape(__A,  __A							)
      elif is_jax_tensor(__A							):
            return jnp.reshape(__A,  __A							)
      else:
            raise ValueError(f"""Type not supported for reshape: {type(__A							)}."""							)




def    lowerCAmelCase_ (     __A,  __A=None							)     ->				str:







      '''simple docstring'''


      if is_numpy_array(__A							):
            return np.squeeze(__A,  axis=__A							)
      elif is_torch_tensor(__A							):
            return array.squeeze() if axis is None else array.squeeze(dim=__A							)
      elif is_tf_tensor(__A							):
            import tensorflow as tf

            return tf.squeeze(__A,  axis=__A							)
      elif is_jax_tensor(__A							):
            return jnp.squeeze(__A,  axis=__A							)
      else:
            raise ValueError(f"""Type not supported for squeeze: {type(__A							)}."""							)




def    lowerCAmelCase_ (     __A,  __A							)     ->				Optional[Any]:







      '''simple docstring'''


      if is_numpy_array(__A							):
            return np.expand_dims(__A,  __A							)
      elif is_torch_tensor(__A							):
            return array.unsqueeze(dim=__A							)
      elif is_tf_tensor(__A							):
            import tensorflow as tf

            return tf.expand_dims(__A,  axis=__A							)
      elif is_jax_tensor(__A							):
            return jnp.expand_dims(__A,  axis=__A							)
      else:
            raise ValueError(f"""Type not supported for expand_dims: {type(__A							)}."""							)




def    lowerCAmelCase_ (     __A							)     ->				Optional[int]:







      '''simple docstring'''


      if is_numpy_array(__A							):
            return np.size(__A							)
      elif is_torch_tensor(__A							):
            return array.numel()
      elif is_tf_tensor(__A							):
            import tensorflow as tf

            return tf.size(__A							)
      elif is_jax_tensor(__A							):
            return array.size
      else:
            raise ValueError(f"""Type not supported for expand_dims: {type(__A							)}."""							)




def    lowerCAmelCase_ (     __A,  __A							)     ->				Dict:







      '''simple docstring'''


      for key, value in auto_map.items():
            if isinstance(__A,  (tuple, list)							):
                  UpperCAmelCase__								=  [f"""{repo_id}--{v}""" if (v is not None and "--" not in v) else v for v in value]
            elif value is not None and "--" not in value:
                  UpperCAmelCase__								=  f"""{repo_id}--{value}"""

      return auto_map







def    lowerCAmelCase_ (     __A							)     ->				Optional[Any]:







      '''simple docstring'''


      for base_class in inspect.getmro(__A							):
            UpperCAmelCase__								=  base_class.__module__
            UpperCAmelCase__								=  base_class.__name__
            if module.startswith("tensorflow"							) or module.startswith("keras"							) or name == "TFPreTrainedModel":
                  return "tf"
            elif module.startswith("torch"							) or name == "PreTrainedModel":
                  return "pt"
            elif module.startswith("flax"							) or module.startswith("jax"							) or name == "FlaxPreTrainedModel":
                  return "flax"
      else:
            raise TypeError(f"""Could not infer framework from class {model_class}."""							)







import gc
import unittest

import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DDPMScheduler,
    PriorTransformer,
    StableUnCLIPPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer
from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import (
    PipelineKarrasSchedulerTesterMixin,
    PipelineLatentTesterMixin,
    PipelineTesterMixin,
    assert_mean_pixel_difference,
)


enable_full_determinism()
class 	UpperCAmelCase_					(					UpperCamelCase		, UpperCamelCase		, UpperCamelCase		, unittest.TestCase    ):

   '''simple docstring'''




   __A :      Tuple     		=		StableUnCLIPPipeline
   __A :      Optional[int]     		=		TEXT_TO_IMAGE_PARAMS
   __A :      str     		=		TEXT_TO_IMAGE_BATCH_PARAMS
   __A :      int     		=		TEXT_TO_IMAGE_IMAGE_PARAMS
   __A :      Tuple     		=		TEXT_TO_IMAGE_IMAGE_PARAMS

   # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false
   __A :      Union[str, Any]     		=		False






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					List[str]    =				32
     lowerCamelCase :					Dict    =				embedder_hidden_size

     # prior components

     torch.manual_seed(0 )
     lowerCamelCase :					Optional[int]    =				CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )

     torch.manual_seed(0 )
     lowerCamelCase :					Optional[int]    =				CLIPTextModelWithProjection(
         CLIPTextConfig(
             bos_token_id=0						,				eos_token_id=2						,				hidden_size=__A						,				projection_dim=__A						,				intermediate_size=37						,				layer_norm_eps=1e-05						,				num_attention_heads=4						,				num_hidden_layers=5						,				pad_token_id=1						,				vocab_size=1000						,				) )

     torch.manual_seed(0 )
     lowerCamelCase :					List[Any]    =				PriorTransformer(
         num_attention_heads=2						,				attention_head_dim=12						,				embedding_dim=__A						,				num_layers=1						,				)

     torch.manual_seed(0 )
     lowerCamelCase :					Dict    =				DDPMScheduler(
         variance_type="fixed_small_log"						,				prediction_type="sample"						,				num_train_timesteps=1000						,				clip_sample=__A						,				clip_sample_range=5.0						,				beta_schedule="squaredcos_cap_v2"						,				)

     # regular denoising components

     torch.manual_seed(0 )
     lowerCamelCase :					Optional[int]    =				StableUnCLIPImageNormalizer(embedding_dim=__A )
     lowerCamelCase :					Tuple    =				DDPMScheduler(beta_schedule="squaredcos_cap_v2" )

     torch.manual_seed(0 )
     lowerCamelCase :					List[Any]    =				CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" )

     torch.manual_seed(0 )
     lowerCamelCase :					str    =				CLIPTextModel(
         CLIPTextConfig(
             bos_token_id=0						,				eos_token_id=2						,				hidden_size=__A						,				projection_dim=32						,				intermediate_size=37						,				layer_norm_eps=1e-05						,				num_attention_heads=4						,				num_hidden_layers=5						,				pad_token_id=1						,				vocab_size=1000						,				) )

     torch.manual_seed(0 )
     lowerCamelCase :					Any    =				UNetaDConditionModel(
         sample_size=32						,				in_channels=4						,				out_channels=4						,				down_block_types=("CrossAttnDownBlock2D", "DownBlock2D")						,				up_block_types=("UpBlock2D", "CrossAttnUpBlock2D")						,				block_out_channels=(32, 64)						,				attention_head_dim=(2, 4)						,				class_embed_type="projection"						,				projection_class_embeddings_input_dim=embedder_projection_dim * 2						,				cross_attention_dim=__A						,				layers_per_block=1						,				upcast_attention=__A						,				use_linear_projection=__A						,				)

     torch.manual_seed(0 )
     lowerCamelCase :					int    =				DDIMScheduler(
         beta_schedule="scaled_linear"						,				beta_start=0.00085						,				beta_end=0.012						,				prediction_type="v_prediction"						,				set_alpha_to_one=__A						,				steps_offset=1						,				)

     torch.manual_seed(0 )
     lowerCamelCase :					Optional[Any]    =				AutoencoderKL()

     lowerCamelCase :					Optional[int]    =				{
         # prior components
         "prior_tokenizer": prior_tokenizer,
         "prior_text_encoder": prior_text_encoder,
         "prior": prior,
         "prior_scheduler": prior_scheduler,
         # image noising components
         "image_normalizer": image_normalizer,
         "image_noising_scheduler": image_noising_scheduler,
         # regular denoising components
         "tokenizer": tokenizer,
         "text_encoder": text_encoder,
         "unet": unet,
         "scheduler": scheduler,
         "vae": vae,
     }

     return components






   def _snake_case    (		self						,				__A						,				__A=0 ):






     """simple docstring"""





     if str(__A ).startswith("mps" ):
       lowerCamelCase :					Optional[int]    =				torch.manual_seed(__A )
     else:
       lowerCamelCase :					Optional[Any]    =				torch.Generator(device=__A ).manual_seed(__A )
     lowerCamelCase :					Tuple    =				{
         "prompt": "A painting of a squirrel eating a burger",
         "generator": generator,
         "num_inference_steps": 2,
         "prior_num_inference_steps": 2,
         "output_type": "numpy",
     }
     return inputs






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					Dict    =				torch_device == "cpu"

     self._test_attention_slicing_forward_pass(test_max_difference=__A )






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					List[Any]    =				torch_device in ["cpu", "mps"]

     self._test_inference_batch_single_identical(test_max_difference=__A )



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

   '''simple docstring'''




   def _snake_case    (		self ):






     """simple docstring"""





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






   def _snake_case    (		self ):






     """simple docstring"""





     lowerCamelCase :					Optional[Any]    =				load_numpy(
         "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy" )

     lowerCamelCase :					str    =				StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l"						,				torch_dtype=torch.floataa )
     pipe.to(__A )
     pipe.set_progress_bar_config(disable=__A )
     # stable unclip will oom when integration tests are run on a V100,
     # so turn on memory savings
     pipe.enable_attention_slicing()
     pipe.enable_sequential_cpu_offload()

     lowerCamelCase :					List[Any]    =				torch.Generator(device="cpu" ).manual_seed(0 )
     lowerCamelCase :					Dict    =				pipe("anime turle"						,				generator=__A						,				output_type="np" )

     lowerCamelCase :					Dict    =				output.images[0]

     assert image.shape == (768, 768, 3)

     assert_mean_pixel_difference(__A						,				__A )






   def _snake_case    (		self ):






     """simple docstring"""





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

     lowerCamelCase :					int    =				StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l"						,				torch_dtype=torch.floataa )
     lowerCamelCase :					Union[str, Any]    =				pipe.to(__A )
     pipe.set_progress_bar_config(disable=__A )
     pipe.enable_attention_slicing()
     pipe.enable_sequential_cpu_offload()

     lowerCamelCase :					Any    =				pipe(
         "anime turtle"						,				prior_num_inference_steps=2						,				num_inference_steps=2						,				output_type="np"						,				)

     lowerCamelCase :					List[str]    =				torch.cuda.max_memory_allocated()
     # make sure that less than 7 GB is allocated
     assert mem_bytes < 7 * 10**9



