





import inspect
import tempfile
import unittest

from huggingface_hub import hf_hub_download

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

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


lowerCAmelCase_    =    1e-4

if is_torch_available():
	import torch

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



@require_torch
class  __lowerCAmelCase	:






			def __init__(self ,							__magic_name__ ,							__magic_name__=16 ,							__magic_name__=13 ,							__magic_name__=7 ,							__magic_name__=14 ,							__magic_name__=10 ,							__magic_name__=19 ,							__magic_name__=5 ,							__magic_name__=4 ,							__magic_name__=True ,							__magic_name__=16 ,							__magic_name__=2 ,							__magic_name__=4 ,							__magic_name__=4 ,							__magic_name__="gelu" ,							__magic_name__=0.1 ,							__magic_name__=0.1 ,							__magic_name__=[1, 2, 3, 4, 5] ,							__magic_name__=25 ,							__magic_name__=5 ,							)					->       int:


							'''simple docstring'''



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

							snake_case_						:   List[Any]           =  context_length
							snake_case_						:   Any           =  prediction_length + label_length
							snake_case_						:   Dict           =  label_length

							snake_case_						:   Dict           =  moving_average
							snake_case_						:   Dict           =  autocorrelation_factor






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


							'''simple docstring'''



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






			def       lowerCamelCase  (self ,							__magic_name__   )					->       Optional[Any]:


							'''simple docstring'''



							snake_case_						:   Dict           =  config.context_length + max(config.lags_sequence   )

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

							# decoder inputs
							snake_case_						:   Union[str, Any]           =  floats_tensor([self.batch_size, config.prediction_length, config.num_time_features]   )
							snake_case_						:   Optional[Any]           =  floats_tensor([self.batch_size, config.prediction_length]   )

							snake_case_						:   List[Any]           =  {
							    '''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   )					->       str:


							'''simple docstring'''



							snake_case_						:   Optional[Any]           =  self.get_config()
							snake_case_						:   List[Any]           =  self.prepare_autoformer_inputs_dict(__magic_name__   )
							return config, inputs_dict






			def       lowerCamelCase  (self   )					->       Optional[Any]:


							'''simple docstring'''



							snake_case_      ,							snake_case_						:   Tuple           =  self.prepare_config_and_inputs()
							return config, inputs_dict






			def       lowerCamelCase  (self ,							__magic_name__ ,							__magic_name__   )					->       List[Any]:


							'''simple docstring'''



							snake_case_						:   List[str]           =  AutoformerModel(config=__magic_name__   ).to(__magic_name__   ).eval()
							snake_case_						:   Any           =  model(**__magic_name__   )

							snake_case_						:   List[Any]           =  outputs.encoder_last_hidden_state
							snake_case_						:   Optional[Any]           =  outputs.last_hidden_state

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

							snake_case_      ,							snake_case_      ,							snake_case_      ,							snake_case_      ,							snake_case_						:   List[Any]           =  model.create_network_inputs(**__magic_name__   )
							snake_case_      ,							snake_case_						:   Optional[int]           =  model.decomposition_layer(transformer_inputs[:, : config.context_length, ...]   )

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

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

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

							with tempfile.TemporaryDirectory() as tmpdirname:
											snake_case_						:   Optional[int]           =  model.get_decoder()
											decoder.save_pretrained(__magic_name__   )
											snake_case_						:   List[Any]           =  AutoformerDecoder.from_pretrained(__magic_name__   ).to(__magic_name__   )

							snake_case_						:   int           =  decoder(
							    trend=__magic_name__ ,							inputs_embeds=__magic_name__ ,							encoder_hidden_states=__magic_name__ ,							)[0]

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




@require_torch
class  __lowerCAmelCase	(      _a,					_a,					unittest.TestCase					):
			lowerCamelCase_					:					Tuple	      =				(AutoformerModel, AutoformerForPrediction) if is_torch_available() else ()
			lowerCamelCase_					:					List[Any]	      =				(AutoformerForPrediction,) if is_torch_available() else ()
			lowerCamelCase_					:					Dict	      =				{'''feature-extraction''': AutoformerModel} if is_torch_available() else {}
			lowerCamelCase_					:					Dict	      =				False
			lowerCamelCase_					:					Union[str, Any]	      =				False
			lowerCamelCase_					:					Tuple	      =				False
			lowerCamelCase_					:					Optional[int]	      =				False
			lowerCamelCase_					:					List[str]	      =				False
			lowerCamelCase_					:					Dict	      =				False






			def       lowerCamelCase  (self   )					->       int:


							'''simple docstring'''



							snake_case_						:   Union[str, Any]           =  AutoformerModelTester(self   )
							snake_case_						:   Optional[int]           =  ConfigTester(self ,							config_class=__magic_name__ ,							has_text_modality=__magic_name__   )






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


							'''simple docstring'''



							self.config_tester.run_common_tests()






			def       lowerCamelCase  (self   )					->       Optional[int]:


							'''simple docstring'''



							snake_case_      ,							snake_case_						:   int           =  self.model_tester.prepare_config_and_inputs()
							for model_class in self.all_model_classes:
											snake_case_						:   List[Any]           =  model_class(__magic_name__   )

											with tempfile.TemporaryDirectory() as tmpdirname:
															model.save_pretrained(__magic_name__   )
															snake_case_      ,							snake_case_						:   Optional[int]           =  model_class.from_pretrained(__magic_name__ ,							output_loading_info=__magic_name__   )
											self.assertEqual(info['''missing_keys'''] ,							[]   )






			def       lowerCamelCase  (self   )					->       Any:


							'''simple docstring'''



							snake_case_						:   Dict           =  self.model_tester.prepare_config_and_inputs_for_common()
							self.model_tester.check_encoder_decoder_model_standalone(*__magic_name__   )






			@unittest.skip(reason='''Model has no tokens embeddings'''   )
			def       lowerCamelCase  (self   )					->       str:


							'''simple docstring'''



							pass






			def       lowerCamelCase  (self   )					->       int:


							'''simple docstring'''



							snake_case_						:   str           =  inspect.signature(getattr(__magic_name__ ,							'''forward'''   )   )
							# The main input is the name of the argument after `self`
							snake_case_						:   Dict           =  list(model_signature.parameters.keys()   )[1]
							self.assertEqual(AutoformerModel.main_input_name ,							__magic_name__   )






			def       lowerCamelCase  (self   )					->       Optional[Any]:


							'''simple docstring'''



							snake_case_      ,							snake_case_						:   str           =  self.model_tester.prepare_config_and_inputs_for_common()

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

											snake_case_						:   List[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(__magic_name__   )] ,							__magic_name__   )






			def       lowerCamelCase  (self   )					->       str:


							'''simple docstring'''



							snake_case_      ,							snake_case_						:   Union[str, Any]           =  self.model_tester.prepare_config_and_inputs_for_common()
							snake_case_						:   str           =  True

							snake_case_						:   int           =  getattr(self.model_tester ,							'''seq_length''' ,							__magic_name__   )
							snake_case_						:   Dict           =  getattr(self.model_tester ,							'''decoder_seq_length''' ,							__magic_name__   )
							snake_case_						:   Tuple           =  getattr(self.model_tester ,							'''encoder_seq_length''' ,							__magic_name__   )
							snake_case_						:   Optional[int]           =  getattr(self.model_tester ,							'''d_model''' ,							__magic_name__   )
							snake_case_						:   str           =  getattr(self.model_tester ,							'''num_attention_heads''' ,							__magic_name__   )
							snake_case_						:   Any           =  d_model // num_attention_heads

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

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

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

											snake_case_						:   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(__magic_name__ ,							__magic_name__   )

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

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

							snake_case_						:   Dict           =  outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions

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






			@is_flaky()
			def       lowerCamelCase  (self   )					->       int:


							'''simple docstring'''



							super().test_retain_grad_hidden_states_attentions()






def 					lowerCamelCase_						(    _UpperCamelCase="train-batch.pt"			)		->						int:






				"""simple docstring"""


				snake_case_						:   Dict           =  hf_hub_download(repo_id='''hf-internal-testing/tourism-monthly-batch'''			,    filename=_UpperCamelCase			,    repo_type='''dataset'''			)
				snake_case_						:   str           =  torch.load(_UpperCamelCase			,    map_location=_UpperCamelCase			)
				return batch





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






			def       lowerCamelCase  (self   )					->       Dict:


							'''simple docstring'''



							snake_case_						:   Any           =  AutoformerModel.from_pretrained('''huggingface/autoformer-tourism-monthly'''   ).to(__magic_name__   )
							snake_case_						:   int           =  prepare_batch()

							with torch.no_grad():
											snake_case_						:   Union[str, 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]

							snake_case_						:   Union[str, Any]           =  torch.Size(
							    (64, model.config.prediction_length + model.config.label_length, model.config.feature_size)   )
							self.assertEqual(output.shape ,							__magic_name__   )

							snake_case_						:   Any           =  torch.tensor(
							    [[0.3_593, -1.3_398, 0.6_330], [0.2_279, 1.5_396, -0.1_792], [0.0_450, 1.3_225, -0.2_335]] ,							device=__magic_name__   )
							self.assertTrue(torch.allclose(output[0, :3, :3] ,							__magic_name__ ,							atol=__magic_name__   )   )






			def       lowerCamelCase  (self   )					->       Dict:


							'''simple docstring'''



							snake_case_						:   int           =  AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly'''   ).to(__magic_name__   )
							snake_case_						:   Dict           =  prepare_batch('''val-batch.pt'''   )
							with torch.no_grad():
											snake_case_						:   List[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
							snake_case_						:   int           =  torch.Size((64, model.config.context_length, model.config.d_model)   )
							self.assertEqual(output.shape ,							__magic_name__   )

							snake_case_						:   List[str]           =  torch.tensor(
							    [[-0.0_734, -0.9_036, 0.8_358], [4.7_186, 2.4_113, 1.9_581], [1.7_953, 2.3_558, 1.2_970]] ,							device=__magic_name__   )
							self.assertTrue(torch.allclose(output[0, :3, :3] ,							__magic_name__ ,							atol=__magic_name__   )   )






			def       lowerCamelCase  (self   )					->       Dict:


							'''simple docstring'''



							snake_case_						:   Optional[Any]           =  AutoformerForPrediction.from_pretrained('''huggingface/autoformer-tourism-monthly'''   ).to(__magic_name__   )
							snake_case_						:   str           =  prepare_batch('''val-batch.pt'''   )
							with torch.no_grad():
											snake_case_						:   List[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'''] ,							)
							snake_case_						:   Optional[int]           =  torch.Size((64, model.config.num_parallel_samples, model.config.prediction_length)   )
							self.assertEqual(outputs.sequences.shape ,							__magic_name__   )

							snake_case_						:   Any           =  torch.tensor([3_130.6_763, 4_056.5_293, 7_053.0_786] ,							device=__magic_name__   )
							snake_case_						:   Tuple           =  outputs.sequences.mean(dim=1   )
							self.assertTrue(torch.allclose(mean_prediction[0, -3:] ,							__magic_name__ ,							rtol=1e-1   )   )







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 					lowerCamelCase_						(    _UpperCamelCase			,    _UpperCamelCase=False			)		->						int:






				"""simple docstring"""


				try:
								snake_case_						:   Optional[Any]           =  os.environ[key]
				except KeyError:
								# KEY isn't set, default to `default`.
								snake_case_						:   Tuple           =  default
				else:
								# KEY is set, convert it to True or False.
								try:
												snake_case_						:   Union[str, Any]           =  strtobool(_UpperCamelCase			)
								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


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






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						List[Any]:






				"""simple docstring"""


				return unittest.skip('''Test was skipped'''			)(_UpperCamelCase			)






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						Optional[int]:






				"""simple docstring"""


				return unittest.skipUnless(_run_slow_tests			,    '''test is slow'''			)(_UpperCamelCase			)






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						Dict:






				"""simple docstring"""


				return unittest.skipUnless(not torch.cuda.is_available()			,    '''test requires only a CPU'''			)(_UpperCamelCase			)






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						int:






				"""simple docstring"""


				return unittest.skipUnless(torch.cuda.is_available()			,    '''test requires a GPU'''			)(_UpperCamelCase			)






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						str:






				"""simple docstring"""


				return unittest.skipUnless(is_xpu_available()			,    '''test requires a XPU'''			)(_UpperCamelCase			)






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						List[Any]:






				"""simple docstring"""


				return unittest.skipUnless(is_mps_available()			,    '''test requires a `mps` backend support in `torch`'''			)(_UpperCamelCase			)






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						Optional[Any]:






				"""simple docstring"""


				return unittest.skipUnless(
				    is_transformers_available() and is_datasets_available()			,    '''test requires the Hugging Face suite'''			)(_UpperCamelCase			)






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						Any:






				"""simple docstring"""


				return unittest.skipUnless(is_bnb_available()			,    '''test requires the bitsandbytes library'''			)(_UpperCamelCase			)






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						List[Any]:






				"""simple docstring"""


				return unittest.skipUnless(is_tpu_available()			,    '''test requires TPU'''			)(_UpperCamelCase			)






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						List[Any]:






				"""simple docstring"""


				return unittest.skipUnless(torch.cuda.device_count() == 1			,    '''test requires a GPU'''			)(_UpperCamelCase			)






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						int:






				"""simple docstring"""


				return unittest.skipUnless(torch.xpu.device_count() == 1			,    '''test requires a XPU'''			)(_UpperCamelCase			)






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						Any:






				"""simple docstring"""


				return unittest.skipUnless(torch.cuda.device_count() > 1			,    '''test requires multiple GPUs'''			)(_UpperCamelCase			)






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						Any:






				"""simple docstring"""


				return unittest.skipUnless(torch.xpu.device_count() > 1			,    '''test requires multiple XPUs'''			)(_UpperCamelCase			)






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						str:






				"""simple docstring"""


				return unittest.skipUnless(is_safetensors_available()			,    '''test requires safetensors'''			)(_UpperCamelCase			)






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						int:






				"""simple docstring"""


				return unittest.skipUnless(is_deepspeed_available()			,    '''test requires DeepSpeed'''			)(_UpperCamelCase			)






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						Any:






				"""simple docstring"""


				return unittest.skipUnless(is_torch_version('''>='''			,    '''1.12.0'''			)			,    '''test requires torch version >= 1.12.0'''			)(_UpperCamelCase			)






def 					lowerCamelCase_						(    _UpperCamelCase=None			,    _UpperCamelCase=None			)		->						Tuple:






				"""simple docstring"""


				if test_case is None:
								return partial(_UpperCamelCase			,    version=_UpperCamelCase			)
				return unittest.skipUnless(is_torch_version('''>='''			,    _UpperCamelCase			)			,    f'''test requires torch version >= {version}'''			)(_UpperCamelCase			)






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						int:






				"""simple docstring"""


				return unittest.skipUnless(is_tensorboard_available()			,    '''test requires Tensorboard'''			)(_UpperCamelCase			)






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						Optional[int]:






				"""simple docstring"""


				return unittest.skipUnless(is_wandb_available()			,    '''test requires wandb'''			)(_UpperCamelCase			)






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						Union[str, Any]:






				"""simple docstring"""


				return unittest.skipUnless(is_comet_ml_available()			,    '''test requires comet_ml'''			)(_UpperCamelCase			)


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






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						Union[str, Any]:






				"""simple docstring"""


				return unittest.skipUnless(
				    _atleast_one_tracker_available			,    '''test requires at least one tracker to be available and for `comet_ml` to not be installed'''			,    )(_UpperCamelCase			)



class  __lowerCAmelCase	(      unittest.TestCase					):
			lowerCamelCase_					:					str	      =				True






			@classmethod
			def       lowerCamelCase  (cls   )					->       List[Any]:


							'''simple docstring'''



							snake_case_						:   Any           =  tempfile.mkdtemp()






			@classmethod
			def       lowerCamelCase  (cls   )					->       List[Any]:


							'''simple docstring'''



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






			def       lowerCamelCase  (self   )					->       Optional[int]:


							'''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(__magic_name__   )




class  __lowerCAmelCase	(      unittest.TestCase					):






			def       lowerCamelCase  (self   )					->       int:


							'''simple docstring'''



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




class  __lowerCAmelCase	(      unittest.TestCase					):






			def       lowerCamelCase  (self ,							__magic_name__   )					->       Dict:


							'''simple docstring'''



							snake_case_						:   str           =  mocks if isinstance(__magic_name__ ,							(tuple, list)   ) else [mocks]
							for m in self.mocks:
											m.start()
											self.addCleanup(m.stop   )






def 					lowerCamelCase_						(    _UpperCamelCase			)		->						List[str]:






				"""simple docstring"""


				snake_case_						:   Optional[Any]           =  AcceleratorState()
				snake_case_						:   List[str]           =  tensor[None].clone().to(state.device			)
				snake_case_						:   Optional[Any]           =  gather(_UpperCamelCase			).cpu()
				snake_case_						:   Optional[Any]           =  tensor[0].cpu()
				for i in range(tensors.shape[0]			):
								if not torch.equal(tensors[i]			,    _UpperCamelCase			):
												return False
				return True



class  __lowerCAmelCase	:






			def __init__(self ,							__magic_name__ ,							__magic_name__ ,							__magic_name__   )					->       Optional[Any]:


							'''simple docstring'''



							snake_case_						:   Any           =  returncode
							snake_case_						:   List[Any]           =  stdout
							snake_case_						:   Tuple           =  stderr






async def 					lowerCamelCase_						(    _UpperCamelCase			,    _UpperCamelCase			)		->						str:






				"""simple docstring"""


				while True:
								snake_case_						:   Tuple           =  await stream.readline()
								if line:
												callback(_UpperCamelCase			)
								else:
												break






async def 					lowerCamelCase_						(    _UpperCamelCase			,    _UpperCamelCase=None			,    _UpperCamelCase=None			,    _UpperCamelCase=None			,    _UpperCamelCase=False			,    _UpperCamelCase=False			)		->						_RunOutput:






				"""simple docstring"""


				if echo:
								print('''\nRunning: '''			,    ''' '''.join(_UpperCamelCase			)			)

				snake_case_						:   List[str]           =  await asyncio.create_subprocess_exec(
				    cmd[0]			,    *cmd[1:]			,    stdin=_UpperCamelCase			,    stdout=asyncio.subprocess.PIPE			,    stderr=asyncio.subprocess.PIPE			,    env=_UpperCamelCase			,    )

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

				snake_case_						:   List[Any]           =  []
				snake_case_						:   List[Any]           =  []

				def tee(_UpperCamelCase			,    _UpperCamelCase			,    _UpperCamelCase			,    _UpperCamelCase=""			):
								snake_case_						:   Union[str, Any]           =  line.decode('''utf-8'''			).rstrip()
								sink.append(_UpperCamelCase			)
								if not quiet:
												print(_UpperCamelCase			,    _UpperCamelCase			,    file=_UpperCamelCase			)

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






def 					lowerCamelCase_						(    _UpperCamelCase			,    _UpperCamelCase=None			,    _UpperCamelCase=None			,    _UpperCamelCase=180			,    _UpperCamelCase=False			,    _UpperCamelCase=True			)		->						_RunOutput:






				"""simple docstring"""


				snake_case_						:   List[str]           =  asyncio.get_event_loop()
				snake_case_						:   List[Any]           =  loop.run_until_complete(
				    _stream_subprocess(_UpperCamelCase			,    env=_UpperCamelCase			,    stdin=_UpperCamelCase			,    timeout=_UpperCamelCase			,    quiet=_UpperCamelCase			,    echo=_UpperCamelCase			)			)

				snake_case_						:   Optional[int]           =  ''' '''.join(_UpperCamelCase			)
				if result.returncode > 0:
								snake_case_						:   Union[str, 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  __lowerCAmelCase	(      _a					):
			pass






def 					lowerCamelCase_						(    _UpperCamelCase			,    _UpperCamelCase=False			)		->						List[Any]:






				"""simple docstring"""


				try:
								snake_case_						:   List[str]           =  subprocess.check_output(_UpperCamelCase			,    stderr=subprocess.STDOUT			)
								if return_stdout:
												if hasattr(_UpperCamelCase			,    '''decode'''			):
																snake_case_						:   Tuple           =  output.decode('''utf-8'''			)
												return output
				except subprocess.CalledProcessError as e:
								raise SubprocessCallException(
								    f'''Command `{" ".join(_UpperCamelCase			)}` failed with the following error:\n\n{e.output.decode()}'''			) from e
