






import warnings
from typing import Dict

import numpy as np

from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available
from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline


if is_tf_available():
	from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING

if is_torch_available():
	from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
def       snake_case_		(     lowerCAmelCase_       :						List[Any]      ):
							return 1.0 / (1.0 + np.exp(-_outputs      ))
def       snake_case_		(     lowerCAmelCase_       :						int      ):
							__lowercase      :							Dict				=     np.max(_outputs       ,       axis=-1       ,       keepdims=lowerCAmelCase_      )
							__lowercase      :							Tuple				=     np.exp(_outputs - maxes      )
							return shifted_exp / shifted_exp.sum(axis=-1       ,       keepdims=lowerCAmelCase_      )

class 		lowerCAmelCase     ( __a			):

					'''simple docstring'''

					_A						:			Union[str, Any]									=      '''sigmoid'''
					_A						:			Optional[int]									=      '''softmax'''
					_A						:			str									=      '''none'''







@add_end_docstrings(
    __a      ,       r'''
        return_all_scores (`bool`, *optional*, defaults to `False`):
            Whether to return all prediction scores or just the one of the predicted class.
        function_to_apply (`str`, *optional*, defaults to `"default"`):
            The function to apply to the model outputs in order to retrieve the scores. Accepts four different values:

            - `"default"`: if the model has a single label, will apply the sigmoid function on the output. If the model
              has several labels, will apply the softmax function on the output.
            - `"sigmoid"`: Applies the sigmoid function on the output.
            - `"softmax"`: Applies the softmax function on the output.
            - `"none"`: Does not apply any function on the output.
    '''      ,       )
