

"""simple docstring"""





import importlib
import json
import os
from collections import OrderedDict
from typing import Dict, Optional, Union

# Build the list of all image processors
from ...configuration_utils import PretrainedConfig
from ...dynamic_module_utils import get_class_from_dynamic_module, resolve_trust_remote_code
from ...image_processing_utils import ImageProcessingMixin
from ...utils import CONFIG_NAME, IMAGE_PROCESSOR_NAME, get_file_from_repo, logging
from .auto_factory import _LazyAutoMapping
from .configuration_auto import (
    CONFIG_MAPPING_NAMES,
    AutoConfig,
    model_type_to_module_name,
    replace_list_option_in_docstrings,
)


__UpperCamelCase    : Optional[int]				 =						logging.get_logger(__name__)

__UpperCamelCase    : List[Any]				 =						OrderedDict(
    [
        ('''align''', '''EfficientNetImageProcessor'''),
        ('''beit''', '''BeitImageProcessor'''),
        ('''bit''', '''BitImageProcessor'''),
        ('''blip''', '''BlipImageProcessor'''),
        ('''blip-2''', '''BlipImageProcessor'''),
        ('''bridgetower''', '''BridgeTowerImageProcessor'''),
        ('''chinese_clip''', '''ChineseCLIPImageProcessor'''),
        ('''clip''', '''CLIPImageProcessor'''),
        ('''clipseg''', '''ViTImageProcessor'''),
        ('''conditional_detr''', '''ConditionalDetrImageProcessor'''),
        ('''convnext''', '''ConvNextImageProcessor'''),
        ('''convnextv2''', '''ConvNextImageProcessor'''),
        ('''cvt''', '''ConvNextImageProcessor'''),
        ('''data2vec-vision''', '''BeitImageProcessor'''),
        ('''deformable_detr''', '''DeformableDetrImageProcessor'''),
        ('''deit''', '''DeiTImageProcessor'''),
        ('''deta''', '''DetaImageProcessor'''),
        ('''detr''', '''DetrImageProcessor'''),
        ('''dinat''', '''ViTImageProcessor'''),
        ('''donut-swin''', '''DonutImageProcessor'''),
        ('''dpt''', '''DPTImageProcessor'''),
        ('''efficientformer''', '''EfficientFormerImageProcessor'''),
        ('''efficientnet''', '''EfficientNetImageProcessor'''),
        ('''flava''', '''FlavaImageProcessor'''),
        ('''focalnet''', '''BitImageProcessor'''),
        ('''git''', '''CLIPImageProcessor'''),
        ('''glpn''', '''GLPNImageProcessor'''),
        ('''groupvit''', '''CLIPImageProcessor'''),
        ('''imagegpt''', '''ImageGPTImageProcessor'''),
        ('''instructblip''', '''BlipImageProcessor'''),
        ('''layoutlmv2''', '''LayoutLMv2ImageProcessor'''),
        ('''layoutlmv3''', '''LayoutLMv3ImageProcessor'''),
        ('''levit''', '''LevitImageProcessor'''),
        ('''mask2former''', '''Mask2FormerImageProcessor'''),
        ('''maskformer''', '''MaskFormerImageProcessor'''),
        ('''mgp-str''', '''ViTImageProcessor'''),
        ('''mobilenet_v1''', '''MobileNetV1ImageProcessor'''),
        ('''mobilenet_v2''', '''MobileNetV2ImageProcessor'''),
        ('''mobilevit''', '''MobileViTImageProcessor'''),
        ('''mobilevit''', '''MobileViTImageProcessor'''),
        ('''mobilevitv2''', '''MobileViTImageProcessor'''),
        ('''nat''', '''ViTImageProcessor'''),
        ('''oneformer''', '''OneFormerImageProcessor'''),
        ('''owlvit''', '''OwlViTImageProcessor'''),
        ('''perceiver''', '''PerceiverImageProcessor'''),
        ('''pix2struct''', '''Pix2StructImageProcessor'''),
        ('''poolformer''', '''PoolFormerImageProcessor'''),
        ('''regnet''', '''ConvNextImageProcessor'''),
        ('''resnet''', '''ConvNextImageProcessor'''),
        ('''sam''', '''SamImageProcessor'''),
        ('''segformer''', '''SegformerImageProcessor'''),
        ('''swiftformer''', '''ViTImageProcessor'''),
        ('''swin''', '''ViTImageProcessor'''),
        ('''swin2sr''', '''Swin2SRImageProcessor'''),
        ('''swinv2''', '''ViTImageProcessor'''),
        ('''table-transformer''', '''DetrImageProcessor'''),
        ('''timesformer''', '''VideoMAEImageProcessor'''),
        ('''tvlt''', '''TvltImageProcessor'''),
        ('''upernet''', '''SegformerImageProcessor'''),
        ('''van''', '''ConvNextImageProcessor'''),
        ('''videomae''', '''VideoMAEImageProcessor'''),
        ('''vilt''', '''ViltImageProcessor'''),
        ('''vit''', '''ViTImageProcessor'''),
        ('''vit_hybrid''', '''ViTHybridImageProcessor'''),
        ('''vit_mae''', '''ViTImageProcessor'''),
        ('''vit_msn''', '''ViTImageProcessor'''),
        ('''xclip''', '''CLIPImageProcessor'''),
        ('''yolos''', '''YolosImageProcessor'''),
    ]
)

