





"""simple docstring"""


# HF Trainer benchmarking tool
#
# This tool can be used to run and compare multiple dimensions of the HF Trainers args.
#
# It then prints a report once in github format with all the information that needs to be shared
# with others and second time in a console-friendly format, so it's easier to use for tuning things up.
#
# The main idea is:
#
#     ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \
#     --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \
#     --target-metric-key train_samples_per_second
#
# The variations can be any command line argument that you want to compare and not just dtype as in
# the example.
#
# --variations allows you to compare variations in multiple dimensions.
#
# as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6
# times adding one of:
#
#    1. --tf32 0 --fp16 0
#    2. --tf32 0 --fp16 1
#    3. --tf32 0 --bf16 1
#    4. --tf32 1 --fp16 0
#    5. --tf32 1 --fp16 1
#    6. --tf32 1 --bf16 1
#
# and print the results. This is just a cartesian product - and more than 2 dimensions can be used.
#
# If you want to rely on defaults, this:
#    --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1'
# is identical to this:
#    --variations '--tf32 0|--tf32 1' '|--fp16|--bf16'
#
# the leading empty variation in the 2nd dimension is a valid variation.
#
# So here we get the following 6 variations:
#
#    1. --tf32 0
#    2. --tf32 0 --fp16
#    3. --tf32 0 --bf16
#    4. --tf32 1
#    5. --tf32 1 --fp16
#    6. --tf32 1 --bf16
#
# In this particular case we don't know what the default tf32 setting is as it's normally
# pytorch-version dependent). That's why it's best to do an explicit setting of each variation:
#    `--tf32 0|--tf32 1`
#
# Here is a full example of a train:
#
# CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \
# --base-cmd \
# ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \
# --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \
# --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \
# --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \
# --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \
# --source_prefix "translate English to Romanian: " --warmup_steps 50 \
# --max_train_samples 20000 --dataloader_num_workers 2 ' \
# --target-metric-key train_samples_per_second --repeat-times 1 --variations \
# '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \
# --repeat-times 1 --base-variation '--tf32 0'
#
# and here is a possible output:
#
#
# | Variation       |     Train |   Diff |   Train |
# |                 |   samples |      % |    loss |
# |                 |       per |        |         |
# |                 |    second |        |         |
# |:----------------|----------:|-------:|--------:|
# | --tf32 0        |    285.11 |      0 |    2.51 |
# | --tf32 1        |    342.09 |     20 |    2.51 |
# | --fp16 --tf32 0 |    423.49 |     49 |    2.51 |
# | --fp16 --tf32 1 |    423.13 |     48 |    2.51 |
# | --bf16 --tf32 0 |    416.80 |     46 |    2.52 |
# | --bf16 --tf32 1 |    415.87 |     46 |    2.52 |
#
#
# So you can quickly compare the different outcomes.
#
# Typically running each experiment once is enough, but if the environment is unstable you can
# re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results.
#
# By default it'll use the lowest result as the base line to use as 100% and then compare the rest to
# it as can be seen from the table above, but you can also specify which combination is the one to use as
# the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0'
#
# --target-metric-key is there to tell the program which metrics to compare - the different metric keys are
# inside output_dir/all_results.json. e.g., to measure eval performance instead of train use:
#    --target-metric-key eval_samples_per_second
# but of course you will need to adjust the --base-cmd value in the example to perform evaluation as
# well (as currently it doesn't)
#

import argparse
import datetime
import io
import itertools
import json
import math
import os
import platform
import re
import shlex
import subprocess
import sys
from pathlib import Path
from statistics import fmean

import pandas as pd
import torch
from tqdm import tqdm

import transformers


__magic_name__       :					List[str]						=			float("""nan""")






class 							lowercase__			:

			"""simple docstring"""







			def __init__(      self						,   _A    ):






									'''simple docstring'''







									UpperCamelCase				:		Tuple				   =			sys.stdout
									UpperCamelCase				:		str				   =			open(_A						,   """a"""    )







			def __getattr__(      self						,   _A    ):






									'''simple docstring'''







									return getattr(self.stdout						,   _A    )







			def   _a      (      self						,   _A    ):






									'''simple docstring'''







									self.stdout.write(_A    )
									# strip tqdm codes
									self.file.write(re.sub(r"""^.*\r"""						,   """"""						,   _A						,   0						,   re.M    )    )