class 		lowerCAmelCase     ( __a			):

					'''simple docstring'''

					_A						:			Any									=      False
					_A						:			Dict									=      ClassificationFunction.NONE



					def __init__(  self				:	Dict		,     **__a				:	int							)			->  str:


												"""simple docstring"""

												super().__init__(**__a							)

												self.check_model_type(
												    TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING
												    if self.framework == """tf"""
												    else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING							)



					def       lowerCAmelCase				(  self				:	Any		,     __a				:	Tuple=None		,     __a				:	Any=None		,     __a				:	Dict=""		,     **__a				:	Dict							)			->  Optional[int]:


												"""simple docstring"""

												__lowercase      :							Union[str, Any]				=     tokenizer_kwargs

												__lowercase      :							Union[str, Any]				=     {}
												if hasattr(self.model.config		,     """return_all_scores"""							) and return_all_scores is None:
																			__lowercase      :							Union[str, Any]				=     self.model.config.return_all_scores

												if isinstance(__a		,     __a							) or top_k is None:
																			__lowercase      :							List[Any]				=     top_k
																			__lowercase      :							Dict				=     False
												elif return_all_scores is not None:
																			warnings.warn(
																			    """`return_all_scores` is now deprecated,  if want a similar functionality use `top_k=None` instead of"""
																			    """ `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`."""		,     __a		,     )
																			if return_all_scores:
																										__lowercase      :							Union[str, Any]				=     None
																			else:
																										__lowercase      :							Tuple				=     1

												if isinstance(__a		,     __a							):
																			__lowercase      :							str				=     ClassificationFunction[function_to_apply.upper()]

												if function_to_apply is not None:
																			__lowercase      :							Any				=     function_to_apply
												return preprocess_params, {}, postprocess_params



					def __call__(  self				:	str		,     *__a				:	str		,     **__a				:	List[Any]							)			->  List[Any]:


												"""simple docstring"""

												__lowercase      :							str				=     super().__call__(*__a		,     **__a							)
												# TODO try and retrieve it in a nicer way from _sanitize_parameters.
												__lowercase      :							Tuple				=     """top_k""" not in kwargs
												if isinstance(args[0]		,     __a							) and _legacy:
																			# This pipeline is odd, and return a list when single item is run
																			return [result]
												else:
																			return result



					def       lowerCAmelCase				(  self				:	Union[str, Any]		,     __a				:	List[Any]		,     **__a				:	Union[str, Any]							)			->  Dict[str, GenericTensor]:


												"""simple docstring"""

												__lowercase      :							int				=     self.framework
												if isinstance(__a		,     __a							):
																			return self.tokenizer(**__a		,     return_tensors=__a		,     **__a							)
												elif isinstance(__a		,     __a							) and len(__a							) == 1 and isinstance(inputs[0]		,     __a							) and len(inputs[0]							) == 2:
																			# It used to be valid to use a list of list of list for text pairs, keeping this path for BC
																			return self.tokenizer(
																			    text=inputs[0][0]		,     text_pair=inputs[0][1]		,     return_tensors=__a		,     **__a							)
												elif isinstance(__a		,     __a							):
																			# This is likely an invalid usage of the pipeline attempting to pass text pairs.
																			raise ValueError(
																			    """The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a"""
																			    """ dictionary `{\"text\": \"My text\", \"text_pair\": \"My pair\"}` in order to send a text pair."""							)
												return self.tokenizer(__a		,     return_tensors=__a		,     **__a							)



					def       lowerCAmelCase				(  self				:	str		,     __a				:	List[str]							)			->  Dict:


												"""simple docstring"""

												return self.model(**__a							)



					def       lowerCAmelCase				(  self				:	int		,     __a				:	Optional[int]		,     __a				:	Optional[int]=None		,     __a				:	Tuple=1		,     __a				:	List[str]=True							)			->  Optional[Any]:


												"""simple docstring"""

												if function_to_apply is None:
																			if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1:
																										__lowercase      :							str				=     ClassificationFunction.SIGMOID
																			elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1:
																										__lowercase      :							Optional[Any]				=     ClassificationFunction.SOFTMAX
																			elif hasattr(self.model.config		,     """function_to_apply"""							) and function_to_apply is None:
																										__lowercase      :							Tuple				=     self.model.config.function_to_apply
																			else:
																										__lowercase      :							List[str]				=     ClassificationFunction.NONE

												__lowercase      :							List[str]				=     model_outputs["""logits"""][0]
												__lowercase      :							Any				=     outputs.numpy()

												if function_to_apply == ClassificationFunction.SIGMOID:
																			__lowercase      :							int				=     sigmoid(__a							)
												elif function_to_apply == ClassificationFunction.SOFTMAX:
																			__lowercase      :							Optional[int]				=     softmax(__a							)
												elif function_to_apply == ClassificationFunction.NONE:
																			__lowercase      :							Union[str, Any]				=     outputs
												else:
																			raise ValueError(F"Unrecognized `function_to_apply` argument: {function_to_apply}"							)

												if top_k == 1 and _legacy:
																			return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()}

												__lowercase      :							int				=     [
												    {"""label""": self.model.config.idalabel[i], """score""": score.item()} for i, score in enumerate(__a							)
												]
												if not _legacy:
																			dict_scores.sort(key=lambda __a							: x["score"]		,     reverse=__a							)
																			if top_k is not None:
																										__lowercase      :							int				=     dict_scores[:top_k]
												return dict_scores







import inspect
import tempfile
import unittest

from huggingface_hub import hf_hub_download

from transformers import is_torch_available
from transformers.testing_utils import is_flaky, require_torch, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


lowerCamelCase : Union[str, Any]						   =       1E-4

if is_torch_available():
	import torch

	from transformers import AutoformerConfig, AutoformerForPrediction, AutoformerModel
	from transformers.models.autoformer.modeling_autoformer import AutoformerDecoder, AutoformerEncoder

