


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     UpperCAmelCase__       (					unittest.TestCase		):



    """simple docstring"""






    def _a					(			self					,   A_					,   A_					,   A_ = None					,   A_ = None    )  ->       Optional[Any]:
         __UpperCamelCase    							=None
         __UpperCamelCase    							=os.path.abspath(os.path.join('examples'					,   'by_feature'    )    )
         __UpperCamelCase    							=os.path.abspath('examples'    )
         for item in os.listdir(A_    ):
              if item not in EXCLUDE_EXAMPLES:
                   __UpperCamelCase    							=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()'					,   ):
                             __UpperCamelCase    							=compare_against_test(
                                 os.path.join(A_					,   A_    )					,   A_					,   A_					,   A_    )
                             __UpperCamelCase    							='\n'.join(A_    )
                             if special_strings is not None:
                                  for string in special_strings:
                                       __UpperCamelCase    							=diff.replace(A_					,   ''    )
                             self.assertEqual(A_					,   ''    )






    def _a					(			self    )  ->       Dict:
         self.one_complete_example('complete_nlp_example.py'					,   A_    )
         self.one_complete_example('complete_nlp_example.py'					,   A_    )






    def _a					(			self    )  ->       Dict:
         __UpperCamelCase    							=os.path.abspath(os.path.join('examples'					,   'cv_example.py'    )    )
         __UpperCamelCase    							=[
             ' ' * 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     UpperCAmelCase__       (					A_		):



    """simple docstring"""






    UpperCAmelCase__						:		Tuple      =  False






    @classmethod
    def _a					(			cls    )  ->       Union[str, Any]:
         super().setUpClass()
         __UpperCamelCase    							=tempfile.mkdtemp()
         __UpperCamelCase    							=os.path.join(cls._tmpdir					,   'default_config.yml'    )

         write_basic_config(save_location=cls.configPath    )
         __UpperCamelCase    							=['accelerate', 'launch', '--config_file', cls.configPath]






    @classmethod
    def _a					(			cls    )  ->       Union[str, Any]:
         super().tearDownClass()
         shutil.rmtree(cls._tmpdir    )






    def _a					(			self    )  ->       List[Any]:
         __UpperCamelCase    							=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 _a					(			self    )  ->       Union[str, Any]:
         __UpperCamelCase    							=f'\n        examples/by_feature/checkpointing.py\n        --checkpointing_steps 1\n        --output_dir {self.tmpdir}\n        '.split()
         __UpperCamelCase    							=run_command(self._launch_args + testargs    )
         self.assertTrue(os.path.exists(os.path.join(self.tmpdir					,   'step_2'    )    )    )






    def _a					(			self    )  ->       Tuple:
         __UpperCamelCase    							=f'\n        examples/by_feature/checkpointing.py\n        --resume_from_checkpoint {os.path.join(self.tmpdir					,   "epoch_0"    )}\n        '.split()
         __UpperCamelCase    							=run_command(self._launch_args + testargs					,   return_stdout=A_    )
         self.assertNotIn('epoch 0:'					,   A_    )
         self.assertIn('epoch 1:'					,   A_    )






    def _a					(			self    )  ->       int:
         __UpperCamelCase    							=f'\n        examples/by_feature/checkpointing.py\n        --resume_from_checkpoint {os.path.join(self.tmpdir					,   "step_2"    )}\n        '.split()
         __UpperCamelCase    							=run_command(self._launch_args + testargs					,   return_stdout=A_    )
         if torch.cuda.is_available():
              __UpperCamelCase    							=torch.cuda.device_count()
         else:
              __UpperCamelCase    							=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 _a					(			self    )  ->       Optional[Any]:
         __UpperCamelCase    							='\n        examples/by_feature/cross_validation.py\n        --num_folds 2\n        '.split()
         with mock.patch.dict(os.environ					,   {'TESTING_MOCKED_DATALOADERS': '0'}    ):
              __UpperCamelCase    							=run_command(self._launch_args + testargs					,   return_stdout=A_    )
              __UpperCamelCase    							=re.findall('({.+})'					,   A_    )
              __UpperCamelCase    							=[r for r in results if 'accuracy' in r][-1]
              __UpperCamelCase    							=ast.literal_eval(A_    )
              self.assertGreaterEqual(results['accuracy']					,   0.75    )






    def _a					(			self    )  ->       str:
         __UpperCamelCase    							=['examples/by_feature/multi_process_metrics.py']
         run_command(self._launch_args + testargs    )






    @require_trackers
    @mock.patch.dict(os.environ					,   {'WANDB_MODE': 'offline'}    )
    def _a					(			self    )  ->       List[str]:
         with tempfile.TemporaryDirectory() as tmpdir:
              __UpperCamelCase    							=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 _a					(			self    )  ->       Optional[int]:
         __UpperCamelCase    							=['examples/by_feature/gradient_accumulation.py']
         run_command(self._launch_args + testargs    )






    def _a					(			self    )  ->       List[Any]:
         __UpperCamelCase    							=['examples/by_feature/local_sgd.py']
         run_command(self._launch_args + testargs    )









import os
import unittest

from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer

from ...test_tokenization_common import TokenizerTesterMixin






class     UpperCAmelCase__       (					A_   ,  unittest.TestCase		):



    """simple docstring"""






    UpperCAmelCase__						:		Tuple      =  TransfoXLTokenizer
    UpperCAmelCase__						:		str      =  False
    UpperCAmelCase__						:		Tuple      =  False






    def _a					(			self    )  ->       Union[str, Any]:
         super().setUp()

         __UpperCamelCase    							=[
             '<unk>',
             '[CLS]',
             '[SEP]',
             'want',
             'unwanted',
             'wa',
             'un',
             'running',
             ',',
             'low',
             'l',
         ]
         __UpperCamelCase    							=os.path.join(self.tmpdirname					,   VOCAB_FILES_NAMES['vocab_file']    )
         with open(self.vocab_file					,   'w'					,   encoding='utf-8'    ) as vocab_writer:
              vocab_writer.write(''.join([x + '\n' for x in vocab_tokens]    )    )






    def _a					(			self					,   **A_    )  ->       Optional[int]:
         __UpperCamelCase    							=True
         return TransfoXLTokenizer.from_pretrained(self.tmpdirname					,   **A_    )






    def _a					(			self					,   A_    )  ->       Tuple:
         __UpperCamelCase    							='<unk> UNwanted , running'
         __UpperCamelCase    							='<unk> unwanted, running'
         return input_text, output_text






    def _a					(			self    )  ->       str:
         __UpperCamelCase    							=TransfoXLTokenizer(vocab_file=self.vocab_file					,   lower_case=A_    )

         __UpperCamelCase    							=tokenizer.tokenize('<unk> UNwanted , running'    )
         self.assertListEqual(A_					,   ['<unk>', 'unwanted', ',', 'running']    )

         self.assertListEqual(tokenizer.convert_tokens_to_ids(A_    )					,   [0, 4, 8, 7]    )






    def _a					(			self    )  ->       Any:
         __UpperCamelCase    							=TransfoXLTokenizer(lower_case=A_    )

         self.assertListEqual(
             tokenizer.tokenize(' \tHeLLo ! how  \n Are yoU ?  '    )					,   ['hello', '!', 'how', 'are', 'you', '?']    )






    def _a					(			self    )  ->       Optional[int]:
         __UpperCamelCase    							=TransfoXLTokenizer(lower_case=A_    )

         self.assertListEqual(
             tokenizer.tokenize(' \tHeLLo ! how  \n Are yoU ?  '    )					,   ['HeLLo', '!', 'how', 'Are', 'yoU', '?']    )






    def _a					(			self    )  ->       int:
         __UpperCamelCase    							=TransfoXLTokenizer(lower_case=A_    )
         __UpperCamelCase    							='Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?'
         __UpperCamelCase    							=[
             'Hello',
             '(',
             'bracket',
             ')',
             'and',
             'side',
             '@-@',
             'scrolled',
             '[',
             'and',
             ']',
             'Henry',
             '\'s',
             '$',
             '5',
             '@,@',
             '000',
             'with',
             '3',
             '@.@',
             '34',
             'm',
             '.',
             'What',
             '\'s',
             'up',
             '!',
             '?',
         ]

         self.assertListEqual(tokenizer.tokenize(A_    )					,   A_    )

         self.assertEqual(tokenizer.convert_tokens_to_string(A_    )					,   A_    )






    def _a					(			self    )  ->       Optional[int]:
         __UpperCamelCase    							=self.get_tokenizer()
         __UpperCamelCase    							=len(A_    )

         tokenizer.add_tokens(['new1', 'new2']    )
         tokenizer.move_added_token('new1'					,   1    )

         # Check that moved token is not copied (duplicate)
         self.assertEqual(len(A_    )					,   original_len + 2    )
         # Check that token is moved to specified id
         self.assertEqual(tokenizer.encode('new1'    )					,   [1]    )
         self.assertEqual(tokenizer.decode([1]    )					,   'new1'    )





