


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 math
import time
from typing import Dict, List, Optional

from torch.utils.data import Dataset

from transformers import SeqaSeqTrainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
			import torch_xla.core.xla_model as xm
			import torch_xla.debug.metrics as met




class     _SCREAMING_SNAKE_CASE     (      snake_case_						):



	def __init__(    self						,  *lowercase						,  lowercase=None						,  lowercase=None						,  **lowercase )				->       List[str]:
					super().__init__(*lowercase						,  **lowercase )
					lowerCamelCase_						=			eval_examples
					lowerCamelCase_						=			post_process_function



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase = None						,  lowercase=None						,  lowercase = None						,  lowercase = "eval"						,  **lowercase						,  )				->       Dict[str, float]:
					lowerCamelCase_						=			gen_kwargs.copy()
					lowerCamelCase_						=			(
					    gen_kwargs["max_length"] if gen_kwargs.get("max_length" ) is not None else self.args.generation_max_length
					)
					lowerCamelCase_						=			(
					    gen_kwargs["num_beams"] if gen_kwargs.get("num_beams" ) is not None else self.args.generation_num_beams
					)
					lowerCamelCase_						=			gen_kwargs

					lowerCamelCase_						=			self.eval_dataset if eval_dataset is None else eval_dataset
					lowerCamelCase_						=			self.get_eval_dataloader(lowercase )
					lowerCamelCase_						=			self.eval_examples if eval_examples is None else eval_examples

					# Temporarily disable metric computation, we will do it in the loop here.
					lowerCamelCase_						=			self.compute_metrics
					lowerCamelCase_						=			None
					lowerCamelCase_						=			time.time()
					lowerCamelCase_						=			self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
					try:
									lowerCamelCase_						=			eval_loop(
									    lowercase						,  description="Evaluation"						,  prediction_loss_only=True if compute_metrics is None else None						,  ignore_keys=lowercase						,  metric_key_prefix=lowercase						,  )
					finally:
									lowerCamelCase_						=			compute_metrics
					lowerCamelCase_						=			self.args.eval_batch_size * self.args.world_size
					if f'{metric_key_prefix}_jit_compilation_time' in output.metrics:
									start_time += output.metrics[f'{metric_key_prefix}_jit_compilation_time']
					output.metrics.update(
					    speed_metrics(
					        lowercase						,  lowercase						,  num_samples=output.num_samples						,  num_steps=math.ceil(output.num_samples / total_batch_size )						,  ) )

					if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
									# Only the main node write the results by default
									lowerCamelCase_						=			self.post_process_function(lowercase						,  lowercase						,  lowercase )
									lowerCamelCase_						=			self.compute_metrics(lowercase )

									# Prefix all keys with metric_key_prefix + '_'
									for key in list(metrics.keys() ):
													if not key.startswith(f'{metric_key_prefix}_' ):
																	lowerCamelCase_						=			metrics.pop(lowercase )

									metrics.update(output.metrics )
					else:
									lowerCamelCase_						=			output.metrics

					if self.args.should_log:
									# Only the main node log the results by default
									self.log(lowercase )

					if self.args.tpu_metrics_debug or self.args.debug:
									# tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
									xm.master_print(met.metrics_report() )

					lowerCamelCase_						=			self.callback_handler.on_evaluate(self.args						,  self.state						,  self.control						,  lowercase )
					return metrics



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase						,  lowercase						,  lowercase=None						,  lowercase = "test"						,  **lowercase )				->       Union[str, Any]:
					lowerCamelCase_						=			gen_kwargs.copy()

					lowerCamelCase_						=			self.get_test_dataloader(lowercase )

					# Temporarily disable metric computation, we will do it in the loop here.
					lowerCamelCase_						=			self.compute_metrics
					lowerCamelCase_						=			None
					lowerCamelCase_						=			time.time()
					lowerCamelCase_						=			self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
					try:
									lowerCamelCase_						=			eval_loop(
									    lowercase						,  description="Prediction"						,  prediction_loss_only=True if compute_metrics is None else None						,  ignore_keys=lowercase						,  metric_key_prefix=lowercase						,  )
					finally:
									lowerCamelCase_						=			compute_metrics

					lowerCamelCase_						=			self.args.eval_batch_size * self.args.world_size
					if f'{metric_key_prefix}_jit_compilation_time' in output.metrics:
									start_time += output.metrics[f'{metric_key_prefix}_jit_compilation_time']
					output.metrics.update(
					    speed_metrics(
					        lowercase						,  lowercase						,  num_samples=output.num_samples						,  num_steps=math.ceil(output.num_samples / total_batch_size )						,  ) )
					if self.post_process_function is None or self.compute_metrics is None:
									return output

					lowerCamelCase_						=			self.post_process_function(lowercase						,  lowercase						,  lowercase						,  "predict" )
					lowerCamelCase_						=			self.compute_metrics(lowercase )

					# Prefix all keys with metric_key_prefix + '_'
					for key in list(metrics.keys() ):
									if not key.startswith(f'{metric_key_prefix}_' ):
													lowerCamelCase_						=			metrics.pop(lowercase )
					metrics.update(output.metrics )
					return PredictionOutput(predictions=predictions.predictions						,  label_ids=predictions.label_ids						,  metrics=lowercase )