def      UpperCamelCase							(SCREAMING_SNAKE_CASE=80							,     SCREAMING_SNAKE_CASE=False     ):
						UpperCamelCase				:		List[str]				   =			[]

						# deal with critical env vars
						UpperCamelCase				:		int				   =			["""CUDA_VISIBLE_DEVICES"""]
						for key in env_keys:
												UpperCamelCase				:		str				   =			os.environ.get(SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE     )
												if val is not None:
																		cmd.append(f"""{key}={val}"""     )

    # python executable (not always needed if the script is executable)
						UpperCamelCase				:		Union[str, Any]				   =			sys.executable if full_python_path else sys.executable.split("""/"""     )[-1]
						cmd.append(SCREAMING_SNAKE_CASE     )

						# now the normal args
						cmd += list(map(shlex.quote							,     sys.argv     )     )

						# split up into up to MAX_WIDTH lines with shell multi-line escapes
						UpperCamelCase				:		List[Any]				   =			[]
						UpperCamelCase				:		Dict				   =			""""""
						while len(SCREAMING_SNAKE_CASE     ) > 0:
												current_line += f"""{cmd.pop(0     )} """
												if len(SCREAMING_SNAKE_CASE     ) == 0 or len(SCREAMING_SNAKE_CASE     ) + len(cmd[0]     ) + 1 > max_width - 1:
																		lines.append(SCREAMING_SNAKE_CASE     )
																		UpperCamelCase				:		List[Any]				   =			""""""
						return "\\\n".join(SCREAMING_SNAKE_CASE     )

def      UpperCamelCase							(SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE     ):
						# unwrap multi-line input
						UpperCamelCase				:		int				   =			re.sub(r"""[\\\n]+"""							,     """ """							,     args.base_cmd     )

						# remove --output_dir if any and set our own
						UpperCamelCase				:		Union[str, Any]				   =			re.sub("""--output_dir\s+[^\s]+"""							,     """"""							,     args.base_cmd     )
						args.base_cmd += f""" --output_dir {output_dir}"""

						# ensure we have --overwrite_output_dir
						UpperCamelCase				:		Optional[Any]				   =			re.sub("""--overwrite_output_dir\s+"""							,     """"""							,     args.base_cmd     )
						args.base_cmd += " --overwrite_output_dir"

						return [sys.executable] + shlex.split(args.base_cmd     )

def      UpperCamelCase							(SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE     ):
						# Enable to debug everything but the run itself, to do it fast and see the progress.
						# This is useful for debugging the output formatting quickly - we can remove it later once
						# everybody is happy with the output
						if 0:
												import random
												from time import sleep

												sleep(0     )
												return dict(
												    {k: random.uniform(0							,     100     ) for k in metric_keys}							,     **{target_metric_key: random.choice([nan, 10.31, 1_00.2, 55.66_66, 2_22.22_22_22_22]     )}							,     )

						UpperCamelCase				:		Tuple				   =			subprocess.run(SCREAMING_SNAKE_CASE							,     capture_output=SCREAMING_SNAKE_CASE							,     text=SCREAMING_SNAKE_CASE     )

						if verbose:
												print("""STDOUT"""							,     result.stdout     )
												print("""STDERR"""							,     result.stderr     )

						# save the streams
						UpperCamelCase				:		List[Any]				   =			variation.replace(""" """							,     """-"""     )
						with open(Path(SCREAMING_SNAKE_CASE     ) / f"""log.{prefix}.stdout.txt"""							,     """w"""     ) as f:
												f.write(result.stdout     )
						with open(Path(SCREAMING_SNAKE_CASE     ) / f"""log.{prefix}.stderr.txt"""							,     """w"""     ) as f:
												f.write(result.stderr     )

						if result.returncode != 0:
												if verbose:
																		print("""failed"""     )
												return {target_metric_key: nan}

						with io.open(f"""{output_dir}/all_results.json"""							,     """r"""							,     encoding="""utf-8"""     ) as f:
												UpperCamelCase				:		Optional[int]				   =			json.load(SCREAMING_SNAKE_CASE     )

						# filter out just the keys we want
						return {k: v for k, v in metrics.items() if k in metric_keys}

