


import gc
import random
import unittest

import numpy as np
import torch
from transformers import XLMRobertaTokenizerFast

from diffusers import DDIMScheduler, KandinskyPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
from diffusers.utils import floats_tensor, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()







class lowerCAmelCase_		(					_a   ,		unittest.TestCase			):

 '''simple docstring'''

 __snake_case				=    KandinskyPipeline
 __snake_case				=    [
     """prompt""",
     """image_embeds""",
     """negative_image_embeds""",
 ]
 __snake_case				=    ["""prompt""", """negative_prompt""", """image_embeds""", """negative_image_embeds"""]
 __snake_case				=    [
     """generator""",
     """height""",
     """width""",
     """latents""",
     """guidance_scale""",
     """negative_prompt""",
     """num_inference_steps""",
     """return_dict""",
     """guidance_scale""",
     """num_images_per_prompt""",
     """output_type""",
     """return_dict""",
 ]
 __snake_case				=    False



 @property
 def 		UpperCamelCase__	(      self   ):
       return 32



 @property
 def 		UpperCamelCase__	(      self   ):
       return 32



 @property
 def 		UpperCamelCase__	(      self   ):
       return self.time_input_dim



 @property
 def 		UpperCamelCase__	(      self   ):
       return self.time_input_dim * 4



 @property
 def 		UpperCamelCase__	(      self   ):
       return 1_00



 @property
 def 		UpperCamelCase__	(      self   ):
       snake_case_			= XLMRobertaTokenizerFast.from_pretrained('''YiYiXu/tiny-random-mclip-base'''   )
       return tokenizer



 @property
 def 		UpperCamelCase__	(      self   ):
       torch.manual_seed(0   )
       snake_case_			= MCLIPConfig(
           numDims=self.cross_attention_dim						, transformerDimensions=self.text_embedder_hidden_size						, hidden_size=self.text_embedder_hidden_size						, intermediate_size=37						, num_attention_heads=4						, num_hidden_layers=5						, vocab_size=10_05						, )

       snake_case_			= MultilingualCLIP(__UpperCAmelCase   )
       snake_case_			= text_encoder.eval()

       return text_encoder



 @property
 def 		UpperCamelCase__	(      self   ):
       torch.manual_seed(0   )

       snake_case_			= {
           "in_channels": 4,
           # Out channels is double in channels because predicts mean and variance
           "out_channels": 8,
           "addition_embed_type": "text_image",
           "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"),
           "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"),
           "mid_block_type": "UNetMidBlock2DSimpleCrossAttn",
           "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2),
           "layers_per_block": 1,
           "encoder_hid_dim": self.text_embedder_hidden_size,
           "encoder_hid_dim_type": "text_image_proj",
           "cross_attention_dim": self.cross_attention_dim,
           "attention_head_dim": 4,
           "resnet_time_scale_shift": "scale_shift",
           "class_embed_type": None,
       }

       snake_case_			= UNetaDConditionModel(**__UpperCAmelCase   )
       return model



 @property
 def 		UpperCamelCase__	(      self   ):
       return {
           "block_out_channels": [32, 64],
           "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
           "in_channels": 3,
           "latent_channels": 4,
           "layers_per_block": 1,
           "norm_num_groups": 8,
           "norm_type": "spatial",
           "num_vq_embeddings": 12,
           "out_channels": 3,
           "up_block_types": [
               "AttnUpDecoderBlock2D",
               "UpDecoderBlock2D",
           ],
           "vq_embed_dim": 4,
       }



 @property
 def 		UpperCamelCase__	(      self   ):
       torch.manual_seed(0   )
       snake_case_			= VQModel(**self.dummy_movq_kwargs   )
       return model



 def 		UpperCamelCase__	(      self   ):
       snake_case_			= self.dummy_text_encoder
       snake_case_			= self.dummy_tokenizer
       snake_case_			= self.dummy_unet
       snake_case_			= self.dummy_movq

       snake_case_			= DDIMScheduler(
           num_train_timesteps=10_00						, beta_schedule='''linear'''						, beta_start=0.00_085						, beta_end=0.012						, clip_sample=__UpperCAmelCase						, set_alpha_to_one=__UpperCAmelCase						, steps_offset=1						, prediction_type='''epsilon'''						, thresholding=__UpperCAmelCase						, )

       snake_case_			= {
           "text_encoder": text_encoder,
           "tokenizer": tokenizer,
           "unet": unet,
           "scheduler": scheduler,
           "movq": movq,
       }
       return components



 def 		UpperCamelCase__	(      self						, _UpperCAmelCase						, _UpperCAmelCase=0   ):
       snake_case_			= floats_tensor((1, self.cross_attention_dim)						, rng=random.Random(__UpperCAmelCase   )   ).to(__UpperCAmelCase   )
       snake_case_			= floats_tensor((1, self.cross_attention_dim)						, rng=random.Random(seed + 1   )   ).to(__UpperCAmelCase   )
       if str(__UpperCAmelCase   ).startswith('''mps'''   ):
             snake_case_			= torch.manual_seed(__UpperCAmelCase   )
       else:
             snake_case_			= torch.Generator(device=__UpperCAmelCase   ).manual_seed(__UpperCAmelCase   )
       snake_case_			= {
           "prompt": "horse",
           "image_embeds": image_embeds,
           "negative_image_embeds": negative_image_embeds,
           "generator": generator,
           "height": 64,
           "width": 64,
           "guidance_scale": 4.0,
           "num_inference_steps": 2,
           "output_type": "np",
       }
       return inputs





 def 		UpperCamelCase__	(      self   ):
       snake_case_			= "cpu"

       snake_case_			= self.get_dummy_components()

       snake_case_			= self.pipeline_class(**__UpperCAmelCase   )
       snake_case_			= pipe.to(__UpperCAmelCase   )

       pipe.set_progress_bar_config(disable=__UpperCAmelCase   )

       snake_case_			= pipe(**self.get_dummy_inputs(__UpperCAmelCase   )   )
       snake_case_			= output.images

       snake_case_			= pipe(
           **self.get_dummy_inputs(__UpperCAmelCase   )						, return_dict=__UpperCAmelCase						, )[0]

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

       assert image.shape == (1, 64, 64, 3)

       snake_case_			= np.array(
           [0.328_663, 1.0, 0.23_216_873, 1.0, 0.92_717_564, 0.4_639_046, 0.96_894_777, 0.31_713_378, 0.6_293_953]   )

       assert (
           np.abs(image_slice.flatten() - expected_slice   ).max() < 1E-2
       ), F''' expected_slice {expected_slice}, but got {image_slice.flatten()}'''
       assert (
           np.abs(image_from_tuple_slice.flatten() - expected_slice   ).max() < 1E-2
       ), F''' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}'''







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

 '''simple docstring'''

 def 		UpperCamelCase__	(      self   ):
       # clean up the VRAM after each test
       super().tearDown()
       gc.collect()
       torch.cuda.empty_cache()





 def 		UpperCamelCase__	(      self   ):
       snake_case_			= load_numpy(
           '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
           '''/kandinsky/kandinsky_text2img_cat_fp16.npy'''   )

       snake_case_			= KandinskyPriorPipeline.from_pretrained(
           '''kandinsky-community/kandinsky-2-1-prior'''						, torch_dtype=torch.floataa   )
       pipe_prior.to(__UpperCAmelCase   )

       snake_case_			= KandinskyPipeline.from_pretrained('''kandinsky-community/kandinsky-2-1'''						, torch_dtype=torch.floataa   )
       snake_case_			= pipeline.to(__UpperCAmelCase   )
       pipeline.set_progress_bar_config(disable=__UpperCAmelCase   )

       snake_case_			= "red cat, 4k photo"

       snake_case_			= torch.Generator(device='''cuda'''   ).manual_seed(0   )
       snake_case_			= pipe_prior(
           __UpperCAmelCase						, generator=__UpperCAmelCase						, num_inference_steps=5						, negative_prompt=''''''						, ).to_tuple()

       snake_case_			= torch.Generator(device='''cuda'''   ).manual_seed(0   )
       snake_case_			= pipeline(
           __UpperCAmelCase						, image_embeds=__UpperCAmelCase						, negative_image_embeds=__UpperCAmelCase						, generator=__UpperCAmelCase						, num_inference_steps=1_00						, output_type='''np'''						, )

       snake_case_			= output.images[0]

       assert image.shape == (5_12, 5_12, 3)

       assert_mean_pixel_difference(__UpperCAmelCase						, __UpperCAmelCase   )



