'''simple docstring'''





# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import os

from accelerate.utils import ComputeEnvironment

from .cluster import get_cluster_input
from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file  # noqa: F401
from .config_utils import _ask_field, _ask_options, _convert_compute_environment  # noqa: F401
from .sagemaker import get_sagemaker_input


SCREAMING_SNAKE_CASE_:	int    ='Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine'





def       lowerCAmelCase_							(   )       -> Optional[int]:


     '''simple docstring'''




     UpperCAmelCase_			       =  _ask_options(
         "In which compute environment are you running?"   ,       ["This machine", "AWS (Amazon SageMaker)"]   ,       _convert_compute_environment   ,       )
     if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
          UpperCAmelCase_			       =  get_sagemaker_input()
     else:
          UpperCAmelCase_			       =  get_cluster_input()
     return config





def       lowerCAmelCase_							(   snake_case_			:					Union[str, Any]=None     )       -> Optional[int]:


     '''simple docstring'''




     if subparsers is not None:
          UpperCAmelCase_			       =  subparsers.add_parser("config"   ,       description=snake_case_     )
     else:
          UpperCAmelCase_			       =  argparse.ArgumentParser("Accelerate config command"   ,       description=snake_case_     )

     parser.add_argument(
         "--config_file"   ,       default=snake_case_   ,       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'."
         )   ,       )

     if subparsers is not None:
          parser.set_defaults(func=snake_case_     )
     return parser





def       lowerCAmelCase_							(   snake_case_			:					Optional[int]     )       -> Dict:


     '''simple docstring'''




     UpperCAmelCase_			       =  get_user_input()
     if args.config_file is not None:
          UpperCAmelCase_			       =  args.config_file
     else:
          if not os.path.isdir(snake_case_     ):
               os.makedirs(snake_case_     )
          UpperCAmelCase_			       =  default_yaml_config_file

     if config_file.endswith(".json"     ):
          config.to_json_file(snake_case_     )
     else:
          config.to_yaml_file(snake_case_     )
     print(f"""accelerate configuration saved at {config_file}"""     )





def       lowerCAmelCase_							(   )       -> Any:


     '''simple docstring'''




     UpperCAmelCase_			       =  config_command_parser()
     UpperCAmelCase_			       =  parser.parse_args()
     config_command(snake_case_     )


if __name__ == "__main__":
    main()









import argparse
import logging
import sys
from unittest.mock import patch

import run_glue_deebert

from transformers.testing_utils import TestCasePlus, get_gpu_count, require_torch_non_multi_gpu, slow


logging.basicConfig(level=logging.DEBUG)

a__   :					Optional[Any] 						=      logging.getLogger()

def 	_lowerCAmelCase (    ):
      lowercase__  =	argparse.ArgumentParser()
      parser.add_argument('-f'						)
      lowercase__  =	parser.parse_args()
      return args.f



class    UpperCAmelCase__(				lowerCamelCase						):

   '''simple docstring'''




   def       UpperCAmelCase		(    self	:      List[str])						->					None:




         """simple docstring"""

         lowercase__  =	logging.StreamHandler(sys.stdout)
         logger.addHandler(lowerCAmelCase)


   def       UpperCAmelCase		(    self	:      List[str]      ,					lowerCAmelCase	:      Union[str, Any])						->					List[Any]:




         """simple docstring"""

         lowercase__  =	get_gpu_count()

         if n_gpu > 1:
               pass
               # XXX: doesn't quite work with n_gpu > 1 https://github.com/huggingface/transformers/issues/10560
               # script = f"{self.examples_dir_str}/research_projects/deebert/run_glue_deebert.py"
               # distributed_args = f"-m torch.distributed.launch --nproc_per_node={n_gpu} {script}".split()
               # cmd = [sys.executable] + distributed_args + args
               # execute_subprocess_async(cmd, env=self.get_env())
               # XXX: test the results - need to save them first into .json file
         else:
               args.insert(0      ,					'run_glue_deebert.py')
               with patch.object(lowerCAmelCase      ,					'argv'      ,					lowerCAmelCase):
                     lowercase__  =	run_glue_deebert.main()
                     for value in result.values():
                           self.assertGreaterEqual(lowerCAmelCase      ,					0.6_66)



   @slow
   @require_torch_non_multi_gpu
   def       UpperCAmelCase		(    self	:      Optional[Any])						->					Union[str, Any]:




         """simple docstring"""

         lowercase__  =	'\n            --model_type roberta\n            --model_name_or_path roberta-base\n            --task_name MRPC\n            --do_train\n            --do_eval\n            --do_lower_case\n            --data_dir ./tests/fixtures/tests_samples/MRPC/\n            --max_seq_length 128\n            --per_gpu_eval_batch_size=1\n            --per_gpu_train_batch_size=8\n            --learning_rate 2e-4\n            --num_train_epochs 3\n            --overwrite_output_dir\n            --seed 42\n            --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n            --plot_data_dir ./examples/deebert/results/\n            --save_steps 0\n            --overwrite_cache\n            --eval_after_first_stage\n            '.split()
         self.run_and_check(lowerCAmelCase)

         lowercase__  =	'\n            --model_type roberta\n            --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n            --task_name MRPC\n            --do_eval\n            --do_lower_case\n            --data_dir ./tests/fixtures/tests_samples/MRPC/\n            --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n            --plot_data_dir ./examples/deebert/results/\n            --max_seq_length 128\n            --eval_each_highway\n            --eval_highway\n            --overwrite_cache\n            --per_gpu_eval_batch_size=1\n            '.split()
         self.run_and_check(lowerCAmelCase)

         lowercase__  =	'\n            --model_type roberta\n            --model_name_or_path ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n            --task_name MRPC\n            --do_eval\n            --do_lower_case\n            --data_dir ./tests/fixtures/tests_samples/MRPC/\n            --output_dir ./examples/deebert/saved_models/roberta-base/MRPC/two_stage\n            --plot_data_dir ./examples/deebert/results/\n            --max_seq_length 128\n            --early_exit_entropy 0.1\n            --eval_highway\n            --overwrite_cache\n            --per_gpu_eval_batch_size=1\n            '.split()
         self.run_and_check(lowerCAmelCase)
