


'''simple docstring'''




from typing import List, Optional, Union

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


_lowerCAmelCase  :		Dict		     =	logging.get_logger(__name__)

_lowerCAmelCase  :		Any		     =	{
    'huggingface/time-series-transformer-tourism-monthly': (
        'https://huggingface.co/huggingface/time-series-transformer-tourism-monthly/resolve/main/config.json'
    ),
    # See all TimeSeriesTransformer models at https://huggingface.co/models?filter=time_series_transformer
}



class  lowerCAmelCase				(				a							):
	_lowerCamelCase   :					Union[str, Any]			      = """time_series_transformer"""
	_lowerCamelCase   :					Optional[Any]			      = {
	    """hidden_size""": """d_model""",
	    """num_attention_heads""": """encoder_attention_heads""",
	    """num_hidden_layers""": """encoder_layers""",
	}



	def __init__(					self ,					snake_case__ = None ,					snake_case__ = None ,					snake_case__ = "student_t" ,					snake_case__ = "nll" ,					snake_case__ = 1 ,					snake_case__ = [1, 2, 3, 4, 5, 6, 7] ,					snake_case__ = "mean" ,					snake_case__ = 0 ,					snake_case__ = 0 ,					snake_case__ = 0 ,					snake_case__ = 0 ,					snake_case__ = None ,					snake_case__ = None ,					snake_case__ = 32 ,					snake_case__ = 32 ,					snake_case__ = 2 ,					snake_case__ = 2 ,					snake_case__ = 2 ,					snake_case__ = 2 ,					snake_case__ = True ,					snake_case__ = "gelu" ,					snake_case__ = 64 ,					snake_case__ = 0.1 ,					snake_case__ = 0.1 ,					snake_case__ = 0.1 ,					snake_case__ = 0.1 ,					snake_case__ = 0.1 ,					snake_case__ = 100 ,					snake_case__ = 0.0_2 ,					snake_case__=True ,					**snake_case__ ,					):
		# time series specific configuration
		lowerCAmelCase					:    Tuple      							= prediction_length
		lowerCAmelCase					:    List[Any]      							= context_length or prediction_length
		lowerCAmelCase					:    int      							= distribution_output
		lowerCAmelCase					:    Dict      							= loss
		lowerCAmelCase					:    Tuple      							= input_size
		lowerCAmelCase					:    List[Any]      							= num_time_features
		lowerCAmelCase					:    Any      							= lags_sequence
		lowerCAmelCase					:    Tuple      							= scaling
		lowerCAmelCase					:    str      							= num_dynamic_real_features
		lowerCAmelCase					:    str      							= num_static_real_features
		lowerCAmelCase					:    str      							= num_static_categorical_features
		if cardinality and num_static_categorical_features > 0:
			if len(snake_case__    ) != num_static_categorical_features:
				raise ValueError(
				    'The cardinality should be a list of the same length as `num_static_categorical_features`'    )
			lowerCAmelCase					:    List[Any]      							= cardinality
		else:
			lowerCAmelCase					:    Any      							= [0]
		if embedding_dimension and num_static_categorical_features > 0:
			if len(snake_case__    ) != num_static_categorical_features:
				raise ValueError(
				    'The embedding dimension should be a list of the same length as `num_static_categorical_features`'    )
			lowerCAmelCase					:    Optional[Any]      							= embedding_dimension
		else:
			lowerCAmelCase					:    Tuple      							= [min(50 ,					(cat + 1) // 2    ) for cat in self.cardinality]
		lowerCAmelCase					:    int      							= num_parallel_samples

		# Transformer architecture configuration
		lowerCAmelCase					:    Union[str, Any]      							= input_size * len(snake_case__    ) + self._number_of_features
		lowerCAmelCase					:    Optional[Any]      							= d_model
		lowerCAmelCase					:    Union[str, Any]      							= encoder_attention_heads
		lowerCAmelCase					:    int      							= decoder_attention_heads
		lowerCAmelCase					:    List[str]      							= encoder_ffn_dim
		lowerCAmelCase					:    Any      							= decoder_ffn_dim
		lowerCAmelCase					:    Tuple      							= encoder_layers
		lowerCAmelCase					:    Tuple      							= decoder_layers

		lowerCAmelCase					:    List[Any]      							= dropout
		lowerCAmelCase					:    Any      							= attention_dropout
		lowerCAmelCase					:    Optional[Any]      							= activation_dropout
		lowerCAmelCase					:    Union[str, Any]      							= encoder_layerdrop
		lowerCAmelCase					:    Union[str, Any]      							= decoder_layerdrop

		lowerCAmelCase					:    List[str]      							= activation_function
		lowerCAmelCase					:    List[str]      							= init_std

		lowerCAmelCase					:    Tuple      							= use_cache

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



	@property
	def 				lowercase     (					self    ):
		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
		)




'''simple docstring'''




import gc
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, LDMTextToImagePipeline, UNetaDConditionModel
from diffusers.utils.testing_utils import (
    enable_full_determinism,
    load_numpy,
    nightly,
    require_torch_gpu,
    slow,
    torch_device,
)

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()



class  lowerCAmelCase				(				a      ,				unittest.TestCase							):
	_lowerCamelCase   :					List[Any]			      = LDMTextToImagePipeline
	_lowerCamelCase   :					Optional[Any]			      = TEXT_TO_IMAGE_PARAMS - {
	    """negative_prompt""",
	    """negative_prompt_embeds""",
	    """cross_attention_kwargs""",
	    """prompt_embeds""",
	}
	_lowerCamelCase   :					List[str]			      = PipelineTesterMixin.required_optional_params - {
	    """num_images_per_prompt""",
	    """callback""",
	    """callback_steps""",
	}
	_lowerCamelCase   :					Union[str, Any]			      = TEXT_TO_IMAGE_BATCH_PARAMS
	_lowerCamelCase   :					Optional[int]			      = False



	def 				lowercase     (					self    ):
		torch.manual_seed(0    )
		lowerCAmelCase					:    Dict      							= UNetaDConditionModel(
		    block_out_channels=(32, 64) ,					layers_per_block=2 ,					sample_size=32 ,					in_channels=4 ,					out_channels=4 ,					down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') ,					up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') ,					cross_attention_dim=32 ,					)
		lowerCAmelCase					:    int      							= DDIMScheduler(
		    beta_start=0.0_0_0_8_5 ,					beta_end=0.0_1_2 ,					beta_schedule='scaled_linear' ,					clip_sample=snake_case__ ,					set_alpha_to_one=snake_case__ ,					)
		torch.manual_seed(0    )
		lowerCAmelCase					:    str      							= AutoencoderKL(
		    block_out_channels=(32, 64) ,					in_channels=3 ,					out_channels=3 ,					down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D') ,					up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D') ,					latent_channels=4 ,					)
		torch.manual_seed(0    )
		lowerCAmelCase					:    Any      							= CLIPTextConfig(
		    bos_token_id=0 ,					eos_token_id=2 ,					hidden_size=32 ,					intermediate_size=37 ,					layer_norm_eps=1e-0_5 ,					num_attention_heads=4 ,					num_hidden_layers=5 ,					pad_token_id=1 ,					vocab_size=1000 ,					)
		lowerCAmelCase					:    str      							= CLIPTextModel(snake_case__    )
		lowerCAmelCase					:    str      							= CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'    )

		lowerCAmelCase					:    List[Any]      							= {
		    'unet': unet,
		    'scheduler': scheduler,
		    'vqvae': vae,
		    'bert': text_encoder,
		    'tokenizer': tokenizer,
		}
		return components



	def 				lowercase     (					self ,					snake_case__ ,					snake_case__=0    ):
		if str(snake_case__    ).startswith('mps'    ):
			lowerCAmelCase					:    Optional[int]      							= torch.manual_seed(snake_case__    )
		else:
			lowerCAmelCase					:    str      							= torch.Generator(device=snake_case__    ).manual_seed(snake_case__    )
		lowerCAmelCase					:    Tuple      							= {
		    'prompt': 'A painting of a squirrel eating a burger',
		    'generator': generator,
		    'num_inference_steps': 2,
		    'guidance_scale': 6.0,
		    'output_type': 'numpy',
		}
		return inputs



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    List[str]      							= 'cpu'  # ensure determinism for the device-dependent torch.Generator

		lowerCAmelCase					:    Optional[Any]      							= self.get_dummy_components()
		lowerCAmelCase					:    Optional[Any]      							= LDMTextToImagePipeline(**snake_case__    )
		pipe.to(snake_case__    )
		pipe.set_progress_bar_config(disable=snake_case__    )

		lowerCAmelCase					:    Tuple      							= self.get_dummy_inputs(snake_case__    )
		lowerCAmelCase					:    Union[str, Any]      							= pipe(**snake_case__    ).images
		lowerCAmelCase					:    str      							= image[0, -3:, -3:, -1]

		assert image.shape == (1, 16, 16, 3)
		lowerCAmelCase					:    List[Any]      							= np.array([0.6_1_0_1, 0.6_1_5_6, 0.5_6_2_2, 0.4_8_9_5, 0.6_6_6_1, 0.3_8_0_4, 0.5_7_4_8, 0.6_1_3_6, 0.5_0_1_4]    )

		assert np.abs(image_slice.flatten() - expected_slice    ).max() < 1e-3



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



	def 				lowercase     (					self    ):
		super().tearDown()
		gc.collect()
		torch.cuda.empty_cache()



	def 				lowercase     (					self ,					snake_case__ ,					snake_case__=torch.floataa ,					snake_case__=0    ):
		lowerCAmelCase					:    List[str]      							= torch.manual_seed(snake_case__    )
		lowerCAmelCase					:    int      							= np.random.RandomState(snake_case__    ).standard_normal((1, 4, 32, 32)    )
		lowerCAmelCase					:    Optional[Any]      							= torch.from_numpy(snake_case__    ).to(device=snake_case__ ,					dtype=snake_case__    )
		lowerCAmelCase					:    List[str]      							= {
		    'prompt': 'A painting of a squirrel eating a burger',
		    'latents': latents,
		    'generator': generator,
		    'num_inference_steps': 3,
		    'guidance_scale': 6.0,
		    'output_type': 'numpy',
		}
		return inputs



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Tuple      							= LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256'    ).to(snake_case__    )
		pipe.set_progress_bar_config(disable=snake_case__    )

		lowerCAmelCase					:    Optional[Any]      							= self.get_inputs(snake_case__    )
		lowerCAmelCase					:    List[Any]      							= pipe(**snake_case__    ).images
		lowerCAmelCase					:    str      							= image[0, -3:, -3:, -1].flatten()

		assert image.shape == (1, 256, 256, 3)
		lowerCAmelCase					:    Tuple      							= np.array([0.5_1_8_2_5, 0.5_2_8_5_0, 0.5_2_5_4_3, 0.5_4_2_5_8, 0.5_2_3_0_4, 0.5_2_5_6_9, 0.5_4_3_6_3, 0.5_5_2_7_6, 0.5_6_8_7_8]    )
		lowerCAmelCase					:    int      							= np.abs(expected_slice - image_slice    ).max()
		assert max_diff < 1e-3