"""simple docstring"""







from dataclasses import dataclass
from typing import Any, Dict, Optional

import torch
import torch.nn.functional as F
from torch import nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..models.embeddings import ImagePositionalEmbeddings
from ..utils import BaseOutput, deprecate
from .attention import BasicTransformerBlock
from .embeddings import PatchEmbed
from .modeling_utils import ModelMixin






@dataclass
class 		_A    (    _a    ):







    """simple docstring"""




    UpperCAmelCase			:				torch.FloatTensor






class 		_A    (    _a       ,_a    ):







    """simple docstring"""




    @register_to_config
    def __init__(   self							:       List[Any]							,					__UpperCAmelCase							:       int = 16							,					__UpperCAmelCase							:       int = 88							,					__UpperCAmelCase							:       Optional[int] = None							,					__UpperCAmelCase							:       Optional[int] = None							,					__UpperCAmelCase							:       int = 1							,					__UpperCAmelCase							:       float = 0.0							,					__UpperCAmelCase							:       int = 32							,					__UpperCAmelCase							:       Optional[int] = None							,					__UpperCAmelCase							:       bool = False							,					__UpperCAmelCase							:       Optional[int] = None							,					__UpperCAmelCase							:       Optional[int] = None							,					__UpperCAmelCase							:       Optional[int] = None							,					__UpperCAmelCase							:       str = "geglu"							,					__UpperCAmelCase							:       Optional[int] = None							,					__UpperCAmelCase							:       bool = False							,					__UpperCAmelCase							:       bool = False							,					__UpperCAmelCase							:       bool = False							,					__UpperCAmelCase							:       str = "layer_norm"							,					__UpperCAmelCase							:       bool = True							,					):
      super().__init__()
      a		:						Optional[Any] 				=     use_linear_projection
      a		:						Any 				=     num_attention_heads
      a		:						Dict 				=     attention_head_dim
      a		:						str 				=     num_attention_heads * attention_head_dim

      # 1. Transformer2DModel can process both standard continuous images of shape `(batch_size, num_channels, width, height)` as well as quantized image embeddings of shape `(batch_size, num_image_vectors)`
      # Define whether input is continuous or discrete depending on configuration
      a		:						int 				=     (in_channels is not None) and (patch_size is None)
      a		:						str 				=     num_vector_embeds is not None
      a		:						Dict 				=     in_channels is not None and patch_size is not None

      if norm_type == "layer_norm" and num_embeds_ada_norm is not None:
        a		:						Dict 				=     (
            f'''The configuration file of this model: {self.__class__} is outdated. `norm_type` is either not set or'''
            " incorrectly set to `'layer_norm'`.Make sure to set `norm_type` to `'ada_norm'` in the config."
            " Please make sure to update the config accordingly as leaving `norm_type` might led to incorrect"
            " results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it"
            " would be very nice if you could open a Pull request for the `transformer/config.json` file"
        )
        deprecate("norm_type!=num_embeds_ada_norm"							,					"1.0.0"							,					__UpperCAmelCase							,					standard_warn=__UpperCAmelCase)
        a		:						Tuple 				=     "ada_norm"

      if self.is_input_continuous and self.is_input_vectorized:
        raise ValueError(
            f'''Cannot define both `in_channels`: {in_channels} and `num_vector_embeds`: {num_vector_embeds}. Make'''
            " sure that either `in_channels` or `num_vector_embeds` is None.")
      elif self.is_input_vectorized and self.is_input_patches:
        raise ValueError(
            f'''Cannot define both `num_vector_embeds`: {num_vector_embeds} and `patch_size`: {patch_size}. Make'''
            " sure that either `num_vector_embeds` or `num_patches` is None.")
      elif not self.is_input_continuous and not self.is_input_vectorized and not self.is_input_patches:
        raise ValueError(
            f'''Has to define `in_channels`: {in_channels}, `num_vector_embeds`: {num_vector_embeds}, or patch_size:'''
            f''' {patch_size}. Make sure that `in_channels`, `num_vector_embeds` or `num_patches` is not None.''')

      # 2. Define input layers
      if self.is_input_continuous:
        a		:						Union[str, Any] 				=     in_channels

        a		:						Dict 				=     torch.nn.GroupNorm(num_groups=__UpperCAmelCase							,					num_channels=__UpperCAmelCase							,					eps=1e-6							,					affine=__UpperCAmelCase)
        if use_linear_projection:
          a		:						Tuple 				=     nn.Linear(__UpperCAmelCase							,					__UpperCAmelCase)
        else:
          a		:						str 				=     nn.Convad(__UpperCAmelCase							,					__UpperCAmelCase							,					kernel_size=1							,					stride=1							,					padding=0)
      elif self.is_input_vectorized:
        assert sample_size is not None, "Transformer2DModel over discrete input must provide sample_size"
        assert num_vector_embeds is not None, "Transformer2DModel over discrete input must provide num_embed"

        a		:						Dict 				=     sample_size
        a		:						List[str] 				=     sample_size
        a		:						Any 				=     num_vector_embeds
        a		:						Union[str, Any] 				=     self.height * self.width

        a		:						Any 				=     ImagePositionalEmbeddings(
            num_embed=__UpperCAmelCase							,					embed_dim=__UpperCAmelCase							,					height=self.height							,					width=self.width)
      elif self.is_input_patches:
        assert sample_size is not None, "Transformer2DModel over patched input must provide sample_size"

        a		:						int 				=     sample_size
        a		:						Optional[int] 				=     sample_size

        a		:						Dict 				=     patch_size
        a		:						Tuple 				=     PatchEmbed(
            height=__UpperCAmelCase							,					width=__UpperCAmelCase							,					patch_size=__UpperCAmelCase							,					in_channels=__UpperCAmelCase							,					embed_dim=__UpperCAmelCase							,					)

      # 3. Define transformers blocks
      a		:						int 				=     nn.ModuleList(
          [
              BasicTransformerBlock(
                  __UpperCAmelCase							,					__UpperCAmelCase							,					__UpperCAmelCase							,					dropout=__UpperCAmelCase							,					cross_attention_dim=__UpperCAmelCase							,					activation_fn=__UpperCAmelCase							,					num_embeds_ada_norm=__UpperCAmelCase							,					attention_bias=__UpperCAmelCase							,					only_cross_attention=__UpperCAmelCase							,					upcast_attention=__UpperCAmelCase							,					norm_type=__UpperCAmelCase							,					norm_elementwise_affine=__UpperCAmelCase							,					)
              for d in range(__UpperCAmelCase)
          ])

      # 4. Define output layers
      a		:						str 				=     in_channels if out_channels is None else out_channels
      if self.is_input_continuous:
        # TODO: should use out_channels for continuous projections
        if use_linear_projection:
          a		:						List[Any] 				=     nn.Linear(__UpperCAmelCase							,					__UpperCAmelCase)
        else:
          a		:						Optional[Any] 				=     nn.Convad(__UpperCAmelCase							,					__UpperCAmelCase							,					kernel_size=1							,					stride=1							,					padding=0)
      elif self.is_input_vectorized:
        a		:						List[Any] 				=     nn.LayerNorm(__UpperCAmelCase)
        a		:						int 				=     nn.Linear(__UpperCAmelCase							,					self.num_vector_embeds - 1)
      elif self.is_input_patches:
        a		:						int 				=     nn.LayerNorm(__UpperCAmelCase							,					elementwise_affine=__UpperCAmelCase							,					eps=1e-6)
        a		:						List[Any] 				=     nn.Linear(__UpperCAmelCase							,					2 * inner_dim)
        a		:						Union[str, Any] 				=     nn.Linear(__UpperCAmelCase							,					patch_size * patch_size * self.out_channels)






    def       __snake_case				(   self							:       Dict							,					__UpperCAmelCase							:       torch.Tensor							,					__UpperCAmelCase							:       Optional[torch.Tensor] = None							,					__UpperCAmelCase							:       Optional[torch.LongTensor] = None							,					__UpperCAmelCase							:       Optional[torch.LongTensor] = None							,					__UpperCAmelCase							:       Dict[str, Any] = None							,					__UpperCAmelCase							:       Optional[torch.Tensor] = None							,					__UpperCAmelCase							:       Optional[torch.Tensor] = None							,					__UpperCAmelCase							:       bool = True							,					):
      # ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
      #   we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
      #   we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
      # expects mask of shape:
      #   [batch, key_tokens]
      # adds singleton query_tokens dimension:
      #   [batch,                    1, key_tokens]
      # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
      #   [batch,  heads, query_tokens, key_tokens] (e.g. torch sdp attn)
      #   [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
      if attention_mask is not None and attention_mask.ndim == 2:
        # assume that mask is expressed as:
        #   (1 = keep,      0 = discard)
        # convert mask into a bias that can be added to attention scores:
        #       (keep = +0,     discard = -10000.0)
        a		:						Optional[Any] 				=     (1 - attention_mask.to(hidden_states.dtype)) * -10_000.0
        a		:						Tuple 				=     attention_mask.unsqueeze(1)

      # convert encoder_attention_mask to a bias the same way we do for attention_mask
      if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:
        a		:						List[Any] 				=     (1 - encoder_attention_mask.to(hidden_states.dtype)) * -10_000.0
        a		:						List[Any] 				=     encoder_attention_mask.unsqueeze(1)

      # 1. Input
      if self.is_input_continuous:
        a				,						a				,						a				,						a		:						Any 				=     hidden_states.shape
        a		:						Optional[int] 				=     hidden_states

        a		:						int 				=     self.norm(__UpperCAmelCase)
        if not self.use_linear_projection:
          a		:						str 				=     self.proj_in(__UpperCAmelCase)
          a		:						Tuple 				=     hidden_states.shape[1]
          a		:						Optional[int] 				=     hidden_states.permute(0							,					2							,					3							,					1).reshape(__UpperCAmelCase							,					height * width							,					__UpperCAmelCase)
        else:
          a		:						Union[str, Any] 				=     hidden_states.shape[1]
          a		:						Optional[Any] 				=     hidden_states.permute(0							,					2							,					3							,					1).reshape(__UpperCAmelCase							,					height * width							,					__UpperCAmelCase)
          a		:						int 				=     self.proj_in(__UpperCAmelCase)
      elif self.is_input_vectorized:
        a		:						Dict 				=     self.latent_image_embedding(__UpperCAmelCase)
      elif self.is_input_patches:
        a		:						Any 				=     self.pos_embed(__UpperCAmelCase)

      # 2. Blocks
      for block in self.transformer_blocks:
        a		:						str 				=     block(
            __UpperCAmelCase							,					attention_mask=__UpperCAmelCase							,					encoder_hidden_states=__UpperCAmelCase							,					encoder_attention_mask=__UpperCAmelCase							,					timestep=__UpperCAmelCase							,					cross_attention_kwargs=__UpperCAmelCase							,					class_labels=__UpperCAmelCase							,					)

      # 3. Output
      if self.is_input_continuous:
        if not self.use_linear_projection:
          a		:						Optional[int] 				=     hidden_states.reshape(__UpperCAmelCase							,					__UpperCAmelCase							,					__UpperCAmelCase							,					__UpperCAmelCase).permute(0							,					3							,					1							,					2).contiguous()
          a		:						Tuple 				=     self.proj_out(__UpperCAmelCase)
        else:
          a		:						str 				=     self.proj_out(__UpperCAmelCase)
          a		:						Optional[Any] 				=     hidden_states.reshape(__UpperCAmelCase							,					__UpperCAmelCase							,					__UpperCAmelCase							,					__UpperCAmelCase).permute(0							,					3							,					1							,					2).contiguous()

        a		:						Tuple 				=     hidden_states + residual
      elif self.is_input_vectorized:
        a		:						Tuple 				=     self.norm_out(__UpperCAmelCase)
        a		:						Any 				=     self.out(__UpperCAmelCase)
        # (batch, self.num_vector_embeds - 1, self.num_latent_pixels)
        a		:						Optional[int] 				=     logits.permute(0							,					2							,					1)

        # log(p(x_0))
        a		:						str 				=     F.log_softmax(logits.double()							,					dim=1).float()
      elif self.is_input_patches:
        # TODO: cleanup!
        a		:						Optional[int] 				=     self.transformer_blocks[0].norma.emb(
            __UpperCAmelCase							,					__UpperCAmelCase							,					hidden_dtype=hidden_states.dtype)
        a				,						a		:						Optional[Any] 				=     self.proj_out_a(F.silu(__UpperCAmelCase)).chunk(2							,					dim=1)
        a		:						List[str] 				=     self.norm_out(__UpperCAmelCase) * (1 + scale[:, None]) + shift[:, None]
        a		:						Union[str, Any] 				=     self.proj_out_a(__UpperCAmelCase)

        # unpatchify
        a		:						Dict 				=     int(hidden_states.shape[1] ** 0.5)
        a		:						Optional[int] 				=     hidden_states.reshape(
            shape=(-1, height, width, self.patch_size, self.patch_size, self.out_channels))
        a		:						int 				=     torch.einsum("nhwpqc->nchpwq"							,					__UpperCAmelCase)
        a		:						List[str] 				=     hidden_states.reshape(
            shape=(-1, self.out_channels, height * self.patch_size, width * self.patch_size))

      if not return_dict:
        return (output,)

      return TransformeraDModelOutput(sample=__UpperCAmelCase)






