


'''simple docstring'''



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


__UpperCAmelCase      :Tuple			    =       "Create a default config file for Accelerate with only a few flags set."




def      _a     (						_lowercase :     List[Any]="no"      , _lowercase :     str = default_json_config_file      , _lowercase :     bool = False  ):





     '''simple docstring'''






     __UpperCAmelCase     :			Dict  							=      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     :			List[str]  							=      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     :			int  							=      {
         '''compute_environment''': '''LOCAL_MACHINE''',
         '''mixed_precision''': mixed_precision,
     }
     if torch.cuda.is_available():
          __UpperCAmelCase     :			Optional[Any]  							=      torch.cuda.device_count()
          __UpperCAmelCase     :			List[str]  							=      num_gpus
          __UpperCAmelCase     :			int  							=      False
          if num_gpus > 1:
               __UpperCAmelCase     :			Any  							=      '''MULTI_GPU'''
          else:
               __UpperCAmelCase     :			int  							=      '''NO'''
     elif is_xpu_available() and use_xpu:
          __UpperCAmelCase     :			List[Any]  							=      torch.xpu.device_count()
          __UpperCAmelCase     :			List[Any]  							=      num_xpus
          __UpperCAmelCase     :			Optional[int]  							=      False
          if num_xpus > 1:
               __UpperCAmelCase     :			Any  							=      '''MULTI_XPU'''
          else:
               __UpperCAmelCase     :			Optional[Any]  							=      '''NO'''
     elif is_npu_available():
          __UpperCAmelCase     :			Dict  							=      torch.npu.device_count()
          __UpperCAmelCase     :			Any  							=      num_npus
          __UpperCAmelCase     :			Any  							=      False
          if num_npus > 1:
               __UpperCAmelCase     :			Dict  							=      '''MULTI_NPU'''
          else:
               __UpperCAmelCase     :			Optional[int]  							=      '''NO'''
     else:
          __UpperCAmelCase     :			List[str]  							=      0
          __UpperCAmelCase     :			Dict  							=      True
          __UpperCAmelCase     :			Dict  							=      1
          __UpperCAmelCase     :			Tuple  							=      '''NO'''
     __UpperCAmelCase     :			List[Any]  							=      ClusterConfig(**_lowercase  )
     config.to_json_file(_lowercase  )
     return path




def      _a     (						_lowercase :     Union[str, Any]      , _lowercase :     str  ):





     '''simple docstring'''






     __UpperCAmelCase     :			Optional[int]  							=      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      _a     (						_lowercase :     List[Any]  ):





     '''simple docstring'''






     __UpperCAmelCase     :			str  							=      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 DebertaConfig, is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device

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


if is_torch_available():
      import torch

      from transformers import (
          DebertaForMaskedLM,
          DebertaForQuestionAnswering,
          DebertaForSequenceClassification,
          DebertaForTokenClassification,
          DebertaModel,
      )
      from transformers.models.deberta.modeling_deberta import DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST



