



"""simple docstring"""


import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import XLMRobertaTokenizerFast

from diffusers import DDIMScheduler, KandinskyImgaImgPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
from diffusers.utils import floats_tensor, load_image, 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 			_a (					lowerCAmelCase			,							unittest.TestCase):
			"""simple docstring"""
			UpperCamelCase__			      =	KandinskyImgaImgPipeline
			UpperCamelCase__			      =	["""prompt""", """image_embeds""", """negative_image_embeds""", """image"""]
			UpperCamelCase__			      =	[
			    """prompt""",
			    """negative_prompt""",
			    """image_embeds""",
			    """negative_image_embeds""",
			    """image""",
			]
			UpperCamelCase__			      =	[
			    """generator""",
			    """height""",
			    """width""",
			    """strength""",
			    """guidance_scale""",
			    """negative_prompt""",
			    """num_inference_steps""",
			    """return_dict""",
			    """guidance_scale""",
			    """num_images_per_prompt""",
			    """output_type""",
			    """return_dict""",
			]
			UpperCamelCase__			      =	False



			@property
			def  lowercase__						(		self     :    Optional[int]   )->List[Any]:
							return 3_2



			@property
			def  lowercase__						(		self     :    List[Any]   )->Optional[int]:
							return 3_2



			@property
			def  lowercase__						(		self     :    Any   )->Optional[Any]:
							return self.time_input_dim



			@property
			def  lowercase__						(		self     :    Dict   )->int:
							return self.time_input_dim * 4



			@property
			def  lowercase__						(		self     :    int   )->int:
							return 1_0_0



			@property
			def  lowercase__						(		self     :    Optional[Any]   )->int:
							_UpperCAmelCase					=    XLMRobertaTokenizerFast.from_pretrained('''YiYiXu/tiny-random-mclip-base'''   )
							return tokenizer



			@property
			def  lowercase__						(		self     :    Any   )->str:
							torch.manual_seed(0   )
							_UpperCAmelCase					=    MCLIPConfig(
							    numDims=self.cross_attention_dim				,   transformerDimensions=self.text_embedder_hidden_size				,   hidden_size=self.text_embedder_hidden_size				,   intermediate_size=3_7				,   num_attention_heads=4				,   num_hidden_layers=5				,   vocab_size=1_0_0_5				,   )

							_UpperCAmelCase					=    MultilingualCLIP(__UpperCamelCase   )
							_UpperCAmelCase					=    text_encoder.eval()

							return text_encoder



			@property
			def  lowercase__						(		self     :    int   )->int:
							torch.manual_seed(0   )

							_UpperCAmelCase					=    {
							    '''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,
							}

							_UpperCAmelCase					=    UNetaDConditionModel(**__UpperCamelCase   )
							return model



			@property
			def  lowercase__						(		self     :    Any   )->str:
							return {
							    "block_out_channels": [3_2, 6_4],
							    "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": 1_2,
							    "out_channels": 3,
							    "up_block_types": [
							        "AttnUpDecoderBlock2D",
							        "UpDecoderBlock2D",
							    ],
							    "vq_embed_dim": 4,
							}



			@property
			def  lowercase__						(		self     :    Optional[int]   )->Optional[Any]:
							torch.manual_seed(0   )
							_UpperCAmelCase					=    VQModel(**self.dummy_movq_kwargs   )
							return model



			def  lowercase__						(		self     :    str   )->int:
							_UpperCAmelCase					=    self.dummy_text_encoder
							_UpperCAmelCase					=    self.dummy_tokenizer
							_UpperCAmelCase					=    self.dummy_unet
							_UpperCAmelCase					=    self.dummy_movq

							_UpperCAmelCase					=    {
							    '''num_train_timesteps''': 1_0_0_0,
							    '''beta_schedule''': '''linear''',
							    '''beta_start''': 0.0_0_0_8_5,
							    '''beta_end''': 0.0_1_2,
							    '''clip_sample''': False,
							    '''set_alpha_to_one''': False,
							    '''steps_offset''': 0,
							    '''prediction_type''': '''epsilon''',
							    '''thresholding''': False,
							}

							_UpperCAmelCase					=    DDIMScheduler(**__UpperCamelCase   )

							_UpperCAmelCase					=    {
							    '''text_encoder''': text_encoder,
							    '''tokenizer''': tokenizer,
							    '''unet''': unet,
							    '''scheduler''': scheduler,
							    '''movq''': movq,
							}

							return components



			def  lowercase__						(		self     :    Dict				,   __UpperCamelCase     :    Dict				,   __UpperCamelCase     :    str=0   )->Union[str, Any]:
							_UpperCAmelCase					=    floats_tensor((1, self.cross_attention_dim)				,   rng=random.Random(__UpperCamelCase   )   ).to(__UpperCamelCase   )
							_UpperCAmelCase					=    floats_tensor((1, self.cross_attention_dim)				,   rng=random.Random(seed + 1   )   ).to(__UpperCamelCase   )
							# create init_image
							_UpperCAmelCase					=    floats_tensor((1, 3, 6_4, 6_4)				,   rng=random.Random(__UpperCamelCase   )   ).to(__UpperCamelCase   )
							_UpperCAmelCase					=    image.cpu().permute(0				,   2				,   3				,   1   )[0]
							_UpperCAmelCase					=    Image.fromarray(np.uinta(__UpperCamelCase   )   ).convert('''RGB'''   ).resize((2_5_6, 2_5_6)   )

							if str(__UpperCamelCase   ).startswith('''mps'''   ):
											_UpperCAmelCase					=    torch.manual_seed(__UpperCamelCase   )
							else:
											_UpperCAmelCase					=    torch.Generator(device=__UpperCamelCase   ).manual_seed(__UpperCamelCase   )
							_UpperCAmelCase					=    {
							    '''prompt''': '''horse''',
							    '''image''': init_image,
							    '''image_embeds''': image_embeds,
							    '''negative_image_embeds''': negative_image_embeds,
							    '''generator''': generator,
							    '''height''': 6_4,
							    '''width''': 6_4,
							    '''num_inference_steps''': 1_0,
							    '''guidance_scale''': 7.0,
							    '''strength''': 0.2,
							    '''output_type''': '''np''',
							}
							return inputs



			def  lowercase__						(		self     :    int   )->Union[str, Any]:
							_UpperCAmelCase					=    '''cpu'''

							_UpperCAmelCase					=    self.get_dummy_components()

							_UpperCAmelCase					=    self.pipeline_class(**__UpperCamelCase   )
							_UpperCAmelCase					=    pipe.to(__UpperCamelCase   )

							pipe.set_progress_bar_config(disable=__UpperCamelCase   )

							_UpperCAmelCase					=    pipe(**self.get_dummy_inputs(__UpperCamelCase   )   )
							_UpperCAmelCase					=    output.images

							_UpperCAmelCase					=    pipe(
							    **self.get_dummy_inputs(__UpperCamelCase   )				,   return_dict=__UpperCamelCase				,   )[0]

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

							assert image.shape == (1, 6_4, 6_4, 3)

							_UpperCAmelCase					=    np.array(
							    [0.6_1_4_7_4_9_4_3, 0.6_0_7_3_5_3_9, 0.4_3_3_0_8_5_4_4, 0.5_9_2_8_2_6_9, 0.4_7_4_9_3_5_9_5, 0.4_6_7_5_5_9_7_3, 0.4_6_1_3_8_3_8, 0.4_5_3_6_8_7_9_7, 0.5_0_1_1_9_2_3_3]   )
							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 			_a (					unittest.TestCase):
			"""simple docstring"""



			def  lowercase__						(		self     :    Union[str, Any]   )->Optional[int]:
							# clean up the VRAM after each test
							super().tearDown()
							gc.collect()
							torch.cuda.empty_cache()



			def  lowercase__						(		self     :    Tuple   )->Tuple:
							_UpperCAmelCase					=    load_numpy(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
							    '''/kandinsky/kandinsky_img2img_frog.npy'''   )

							_UpperCAmelCase					=    load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main''' '''/kandinsky/cat.png'''   )
							_UpperCAmelCase					=    '''A red cartoon frog, 4k'''

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

							_UpperCAmelCase					=    KandinskyImgaImgPipeline.from_pretrained(
							    '''kandinsky-community/kandinsky-2-1'''				,   torch_dtype=torch.floataa   )
							_UpperCAmelCase					=    pipeline.to(__UpperCamelCase   )

							pipeline.set_progress_bar_config(disable=__UpperCamelCase   )

							_UpperCAmelCase					=    torch.Generator(device='''cpu'''   ).manual_seed(0   )
							_UpperCAmelCase		,						_UpperCAmelCase					=    pipe_prior(
							    __UpperCamelCase				,   generator=__UpperCamelCase				,   num_inference_steps=5				,   negative_prompt=''''''				,   ).to_tuple()

							_UpperCAmelCase					=    pipeline(
							    __UpperCamelCase				,   image=__UpperCamelCase				,   image_embeds=__UpperCamelCase				,   negative_image_embeds=__UpperCamelCase				,   generator=__UpperCamelCase				,   num_inference_steps=1_0_0				,   height=7_6_8				,   width=7_6_8				,   strength=0.2				,   output_type='''np'''				,   )

							_UpperCAmelCase					=    output.images[0]

							assert image.shape == (7_6_8, 7_6_8, 3)

							assert_mean_pixel_difference(__UpperCamelCase				,   __UpperCamelCase   )