@require_torch
class 		lowerCAmelCase     :

					'''simple docstring'''

					def __init__(  self				:	Dict		,     __a				:	List[str]		,     __a				:	Optional[int]=16		,     __a				:	Optional[Any]=13		,     __a				:	str=7		,     __a				:	List[str]=14		,     __a				:	Any=10		,     __a				:	str=19		,     __a				:	int=5		,     __a				:	Any=4		,     __a				:	List[Any]=True		,     __a				:	Tuple=16		,     __a				:	Dict=2		,     __a				:	Tuple=4		,     __a				:	int=4		,     __a				:	List[Any]="gelu"		,     __a				:	Tuple=0.1		,     __a				:	List[str]=0.1		,     __a				:	int=[1, 2, 3, 4, 5]		,     __a				:	str=25		,     __a				:	Any=5		,     )			->  Optional[Any]:


												"""simple docstring"""

												__lowercase      :							Optional[Any]				=     d_model
												__lowercase      :							Dict				=     parent
												__lowercase      :							Tuple				=     batch_size
												__lowercase      :							Optional[int]				=     prediction_length
												__lowercase      :							List[str]				=     context_length
												__lowercase      :							Any				=     cardinality
												__lowercase      :							str				=     num_time_features
												__lowercase      :							Optional[int]				=     lags_sequence
												__lowercase      :							Optional[Any]				=     embedding_dimension
												__lowercase      :							List[Any]				=     is_training
												__lowercase      :							List[str]				=     hidden_size
												__lowercase      :							int				=     num_hidden_layers
												__lowercase      :							Any				=     num_attention_heads
												__lowercase      :							List[Any]				=     intermediate_size
												__lowercase      :							int				=     hidden_act
												__lowercase      :							str				=     hidden_dropout_prob
												__lowercase      :							List[Any]				=     attention_probs_dropout_prob

												__lowercase      :							str				=     context_length
												__lowercase      :							int				=     prediction_length + label_length
												__lowercase      :							Union[str, Any]				=     label_length

												__lowercase      :							Optional[int]				=     moving_average
												__lowercase      :							Optional[Any]				=     autocorrelation_factor



					def       lowerCAmelCase				(  self				:	str							)			->  List[str]:


												"""simple docstring"""

												return AutoformerConfig(
												    d_model=self.d_model		,     encoder_layers=self.num_hidden_layers		,     decoder_layers=self.num_hidden_layers		,     encoder_attention_heads=self.num_attention_heads		,     decoder_attention_heads=self.num_attention_heads		,     encoder_ffn_dim=self.intermediate_size		,     decoder_ffn_dim=self.intermediate_size		,     dropout=self.hidden_dropout_prob		,     attention_dropout=self.attention_probs_dropout_prob		,     prediction_length=self.prediction_length		,     context_length=self.context_length		,     label_length=self.label_length		,     lags_sequence=self.lags_sequence		,     num_time_features=self.num_time_features		,     num_static_categorical_features=1		,     cardinality=[self.cardinality]		,     embedding_dimension=[self.embedding_dimension]		,     moving_average=self.moving_average		,     )



					def       lowerCAmelCase				(  self				:	Tuple		,     __a				:	str							)			->  int:


												"""simple docstring"""

												__lowercase      :							Any				=     config.context_length + max(config.lags_sequence							)

												__lowercase      :							Any				=     ids_tensor([self.batch_size, 1]		,     config.cardinality[0]							)
												__lowercase      :							Optional[int]				=     floats_tensor([self.batch_size, _past_length, config.num_time_features]							)
												__lowercase      :							List[str]				=     floats_tensor([self.batch_size, _past_length]							)
												__lowercase      :							List[str]				=     floats_tensor([self.batch_size, _past_length]							) > 0.5

												# decoder inputs
												__lowercase      :							Dict				=     floats_tensor([self.batch_size, config.prediction_length, config.num_time_features]							)
												__lowercase      :							str				=     floats_tensor([self.batch_size, config.prediction_length]							)

												__lowercase      :							List[str]				=     {
												    """past_values""": past_values,
												    """static_categorical_features""": static_categorical_features,
												    """past_time_features""": past_time_features,
												    """past_observed_mask""": past_observed_mask,
												    """future_time_features""": future_time_features,
												    """future_values""": future_values,
												}
												return inputs_dict



					def       lowerCAmelCase				(  self				:	Union[str, Any]							)			->  Optional[Any]:


												"""simple docstring"""

												__lowercase      :							Optional[Any]				=     self.get_config()
												__lowercase      :							Any				=     self.prepare_autoformer_inputs_dict(__a							)
												return config, inputs_dict



					def       lowerCAmelCase				(  self				:	Optional[Any]							)			->  Tuple:


												"""simple docstring"""

												__lowercase			,			__lowercase      :							List[str]				=     self.prepare_config_and_inputs()
												return config, inputs_dict



					def       lowerCAmelCase				(  self				:	Optional[Any]		,     __a				:	Tuple		,     __a				:	Optional[int]							)			->  Any:


												"""simple docstring"""

												__lowercase      :							List[str]				=     AutoformerModel(config=__a							).to(__a							).eval()
												__lowercase      :							Optional[int]				=     model(**__a							)

												__lowercase      :							Dict				=     outputs.encoder_last_hidden_state
												__lowercase      :							Tuple				=     outputs.last_hidden_state

												with tempfile.TemporaryDirectory() as tmpdirname:
																			__lowercase      :							List[str]				=     model.get_encoder()
																			encoder.save_pretrained(__a							)
																			__lowercase      :							List[str]				=     AutoformerEncoder.from_pretrained(__a							).to(__a							)

												__lowercase			,			__lowercase			,			__lowercase			,			__lowercase			,			__lowercase      :							Any				=     model.create_network_inputs(**__a							)
												__lowercase			,			__lowercase      :							Any				=     model.decomposition_layer(transformer_inputs[:, : config.context_length, ...]							)

												__lowercase      :							Optional[Any]				=     torch.cat(
												    (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...])		,     dim=-1		,     )
												__lowercase      :							Union[str, Any]				=     encoder(inputs_embeds=__a							)[0]
												self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3							)

												__lowercase      :							str				=     (
												    torch.mean(transformer_inputs[:, : config.context_length, ...]		,     dim=1							)
												    .unsqueeze(1							)
												    .repeat(1		,     config.prediction_length		,     1							)
												)
												__lowercase      :							Optional[int]				=     torch.zeros(
												    [transformer_inputs.shape[0], config.prediction_length, transformer_inputs.shape[2]]		,     device=enc_input.device		,     )

												__lowercase      :							Any				=     torch.cat(
												    (
												        torch.cat((seasonal_input[:, -config.label_length :, ...], zeros)		,     dim=1							),
												        feature[:, config.context_length - config.label_length :, ...],
												    )		,     dim=-1		,     )
												__lowercase      :							Dict				=     torch.cat(
												    (
												        torch.cat((trend_input[:, -config.label_length :, ...], mean)		,     dim=1							),
												        feature[:, config.context_length - config.label_length :, ...],
												    )		,     dim=-1		,     )

												with tempfile.TemporaryDirectory() as tmpdirname:
																			__lowercase      :							Optional[Any]				=     model.get_decoder()
																			decoder.save_pretrained(__a							)
																			__lowercase      :							Tuple				=     AutoformerDecoder.from_pretrained(__a							).to(__a							)

												__lowercase      :							str				=     decoder(
												    trend=__a		,     inputs_embeds=__a		,     encoder_hidden_states=__a		,     )[0]

												self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1E-3							)







