'''simple docstring'''





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       __lowerCAmelCase      (						A_   : Union[str, Any]						,	A_   : List[Any]						,	A_   : Optional[Any]					)    ->  int:
  __UpperCAmelCase						    =       parameterized.to_safe_name("_".join(str(__UpperCAmelCase					) 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 			UpperCAmelCase__    (		_snake_case					):



  """simple docstring"""






  @parameterized.expand(__lowerCAmelCase				,				name_func=__lowerCAmelCase   )
  def 	_UpperCAmelCase				(				self:			Dict				,				__lowerCAmelCase:			Optional[int]				,				__lowerCAmelCase:			Tuple   ) -> Union[str, 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 	_UpperCAmelCase				(				self:			Dict				,				__lowerCAmelCase:			List[Any]				,				__lowerCAmelCase:			Dict   ) -> str:




    '''simple docstring'''




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






  @parameterized.expand(__lowerCAmelCase				,				name_func=__lowerCAmelCase   )
  def 	_UpperCAmelCase				(				self:			Optional[Any]				,				__lowerCAmelCase:			Union[str, Any]				,				__lowerCAmelCase:			List[Any]   ) -> Union[str, 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 	_UpperCAmelCase				(				self:			Optional[int]				,				__lowerCAmelCase:			Optional[Any]				,				__lowerCAmelCase:			Optional[Any]   ) -> List[str]:




    '''simple docstring'''




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






  def 	_UpperCAmelCase				(				self:			Union[str, Any]				,				__lowerCAmelCase:			Dict   ) -> List[str]:




    '''simple docstring'''




    pass






  def 	_UpperCAmelCase				(				self:			Tuple				,				__lowerCAmelCase:			str				,				__lowerCAmelCase:			str				,				__lowerCAmelCase:			int = 10				,				__lowerCAmelCase:			bool = True				,				__lowerCAmelCase:			bool = True				,				__lowerCAmelCase:			bool = True				,				) -> Dict:




    '''simple docstring'''




    __UpperCAmelCase						    =       models[model]

    __UpperCAmelCase						    =       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 	_UpperCAmelCase				(				self:			List[str]				,				__lowerCAmelCase:			str				,				__lowerCAmelCase:			str				,				__lowerCAmelCase:			int = 10				,				__lowerCAmelCase:			int = 1				,				__lowerCAmelCase:			bool = True				,				__lowerCAmelCase:			bool = True				,				) -> Dict:




    '''simple docstring'''




    __UpperCAmelCase						    =       self.get_auto_remove_tmp_dir("./xxx"				,				after=__lowerCAmelCase   )
    __UpperCAmelCase						    =       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						    =       F'''--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json'''.split()
    __UpperCAmelCase						    =       [F'''{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py''']
    __UpperCAmelCase						    =       self.get_launcher(__lowerCAmelCase   )

    __UpperCAmelCase						    =       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 	_UpperCAmelCase				(				self:			Tuple				,				__lowerCAmelCase:			List[Any]=False   ) -> List[Any]:




    '''simple docstring'''




    __UpperCAmelCase						    =       min(2				,				get_gpu_count()   ) if distributed else 1
    return F'''deepspeed --num_nodes 1 --num_gpus {num_gpus}'''.split()




from ..utils import DummyObject, requires_backends


class 			UpperCAmelCase__    (		metaclass=snake_case					):



  """simple docstring"""






  lowerCAmelCase__		:	List[str]    		= ['transformers', 'torch', 'note_seq']






  def __init__(				self:			List[str]				,				*__lowerCAmelCase:			Optional[int]				,				**__lowerCAmelCase:			List[Any]   ) -> Optional[int]:




    '''simple docstring'''




    requires_backends(self				,				["transformers", "torch", "note_seq"]   )






  @classmethod
  def 	_UpperCAmelCase				(				cls:			Optional[int]				,				*__lowerCAmelCase:			Any				,				**__lowerCAmelCase:			List[str]   ) -> Dict:




    '''simple docstring'''




    requires_backends(cls				,				["transformers", "torch", "note_seq"]   )






  @classmethod
  def 	_UpperCAmelCase				(				cls:			Union[str, Any]				,				*__lowerCAmelCase:			Optional[Any]				,				**__lowerCAmelCase:			Optional[Any]   ) -> Any:




    '''simple docstring'''




    requires_backends(cls				,				["transformers", "torch", "note_seq"]   )



