'''simple docstring'''






# XXX: we want transformers master here - in the absense of conftest manipulating sys.path:
# hack it in for now:
import sys
from pathlib import Path


__a										=					Path(__file__).resolve().parents[3] / '''src'''
sys.path.insert(1, str(git_repo_path))

import dataclasses  # noqa
import io  # noqa
import itertools  # noqa
import json  # noqa
import os  # noqa
import unittest  # noqa
from copy import deepcopy  # noqa

from parameterized import parameterized  # noqa
from transformers import TrainingArguments, is_torch_available  # noqa
from transformers.deepspeed import is_deepspeed_available  # noqa
from transformers.file_utils import WEIGHTS_NAME  # noqa
from transformers.testing_utils import (  # noqa
    CaptureLogger,
    ExtendSysPath,
    TestCasePlus,
    execute_subprocess_async,
    get_gpu_count,
    mockenv_context,
    require_deepspeed,
    require_torch_gpu,
    require_torch_multi_gpu,
    slow,
)
from transformers.trainer_utils import set_seed  # noqa


set_seed(42)

__a										=					{'''base''': '''patrickvonplaten/wav2vec2_tiny_random''', '''robust''': '''patrickvonplaten/wav2vec2_tiny_random_robust'''}

__a										=					'''zero2'''
__a										=					'''zero3'''
__a										=					[ZEROa, ZEROa]






def    __UpperCAmelCase			(  a_:       List[Any],					a_:       Optional[Any],					a_:       Optional[int]							):
   # customize the test name generator function as we want both params to appear in the sub-test
   # name, as by default it shows only the first param
   _UpperCAmelCase							:	Dict							=   parameterized.to_safe_name("_".join(str(__lowercase							) for x in param.args							)							)
   return f"""{func.__name__}_{param_based_name}"""


# Cartesian-product of zero stages with models to test
__a										=					list(itertools.product(stages, models.keys()))






@slow
@require_deepspeed
@require_torch_gpu
class     A__							(       UpperCamelCase   ):





   """simple docstring"""





   @parameterized.expand(lowerCAmelCase__						,     name_func=lowerCAmelCase__			)
   def 			_lowerCAmelCase		( self     :		List[str]						,     lowerCAmelCase__     :		List[Any]						,     lowerCAmelCase__     :		List[Any]			)       ->    Optional[Any]:







      """simple docstring"""




      self.run_and_check(
          stage=lowerCAmelCase__						,     model=lowerCAmelCase__						,     distributed=lowerCAmelCase__						,     fpaa=lowerCAmelCase__						,     )




   @require_torch_multi_gpu
   @parameterized.expand(lowerCAmelCase__						,     name_func=lowerCAmelCase__			)
   def 			_lowerCAmelCase		( self     :		Optional[int]						,     lowerCAmelCase__     :		int						,     lowerCAmelCase__     :		List[str]			)       ->    Optional[Any]:







      """simple docstring"""




      self.run_and_check(
          stage=lowerCAmelCase__						,     model=lowerCAmelCase__						,     distributed=lowerCAmelCase__						,     fpaa=lowerCAmelCase__						,     )




   @parameterized.expand(lowerCAmelCase__						,     name_func=lowerCAmelCase__			)
   def 			_lowerCAmelCase		( self     :		str						,     lowerCAmelCase__     :		int						,     lowerCAmelCase__     :		Dict			)       ->    Optional[Any]:







      """simple docstring"""




      self.run_and_check(
          stage=lowerCAmelCase__						,     model=lowerCAmelCase__						,     distributed=lowerCAmelCase__						,     fpaa=lowerCAmelCase__						,     )




   @require_torch_multi_gpu
   @parameterized.expand(lowerCAmelCase__						,     name_func=lowerCAmelCase__			)
   def 			_lowerCAmelCase		( self     :		int						,     lowerCAmelCase__     :		str						,     lowerCAmelCase__     :		int			)       ->    str:







      """simple docstring"""




      self.run_and_check(
          stage=lowerCAmelCase__						,     model=lowerCAmelCase__						,     distributed=lowerCAmelCase__						,     fpaa=lowerCAmelCase__						,     )




   def 			_lowerCAmelCase		( self     :		Union[str, Any]						,     lowerCAmelCase__     :		Optional[Any]			)       ->    Dict:







      """simple docstring"""




      pass




   def 			_lowerCAmelCase		( self     :		Dict						,     lowerCAmelCase__     :		str						,     lowerCAmelCase__     :		str						,     lowerCAmelCase__     :		int = 1_0						,     lowerCAmelCase__     :		bool = True						,     lowerCAmelCase__     :		bool = True						,     lowerCAmelCase__     :		bool = True						,     )       ->    Dict:







      """simple docstring"""




      _UpperCAmelCase							:	Optional[int]							=   models[model]

      _UpperCAmelCase							:	List[Any]							=   self.run_trainer(
          stage=lowerCAmelCase__						,     model_name=lowerCAmelCase__						,     eval_steps=lowerCAmelCase__						,     num_train_epochs=1						,     distributed=lowerCAmelCase__						,     fpaa=lowerCAmelCase__						,     )

      self.do_checks(lowerCAmelCase__			)

      return output_dir




   def 			_lowerCAmelCase		( self     :		str						,     lowerCAmelCase__     :		str						,     lowerCAmelCase__     :		str						,     lowerCAmelCase__     :		int = 1_0						,     lowerCAmelCase__     :		int = 1						,     lowerCAmelCase__     :		bool = True						,     lowerCAmelCase__     :		bool = True						,     )       ->    Optional[int]:







      """simple docstring"""




      _UpperCAmelCase							:	Optional[int]							=   self.get_auto_remove_tmp_dir("./xxx"						,     after=lowerCAmelCase__			)
      _UpperCAmelCase							:	str							=   F"""
            --model_name_or_path {model_name}
            --dataset_name hf-internal-testing/librispeech_asr_dummy
            --dataset_config_name clean
            --train_split_name validation
            --validation_split_name validation
            --output_dir {output_dir}
            --num_train_epochs {str(lowerCAmelCase__			)}
            --per_device_train_batch_size 2
            --per_device_eval_batch_size 2
            --evaluation_strategy steps
            --learning_rate 5e-4
            --warmup_steps 8
            --orthography timit
            --preprocessing_num_workers 1
            --group_by_length
            --freeze_feature_extractor
            --report_to none
            --save_steps 0
            --eval_steps {eval_steps}
            --report_to none
        """.split()

      if fpaa:
         args.extend(["--fp16"]			)

      # currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true,
      # hence the separate config files
      _UpperCAmelCase							:	List[str]							=   F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split()
      _UpperCAmelCase							:	Dict							=   [F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""]
      _UpperCAmelCase							:	str							=   self.get_launcher(lowerCAmelCase__			)

      _UpperCAmelCase							:	List[Any]							=   launcher + script + args + ds_args
      # keep for quick debug
      # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
      execute_subprocess_async(lowerCAmelCase__						,     env=self.get_env()			)

      return output_dir




   def 			_lowerCAmelCase		( self     :		List[Any]						,     lowerCAmelCase__     :		str=False			)       ->    Dict:







      """simple docstring"""




      _UpperCAmelCase							:	Optional[Any]							=   min(2						,     get_gpu_count()			) if distributed else 1
      return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()

