

import logging
import math
from functools import partial
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union

import torch

from .tensor_utils import tensor_tree_map, tree_map


def     __SCREAMING_SNAKE_CASE   (SCREAMING_SNAKE_CASE__			):
						snake_case_  =      []
						if isinstance(SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__			):
												for v in tree.values():
																		shapes.extend(_fetch_dims(SCREAMING_SNAKE_CASE__			)			)
						elif isinstance(SCREAMING_SNAKE_CASE__    ,						(list, tuple)			):
												for t in tree:
																		shapes.extend(_fetch_dims(SCREAMING_SNAKE_CASE__			)			)
						elif isinstance(SCREAMING_SNAKE_CASE__    ,						torch.Tensor			):
												shapes.append(tree.shape			)
						else:
												raise ValueError('''Not supported'''			)

						return shapes


@torch.jit.ignore
def     __SCREAMING_SNAKE_CASE   (SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__			):
						snake_case_  =      []
						for d in reversed(SCREAMING_SNAKE_CASE__			):
												idx.append(flat_idx % d			)
												snake_case_  =      flat_idx // d

						return tuple(reversed(SCREAMING_SNAKE_CASE__			)			)


@torch.jit.ignore
def     __SCREAMING_SNAKE_CASE   (SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__ = None    ,						SCREAMING_SNAKE_CASE__ = None    ,						):

						# start_edges and end_edges both indicate whether, starting from any given
						# dimension, the start/end index is at the top/bottom edge of the
						# corresponding tensor, modeled as a tree
						def reduce_edge_list(SCREAMING_SNAKE_CASE__			) -> None:
												snake_case_  =      True
												for i in range(len(SCREAMING_SNAKE_CASE__			)			):
																		snake_case_  =      -1 * (i + 1)
																		l[reversed_idx] &= tally
																		snake_case_  =      l[reversed_idx]

						if start_edges is None:
												snake_case_  =      [s == 0 for s in start]
												reduce_edge_list(SCREAMING_SNAKE_CASE__			)
						if end_edges is None:
												snake_case_  =      [e == (d - 1) for e, d in zip(SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__			)]
												reduce_edge_list(SCREAMING_SNAKE_CASE__			)

						# Base cases. Either start/end are empty and we're done, or the final,
						# one-dimensional tensor can be simply sliced
						if len(SCREAMING_SNAKE_CASE__			) == 0:
												return [()]
						elif len(SCREAMING_SNAKE_CASE__			) == 1:
												return [(slice(start[0]    ,						end[0] + 1			),)]

						snake_case_  =      []
						snake_case_  =      []

						# Dimensions common to start and end can be selected directly
						for s, e in zip(SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__			):
												if s == e:
																		path_list.append(slice(SCREAMING_SNAKE_CASE__    ,						s + 1			)			)
												else:
																		break

						snake_case_  =      tuple(SCREAMING_SNAKE_CASE__			)
						snake_case_  =      len(SCREAMING_SNAKE_CASE__			)

						# start == end, and we're done
						if divergence_idx == len(SCREAMING_SNAKE_CASE__			):
												return [path]

						def upper() -> Tuple[Tuple[slice, ...], ...]:
												assert start_edges is not None
												assert end_edges is not None

												snake_case_  =      start[divergence_idx]
												return tuple(
												    path + (slice(SCREAMING_SNAKE_CASE__    ,						sdi + 1			),) + s
												    for s in _get_minimal_slice_set(
												        start[divergence_idx + 1 :]    ,						[d - 1 for d in dims[divergence_idx + 1 :]]    ,						dims[divergence_idx + 1 :]    ,						start_edges=start_edges[divergence_idx + 1 :]    ,						end_edges=[True for _ in end_edges[divergence_idx + 1 :]]    ,						)			)

						def lower() -> Tuple[Tuple[slice, ...], ...]:
												assert start_edges is not None
												assert end_edges is not None

												snake_case_  =      end[divergence_idx]
												return tuple(
												    path + (slice(SCREAMING_SNAKE_CASE__    ,						edi + 1			),) + s
												    for s in _get_minimal_slice_set(
												        [0 for _ in start[divergence_idx + 1 :]]    ,						end[divergence_idx + 1 :]    ,						dims[divergence_idx + 1 :]    ,						start_edges=[True for _ in start_edges[divergence_idx + 1 :]]    ,						end_edges=end_edges[divergence_idx + 1 :]    ,						)			)

						# If both start and end are at the edges of the subtree rooted at
						# divergence_idx, we can just select the whole subtree at once
						if start_edges[divergence_idx] and end_edges[divergence_idx]:
												slices.append(path + (slice(start[divergence_idx]    ,						end[divergence_idx] + 1			),)			)
						# If just start is at the edge, we can grab almost all of the subtree,
						# treating only the ragged bottom edge as an edge case
						elif start_edges[divergence_idx]:
												slices.append(path + (slice(start[divergence_idx]    ,						end[divergence_idx]			),)			)
												slices.extend(lower()			)
						# Analogous to the previous case, but the top is ragged this time
						elif end_edges[divergence_idx]:
												slices.extend(upper()			)
												slices.append(path + (slice(start[divergence_idx] + 1    ,						end[divergence_idx] + 1			),)			)
						# If both sides of the range are ragged, we need to handle both sides
						# separately. If there's contiguous meat in between them, we can index it
						# in one big chunk
						else:
												slices.extend(upper()			)
												snake_case_  =      end[divergence_idx] - start[divergence_idx]
												if middle_ground > 1:
																		slices.append(path + (slice(start[divergence_idx] + 1    ,						end[divergence_idx]			),)			)
												slices.extend(lower()			)

						return slices


