


# 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


lowerCamelCase		   =			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)

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

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




def       a_ (       SCREAMING_SNAKE_CASE__   : Dict						,     SCREAMING_SNAKE_CASE__   : Any						,     SCREAMING_SNAKE_CASE__   : List[Any]	):
       '''simple docstring'''





       _lowerCamelCase			:						Tuple            =parameterized.to_safe_name('_'.join(str(SCREAMING_SNAKE_CASE__	) for x in param.args	)	)
       return F'''{func.__name__}_{param_based_name}'''


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




@slow
@require_deepspeed
@require_torch_gpu
class A    (  UpperCamelCase_	):






      @parameterized.expand(lowercase_     ,  name_func=lowercase_					)
      def 			lowerCamelCase			(   self		:	str     ,  lowercase_		:	Optional[int]     ,  lowercase_		:	str					)   ->		Union[str, 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 			lowerCamelCase			(   self		:	Optional[int]     ,  lowercase_		:	Optional[Any]     ,  lowercase_		:	str					)   ->		Optional[int]:
             """simple docstring"""




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






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




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






      def 			lowerCamelCase			(   self		:	Any     ,  lowercase_		:	Union[str, Any]					)   ->		List[Any]:
             """simple docstring"""




             pass






      def 			lowerCamelCase			(   self		:	str     ,  lowercase_		:	str     ,  lowercase_		:	str     ,  lowercase_		:	int = 10     ,  lowercase_		:	bool = True     ,  lowercase_		:	bool = True     ,  lowercase_		:	bool = True     ,  )   ->		Dict:
             """simple docstring"""




             _lowerCamelCase			:						Optional[Any]            =models[model]

             _lowerCamelCase			:						str            =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 			lowerCamelCase			(   self		:	Tuple     ,  lowercase_		:	str     ,  lowercase_		:	str     ,  lowercase_		:	int = 10     ,  lowercase_		:	int = 1     ,  lowercase_		:	bool = True     ,  lowercase_		:	bool = True     ,  )   ->		List[str]:
             """simple docstring"""




             _lowerCamelCase			:						Dict            =self.get_auto_remove_tmp_dir('./xxx'     ,  after=lowercase_					)
             _lowerCamelCase			:						Any            =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			:						Optional[int]            =F'''--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json'''.split()
             _lowerCamelCase			:						Any            =[F'''{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py''']
             _lowerCamelCase			:						Tuple            =self.get_launcher(lowercase_					)

             _lowerCamelCase			:						Tuple            =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 			lowerCamelCase			(   self		:	List[Any]     ,  lowercase_		:	List[Any]=False					)   ->		Any:
             """simple docstring"""




             _lowerCamelCase			:						str            =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


lowerCamelCase		   =			logging.get_logger(__name__)

lowerCamelCase		   =			{
    'sayakpaul/vit-msn-base': 'https://huggingface.co/sayakpaul/vit-msn-base/resolve/main/config.json',
    # See all ViT MSN models at https://huggingface.co/models?filter=vit_msn
}




class A    (  UpperCamelCase_	):
      UpperCamelCase__				:    Union[str, Any] ='vit_msn'






      def __init__(   self		:	Union[str, Any]     ,  lowercase_		:	List[str]=768     ,  lowercase_		:	Optional[int]=12     ,  lowercase_		:	List[str]=12     ,  lowercase_		:	List[Any]=3072     ,  lowercase_		:	int="gelu"     ,  lowercase_		:	List[Any]=0.0     ,  lowercase_		:	Optional[int]=0.0     ,  lowercase_		:	Dict=0.02     ,  lowercase_		:	Any=1E-06     ,  lowercase_		:	Union[str, Any]=224     ,  lowercase_		:	Optional[int]=16     ,  lowercase_		:	List[Any]=3     ,  lowercase_		:	Any=True     ,  **lowercase_		:	Tuple     ,  )   ->		Dict:
             """simple docstring"""




             super().__init__(**lowercase_					)

             _lowerCamelCase			:						Dict            =hidden_size
             _lowerCamelCase			:						Any            =num_hidden_layers
             _lowerCamelCase			:						Union[str, Any]            =num_attention_heads
             _lowerCamelCase			:						List[Any]            =intermediate_size
             _lowerCamelCase			:						Tuple            =hidden_act
             _lowerCamelCase			:						Any            =hidden_dropout_prob
             _lowerCamelCase			:						Dict            =attention_probs_dropout_prob
             _lowerCamelCase			:						Any            =initializer_range
             _lowerCamelCase			:						List[Any]            =layer_norm_eps
             _lowerCamelCase			:						Optional[int]            =image_size
             _lowerCamelCase			:						Optional[int]            =patch_size
             _lowerCamelCase			:						List[Any]            =num_channels
             _lowerCamelCase			:						Optional[Any]            =qkv_bias


