





from typing import Callable, List, Optional, Tuple, Union

import torch
from transformers import CLIPTextModel, CLIPTokenizer

from ...configuration_utils import ConfigMixin, register_to_config
from ...models import ModelMixin, TransformeraDModel, VQModel
from ...schedulers import VQDiffusionScheduler
from ...utils import logging
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput


__A							   =							logging.get_logger(__name__)  # pylint: disable=invalid-name



class   _SCREAMING_SNAKE_CASE		(      __SCREAMING_SNAKE_CASE       ,				__SCREAMING_SNAKE_CASE       ):







 '''simple docstring'''

 @register_to_config
 def __init__(self							:  str			,					UpperCAmelCase_							:  bool			,					UpperCAmelCase_							:  Optional[int] = None			,					UpperCAmelCase_							:  Optional[int] = None)			->Any:



   '''simple docstring'''



   super().__init__()

   lowerCamelCase__: Any         =learnable

   if self.learnable:
     assert hidden_size is not None, "learnable=True requires `hidden_size` to be set"
     assert length is not None, "learnable=True requires `length` to be set"

     lowerCamelCase__: int         =torch.zeros(UpperCAmelCase_			,					UpperCAmelCase_)
   else:
     lowerCamelCase__: Optional[int]         =None

   lowerCamelCase__: Tuple         =torch.nn.Parameter(UpperCAmelCase_)



