






'''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       (							_lowerCamelCase ,       _lowerCamelCase ,       _lowerCamelCase ,       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     :     Dict     )							->							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=__lowerCamelCase				,     projection_dim=__lowerCamelCase				,     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=__lowerCamelCase				,     num_layers=1				,     )

     torch.manual_seed(0     )
     lowerCamelCase__  =     DDPMScheduler(
         variance_type="fixed_small_log"				,     prediction_type="sample"				,     num_train_timesteps=1000				,     clip_sample=__lowerCamelCase				,     clip_sample_range=5.0				,     beta_schedule="squaredcos_cap_v2"				,     )

     # regular denoising components

     torch.manual_seed(0     )
     lowerCamelCase__  =     StableUnCLIPImageNormalizer(embedding_dim=__lowerCamelCase     )
     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=__lowerCamelCase				,     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=__lowerCamelCase				,     layers_per_block=1				,     upcast_attention=__lowerCamelCase				,     use_linear_projection=__lowerCamelCase				,     )

     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=__lowerCamelCase				,     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     :     Tuple				,     __lowerCamelCase     :     Optional[int]=0     )							->							List[str]:

     '''simple docstring'''




     if str(__lowerCamelCase     ).startswith("mps"     ):
      lowerCamelCase__  =     torch.manual_seed(__lowerCamelCase     )
     else:
      lowerCamelCase__  =     torch.Generator(device=__lowerCamelCase     ).manual_seed(__lowerCamelCase     )
     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[Any]     )							->							int:

     '''simple docstring'''




     lowerCamelCase__  =     torch_device == "cpu"

     self._test_attention_slicing_forward_pass(test_max_difference=__lowerCamelCase     )




    def    a__				(					self     :     str     )							->							str:

     '''simple docstring'''




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

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


    '''simple docstring'''

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

     '''simple docstring'''




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

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

     '''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(__lowerCamelCase     )
     pipe.set_progress_bar_config(disable=__lowerCamelCase     )
     # 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=__lowerCamelCase				,     output_type="np"     )

     lowerCamelCase__  =     output.images[0]

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

     assert_mean_pixel_difference(__lowerCamelCase				,     __lowerCamelCase     )




    def    a__				(					self     :     Any     )							->							Tuple:

     '''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(__lowerCamelCase     )
     pipe.set_progress_bar_config(disable=__lowerCamelCase     )
     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'''





import warnings

from transformers import AutoTokenizer
from transformers.utils import is_torch_available
from transformers.utils.generic import ExplicitEnum

from ...processing_utils import ProcessorMixin


if is_torch_available():
 import torch