__UpperCamelCase    : Any				 =						_LazyAutoMapping(CONFIG_MAPPING_NAMES, IMAGE_PROCESSOR_MAPPING_NAMES)

def     __SCREAMING_SNAKE_CASE    ( A_					):
	for module_name, extractors in IMAGE_PROCESSOR_MAPPING_NAMES.items():
		if class_name in extractors:
			lowerCAmelCase__      :		str    							=      model_type_to_module_name(A_					)

			lowerCAmelCase__      :		Tuple    							=      importlib.import_module(f'.{module_name}'		,	'''transformers.models'''					)
			try:
				return getattr(A_		,	A_					)
			except AttributeError:
				continue

	for _, extractor in IMAGE_PROCESSOR_MAPPING._extra_content.items():
		if getattr(A_		,	'''__name__'''		,	A_					) == class_name:
			return extractor

    # We did not fine the class, but maybe it's because a dep is missing. In that case, the class will be in the main
    # init and we return the proper dummy to get an appropriate error message.
	lowerCAmelCase__      :		Any    							=      importlib.import_module('''transformers'''					)
	if hasattr(A_		,	A_					):
		return getattr(A_		,	A_					)

	return None

def     __SCREAMING_SNAKE_CASE    ( A_		,	A_ = None		,	A_ = False		,	A_ = False		,	A_ = None		,	A_ = None		,	A_ = None		,	A_ = False		,	**A_		,	):
	lowerCAmelCase__      :		str    							=      get_file_from_repo(
	    A_		,	A_		,	cache_dir=A_		,	force_download=A_		,	resume_download=A_		,	proxies=A_		,	use_auth_token=A_		,	revision=A_		,	local_files_only=A_		,	)
	if resolved_config_file is None:
		logger.info(
		    '''Could not locate the image processor configuration file, will try to use the model config instead.'''					)
		return {}

	with open(A_		,	encoding='''utf-8'''					) as reader:
		return json.load(A_					)







