"""simple docstring"""







from typing import List, Optional

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


SCREAMING_SNAKE_CASE									=						logging.get_logger(__name__)

SCREAMING_SNAKE_CASE									=						{
    '''huggingface/autoformer-tourism-monthly''': '''https://huggingface.co/huggingface/autoformer-tourism-monthly/resolve/main/config.json''',
}



class  _lowerCamelCase			(SCREAMING_SNAKE_CASE__     ):
				_snake_case     =  "autoformer"
				_snake_case     =  {
				    "hidden_size": "d_model",
				    "num_attention_heads": "encoder_attention_heads",
				    "num_hidden_layers": "encoder_layers",
				}







				def __init__( self    :       int			,					lowerCamelCase_    :       Dict = None			,					lowerCamelCase_    :       Tuple = None			,					lowerCamelCase_    :       str = "student_t"			,					lowerCamelCase_    :       str = "nll"			,					lowerCamelCase_    :       Tuple = 1			,					lowerCamelCase_    :       Any = [1, 2, 3, 4, 5, 6, 7]			,					lowerCamelCase_    :       List[Any] = True			,					lowerCamelCase_    :       Any = 0			,					lowerCamelCase_    :       Optional[int] = 0			,					lowerCamelCase_    :       Optional[int] = 0			,					lowerCamelCase_    :       List[Any] = 0			,					lowerCamelCase_    :       str = None			,					lowerCamelCase_    :       List[Any] = None			,					lowerCamelCase_    :       int = 6_4			,					lowerCamelCase_    :       Tuple = 2			,					lowerCamelCase_    :       Optional[int] = 2			,					lowerCamelCase_    :       str = 2			,					lowerCamelCase_    :       str = 2			,					lowerCamelCase_    :       int = 3_2			,					lowerCamelCase_    :       List[str] = 3_2			,					lowerCamelCase_    :       Optional[Any] = "gelu"			,					lowerCamelCase_    :       Any = 0.1			,					lowerCamelCase_    :       Optional[Any] = 0.1			,					lowerCamelCase_    :       List[Any] = 0.1			,					lowerCamelCase_    :       Dict = 0.1			,					lowerCamelCase_    :       List[str] = 0.1			,					lowerCamelCase_    :       Union[str, Any] = 1_0_0			,					lowerCamelCase_    :       Dict = 0.02			,					lowerCamelCase_    :       List[Any] = True			,					lowerCamelCase_    :       Tuple=True			,					lowerCamelCase_    :       List[Any] = 1_0			,					lowerCamelCase_    :       List[str] = 2_5			,					lowerCamelCase_    :       List[str] = 3			,					**lowerCamelCase_    :       Tuple			,					)     ->   Optional[Any]:

					"""simple docstring"""






					_lowercase :    Tuple							=							prediction_length
					_lowercase :    Tuple							=							context_length if context_length is not None else prediction_length
					_lowercase :    Optional[int]							=							distribution_output
					_lowercase :    List[str]							=							loss
					_lowercase :    Dict							=							input_size
					_lowercase :    str							=							num_time_features
					_lowercase :    Union[str, Any]							=							lags_sequence
					_lowercase :    Union[str, Any]							=							scaling
					_lowercase :    str							=							num_dynamic_real_features
					_lowercase :    List[Any]							=							num_static_real_features
					_lowercase :    str							=							num_static_categorical_features
					if cardinality is not None and num_static_categorical_features > 0:
						if len(_lowercase						) != num_static_categorical_features:
							raise ValueError(
							    'The cardinality should be a list of the same length as `num_static_categorical_features`'						)
						_lowercase :    Optional[Any]							=							cardinality
					else:
						_lowercase :    Tuple							=							[0]
					if embedding_dimension is not None and num_static_categorical_features > 0:
						if len(_lowercase						) != num_static_categorical_features:
							raise ValueError(
							    'The embedding dimension should be a list of the same length as `num_static_categorical_features`'						)
						_lowercase :    Optional[int]							=							embedding_dimension
					else:
						_lowercase :    str							=							[min(5_0			,					(cat + 1) // 2						) for cat in self.cardinality]
					_lowercase :    str							=							num_parallel_samples

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

					_lowercase :    Union[str, Any]							=							dropout
					_lowercase :    List[Any]							=							attention_dropout
					_lowercase :    Dict							=							activation_dropout
					_lowercase :    str							=							encoder_layerdrop
					_lowercase :    Any							=							decoder_layerdrop

					_lowercase :    Tuple							=							activation_function
					_lowercase :    Optional[Any]							=							init_std

					_lowercase :    Optional[int]							=							use_cache

					# Autoformer
					_lowercase :    List[Any]							=							label_length
					_lowercase :    Union[str, Any]							=							moving_average
					_lowercase :    Optional[Any]							=							autocorrelation_factor

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







				@property
				def 							__UpperCAmelCase					( self    :       Optional[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 doctest
import glob
import importlib
import inspect
import os
import re
from contextlib import contextmanager
from functools import wraps
from unittest.mock import patch

import numpy as np
import pytest
from absl.testing import parameterized

import datasets
from datasets import load_metric

from .utils import for_all_test_methods, local, slow


# mark all tests as integration
SCREAMING_SNAKE_CASE									=						pytest.mark.integration


SCREAMING_SNAKE_CASE									=						{'comet'}
SCREAMING_SNAKE_CASE									=						importlib.util.find_spec('fairseq') is not None

SCREAMING_SNAKE_CASE									=						{'code_eval'}
SCREAMING_SNAKE_CASE									=						os.name == 'nt'

SCREAMING_SNAKE_CASE									=						{'bertscore', 'frugalscore', 'perplexity'}
SCREAMING_SNAKE_CASE									=						importlib.util.find_spec('transformers') is not None


def      __lowerCAmelCase(		__UpperCAmelCase			):






	"""simple docstring"""





	@wraps(__UpperCAmelCase			)
	def wrapper(self     ,__UpperCAmelCase			):
		if not _has_fairseq and metric_name in REQUIRE_FAIRSEQ:
			self.skipTest('"test requires Fairseq"'			)
		else:
			test_case(self     ,__UpperCAmelCase			)

	return wrapper


def      __lowerCAmelCase(		__UpperCAmelCase			):






	"""simple docstring"""





	@wraps(__UpperCAmelCase			)
	def wrapper(self     ,__UpperCAmelCase			):
		if not _has_transformers and metric_name in REQUIRE_TRANSFORMERS:
			self.skipTest('"test requires transformers"'			)
		else:
			test_case(self     ,__UpperCAmelCase			)

	return wrapper


def      __lowerCAmelCase(		__UpperCAmelCase			):






	"""simple docstring"""





	@wraps(__UpperCAmelCase			)
	def wrapper(self     ,__UpperCAmelCase			):
		if _on_windows and metric_name in UNSUPPORTED_ON_WINDOWS:
			self.skipTest('"test not supported on Windows"'			)
		else:
			test_case(self     ,__UpperCAmelCase			)

	return wrapper


def      __lowerCAmelCase(		):






	"""simple docstring"""





	_lowercase :    int							=							[metric_dir.split(os.sep			)[-2] for metric_dir in glob.glob('./metrics/*/'			)]
	return [{"testcase_name": x, "metric_name": x} for x in metrics if x != "gleu"]  # gleu is unfinished



@parameterized.named_parameters(get_local_metric_names()     )
@for_all_test_methods(
    __lowerCamelCase						,							__lowerCamelCase						,							__lowerCamelCase     )
@local
class  _lowerCamelCase			(parameterized.TestCase     ):
				_snake_case     =  {}
				_snake_case     =  None







				@pytest.mark.filterwarnings('ignore:metric_module_factory is deprecated:FutureWarning'						)
				@pytest.mark.filterwarnings('ignore:load_metric is deprecated:FutureWarning'						)
				def 							__UpperCAmelCase					( self    :       str			,					lowerCamelCase_    :       List[str]						):

					"""simple docstring"""






					_lowercase :    Optional[Any]							=							'[...]'
					_lowercase :    str							=							importlib.import_module(
					    datasets.load.metric_module_factory(os.path.join('metrics'			,					lowerCamelCase_						)						).module_path						)
					_lowercase :    Dict							=							datasets.load.import_main_class(metric_module.__name__			,					dataset=lowerCamelCase_						)
					# check parameters
					_lowercase :    Optional[int]							=							inspect.signature(metric._compute						).parameters
					self.assertTrue(all(p.kind != p.VAR_KEYWORD for p in parameters.values()						)						)  # no **kwargs
					# run doctest
					with self.patch_intensive_calls(lowerCamelCase_			,					metric_module.__name__						):
						with self.use_local_metrics():
							try:
								_lowercase :    Optional[Any]							=							doctest.testmod(lowerCamelCase_			,					verbose=lowerCamelCase_			,					raise_on_error=lowerCamelCase_						)
							except doctest.UnexpectedException as e:
								raise e.exc_info[1]  # raise the exception that doctest caught
					self.assertEqual(results.failed			,					0						)
					self.assertGreater(results.attempted			,					1						)







				@slow
				def 							__UpperCAmelCase					( self    :       Any			,					lowerCamelCase_    :       Dict						):

					"""simple docstring"""






					_lowercase :    Optional[Any]							=							'[...]'
					_lowercase :    Dict							=							importlib.import_module(
					    datasets.load.metric_module_factory(os.path.join('metrics'			,					lowerCamelCase_						)						).module_path						)
					# run doctest
					with self.use_local_metrics():
						_lowercase :    str							=							doctest.testmod(lowerCamelCase_			,					verbose=lowerCamelCase_			,					raise_on_error=lowerCamelCase_						)
					self.assertEqual(results.failed			,					0						)
					self.assertGreater(results.attempted			,					1						)







				@contextmanager
				def 							__UpperCAmelCase					( self    :       Tuple			,					lowerCamelCase_    :       int			,					lowerCamelCase_    :       str						):

					"""simple docstring"""






					if metric_name in self.INTENSIVE_CALLS_PATCHER:
						with self.INTENSIVE_CALLS_PATCHER[metric_name](lowerCamelCase_						):
							yield
					else:
						yield







				@contextmanager
				def 							__UpperCAmelCase					( self    :       Dict						):

					"""simple docstring"""






					def load_local_metric(lowerCamelCase_    :       Optional[Any]			,					*lowerCamelCase_    :       Any			,					**lowerCamelCase_    :       Optional[int]						):
						return load_metric(os.path.join('metrics'			,					lowerCamelCase_						)			,					*lowerCamelCase_			,					**lowerCamelCase_						)

					with patch('datasets.load_metric'						) as mock_load_metric:
						_lowercase :    str							=							load_local_metric
						yield







				@classmethod
				def 							__UpperCAmelCase					( cls    :       Tuple			,					lowerCamelCase_    :       Tuple						):

					"""simple docstring"""






					def wrapper(lowerCamelCase_    :       int						):
						_lowercase :    Any							=							contextmanager(lowerCamelCase_						)
						_lowercase :    Any							=							patcher
						return patcher

					return wrapper



@LocalMetricTest.register_intensive_calls_patcher('bleurt'			)
def      __lowerCAmelCase(		__UpperCAmelCase			):






	"""simple docstring"""





	import tensorflow.compat.va as tf
	from bleurt.score import Predictor

	tf.flags.DEFINE_string('sv'     ,''     ,''			)  # handle pytest cli flags



	class  _lowerCamelCase			(__lowerCamelCase     ):







					def 							__UpperCAmelCase					( self    :       Optional[Any]			,					lowerCamelCase_    :       str						):

						"""simple docstring"""






						assert len(input_dict['input_ids']						) == 2
						return np.array([1.03, 1.04]						)

    # mock predict_fn which is supposed to do a forward pass with a bleurt model
	with patch('bleurt.score._create_predictor'			) as mock_create_predictor:
		_lowercase :    Dict							=							MockedPredictor()
		yield


@LocalMetricTest.register_intensive_calls_patcher('bertscore'			)
def      __lowerCAmelCase(		__UpperCAmelCase			):






	"""simple docstring"""





	import torch

	def bert_cos_score_idf(__UpperCAmelCase     ,__UpperCAmelCase     ,*__UpperCAmelCase     ,**__UpperCAmelCase			):
		return torch.tensor([[1.0, 1.0, 1.0]] * len(__UpperCAmelCase			)			)

	# mock get_model which is supposed to do download a bert model
	# mock bert_cos_score_idf which is supposed to do a forward pass with a bert model
	with patch('bert_score.scorer.get_model'			), patch(
	    'bert_score.scorer.bert_cos_score_idf'			) as mock_bert_cos_score_idf:
		_lowercase :    Tuple							=							bert_cos_score_idf
		yield


@LocalMetricTest.register_intensive_calls_patcher('comet'			)
def      __lowerCAmelCase(		__UpperCAmelCase			):






	"""simple docstring"""





	def load_from_checkpoint(__UpperCAmelCase			):



		class  _lowerCamelCase			:







						def 							__UpperCAmelCase					( self    :       Tuple			,					lowerCamelCase_    :       str			,					*lowerCamelCase_    :       List[Any]			,					**lowerCamelCase_    :       List[str]						):

							"""simple docstring"""






							assert len(lowerCamelCase_						) == 2
							_lowercase :    Union[str, Any]							=							[0.19, 0.92]
							return scores, sum(lowerCamelCase_						) / len(lowerCamelCase_						)



		return Model()

	# mock load_from_checkpoint which is supposed to do download a bert model
	# mock load_from_checkpoint which is supposed to do download a bert model
	with patch('comet.download_model'			) as mock_download_model:
		_lowercase :    Dict							=							None
		with patch('comet.load_from_checkpoint'			) as mock_load_from_checkpoint:
			_lowercase :    str							=							load_from_checkpoint
			yield







def      __lowerCAmelCase(		):






	"""simple docstring"""





	_lowercase :    Tuple							=							load_metric(os.path.join('metrics'     ,'seqeval'			)			)
	_lowercase :    int							=							'ERROR'
	_lowercase :    Union[str, Any]							=							F'''Scheme should be one of [IOB1, IOB2, IOE1, IOE2, IOBES, BILOU], got {wrong_scheme}'''
	with pytest.raises(__UpperCAmelCase     ,match=re.escape(__UpperCAmelCase			)			):
		metric.compute(predictions=[]     ,references=[]     ,scheme=__UpperCAmelCase			)



