





from pathlib import Path

import torch

from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter


_lowerCamelCase						:     Dict		   =	'Create a default config file for Accelerate with only a few flags set.'





def 						_lowerCAmelCase						(      __magic_name__	:str="no"  ,							__magic_name__	:Dict = default_json_config_file  ,							__magic_name__	:List[str] = False      ):
					UpperCAmelCase_		=  Path(lowercase__      )
					path.parent.mkdir(parents=lowercase__  ,							exist_ok=lowercase__      )
					if path.exists():
										print(
										    F'''Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.'''      )
										return False
					UpperCAmelCase_		=  mixed_precision.lower()
					if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
										raise ValueError(
										    F'''`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}'''      )
					UpperCAmelCase_		=  {
					    'compute_environment': 'LOCAL_MACHINE',
					    'mixed_precision': mixed_precision,
					}
					if torch.cuda.is_available():
										UpperCAmelCase_		=  torch.cuda.device_count()
										UpperCAmelCase_		=  num_gpus
										UpperCAmelCase_		=  False
										if num_gpus > 1:
															UpperCAmelCase_		=  'MULTI_GPU'
										else:
															UpperCAmelCase_		=  'NO'
					elif is_xpu_available() and use_xpu:
										UpperCAmelCase_		=  torch.xpu.device_count()
										UpperCAmelCase_		=  num_xpus
										UpperCAmelCase_		=  False
										if num_xpus > 1:
															UpperCAmelCase_		=  'MULTI_XPU'
										else:
															UpperCAmelCase_		=  'NO'
					elif is_npu_available():
										UpperCAmelCase_		=  torch.npu.device_count()
										UpperCAmelCase_		=  num_npus
										UpperCAmelCase_		=  False
										if num_npus > 1:
															UpperCAmelCase_		=  'MULTI_NPU'
										else:
															UpperCAmelCase_		=  'NO'
					else:
										UpperCAmelCase_		=  0
										UpperCAmelCase_		=  True
										UpperCAmelCase_		=  1
										UpperCAmelCase_		=  'NO'
					UpperCAmelCase_		=  ClusterConfig(**lowercase__      )
					config.to_json_file(lowercase__      )
					return path





def 						_lowerCAmelCase						(      __magic_name__	:int  ,							__magic_name__	:List[Any]      ):
					UpperCAmelCase_		=  parser.add_parser('''default'''  ,							parents=lowercase__  ,							help=lowercase__  ,							formatter_class=lowercase__      )
					parser.add_argument(
					    '''--config_file'''  ,							default=lowercase__  ,							help=(
					        '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache '''
					        '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have '''
					        '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed '''
					        '''with \'huggingface\'.'''
					    )  ,							dest='''save_location'''  ,							)

					parser.add_argument(
					    '''--mixed_precision'''  ,							choices=['''no''', '''fp16''', '''bf16''']  ,							type=lowercase__  ,							help='''Whether or not to use mixed precision training. '''
					    '''Choose between FP16 and BF16 (bfloat16) training. '''
					    '''BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.'''  ,							default='''no'''  ,							)
					parser.set_defaults(func=lowercase__      )
					return parser





def 						_lowerCAmelCase						(      __magic_name__	:Dict      ):
					UpperCAmelCase_		=  write_basic_config(args.mixed_precision  ,							args.save_location      )
					if config_file:
										print(F'''accelerate configuration saved at {config_file}'''      )






"""simple docstring"""






import unittest

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

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


if is_torch_available():
			import torch

			from transformers import (
			    MPNetForMaskedLM,
			    MPNetForMultipleChoice,
			    MPNetForQuestionAnswering,
			    MPNetForSequenceClassification,
			    MPNetForTokenClassification,
			    MPNetModel,
			)