def      UpperCamelCase							(SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     ):
						UpperCamelCase				:		Tuple				   =			[]
						UpperCamelCase				:		List[Any]				   =			[]
						UpperCamelCase				:		Tuple				   =			f"""{id}: {variation:<{longest_variation_len}}"""
						UpperCamelCase				:		List[str]				   =			f"""{preamble}: """
						UpperCamelCase				:		List[Any]				   =			set(report_metric_keys + [target_metric_key]     )
						for i in tqdm(range(SCREAMING_SNAKE_CASE     )							,     desc=SCREAMING_SNAKE_CASE							,     leave=SCREAMING_SNAKE_CASE     ):
												UpperCamelCase				:		List[str]				   =			process_run_single(
												    SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE     )
												UpperCamelCase				:		Optional[int]				   =			single_run_metrics[target_metric_key]
												if not math.isnan(SCREAMING_SNAKE_CASE     ):
																		metrics.append(SCREAMING_SNAKE_CASE     )
																		results.append(SCREAMING_SNAKE_CASE     )
																		outcome += "✓"
												else:
																		outcome += "✘"
						UpperCamelCase				:		Any				   =			f"""\33[2K\r{outcome}"""
						if len(SCREAMING_SNAKE_CASE     ) > 0:
												UpperCamelCase				:		Optional[int]				   =			{k: fmean([x[k] for x in metrics]     ) for k in metrics[0].keys()}
												UpperCamelCase				:		Any				   =			round(mean_metrics[target_metric_key]							,     2     )
												UpperCamelCase				:		Any				   =			f"""{outcome} {mean_target}"""
												if len(SCREAMING_SNAKE_CASE     ) > 1:
																		results_str += f""" {tuple(round(SCREAMING_SNAKE_CASE							,     2     ) for x in results     )}"""
												print(SCREAMING_SNAKE_CASE     )
												UpperCamelCase				:		Tuple				   =			variation
												return mean_metrics
						else:
												print(SCREAMING_SNAKE_CASE     )
												return {variation_key: variation, target_metric_key: nan}

def      UpperCamelCase							():
						UpperCamelCase				:		int				   =			torch.cuda.get_device_properties(torch.device("""cuda"""     )     )
						return f"""
Datetime    : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"     )}

Software:
transformers: {transformers.__version__}
torch       : {torch.__version__}
cuda        : {torch.version.cuda}
python      : {platform.python_version()}

Hardware:
{torch.cuda.device_count()} GPUs      : {properties.name}, {properties.total_memory/2**30:0.2f}GB
"""

def      UpperCamelCase							(SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE     ):
						UpperCamelCase				:		List[str]				   =			pd.DataFrame(SCREAMING_SNAKE_CASE     )
						UpperCamelCase				:		str				   =			"""variation"""
						UpperCamelCase				:		int				   =			"""diff_%"""

						UpperCamelCase				:		List[str]				   =			nan
						if base_variation is not None and len(df[df[variation_key] == base_variation]     ):
												# this may still return nan
												UpperCamelCase				:		Union[str, Any]				   =			df.loc[df[variation_key] == base_variation][target_metric_key].item()
						if math.isnan(SCREAMING_SNAKE_CASE     ):
												# as a fallback, use the minimal value as the sentinel
												UpperCamelCase				:		List[str]				   =			df.loc[df[target_metric_key] != nan][target_metric_key].min()

						# create diff column if possible
						if not math.isnan(SCREAMING_SNAKE_CASE     ):
												UpperCamelCase				:		str				   =			df.apply(
												    lambda SCREAMING_SNAKE_CASE     : round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value     )
												    if not math.isnan(r[target_metric_key]     )
												    else 0							,     axis="""columns"""							,     )

						# re-order columns
						UpperCamelCase				:		Tuple				   =			[variation_key, target_metric_key, diff_key, *report_metric_keys]
						UpperCamelCase				:		Dict				   =			df.reindex(SCREAMING_SNAKE_CASE							,     axis="""columns"""     )  # reorder cols

						# capitalize
						UpperCamelCase				:		Any				   =			df.rename(str.capitalize							,     axis="""columns"""     )

						# make the cols as narrow as possible
						UpperCamelCase				:		int				   =			df.rename(lambda SCREAMING_SNAKE_CASE     : c.replace("""_"""							,     """<br>"""     )							,     axis="""columns"""     )
						UpperCamelCase				:		Tuple				   =			df.rename(lambda SCREAMING_SNAKE_CASE     : c.replace("""_"""							,     """\n"""     )							,     axis="""columns"""     )

						UpperCamelCase				:		List[str]				   =			["""""", """Copy between the cut-here-lines and paste as is to github or a forum"""]
						report += ["----------8<-----------------8<--------"]
						report += ["*** Results:", df_github.to_markdown(index=SCREAMING_SNAKE_CASE							,     floatfmt=""".2f"""     )]
						report += ["```"]
						report += ["*** Setup:", get_versions()]
						report += ["*** The benchmark command line was:", get_original_command()]
						report += ["```"]
						report += ["----------8<-----------------8<--------"]
						report += ["*** Results (console):", df_console.to_markdown(index=SCREAMING_SNAKE_CASE							,     floatfmt=""".2f"""     )]

						print("""\n\n""".join(SCREAMING_SNAKE_CASE     )     )