class   _SCREAMING_SNAKE_CASE		(      __SCREAMING_SNAKE_CASE       ):







 '''simple docstring'''
 lowercase_						=     42
 lowercase_						=     42
 lowercase_						=     42
 lowercase_						=     42
 lowercase_						=     42
 lowercase_						=     42

 def __init__(self							:  Union[str, Any]			,					UpperCAmelCase_							:  VQModel			,					UpperCAmelCase_							:  CLIPTextModel			,					UpperCAmelCase_							:  CLIPTokenizer			,					UpperCAmelCase_							:  TransformeraDModel			,					UpperCAmelCase_							:  VQDiffusionScheduler			,					UpperCAmelCase_							:  LearnedClassifierFreeSamplingEmbeddings			,					)			->Optional[Any]:



   '''simple docstring'''



   super().__init__()

   self.register_modules(
       vqvae=UpperCAmelCase_			,					transformer=UpperCAmelCase_			,					text_encoder=UpperCAmelCase_			,					tokenizer=UpperCAmelCase_			,					scheduler=UpperCAmelCase_			,					learned_classifier_free_sampling_embeddings=UpperCAmelCase_			,					)

 def 				SCREAMING_SNAKE_CASE_   (self							:  Union[str, Any]			,					UpperCAmelCase_							:  Optional[int]			,					UpperCAmelCase_							:  int			,					UpperCAmelCase_							:  List[Any])			->List[Any]:



   '''simple docstring'''



   lowerCamelCase__: Optional[Any]         =len(UpperCAmelCase_) if isinstance(UpperCAmelCase_			,					UpperCAmelCase_) else 1

   # get prompt text embeddings
   lowerCamelCase__: Optional[Any]         =self.tokenizer(
       UpperCAmelCase_			,					padding="max_length"			,					max_length=self.tokenizer.model_max_length			,					return_tensors="pt"			,					)
   lowerCamelCase__: List[Any]         =text_inputs.input_ids

   if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
     lowerCamelCase__: Union[str, Any]         =self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :])
     logger.warning(
         "The following part of your input was truncated because CLIP can only handle sequences up to"
         F""" {self.tokenizer.model_max_length} tokens: {removed_text}""")
     lowerCamelCase__: Tuple         =text_input_ids[:, : self.tokenizer.model_max_length]
   lowerCamelCase__: Optional[int]         =self.text_encoder(text_input_ids.to(self.device))[0]

   # NOTE: This additional step of normalizing the text embeddings is from VQ-Diffusion.
   # While CLIP does normalize the pooled output of the text transformer when combining
   # the image and text embeddings, CLIP does not directly normalize the last hidden state.
   #
   # CLIP normalizing the pooled output.
   # https://github.com/huggingface/transformers/blob/d92e22d1f28324f513f3080e5c47c071a3916721/src/transformers/models/clip/modeling_clip.py#L1052-L1053
   lowerCamelCase__: List[str]         =prompt_embeds / prompt_embeds.norm(dim=-1			,					keepdim=UpperCAmelCase_)

   # duplicate text embeddings for each generation per prompt
   lowerCamelCase__: Tuple         =prompt_embeds.repeat_interleave(UpperCAmelCase_			,					dim=0)

   if do_classifier_free_guidance:
     if self.learned_classifier_free_sampling_embeddings.learnable:
       lowerCamelCase__: Tuple         =self.learned_classifier_free_sampling_embeddings.embeddings
       lowerCamelCase__: str         =negative_prompt_embeds.unsqueeze(0).repeat(UpperCAmelCase_			,					1			,					1)
     else:
       lowerCamelCase__: Any         =[""] * batch_size

       lowerCamelCase__: List[str]         =text_input_ids.shape[-1]
       lowerCamelCase__: List[Any]         =self.tokenizer(
           UpperCAmelCase_			,					padding="max_length"			,					max_length=UpperCAmelCase_			,					truncation=UpperCAmelCase_			,					return_tensors="pt"			,					)
       lowerCamelCase__: int         =self.text_encoder(uncond_input.input_ids.to(self.device))[0]
       # See comment for normalizing text embeddings
       lowerCamelCase__: List[str]         =negative_prompt_embeds / negative_prompt_embeds.norm(dim=-1			,					keepdim=UpperCAmelCase_)

     # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
     lowerCamelCase__: Any         =negative_prompt_embeds.shape[1]
     lowerCamelCase__: Optional[Any]         =negative_prompt_embeds.repeat(1			,					UpperCAmelCase_			,					1)
     lowerCamelCase__: int         =negative_prompt_embeds.view(batch_size * num_images_per_prompt			,					UpperCAmelCase_			,					-1)

     # For classifier free guidance, we need to do two forward passes.
     # Here we concatenate the unconditional and text embeddings into a single batch
     # to avoid doing two forward passes
     lowerCamelCase__: Tuple         =torch.cat([negative_prompt_embeds, prompt_embeds])

   return prompt_embeds

 @torch.no_grad()
 def __call__(self							:  Optional[Any]			,					UpperCAmelCase_							:  Union[str, List[str]]			,					UpperCAmelCase_							:  int = 100			,					UpperCAmelCase_							:  float = 5.0			,					UpperCAmelCase_							:  float = 1.0			,					UpperCAmelCase_							:  int = 1			,					UpperCAmelCase_							:  Optional[Union[torch.Generator, List[torch.Generator]]] = None			,					UpperCAmelCase_							:  Optional[torch.FloatTensor] = None			,					UpperCAmelCase_							:  Optional[str] = "pil"			,					UpperCAmelCase_							:  bool = True			,					UpperCAmelCase_							:  Optional[Callable[[int, int, torch.FloatTensor], None]] = None			,					UpperCAmelCase_							:  int = 1			,					)			->Union[ImagePipelineOutput, Tuple]:



   '''simple docstring'''



   if isinstance(UpperCAmelCase_			,					UpperCAmelCase_):
     lowerCamelCase__: int         =1
   elif isinstance(UpperCAmelCase_			,					UpperCAmelCase_):
     lowerCamelCase__: Union[str, Any]         =len(UpperCAmelCase_)
   else:
     raise ValueError(F"""`prompt` has to be of type `str` or `list` but is {type(UpperCAmelCase_)}""")

   lowerCamelCase__: List[str]         =batch_size * num_images_per_prompt

   lowerCamelCase__: Optional[int]         =guidance_scale > 1.0

   lowerCamelCase__: Tuple         =self._encode_prompt(UpperCAmelCase_			,					UpperCAmelCase_			,					UpperCAmelCase_)

   if (callback_steps is None) or (
       callback_steps is not None and (not isinstance(UpperCAmelCase_			,					UpperCAmelCase_) or callback_steps <= 0)
   ):
     raise ValueError(
         F"""`callback_steps` has to be a positive integer but is {callback_steps} of type"""
         F""" {type(UpperCAmelCase_)}.""")

   # get the initial completely masked latents unless the user supplied it

   lowerCamelCase__: Any         =(batch_size, self.transformer.num_latent_pixels)
   if latents is None:
     lowerCamelCase__: List[Any]         =self.transformer.num_vector_embeds - 1
     lowerCamelCase__: Tuple         =torch.full(UpperCAmelCase_			,					UpperCAmelCase_).to(self.device)
   else:
     if latents.shape != latents_shape:
       raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""")
     if (latents < 0).any() or (latents >= self.transformer.num_vector_embeds).any():
       raise ValueError(
           "Unexpected latents value(s). All latents be valid embedding indices i.e. in the range 0,"
           F""" {self.transformer.num_vector_embeds - 1} (inclusive).""")
     lowerCamelCase__: int         =latents.to(self.device)

   # set timesteps
   self.scheduler.set_timesteps(UpperCAmelCase_			,					device=self.device)

   lowerCamelCase__: str         =self.scheduler.timesteps.to(self.device)

   lowerCamelCase__: Union[str, Any]         =latents

   for i, t in enumerate(self.progress_bar(UpperCAmelCase_)):
     # expand the sample if we are doing classifier free guidance
     lowerCamelCase__: Optional[Any]         =torch.cat([sample] * 2) if do_classifier_free_guidance else sample

     # predict the un-noised image
     # model_output == `log_p_x_0`
     lowerCamelCase__: Optional[int]         =self.transformer(UpperCAmelCase_			,					encoder_hidden_states=UpperCAmelCase_			,					timestep=UpperCAmelCase_).sample

     if do_classifier_free_guidance:
       lowerCamelCase__    ,   lowerCamelCase__: Any         =model_output.chunk(2)
       lowerCamelCase__: Optional[Any]         =model_output_uncond + guidance_scale * (model_output_text - model_output_uncond)
       model_output -= torch.logsumexp(UpperCAmelCase_			,					dim=1			,					keepdim=UpperCAmelCase_)

     lowerCamelCase__: Optional[int]         =self.truncate(UpperCAmelCase_			,					UpperCAmelCase_)

     # remove `log(0)`'s (`-inf`s)
     lowerCamelCase__: Optional[Any]         =model_output.clamp(-70)

     # compute the previous noisy sample x_t -> x_t-1
     lowerCamelCase__: str         =self.scheduler.step(UpperCAmelCase_			,					timestep=UpperCAmelCase_			,					sample=UpperCAmelCase_			,					generator=UpperCAmelCase_).prev_sample

     # call the callback, if provided
     if callback is not None and i % callback_steps == 0:
       callback(UpperCAmelCase_			,					UpperCAmelCase_			,					UpperCAmelCase_)

   lowerCamelCase__: int         =self.vqvae.config.vq_embed_dim
   lowerCamelCase__: Union[str, Any]         =(batch_size, self.transformer.height, self.transformer.width, embedding_channels)
   lowerCamelCase__: int         =self.vqvae.quantize.get_codebook_entry(UpperCAmelCase_			,					shape=UpperCAmelCase_)
   lowerCamelCase__: str         =self.vqvae.decode(UpperCAmelCase_			,					force_not_quantize=UpperCAmelCase_).sample

   lowerCamelCase__: Optional[int]         =(image / 2 + 0.5).clamp(0			,					1)
   lowerCamelCase__: int         =image.cpu().permute(0			,					2			,					3			,					1).numpy()

   if output_type == "pil":
     lowerCamelCase__: List[Any]         =self.numpy_to_pil(UpperCAmelCase_)

   if not return_dict:
     return (image,)

   return ImagePipelineOutput(images=UpperCAmelCase_)







 def 				SCREAMING_SNAKE_CASE_   (self							:  Any			,					UpperCAmelCase_							:  torch.FloatTensor			,					UpperCAmelCase_							:  float)			->torch.FloatTensor:



   '''simple docstring'''



   lowerCamelCase__    ,   lowerCamelCase__: Tuple         =torch.sort(UpperCAmelCase_			,					1			,					descending=UpperCAmelCase_)
   lowerCamelCase__: List[str]         =torch.exp(UpperCAmelCase_)
   lowerCamelCase__: Union[str, Any]         =sorted_p_x_0.cumsum(dim=1) < truncation_rate

   # Ensure that at least the largest probability is not zeroed out
   lowerCamelCase__: Optional[int]         =torch.full_like(keep_mask[:, 0:1, :]			,					UpperCAmelCase_)
   lowerCamelCase__: int         =torch.cat((all_true, keep_mask)			,					dim=1)
   lowerCamelCase__: str         =keep_mask[:, :-1, :]

   lowerCamelCase__: Dict         =keep_mask.gather(1			,					indices.argsort(1))

   lowerCamelCase__: List[Any]         =log_p_x_0.clone()

   lowerCamelCase__: int         =-torch.inf  # -inf = log(0)

   return rv









"""simple docstring"""
from typing import List, Optional, Union

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


_lowerCAmelCase       =				logging.get_logger(__name__)

_lowerCAmelCase       =				{
    "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   SCREAMING_SNAKE_CASE	(					_SCREAMING_SNAKE_CASE    ):





	"""simple docstring"""




	_A							:					Optional[Any] 			=					"""informer"""
	_A							:					Dict 			=					{
	    """hidden_size""": """d_model""",
	    """num_attention_heads""": """encoder_attention_heads""",
	    """num_hidden_layers""": """encoder_layers""",
	}





	def __init__(self  ,  lowerCAmelCase_ = None  ,  lowerCAmelCase_ = None  ,  lowerCAmelCase_ = "student_t"  ,  lowerCAmelCase_ = "nll"  ,  lowerCAmelCase_ = 1  ,  lowerCAmelCase_ = None  ,  lowerCAmelCase_ = "mean"  ,  lowerCAmelCase_ = 0  ,  lowerCAmelCase_ = 0  ,  lowerCAmelCase_ = 0  ,  lowerCAmelCase_ = 0  ,  lowerCAmelCase_ = None  ,  lowerCAmelCase_ = None  ,  lowerCAmelCase_ = 64  ,  lowerCAmelCase_ = 32  ,  lowerCAmelCase_ = 32  ,  lowerCAmelCase_ = 2  ,  lowerCAmelCase_ = 2  ,  lowerCAmelCase_ = 2  ,  lowerCAmelCase_ = 2  ,  lowerCAmelCase_ = True  ,  lowerCAmelCase_ = "gelu"  ,  lowerCAmelCase_ = 0.05  ,  lowerCAmelCase_ = 0.1  ,  lowerCAmelCase_ = 0.1  ,  lowerCAmelCase_ = 0.1  ,  lowerCAmelCase_ = 0.1  ,  lowerCAmelCase_ = 100  ,  lowerCAmelCase_ = 0.02  ,  lowerCAmelCase_=True  ,  lowerCAmelCase_ = "prob"  ,  lowerCAmelCase_ = 5  ,  lowerCAmelCase_ = True  ,  **lowerCAmelCase_  ,  ):
		# time series specific configuration
		A_		:    Optional[Any]						     = prediction_length
		A_		:    Dict						     = context_length or prediction_length
		A_		:    Dict						     = distribution_output
		A_		:    Tuple						     = loss
		A_		:    Dict						     = input_size
		A_		:    Union[str, Any]						     = num_time_features
		A_		:    List[str]						     = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7]
		A_		:    Optional[int]						     = scaling
		A_		:    Optional[Any]						     = num_dynamic_real_features
		A_		:    Tuple						     = num_static_real_features
		A_		:    Tuple						     = num_static_categorical_features

		# set cardinality
		if cardinality and num_static_categorical_features > 0:
			if len(lowerCAmelCase_				) != num_static_categorical_features:
				raise ValueError(
				    """The cardinality should be a list of the same length as `num_static_categorical_features`"""				)
			A_		:    List[str]						     = cardinality
		else:
			A_		:    List[Any]						     = [0]

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

		A_		:    Optional[int]						     = num_parallel_samples

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

		A_		:    List[str]						     = dropout
		A_		:    List[str]						     = attention_dropout
		A_		:    Any						     = activation_dropout
		A_		:    Any						     = encoder_layerdrop
		A_		:    List[Any]						     = decoder_layerdrop

		A_		:    str						     = activation_function
		A_		:    Optional[Any]						     = init_std

		A_		:    Optional[int]						     = use_cache

		# Informer
		A_		:    Dict						     = attention_type
		A_		:    List[Any]						     = sampling_factor
		A_		:    List[Any]						     = distil

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





	@property
	def  lowerCamelCase(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
		)