class lowerCAmelCase__      :






			'''simple docstring'''



			def __init__(    self    , lowercase    , lowercase=13    , lowercase=7    , lowercase=True    , lowercase=True    , lowercase=False    , lowercase=True    , lowercase=99    , lowercase=64    , lowercase=5    , lowercase=4    , lowercase=64    , lowercase="gelu"    , lowercase=0.1    , lowercase=0.1    , lowercase=512    , lowercase=16    , lowercase=2    , lowercase=0.02    , lowercase=3    , lowercase=4    , lowercase=None    , ):
							_lowerCamelCase	:     List[str]       =       parent
							_lowerCamelCase	:     List[str]       =       batch_size
							_lowerCamelCase	:     Tuple       =       seq_length
							_lowerCamelCase	:     List[Any]       =       is_training
							_lowerCamelCase	:     int       =       use_input_mask
							_lowerCamelCase	:     Optional[Any]       =       use_token_type_ids
							_lowerCamelCase	:     List[Any]       =       use_labels
							_lowerCamelCase	:     str       =       vocab_size
							_lowerCamelCase	:     Optional[int]       =       hidden_size
							_lowerCamelCase	:     List[str]       =       num_hidden_layers
							_lowerCamelCase	:     Optional[int]       =       num_attention_heads
							_lowerCamelCase	:     List[str]       =       intermediate_size
							_lowerCamelCase	:     int       =       hidden_act
							_lowerCamelCase	:     Optional[int]       =       hidden_dropout_prob
							_lowerCamelCase	:     List[Any]       =       attention_probs_dropout_prob
							_lowerCamelCase	:     List[str]       =       max_position_embeddings
							_lowerCamelCase	:     List[Any]       =       type_vocab_size
							_lowerCamelCase	:     Optional[int]       =       type_sequence_label_size
							_lowerCamelCase	:     Union[str, Any]       =       initializer_range
							_lowerCamelCase	:     Tuple       =       num_labels
							_lowerCamelCase	:     int       =       num_choices
							_lowerCamelCase	:     int       =       scope
			def    A_       (    self    ):
							return MPNetConfig.from_pretrained('microsoft/mpnet-base'    )
			def    A_       (    self    ):
							_lowerCamelCase	:     Tuple       =       ids_tensor([self.batch_size, self.seq_length]    , self.vocab_size    )

							_lowerCamelCase	:     Dict       =       None
							if self.use_input_mask:
											_lowerCamelCase	:     Optional[int]       =       random_attention_mask([self.batch_size, self.seq_length]    )

							_lowerCamelCase	:     int       =       None
							_lowerCamelCase	:     List[str]       =       None
							_lowerCamelCase	:     Any       =       None
							if self.use_labels:
											_lowerCamelCase	:     List[str]       =       ids_tensor([self.batch_size]    , self.type_sequence_label_size    )
											_lowerCamelCase	:     str       =       ids_tensor([self.batch_size, self.seq_length]    , self.num_labels    )
											_lowerCamelCase	:     Dict       =       ids_tensor([self.batch_size]    , self.num_choices    )

							_lowerCamelCase	:     int       =       self.get_config()
							return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
			def    A_       (    self    ):
							return MPNetConfig(
							    vocab_size=self.vocab_size    , hidden_size=self.hidden_size    , num_hidden_layers=self.num_hidden_layers    , num_attention_heads=self.num_attention_heads    , intermediate_size=self.intermediate_size    , hidden_act=self.hidden_act    , hidden_dropout_prob=self.hidden_dropout_prob    , attention_probs_dropout_prob=self.attention_probs_dropout_prob    , max_position_embeddings=self.max_position_embeddings    , initializer_range=self.initializer_range    , )
			def    A_       (    self    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    ):
							_lowerCamelCase	:     Optional[Any]       =       MPNetModel(config=lowercase    )
							model.to(lowercase    )
							model.eval()
							_lowerCamelCase	:     Tuple       =       model(lowercase    , lowercase    )
							_lowerCamelCase	:     Tuple       =       model(lowercase    )
							self.parent.assertEqual(result.last_hidden_state.shape    , (self.batch_size, self.seq_length, self.hidden_size)    )
							self.parent.assertEqual(result.pooler_output.shape    , (self.batch_size, self.hidden_size)    )
			def    A_       (    self    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    ):
							_lowerCamelCase	:     str       =       MPNetForQuestionAnswering(config=lowercase    )
							model.to(lowercase    )
							model.eval()
							_lowerCamelCase	:     str       =       model(
							    lowercase    , attention_mask=lowercase    , start_positions=lowercase    , end_positions=lowercase    , )
							self.parent.assertEqual(result.start_logits.shape    , (self.batch_size, self.seq_length)    )
							self.parent.assertEqual(result.end_logits.shape    , (self.batch_size, self.seq_length)    )
			def    A_       (    self    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    ):
							_lowerCamelCase	:     Optional[int]       =       self.num_labels
							_lowerCamelCase	:     int       =       MPNetForSequenceClassification(lowercase    )
							model.to(lowercase    )
							model.eval()
							_lowerCamelCase	:     Optional[Any]       =       model(lowercase    , attention_mask=lowercase    , labels=lowercase    )
							self.parent.assertEqual(result.logits.shape    , (self.batch_size, self.num_labels)    )
			def    A_       (    self    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    ):
							_lowerCamelCase	:     List[str]       =       self.num_choices
							_lowerCamelCase	:     List[str]       =       MPNetForMultipleChoice(config=lowercase    )
							model.to(lowercase    )
							model.eval()
							_lowerCamelCase	:     Union[str, Any]       =       input_ids.unsqueeze(1    ).expand(-1    , self.num_choices    , -1    ).contiguous()
							_lowerCamelCase	:     List[str]       =       input_mask.unsqueeze(1    ).expand(-1    , self.num_choices    , -1    ).contiguous()
							_lowerCamelCase	:     Any       =       model(
							    lowercase    , attention_mask=lowercase    , labels=lowercase    , )
							self.parent.assertEqual(result.logits.shape    , (self.batch_size, self.num_choices)    )
			def    A_       (    self    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    , lowercase    ):
							_lowerCamelCase	:     Any       =       self.num_labels
							_lowerCamelCase	:     Union[str, Any]       =       MPNetForTokenClassification(config=lowercase    )
							model.to(lowercase    )
							model.eval()
							_lowerCamelCase	:     Union[str, Any]       =       model(lowercase    , attention_mask=lowercase    , labels=lowercase    )
							self.parent.assertEqual(result.logits.shape    , (self.batch_size, self.seq_length, self.num_labels)    )






			def    A_       (    self    ):
							_lowerCamelCase	:     Dict       =       self.prepare_config_and_inputs()
							((_lowerCamelCase),					(_lowerCamelCase),					(_lowerCamelCase),					(_lowerCamelCase),					(_lowerCamelCase),					(_lowerCamelCase))	:     List[Any]       =       config_and_inputs
							_lowerCamelCase	:     str       =       {'input_ids': input_ids, 'attention_mask': input_mask}
							return config, inputs_dict