def      UpperCamelCase							():
						UpperCamelCase				:		Tuple				   =			argparse.ArgumentParser()
						parser.add_argument(
						    """--base-cmd"""							,     default=SCREAMING_SNAKE_CASE							,     type=SCREAMING_SNAKE_CASE							,     required=SCREAMING_SNAKE_CASE							,     help="""Base cmd"""							,     )
						parser.add_argument(
						    """--variations"""							,     default=SCREAMING_SNAKE_CASE							,     type=SCREAMING_SNAKE_CASE							,     nargs="""+"""							,     required=SCREAMING_SNAKE_CASE							,     help="""Multi-dimensional variations, example: '|--fp16|--bf16' '|--tf32'"""							,     )
						parser.add_argument(
						    """--base-variation"""							,     default=SCREAMING_SNAKE_CASE							,     type=SCREAMING_SNAKE_CASE							,     help="""Baseline variation to compare to. if None the minimal target value will be used to compare against"""							,     )
						parser.add_argument(
						    """--target-metric-key"""							,     default=SCREAMING_SNAKE_CASE							,     type=SCREAMING_SNAKE_CASE							,     required=SCREAMING_SNAKE_CASE							,     help="""Target metric key in output_dir/all_results.json, e.g., train_samples_per_second"""							,     )
						parser.add_argument(
						    """--report-metric-keys"""							,     default=""""""							,     type=SCREAMING_SNAKE_CASE							,     help="""Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., 'train_loss train_samples"""							,     )
						parser.add_argument(
						    """--repeat-times"""							,     default=1							,     type=SCREAMING_SNAKE_CASE							,     help="""How many times to re-run each variation - an average will be reported"""							,     )
						parser.add_argument(
						    """--output_dir"""							,     default="""output_benchmark"""							,     type=SCREAMING_SNAKE_CASE							,     help="""The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked"""							,     )
						parser.add_argument(
						    """--verbose"""							,     default=SCREAMING_SNAKE_CASE							,     action="""store_true"""							,     help="""Whether to show the outputs of each run or just the benchmark progress"""							,     )
						UpperCamelCase				:		str				   =			parser.parse_args()

						UpperCamelCase				:		Union[str, Any]				   =			args.output_dir
						Path(SCREAMING_SNAKE_CASE     ).mkdir(exist_ok=SCREAMING_SNAKE_CASE     )
						UpperCamelCase				:		Dict				   =			get_base_command(SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE     )

						# split each dimension into its --foo variations
						UpperCamelCase				:		Union[str, Any]				   =			[list(map(str.strip							,     re.split(r"""\|"""							,     SCREAMING_SNAKE_CASE     )     )     ) for x in args.variations]
						# build a cartesian product of dimensions and convert those back into cmd-line arg strings,
						# while stripping white space for inputs that were empty
						UpperCamelCase				:		int				   =			list(map(str.strip							,     map(""" """.join							,     itertools.product(*SCREAMING_SNAKE_CASE     )     )     )     )
						UpperCamelCase				:		int				   =			max(len(SCREAMING_SNAKE_CASE     ) for x in variations     )

						# split wanted keys
						UpperCamelCase				:		Union[str, Any]				   =			args.report_metric_keys.split()

						# capture prints into a log file for convenience
						UpperCamelCase				:		List[str]				   =			f"""benchmark-report-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S"     )}.txt"""
						print(f"""\nNote: each run's output is also logged under {output_dir}/log.*.std*.txt"""     )
						print(f"""and this script's output is also piped into {report_fn}"""     )

						UpperCamelCase				:		Union[str, Any]				   =			Tee(SCREAMING_SNAKE_CASE     )

						print(f"""\n*** Running {len(SCREAMING_SNAKE_CASE     )} benchmarks:"""     )
						print(f"""Base command: {" ".join(SCREAMING_SNAKE_CASE     )}"""     )

						UpperCamelCase				:		Optional[Any]				   =			"""variation"""
						UpperCamelCase				:		Any				   =			[]
						for id, variation in enumerate(tqdm(SCREAMING_SNAKE_CASE							,     desc="""Total completion: """							,     leave=SCREAMING_SNAKE_CASE     )     ):
												UpperCamelCase				:		Optional[int]				   =			base_cmd + variation.split()
												results.append(
												    process_run(
												        id + 1							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     SCREAMING_SNAKE_CASE							,     args.target_metric_key							,     SCREAMING_SNAKE_CASE							,     args.repeat_times							,     SCREAMING_SNAKE_CASE							,     args.verbose							,     )     )

						process_results(SCREAMING_SNAKE_CASE							,     args.target_metric_key							,     SCREAMING_SNAKE_CASE							,     args.base_variation							,     SCREAMING_SNAKE_CASE     )


