# 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


A   :     Tuple       =				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)

A   :     Optional[Any]       =				{"base": "patrickvonplaten/wav2vec2_tiny_random", "robust": "patrickvonplaten/wav2vec2_tiny_random_robust"}

A   :     Optional[Any]       =				"zero2"
A   :     int       =				"zero3"
A   :     Optional[int]       =				[ZEROa, ZEROa]


def    a__       (						__UpperCamelCase   ,					__UpperCamelCase   ,					__UpperCamelCase ):
      # 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(__UpperCAmelCase ) for x in param.args ) )
      return F'''{func.__name__}_{param_based_name}'''


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





@slow
@require_deepspeed
@require_torch_gpu
class      lowerCamelCase    (__lowerCamelCase    ):
  """simple docstring"""







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







  @require_torch_multi_gpu
  @parameterized.expand(__magic_name__     ,   name_func=__magic_name__      )
  def       __A   (							self       :				int     ,   __magic_name__       :				List[Any]     ,   __magic_name__       :				str      )     ->		Optional[int]:
        self.run_and_check(
            stage=__magic_name__     ,   model=__magic_name__     ,   distributed=__magic_name__     ,   fpaa=__magic_name__     ,   )







  @parameterized.expand(__magic_name__     ,   name_func=__magic_name__      )
  def       __A   (							self       :				str     ,   __magic_name__       :				Union[str, Any]     ,   __magic_name__       :				Dict      )     ->		Union[str, Any]:
        self.run_and_check(
            stage=__magic_name__     ,   model=__magic_name__     ,   distributed=__magic_name__     ,   fpaa=__magic_name__     ,   )







  @require_torch_multi_gpu
  @parameterized.expand(__magic_name__     ,   name_func=__magic_name__      )
  def       __A   (							self       :				Dict     ,   __magic_name__       :				Optional[Any]     ,   __magic_name__       :				Any      )     ->		str:
        self.run_and_check(
            stage=__magic_name__     ,   model=__magic_name__     ,   distributed=__magic_name__     ,   fpaa=__magic_name__     ,   )







  def       __A   (							self       :				Union[str, Any]     ,   __magic_name__       :				Any      )     ->		str:
        pass







  def       __A   (							self       :				Any     ,   __magic_name__       :				Any     ,   __magic_name__       :				str     ,   __magic_name__       :				List[Any] = 10     ,   __magic_name__       :				Optional[Any] = True     ,   __magic_name__       :				List[Any] = True     ,   __magic_name__       :				List[Any] = True     ,   )     ->		str:
        SCREAMING_SNAKE_CASE_      =     models[model]

        SCREAMING_SNAKE_CASE_      =     self.run_trainer(
            stage=__magic_name__     ,   model_name=__magic_name__     ,   eval_steps=__magic_name__     ,   num_train_epochs=1     ,   distributed=__magic_name__     ,   fpaa=__magic_name__     ,   )

        self.do_checks(__magic_name__      )

        return output_dir







  def       __A   (							self       :				Tuple     ,   __magic_name__       :				List[Any]     ,   __magic_name__       :				Optional[int]     ,   __magic_name__       :				Dict = 10     ,   __magic_name__       :				str = 1     ,   __magic_name__       :				str = True     ,   __magic_name__       :				Optional[Any] = True     ,   )     ->		Tuple:
        SCREAMING_SNAKE_CASE_      =     self.get_auto_remove_tmp_dir("./xxx"     ,   after=__magic_name__      )
        SCREAMING_SNAKE_CASE_      =     F'''\n            --model_name_or_path {model_name}\n            --dataset_name hf-internal-testing/librispeech_asr_dummy\n            --dataset_config_name clean\n            --train_split_name validation\n            --validation_split_name validation\n            --output_dir {output_dir}\n            --num_train_epochs {str(__magic_name__      )}\n            --per_device_train_batch_size 2\n            --per_device_eval_batch_size 2\n            --evaluation_strategy steps\n            --learning_rate 5e-4\n            --warmup_steps 8\n            --orthography timit\n            --preprocessing_num_workers 1\n            --group_by_length\n            --freeze_feature_extractor\n            --report_to none\n            --save_steps 0\n            --eval_steps {eval_steps}\n            --report_to none\n        '''.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(__magic_name__      )

        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(__magic_name__     ,   env=self.get_env()      )

        return output_dir







  def       __A   (							self       :				Tuple     ,   __magic_name__       :				Optional[Any]=False      )     ->		Tuple:
        SCREAMING_SNAKE_CASE_      =     min(2     ,   get_gpu_count()      ) if distributed else 1
        return F'''deepspeed --num_nodes 1 --num_gpus {num_gpus}'''.split()









import re
from pathlib import Path
from unittest import TestCase

import pytest






@pytest.mark.integration
class     lowercase__       (	__lowerCamelCase				):

   '''simple docstring'''


   def       UpperCamelCase__  (    self,		__magic_name__							) ->      Union[str, Any]:






       """simple docstring"""

       with open(__magic_name__,		encoding='''utf-8'''							) as input_file:
           UpperCamelCase__							:				Tuple          =      re.compile(R'''(?!.*\b(?:encoding|rb|w|wb|w+|wb+|ab|ab+)\b)(?<=\s)(open)\((.*)\)'''							)
           UpperCamelCase__							:				str          =      input_file.read()
           UpperCamelCase__							:				List[Any]          =      regexp.search(__magic_name__							)

       return match




   def       UpperCamelCase__  (    self,		__magic_name__							) ->      Any:






       """simple docstring"""

       with open(__magic_name__,		encoding='''utf-8'''							) as input_file:
           UpperCamelCase__							:				Dict          =      re.compile(R'''#[^\r\n]*print\(|\"[^\r\n]*print\(|\"\"\".*?print\(.*?\"\"\"|(print\()''',		re.DOTALL							)
           UpperCamelCase__							:				Any          =      input_file.read()
           # use `re.finditer` to handle the case where the ignored groups would be matched first by `re.search`
           UpperCamelCase__							:				Tuple          =      regexp.finditer(__magic_name__							)

       UpperCamelCase__							:				Dict          =      [match for match in matches if match is not None and match.group(1							) is not None]
       return matches[0] if matches else None




   def       UpperCamelCase__  (    self							) ->      List[Any]:






       """simple docstring"""
       UpperCamelCase__							:				int          =      Path('''./datasets'''							)
       UpperCamelCase__							:				Any          =      list(dataset_paths.absolute().glob('''**/*.py'''							)							)

       for dataset in dataset_files:
           if self._no_encoding_on_file_open(str(__magic_name__							)							):
               raise AssertionError(f"open(...) must use utf-8 encoding in {dataset}"							)




   def       UpperCamelCase__  (    self							) ->      Dict:






       """simple docstring"""
       UpperCamelCase__							:				Optional[int]          =      Path('''./datasets'''							)
       UpperCamelCase__							:				Optional[Any]          =      list(dataset_paths.absolute().glob('''**/*.py'''							)							)

       for dataset in dataset_files:
           if self._no_print_statements(str(__magic_name__							)							):
               raise AssertionError(f"print statement found in {dataset}. Use datasets.logger/logging instead."							)