@nightly
@require_torch_gpu
class  lowerCAmelCase				(				unittest.TestCase							):



	def 				lowercase     (					self    ):
		super().tearDown()
		gc.collect()
		torch.cuda.empty_cache()



	def 				lowercase     (					self ,					snake_case__ ,					snake_case__=torch.floataa ,					snake_case__=0    ):
		lowerCAmelCase					:    List[str]      							= torch.manual_seed(snake_case__    )
		lowerCAmelCase					:    Any      							= np.random.RandomState(snake_case__    ).standard_normal((1, 4, 32, 32)    )
		lowerCAmelCase					:    List[Any]      							= torch.from_numpy(snake_case__    ).to(device=snake_case__ ,					dtype=snake_case__    )
		lowerCAmelCase					:    List[str]      							= {
		    'prompt': 'A painting of a squirrel eating a burger',
		    'latents': latents,
		    'generator': generator,
		    'num_inference_steps': 50,
		    'guidance_scale': 6.0,
		    'output_type': 'numpy',
		}
		return inputs



	def 				lowercase     (					self    ):
		lowerCAmelCase					:    Optional[int]      							= LDMTextToImagePipeline.from_pretrained('CompVis/ldm-text2im-large-256'    ).to(snake_case__    )
		pipe.set_progress_bar_config(disable=snake_case__    )

		lowerCAmelCase					:    int      							= self.get_inputs(snake_case__    )
		lowerCAmelCase					:    Optional[int]      							= pipe(**snake_case__    ).images[0]

		lowerCAmelCase					:    Optional[int]      							= load_numpy(
		    'https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/ldm_text2img/ldm_large_256_ddim.npy'    )
		lowerCAmelCase					:    List[str]      							= np.abs(expected_image - image    ).max()
		assert max_diff < 1e-3
