

'''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	(		__UpperCamelCase    ,__UpperCamelCase    ,__UpperCamelCase	)       ->			Any:
					lowerCamelCase_  				=      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 (							_UpperCAmelCase    ):

		'''simple docstring'''






		@parameterized.expand(lowerCAmelCase__   ,			name_func=lowerCAmelCase__		)
		def 			UpperCamelCase(					self   ,			SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_		)  ->     Optional[int]:






							'''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   ,			SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_		)  ->     Optional[int]:






							'''simple docstring'''



							self.run_and_check(
							    stage=lowerCAmelCase__   ,			model=lowerCAmelCase__   ,			distributed=lowerCAmelCase__   ,			fpaa=lowerCAmelCase__   ,			)
		@parameterized.expand(lowerCAmelCase__   ,			name_func=lowerCAmelCase__		)
		def 			UpperCamelCase(					self   ,			SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_		)  ->     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   ,			SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_		)  ->     Optional[Any]:






							'''simple docstring'''



							self.run_and_check(
							    stage=lowerCAmelCase__   ,			model=lowerCAmelCase__   ,			distributed=lowerCAmelCase__   ,			fpaa=lowerCAmelCase__   ,			)
		def 			UpperCamelCase(					self   ,			SCREAMING_SNAKE_CASE_		)  ->     int:






							'''simple docstring'''



							pass
		def 			UpperCamelCase(					self   ,			SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_ = 10   ,			SCREAMING_SNAKE_CASE_ = True   ,			SCREAMING_SNAKE_CASE_ = True   ,			SCREAMING_SNAKE_CASE_ = True   ,			)  ->     str:






							'''simple docstring'''



							lowerCamelCase_  				=      models[model]

							lowerCamelCase_  				=      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   ,			SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_   ,			SCREAMING_SNAKE_CASE_ = 10   ,			SCREAMING_SNAKE_CASE_ = 1   ,			SCREAMING_SNAKE_CASE_ = True   ,			SCREAMING_SNAKE_CASE_ = True   ,			)  ->     List[str]:






							'''simple docstring'''



							lowerCamelCase_  				=      self.get_auto_remove_tmp_dir('./xxx'   ,			after=lowerCAmelCase__		)
							lowerCamelCase_  				=      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
							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(lowerCAmelCase__		)

							lowerCamelCase_  				=      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   ,			SCREAMING_SNAKE_CASE_=False		)  ->     int:






							'''simple docstring'''



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




from ...configuration_utils import PretrainedConfig
from ...utils import logging


__a    :	int         =    logging.get_logger(__name__)

__a    :	Optional[int]         =    {
    """google/pegasus-large""": """https://huggingface.co/google/pegasus-large/resolve/main/config.json""",
    # See all PEGASUS models at https://huggingface.co/models?filter=pegasus
}




class   _UpperCamelCase (		_UpperCAmelCase					):


			"""simple docstring"""






			__a    :					Any     					=		'''pegasus'''
			__a    :					Optional[Any]     					=		['''past_key_values''']
			__a    :					Tuple     					=		{'''num_attention_heads''': '''encoder_attention_heads''', '''hidden_size''': '''d_model'''}





			def __init__(  self ,  lowerCAmelCase__=5_02_65 ,  lowerCAmelCase__=10_24 ,  lowerCAmelCase__=12 ,  lowerCAmelCase__=40_96 ,  lowerCAmelCase__=16 ,  lowerCAmelCase__=12 ,  lowerCAmelCase__=40_96 ,  lowerCAmelCase__=16 ,  lowerCAmelCase__=0.0 ,  lowerCAmelCase__=0.0 ,  lowerCAmelCase__=True ,  lowerCAmelCase__=True ,  lowerCAmelCase__="gelu" ,  lowerCAmelCase__=10_24 ,  lowerCAmelCase__=0.1 ,  lowerCAmelCase__=0.0 ,  lowerCAmelCase__=0.0 ,  lowerCAmelCase__=0.02 ,  lowerCAmelCase__=0 ,  lowerCAmelCase__=False ,  lowerCAmelCase__=0 ,  lowerCAmelCase__=1 ,  lowerCAmelCase__=1 ,  **lowerCAmelCase__ ,  )	->   Dict:

							'''simple docstring'''


							__lowercase					     =				vocab_size
							__lowercase					     =				max_position_embeddings
							__lowercase					     =				d_model
							__lowercase					     =				encoder_ffn_dim
							__lowercase					     =				encoder_layers
							__lowercase					     =				encoder_attention_heads
							__lowercase					     =				decoder_ffn_dim
							__lowercase					     =				decoder_layers
							__lowercase					     =				decoder_attention_heads
							__lowercase					     =				dropout
							__lowercase					     =				attention_dropout
							__lowercase					     =				activation_dropout
							__lowercase					     =				activation_function
							__lowercase					     =				init_std
							__lowercase					     =				encoder_layerdrop
							__lowercase					     =				decoder_layerdrop
							__lowercase					     =				use_cache
							__lowercase					     =				encoder_layers
							__lowercase					     =				scale_embedding  # scale factor will be sqrt(d_model) if True
							super().__init__(
							    pad_token_id=lowerCAmelCase__ ,  eos_token_id=lowerCAmelCase__ ,  is_encoder_decoder=lowerCAmelCase__ ,  decoder_start_token_id=lowerCAmelCase__ ,  forced_eos_token_id=lowerCAmelCase__ ,  **lowerCAmelCase__ ,  )





			@property
			def 			_SCREAMING_SNAKE_CASE     (  self		)	->   int:

							'''simple docstring'''


							return self.encoder_attention_heads





			@property
			def 			_SCREAMING_SNAKE_CASE     (  self		)	->   int:

							'''simple docstring'''


							return self.d_model