

"""simple docstring"""




import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					List[str]					, lowerCAmelCase:					Union[str, Any]=False	)				->    List[Any]:
				try:
								_UpperCAmelCase    :						Optional[int]							=      os.environ[key]
				except KeyError:
								# KEY isn't set, default to `default`.
								_UpperCAmelCase    :						List[Any]							=      default
				else:
								# KEY is set, convert it to True or False.
								try:
												_UpperCAmelCase    :						str							=      strtobool(lowerCamelCase__	)
								except ValueError:
												# More values are supported, but let's keep the message simple.
												raise ValueError(F'If set, {key} must be yes or no.'	)
				return _value


SCREAMING_SNAKE_CASE_            = parse_flag_from_env('RUN_SLOW', default=False)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Optional[int]	)				->    Optional[int]:
				return unittest.skip("Test was skipped"	)(lowerCamelCase__	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Tuple	)				->    str:
				return unittest.skipUnless(_run_slow_tests					, "test is slow"	)(lowerCamelCase__	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					str	)				->    Optional[int]:
				return unittest.skipUnless(not torch.cuda.is_available()					, "test requires only a CPU"	)(lowerCamelCase__	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Tuple	)				->    List[Any]:
				return unittest.skipUnless(torch.cuda.is_available()					, "test requires a GPU"	)(lowerCamelCase__	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Any	)				->    Optional[int]:
				return unittest.skipUnless(is_xpu_available()					, "test requires a XPU"	)(lowerCamelCase__	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					List[Any]	)				->    List[Any]:
				return unittest.skipUnless(is_mps_available()					, "test requires a `mps` backend support in `torch`"	)(lowerCamelCase__	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Tuple	)				->    Any:
				return unittest.skipUnless(
				    is_transformers_available() and is_datasets_available()					, "test requires the Hugging Face suite"	)(lowerCamelCase__	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Union[str, Any]	)				->    Dict:
				return unittest.skipUnless(is_bnb_available()					, "test requires the bitsandbytes library"	)(lowerCamelCase__	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					str	)				->    int:
				return unittest.skipUnless(is_tpu_available()					, "test requires TPU"	)(lowerCamelCase__	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					int	)				->    Union[str, Any]:
				return unittest.skipUnless(torch.cuda.device_count() == 1					, "test requires a GPU"	)(lowerCamelCase__	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Optional[Any]	)				->    int:
				return unittest.skipUnless(torch.xpu.device_count() == 1					, "test requires a XPU"	)(lowerCamelCase__	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					List[str]	)				->    Any:
				return unittest.skipUnless(torch.cuda.device_count() > 1					, "test requires multiple GPUs"	)(lowerCamelCase__	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Optional[Any]	)				->    Dict:
				return unittest.skipUnless(torch.xpu.device_count() > 1					, "test requires multiple XPUs"	)(lowerCamelCase__	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Tuple	)				->    Union[str, Any]:
				return unittest.skipUnless(is_safetensors_available()					, "test requires safetensors"	)(lowerCamelCase__	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Optional[int]	)				->    Any:
				return unittest.skipUnless(is_deepspeed_available()					, "test requires DeepSpeed"	)(lowerCamelCase__	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Dict	)				->    List[str]:
				return unittest.skipUnless(is_torch_version(">="					, "1.12.0"	)					, "test requires torch version >= 1.12.0"	)(lowerCamelCase__	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Optional[Any]=None					, lowerCAmelCase:					int=None	)				->    Dict:
				if test_case is None:
								return partial(lowerCamelCase__					, version=lowerCamelCase__	)
				return unittest.skipUnless(is_torch_version(">="					, lowerCamelCase__	)					, F'test requires torch version >= {version}'	)(lowerCamelCase__	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Optional[int]	)				->    Optional[Any]:
				return unittest.skipUnless(is_tensorboard_available()					, "test requires Tensorboard"	)(lowerCamelCase__	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Dict	)				->    Optional[int]:
				return unittest.skipUnless(is_wandb_available()					, "test requires wandb"	)(lowerCamelCase__	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Optional[Any]	)				->    int:
				return unittest.skipUnless(is_comet_ml_available()					, "test requires comet_ml"	)(lowerCamelCase__	)


SCREAMING_SNAKE_CASE_            = (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Tuple	)				->    Optional[Any]:
				return unittest.skipUnless(
				    _atleast_one_tracker_available					, "test requires at least one tracker to be available and for `comet_ml` to not be installed"					, )(lowerCamelCase__	)