@require_torch
class lowerCAmelCase__      (	lowercase,      lowercase,      unittest.TestCase		):






			'''simple docstring'''



			lowerCamelCase__ =     (
			    (
			        MPNetForMaskedLM,
			        MPNetForMultipleChoice,
			        MPNetForQuestionAnswering,
			        MPNetForSequenceClassification,
			        MPNetForTokenClassification,
			        MPNetModel,
			    )
			    if is_torch_available()
			    else ()
			)
			lowerCamelCase__ =     (
			    {
			        """feature-extraction""": MPNetModel,
			        """fill-mask""": MPNetForMaskedLM,
			        """question-answering""": MPNetForQuestionAnswering,
			        """text-classification""": MPNetForSequenceClassification,
			        """token-classification""": MPNetForTokenClassification,
			        """zero-shot""": MPNetForSequenceClassification,
			    }
			    if is_torch_available()
			    else {}
			)
			lowerCamelCase__ =     False
			lowerCamelCase__ =     True
			def    A_       (    self    ):
							_lowerCamelCase	:     Union[str, Any]       =       MPNetModelTester(self    )
							_lowerCamelCase	:     List[Any]       =       ConfigTester(self    , config_class=lowercase    , hidden_size=37    )
			def    A_       (    self    ):
							self.config_tester.run_common_tests()
			def    A_       (    self    ):
							_lowerCamelCase	:     Union[str, Any]       =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_mpnet_model(*lowercase    )
			def    A_       (    self    ):
							_lowerCamelCase	:     List[Any]       =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_mpnet_for_sequence_classification(*lowercase    )
			def    A_       (    self    ):
							_lowerCamelCase	:     Optional[Any]       =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_mpnet_for_multiple_choice(*lowercase    )
			def    A_       (    self    ):
							_lowerCamelCase	:     List[Any]       =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_mpnet_for_token_classification(*lowercase    )






			def    A_       (    self    ):
							_lowerCamelCase	:     str       =       self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_mpnet_for_question_answering(*lowercase    )






@require_torch
class lowerCAmelCase__      (	unittest.TestCase		):






			'''simple docstring'''



			@slow
			def    A_       (    self    ):
							_lowerCamelCase	:     Optional[Any]       =       MPNetModel.from_pretrained('microsoft/mpnet-base'    )
							_lowerCamelCase	:     Optional[Any]       =       torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]]    )
							_lowerCamelCase	:     Any       =       model(lowercase    )[0]
							_lowerCamelCase	:     Dict       =       torch.Size((1, 11, 768)    )
							self.assertEqual(output.shape    , lowercase    )
							_lowerCamelCase	:     List[Any]       =       torch.tensor(
							    [[[-0.05_50, 0.19_43, -0.07_40], [-0.05_62, 0.22_11, -0.05_79], [-0.04_37, 0.33_37, -0.06_41]]]    )
							# compare the actual values for a slice.
							self.assertTrue(torch.allclose(output[:, :3, :3]    , lowercase    , atol=1E-4    )    )