

'''simple docstring'''





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 				lowercase       (							__snake_case ,       __snake_case ,       __snake_case ,       unittest.TestCase      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							StableUnCLIPPipeline
    lowerCAmelCase__      				=							TEXT_TO_IMAGE_PARAMS
    lowerCAmelCase__      				=							TEXT_TO_IMAGE_BATCH_PARAMS
    lowerCAmelCase__      				=							TEXT_TO_IMAGE_IMAGE_PARAMS
    lowerCAmelCase__      				=							TEXT_TO_IMAGE_IMAGE_PARAMS

    # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false
    lowerCAmelCase__      				=							False

    def    a__				(					self     :     Optional[int]     )							->							Tuple:

     '''simple docstring'''




     lowerCamelCase__  =     32
     lowerCamelCase__  =     embedder_hidden_size

     # prior components

     torch.manual_seed(0     )
     lowerCamelCase__  =     CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"     )

     torch.manual_seed(0     )
     lowerCamelCase__  =     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__  =     PriorTransformer(
         num_attention_heads=2				,     attention_head_dim=12				,     embedding_dim=A_				,     num_layers=1				,     )

     torch.manual_seed(0     )
     lowerCamelCase__  =     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__  =     StableUnCLIPImageNormalizer(embedding_dim=A_     )
     lowerCamelCase__  =     DDPMScheduler(beta_schedule="squaredcos_cap_v2"     )

     torch.manual_seed(0     )
     lowerCamelCase__  =     CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"     )

     torch.manual_seed(0     )
     lowerCamelCase__  =     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__  =     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__  =     DDIMScheduler(
         beta_schedule="scaled_linear"				,     beta_start=0.0_0_0_8_5				,     beta_end=0.0_1_2				,     prediction_type="v_prediction"				,     set_alpha_to_one=A_				,     steps_offset=1				,     )

     torch.manual_seed(0     )
     lowerCamelCase__  =     AutoencoderKL()

     lowerCamelCase__  =     {
         # 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    a__				(					self     :     List[str]				,     __lowerCamelCase     :     List[Any]				,     __lowerCamelCase     :     Optional[Any]=0     )							->							Any:

     '''simple docstring'''




     if str(A_     ).startswith("mps"     ):
      lowerCamelCase__  =     torch.manual_seed(A_     )
     else:
      lowerCamelCase__  =     torch.Generator(device=A_     ).manual_seed(A_     )
     lowerCamelCase__  =     {
         "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    a__				(					self     :     List[str]     )							->							Any:

     '''simple docstring'''




     lowerCamelCase__  =     torch_device == "cpu"

     self._test_attention_slicing_forward_pass(test_max_difference=A_     )




    def    a__				(					self     :     Tuple     )							->							Dict:

     '''simple docstring'''




     lowerCamelCase__  =     torch_device in ["cpu", "mps"]

     self._test_inference_batch_single_identical(test_max_difference=A_     )
@slow
@require_torch_gpu
class 				lowercase       (							unittest.TestCase      ):


    '''simple docstring'''

    def    a__				(					self     :     Any     )							->							int:

     '''simple docstring'''




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

    def    a__				(					self     :     int     )							->							Optional[int]:

     '''simple docstring'''




     lowerCamelCase__  =     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__  =     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__  =     torch.Generator(device="cpu"     ).manual_seed(0     )
     lowerCamelCase__  =     pipe("anime turle"				,     generator=A_				,     output_type="np"     )

     lowerCamelCase__  =     output.images[0]

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

     assert_mean_pixel_difference(A_				,     A_     )




    def    a__				(					self     :     Optional[Any]     )							->							List[str]:

     '''simple docstring'''




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

     lowerCamelCase__  =     StableUnCLIPPipeline.from_pretrained("fusing/stable-unclip-2-1-l"				,     torch_dtype=torch.floataa     )
     lowerCamelCase__  =     pipe.to(A_     )
     pipe.set_progress_bar_config(disable=A_     )
     pipe.enable_attention_slicing()
     pipe.enable_sequential_cpu_offload()

     lowerCamelCase__  =     pipe(
         "anime turtle"				,     prior_num_inference_steps=2				,     num_inference_steps=2				,     output_type="np"				,     )

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









'''simple docstring'''





# Lint as: python3
import sys
from collections.abc import Mapping
from typing import TYPE_CHECKING, Dict, Optional

import numpy as np
import pyarrow as pa

from .. import config
from ..utils.logging import get_logger
from ..utils.py_utils import map_nested
from .formatting import TensorFormatter


if TYPE_CHECKING:
 import jax
 import jaxlib

__A							:							Any  							=		get_logger()

__A							:							Optional[dict]  							=		None
class 				lowercase       (							TensorFormatter[Mapping, "jax.Array", Mapping]      ):


    '''simple docstring'''

    def __init__(					self     :     str				,     __lowerCamelCase     :     Optional[Any]=None				,     __lowerCamelCase     :     Dict=None				,     **__lowerCamelCase     :     str     )							->							List[Any]:

     '''simple docstring'''




     super().__init__(features=__lowerCamelCase     )
     import jax
     from jaxlib.xla_client import Device

     if isinstance(__lowerCamelCase				,     __lowerCamelCase     ):
      raise ValueError(
          f'''Expected {device} to be a `str` not {type(__lowerCamelCase     )}, as `jaxlib.xla_extension.Device` '''
          "is not serializable neither with `pickle` nor with `dill`. Instead you can surround "
          "the device with `str()` to get its string identifier that will be internally mapped "
          "to the actual `jaxlib.xla_extension.Device`."     )
     lowerCamelCase__  =     device if isinstance(__lowerCamelCase				,     __lowerCamelCase     ) else str(jax.devices()[0]     )
     # using global variable since `jaxlib.xla_extension.Device` is not serializable neither
     # with `pickle` nor with `dill`, so we need to use a global variable instead
     global DEVICE_MAPPING
     if DEVICE_MAPPING is None:
      lowerCamelCase__  =     self._map_devices_to_str()
     if self.device not in list(DEVICE_MAPPING.keys()     ):
      logger.warning(
          f'''Device with string identifier {self.device} not listed among the available '''
          f'''devices: {list(DEVICE_MAPPING.keys()     )}, so falling back to the default '''
          f'''device: {str(jax.devices()[0]     )}.'''     )
      lowerCamelCase__  =     str(jax.devices()[0]     )
     lowerCamelCase__  =     jnp_array_kwargs

    @staticmethod
    def    a__				(					)							->							Dict[str, "jaxlib.xla_extension.Device"]:

     '''simple docstring'''




     import jax

     return {str(__lowerCamelCase     ): device for device in jax.devices()}

    def    a__				(					self     :     Optional[Any]				,     __lowerCamelCase     :     Optional[int]     )							->							List[str]:

     '''simple docstring'''




     import jax
     import jax.numpy as jnp

     if isinstance(__lowerCamelCase				,     __lowerCamelCase     ) and column:
      if all(
          isinstance(__lowerCamelCase				,     jax.Array     ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column     ):
       return jnp.stack(__lowerCamelCase				,     axis=0     )
     return column

    def    a__				(					self     :     List[Any]				,     __lowerCamelCase     :     List[Any]     )							->							Optional[int]:

     '''simple docstring'''




     import jax
     import jax.numpy as jnp

     if isinstance(__lowerCamelCase				,     (str, bytes, type(__lowerCamelCase     ))     ):
      return value
     elif isinstance(__lowerCamelCase				,     (np.character, np.ndarray)     ) and np.issubdtype(value.dtype				,     np.character     ):
      return value.tolist()

     lowerCamelCase__  =     {}

     if isinstance(__lowerCamelCase				,     (np.number, np.ndarray)     ) and np.issubdtype(value.dtype				,     np.integer     ):
      # the default int precision depends on the jax config
      # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision
      if jax.config.jax_enable_xaa:
       lowerCamelCase__  =     {"dtype": jnp.intaa}
      else:
       lowerCamelCase__  =     {"dtype": jnp.intaa}
     elif isinstance(__lowerCamelCase				,     (np.number, np.ndarray)     ) and np.issubdtype(value.dtype				,     np.floating     ):
      lowerCamelCase__  =     {"dtype": jnp.floataa}
     elif config.PIL_AVAILABLE and "PIL" in sys.modules:
      import PIL.Image

      if isinstance(__lowerCamelCase				,     PIL.Image.Image     ):
       lowerCamelCase__  =     np.asarray(__lowerCamelCase     )

        # using global variable since `jaxlib.xla_extension.Device` is not serializable neither
        # with `pickle` nor with `dill`, so we need to use a global variable instead
     global DEVICE_MAPPING
     if DEVICE_MAPPING is None:
      lowerCamelCase__  =     self._map_devices_to_str()

     with jax.default_device(DEVICE_MAPPING[self.device]     ):
      # calling jnp.array on a np.ndarray does copy the data
      # see https://github.com/google/jax/issues/4486
      return jnp.array(__lowerCamelCase				,     **{**default_dtype, **self.jnp_array_kwargs}     )

    def    a__				(					self     :     List[str]				,     __lowerCamelCase     :     Optional[Any]     )							->							Dict:

     '''simple docstring'''




     import jax

     # support for torch, tf, jax etc.
     if config.TORCH_AVAILABLE and "torch" in sys.modules:
      import torch

      if isinstance(__lowerCamelCase				,     torch.Tensor     ):
       return self._tensorize(data_struct.detach().cpu().numpy()[()]     )
     if hasattr(__lowerCamelCase				,     "__array__"     ) and not isinstance(__lowerCamelCase				,     jax.Array     ):
      lowerCamelCase__  =     data_struct.__array__()
     # support for nested types like struct of list of struct
     if isinstance(__lowerCamelCase				,     np.ndarray     ):
      if data_struct.dtype == object:  # jax arrays cannot be instantied from an array of objects
       return self._consolidate([self.recursive_tensorize(__lowerCamelCase     ) for substruct in data_struct]     )
     elif isinstance(__lowerCamelCase				,     (list, tuple)     ):
      return self._consolidate([self.recursive_tensorize(__lowerCamelCase     ) for substruct in data_struct]     )
     return self._tensorize(__lowerCamelCase     )

    def    a__				(					self     :     Any				,     __lowerCamelCase     :     dict     )							->							int:

     '''simple docstring'''




     return map_nested(self._recursive_tensorize				,     __lowerCamelCase				,     map_list=__lowerCamelCase     )

    def    a__				(					self     :     Union[str, Any]				,     __lowerCamelCase     :     pa.Table     )							->							Mapping:

     '''simple docstring'''




     lowerCamelCase__  =     self.numpy_arrow_extractor().extract_row(__lowerCamelCase     )
     lowerCamelCase__  =     self.python_features_decoder.decode_row(__lowerCamelCase     )
     return self.recursive_tensorize(__lowerCamelCase     )

    def    a__				(					self     :     List[Any]				,     __lowerCamelCase     :     pa.Table     )							->							"jax.Array":

     '''simple docstring'''




     lowerCamelCase__  =     self.numpy_arrow_extractor().extract_column(__lowerCamelCase     )
     lowerCamelCase__  =     self.python_features_decoder.decode_column(__lowerCamelCase				,     pa_table.column_names[0]     )
     lowerCamelCase__  =     self.recursive_tensorize(__lowerCamelCase     )
     lowerCamelCase__  =     self._consolidate(__lowerCamelCase     )
     return column




    def    a__				(					self     :     List[str]				,     __lowerCamelCase     :     pa.Table     )							->							Mapping:

     '''simple docstring'''




     lowerCamelCase__  =     self.numpy_arrow_extractor().extract_batch(__lowerCamelCase     )
     lowerCamelCase__  =     self.python_features_decoder.decode_batch(__lowerCamelCase     )
     lowerCamelCase__  =     self.recursive_tensorize(__lowerCamelCase     )
     for column_name in batch:
      lowerCamelCase__  =     self._consolidate(batch[column_name]     )
     return batch