if __name__ == "__main__":
		main()










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


__magic_name__       :					int						=			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 							lowercase__			:

			"""simple docstring"""







			def __init__(      self						,   _A						,   _A=1_6						,   _A=1_3						,   _A=7						,   _A=1_4						,   _A=1_0						,   _A=1_9						,   _A=5						,   _A=4						,   _A=True						,   _A=1_6						,   _A=2						,   _A=4						,   _A=4						,   _A="gelu"						,   _A=0.1						,   _A=0.1						,   _A=[1, 2, 3, 4, 5]						,   _A=2_5						,   _A=5						,   ):






									'''simple docstring'''







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

									UpperCamelCase				:		Union[str, Any]				   =			context_length
									UpperCamelCase				:		str				   =			prediction_length + label_length
									UpperCamelCase				:		Dict				   =			label_length

									UpperCamelCase				:		Any				   =			moving_average
									UpperCamelCase				:		int				   =			autocorrelation_factor







			def   _a      (      self    ):






									'''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   _a      (      self						,   _A    ):






									'''simple docstring'''







									UpperCamelCase				:		List[str]				   =			config.context_length + max(config.lags_sequence    )

									UpperCamelCase				:		Any				   =			ids_tensor([self.batch_size, 1]						,   config.cardinality[0]    )
									UpperCamelCase				:		Any				   =			floats_tensor([self.batch_size, _past_length, config.num_time_features]    )
									UpperCamelCase				:		Union[str, Any]				   =			floats_tensor([self.batch_size, _past_length]    )
									UpperCamelCase				:		str				   =			floats_tensor([self.batch_size, _past_length]    ) > 0.5

									# decoder inputs
									UpperCamelCase				:		int				   =			floats_tensor([self.batch_size, config.prediction_length, config.num_time_features]    )
									UpperCamelCase				:		Optional[Any]				   =			floats_tensor([self.batch_size, config.prediction_length]    )

									UpperCamelCase				:		Dict				   =			{
									    """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   _a      (      self    ):






									'''simple docstring'''







									UpperCamelCase				:		List[Any]				   =			self.get_config()
									UpperCamelCase				:		int				   =			self.prepare_autoformer_inputs_dict(_A    )
									return config, inputs_dict







			def   _a      (      self    ):






									'''simple docstring'''







									UpperCamelCase   ,						UpperCamelCase				:		Optional[int]				   =			self.prepare_config_and_inputs()
									return config, inputs_dict







			def   _a      (      self						,   _A						,   _A    ):






									'''simple docstring'''







									UpperCamelCase				:		str				   =			AutoformerModel(config=_A    ).to(_A    ).eval()
									UpperCamelCase				:		List[str]				   =			model(**_A    )

									UpperCamelCase				:		Any				   =			outputs.encoder_last_hidden_state
									UpperCamelCase				:		List[Any]				   =			outputs.last_hidden_state

									with tempfile.TemporaryDirectory() as tmpdirname:
															UpperCamelCase				:		Optional[Any]				   =			model.get_encoder()
															encoder.save_pretrained(_A    )
															UpperCamelCase				:		Union[str, Any]				   =			AutoformerEncoder.from_pretrained(_A    ).to(_A    )

									UpperCamelCase   ,						UpperCamelCase   ,						UpperCamelCase   ,						UpperCamelCase   ,						UpperCamelCase				:		Dict				   =			model.create_network_inputs(**_A    )
									UpperCamelCase   ,						UpperCamelCase				:		Tuple				   =			model.decomposition_layer(transformer_inputs[:, : config.context_length, ...]    )

									UpperCamelCase				:		Dict				   =			torch.cat(
									    (transformer_inputs[:, : config.context_length, ...], feature[:, : config.context_length, ...])						,   dim=-1						,   )
									UpperCamelCase				:		str				   =			encoder(inputs_embeds=_A    )[0]
									self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3    )

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

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

									UpperCamelCase				:		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 							lowercase__			(   __SCREAMING_SNAKE_CASE					,     __SCREAMING_SNAKE_CASE					,     unittest.TestCase	):

			"""simple docstring"""
			__lowerCAmelCase     :				Tuple										=  (AutoformerModel, AutoformerForPrediction) if is_torch_available() else ()
			__lowerCAmelCase     :				str										=  (AutoformerForPrediction,) if is_torch_available() else ()
			__lowerCAmelCase     :				Dict										=  {"""feature-extraction""": AutoformerModel} if is_torch_available() else {}
			__lowerCAmelCase     :				List[Any]										=  False
			__lowerCAmelCase     :				Any										=  False
			__lowerCAmelCase     :				List[Any]										=  False
			__lowerCAmelCase     :				Optional[int]										=  False
			__lowerCAmelCase     :				Optional[Any]										=  False
			__lowerCAmelCase     :				Optional[int]										=  False







			def   _a      (      self    ):






									'''simple docstring'''







									UpperCamelCase				:		Optional[Any]				   =			AutoformerModelTester(self    )
									UpperCamelCase				:		int				   =			ConfigTester(self						,   config_class=_A						,   has_text_modality=_A    )







			def   _a      (      self    ):






									'''simple docstring'''







									self.config_tester.run_common_tests()







			def   _a      (      self    ):






									'''simple docstring'''







									UpperCamelCase   ,						UpperCamelCase				:		Tuple				   =			self.model_tester.prepare_config_and_inputs()
									for model_class in self.all_model_classes:
															UpperCamelCase				:		Optional[int]				   =			model_class(_A    )

															with tempfile.TemporaryDirectory() as tmpdirname:
																					model.save_pretrained(_A    )
																					UpperCamelCase   ,						UpperCamelCase				:		Optional[Any]				   =			model_class.from_pretrained(_A						,   output_loading_info=_A    )
															self.assertEqual(info["""missing_keys"""]						,   []    )







			def   _a      (      self    ):






									'''simple docstring'''







									UpperCamelCase				:		Dict				   =			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   _a      (      self    ):






									'''simple docstring'''







									pass







			def   _a      (      self    ):






									'''simple docstring'''







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







			def   _a      (      self    ):






									'''simple docstring'''







									UpperCamelCase   ,						UpperCamelCase				:		Optional[int]				   =			self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															UpperCamelCase				:		Dict				   =			model_class(_A    )
															UpperCamelCase				:		int				   =			inspect.signature(model.forward    )
															# signature.parameters is an OrderedDict => so arg_names order is deterministic
															UpperCamelCase				:		str				   =			[*signature.parameters.keys()]

															UpperCamelCase				:		Optional[Any]				   =			[
															    """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   _a      (      self    ):






									'''simple docstring'''







									UpperCamelCase   ,						UpperCamelCase				:		List[str]				   =			self.model_tester.prepare_config_and_inputs_for_common()
									UpperCamelCase				:		Dict				   =			True

									UpperCamelCase				:		Tuple				   =			getattr(self.model_tester						,   """seq_length"""						,   _A    )
									UpperCamelCase				:		Dict				   =			getattr(self.model_tester						,   """decoder_seq_length"""						,   _A    )
									UpperCamelCase				:		Optional[Any]				   =			getattr(self.model_tester						,   """encoder_seq_length"""						,   _A    )
									UpperCamelCase				:		Optional[int]				   =			getattr(self.model_tester						,   """d_model"""						,   _A    )
									UpperCamelCase				:		Optional[Any]				   =			getattr(self.model_tester						,   """num_attention_heads"""						,   _A    )
									UpperCamelCase				:		Tuple				   =			d_model // num_attention_heads

									for model_class in self.all_model_classes:
															UpperCamelCase				:		List[Any]				   =			True
															UpperCamelCase				:		Any				   =			False
															UpperCamelCase				:		List[str]				   =			True
															UpperCamelCase				:		List[str]				   =			model_class(_A    )
															model.to(_A    )
															model.eval()
															with torch.no_grad():
																					UpperCamelCase				:		Tuple				   =			model(**self._prepare_for_class(_A						,   _A    )    )
															UpperCamelCase				:		Optional[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"]
															UpperCamelCase				:		Tuple				   =			True
															UpperCamelCase				:		Optional[int]				   =			model_class(_A    )
															model.to(_A    )
															model.eval()
															with torch.no_grad():
																					UpperCamelCase				:		List[Any]				   =			model(**self._prepare_for_class(_A						,   _A    )    )
															UpperCamelCase				:		List[str]				   =			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]						,   )
															UpperCamelCase				:		List[str]				   =			len(_A    )

															UpperCamelCase				:		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(_A						,   _A    )

															# decoder attentions
															UpperCamelCase				:		Optional[int]				   =			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
															UpperCamelCase				:		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
									UpperCamelCase				:		Any				   =			True
									UpperCamelCase				:		Dict				   =			True
									UpperCamelCase				:		int				   =			model_class(_A    )
									model.to(_A    )
									model.eval()
									with torch.no_grad():
															UpperCamelCase				:		int				   =			model(**self._prepare_for_class(_A						,   _A    )    )

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

									UpperCamelCase				:		str				   =			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   _a      (      self    ):






									'''simple docstring'''







									super().test_retain_grad_hidden_states_attentions()


def      UpperCamelCase							(SCREAMING_SNAKE_CASE="train-batch.pt"     ):
						UpperCamelCase				:		List[str]				   =			hf_hub_download(repo_id="""hf-internal-testing/tourism-monthly-batch"""							,     filename=SCREAMING_SNAKE_CASE							,     repo_type="""dataset"""     )
						UpperCamelCase				:		Optional[int]				   =			torch.load(SCREAMING_SNAKE_CASE							,     map_location=SCREAMING_SNAKE_CASE     )
						return batch






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

			"""simple docstring"""







			def   _a      (      self    ):






									'''simple docstring'''







									UpperCamelCase				:		Dict				   =			AutoformerModel.from_pretrained("""huggingface/autoformer-tourism-monthly"""    ).to(_A    )
									UpperCamelCase				:		List[str]				   =			prepare_batch()

									with torch.no_grad():
															UpperCamelCase				:		Dict				   =			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]

									UpperCamelCase				:		Optional[int]				   =			torch.Size(
									    (6_4, model.config.prediction_length + model.config.label_length, model.config.feature_size)    )
									self.assertEqual(output.shape						,   _A    )

									UpperCamelCase				:		Optional[int]				   =			torch.tensor(
									    [[0.35_93, -1.33_98, 0.63_30], [0.22_79, 1.53_96, -0.17_92], [0.04_50, 1.32_25, -0.23_35]]						,   device=_A    )
									self.assertTrue(torch.allclose(output[0, :3, :3]						,   _A						,   atol=_A    )    )







			def   _a      (      self    ):






									'''simple docstring'''







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

									UpperCamelCase				:		Any				   =			torch.tensor(
									    [[-0.07_34, -0.90_36, 0.83_58], [4.71_86, 2.41_13, 1.95_81], [1.79_53, 2.35_58, 1.29_70]]						,   device=_A    )
									self.assertTrue(torch.allclose(output[0, :3, :3]						,   _A						,   atol=_A    )    )







			def   _a      (      self    ):






									'''simple docstring'''







									UpperCamelCase				:		Dict				   =			AutoformerForPrediction.from_pretrained("""huggingface/autoformer-tourism-monthly"""    ).to(_A    )
									UpperCamelCase				:		List[Any]				   =			prepare_batch("""val-batch.pt"""    )
									with torch.no_grad():
															UpperCamelCase				:		Optional[Any]				   =			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"""]						,   )
									UpperCamelCase				:		Tuple				   =			torch.Size((6_4, model.config.num_parallel_samples, model.config.prediction_length)    )
									self.assertEqual(outputs.sequences.shape						,   _A    )

									UpperCamelCase				:		Dict				   =			torch.tensor([31_30.67_63, 40_56.52_93, 70_53.07_86]						,   device=_A    )
									UpperCamelCase				:		Optional[Any]				   =			outputs.sequences.mean(dim=1    )
									self.assertTrue(torch.allclose(mean_prediction[0, -3:]						,   _A						,   rtol=1e-1    )    )



