


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


a_					:    Any          =    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(4_2)

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

a_					:    List[Any]          =    "zero2"
a_					:    str          =    "zero3"
a_					:    Tuple          =    [ZEROa, ZEROa]






def 	_A				(lowerCAmelCase__  :Union[str, Any]				,						lowerCAmelCase__  :Any				,						lowerCAmelCase__  :str		)   ->  Optional[Any]:




     '''simple docstring'''



     _a			      =							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
a_					:    Optional[Any]          =    list(itertools.product(stages, models.keys()))






@slow
@require_deepspeed
@require_torch_gpu
class  a     (     _SCREAMING_SNAKE_CASE       ):
 @parameterized.expand(__magic_name__      ,				name_func=__magic_name__						)
 def 							__UpperCAmelCase		( self      ,				__magic_name__      ,				__magic_name__						)					->							List[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 							__UpperCAmelCase		( self      ,				__magic_name__      ,				__magic_name__						)					->							List[Any]:
      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 							__UpperCAmelCase		( self      ,				__magic_name__      ,				__magic_name__						)					->							str:
      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 							__UpperCAmelCase		( self      ,				__magic_name__      ,				__magic_name__						)					->							Tuple:
      self.run_and_check(
          stage=__magic_name__      ,				model=__magic_name__      ,				distributed=__magic_name__      ,				fpaa=__magic_name__      ,				)
 def 							__UpperCAmelCase		( self      ,				__magic_name__						)					->							Optional[int]:
      # 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 							__UpperCAmelCase		( self      ,				__magic_name__      ,				__magic_name__      ,				__magic_name__ = 10      ,				__magic_name__ = True      ,				__magic_name__ = True      ,				__magic_name__ = True      ,				)					->							Optional[Any]:
      _a			      =							models[model]

      _a			      =							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 							__UpperCAmelCase		( self      ,				__magic_name__      ,				__magic_name__      ,				__magic_name__ = 10      ,				__magic_name__ = 1      ,				__magic_name__ = True      ,				__magic_name__ = True      ,				)					->							str:
      _a			      =							self.get_auto_remove_tmp_dir('./xxx'      ,				after=__magic_name__						)
      _a			      =							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
      _a			      =							f'--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json'.split()
      _a			      =							[f'{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py']
      _a			      =							self.get_launcher(__magic_name__						)

      _a			      =							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 							__UpperCAmelCase		( self      ,				__magic_name__=False						)					->							Optional[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)
      _a			      =							min(2      ,				get_gpu_count()						) if distributed else 1
      return f'deepspeed --num_nodes 1 --num_gpus {num_gpus}'.split()





'''simple docstring'''






import pytest

from datasets.splits import SplitDict, SplitInfo
from datasets.utils.py_utils import asdict






@pytest.mark.parametrize(
    'split_dict'				,						[
        SplitDict(),
        SplitDict({'train': SplitInfo(name='train'				,						num_bytes=13_37				,						num_examples=42				,						dataset_name='my_dataset'		)}		),
        SplitDict({'train': SplitInfo(name='train'				,						num_bytes=13_37				,						num_examples=42		)}		),
        SplitDict({'train': SplitInfo()}		),
    ]				,						)
def 	_A				(lowerCAmelCase__  :SplitDict		)   ->  Any:




     '''simple docstring'''



     _a			      =							split_dict._to_yaml_list()
     assert len(lowerCAmelCase__		) == len(lowerCAmelCase__		)
     _a			      =							SplitDict._from_yaml_list(lowerCAmelCase__		)
     for split_name, split_info in split_dict.items():
          # dataset_name field is deprecated, and is therefore not part of the YAML dump
          _a			      =							None
          # the split name of split_dict takes over the name of the split info object
          _a			      =							split_name
     assert split_dict == reloaded






@pytest.mark.parametrize(
    'split_info'				,						[SplitInfo(), SplitInfo(dataset_name=lowerCAmelCase__		), SplitInfo(dataset_name='my_dataset'		)]		)
def 	_A				(lowerCAmelCase__  :Optional[Any]		)   ->  List[str]:




     '''simple docstring'''



     _a			      =							asdict(SplitDict({'train': split_info}		)		)
     assert "dataset_name" in split_dict_asdict["train"]
     assert split_dict_asdict["train"]["dataset_name"] == split_info.dataset_name