"""simple docstring"""


from typing import List, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...utils import logging


__A   :							Any										=   logging.get_logger(__name__)

__A   :							Dict										=   {
    "huggingface/informer-tourism-monthly": (
        "https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json"
    ),
    # See all Informer models at https://huggingface.co/models?filter=informer
}
class 			_a (					lowerCAmelCase):
			"""simple docstring"""
			UpperCamelCase__			      =	"""informer"""
			UpperCamelCase__			      =	{
			    """hidden_size""": """d_model""",
			    """num_attention_heads""": """encoder_attention_heads""",
			    """num_hidden_layers""": """encoder_layers""",
			}



			def __init__(		self     :    List[str]				,   __UpperCamelCase     :    Optional[int] = None				,   __UpperCamelCase     :    Optional[int] = None				,   __UpperCamelCase     :    str = "student_t"				,   __UpperCamelCase     :    str = "nll"				,   __UpperCamelCase     :    int = 1				,   __UpperCamelCase     :    List[int] = None				,   __UpperCamelCase     :    Optional[Union[str, bool]] = "mean"				,   __UpperCamelCase     :    int = 0				,   __UpperCamelCase     :    int = 0				,   __UpperCamelCase     :    int = 0				,   __UpperCamelCase     :    int = 0				,   __UpperCamelCase     :    Optional[List[int]] = None				,   __UpperCamelCase     :    Optional[List[int]] = None				,   __UpperCamelCase     :    int = 6_4				,   __UpperCamelCase     :    int = 3_2				,   __UpperCamelCase     :    int = 3_2				,   __UpperCamelCase     :    int = 2				,   __UpperCamelCase     :    int = 2				,   __UpperCamelCase     :    int = 2				,   __UpperCamelCase     :    int = 2				,   __UpperCamelCase     :    bool = True				,   __UpperCamelCase     :    str = "gelu"				,   __UpperCamelCase     :    float = 0.0_5				,   __UpperCamelCase     :    float = 0.1				,   __UpperCamelCase     :    float = 0.1				,   __UpperCamelCase     :    float = 0.1				,   __UpperCamelCase     :    float = 0.1				,   __UpperCamelCase     :    int = 1_0_0				,   __UpperCamelCase     :    float = 0.0_2				,   __UpperCamelCase     :    Optional[Any]=True				,   __UpperCamelCase     :    str = "prob"				,   __UpperCamelCase     :    int = 5				,   __UpperCamelCase     :    bool = True				,   **__UpperCamelCase     :    Union[str, Any]				,   )->Dict:
							# time series specific configuration
							_UpperCAmelCase					=    prediction_length
							_UpperCAmelCase					=    context_length or prediction_length
							_UpperCAmelCase					=    distribution_output
							_UpperCAmelCase					=    loss
							_UpperCAmelCase					=    input_size
							_UpperCAmelCase					=    num_time_features
							_UpperCAmelCase					=    lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7]
							_UpperCAmelCase					=    scaling
							_UpperCAmelCase					=    num_dynamic_real_features
							_UpperCAmelCase					=    num_static_real_features
							_UpperCAmelCase					=    num_static_categorical_features

							# set cardinality
							if cardinality and num_static_categorical_features > 0:
											if len(__UpperCamelCase   ) != num_static_categorical_features:
															raise ValueError(
															    '''The cardinality should be a list of the same length as `num_static_categorical_features`'''   )
											_UpperCAmelCase					=    cardinality
							else:
											_UpperCAmelCase					=    [0]

							# set embedding_dimension
							if embedding_dimension and num_static_categorical_features > 0:
											if len(__UpperCamelCase   ) != num_static_categorical_features:
															raise ValueError(
															    '''The embedding dimension should be a list of the same length as `num_static_categorical_features`'''   )
											_UpperCAmelCase					=    embedding_dimension
							else:
											_UpperCAmelCase					=    [min(5_0				,   (cat + 1) // 2   ) for cat in self.cardinality]

							_UpperCAmelCase					=    num_parallel_samples

							# Transformer architecture configuration
							_UpperCAmelCase					=    input_size * len(self.lags_sequence   ) + self._number_of_features
							_UpperCAmelCase					=    d_model
							_UpperCAmelCase					=    encoder_attention_heads
							_UpperCAmelCase					=    decoder_attention_heads
							_UpperCAmelCase					=    encoder_ffn_dim
							_UpperCAmelCase					=    decoder_ffn_dim
							_UpperCAmelCase					=    encoder_layers
							_UpperCAmelCase					=    decoder_layers

							_UpperCAmelCase					=    dropout
							_UpperCAmelCase					=    attention_dropout
							_UpperCAmelCase					=    activation_dropout
							_UpperCAmelCase					=    encoder_layerdrop
							_UpperCAmelCase					=    decoder_layerdrop

							_UpperCAmelCase					=    activation_function
							_UpperCAmelCase					=    init_std

							_UpperCAmelCase					=    use_cache

							# Informer
							_UpperCAmelCase					=    attention_type
							_UpperCAmelCase					=    sampling_factor
							_UpperCAmelCase					=    distil

							super().__init__(is_encoder_decoder=__UpperCamelCase				,   **__UpperCamelCase   )



			@property
			def  lowercase__						(		self     :    Optional[int]   )->int:
							return (
							    sum(self.embedding_dimension   )
							    + self.num_dynamic_real_features
							    + self.num_time_features
							    + self.num_static_real_features
							    + self.input_size * 2  # the log1p(abs(loc)) and log(scale) features
							)