class 			a					(		unittest.TestCase			):
						_lowercase        =     True


						@classmethod
						def     _UpperCAmelCase			(    cls		):







										'''simple docstring'''


										_UpperCAmelCase    :						Any							=      tempfile.mkdtemp()


						@classmethod
						def     _UpperCAmelCase			(    cls		):







										'''simple docstring'''


										if os.path.exists(cls.tmpdir		):
														shutil.rmtree(cls.tmpdir		)





						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										if self.clear_on_setup:
														for path in Path(self.tmpdir		).glob("**/*"		):
																		if path.is_file():
																						path.unlink()
																		elif path.is_dir():
																						shutil.rmtree(A_		)







class 			a					(		unittest.TestCase			):


						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										super().tearDown()
										# Reset the state of the AcceleratorState singleton.
										AcceleratorState._reset_state()
										PartialState._reset_state()







class 			a					(		unittest.TestCase			):


						def     _UpperCAmelCase			(    self  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						Optional[int]							=      mocks if isinstance(A_  ,   (tuple, list)		) else [mocks]
										for m in self.mocks:
														m.start()
														self.addCleanup(m.stop		)







def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Dict	)				->    Optional[int]:
				_UpperCAmelCase    :						Tuple							=      AcceleratorState()
				_UpperCAmelCase    :						List[str]							=      tensor[None].clone().to(state.device	)
				_UpperCAmelCase    :						Dict							=      gather(lowerCamelCase__	).cpu()
				_UpperCAmelCase    :						List[Any]							=      tensor[0].cpu()
				for i in range(tensors.shape[0]	):
								if not torch.equal(tensors[i]					, lowerCamelCase__	):
												return False
				return True

class 			a					:


						def __init__(    self  ,   A_  ,   A_  ,   A_		):







										'''simple docstring'''


										_UpperCAmelCase    :						str							=      returncode
										_UpperCAmelCase    :						Optional[Any]							=      stdout
										_UpperCAmelCase    :						Union[str, Any]							=      stderr







async def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					int					, lowerCAmelCase:					str	)				->    int:
				while True:
								_UpperCAmelCase    :						Dict							=      await stream.readline()
								if line:
												callback(lowerCamelCase__	)
								else:
												break

async def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					List[Any]					, lowerCAmelCase:					Dict=None					, lowerCAmelCase:					Union[str, Any]=None					, lowerCAmelCase:					List[str]=None					, lowerCAmelCase:					Dict=False					, lowerCAmelCase:					Union[str, Any]=False	)				->    Tuple:
				if echo:
								print("\nRunning: "					, " ".join(lowerCamelCase__	)	)

				_UpperCAmelCase    :						Any							=      await asyncio.create_subprocess_exec(
				    cmd[0]					, *cmd[1:]					, stdin=lowerCamelCase__					, stdout=asyncio.subprocess.PIPE					, stderr=asyncio.subprocess.PIPE					, env=lowerCamelCase__					, )

				# note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
				# https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
				#
				# If it starts hanging, will need to switch to the following code. The problem is that no data
				# will be seen until it's done and if it hangs for example there will be no debug info.
				# out, err = await p.communicate()
				# return _RunOutput(p.returncode, out, err)

				_UpperCAmelCase    :						Union[str, Any]							=      []
				_UpperCAmelCase    :						Optional[Any]							=      []

				def tee(lowerCAmelCase:					List[Any]					, lowerCAmelCase:					List[str]					, lowerCAmelCase:					Tuple					, lowerCAmelCase:					Optional[Any]=""	):
								_UpperCAmelCase    :						List[str]							=      line.decode("utf-8"	).rstrip()
								sink.append(lowerCamelCase__	)
								if not quiet:
												print(lowerCamelCase__					, lowerCamelCase__					, file=lowerCamelCase__	)

    # XXX: the timeout doesn't seem to make any difference here
				await asyncio.wait(
				    [
				        asyncio.create_task(_read_stream(p.stdout					, lambda lowerCAmelCase	: tee(lowerCamelCase__					, lowerCamelCase__					, sys.stdout					, label="stdout:"	)	)	),
				        asyncio.create_task(_read_stream(p.stderr					, lambda lowerCAmelCase	: tee(lowerCamelCase__					, lowerCamelCase__					, sys.stderr					, label="stderr:"	)	)	),
				    ]					, timeout=lowerCamelCase__					, )
				return _RunOutput(await p.wait()					, lowerCamelCase__					, lowerCamelCase__	)

