

from typing import List, Optional, Union

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


A_	:			Tuple  	=      logging.get_logger(__name__)

A_	:			Optional[int]  	=      {
    '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    _a						(__magic_name__    ):


					'''simple docstring'''






					UpperCAmelCase__:       Dict  							=	'''time_series_transformer'''
					UpperCAmelCase__:       Union[str, Any]  							=	{
					    '''hidden_size''': '''d_model''',
					    '''num_attention_heads''': '''encoder_attention_heads''',
					    '''num_hidden_layers''': '''encoder_layers''',
					}






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

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

						A__							:   int					       =		dropout
						A__							:   Optional[int]					       =		attention_dropout
						A__							:   List[Any]					       =		activation_dropout
						A__							:   str					       =		encoder_layerdrop
						A__							:   str					       =		decoder_layerdrop

						A__							:   List[Any]					       =		activation_function
						A__							:   Optional[Any]					       =		init_std

						A__							:   Any					       =		use_cache

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






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






import os
import shutil
from pathlib import Path
from typing import Optional, Union

import numpy as np
from huggingface_hub import hf_hub_download

from ..utils import ONNX_EXTERNAL_WEIGHTS_NAME, ONNX_WEIGHTS_NAME, is_onnx_available, logging


if is_onnx_available():
	import onnxruntime as ort


A_	:			Union[str, Any]  	=      logging.get_logger(__name__)

A_	:			str  	=      {
    'tensor(bool)': np.bool_,
    'tensor(int8)': np.inta,
    'tensor(uint8)': np.uinta,
    'tensor(int16)': np.intaa,
    'tensor(uint16)': np.uintaa,
    'tensor(int32)': np.intaa,
    'tensor(uint32)': np.uintaa,
    'tensor(int64)': np.intaa,
    'tensor(uint64)': np.uintaa,
    'tensor(float16)': np.floataa,
    'tensor(float)': np.floataa,
    'tensor(double)': np.floataa,
}



class    _a						:


					'''simple docstring'''






					def __init__(			self   ,	A__=None   ,	**A__      ):
						logger.info("""`diffusers.OnnxRuntimeModel` is experimental and might change in the future."""      )
						A__							:   Dict					       =		model
						A__							:   Any					       =		kwargs.get("""model_save_dir"""   ,	A__      )
						A__							:   Optional[int]					       =		kwargs.get("""latest_model_name"""   ,	A__      )






					def __call__(			self   ,	**A__      ):
						A__							:   int					       =		{k: np.array(A__      ) for k, v in kwargs.items()}
						return self.model.run(A__   ,	A__      )






					@staticmethod
					def   __A      (			A__   ,	A__=None   ,	A__=None      ):
						if provider is None:
							logger.info("""No onnxruntime provider specified, using CPUExecutionProvider"""      )
							A__							:   List[Any]					       =		"""CPUExecutionProvider"""

						return ort.InferenceSession(A__   ,	providers=[provider]   ,	sess_options=A__      )






					def   __A      (			self   ,	A__   ,	A__ = None   ,	**A__      ):
						A__							:   List[Any]					       =		file_name if file_name is not None else ONNX_WEIGHTS_NAME

						A__							:   List[Any]					       =		self.model_save_dir.joinpath(self.latest_model_name      )
						A__							:   Optional[int]					       =		Path(A__      ).joinpath(A__      )
						try:
							shutil.copyfile(A__   ,	A__      )
						except shutil.SameFileError:
							pass

						# copy external weights (for models >2GB)
						A__							:   str					       =		self.model_save_dir.joinpath(A__      )
						if src_path.exists():
							A__							:   List[str]					       =		Path(A__      ).joinpath(A__      )
							try:
								shutil.copyfile(A__   ,	A__      )
							except shutil.SameFileError:
								pass






					def   __A      (			self   ,	A__   ,	**A__   ,	):
						if os.path.isfile(A__      ):
							logger.error(F"""Provided path ({save_directory}) should be a directory, not a file"""      )
							return

						os.makedirs(A__   ,	exist_ok=A__      )

						# saving model weights/files
						self._save_pretrained(A__   ,	**A__      )






					@classmethod
					def   __A      (			cls   ,	A__   ,	A__ = None   ,	A__ = None   ,	A__ = False   ,	A__ = None   ,	A__ = None   ,	A__ = None   ,	A__ = None   ,	**A__   ,	):
						A__							:   str					       =		file_name if file_name is not None else ONNX_WEIGHTS_NAME
						# load model from local directory
						if os.path.isdir(A__      ):
							A__							:   Dict					       =		OnnxRuntimeModel.load_model(
							    os.path.join(A__   ,	A__      )   ,	provider=A__   ,	sess_options=A__      )
							A__							:   Optional[Any]					       =		Path(A__      )
						# load model from hub
						else:
							# download model
							A__							:   Union[str, Any]					       =		hf_hub_download(
							    repo_id=A__   ,	filename=A__   ,	use_auth_token=A__   ,	revision=A__   ,	cache_dir=A__   ,	force_download=A__   ,	)
							A__							:   List[str]					       =		Path(A__      ).parent
							A__							:   str					       =		Path(A__      ).name
							A__							:   Optional[int]					       =		OnnxRuntimeModel.load_model(A__   ,	provider=A__   ,	sess_options=A__      )
						return cls(model=A__   ,	**A__      )






					@classmethod
					def   __A      (			cls   ,	A__   ,	A__ = True   ,	A__ = None   ,	A__ = None   ,	**A__   ,	):
						A__							:   Optional[Any]					       =		None
						if len(str(A__      ).split("""@"""      )      ) == 2:
							A__       ,       A__							:   Union[str, Any]					       =		model_id.split("""@"""      )

						return cls._from_pretrained(
						    model_id=A__   ,	revision=A__   ,	cache_dir=A__   ,	force_download=A__   ,	use_auth_token=A__   ,	**A__   ,	)



