


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 			_a				(     UpperCamelCase__     ):
							_lowercase      :     Union[str, Any]     =					'''informer'''
							_lowercase      :     int     =					{
							    '''hidden_size''': '''d_model''',
							    '''num_attention_heads''': '''encoder_attention_heads''',
							    '''num_hidden_layers''': '''encoder_layers''',
							}

							def __init__(				self:      Dict       ,		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 = 64       ,		UpperCamelCase_:      int = 32       ,		UpperCamelCase_:      int = 32       ,		UpperCamelCase_:      int = 2       ,		UpperCamelCase_:      int = 2       ,		UpperCamelCase_:      int = 2       ,		UpperCamelCase_:      int = 2       ,		UpperCamelCase_:      bool = True       ,		UpperCamelCase_:      str = "gelu"       ,		UpperCamelCase_:      float = 0.05       ,		UpperCamelCase_:      float = 0.1       ,		UpperCamelCase_:      float = 0.1       ,		UpperCamelCase_:      float = 0.1       ,		UpperCamelCase_:      float = 0.1       ,		UpperCamelCase_:      int = 100       ,		UpperCamelCase_:      float = 0.02       ,		UpperCamelCase_:      Tuple=True       ,		UpperCamelCase_:      str = "prob"       ,		UpperCamelCase_:      int = 5       ,		UpperCamelCase_:      bool = True       ,		**UpperCamelCase_:      Optional[int]       ,		)     ->  Union[str, Any]:





									"""simple docstring"""







									lowercase__				= prediction_length
									lowercase__				= context_length or prediction_length
									lowercase__				= distribution_output
									lowercase__				= loss
									lowercase__				= input_size
									lowercase__				= num_time_features
									lowercase__				= lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7]
									lowercase__				= scaling
									lowercase__				= num_dynamic_real_features
									lowercase__				= num_static_real_features
									lowercase__				= 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`'''				)
											lowercase__				= cardinality
									else:
											lowercase__				= [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`'''				)
											lowercase__				= embedding_dimension
									else:
											lowercase__				= [min(50       ,		(cat + 1) // 2				) for cat in self.cardinality]

									lowercase__				= num_parallel_samples

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

									lowercase__				= dropout
									lowercase__				= attention_dropout
									lowercase__				= activation_dropout
									lowercase__				= encoder_layerdrop
									lowercase__				= decoder_layerdrop

									lowercase__				= activation_function
									lowercase__				= init_std

									lowercase__				= use_cache

									# Informer
									lowercase__				= attention_type
									lowercase__				= sampling_factor
									lowercase__				= distil

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


							@property
							def  lowerCamelCase_					(				self:      Any				)     ->  int:





									"""simple docstring"""







									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 math
from typing import Any, Callable, List, Optional, Tuple, Union

import numpy as np
import torch

from ...models import TaFilmDecoder
from ...schedulers import DDPMScheduler
from ...utils import is_onnx_available, logging, randn_tensor


if is_onnx_available():
		from ..onnx_utils import OnnxRuntimeModel

from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline
from .continous_encoder import SpectrogramContEncoder
from .notes_encoder import SpectrogramNotesEncoder


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

UpperCamelCase_       :    List[Any]						      =			256



class __lowerCAmelCase					(       _lowercase   ):




			"""simple docstring"""







			snake_case						   =					["melgan"]




			def __init__(					self    :       Dict							, _snake_case    :       SpectrogramNotesEncoder							, _snake_case    :       SpectrogramContEncoder							, _snake_case    :       TaFilmDecoder							, _snake_case    :       DDPMScheduler							, _snake_case    :       OnnxRuntimeModel if is_onnx_available() else Any							, )   ->			None:







								"""simple docstring"""
								super().__init__()

								# From MELGAN
								A_								=    math.log(1e-5						)  # Matches MelGAN training.
								A_								=    4.0  # Largest value for most examples
								A_								=    128

								self.register_modules(
								    notes_encoder=_snake_case							, continuous_encoder=_snake_case							, decoder=_snake_case							, scheduler=_snake_case							, melgan=_snake_case							, )




			def   lowerCamelCase__  (					self    :       Union[str, Any]							, _snake_case    :       Tuple							, _snake_case    :       str=(-1.0, 1.0)							, _snake_case    :       int=False						)   ->			str:







								"""simple docstring"""
								A_			,     A_								=    output_range
								if clip:
													A_								=    torch.clip(_snake_case							, self.min_value							, self.max_value						)
								# Scale to [0, 1].
								A_								=    (features - self.min_value) / (self.max_value - self.min_value)
								# Scale to [min_out, max_out].
								return zero_one * (max_out - min_out) + min_out




			def   lowerCamelCase__  (					self    :       Dict							, _snake_case    :       Tuple							, _snake_case    :       Optional[Any]=(-1.0, 1.0)							, _snake_case    :       List[str]=False						)   ->			List[str]:







								"""simple docstring"""
								A_			,     A_								=    input_range
								A_								=    torch.clip(_snake_case							, _snake_case							, _snake_case						) if clip else outputs
								# Scale to [0, 1].
								A_								=    (outputs - min_out) / (max_out - min_out)
								# Scale to [self.min_value, self.max_value].
								return zero_one * (self.max_value - self.min_value) + self.min_value




			def   lowerCamelCase__  (					self    :       Union[str, Any]							, _snake_case    :       str							, _snake_case    :       List[Any]							, _snake_case    :       Union[str, Any]						)   ->			List[str]:







								"""simple docstring"""
								A_								=    input_tokens > 0
								A_			,     A_								=    self.notes_encoder(
								    encoder_input_tokens=_snake_case							, encoder_inputs_mask=_snake_case						)

								A_			,     A_								=    self.continuous_encoder(
								    encoder_inputs=_snake_case							, encoder_inputs_mask=_snake_case						)

								return [(tokens_encoded, tokens_mask), (continuous_encoded, continuous_mask)]




			def   lowerCamelCase__  (					self    :       List[Any]							, _snake_case    :       List[Any]							, _snake_case    :       int							, _snake_case    :       Tuple						)   ->			Optional[int]:







								"""simple docstring"""
								A_								=    noise_time
								if not torch.is_tensor(_snake_case						):
													A_								=    torch.tensor([timesteps]							, dtype=torch.long							, device=input_tokens.device						)
								elif torch.is_tensor(_snake_case						) and len(timesteps.shape						) == 0:
													A_								=    timesteps[None].to(input_tokens.device						)

								# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
								A_								=    timesteps * torch.ones(input_tokens.shape[0]							, dtype=timesteps.dtype							, device=timesteps.device						)

								A_								=    self.decoder(
								    encodings_and_masks=_snake_case							, decoder_input_tokens=_snake_case							, decoder_noise_time=_snake_case						)
								return logits






			@torch.no_grad()
			def __call__(					self    :       List[Any]							, _snake_case    :       List[List[int]]							, _snake_case    :       Optional[torch.Generator] = None							, _snake_case    :       int = 100							, _snake_case    :       bool = True							, _snake_case    :       str = "numpy"							, _snake_case    :       Optional[Callable[[int, int, torch.FloatTensor], None]] = None							, _snake_case    :       int = 1							, )   ->			Union[AudioPipelineOutput, Tuple]:







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

								A_								=    np.zeros([1, TARGET_FEATURE_LENGTH, self.n_dims]							, dtype=np.floataa						)
								A_								=    np.zeros([1, 0, self.n_dims]							, np.floataa						)
								A_								=    torch.ones((1, TARGET_FEATURE_LENGTH)							, dtype=_snake_case							, device=self.device						)

								for i, encoder_input_tokens in enumerate(_snake_case						):
													if i == 0:
																		A_								=    torch.from_numpy(pred_mel[:1].copy()						).to(
																		    device=self.device							, dtype=self.decoder.dtype						)
																		# The first chunk has no previous context.
																		A_								=    torch.zeros((1, TARGET_FEATURE_LENGTH)							, dtype=_snake_case							, device=self.device						)
													else:
																		# The full song pipeline does not feed in a context feature, so the mask
																		# will be all 0s after the feature converter. Because we know we're
																		# feeding in a full context chunk from the previous prediction, set it
																		# to all 1s.
																		A_								=    ones

													A_								=    self.scale_features(
													    _snake_case							, output_range=[-1.0, 1.0]							, clip=_snake_case						)

													A_								=    self.encode(
													    input_tokens=torch.IntTensor([encoder_input_tokens]						).to(device=self.device						)							, continuous_inputs=_snake_case							, continuous_mask=_snake_case							, )

													# Sample encoder_continuous_inputs shaped gaussian noise to begin loop
													A_								=    randn_tensor(
													    shape=encoder_continuous_inputs.shape							, generator=_snake_case							, device=self.device							, dtype=self.decoder.dtype							, )

													# set step values
													self.scheduler.set_timesteps(_snake_case						)

													# Denoising diffusion loop
													for j, t in enumerate(self.progress_bar(self.scheduler.timesteps						)						):
																		A_								=    self.decode(
																		    encodings_and_masks=_snake_case							, input_tokens=_snake_case							, noise_time=t / self.scheduler.config.num_train_timesteps							, )

																		# Compute previous output: x_t -> x_t-1
																		A_								=    self.scheduler.step(_snake_case							, _snake_case							, _snake_case							, generator=_snake_case						).prev_sample

													A_								=    self.scale_to_features(_snake_case							, input_range=[-1.0, 1.0]						)
													A_								=    mel[:1]
													A_								=    mel.cpu().float().numpy()

													A_								=    np.concatenate([full_pred_mel, pred_mel[:1]]							, axis=1						)

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

													logger.info("Generated segment"							, _snake_case						)

								if output_type == "numpy" and not is_onnx_available():
													raise ValueError(
													    "Cannot return output in 'np' format if ONNX is not available. Make sure to have ONNX installed or set 'output_type' to 'mel'."						)
								elif output_type == "numpy" and self.melgan is None:
													raise ValueError(
													    "Cannot return output in 'np' format if melgan component is not defined. Make sure to define `self.melgan` or set 'output_type' to 'mel'."						)

								if output_type == "numpy":
													A_								=    self.melgan(input_features=full_pred_mel.astype(np.floataa						)						)
								else:
													A_								=    full_pred_mel

								if not return_dict:
													return (output,)

								return AudioPipelineOutput(audios=_snake_case						)