class 							SCREAMING_SNAKE_CASE   :






					"""simple docstring"""



					def __init__(			self     :							Tuple						):
						raise EnvironmentError(
						    '''AutoImageProcessor is designed to be instantiated '''
						    '''using the `AutoImageProcessor.from_pretrained(pretrained_model_name_or_path)` method.'''						)







					@classmethod
					@replace_list_option_in_docstrings(lowercase_						)
					def 			__lowerCAmelCase					(			cls     :							int  ,lowercase_     :							List[str]  ,**lowercase_     :							List[str]						):
						lowerCAmelCase__      :		Union[str, Any]    							=      kwargs.pop('''config'''  ,lowercase_						)
						lowerCAmelCase__      :		List[Any]    							=      kwargs.pop('''trust_remote_code'''  ,lowercase_						)
						lowerCAmelCase__      :		str    							=      True

						lowerCAmelCase__							,lowerCAmelCase__      :		List[Any]    							=      ImageProcessingMixin.get_image_processor_dict(lowercase_  ,**lowercase_						)
						lowerCAmelCase__      :		Union[str, Any]    							=      config_dict.get('''image_processor_type'''  ,lowercase_						)
						lowerCAmelCase__      :		Optional[int]    							=      None
						if "AutoImageProcessor" in config_dict.get('''auto_map'''  ,{}						):
							lowerCAmelCase__      :		Any    							=      config_dict['''auto_map''']['''AutoImageProcessor''']

						# If we still don't have the image processor class, check if we're loading from a previous feature extractor config
						# and if so, infer the image processor class from there.
						if image_processor_class is None and image_processor_auto_map is None:
							lowerCAmelCase__      :		Optional[int]    							=      config_dict.pop('''feature_extractor_type'''  ,lowercase_						)
							if feature_extractor_class is not None:
								logger.warning(
								    '''Could not find image processor class in the image processor config or the model config. Loading'''
								    ''' based on pattern matching with the model\'s feature extractor configuration.'''						)
								lowerCAmelCase__      :		List[Any]    							=      feature_extractor_class.replace('''FeatureExtractor'''  ,'''ImageProcessor'''						)
							if "AutoFeatureExtractor" in config_dict.get('''auto_map'''  ,{}						):
								lowerCAmelCase__      :		Optional[int]    							=      config_dict['''auto_map''']['''AutoFeatureExtractor''']
								lowerCAmelCase__      :		Tuple    							=      feature_extractor_auto_map.replace('''FeatureExtractor'''  ,'''ImageProcessor'''						)
								logger.warning(
								    '''Could not find image processor auto map in the image processor config or the model config.'''
								    ''' Loading based on pattern matching with the model\'s feature extractor configuration.'''						)

        # If we don't find the image processor class in the image processor config, let's try the model config.
						if image_processor_class is None and image_processor_auto_map is None:
							if not isinstance(lowercase_  ,lowercase_						):
								lowerCAmelCase__      :		int    							=      AutoConfig.from_pretrained(lowercase_  ,**lowercase_						)
							# It could be in `config.image_processor_type``
							lowerCAmelCase__      :		Dict    							=      getattr(lowercase_  ,'''image_processor_type'''  ,lowercase_						)
							if hasattr(lowercase_  ,'''auto_map'''						) and "AutoImageProcessor" in config.auto_map:
								lowerCAmelCase__      :		List[str]    							=      config.auto_map['''AutoImageProcessor''']

						if image_processor_class is not None:
							lowerCAmelCase__      :		Optional[Any]    							=      image_processor_class_from_name(lowercase_						)

						lowerCAmelCase__      :		Dict    							=      image_processor_auto_map is not None
						lowerCAmelCase__      :		Tuple    							=      image_processor_class is not None or type(lowercase_						) in IMAGE_PROCESSOR_MAPPING
						lowerCAmelCase__      :		Optional[int]    							=      resolve_trust_remote_code(
						    lowercase_  ,lowercase_  ,lowercase_  ,lowercase_						)

						if has_remote_code and trust_remote_code:
							lowerCAmelCase__      :		List[str]    							=      get_class_from_dynamic_module(
							    lowercase_  ,lowercase_  ,**lowercase_						)
							lowerCAmelCase__      :		Union[str, Any]    							=      kwargs.pop('''code_revision'''  ,lowercase_						)
							if os.path.isdir(lowercase_						):
								image_processor_class.register_for_auto_class()
							return image_processor_class.from_dict(lowercase_  ,**lowercase_						)
						elif image_processor_class is not None:
							return image_processor_class.from_dict(lowercase_  ,**lowercase_						)
						# Last try: we use the IMAGE_PROCESSOR_MAPPING.
						elif type(lowercase_						) in IMAGE_PROCESSOR_MAPPING:
							lowerCAmelCase__      :		Dict    							=      IMAGE_PROCESSOR_MAPPING[type(lowercase_						)]
							return image_processor_class.from_dict(lowercase_  ,**lowercase_						)

						raise ValueError(
						    F'Unrecognized image processor in {pretrained_model_name_or_path}. Should have a '
						    F'`image_processor_type` key in its {IMAGE_PROCESSOR_NAME} of {CONFIG_NAME}, or one of the following '
						    F'`model_type` keys in its {CONFIG_NAME}: {", ".join(c for c in IMAGE_PROCESSOR_MAPPING_NAMES.keys()						)}'						)







					@staticmethod
					def 			__lowerCAmelCase					(			lowercase_     :							str  ,lowercase_     :							Dict						):
						IMAGE_PROCESSOR_MAPPING.register(lowercase_  ,lowercase_						)







"""simple docstring"""





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


