




"""simple docstring"""


import ast
import os
import re
import shutil
import tempfile
import unittest
from unittest import mock

import torch

from accelerate.test_utils.examples import compare_against_test
from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow
from accelerate.utils import write_basic_config


# DataLoaders built from `test_samples/MRPC` for quick testing
# Should mock `{script_name}.get_dataloaders` via:
# @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders)

A_      			=       [
    '''cross_validation.py''',
    '''gradient_accumulation.py''',
    '''local_sgd.py''',
    '''multi_process_metrics.py''',
    '''memory.py''',
    '''automatic_gradient_accumulation.py''',
    '''fsdp_with_peak_mem_tracking.py''',
    '''deepspeed_with_config_support.py''',
    '''megatron_lm_gpt_pretraining.py''',
]






class       lowercase(  unittest.TestCase				):







 '''simple docstring'''





 def 				UpperCamelCase_     (       self:	List[Any],   a_:	str,   a_:	bool,   a_:	str = None,   a_:	list = None	):




   '''simple docstring'''



   _snake_case							:	List[Any]			=						None
   _snake_case							:	Union[str, Any]			=						os.path.abspath(os.path.join("""examples""",   """by_feature"""	)	)
   _snake_case							:	List[Any]			=						os.path.abspath("""examples"""	)
   for item in os.listdir(a_	):
     if item not in EXCLUDE_EXAMPLES:
       _snake_case							:	List[Any]			=						os.path.join(a_,   a_	)
       if os.path.isfile(a_	) and ".py" in item_path:
         with self.subTest(
             tested_script=a_,   feature_script=a_,   tested_section="""main()""" if parser_only else """training_function()""",   ):
           _snake_case							:	Dict			=						compare_against_test(
               os.path.join(a_,   a_	),   a_,   a_,   a_	)
           _snake_case							:	Any			=						"""\n""".join(a_	)
           if special_strings is not None:
             for string in special_strings:
               _snake_case							:	int			=						diff.replace(a_,   """"""	)
           self.assertEqual(a_,   """"""	)


 def 				UpperCamelCase_     (       self:	List[Any]	):




   '''simple docstring'''



   self.one_complete_example("""complete_nlp_example.py""",   a_	)
   self.one_complete_example("""complete_nlp_example.py""",   a_	)


 def 				UpperCamelCase_     (       self:	int	):




   '''simple docstring'''



   _snake_case							:	List[str]			=						os.path.abspath(os.path.join("""examples""",   """cv_example.py"""	)	)
   _snake_case							:	Optional[Any]			=						[
       """ """ * 16 + """{\n\n""",
       """ """ * 20 + """\"accuracy\": eval_metric[\"accuracy\"],\n\n""",
       """ """ * 20 + """\"f1\": eval_metric[\"f1\"],\n\n""",
       """ """ * 20 + """\"train_loss\": total_loss.item() / len(train_dataloader),\n\n""",
       """ """ * 20 + """\"epoch\": epoch,\n\n""",
       """ """ * 16 + """},\n\n""",
       """ """ * 16 + """step=epoch,\n""",
       """ """ * 12,
       """ """ * 8 + """for step, batch in enumerate(active_dataloader):\n""",
   ]
   self.one_complete_example("""complete_cv_example.py""",   a_,   a_,   a_	)
   self.one_complete_example("""complete_cv_example.py""",   a_,   a_,   a_	)







