



'''simple docstring'''




import math

import torch
from torch import nn

from ..configuration_utils import ConfigMixin, register_to_config
from .attention_processor import Attention
from .embeddings import get_timestep_embedding
from .modeling_utils import ModelMixin






class 		_UpperCamelCase						(							lowerCamelCase__					,      lowerCamelCase__					):


			'''simple docstring'''

			@register_to_config
			def __init__(							self  :				Any							,  lowerCAmelCase__  :				int = 1_2_8							,  lowerCAmelCase__  :				int = 2_5_6							,  lowerCAmelCase__  :				float = 20_00.0							,  lowerCAmelCase__  :				int = 7_6_8							,  lowerCAmelCase__  :				int = 1_2							,  lowerCAmelCase__  :				int = 1_2							,  lowerCAmelCase__  :				int = 6_4							,  lowerCAmelCase__  :				int = 2_0_4_8							,  lowerCAmelCase__  :				float = 0.1							,  ):





					"""simple docstring"""






					super().__init__()

					__SCREAMING_SNAKE_CASE :	Optional[int]					 =	nn.Sequential(
					    nn.Linear(lowerCAmelCase__							,  d_model * 4							,  bias=lowerCAmelCase__		)							,  nn.SiLU()							,  nn.Linear(d_model * 4							,  d_model * 4							,  bias=lowerCAmelCase__		)							,  nn.SiLU()							,  )

					__SCREAMING_SNAKE_CASE :	Dict					 =	nn.Embedding(lowerCAmelCase__							,  lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	False

					__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	nn.Linear(lowerCAmelCase__							,  lowerCAmelCase__							,  bias=lowerCAmelCase__		)

					__SCREAMING_SNAKE_CASE :	str					 =	nn.Dropout(p=lowerCAmelCase__		)

					__SCREAMING_SNAKE_CASE :	List[Any]					 =	nn.ModuleList()
					for lyr_num in range(lowerCAmelCase__		):
							# FiLM conditional T5 decoder
							__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	DecoderLayer(d_model=lowerCAmelCase__							,  d_kv=lowerCAmelCase__							,  num_heads=lowerCAmelCase__							,  d_ff=lowerCAmelCase__							,  dropout_rate=lowerCAmelCase__		)
							self.decoders.append(lowerCAmelCase__		)

					__SCREAMING_SNAKE_CASE :	List[str]					 =	TaLayerNorm(lowerCAmelCase__		)

					__SCREAMING_SNAKE_CASE :	int					 =	nn.Dropout(p=lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	List[Any]					 =	nn.Linear(lowerCAmelCase__							,  lowerCAmelCase__							,  bias=lowerCAmelCase__		)

			def UpperCamelCase__      (							self  :				Optional[int]							,  lowerCAmelCase__  :				Optional[Any]							,  lowerCAmelCase__  :				List[Any]		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	List[Any]					 =	torch.mul(query_input.unsqueeze(-1		)							,  key_input.unsqueeze(-2		)		)
					return mask.unsqueeze(-3		)



			def UpperCamelCase__      (							self  :				Dict							,  lowerCAmelCase__  :				Optional[int]							,  lowerCAmelCase__  :				Union[str, Any]							,  lowerCAmelCase__  :				List[str]		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE ,		__SCREAMING_SNAKE_CASE ,		__SCREAMING_SNAKE_CASE :	List[str]					 =	decoder_input_tokens.shape
					assert decoder_noise_time.shape == (batch,)

					# decoder_noise_time is in [0, 1), so rescale to expected timing range.
					__SCREAMING_SNAKE_CASE :	Tuple					 =	get_timestep_embedding(
					    decoder_noise_time * self.config.max_decoder_noise_time							,  embedding_dim=self.config.d_model							,  max_period=self.config.max_decoder_noise_time							,  ).to(dtype=self.dtype		)

					__SCREAMING_SNAKE_CASE :	Optional[int]					 =	self.conditioning_emb(lowerCAmelCase__		).unsqueeze(1		)

					assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4)

					__SCREAMING_SNAKE_CASE :	Union[str, Any]					 =	decoder_input_tokens.shape[1]

					# If we want to use relative positions for audio context, we can just offset
					# this sequence by the length of encodings_and_masks.
					__SCREAMING_SNAKE_CASE :	Tuple					 =	torch.broadcast_to(
					    torch.arange(lowerCAmelCase__							,  device=decoder_input_tokens.device		)							,  (batch, seq_length)							,  )

					__SCREAMING_SNAKE_CASE :	str					 =	self.position_encoding(lowerCAmelCase__		)

					__SCREAMING_SNAKE_CASE :	Tuple					 =	self.continuous_inputs_projection(lowerCAmelCase__		)
					inputs += position_encodings
					__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	self.dropout(lowerCAmelCase__		)

					# decoder: No padding present.
					__SCREAMING_SNAKE_CASE :	Tuple					 =	torch.ones(
					    decoder_input_tokens.shape[:2]							,  device=decoder_input_tokens.device							,  dtype=inputs.dtype		)

					# Translate encoding masks to encoder-decoder masks.
					__SCREAMING_SNAKE_CASE :	List[Any]					 =	[(x, self.encoder_decoder_mask(lowerCAmelCase__							,  lowerCAmelCase__		)) for x, y in encodings_and_masks]

					# cross attend style: concat encodings
					__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	torch.cat([x[0] for x in encodings_and_encdec_masks]							,  dim=1		)
					__SCREAMING_SNAKE_CASE :	List[str]					 =	torch.cat([x[1] for x in encodings_and_encdec_masks]							,  dim=-1		)

					for lyr in self.decoders:
							__SCREAMING_SNAKE_CASE :	Dict					 =	lyr(
							    lowerCAmelCase__							,  conditioning_emb=lowerCAmelCase__							,  encoder_hidden_states=lowerCAmelCase__							,  encoder_attention_mask=lowerCAmelCase__							,  )[0]

					__SCREAMING_SNAKE_CASE :	List[str]					 =	self.decoder_norm(lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	List[Any]					 =	self.post_dropout(lowerCAmelCase__		)

					__SCREAMING_SNAKE_CASE :	str					 =	self.spec_out(lowerCAmelCase__		)
					return spec_out






class 		_UpperCamelCase						(							nn.Module					):


			'''simple docstring'''

			def __init__(							self  :				Dict							,  lowerCAmelCase__  :				int							,  lowerCAmelCase__  :				Any							,  lowerCAmelCase__  :				Optional[Any]							,  lowerCAmelCase__  :				Optional[int]							,  lowerCAmelCase__  :				str							,  lowerCAmelCase__  :				Tuple=1E-6		):





					"""simple docstring"""






					super().__init__()
					__SCREAMING_SNAKE_CASE :	Dict					 =	nn.ModuleList()

					# cond self attention: layer 0
					self.layer.append(
					    TaLayerSelfAttentionCond(d_model=lowerCAmelCase__							,  d_kv=lowerCAmelCase__							,  num_heads=lowerCAmelCase__							,  dropout_rate=lowerCAmelCase__		)		)

					# cross attention: layer 1
					self.layer.append(
					    TaLayerCrossAttention(
					        d_model=lowerCAmelCase__							,  d_kv=lowerCAmelCase__							,  num_heads=lowerCAmelCase__							,  dropout_rate=lowerCAmelCase__							,  layer_norm_epsilon=lowerCAmelCase__							,  )		)

					# Film Cond MLP + dropout: last layer
					self.layer.append(
					    TaLayerFFCond(d_model=lowerCAmelCase__							,  d_ff=lowerCAmelCase__							,  dropout_rate=lowerCAmelCase__							,  layer_norm_epsilon=lowerCAmelCase__		)		)



			def UpperCamelCase__      (							self  :				int							,  lowerCAmelCase__  :				Dict							,  lowerCAmelCase__  :				Optional[Any]=None							,  lowerCAmelCase__  :				List[Any]=None							,  lowerCAmelCase__  :				Any=None							,  lowerCAmelCase__  :				Dict=None							,  lowerCAmelCase__  :				Optional[int]=None							,  ):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	str					 =	self.layer[0](
					    lowerCAmelCase__							,  conditioning_emb=lowerCAmelCase__							,  attention_mask=lowerCAmelCase__							,  )

					if encoder_hidden_states is not None:
							__SCREAMING_SNAKE_CASE :	List[str]					 =	torch.where(encoder_attention_mask > 0							,  0							,  -1E10		).to(
							    encoder_hidden_states.dtype		)

							__SCREAMING_SNAKE_CASE :	Union[str, Any]					 =	self.layer[1](
							    lowerCAmelCase__							,  key_value_states=lowerCAmelCase__							,  attention_mask=lowerCAmelCase__							,  )

					# Apply Film Conditional Feed Forward layer
					__SCREAMING_SNAKE_CASE :	Union[str, Any]					 =	self.layer[-1](lowerCAmelCase__							,  lowerCAmelCase__		)

					return (hidden_states,)






class 		_UpperCamelCase						(							nn.Module					):


			'''simple docstring'''

			def __init__(							self  :				List[str]							,  lowerCAmelCase__  :				List[str]							,  lowerCAmelCase__  :				str							,  lowerCAmelCase__  :				int							,  lowerCAmelCase__  :				Union[str, Any]		):





					"""simple docstring"""






					super().__init__()
					__SCREAMING_SNAKE_CASE :	List[Any]					 =	TaLayerNorm(lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	Any					 =	TaFiLMLayer(in_features=d_model * 4							,  out_features=lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	List[str]					 =	Attention(query_dim=lowerCAmelCase__							,  heads=lowerCAmelCase__							,  dim_head=lowerCAmelCase__							,  out_bias=lowerCAmelCase__							,  scale_qk=lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	Optional[int]					 =	nn.Dropout(lowerCAmelCase__		)



			def UpperCamelCase__      (							self  :				int							,  lowerCAmelCase__  :				Union[str, Any]							,  lowerCAmelCase__  :				List[str]=None							,  lowerCAmelCase__  :				int=None							,  ):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	Tuple					 =	self.layer_norm(lowerCAmelCase__		)

					if conditioning_emb is not None:
							__SCREAMING_SNAKE_CASE :	str					 =	self.FiLMLayer(lowerCAmelCase__							,  lowerCAmelCase__		)

					# Self-attention block
					__SCREAMING_SNAKE_CASE :	List[Any]					 =	self.attention(lowerCAmelCase__		)

					__SCREAMING_SNAKE_CASE :	str					 =	hidden_states + self.dropout(lowerCAmelCase__		)

					return hidden_states






class 		_UpperCamelCase						(							nn.Module					):


			'''simple docstring'''

			def __init__(							self  :				Union[str, Any]							,  lowerCAmelCase__  :				int							,  lowerCAmelCase__  :				Dict							,  lowerCAmelCase__  :				Tuple							,  lowerCAmelCase__  :				Dict							,  lowerCAmelCase__  :				str		):





					"""simple docstring"""






					super().__init__()
					__SCREAMING_SNAKE_CASE :	Dict					 =	Attention(query_dim=lowerCAmelCase__							,  heads=lowerCAmelCase__							,  dim_head=lowerCAmelCase__							,  out_bias=lowerCAmelCase__							,  scale_qk=lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	Any					 =	TaLayerNorm(lowerCAmelCase__							,  eps=lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	Optional[int]					 =	nn.Dropout(lowerCAmelCase__		)



			def UpperCamelCase__      (							self  :				List[Any]							,  lowerCAmelCase__  :				Tuple							,  lowerCAmelCase__  :				List[str]=None							,  lowerCAmelCase__  :				Any=None							,  ):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	Dict					 =	self.layer_norm(lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	List[str]					 =	self.attention(
					    lowerCAmelCase__							,  encoder_hidden_states=lowerCAmelCase__							,  attention_mask=attention_mask.squeeze(1		)							,  )
					__SCREAMING_SNAKE_CASE :	Dict					 =	hidden_states + self.dropout(lowerCAmelCase__		)
					return layer_output






class 		_UpperCamelCase						(							nn.Module					):


			'''simple docstring'''

			def __init__(							self  :				List[str]							,  lowerCAmelCase__  :				Dict							,  lowerCAmelCase__  :				Any							,  lowerCAmelCase__  :				Tuple							,  lowerCAmelCase__  :				int		):





					"""simple docstring"""






					super().__init__()
					__SCREAMING_SNAKE_CASE :	Any					 =	TaDenseGatedActDense(d_model=lowerCAmelCase__							,  d_ff=lowerCAmelCase__							,  dropout_rate=lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	Union[str, Any]					 =	TaFiLMLayer(in_features=d_model * 4							,  out_features=lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	Tuple					 =	TaLayerNorm(lowerCAmelCase__							,  eps=lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	Tuple					 =	nn.Dropout(lowerCAmelCase__		)



			def UpperCamelCase__      (							self  :				int							,  lowerCAmelCase__  :				List[Any]							,  lowerCAmelCase__  :				Tuple=None		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	str					 =	self.layer_norm(lowerCAmelCase__		)
					if conditioning_emb is not None:
							__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	self.film(lowerCAmelCase__							,  lowerCAmelCase__		)

					__SCREAMING_SNAKE_CASE :	int					 =	self.DenseReluDense(lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	Any					 =	hidden_states + self.dropout(lowerCAmelCase__		)
					return hidden_states






class 		_UpperCamelCase						(							nn.Module					):


			'''simple docstring'''

			def __init__(							self  :				Tuple							,  lowerCAmelCase__  :				List[str]							,  lowerCAmelCase__  :				Optional[int]							,  lowerCAmelCase__  :				Dict		):





					"""simple docstring"""






					super().__init__()
					__SCREAMING_SNAKE_CASE :	Tuple					 =	nn.Linear(lowerCAmelCase__							,  lowerCAmelCase__							,  bias=lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	Any					 =	nn.Linear(lowerCAmelCase__							,  lowerCAmelCase__							,  bias=lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	Dict					 =	nn.Linear(lowerCAmelCase__							,  lowerCAmelCase__							,  bias=lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	nn.Dropout(lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	Dict					 =	NewGELUActivation()



			def UpperCamelCase__      (							self  :				List[str]							,  lowerCAmelCase__  :				Optional[Any]		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	int					 =	self.act(self.wi_a(lowerCAmelCase__		)		)
					__SCREAMING_SNAKE_CASE :	Any					 =	self.wi_a(lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	Union[str, Any]					 =	hidden_gelu * hidden_linear
					__SCREAMING_SNAKE_CASE :	List[Any]					 =	self.dropout(lowerCAmelCase__		)

					__SCREAMING_SNAKE_CASE :	List[str]					 =	self.wo(lowerCAmelCase__		)
					return hidden_states






class 		_UpperCamelCase						(							nn.Module					):


			'''simple docstring'''

			def __init__(							self  :				List[Any]							,  lowerCAmelCase__  :				Union[str, Any]							,  lowerCAmelCase__  :				Tuple=1E-6		):





					"""simple docstring"""






					super().__init__()
					__SCREAMING_SNAKE_CASE :	Dict					 =	nn.Parameter(torch.ones(lowerCAmelCase__		)		)
					__SCREAMING_SNAKE_CASE :	str					 =	eps



			def UpperCamelCase__      (							self  :				Dict							,  lowerCAmelCase__  :				Optional[Any]		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	Optional[int]					 =	hidden_states.to(torch.floataa		).pow(2		).mean(-1							,  keepdim=lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	Any					 =	hidden_states * torch.rsqrt(variance + self.variance_epsilon		)

					# convert into half-precision if necessary
					if self.weight.dtype in [torch.floataa, torch.bfloataa]:
							__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	hidden_states.to(self.weight.dtype		)

					return self.weight * hidden_states






class 		_UpperCamelCase						(							nn.Module					):


			'''simple docstring'''

			def UpperCamelCase__      (							self  :				Union[str, Any]							,  lowerCAmelCase__  :				torch.Tensor		):





					"""simple docstring"""






					return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi		) * (input + 0.04_47_15 * torch.pow(lowerCAmelCase__							,  3.0		))		))






class 		_UpperCamelCase						(							nn.Module					):


			'''simple docstring'''

			def __init__(							self  :				Any							,  lowerCAmelCase__  :				Dict							,  lowerCAmelCase__  :				Union[str, Any]		):





					"""simple docstring"""






					super().__init__()
					__SCREAMING_SNAKE_CASE :	Tuple					 =	nn.Linear(lowerCAmelCase__							,  out_features * 2							,  bias=lowerCAmelCase__		)



			def UpperCamelCase__      (							self  :				List[Any]							,  lowerCAmelCase__  :				List[str]							,  lowerCAmelCase__  :				Tuple		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	Dict					 =	self.scale_bias(lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE ,		__SCREAMING_SNAKE_CASE :	Tuple					 =	torch.chunk(lowerCAmelCase__							,  2							,  -1		)
					__SCREAMING_SNAKE_CASE :	Dict					 =	x * (1 + scale) + shift
					return x




'''simple docstring'''




from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


UpperCamelCase__ :			List[Any]												=				{
    '''configuration_time_series_transformer''': [
        '''TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''TimeSeriesTransformerConfig''',
    ],
}

try:
						if not is_torch_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						UpperCamelCase__ :			List[Any]												=				[
						    '''TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST''',
						    '''TimeSeriesTransformerForPrediction''',
						    '''TimeSeriesTransformerModel''',
						    '''TimeSeriesTransformerPreTrainedModel''',
						]


if TYPE_CHECKING:
						from .configuration_time_series_transformer import (
						    TIME_SERIES_TRANSFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP,
						    TimeSeriesTransformerConfig,
						)

						try:
												if not is_torch_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_time_series_transformer import (
												    TIME_SERIES_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
												    TimeSeriesTransformerForPrediction,
												    TimeSeriesTransformerModel,
												    TimeSeriesTransformerPreTrainedModel,
												)

else:
						import sys

						UpperCamelCase__ :			Dict												=				_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)