'''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


__UpperCAmelCase     							=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(4_2)

__UpperCAmelCase     							={"base": "patrickvonplaten/wav2vec2_tiny_random", "robust": "patrickvonplaten/wav2vec2_tiny_random_robust"}

__UpperCAmelCase     							="zero2"
__UpperCAmelCase     							="zero3"
__UpperCAmelCase     							=[ZEROa, ZEROa]






def __lowerCAmelCase (							UpperCamelCase__				,  UpperCamelCase__				,  UpperCamelCase__				)	->    Any:
    __lowerCamelCase		=  parameterized.to_safe_name('''_'''.join(str(_A				) for x in param.args				)				)
    return f"""{func.__name__}_{param_based_name}"""


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




@slow
@require_deepspeed
@require_torch_gpu
class     a__      (   lowerCamelCase__ ):






     @parameterized.expand(lowercase_  ,				name_func=lowercase_    )
     def    SCREAMING_SNAKE_CASE__   ( self		:		Dict  ,				a		:		Union[str, Any]  ,				a		:		Tuple    ):





         """simple docstring"""



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






     @require_torch_multi_gpu
     @parameterized.expand(lowercase_  ,				name_func=lowercase_    )
     def    SCREAMING_SNAKE_CASE__   ( self		:		Any  ,				a		:		Tuple  ,				a		:		Optional[int]    ):





         """simple docstring"""



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






     @parameterized.expand(lowercase_  ,				name_func=lowercase_    )
     def    SCREAMING_SNAKE_CASE__   ( self		:		Tuple  ,				a		:		Any  ,				a		:		Optional[Any]    ):





         """simple docstring"""



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






     @require_torch_multi_gpu
     @parameterized.expand(lowercase_  ,				name_func=lowercase_    )
     def    SCREAMING_SNAKE_CASE__   ( self		:		int  ,				a		:		Any  ,				a		:		Dict    ):





         """simple docstring"""



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






     def    SCREAMING_SNAKE_CASE__   ( self		:		Optional[int]  ,				a		:		List[str]    ):





         """simple docstring"""



         pass






     def    SCREAMING_SNAKE_CASE__   ( self		:		List[Any]  ,				a		:		int  ,				a		:		Dict  ,				a		:		int = 10  ,				a		:		List[str] = True  ,				a		:		Union[str, Any] = True  ,				a		:		str = True  ,				):





         """simple docstring"""



         __lowerCamelCase		=  models[model]

         __lowerCamelCase		=  self.run_trainer(
             stage=lowercase_  ,				model_name=lowercase_  ,				eval_steps=lowercase_  ,				num_train_epochs=1  ,				distributed=lowercase_  ,				fpaa=lowercase_  ,				)

         self.do_checks(lowercase_    )

         return output_dir






     def    SCREAMING_SNAKE_CASE__   ( self		:		Tuple  ,				a		:		Dict  ,				a		:		Optional[Any]  ,				a		:		str = 10  ,				a		:		Tuple = 1  ,				a		:		int = True  ,				a		:		Optional[int] = True  ,				):





         """simple docstring"""



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

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

         return output_dir






     def    SCREAMING_SNAKE_CASE__   ( self		:		Optional[Any]  ,				a		:		Tuple=False    ):





         """simple docstring"""



         __lowerCamelCase		=  min(2  ,				get_gpu_count()    ) if distributed else 1
         return f"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()



from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


lowerCamelCase           =					{
    '''configuration_mvp''': ['''MVP_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''MvpConfig''', '''MvpOnnxConfig'''],
    '''tokenization_mvp''': ['''MvpTokenizer'''],
}

try:
       if not is_tokenizers_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       lowerCamelCase           =					['''MvpTokenizerFast''']

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       lowerCamelCase           =					[
           '''MVP_PRETRAINED_MODEL_ARCHIVE_LIST''',
           '''MvpForCausalLM''',
           '''MvpForConditionalGeneration''',
           '''MvpForQuestionAnswering''',
           '''MvpForSequenceClassification''',
           '''MvpModel''',
           '''MvpPreTrainedModel''',
       ]

if TYPE_CHECKING:
       from .configuration_mvp import MVP_PRETRAINED_CONFIG_ARCHIVE_MAP, MvpConfig, MvpOnnxConfig
       from .tokenization_mvp import MvpTokenizer

       try:
              if not is_tokenizers_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .tokenization_mvp_fast import MvpTokenizerFast

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_mvp import (
                  MVP_PRETRAINED_MODEL_ARCHIVE_LIST,
                  MvpForCausalLM,
                  MvpForConditionalGeneration,
                  MvpForQuestionAnswering,
                  MvpForSequenceClassification,
                  MvpModel,
                  MvpPreTrainedModel,
              )

else:
       import sys

       lowerCamelCase           =					_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