@mock.patch.dict(os.environ ,    {"TESTING_MOCKED_DATALOADERS": "1"}				)
class       lowercase(  __a				):







 '''simple docstring'''





 lowercase__				      =      False


 @classmethod
 def 				UpperCamelCase_     (       cls:	Any	):




   '''simple docstring'''



   super().setUpClass()
   _snake_case							:	int			=						tempfile.mkdtemp()
   _snake_case							:	Any			=						os.path.join(cls._tmpdir,   """default_config.yml"""	)

   write_basic_config(save_location=cls.configPath	)
   _snake_case							:	Any			=						["""accelerate""", """launch""", """--config_file""", cls.configPath]


 @classmethod
 def 				UpperCamelCase_     (       cls:	Dict	):




   '''simple docstring'''



   super().tearDownClass()
   shutil.rmtree(cls._tmpdir	)


 def 				UpperCamelCase_     (       self:	Any	):




   '''simple docstring'''



   _snake_case							:	Optional[Any]			=						f"\n        examples/by_feature/checkpointing.py\n        --checkpointing_steps epoch\n        --output_dir {self.tmpdir}\n        ".split()
   run_command(self._launch_args + testargs	)
   self.assertTrue(os.path.exists(os.path.join(self.tmpdir,   """epoch_0"""	)	)	)


 def 				UpperCamelCase_     (       self:	Union[str, Any]	):




   '''simple docstring'''



   _snake_case							:	Optional[Any]			=						f"\n        examples/by_feature/checkpointing.py\n        --checkpointing_steps 1\n        --output_dir {self.tmpdir}\n        ".split()
   _snake_case							:	List[str]			=						run_command(self._launch_args + testargs	)
   self.assertTrue(os.path.exists(os.path.join(self.tmpdir,   """step_2"""	)	)	)


 def 				UpperCamelCase_     (       self:	List[str]	):




   '''simple docstring'''



   _snake_case							:	str			=						f"\n        examples/by_feature/checkpointing.py\n        --resume_from_checkpoint {os.path.join(self.tmpdir,   'epoch_0'	)}\n        ".split()
   _snake_case							:	Optional[Any]			=						run_command(self._launch_args + testargs,   return_stdout=a_	)
   self.assertNotIn("""epoch 0:""",   a_	)
   self.assertIn("""epoch 1:""",   a_	)


 def 				UpperCamelCase_     (       self:	List[Any]	):




   '''simple docstring'''



   _snake_case							:	List[Any]			=						f"\n        examples/by_feature/checkpointing.py\n        --resume_from_checkpoint {os.path.join(self.tmpdir,   'step_2'	)}\n        ".split()
   _snake_case							:	Dict			=						run_command(self._launch_args + testargs,   return_stdout=a_	)
   if torch.cuda.is_available():
     _snake_case							:	Dict			=						torch.cuda.device_count()
   else:
     _snake_case							:	Optional[Any]			=						1
   if num_processes > 1:
     self.assertNotIn("""epoch 0:""",   a_	)
     self.assertIn("""epoch 1:""",   a_	)
   else:
     self.assertIn("""epoch 0:""",   a_	)
     self.assertIn("""epoch 1:""",   a_	)


 @slow
 def 				UpperCamelCase_     (       self:	Optional[Any]	):




   '''simple docstring'''



   _snake_case							:	Union[str, Any]			=						"""
        examples/by_feature/cross_validation.py
        --num_folds 2
        """.split()
   with mock.patch.dict(os.environ,   {"""TESTING_MOCKED_DATALOADERS""": """0"""}	):
     _snake_case							:	Optional[int]			=						run_command(self._launch_args + testargs,   return_stdout=a_	)
     _snake_case							:	List[Any]			=						re.findall("""({.+})""",   a_	)
     _snake_case							:	List[Any]			=						[r for r in results if """accuracy""" in r][-1]
     _snake_case							:	List[Any]			=						ast.literal_eval(a_	)
     self.assertGreaterEqual(results["""accuracy"""],   0.75	)


 def 				UpperCamelCase_     (       self:	List[Any]	):




   '''simple docstring'''



   _snake_case							:	List[Any]			=						["""examples/by_feature/multi_process_metrics.py"""]
   run_command(self._launch_args + testargs	)


 @require_trackers
 @mock.patch.dict(os.environ,   {"""WANDB_MODE""": """offline"""}	)
 def 				UpperCamelCase_     (       self:	List[Any]	):




   '''simple docstring'''



   with tempfile.TemporaryDirectory() as tmpdir:
     _snake_case							:	Dict			=						f"\n            examples/by_feature/tracking.py\n            --with_tracking\n            --project_dir {tmpdir}\n            ".split()
     run_command(self._launch_args + testargs	)
     self.assertTrue(os.path.exists(os.path.join(a_,   """tracking"""	)	)	)


 def 				UpperCamelCase_     (       self:	Optional[int]	):




   '''simple docstring'''



   _snake_case							:	Optional[Any]			=						["""examples/by_feature/gradient_accumulation.py"""]
   run_command(self._launch_args + testargs	)


 def 				UpperCamelCase_     (       self:	int	):




   '''simple docstring'''



   _snake_case							:	Any			=						["""examples/by_feature/local_sgd.py"""]
   run_command(self._launch_args + testargs	)








"""simple docstring"""


from typing import Any


def       UpperCAmelCase__ (snake_case__							:      list					):
  """simple docstring"""

  if not input_list:
    return []
  _snake_case							:	List[Any]			=						[input_list.count(snake_case__					) for value in input_list]
  _snake_case							:	Optional[int]			=						max(snake_case__					)  # Gets the maximum count in the input list.
  # Gets values of modes
  return sorted({input_list[i] for i, value in enumerate(snake_case__					) if value == y}					)


if __name__ == "__main__":
     import doctest

     doctest.testmod()


