


# 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


snake_case__				:	Optional[int]					       =					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)

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

snake_case__				:	int					       =					'zero2'
snake_case__				:	List[Any]					       =					'zero3'
snake_case__				:	Optional[Any]					       =					[ZEROa, ZEROa]


def    __lowerCamelCase   (      A__						: int						,						A__						: Dict						,						A__						: List[Any]					)     ->    Optional[Any]:
   # 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
   lowerCamelCase_						:   Optional[Any]		= 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
snake_case__				:	str					       =					list(itertools.product(stages, models.keys()))





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




       '''simple docstring'''



       @parameterized.expand(__a		,				name_func=__a							)
       def 				_lowerCAmelCase							(						self				:				Optional[Any]		,				__a				:				Union[str, Any]		,				__a				:				Any							)					->Tuple:
          self.run_and_check(
              stage=__a		,				model=__a		,				distributed=__a		,				fpaa=__a		,				)



       @require_torch_multi_gpu
       @parameterized.expand(__a		,				name_func=__a							)
       def 				_lowerCAmelCase							(						self				:				List[str]		,				__a				:				Tuple		,				__a				:				List[str]							)					->List[Any]:
          self.run_and_check(
              stage=__a		,				model=__a		,				distributed=__a		,				fpaa=__a		,				)



       @parameterized.expand(__a		,				name_func=__a							)
       def 				_lowerCAmelCase							(						self				:				Tuple		,				__a				:				List[Any]		,				__a				:				str							)					->Union[str, Any]:
          self.run_and_check(
              stage=__a		,				model=__a		,				distributed=__a		,				fpaa=__a		,				)



       @require_torch_multi_gpu
       @parameterized.expand(__a		,				name_func=__a							)
       def 				_lowerCAmelCase							(						self				:				Any		,				__a				:				Tuple		,				__a				:				Dict							)					->List[Any]:
          self.run_and_check(
              stage=__a		,				model=__a		,				distributed=__a		,				fpaa=__a		,				)



       def 				_lowerCAmelCase							(						self				:				Dict		,				__a				:				Tuple							)					->str:
          # 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]		,				__a				:				str		,				__a				:				str		,				__a				:				int = 10		,				__a				:				bool = True		,				__a				:				bool = True		,				__a				:				bool = True		,				)					->Optional[Any]:
          lowerCamelCase_						:   int		= models[model]

          lowerCamelCase_						:   Any		= 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 				_lowerCAmelCase							(						self				:				List[str]		,				__a				:				str		,				__a				:				str		,				__a				:				int = 10		,				__a				:				int = 1		,				__a				:				bool = True		,				__a				:				bool = True		,				)					->Optional[int]:
          lowerCamelCase_						:   Union[str, Any]		= self.get_auto_remove_tmp_dir("""./xxx"""		,				after=__a							)
          lowerCamelCase_						:   List[str]		= 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
          lowerCamelCase_						:   Tuple		= 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_						:   Union[str, Any]		= self.get_launcher(__a							)

          lowerCamelCase_						:   int		= 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 				_lowerCAmelCase							(						self				:				Any		,				__a				:				Optional[Any]=False							)					->Any:
          # 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)
          lowerCamelCase_						:   Tuple		= min(2		,				get_gpu_count()							) if distributed else 1
          return F'''deepspeed --num_nodes 1 --num_gpus {num_gpus}'''.split()









from . import (
    albert,
    align,
    altclip,
    audio_spectrogram_transformer,
    auto,
    autoformer,
    bark,
    bart,
    barthez,
    bartpho,
    beit,
    bert,
    bert_generation,
    bert_japanese,
    bertweet,
    big_bird,
    bigbird_pegasus,
    biogpt,
    bit,
    blenderbot,
    blenderbot_small,
    blip,
    blip_a,
    bloom,
    bridgetower,
    byta,
    camembert,
    canine,
    chinese_clip,
    clap,
    clip,
    clipseg,
    codegen,
    conditional_detr,
    convbert,
    convnext,
    convnextva,
    cpm,
    cpmant,
    ctrl,
    cvt,
    dataavec,
    deberta,
    deberta_va,
    decision_transformer,
    deformable_detr,
    deit,
    deprecated,
    deta,
    detr,
    dialogpt,
    dinat,
    distilbert,
    dit,
    donut,
    dpr,
    dpt,
    efficientformer,
    efficientnet,
    electra,
    encodec,
    encoder_decoder,
    ernie,
    ernie_m,
    esm,
    falcon,
    flaubert,
    flava,
    fnet,
    focalnet,
    fsmt,
    funnel,
    git,
    glpn,
    gpta,
    gpt_bigcode,
    gpt_neo,
    gpt_neox,
    gpt_neox_japanese,
    gpt_swa,
    gptj,
    gptsan_japanese,
    graphormer,
    groupvit,
    herbert,
    hubert,
    ibert,
    imagegpt,
    informer,
    instructblip,
    jukebox,
    layoutlm,
    layoutlmva,
    layoutlmva,
    layoutxlm,
    led,
    levit,
    lilt,
    llama,
    longformer,
    longta,
    luke,
    lxmert,
    mam_aaa,
    marian,
    markuplm,
    maskaformer,
    maskformer,
    mbart,
    mbartaa,
    mega,
    megatron_bert,
    megatron_gpta,
    mgp_str,
    mluke,
    mobilebert,
    mobilenet_va,
    mobilenet_va,
    mobilevit,
    mobilevitva,
    mpnet,
    mra,
    mta,
    musicgen,
    mvp,
    nat,
    nezha,
    nllb,
    nllb_moe,
    nystromformer,
    oneformer,
    open_llama,
    openai,
    opt,
    owlvit,
    pegasus,
    pegasus_x,
    perceiver,
    phobert,
    pixastruct,
    plbart,
    poolformer,
    prophetnet,
    qdqbert,
    rag,
    realm,
    reformer,
    regnet,
    rembert,
    resnet,
    roberta,
    roberta_prelayernorm,
    roc_bert,
    roformer,
    rwkv,
    sam,
    segformer,
    sew,
    sew_d,
    speech_encoder_decoder,
    speech_to_text,
    speech_to_text_a,
    speechta,
    splinter,
    squeezebert,
    swiftformer,
    swin,
    swinasr,
    swinva,
    switch_transformers,
    ta,
    table_transformer,
    tapas,
    time_series_transformer,
    timesformer,
    timm_backbone,
    transfo_xl,
    trocr,
    tvlt,
    umta,
    unispeech,
    unispeech_sat,
    upernet,
    videomae,
    vilt,
    vision_encoder_decoder,
    vision_text_dual_encoder,
    visual_bert,
    vit,
    vit_hybrid,
    vit_mae,
    vit_msn,
    vivit,
    wavaveca,
    wavaveca_conformer,
    wavaveca_phoneme,
    wavaveca_with_lm,
    wavlm,
    whisper,
    x_clip,
    xglm,
    xlm,
    xlm_prophetnet,
    xlm_roberta,
    xlm_roberta_xl,
    xlnet,
    xmod,
    yolos,
    yoso,
)





