




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


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 			SCREAMING_SNAKE_CASE_			(							__A    :			List[Any]	,					__A    :			Tuple	,					__A    :			Optional[Any]  )			->			str:
   # 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
   _SCREAMING_SNAKE_CASE	=				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
lowerCamelCase_			=						list(itertools.product(stages, models.keys()))







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


   """simple docstring"""

   @parameterized.expand(__lowerCamelCase  ,				name_func=__lowerCamelCase   )
   def 							lowerCAmelCase_      (   self :     str  ,				__lowerCamelCase :     Dict  ,				__lowerCamelCase :     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 							lowerCAmelCase_      (   self :     List[str]  ,				__lowerCamelCase :     List[str]  ,				__lowerCamelCase :     Optional[int]   ):

      """simple docstring"""
      self.run_and_check(
          stage=__lowerCamelCase  ,				model=__lowerCamelCase  ,				distributed=__lowerCamelCase  ,				fpaa=__lowerCamelCase  ,				)



   @parameterized.expand(__lowerCamelCase  ,				name_func=__lowerCamelCase   )
   def 							lowerCAmelCase_      (   self :     Optional[int]  ,				__lowerCamelCase :     Any  ,				__lowerCamelCase :     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 							lowerCAmelCase_      (   self :     Tuple  ,				__lowerCamelCase :     Dict  ,				__lowerCamelCase :     Optional[int]   ):

      """simple docstring"""
      self.run_and_check(
          stage=__lowerCamelCase  ,				model=__lowerCamelCase  ,				distributed=__lowerCamelCase  ,				fpaa=__lowerCamelCase  ,				)



   def 							lowerCAmelCase_      (   self :     Any  ,				__lowerCamelCase :     List[str]   ):

      """simple docstring"""
      # XXX: run_asr is premature and doesn't save any results
      # so all we check for now is that the process didn't fail
      pass



   def 							lowerCAmelCase_      (   self :     Optional[int]  ,				__lowerCamelCase :     str  ,				__lowerCamelCase :     str  ,				__lowerCamelCase :     int = 1_0  ,				__lowerCamelCase :     bool = True  ,				__lowerCamelCase :     bool = True  ,				__lowerCamelCase :     bool = True  ,				):

      """simple docstring"""
      _SCREAMING_SNAKE_CASE	=				models[model]

      _SCREAMING_SNAKE_CASE	=				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 							lowerCAmelCase_      (   self :     Optional[Any]  ,				__lowerCamelCase :     str  ,				__lowerCamelCase :     str  ,				__lowerCamelCase :     int = 1_0  ,				__lowerCamelCase :     int = 1  ,				__lowerCamelCase :     bool = True  ,				__lowerCamelCase :     bool = True  ,				):

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

      _SCREAMING_SNAKE_CASE	=				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 							lowerCAmelCase_      (   self :     int  ,				__lowerCamelCase :     Optional[int]=False   ):

      """simple docstring"""
      # 1. explicitly set --num_nodes=1 just in case these tests end up run on a multi-node setup
      # - it won't be able to handle that
      # 2. for now testing with just 2 gpus max (since some quality tests may give different
      # results with mode gpus because we use very little data)
      _SCREAMING_SNAKE_CASE	=				min(2  ,				get_gpu_count()   ) if distributed else 1
      return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()







'''simple docstring'''



from collections import OrderedDict
from typing import List, Mapping

from packaging import version

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


lowerCamelCase_			=						logging.get_logger(__name__)

lowerCamelCase_			=						{
    'google/efficientnet-b7': 'https://huggingface.co/google/efficientnet-b7/resolve/main/config.json',
}







class 		lowercase_   (			A       ):


   """simple docstring"""

   lowerCamelCase_      =						'''efficientnet'''



   def __init__(   self :     Optional[Any]  ,				__lowerCamelCase :     int = 3  ,				__lowerCamelCase :     int = 6_0_0  ,				__lowerCamelCase :     float = 2.0  ,				__lowerCamelCase :     float = 3.1  ,				__lowerCamelCase :     int = 8  ,				__lowerCamelCase :     List[int] = [3, 3, 5, 3, 5, 5, 3]  ,				__lowerCamelCase :     List[int] = [3_2, 1_6, 2_4, 4_0, 8_0, 1_1_2, 1_9_2]  ,				__lowerCamelCase :     List[int] = [1_6, 2_4, 4_0, 8_0, 1_1_2, 1_9_2, 3_2_0]  ,				__lowerCamelCase :     List[int] = []  ,				__lowerCamelCase :     List[int] = [1, 2, 2, 2, 1, 2, 1]  ,				__lowerCamelCase :     List[int] = [1, 2, 2, 3, 3, 4, 1]  ,				__lowerCamelCase :     List[int] = [1, 6, 6, 6, 6, 6, 6]  ,				__lowerCamelCase :     float = 0.2_5  ,				__lowerCamelCase :     str = "swish"  ,				__lowerCamelCase :     int = 2_5_6_0  ,				__lowerCamelCase :     str = "mean"  ,				__lowerCamelCase :     float = 0.0_2  ,				__lowerCamelCase :     float = 0.0_0_1  ,				__lowerCamelCase :     float = 0.9_9  ,				__lowerCamelCase :     float = 0.5  ,				__lowerCamelCase :     float = 0.2  ,				**__lowerCamelCase :     Tuple  ,				):

      """simple docstring"""
      super().__init__(**__lowerCamelCase   )

      _SCREAMING_SNAKE_CASE	=				num_channels
      _SCREAMING_SNAKE_CASE	=				image_size
      _SCREAMING_SNAKE_CASE	=				width_coefficient
      _SCREAMING_SNAKE_CASE	=				depth_coefficient
      _SCREAMING_SNAKE_CASE	=				depth_divisor
      _SCREAMING_SNAKE_CASE	=				kernel_sizes
      _SCREAMING_SNAKE_CASE	=				in_channels
      _SCREAMING_SNAKE_CASE	=				out_channels
      _SCREAMING_SNAKE_CASE	=				depthwise_padding
      _SCREAMING_SNAKE_CASE	=				strides
      _SCREAMING_SNAKE_CASE	=				num_block_repeats
      _SCREAMING_SNAKE_CASE	=				expand_ratios
      _SCREAMING_SNAKE_CASE	=				squeeze_expansion_ratio
      _SCREAMING_SNAKE_CASE	=				hidden_act
      _SCREAMING_SNAKE_CASE	=				hidden_dim
      _SCREAMING_SNAKE_CASE	=				pooling_type
      _SCREAMING_SNAKE_CASE	=				initializer_range
      _SCREAMING_SNAKE_CASE	=				batch_norm_eps
      _SCREAMING_SNAKE_CASE	=				batch_norm_momentum
      _SCREAMING_SNAKE_CASE	=				dropout_rate
      _SCREAMING_SNAKE_CASE	=				drop_connect_rate
      _SCREAMING_SNAKE_CASE	=				sum(__lowerCamelCase   ) * 4







class 		lowercase_   (			A       ):


   """simple docstring"""

   lowerCamelCase_      =						version.parse('''1.11'''       )



   @property
   def 							lowerCAmelCase_      (   self :     Optional[Any]   ):

      """simple docstring"""
      return OrderedDict(
          [
              ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}),
          ]   )



   @property
   def 							lowerCAmelCase_      (   self :     List[Any]   ):

      """simple docstring"""
      return 1e-5