@require_torch
class 		lowerCAmelCase     ( __a      ,       __a      ,       unittest.TestCase			):

					'''simple docstring'''

					_A						:			List[str]									=      (AutoformerModel, AutoformerForPrediction) if is_torch_available() else ()
					_A						:			List[Any]									=      (AutoformerForPrediction,) if is_torch_available() else ()
					_A						:			Any									=      {'''feature-extraction''': AutoformerModel} if is_torch_available() else {}
					_A						:			Dict									=      False
					_A						:			Tuple									=      False
					_A						:			Optional[int]									=      False
					_A						:			Tuple									=      False
					_A						:			str									=      False
					_A						:			Union[str, Any]									=      False



					def       lowerCAmelCase				(  self				:	Dict							)			->  str:


												"""simple docstring"""

												__lowercase      :							List[str]				=     AutoformerModelTester(self							)
												__lowercase      :							Dict				=     ConfigTester(self		,     config_class=__a		,     has_text_modality=__a							)



					def       lowerCAmelCase				(  self				:	Union[str, Any]							)			->  str:


												"""simple docstring"""

												self.config_tester.run_common_tests()



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


												"""simple docstring"""

												__lowercase			,			__lowercase      :							Dict				=     self.model_tester.prepare_config_and_inputs()
												for model_class in self.all_model_classes:
																			__lowercase      :							Dict				=     model_class(__a							)

																			with tempfile.TemporaryDirectory() as tmpdirname:
																										model.save_pretrained(__a							)
																										__lowercase			,			__lowercase      :							Tuple				=     model_class.from_pretrained(__a		,     output_loading_info=__a							)
																			self.assertEqual(info["""missing_keys"""]		,     []							)



					def       lowerCAmelCase				(  self				:	List[str]							)			->  List[str]:


												"""simple docstring"""

												__lowercase      :							str				=     self.model_tester.prepare_config_and_inputs_for_common()
												self.model_tester.check_encoder_decoder_model_standalone(*__a							)



					@unittest.skip(reason="""Model has no tokens embeddings"""							)
					def       lowerCAmelCase				(  self				:	str							)			->  int:


												"""simple docstring"""

												pass



					def       lowerCAmelCase				(  self				:	Any							)			->  List[str]:


												"""simple docstring"""

												__lowercase      :							Any				=     inspect.signature(getattr(__a		,     """forward"""							)							)
												# The main input is the name of the argument after `self`
												__lowercase      :							Optional[int]				=     list(model_signature.parameters.keys()							)[1]
												self.assertEqual(AutoformerModel.main_input_name		,     __a							)



					def       lowerCAmelCase				(  self				:	List[Any]							)			->  Optional[Any]:


												"""simple docstring"""

												__lowercase			,			__lowercase      :							Optional[Any]				=     self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																			__lowercase      :							Dict				=     model_class(__a							)
																			__lowercase      :							Union[str, Any]				=     inspect.signature(model.forward							)
																			# signature.parameters is an OrderedDict => so arg_names order is deterministic
																			__lowercase      :							Any				=     [*signature.parameters.keys()]

																			__lowercase      :							int				=     [
																			    """past_values""",
																			    """past_time_features""",
																			    """past_observed_mask""",
																			    """static_categorical_features""",
																			    """static_real_features""",
																			    """future_values""",
																			    """future_time_features""",
																			]

																			if model.__class__.__name__ in ["AutoformerForPrediction"]:
																										expected_arg_names.append("""future_observed_mask"""							)

																			expected_arg_names.extend(
																			    [
																			        """decoder_attention_mask""",
																			        """head_mask""",
																			        """decoder_head_mask""",
																			        """cross_attn_head_mask""",
																			        """encoder_outputs""",
																			        """past_key_values""",
																			        """output_hidden_states""",
																			        """output_attentions""",
																			        """use_cache""",
																			        """return_dict""",
																			    ]							)

																			self.assertListEqual(arg_names[: len(__a							)]		,     __a							)



					def       lowerCAmelCase				(  self				:	int							)			->  int:


												"""simple docstring"""

												__lowercase			,			__lowercase      :							str				=     self.model_tester.prepare_config_and_inputs_for_common()
												__lowercase      :							int				=     True

												__lowercase      :							Tuple				=     getattr(self.model_tester		,     """seq_length"""		,     __a							)
												__lowercase      :							Union[str, Any]				=     getattr(self.model_tester		,     """decoder_seq_length"""		,     __a							)
												__lowercase      :							List[str]				=     getattr(self.model_tester		,     """encoder_seq_length"""		,     __a							)
												__lowercase      :							List[Any]				=     getattr(self.model_tester		,     """d_model"""		,     __a							)
												__lowercase      :							Optional[int]				=     getattr(self.model_tester		,     """num_attention_heads"""		,     __a							)
												__lowercase      :							Any				=     d_model // num_attention_heads

												for model_class in self.all_model_classes:
																			__lowercase      :							Dict				=     True
																			__lowercase      :							List[str]				=     False
																			__lowercase      :							Optional[int]				=     True
																			__lowercase      :							str				=     model_class(__a							)
																			model.to(__a							)
																			model.eval()
																			with torch.no_grad():
																										__lowercase      :							int				=     model(**self._prepare_for_class(__a		,     __a							)							)
																			__lowercase      :							Any				=     outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions
																			self.assertEqual(len(__a							)		,     self.model_tester.num_hidden_layers							)

																			# check that output_attentions also work using config
																			del inputs_dict["output_attentions"]
																			__lowercase      :							Optional[int]				=     True
																			__lowercase      :							List[str]				=     model_class(__a							)
																			model.to(__a							)
																			model.eval()
																			with torch.no_grad():
																										__lowercase      :							Union[str, Any]				=     model(**self._prepare_for_class(__a		,     __a							)							)
																			__lowercase      :							Dict				=     outputs.encoder_attentions
																			self.assertEqual(len(__a							)		,     self.model_tester.num_hidden_layers							)

																			self.assertListEqual(
																			    list(attentions[0].shape[-3:]							)		,     [self.model_tester.num_attention_heads, encoder_seq_length, dim]		,     )
																			__lowercase      :							Tuple				=     len(__a							)

																			__lowercase      :							str				=     7

																			if "last_hidden_state" in outputs:
																										correct_outlen += 1

																			if "trend" in outputs:
																										correct_outlen += 1

																			if "past_key_values" in outputs:
																										correct_outlen += 1  # past_key_values have been returned

																			if "loss" in outputs:
																										correct_outlen += 1

																			if "params" in outputs:
																										correct_outlen += 1

																			self.assertEqual(__a		,     __a							)

																			# decoder attentions
																			__lowercase      :							List[Any]				=     outputs.decoder_attentions
																			self.assertIsInstance(__a		,     (list, tuple)							)
																			self.assertEqual(len(__a							)		,     self.model_tester.num_hidden_layers							)
																			self.assertListEqual(
																			    list(decoder_attentions[0].shape[-3:]							)		,     [self.model_tester.num_attention_heads, decoder_seq_length, dim]		,     )

																			# cross attentions
																			__lowercase      :							Optional[int]				=     outputs.cross_attentions
																			self.assertIsInstance(__a		,     (list, tuple)							)
																			self.assertEqual(len(__a							)		,     self.model_tester.num_hidden_layers							)
																			self.assertListEqual(
																			    list(cross_attentions[0].shape[-3:]							)		,     [self.model_tester.num_attention_heads, decoder_seq_length, dim]		,     )

												# Check attention is always last and order is fine
												__lowercase      :							Tuple				=     True
												__lowercase      :							Union[str, Any]				=     True
												__lowercase      :							Tuple				=     model_class(__a							)
												model.to(__a							)
												model.eval()
												with torch.no_grad():
																			__lowercase      :							Any				=     model(**self._prepare_for_class(__a		,     __a							)							)

												self.assertEqual(out_len + 2		,     len(__a							)							)

												__lowercase      :							Optional[Any]				=     outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions

												self.assertEqual(len(__a							)		,     self.model_tester.num_hidden_layers							)
												self.assertListEqual(
												    list(self_attentions[0].shape[-3:]							)		,     [self.model_tester.num_attention_heads, encoder_seq_length, dim]		,     )



					@is_flaky()
					def       lowerCAmelCase				(  self				:	int							)			->  Any:


												"""simple docstring"""

												super().test_retain_grad_hidden_states_attentions()