class 				lowercase       (							_lowerCamelCase      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							"char"
    lowerCAmelCase__      				=							"bpe"
    lowerCAmelCase__      				=							"wp"
__A							:							Any  							=		(DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE)
class 				lowercase       (							_lowerCamelCase      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							["image_processor", "char_tokenizer"]
    lowerCAmelCase__      				=							"ViTImageProcessor"
    lowerCAmelCase__      				=							"MgpstrTokenizer"

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

     '''simple docstring'''




     lowerCamelCase__  =     None
     if "feature_extractor" in kwargs:
      warnings.warn(
          "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
          " instead."				,     __lowerCamelCase				,     )
      lowerCamelCase__  =     kwargs.pop("feature_extractor"     )

     lowerCamelCase__  =     image_processor if image_processor is not None else feature_extractor
     if image_processor is None:
      raise ValueError("You need to specify an `image_processor`."     )
     if tokenizer is None:
      raise ValueError("You need to specify a `tokenizer`."     )

     lowerCamelCase__  =     tokenizer
     lowerCamelCase__  =     AutoTokenizer.from_pretrained("gpt2"     )
     lowerCamelCase__  =     AutoTokenizer.from_pretrained("bert-base-uncased"     )

     super().__init__(__lowerCamelCase				,     __lowerCamelCase     )

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

     '''simple docstring'''




     if images is None and text is None:
      raise ValueError("You need to specify either an `images` or `text` input to process."     )

     if images is not None:
      lowerCamelCase__  =     self.image_processor(__lowerCamelCase				,     return_tensors=__lowerCamelCase				,     **__lowerCamelCase     )
     if text is not None:
      lowerCamelCase__  =     self.char_tokenizer(__lowerCamelCase				,     return_tensors=__lowerCamelCase				,     **__lowerCamelCase     )

     if text is None:
      return inputs
     elif images is None:
      return encodings
     else:
      lowerCamelCase__  =     encodings["input_ids"]
      return inputs

    def    a__				(					self     :     Any				,     __lowerCamelCase     :     Tuple     )							->							Tuple:

     '''simple docstring'''




     lowerCamelCase__  ,	lowerCamelCase__  ,	lowerCamelCase__  =     sequences
     lowerCamelCase__  =     char_preds.size(0     )

     lowerCamelCase__  ,	lowerCamelCase__  =     self._decode_helper(__lowerCamelCase				,     "char"     )
     lowerCamelCase__  ,	lowerCamelCase__  =     self._decode_helper(__lowerCamelCase				,     "bpe"     )
     lowerCamelCase__  ,	lowerCamelCase__  =     self._decode_helper(__lowerCamelCase				,     "wp"     )

     lowerCamelCase__  =     []
     lowerCamelCase__  =     []
     for i in range(__lowerCamelCase     ):
      lowerCamelCase__  =     [char_scores[i], bpe_scores[i], wp_scores[i]]
      lowerCamelCase__  =     [char_strs[i], bpe_strs[i], wp_strs[i]]
      lowerCamelCase__  =     scores.index(max(__lowerCamelCase     )     )
      final_strs.append(strs[max_score_index]     )
      final_scores.append(scores[max_score_index]     )

     lowerCamelCase__  =     {}
     lowerCamelCase__  =     final_strs
     lowerCamelCase__  =     final_scores
     lowerCamelCase__  =     char_strs
     lowerCamelCase__  =     bpe_strs
     lowerCamelCase__  =     wp_strs
     return out

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

     '''simple docstring'''




     if format == DecodeType.CHARACTER:
      lowerCamelCase__  =     self.char_decode
      lowerCamelCase__  =     1
      lowerCamelCase__  =     "[s]"
     elif format == DecodeType.BPE:
      lowerCamelCase__  =     self.bpe_decode
      lowerCamelCase__  =     2
      lowerCamelCase__  =     "#"
     elif format == DecodeType.WORDPIECE:
      lowerCamelCase__  =     self.wp_decode
      lowerCamelCase__  =     102
      lowerCamelCase__  =     "[SEP]"
     else:
      raise ValueError(f'''Format {format} is not supported.'''     )

     lowerCamelCase__  ,	lowerCamelCase__  =     [], []
     lowerCamelCase__  =     pred_logits.size(0     )
     lowerCamelCase__  =     pred_logits.size(1     )
     lowerCamelCase__  ,	lowerCamelCase__  =     pred_logits.topk(1				,     dim=-1				,     largest=__lowerCamelCase				,     sorted=__lowerCamelCase     )
     lowerCamelCase__  =     preds_index.view(-1				,     __lowerCamelCase     )[:, 1:]
     lowerCamelCase__  =     decoder(__lowerCamelCase     )
     lowerCamelCase__  ,	lowerCamelCase__  =     torch.nn.functional.softmax(__lowerCamelCase				,     dim=2     ).max(dim=2     )
     lowerCamelCase__  =     preds_max_prob[:, 1:]

     for index in range(__lowerCamelCase     ):
      lowerCamelCase__  =     preds_str[index].find(__lowerCamelCase     )
      lowerCamelCase__  =     preds_str[index][:pred_eos]
      lowerCamelCase__  =     preds_index[index].cpu().tolist()
      lowerCamelCase__  =     pred_index.index(__lowerCamelCase     ) if eos_token in pred_index else -1
      lowerCamelCase__  =     preds_max_prob[index][: pred_eos_index + 1]
      lowerCamelCase__  =     pred_max_prob.cumprod(dim=0     )[-1] if pred_max_prob.nelement() != 0 else 0.0
      dec_strs.append(__lowerCamelCase     )
      conf_scores.append(__lowerCamelCase     )

     return dec_strs, conf_scores

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

     '''simple docstring'''




     lowerCamelCase__  =     [seq.replace(" "				,     ""     ) for seq in self.char_tokenizer.batch_decode(__lowerCamelCase     )]
     return decode_strs

    def    a__				(					self     :     Optional[Any]				,     __lowerCamelCase     :     Tuple     )							->							Union[str, Any]:

     '''simple docstring'''




     return self.bpe_tokenizer.batch_decode(__lowerCamelCase     )




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

     '''simple docstring'''




     lowerCamelCase__  =     [seq.replace(" "				,     ""     ) for seq in self.wp_tokenizer.batch_decode(__lowerCamelCase     )]
     return decode_strs