__UpperCamelCase    : Optional[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 							SCREAMING_SNAKE_CASE   :






					"""simple docstring"""



					def __init__(			self     :							str  ,lowercase_     :							Optional[Any]  ,lowercase_     :							Optional[Any]=1_6  ,lowercase_     :							int=1_3  ,lowercase_     :							Optional[int]=7  ,lowercase_     :							int=1_4  ,lowercase_     :							str=1_0  ,lowercase_     :							List[Any]=1_9  ,lowercase_     :							Any=5  ,lowercase_     :							Any=4  ,lowercase_     :							List[str]=True  ,lowercase_     :							Union[str, Any]=1_6  ,lowercase_     :							Tuple=2  ,lowercase_     :							str=4  ,lowercase_     :							Tuple=4  ,lowercase_     :							int="gelu"  ,lowercase_     :							Any=0.1  ,lowercase_     :							int=0.1  ,lowercase_     :							Optional[int]=[1, 2, 3, 4, 5]  ,lowercase_     :							List[Any]=2_5  ,lowercase_     :							Union[str, Any]=5  ,):
						lowerCAmelCase__      :		List[str]    							=      d_model
						lowerCAmelCase__      :		Optional[Any]    							=      parent
						lowerCAmelCase__      :		Dict    							=      batch_size
						lowerCAmelCase__      :		Any    							=      prediction_length
						lowerCAmelCase__      :		str    							=      context_length
						lowerCAmelCase__      :		int    							=      cardinality
						lowerCAmelCase__      :		Dict    							=      num_time_features
						lowerCAmelCase__      :		str    							=      lags_sequence
						lowerCAmelCase__      :		int    							=      embedding_dimension
						lowerCAmelCase__      :		Dict    							=      is_training
						lowerCAmelCase__      :		Optional[Any]    							=      hidden_size
						lowerCAmelCase__      :		Optional[int]    							=      num_hidden_layers
						lowerCAmelCase__      :		List[str]    							=      num_attention_heads
						lowerCAmelCase__      :		int    							=      intermediate_size
						lowerCAmelCase__      :		List[str]    							=      hidden_act
						lowerCAmelCase__      :		Dict    							=      hidden_dropout_prob
						lowerCAmelCase__      :		Optional[int]    							=      attention_probs_dropout_prob

						lowerCAmelCase__      :		Tuple    							=      context_length
						lowerCAmelCase__      :		Optional[Any]    							=      prediction_length + label_length
						lowerCAmelCase__      :		Union[str, Any]    							=      label_length

						lowerCAmelCase__      :		Optional[int]    							=      moving_average
						lowerCAmelCase__      :		Dict    							=      autocorrelation_factor







					def 			__lowerCAmelCase					(			self     :							Tuple						):
						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     :							Union[str, Any]  ,lowercase_     :							str						):
						lowerCAmelCase__      :		str    							=      config.context_length + max(config.lags_sequence						)

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

						# decoder inputs
						lowerCAmelCase__      :		List[str]    							=      floats_tensor([self.batch_size, config.prediction_length, config.num_time_features]						)
						lowerCAmelCase__      :		Tuple    							=      floats_tensor([self.batch_size, config.prediction_length]						)

						lowerCAmelCase__      :		Optional[int]    							=      {
						    '''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     :							Optional[Any]						):
						lowerCAmelCase__      :		Dict    							=      self.get_config()
						lowerCAmelCase__      :		Dict    							=      self.prepare_autoformer_inputs_dict(lowercase_						)
						return config, inputs_dict







					def 			__lowerCAmelCase					(			self     :							List[Any]						):
						lowerCAmelCase__							,lowerCAmelCase__      :		List[Any]    							=      self.prepare_config_and_inputs()
						return config, inputs_dict







					def 			__lowerCAmelCase					(			self     :							Dict  ,lowercase_     :							Optional[int]  ,lowercase_     :							Union[str, Any]						):
						lowerCAmelCase__      :		Any    							=      AutoformerModel(config=lowercase_						).to(lowercase_						).eval()
						lowerCAmelCase__      :		Tuple    							=      model(**lowercase_						)

						lowerCAmelCase__      :		Any    							=      outputs.encoder_last_hidden_state
						lowerCAmelCase__      :		str    							=      outputs.last_hidden_state

						with tempfile.TemporaryDirectory() as tmpdirname:
							lowerCAmelCase__      :		List[Any]    							=      model.get_encoder()
							encoder.save_pretrained(lowercase_						)
							lowerCAmelCase__      :		Union[str, Any]    							=      AutoformerEncoder.from_pretrained(lowercase_						).to(lowercase_						)

						lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__							,lowerCAmelCase__      :		str    							=      model.create_network_inputs(**lowercase_						)
						lowerCAmelCase__							,lowerCAmelCase__      :		Optional[int]    							=      model.decomposition_layer(transformer_inputs[:, : config.context_length, ...]						)

						lowerCAmelCase__      :		int    							=      torch.cat(
						    (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...])  ,dim=-1  ,)
						lowerCAmelCase__      :		Dict    							=      encoder(inputs_embeds=lowercase_						)[0]
						self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1E-3						)

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

						lowerCAmelCase__      :		List[Any]    							=      torch.cat(
						    (
						        torch.cat((seasonal_input[:, -config.label_length :, ...], zeros)  ,dim=1						),
						        feature[:, config.context_length - config.label_length :, ...],
						    )  ,dim=-1  ,)
						lowerCAmelCase__      :		Any    							=      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:
							lowerCAmelCase__      :		Optional[int]    							=      model.get_decoder()
							decoder.save_pretrained(lowercase_						)
							lowerCAmelCase__      :		Tuple    							=      AutoformerDecoder.from_pretrained(lowercase_						).to(lowercase_						)

						lowerCAmelCase__      :		Union[str, Any]    							=      decoder(
						    trend=lowercase_  ,inputs_embeds=lowercase_  ,encoder_hidden_states=lowercase_  ,)[0]

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







@require_torch
class 							SCREAMING_SNAKE_CASE   (						a_       ,				a_       ,				unittest.TestCase			):






					"""simple docstring"""



					lowercase__												=			(AutoformerModel, AutoformerForPrediction) if is_torch_available() else ()
					lowercase__												=			(AutoformerForPrediction,) if is_torch_available() else ()
					lowercase__												=			{"feature-extraction": AutoformerModel} if is_torch_available() else {}
					lowercase__												=			False
					lowercase__												=			False
					lowercase__												=			False
					lowercase__												=			False
					lowercase__												=			False
					lowercase__												=			False







					def 			__lowerCAmelCase					(			self     :							int						):
						lowerCAmelCase__      :		int    							=      AutoformerModelTester(self						)
						lowerCAmelCase__      :		Optional[int]    							=      ConfigTester(self  ,config_class=lowercase_  ,has_text_modality=lowercase_						)







					def 			__lowerCAmelCase					(			self     :							Optional[Any]						):
						self.config_tester.run_common_tests()







					def 			__lowerCAmelCase					(			self     :							str						):
						lowerCAmelCase__							,lowerCAmelCase__      :		Union[str, Any]    							=      self.model_tester.prepare_config_and_inputs()
						for model_class in self.all_model_classes:
							lowerCAmelCase__      :		Optional[Any]    							=      model_class(lowercase_						)

							with tempfile.TemporaryDirectory() as tmpdirname:
								model.save_pretrained(lowercase_						)
								lowerCAmelCase__							,lowerCAmelCase__      :		List[Any]    							=      model_class.from_pretrained(lowercase_  ,output_loading_info=lowercase_						)
							self.assertEqual(info['''missing_keys''']  ,[]						)







					def 			__lowerCAmelCase					(			self     :							List[Any]						):
						lowerCAmelCase__      :		Tuple    							=      self.model_tester.prepare_config_and_inputs_for_common()
						self.model_tester.check_encoder_decoder_model_standalone(*lowercase_						)







					@unittest.skip(reason='''Model has no tokens embeddings'''						)
					def 			__lowerCAmelCase					(			self     :							Optional[int]						):
						pass







					def 			__lowerCAmelCase					(			self     :							Optional[Any]						):
						lowerCAmelCase__      :		List[str]    							=      inspect.signature(getattr(lowercase_  ,'''forward'''						)						)
						# The main input is the name of the argument after `self`
						lowerCAmelCase__      :		Any    							=      list(model_signature.parameters.keys()						)[1]
						self.assertEqual(AutoformerModel.main_input_name  ,lowercase_						)







					def 			__lowerCAmelCase					(			self     :							Union[str, Any]						):
						lowerCAmelCase__							,lowerCAmelCase__      :		Optional[Any]    							=      self.model_tester.prepare_config_and_inputs_for_common()

						for model_class in self.all_model_classes:
							lowerCAmelCase__      :		int    							=      model_class(lowercase_						)
							lowerCAmelCase__      :		Optional[Any]    							=      inspect.signature(model.forward						)
							# signature.parameters is an OrderedDict => so arg_names order is deterministic
							lowerCAmelCase__      :		int    							=      [*signature.parameters.keys()]

							lowerCAmelCase__      :		Optional[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(lowercase_						)]  ,lowercase_						)







					def 			__lowerCAmelCase					(			self     :							List[Any]						):
						lowerCAmelCase__							,lowerCAmelCase__      :		str    							=      self.model_tester.prepare_config_and_inputs_for_common()
						lowerCAmelCase__      :		List[str]    							=      True

						lowerCAmelCase__      :		int    							=      getattr(self.model_tester  ,'''seq_length'''  ,lowercase_						)
						lowerCAmelCase__      :		Union[str, Any]    							=      getattr(self.model_tester  ,'''decoder_seq_length'''  ,lowercase_						)
						lowerCAmelCase__      :		Tuple    							=      getattr(self.model_tester  ,'''encoder_seq_length'''  ,lowercase_						)
						lowerCAmelCase__      :		List[Any]    							=      getattr(self.model_tester  ,'''d_model'''  ,lowercase_						)
						lowerCAmelCase__      :		Union[str, Any]    							=      getattr(self.model_tester  ,'''num_attention_heads'''  ,lowercase_						)
						lowerCAmelCase__      :		str    							=      d_model // num_attention_heads

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

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

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

							lowerCAmelCase__      :		List[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(lowercase_  ,lowercase_						)

							# decoder attentions
							lowerCAmelCase__      :		str    							=      outputs.decoder_attentions
							self.assertIsInstance(lowercase_  ,(list, tuple)						)
							self.assertEqual(len(lowercase_						)  ,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
							lowerCAmelCase__      :		Any    							=      outputs.cross_attentions
							self.assertIsInstance(lowercase_  ,(list, tuple)						)
							self.assertEqual(len(lowercase_						)  ,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
						lowerCAmelCase__      :		str    							=      True
						lowerCAmelCase__      :		Tuple    							=      True
						lowerCAmelCase__      :		Optional[Any]    							=      model_class(lowercase_						)
						model.to(lowercase_						)
						model.eval()
						with torch.no_grad():
							lowerCAmelCase__      :		Optional[Any]    							=      model(**self._prepare_for_class(lowercase_  ,lowercase_						)						)

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

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

						self.assertEqual(len(lowercase_						)  ,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     :							str						):
						super().test_retain_grad_hidden_states_attentions()

def     __SCREAMING_SNAKE_CASE    ( A_="train-batch.pt"					):
	lowerCAmelCase__      :		Any    							=      hf_hub_download(repo_id='''hf-internal-testing/tourism-monthly-batch'''		,	filename=A_		,	repo_type='''dataset'''					)
	lowerCAmelCase__      :		Union[str, Any]    							=      torch.load(A_		,	map_location=A_					)
	return batch







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






					"""simple docstring"""



					def 			__lowerCAmelCase					(			self     :							int						):
						lowerCAmelCase__      :		List[Any]    							=      AutoformerModel.from_pretrained('''huggingface/autoformer-tourism-monthly'''						).to(lowercase_						)
						lowerCAmelCase__      :		int    							=      prepare_batch()

						with torch.no_grad():
							lowerCAmelCase__      :		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''']  ,future_values=batch['''future_values''']  ,future_time_features=batch['''future_time_features''']  ,)[0]

						lowerCAmelCase__      :		Dict    							=      torch.Size(
						    (6_4, model.config.prediction_length + model.config.label_length, model.config.feature_size)						)
						self.assertEqual(output.shape  ,lowercase_						)

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







					def 			__lowerCAmelCase					(			self     :							Dict						):
						lowerCAmelCase__      :		List[Any]    							=      AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly'''						).to(lowercase_						)
						lowerCAmelCase__      :		Optional[int]    							=      prepare_batch('''val-batch.pt'''						)
						with torch.no_grad():
							lowerCAmelCase__      :		str    							=      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
						lowerCAmelCase__      :		Any    							=      torch.Size((6_4, model.config.context_length, model.config.d_model)						)
						self.assertEqual(output.shape  ,lowercase_						)

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







					def 			__lowerCAmelCase					(			self     :							List[str]						):
						lowerCAmelCase__      :		Union[str, Any]    							=      AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly'''						).to(lowercase_						)
						lowerCAmelCase__      :		Dict    							=      prepare_batch('''val-batch.pt'''						)
						with torch.no_grad():
							lowerCAmelCase__      :		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''']  ,)
						lowerCAmelCase__      :		List[Any]    							=      torch.Size((6_4, model.config.num_parallel_samples, model.config.prediction_length)						)
						self.assertEqual(outputs.sequences.shape  ,lowercase_						)

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