def       snake_case_		(     lowerCAmelCase_       :						Optional[int]="train-batch.pt"      ):
							__lowercase      :							Dict				=     hf_hub_download(repo_id="""hf-internal-testing/tourism-monthly-batch"""       ,       filename=lowerCAmelCase_       ,       repo_type="""dataset"""      )
							__lowercase      :							Optional[int]				=     torch.load(lowerCAmelCase_       ,       map_location=lowerCAmelCase_      )
							return batch



@require_torch
@slow
class 		lowerCAmelCase     ( unittest.TestCase			):

					'''simple docstring'''

					def       lowerCAmelCase				(  self				:	Dict							)			->  int:


												"""simple docstring"""

												__lowercase      :							List[str]				=     AutoformerModel.from_pretrained("""huggingface/autoformer-tourism-monthly"""							).to(__a							)
												__lowercase      :							List[Any]				=     prepare_batch()

												with torch.no_grad():
																			__lowercase      :							Tuple				=     model(
																			    past_values=batch["""past_values"""]		,     past_time_features=batch["""past_time_features"""]		,     past_observed_mask=batch["""past_observed_mask"""]		,     static_categorical_features=batch["""static_categorical_features"""]		,     future_values=batch["""future_values"""]		,     future_time_features=batch["""future_time_features"""]		,     )[0]

												__lowercase      :							List[str]				=     torch.Size(
												    (64, model.config.prediction_length + model.config.label_length, model.config.feature_size)							)
												self.assertEqual(output.shape		,     __a							)

												__lowercase      :							Optional[int]				=     torch.tensor(
												    [[0.3593, -1.3398, 0.6330], [0.2279, 1.5396, -0.1792], [0.0450, 1.3225, -0.2335]]		,     device=__a							)
												self.assertTrue(torch.allclose(output[0, :3, :3]		,     __a		,     atol=__a							)							)



					def       lowerCAmelCase				(  self				:	str							)			->  str:


												"""simple docstring"""

												__lowercase      :							int				=     AutoformerForPrediction.from_pretrained("""huggingface/autoformer-tourism-monthly"""							).to(__a							)
												__lowercase      :							List[str]				=     prepare_batch("""val-batch.pt"""							)
												with torch.no_grad():
																			__lowercase      :							Optional[Any]				=     model(
																			    past_values=batch["""past_values"""]		,     past_time_features=batch["""past_time_features"""]		,     past_observed_mask=batch["""past_observed_mask"""]		,     static_categorical_features=batch["""static_categorical_features"""]		,     ).encoder_last_hidden_state
												__lowercase      :							List[str]				=     torch.Size((64, model.config.context_length, model.config.d_model)							)
												self.assertEqual(output.shape		,     __a							)

												__lowercase      :							Optional[int]				=     torch.tensor(
												    [[-0.0734, -0.9036, 0.8358], [4.7186, 2.4113, 1.9581], [1.7953, 2.3558, 1.2970]]		,     device=__a							)
												self.assertTrue(torch.allclose(output[0, :3, :3]		,     __a		,     atol=__a							)							)



					def       lowerCAmelCase				(  self				:	Dict							)			->  List[Any]:


												"""simple docstring"""

												__lowercase      :							Optional[Any]				=     AutoformerForPrediction.from_pretrained("""huggingface/autoformer-tourism-monthly"""							).to(__a							)
												__lowercase      :							Optional[int]				=     prepare_batch("""val-batch.pt"""							)
												with torch.no_grad():
																			__lowercase      :							int				=     model.generate(
																			    static_categorical_features=batch["""static_categorical_features"""]		,     past_time_features=batch["""past_time_features"""]		,     past_values=batch["""past_values"""]		,     future_time_features=batch["""future_time_features"""]		,     past_observed_mask=batch["""past_observed_mask"""]		,     )
												__lowercase      :							int				=     torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length)							)
												self.assertEqual(outputs.sequences.shape		,     __a							)

												__lowercase      :							Optional[Any]				=     torch.tensor([3130.6763, 4056.5293, 7053.0786]		,     device=__a							)
												__lowercase      :							Dict				=     outputs.sequences.mean(dim=1							)
												self.assertTrue(torch.allclose(mean_prediction[0, -3:]		,     __a		,     rtol=1E-1							)							)