import os
import tempfile
import unittest
from pathlib import Path

from transformers import AutoConfig, is_torch_available
from transformers.testing_utils import require_torch, torch_device


if is_torch_available():
			from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments




@require_torch
class    SCREAMING_SNAKE_CASE__     (	unittest.TestCase					):





	'''simple docstring'''



	def  A							(  self	:    List[Any]			,  lowercase	:    Dict	):


				'''simple docstring'''


				for model_result in results.values():
							for batch_size, sequence_length in zip(model_result['bs']			,  model_result['ss']	):
										_snake_case		=			model_result['result'][batch_size][sequence_length]
										self.assertIsNotNone(lowercase	)



	def  A							(  self	:    str	):


				'''simple docstring'''


				_snake_case		=			'sshleifer/tiny-gpt2'
				_snake_case		=			PyTorchBenchmarkArguments(
				    models=[MODEL_ID]			,  training=lowercase			,  inference=lowercase			,  sequence_lengths=[8]			,  batch_sizes=[1]			,  multi_process=lowercase			,  )
				_snake_case		=			PyTorchBenchmark(lowercase	)
				_snake_case		=			benchmark.run()
				self.check_results_dict_not_empty(results.time_inference_result	)
				self.check_results_dict_not_empty(results.memory_inference_result	)



	def  A							(  self	:    Any	):


				'''simple docstring'''


				_snake_case		=			'sgugger/tiny-distilbert-classification'
				_snake_case		=			PyTorchBenchmarkArguments(
				    models=[MODEL_ID]			,  training=lowercase			,  inference=lowercase			,  sequence_lengths=[8]			,  batch_sizes=[1]			,  multi_process=lowercase			,  only_pretrain_model=lowercase			,  )
				_snake_case		=			PyTorchBenchmark(lowercase	)
				_snake_case		=			benchmark.run()
				self.check_results_dict_not_empty(results.time_inference_result	)
				self.check_results_dict_not_empty(results.memory_inference_result	)



	def  A							(  self	:    Optional[int]	):


				'''simple docstring'''


				_snake_case		=			'sshleifer/tiny-gpt2'
				_snake_case		=			PyTorchBenchmarkArguments(
				    models=[MODEL_ID]			,  training=lowercase			,  inference=lowercase			,  torchscript=lowercase			,  sequence_lengths=[8]			,  batch_sizes=[1]			,  multi_process=lowercase			,  )
				_snake_case		=			PyTorchBenchmark(lowercase	)
				_snake_case		=			benchmark.run()
				self.check_results_dict_not_empty(results.time_inference_result	)
				self.check_results_dict_not_empty(results.memory_inference_result	)



	@unittest.skipIf(torch_device == 'cpu'			,  'Cant do half precision'	)
	def  A							(  self	:    Optional[Any]	):


				'''simple docstring'''


				_snake_case		=			'sshleifer/tiny-gpt2'
				_snake_case		=			PyTorchBenchmarkArguments(
				    models=[MODEL_ID]			,  training=lowercase			,  inference=lowercase			,  fpaa=lowercase			,  sequence_lengths=[8]			,  batch_sizes=[1]			,  multi_process=lowercase			,  )
				_snake_case		=			PyTorchBenchmark(lowercase	)
				_snake_case		=			benchmark.run()
				self.check_results_dict_not_empty(results.time_inference_result	)
				self.check_results_dict_not_empty(results.memory_inference_result	)



	def  A							(  self	:    str	):


				'''simple docstring'''


				_snake_case		=			'sshleifer/tiny-gpt2'
				_snake_case		=			AutoConfig.from_pretrained(lowercase	)
				# set architectures equal to `None`
				_snake_case		=			None
				_snake_case		=			PyTorchBenchmarkArguments(
				    models=[MODEL_ID]			,  training=lowercase			,  inference=lowercase			,  sequence_lengths=[8]			,  batch_sizes=[1]			,  multi_process=lowercase			,  )
				_snake_case		=			PyTorchBenchmark(lowercase			,  configs=[config]	)
				_snake_case		=			benchmark.run()
				self.check_results_dict_not_empty(results.time_inference_result	)
				self.check_results_dict_not_empty(results.memory_inference_result	)



	def  A							(  self	:    Optional[Any]	):


				'''simple docstring'''


				_snake_case		=			'sshleifer/tiny-gpt2'
				_snake_case		=			PyTorchBenchmarkArguments(
				    models=[MODEL_ID]			,  training=lowercase			,  inference=lowercase			,  sequence_lengths=[8]			,  batch_sizes=[1]			,  multi_process=lowercase			,  )
				_snake_case		=			PyTorchBenchmark(lowercase	)
				_snake_case		=			benchmark.run()
				self.check_results_dict_not_empty(results.time_train_result	)
				self.check_results_dict_not_empty(results.memory_train_result	)



	@unittest.skipIf(torch_device == 'cpu'			,  'Can\'t do half precision'	)
	def  A							(  self	:    str	):


				'''simple docstring'''


				_snake_case		=			'sshleifer/tiny-gpt2'
				_snake_case		=			PyTorchBenchmarkArguments(
				    models=[MODEL_ID]			,  training=lowercase			,  inference=lowercase			,  sequence_lengths=[8]			,  batch_sizes=[1]			,  fpaa=lowercase			,  multi_process=lowercase			,  )
				_snake_case		=			PyTorchBenchmark(lowercase	)
				_snake_case		=			benchmark.run()
				self.check_results_dict_not_empty(results.time_train_result	)
				self.check_results_dict_not_empty(results.memory_train_result	)



	def  A							(  self	:    Tuple	):


				'''simple docstring'''


				_snake_case		=			'sshleifer/tiny-gpt2'
				_snake_case		=			AutoConfig.from_pretrained(lowercase	)
				_snake_case		=			PyTorchBenchmarkArguments(
				    models=[MODEL_ID]			,  training=lowercase			,  inference=lowercase			,  sequence_lengths=[8]			,  batch_sizes=[1]			,  multi_process=lowercase			,  )
				_snake_case		=			PyTorchBenchmark(lowercase			,  configs=[config]	)
				_snake_case		=			benchmark.run()
				self.check_results_dict_not_empty(results.time_inference_result	)
				self.check_results_dict_not_empty(results.memory_inference_result	)



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


				'''simple docstring'''


				_snake_case		=			'sshleifer/tinier_bart'
				_snake_case		=			AutoConfig.from_pretrained(lowercase	)
				_snake_case		=			PyTorchBenchmarkArguments(
				    models=[MODEL_ID]			,  training=lowercase			,  inference=lowercase			,  sequence_lengths=[8]			,  batch_sizes=[1]			,  multi_process=lowercase			,  )
				_snake_case		=			PyTorchBenchmark(lowercase			,  configs=[config]	)
				_snake_case		=			benchmark.run()
				self.check_results_dict_not_empty(results.time_inference_result	)
				self.check_results_dict_not_empty(results.memory_inference_result	)



	def  A							(  self	:    Dict	):


				'''simple docstring'''


				_snake_case		=			'sshleifer/tiny-gpt2'
				_snake_case		=			AutoConfig.from_pretrained(lowercase	)
				_snake_case		=			PyTorchBenchmarkArguments(
				    models=[MODEL_ID]			,  training=lowercase			,  inference=lowercase			,  sequence_lengths=[8]			,  batch_sizes=[1]			,  multi_process=lowercase			,  )
				_snake_case		=			PyTorchBenchmark(lowercase			,  configs=[config]	)
				_snake_case		=			benchmark.run()
				self.check_results_dict_not_empty(results.time_train_result	)
				self.check_results_dict_not_empty(results.memory_train_result	)



	def  A							(  self	:    Dict	):


				'''simple docstring'''


				_snake_case		=			'sshleifer/tinier_bart'
				_snake_case		=			AutoConfig.from_pretrained(lowercase	)
				_snake_case		=			PyTorchBenchmarkArguments(
				    models=[MODEL_ID]			,  training=lowercase			,  inference=lowercase			,  sequence_lengths=[8]			,  batch_sizes=[1]			,  multi_process=lowercase			,  )
				_snake_case		=			PyTorchBenchmark(lowercase			,  configs=[config]	)
				_snake_case		=			benchmark.run()
				self.check_results_dict_not_empty(results.time_train_result	)
				self.check_results_dict_not_empty(results.memory_train_result	)



	def  A							(  self	:    Optional[Any]	):


				'''simple docstring'''


				_snake_case		=			'sshleifer/tiny-gpt2'
				with tempfile.TemporaryDirectory() as tmp_dir:
							_snake_case		=			PyTorchBenchmarkArguments(
							    models=[MODEL_ID]			,  training=lowercase			,  inference=lowercase			,  save_to_csv=lowercase			,  sequence_lengths=[8]			,  batch_sizes=[1]			,  inference_time_csv_file=os.path.join(lowercase			,  'inf_time.csv'	)			,  train_memory_csv_file=os.path.join(lowercase			,  'train_mem.csv'	)			,  inference_memory_csv_file=os.path.join(lowercase			,  'inf_mem.csv'	)			,  train_time_csv_file=os.path.join(lowercase			,  'train_time.csv'	)			,  env_info_csv_file=os.path.join(lowercase			,  'env.csv'	)			,  multi_process=lowercase			,  )
							_snake_case		=			PyTorchBenchmark(lowercase	)
							benchmark.run()
							self.assertTrue(Path(os.path.join(lowercase			,  'inf_time.csv'	)	).exists()	)
							self.assertTrue(Path(os.path.join(lowercase			,  'train_time.csv'	)	).exists()	)
							self.assertTrue(Path(os.path.join(lowercase			,  'inf_mem.csv'	)	).exists()	)
							self.assertTrue(Path(os.path.join(lowercase			,  'train_mem.csv'	)	).exists()	)
							self.assertTrue(Path(os.path.join(lowercase			,  'env.csv'	)	).exists()	)





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


				'''simple docstring'''


				_snake_case		=			'sshleifer/tiny-gpt2'

				def _check_summary_is_not_empty(lowercase	:    Optional[Any]	):
							self.assertTrue(hasattr(lowercase			,  'sequential'	)	)
							self.assertTrue(hasattr(lowercase			,  'cumulative'	)	)
							self.assertTrue(hasattr(lowercase			,  'current'	)	)
							self.assertTrue(hasattr(lowercase			,  'total'	)	)

				with tempfile.TemporaryDirectory() as tmp_dir:
							_snake_case		=			PyTorchBenchmarkArguments(
							    models=[MODEL_ID]			,  training=lowercase			,  inference=lowercase			,  sequence_lengths=[8]			,  batch_sizes=[1]			,  log_filename=os.path.join(lowercase			,  'log.txt'	)			,  log_print=lowercase			,  trace_memory_line_by_line=lowercase			,  multi_process=lowercase			,  )
							_snake_case		=			PyTorchBenchmark(lowercase	)
							_snake_case		=			benchmark.run()
							_check_summary_is_not_empty(result.inference_summary	)
							_check_summary_is_not_empty(result.train_summary	)
							self.assertTrue(Path(os.path.join(lowercase			,  'log.txt'	)	).exists()	)