class      a    (		_a	):


     """simple docstring"""






     def __init__(    self					:		Optional[Any]							,			snake_case					:		Dict							,			snake_case					:		Dict=13							,			snake_case					:		str=7							,			snake_case					:		Dict=True							,			snake_case					:		Any=True							,			snake_case					:		Optional[Any]=True							,			snake_case					:		Optional[Any]=True							,			snake_case					:		List[str]=99							,			snake_case					:		str=32							,			snake_case					:		Any=5							,			snake_case					:		List[str]=4							,			snake_case					:		List[str]=37							,			snake_case					:		int="gelu"							,			snake_case					:		int=0.1							,			snake_case					:		int=0.1							,			snake_case					:		Union[str, Any]=512							,			snake_case					:		int=16							,			snake_case					:		Optional[Any]=2							,			snake_case					:		List[Any]=0.02							,			snake_case					:		Any=False							,			snake_case					:		int=True							,			snake_case					:		Union[str, Any]="None"							,			snake_case					:		str=3							,			snake_case					:		Union[str, Any]=4							,			snake_case					:		Any=None							,			)						->							List[Any]:
          __UpperCAmelCase     :			List[str]  							=      parent
          __UpperCAmelCase     :			Dict  							=      batch_size
          __UpperCAmelCase     :			Any  							=      seq_length
          __UpperCAmelCase     :			List[Any]  							=      is_training
          __UpperCAmelCase     :			List[str]  							=      use_input_mask
          __UpperCAmelCase     :			Union[str, Any]  							=      use_token_type_ids
          __UpperCAmelCase     :			Any  							=      use_labels
          __UpperCAmelCase     :			Any  							=      vocab_size
          __UpperCAmelCase     :			Dict  							=      hidden_size
          __UpperCAmelCase     :			List[str]  							=      num_hidden_layers
          __UpperCAmelCase     :			Union[str, Any]  							=      num_attention_heads
          __UpperCAmelCase     :			List[str]  							=      intermediate_size
          __UpperCAmelCase     :			str  							=      hidden_act
          __UpperCAmelCase     :			Union[str, Any]  							=      hidden_dropout_prob
          __UpperCAmelCase     :			int  							=      attention_probs_dropout_prob
          __UpperCAmelCase     :			Tuple  							=      max_position_embeddings
          __UpperCAmelCase     :			Any  							=      type_vocab_size
          __UpperCAmelCase     :			Tuple  							=      type_sequence_label_size
          __UpperCAmelCase     :			Union[str, Any]  							=      initializer_range
          __UpperCAmelCase     :			Dict  							=      num_labels
          __UpperCAmelCase     :			Any  							=      num_choices
          __UpperCAmelCase     :			Any  							=      relative_attention
          __UpperCAmelCase     :			Dict  							=      position_biased_input
          __UpperCAmelCase     :			Optional[int]  							=      pos_att_type
          __UpperCAmelCase     :			Dict  							=      scope

     def 			lowerCamelCase__			(    self					:		Dict      )						->							Optional[int]:
          __UpperCAmelCase     :			int  							=      ids_tensor([self.batch_size, self.seq_length]							,			self.vocab_size      )

          __UpperCAmelCase     :			Optional[Any]  							=      None
          if self.use_input_mask:
               __UpperCAmelCase     :			str  							=      ids_tensor([self.batch_size, self.seq_length]							,			vocab_size=2      )

          __UpperCAmelCase     :			Any  							=      None
          if self.use_token_type_ids:
               __UpperCAmelCase     :			Dict  							=      ids_tensor([self.batch_size, self.seq_length]							,			self.type_vocab_size      )

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

          __UpperCAmelCase     :			str  							=      self.get_config()

          return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels

     def 			lowerCamelCase__			(    self					:		Tuple      )						->							List[str]:
          return DebertaConfig(
              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							,			type_vocab_size=self.type_vocab_size							,			initializer_range=self.initializer_range							,			relative_attention=self.relative_attention							,			position_biased_input=self.position_biased_input							,			pos_att_type=self.pos_att_type							,			)

     def 			lowerCamelCase__			(    self					:		Union[str, Any]      )						->							str:
          __UpperCAmelCase     :			Optional[int]  							=      self.get_config()
          __UpperCAmelCase     :			Dict  							=      300
          return config

     def 			lowerCamelCase__			(    self					:		Any							,			snake_case					:		int      )						->							Any:
          self.parent.assertListEqual(list(result.loss.size()      )							,			[]      )

     def 			lowerCamelCase__			(    self					:		List[Any]							,			snake_case					:		Optional[int]							,			snake_case					:		Any							,			snake_case					:		List[Any]							,			snake_case					:		Any							,			snake_case					:		Union[str, Any]							,			snake_case					:		Optional[Any]							,			snake_case					:		Union[str, Any]      )						->							Optional[Any]:
          __UpperCAmelCase     :			List[str]  							=      DebertaModel(config=snake_case      )
          model.to(snake_case      )
          model.eval()
          __UpperCAmelCase     :			str  							=      model(snake_case							,			attention_mask=snake_case							,			token_type_ids=snake_case      )[0]
          __UpperCAmelCase     :			Tuple  							=      model(snake_case							,			token_type_ids=snake_case      )[0]
          __UpperCAmelCase     :			Optional[int]  							=      model(snake_case      )[0]

          self.parent.assertListEqual(list(sequence_output.size()      )							,			[self.batch_size, self.seq_length, self.hidden_size]      )

     def 			lowerCamelCase__			(    self					:		Optional[int]							,			snake_case					:		int							,			snake_case					:		Tuple							,			snake_case					:		Any							,			snake_case					:		Tuple							,			snake_case					:		Union[str, Any]							,			snake_case					:		Optional[int]							,			snake_case					:		List[str]      )						->							Optional[int]:
          __UpperCAmelCase     :			Union[str, Any]  							=      DebertaForMaskedLM(config=snake_case      )
          model.to(snake_case      )
          model.eval()
          __UpperCAmelCase     :			int  							=      model(snake_case							,			attention_mask=snake_case							,			token_type_ids=snake_case							,			labels=snake_case      )

          self.parent.assertEqual(result.logits.shape							,			(self.batch_size, self.seq_length, self.vocab_size)      )

     def 			lowerCamelCase__			(    self					:		str							,			snake_case					:		Union[str, Any]							,			snake_case					:		Tuple							,			snake_case					:		Optional[Any]							,			snake_case					:		Tuple							,			snake_case					:		List[Any]							,			snake_case					:		str							,			snake_case					:		Tuple      )						->							Union[str, Any]:
          __UpperCAmelCase     :			Tuple  							=      self.num_labels
          __UpperCAmelCase     :			List[Any]  							=      DebertaForSequenceClassification(snake_case      )
          model.to(snake_case      )
          model.eval()
          __UpperCAmelCase     :			Any  							=      model(snake_case							,			attention_mask=snake_case							,			token_type_ids=snake_case							,			labels=snake_case      )
          self.parent.assertListEqual(list(result.logits.size()      )							,			[self.batch_size, self.num_labels]      )
          self.check_loss_output(snake_case      )

     def 			lowerCamelCase__			(    self					:		str							,			snake_case					:		List[str]							,			snake_case					:		Union[str, Any]							,			snake_case					:		List[str]							,			snake_case					:		Dict							,			snake_case					:		Optional[Any]							,			snake_case					:		Dict							,			snake_case					:		Optional[int]      )						->							int:
          __UpperCAmelCase     :			List[Any]  							=      self.num_labels
          __UpperCAmelCase     :			Union[str, Any]  							=      DebertaForTokenClassification(config=snake_case      )
          model.to(snake_case      )
          model.eval()
          __UpperCAmelCase     :			Any  							=      model(snake_case							,			attention_mask=snake_case							,			token_type_ids=snake_case							,			labels=snake_case      )
          self.parent.assertEqual(result.logits.shape							,			(self.batch_size, self.seq_length, self.num_labels)      )

     def 			lowerCamelCase__			(    self					:		str							,			snake_case					:		List[Any]							,			snake_case					:		Optional[Any]							,			snake_case					:		str							,			snake_case					:		Optional[int]							,			snake_case					:		int							,			snake_case					:		int							,			snake_case					:		str      )						->							Union[str, Any]:
          __UpperCAmelCase     :			Union[str, Any]  							=      DebertaForQuestionAnswering(config=snake_case      )
          model.to(snake_case      )
          model.eval()
          __UpperCAmelCase     :			Optional[int]  							=      model(
              snake_case							,			attention_mask=snake_case							,			token_type_ids=snake_case							,			start_positions=snake_case							,			end_positions=snake_case							,			)
          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 			lowerCamelCase__			(    self					:		str      )						->							int:
          __UpperCAmelCase     :			int  							=      self.prepare_config_and_inputs()
          (
              (
              __UpperCAmelCase
          )							,       (
              __UpperCAmelCase
          )							,       (
              __UpperCAmelCase
          )							,       (
              __UpperCAmelCase
          )							,       (
              __UpperCAmelCase
          )							,       (
              __UpperCAmelCase
          )							,       (
              __UpperCAmelCase
          )							,       
          )     :			Any  							=      config_and_inputs
          __UpperCAmelCase     :			str  							=      {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
          return config, inputs_dict



@require_torch
class      a    (		_a     ,  _a     ,  unittest.TestCase	):


     """simple docstring"""






     SCREAMING_SNAKE_CASE	:			Optional[int]							       =       (
         (
             DebertaModel,
             DebertaForMaskedLM,
             DebertaForSequenceClassification,
             DebertaForTokenClassification,
             DebertaForQuestionAnswering,
         )
         if is_torch_available()
         else ()
     )
     SCREAMING_SNAKE_CASE	:			Dict							       =       (
         {
             "feature-extraction": DebertaModel,
             "fill-mask": DebertaForMaskedLM,
             "question-answering": DebertaForQuestionAnswering,
             "text-classification": DebertaForSequenceClassification,
             "token-classification": DebertaForTokenClassification,
             "zero-shot": DebertaForSequenceClassification,
         }
         if is_torch_available()
         else {}
     )

     SCREAMING_SNAKE_CASE	:			Union[str, Any]							       =       True
     SCREAMING_SNAKE_CASE	:			Dict							       =       False
     SCREAMING_SNAKE_CASE	:			List[Any]							       =       False
     SCREAMING_SNAKE_CASE	:			List[str]							       =       False
     SCREAMING_SNAKE_CASE	:			Any							       =       False

     def 			lowerCamelCase__			(    self					:		Union[str, Any]      )						->							Union[str, Any]:
          __UpperCAmelCase     :			Dict  							=      DebertaModelTester(self      )
          __UpperCAmelCase     :			List[Any]  							=      ConfigTester(self							,			config_class=snake_case							,			hidden_size=37      )

     def 			lowerCamelCase__			(    self					:		Optional[int]      )						->							Dict:
          self.config_tester.run_common_tests()

     def 			lowerCamelCase__			(    self					:		List[str]      )						->							Optional[Any]:
          __UpperCAmelCase     :			Any  							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_deberta_model(*snake_case      )

     def 			lowerCamelCase__			(    self					:		Dict      )						->							List[str]:
          __UpperCAmelCase     :			Tuple  							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_deberta_for_sequence_classification(*snake_case      )

     def 			lowerCamelCase__			(    self					:		Dict      )						->							str:
          __UpperCAmelCase     :			Any  							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_deberta_for_masked_lm(*snake_case      )

     def 			lowerCamelCase__			(    self					:		Union[str, Any]      )						->							Any:
          __UpperCAmelCase     :			Optional[int]  							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_deberta_for_question_answering(*snake_case      )

     def 			lowerCamelCase__			(    self					:		Dict      )						->							Optional[Any]:
          __UpperCAmelCase     :			Any  							=      self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_deberta_for_token_classification(*snake_case      )






     @slow
     def 			lowerCamelCase__			(    self					:		Dict      )						->							Tuple:
          for model_name in DEBERTA_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               __UpperCAmelCase     :			str  							=      DebertaModel.from_pretrained(snake_case      )
               self.assertIsNotNone(snake_case      )



@require_torch
@require_sentencepiece
@require_tokenizers
class      a    (		unittest.TestCase	):


     """simple docstring"""






     @unittest.skip(reason='''Model not available yet'''      )
     def 			lowerCamelCase__			(    self					:		Dict      )						->							Tuple:
          pass






     @slow
     def 			lowerCamelCase__			(    self					:		int      )						->							Optional[Any]:
          __UpperCAmelCase     :			Any  							=      DebertaModel.from_pretrained('''microsoft/deberta-base'''      )

          __UpperCAmelCase     :			Any  							=      torch.tensor([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]]      )
          __UpperCAmelCase     :			Dict  							=      torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]      )
          with torch.no_grad():
               __UpperCAmelCase     :			int  							=      model(snake_case							,			attention_mask=snake_case      )[0]
          # compare the actual values for a slice.
          __UpperCAmelCase     :			Optional[Any]  							=      torch.tensor(
              [[[-0.5_986, -0.8_055, -0.8_462], [1.4_484, -0.9_348, -0.8_059], [0.3_123, 0.0_032, -1.4_131]]]      )
          self.assertTrue(torch.allclose(output[:, 1:4, 1:4]							,			snake_case							,			atol=1E-4      )							,			f'{output[:, 1:4, 1:4]}'      )