def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Optional[int]					, lowerCAmelCase:					Dict=None					, lowerCAmelCase:					Union[str, Any]=None					, lowerCAmelCase:					str=180					, lowerCAmelCase:					Tuple=False					, lowerCAmelCase:					Optional[int]=True	)				->    str:
				_UpperCAmelCase    :						List[Any]							=      asyncio.get_event_loop()
				_UpperCAmelCase    :						Union[str, Any]							=      loop.run_until_complete(
				    _stream_subprocess(lowerCamelCase__					, env=lowerCamelCase__					, stdin=lowerCamelCase__					, timeout=lowerCamelCase__					, quiet=lowerCamelCase__					, echo=lowerCamelCase__	)	)

				_UpperCAmelCase    :						Union[str, Any]							=      " ".join(lowerCamelCase__	)
				if result.returncode > 0:
								_UpperCAmelCase    :						Any							=      "\n".join(result.stderr	)
								raise RuntimeError(
								    F'\'{cmd_str}\' failed with returncode {result.returncode}\n\n'
								    F'The combined stderr from workers follows:\n{stderr}'	)

				return result

class 			a					(		snake_case_			):
						pass







def 							__SCREAMING_SNAKE_CASE							(			lowerCAmelCase:					Union[str, Any]					, lowerCAmelCase:					Dict=False	)				->    List[Any]:
				try:
								_UpperCAmelCase    :						Optional[Any]							=      subprocess.check_output(lowerCamelCase__					, stderr=subprocess.STDOUT	)
								if return_stdout:
												if hasattr(lowerCamelCase__					, "decode"	):
																_UpperCAmelCase    :						Dict							=      output.decode("utf-8"	)
												return output
				except subprocess.CalledProcessError as e:
								raise SubprocessCallException(
								    F'Command `{" ".join(lowerCamelCase__	)}` failed with the following error:\n\n{e.output.decode()}'	) from e





from typing import List, Optional

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


SCREAMING_SNAKE_CASE_            = logging.get_logger(__name__)

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

class 			a					(		UpperCAmelCase			):
						_lowercase        =     "autoformer"
						_lowercase        =     {
						    "hidden_size": "d_model",
						    "num_attention_heads": "encoder_attention_heads",
						    "num_hidden_layers": "encoder_layers",
						}


						def __init__(    self  ,   A_ = None  ,   A_ = None  ,   A_ = "student_t"  ,   A_ = "nll"  ,   A_ = 1  ,   A_ = [1, 2, 3, 4, 5, 6, 7]  ,   A_ = True  ,   A_ = 0  ,   A_ = 0  ,   A_ = 0  ,   A_ = 0  ,   A_ = None  ,   A_ = None  ,   A_ = 64  ,   A_ = 2  ,   A_ = 2  ,   A_ = 2  ,   A_ = 2  ,   A_ = 32  ,   A_ = 32  ,   A_ = "gelu"  ,   A_ = 0.1  ,   A_ = 0.1  ,   A_ = 0.1  ,   A_ = 0.1  ,   A_ = 0.1  ,   A_ = 100  ,   A_ = 0.02  ,   A_ = True  ,   A_=True  ,   A_ = 10  ,   A_ = 25  ,   A_ = 3  ,   **A_  ,   ):







										'''simple docstring'''


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

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

										_UpperCAmelCase    :						Optional[Any]							=      dropout
										_UpperCAmelCase    :						Union[str, Any]							=      attention_dropout
										_UpperCAmelCase    :						Dict							=      activation_dropout
										_UpperCAmelCase    :						Dict							=      encoder_layerdrop
										_UpperCAmelCase    :						int							=      decoder_layerdrop

										_UpperCAmelCase    :						Union[str, Any]							=      activation_function
										_UpperCAmelCase    :						str							=      init_std

										_UpperCAmelCase    :						Tuple							=      use_cache

										# Autoformer
										_UpperCAmelCase    :						str							=      label_length
										_UpperCAmelCase    :						Any							=      moving_average
										_UpperCAmelCase    :						Optional[Any]							=      autocorrelation_factor

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





						@property
						def     _UpperCAmelCase			(    self		):







										'''simple docstring'''


										return (
										    sum(self.embedding_dimension		)
										    + self.num_dynamic_real_features
										    + self.num_time_features
										    + self.num_static_real_features
										    + self.input_size * 2  # the log1p(abs(loc)) and log(scale) features
										)


