





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


_SCREAMING_SNAKE_CASE      	=		logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE      	=		{
    """MIT/ast-finetuned-audioset-10-10-0.4593""": (
        """https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json"""
    ),
}
class SCREAMING_SNAKE_CASE_						(					snake_case_					):
						__magic_name__:			List[Any]       =       "audio-spectrogram-transformer"






						def __init__(      self      :      Tuple		,   _A      :      Any=768		,   _A      :      Union[str, Any]=12		,   _A      :      Optional[Any]=12		,   _A      :      Dict=3072		,   _A      :      int="gelu"		,   _A      :      int=0.0		,   _A      :      Dict=0.0		,   _A      :      Tuple=0.0_2		,   _A      :      int=1E-12		,   _A      :      Tuple=16		,   _A      :      Optional[int]=True		,   _A      :      Optional[Any]=10		,   _A      :      Tuple=10		,   _A      :      Tuple=1024		,   _A      :      Tuple=128		,   **_A      :      int		,   )							->    Any:







							"""simple docstring"""


							super().__init__(**_A	)

							snake_case_		:			List[str]											=	hidden_size
							snake_case_		:			Optional[int]											=	num_hidden_layers
							snake_case_		:			Optional[Any]											=	num_attention_heads
							snake_case_		:			List[str]											=	intermediate_size
							snake_case_		:			List[str]											=	hidden_act
							snake_case_		:			Union[str, Any]											=	hidden_dropout_prob
							snake_case_		:			int											=	attention_probs_dropout_prob
							snake_case_		:			List[Any]											=	initializer_range
							snake_case_		:			Optional[Any]											=	layer_norm_eps
							snake_case_		:			List[str]											=	patch_size
							snake_case_		:			Any											=	qkv_bias
							snake_case_		:			int											=	frequency_stride
							snake_case_		:			int											=	time_stride
							snake_case_		:			str											=	max_length
							snake_case_		:			Optional[Any]											=	num_mel_bins








# 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


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

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

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


def 							SCREAMING_SNAKE_CASE__						(    __a   , __a   , __a   ):
	# customize the test name generator function as we want both params to appear in the sub-test
	# name, as by default it shows only the first param
	snake_case_		:			Tuple											=	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
_SCREAMING_SNAKE_CASE      	=		list(itertools.product(stages, models.keys()))


@slow
@require_deepspeed
@require_torch_gpu
class SCREAMING_SNAKE_CASE_						(					snake_case_					):






						@parameterized.expand(_A		,   name_func=_A	)
						def UpperCAmelCase_				(      self      :      Tuple		,   _A      :      Optional[Any]		,   _A      :      Optional[int]	)							->    Dict:







							"""simple docstring"""


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






						@require_torch_multi_gpu
						@parameterized.expand(_A		,   name_func=_A	)
						def UpperCAmelCase_				(      self      :      int		,   _A      :      Any		,   _A      :      int	)							->    Dict:







							"""simple docstring"""


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






						@parameterized.expand(_A		,   name_func=_A	)
						def UpperCAmelCase_				(      self      :      str		,   _A      :      List[str]		,   _A      :      str	)							->    Tuple:







							"""simple docstring"""


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






						@require_torch_multi_gpu
						@parameterized.expand(_A		,   name_func=_A	)
						def UpperCAmelCase_				(      self      :      Optional[int]		,   _A      :      int		,   _A      :      Union[str, Any]	)							->    List[Any]:







							"""simple docstring"""


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






						def UpperCAmelCase_				(      self      :      Any		,   _A      :      Union[str, Any]	)							->    Any:







							"""simple docstring"""


							pass






						def UpperCAmelCase_				(      self      :      List[str]		,   _A      :      str		,   _A      :      str		,   _A      :      int = 10		,   _A      :      bool = True		,   _A      :      bool = True		,   _A      :      bool = True		,   )							->    Any:







							"""simple docstring"""


							snake_case_		:			Dict											=	models[model]

							snake_case_		:			str											=	self.run_trainer(
							    stage=_A		,   model_name=_A		,   eval_steps=_A		,   num_train_epochs=1		,   distributed=_A		,   fpaa=_A		,   )

							self.do_checks(_A	)

							return output_dir






						def UpperCAmelCase_				(      self      :      Any		,   _A      :      str		,   _A      :      str		,   _A      :      int = 10		,   _A      :      int = 1		,   _A      :      bool = True		,   _A      :      bool = True		,   )							->    Dict:







							"""simple docstring"""


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

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

							return output_dir






						def UpperCAmelCase_				(      self      :      Optional[Any]		,   _A      :      Optional[Any]=False	)							->    List[str]:







							"""simple docstring"""


							snake_case_		:			str											=	min(2		,   get_gpu_count()	) if distributed else 1
							return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()