@torch.jit.ignore
def     __SCREAMING_SNAKE_CASE   (SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__			):
						snake_case_  =      t.shape[:no_batch_dims]
						snake_case_  =      list(_flat_idx_to_idx(SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__			)			)
						# _get_minimal_slice_set is inclusive
						snake_case_  =      list(_flat_idx_to_idx(flat_end - 1    ,						SCREAMING_SNAKE_CASE__			)			)

						# Get an ordered list of slices to perform
						snake_case_  =      _get_minimal_slice_set(
						    SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						)

						snake_case_  =      [t[s] for s in slices]

						return torch.cat([s.view((-1,) + t.shape[no_batch_dims:]			) for s in sliced_tensors]			)


def     __SCREAMING_SNAKE_CASE   (SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__ = False    ,						SCREAMING_SNAKE_CASE__ = None    ,						SCREAMING_SNAKE_CASE__ = False    ,						):
						if not (len(SCREAMING_SNAKE_CASE__			) > 0):
												raise ValueError('''Must provide at least one input'''			)

						snake_case_  =      [shape[:no_batch_dims] for shape in _fetch_dims(SCREAMING_SNAKE_CASE__			)]
						snake_case_  =      tuple([max(SCREAMING_SNAKE_CASE__			) for s in zip(*SCREAMING_SNAKE_CASE__			)]			)

						def _prep_inputs(SCREAMING_SNAKE_CASE__			) -> torch.Tensor:
												if not low_mem:
																		if not sum(t.shape[:no_batch_dims]			) == no_batch_dims:
																								snake_case_  =      t.expand(orig_batch_dims + t.shape[no_batch_dims:]			)
																		snake_case_  =      t.reshape(-1    ,						*t.shape[no_batch_dims:]			)
												else:
																		snake_case_  =      t.expand(orig_batch_dims + t.shape[no_batch_dims:]			)
												return t

						snake_case_  =      tensor_tree_map(_prep_inputs    ,						SCREAMING_SNAKE_CASE__			)
						snake_case_  =      None
						if _out is not None:
												snake_case_  =      tensor_tree_map(lambda SCREAMING_SNAKE_CASE__			: t.view([-1] + list(t.shape[no_batch_dims:]			)			)    ,						_out			)

						snake_case_  =      1
						for d in orig_batch_dims:
												flat_batch_dim *= d

						snake_case_  =      flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0)

						def _select_chunk(SCREAMING_SNAKE_CASE__			) -> torch.Tensor:
												return t[i : i + chunk_size] if t.shape[0] != 1 else t

						snake_case_  =      0
						snake_case_  =      prepped_outputs
						for _ in range(SCREAMING_SNAKE_CASE__			):
												# Chunk the input
												if not low_mem:
																		snake_case_  =      _select_chunk
												else:
																		snake_case_  =      partial(
																		    _chunk_slice    ,						flat_start=SCREAMING_SNAKE_CASE__    ,						flat_end=min(SCREAMING_SNAKE_CASE__    ,						i + chunk_size			)    ,						no_batch_dims=len(SCREAMING_SNAKE_CASE__			)    ,						)

												snake_case_  =      tensor_tree_map(SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__			)

												# Run the layer on the chunk
												snake_case_  =      layer(**SCREAMING_SNAKE_CASE__			)

												# Allocate space for the output
												if out is None:
																		snake_case_  =      tensor_tree_map(lambda SCREAMING_SNAKE_CASE__			: t.new_zeros((flat_batch_dim,) + t.shape[1:]			)    ,						SCREAMING_SNAKE_CASE__			)

												# Put the chunk in its pre-allocated space
												if isinstance(SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__			):

																		def assign(SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__			) -> None:
																								for k, v in da.items():
																														if isinstance(SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__			):
																																				assign(SCREAMING_SNAKE_CASE__    ,						da[k]			)
																														else:
																																				if _add_into_out:
																																										v[i : i + chunk_size] += da[k]
																																				else:
																																										snake_case_  =      da[k]

																		assign(SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__			)
												elif isinstance(SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__			):
																		for xa, xa in zip(SCREAMING_SNAKE_CASE__    ,						SCREAMING_SNAKE_CASE__			):
																								if _add_into_out:
																														xa[i : i + chunk_size] += xa
																								else:
																														snake_case_  =      xa
												elif isinstance(SCREAMING_SNAKE_CASE__    ,						torch.Tensor			):
																		if _add_into_out:
																								out[i : i + chunk_size] += output_chunk
																		else:
																								snake_case_  =      output_chunk
												else:
																		raise ValueError('''Not supported'''			)

												i += chunk_size

						snake_case_  =      tensor_tree_map(lambda SCREAMING_SNAKE_CASE__			: t.view(orig_batch_dims + t.shape[1:]			)    ,						SCREAMING_SNAKE_CASE__			)

						return out





