


"""simple docstring"""





from collections import OrderedDict
from typing import Mapping

from packaging import version

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


lowerCamelCase       	=						logging.get_logger(__name__)

lowerCamelCase       	=						{
    '''hustvl/yolos-small''': '''https://huggingface.co/hustvl/yolos-small/resolve/main/config.json''',
    # See all YOLOS models at https://huggingface.co/models?filter=yolos
}
class 				lowercase__       (   _a				):







       '''simple docstring'''


       UpperCamelCase						=					"""yolos"""



       def __init__(							self      :  List[str]		,    _UpperCAmelCase      :  Any=768		,    _UpperCAmelCase      :  Union[str, Any]=12		,    _UpperCAmelCase      :  List[Any]=12		,    _UpperCAmelCase      :  List[str]=3072		,    _UpperCAmelCase      :  str="gelu"		,    _UpperCAmelCase      :  str=0.0		,    _UpperCAmelCase      :  Any=0.0		,    _UpperCAmelCase      :  Tuple=0.02		,    _UpperCAmelCase      :  List[Any]=1e-12		,    _UpperCAmelCase      :  str=[512, 864]		,    _UpperCAmelCase      :  Optional[Any]=16		,    _UpperCAmelCase      :  Union[str, Any]=3		,    _UpperCAmelCase      :  List[str]=True		,    _UpperCAmelCase      :  Optional[Any]=100		,    _UpperCAmelCase      :  Any=True		,    _UpperCAmelCase      :  List[Any]=False		,    _UpperCAmelCase      :  List[Any]=1		,    _UpperCAmelCase      :  Tuple=5		,    _UpperCAmelCase      :  Union[str, Any]=2		,    _UpperCAmelCase      :  List[str]=5		,    _UpperCAmelCase      :  Optional[Any]=2		,    _UpperCAmelCase      :  int=0.1		,    **_UpperCAmelCase      :  Optional[int]		,    )			->						int:


             '''simple docstring'''




             super().__init__(**__lowerCamelCase   )

             UpperCAmelCase_      			=							hidden_size
             UpperCAmelCase_      			=							num_hidden_layers
             UpperCAmelCase_      			=							num_attention_heads
             UpperCAmelCase_      			=							intermediate_size
             UpperCAmelCase_      			=							hidden_act
             UpperCAmelCase_      			=							hidden_dropout_prob
             UpperCAmelCase_      			=							attention_probs_dropout_prob
             UpperCAmelCase_      			=							initializer_range
             UpperCAmelCase_      			=							layer_norm_eps
             UpperCAmelCase_      			=							image_size
             UpperCAmelCase_      			=							patch_size
             UpperCAmelCase_      			=							num_channels
             UpperCAmelCase_      			=							qkv_bias
             UpperCAmelCase_      			=							num_detection_tokens
             UpperCAmelCase_      			=							use_mid_position_embeddings
             UpperCAmelCase_      			=							auxiliary_loss
             # Hungarian matcher
             UpperCAmelCase_      			=							class_cost
             UpperCAmelCase_      			=							bbox_cost
             UpperCAmelCase_      			=							giou_cost
             # Loss coefficients
             UpperCAmelCase_      			=							bbox_loss_coefficient
             UpperCAmelCase_      			=							giou_loss_coefficient
             UpperCAmelCase_      			=							eos_coefficient



class 				lowercase__       (   _a				):







       '''simple docstring'''


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



       @property
       def 					lowercase__    (							self      :  Any   )			->						Any:


             '''simple docstring'''




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



       @property
       def 					lowercase__    (							self      :  List[str]   )			->						Any:


             '''simple docstring'''




             return 1e-4







       @property
       def 					lowercase__    (							self      :  List[Any]   )			->						Dict:


             '''simple docstring'''




             return 12









"""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        a__     (				lowerCAmelCase__     ,      lowerCAmelCase__     ,      lowerCAmelCase__				):
      # 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
      UpperCAmelCase_      			=							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
lowerCamelCase       	=						list(itertools.product(stages, models.keys()))


@slow
@require_deepspeed
@require_torch_gpu
class 				lowercase__       (   SCREAMING_SNAKE_CASE				):







       '''simple docstring'''


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


             '''simple docstring'''




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



       @require_torch_multi_gpu
       @parameterized.expand(_UpperCAmelCase		,    name_func=_UpperCAmelCase   )
       def 					lowercase__    (							self      :  Any		,    _UpperCAmelCase      :  Optional[Any]		,    _UpperCAmelCase      :  str   )			->						Any:


             '''simple docstring'''




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



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


             '''simple docstring'''




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



       @require_torch_multi_gpu
       @parameterized.expand(_UpperCAmelCase		,    name_func=_UpperCAmelCase   )
       def 					lowercase__    (							self      :  int		,    _UpperCAmelCase      :  int		,    _UpperCAmelCase      :  Optional[int]   )			->						Optional[int]:


             '''simple docstring'''




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



       def 					lowercase__    (							self      :  Optional[Any]		,    _UpperCAmelCase      :  Tuple   )			->						Optional[int]:


             '''simple docstring'''




             pass



       def 					lowercase__    (							self      :  Optional[Any]		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  int = 10		,    _UpperCAmelCase      :  bool = True		,    _UpperCAmelCase      :  bool = True		,    _UpperCAmelCase      :  bool = True		,    )			->						Optional[Any]:


             '''simple docstring'''




             UpperCAmelCase_      			=							models[model]

             UpperCAmelCase_      			=							self.run_trainer(
                 stage=_UpperCAmelCase		,    model_name=_UpperCAmelCase		,    eval_steps=_UpperCAmelCase		,    num_train_epochs=1		,    distributed=_UpperCAmelCase		,    fpaa=_UpperCAmelCase		,    )

             self.do_checks(_UpperCAmelCase   )

             return output_dir



       def 					lowercase__    (							self      :  Union[str, Any]		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  str		,    _UpperCAmelCase      :  int = 10		,    _UpperCAmelCase      :  int = 1		,    _UpperCAmelCase      :  bool = True		,    _UpperCAmelCase      :  bool = True		,    )			->						Tuple:


             '''simple docstring'''




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

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

             return output_dir







       def 					lowercase__    (							self      :  List[Any]		,    _UpperCAmelCase      :  int=False   )			->						Optional[Any]:


             '''simple docstring'''




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




