






# 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   :   Optional[Any]      =    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)

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

__UpperCamelCase   :   List[str]      =    """zero2"""
__UpperCamelCase   :   List[Any]      =    """zero3"""
__UpperCamelCase   :   Optional[int]      =    [ZEROa, ZEROa]





def 					snake_case	(  lowerCamelCase					,	lowerCamelCase					,	lowerCamelCase       ):




	'''simple docstring'''







	__lowercase   							=	parameterized.to_safe_name("""_""".join(str(lowerCamelCase       ) for x in param.args       )       )
	return F'{func.__name__}_{param_based_name}'


# Cartesian-product of zero stages with models to test
__UpperCamelCase   :   Union[str, Any]      =    list(itertools.product(stages, models.keys()))




@slow
@require_deepspeed
@require_torch_gpu
class 							__UpperCamelCase     (  _lowerCAmelCase ):







	@parameterized.expand(_lowerCAmelCase							,					name_func=_lowerCAmelCase      )
	def 			_a (	self   :				Dict							,					_lowerCAmelCase   :				int							,					_lowerCAmelCase   :				Dict      )		->			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 			_a (	self   :				Optional[int]							,					_lowerCAmelCase   :				Dict							,					_lowerCAmelCase   :				List[Any]      )		->			Tuple:
		"""simple docstring"""







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







	@parameterized.expand(_lowerCAmelCase							,					name_func=_lowerCAmelCase      )
	def 			_a (	self   :				Tuple							,					_lowerCAmelCase   :				Dict							,					_lowerCAmelCase   :				Tuple      )		->			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 			_a (	self   :				str							,					_lowerCAmelCase   :				Optional[Any]							,					_lowerCAmelCase   :				Dict      )		->			str:
		"""simple docstring"""







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







	def 			_a (	self   :				Union[str, Any]							,					_lowerCAmelCase   :				Optional[Any]      )		->			Any:
		"""simple docstring"""







		pass







	def 			_a (	self   :				str							,					_lowerCAmelCase   :				str							,					_lowerCAmelCase   :				str							,					_lowerCAmelCase   :				int = 10							,					_lowerCAmelCase   :				bool = True							,					_lowerCAmelCase   :				bool = True							,					_lowerCAmelCase   :				bool = True							,					)		->			str:
		"""simple docstring"""







		__lowercase   							=	models[model]

		__lowercase   							=	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 			_a (	self   :				List[str]							,					_lowerCAmelCase   :				str							,					_lowerCAmelCase   :				str							,					_lowerCAmelCase   :				int = 10							,					_lowerCAmelCase   :				int = 1							,					_lowerCAmelCase   :				bool = True							,					_lowerCAmelCase   :				bool = True							,					)		->			Dict:
		"""simple docstring"""







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

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

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

		__lowercase   							=	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 			_a (	self   :				List[str]							,					_lowerCAmelCase   :				str=False      )		->			Dict:
		"""simple docstring"""







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



"""simple docstring"""






from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_torch_available,
)


__SCREAMING_SNAKE_CASE							=     {
    'configuration_mega': ['MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MegaConfig', 'MegaOnnxConfig'],
}

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 __SCREAMING_SNAKE_CASE							=     [
     'MEGA_PRETRAINED_MODEL_ARCHIVE_LIST',
     'MegaForCausalLM',
     'MegaForMaskedLM',
     'MegaForMultipleChoice',
     'MegaForQuestionAnswering',
     'MegaForSequenceClassification',
     'MegaForTokenClassification',
     'MegaModel',
     'MegaPreTrainedModel',
 ]

if TYPE_CHECKING:
 from .configuration_mega import MEGA_PRETRAINED_CONFIG_ARCHIVE_MAP, MegaConfig, MegaOnnxConfig

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_mega import (
      MEGA_PRETRAINED_MODEL_ARCHIVE_LIST,
      MegaForCausalLM,
      MegaForMaskedLM,
      MegaForMultipleChoice,
      MegaForQuestionAnswering,
      MegaForSequenceClassification,
      MegaForTokenClassification,
      MegaModel,
      MegaPreTrainedModel,
  )

else:
 import sys

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