class       snake_case_  :







			'''simple docstring'''

			def __init__(	self					:							Optional[Any]				,  _UpperCamelCase					:							int = 5_1_2				,  ) ->Dict:
									snake_case_  =      max_chunk_size
									snake_case_  =      None
									snake_case_  =      None







			def 							snake_case__(	self					:							Any				,  _UpperCamelCase					:							Callable				,  _UpperCamelCase					:							tuple				,  _UpperCamelCase					:							int				) ->int:
									logging.info('''Tuning chunk size...'''				)

									if min_chunk_size >= self.max_chunk_size:
															return min_chunk_size

									snake_case_  =      [2**l for l in range(int(math.log(self.max_chunk_size				,  2				)				) + 1				)]
									snake_case_  =      [c for c in candidates if c > min_chunk_size]
									snake_case_  =      [min_chunk_size] + candidates
									candidates[-1] += 4

									def test_chunk_size(_UpperCamelCase					:							int				) -> bool:
															try:
																					with torch.no_grad():
																											fn(*_UpperCamelCase				,  chunk_size=_UpperCamelCase				)
																					return True
															except RuntimeError:
																					return False

									snake_case_  =      0
									snake_case_  =      len(_UpperCamelCase				) - 1
									while i > min_viable_chunk_size_index:
															snake_case_  =      test_chunk_size(candidates[i]				)
															if not viable:
																					snake_case_  =      (min_viable_chunk_size_index + i) // 2
															else:
																					snake_case_  =      i
																					snake_case_  =      (i + len(_UpperCamelCase				) - 1) // 2

									return candidates[min_viable_chunk_size_index]







			def 							snake_case__(	self					:							Union[str, Any]				,  _UpperCamelCase					:							Iterable				,  _UpperCamelCase					:							Iterable				) ->bool:
									snake_case_  =      True
									for aa, aa in zip(_UpperCamelCase				,  _UpperCamelCase				):
															assert type(_UpperCamelCase				) == type(_UpperCamelCase				)
															if isinstance(_UpperCamelCase				,  (list, tuple)				):
																					consistent &= self._compare_arg_caches(_UpperCamelCase				,  _UpperCamelCase				)
															elif isinstance(_UpperCamelCase				,  _UpperCamelCase				):
																					snake_case_  =      [v for _, v in sorted(aa.items()				,  key=lambda _UpperCamelCase				: x[0]				)]
																					snake_case_  =      [v for _, v in sorted(aa.items()				,  key=lambda _UpperCamelCase				: x[0]				)]
																					consistent &= self._compare_arg_caches(_UpperCamelCase				,  _UpperCamelCase				)
															else:
																					consistent &= aa == aa

									return consistent







			def 							snake_case__(	self					:							str				,  _UpperCamelCase					:							Callable				,  _UpperCamelCase					:							tuple				,  _UpperCamelCase					:							int				,  ) ->int:
									snake_case_  =      True
									snake_case_  =      tree_map(lambda _UpperCamelCase				: a.shape if isinstance(_UpperCamelCase				,  torch.Tensor				) else a				,  _UpperCamelCase				,  _UpperCamelCase				)
									if self.cached_arg_data is not None:
															# If args have changed shape/value, we need to re-tune
															assert len(self.cached_arg_data				) == len(_UpperCamelCase				)
															snake_case_  =      self._compare_arg_caches(self.cached_arg_data				,  _UpperCamelCase				)
									else:
															# Otherwise, we can reuse the precomputed value
															snake_case_  =      False

									if not consistent:
															snake_case_  =      self._determine_favorable_chunk_size(
															    _UpperCamelCase				,  _UpperCamelCase				,  _UpperCamelCase				,  )
															snake_case_  =      arg_data

									assert self.cached_chunk_size is not None

									return self.cached_chunk_size


"""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						)						)




