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


_lowercase							=				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)

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

_lowercase							=				'''zero2'''
_lowercase							=				'''zero3'''
_lowercase							=				[ZEROa, ZEROa]



def      lowerCAmelCase__			(		__magic_name__			,   __magic_name__			,   __magic_name__      )						->Dict:
			# 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
			__lowercase       =       parameterized.to_safe_name("_".join(str(__magic_name__      ) for x in param.args      )      )
			return F'''{func.__name__}_{param_based_name}'''


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







@slow
@require_deepspeed
@require_torch_gpu
class 					__a     ( __a       ):



							'''simple docstring'''







							@parameterized.expand(_lowerCamelCase  ,    name_func=_lowerCamelCase       )
							def   SCREAMING_SNAKE_CASE						(     self  ,    _lowerCamelCase  ,    _lowerCamelCase       )			->							str:




										'''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   SCREAMING_SNAKE_CASE						(     self  ,    _lowerCamelCase  ,    _lowerCamelCase       )			->							Union[str, Any]:




										'''simple docstring'''
										self.run_and_check(
										    stage=_lowerCamelCase  ,    model=_lowerCamelCase  ,    distributed=_lowerCamelCase  ,    fpaa=_lowerCamelCase  ,    )
							@parameterized.expand(_lowerCamelCase  ,    name_func=_lowerCamelCase       )
							def   SCREAMING_SNAKE_CASE						(     self  ,    _lowerCamelCase  ,    _lowerCamelCase       )			->							Tuple:




										'''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   SCREAMING_SNAKE_CASE						(     self  ,    _lowerCamelCase  ,    _lowerCamelCase       )			->							int:




										'''simple docstring'''
										self.run_and_check(
										    stage=_lowerCamelCase  ,    model=_lowerCamelCase  ,    distributed=_lowerCamelCase  ,    fpaa=_lowerCamelCase  ,    )
							def   SCREAMING_SNAKE_CASE						(     self  ,    _lowerCamelCase       )			->							int:




										'''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   SCREAMING_SNAKE_CASE						(     self  ,    _lowerCamelCase  ,    _lowerCamelCase  ,    _lowerCamelCase = 10  ,    _lowerCamelCase = True  ,    _lowerCamelCase = True  ,    _lowerCamelCase = True  ,    )			->							Tuple:




										'''simple docstring'''
										__lowercase       =       models[model]

										__lowercase       =       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   SCREAMING_SNAKE_CASE						(     self  ,    _lowerCamelCase  ,    _lowerCamelCase  ,    _lowerCamelCase = 10  ,    _lowerCamelCase = 1  ,    _lowerCamelCase = True  ,    _lowerCamelCase = True  ,    )			->							Dict:




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

										__lowercase       =       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   SCREAMING_SNAKE_CASE						(     self  ,    _lowerCamelCase=False       )			->							List[Any]:




										'''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)
										__lowercase       =       min(2  ,    get_gpu_count()       ) if distributed else 1
										return f'''deepspeed --num_nodes 1 --num_gpus {num_gpus}'''.split()







"""simple docstring"""






import enum
import os
from hashlib import shaaaa
from typing import Optional

from .. import config
from .logging import get_logger


_lowercase							=				get_logger(__name__)

class 					__a     ( enum.Enum       ):



							'''simple docstring'''







							_lowerCamelCase					:			Tuple          =   """all_checks"""
							_lowerCamelCase					:			Optional[int]          =   """basic_checks"""
							_lowerCamelCase					:			str          =   """no_checks"""





class 					__a     ( __a       ):



							'''simple docstring'''












class 					__a     ( __a       ):



							'''simple docstring'''












class 					__a     ( __a       ):



							'''simple docstring'''












class 					__a     ( __a       ):



							'''simple docstring'''












def      lowerCAmelCase__			(		__magic_name__			,   __magic_name__			,   __magic_name__=None      )						->Union[str, Any]:
			if expected_checksums is None:
						logger.info("Unable to verify checksums."      )
						return
			if len(set(__magic_name__      ) - set(__magic_name__      )      ) > 0:
						raise ExpectedMoreDownloadedFiles(str(set(__magic_name__      ) - set(__magic_name__      )      )      )
			if len(set(__magic_name__      ) - set(__magic_name__      )      ) > 0:
						raise UnexpectedDownloadedFile(str(set(__magic_name__      ) - set(__magic_name__      )      )      )
			__lowercase       =       [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]]
			__lowercase       =       " for " + verification_name if verification_name is not None else ""
			if len(__magic_name__      ) > 0:
						raise NonMatchingChecksumError(
						    F'''Checksums didn\'t match{for_verification_name}:\n'''
						    F'''{bad_urls}\n'''
						    "Set `verification_mode='no_checks'` to skip checksums verification and ignore this error"      )
			logger.info("All the checksums matched successfully" + for_verification_name      )

class 					__a     ( __a       ):



							'''simple docstring'''












class 					__a     ( __a       ):



							'''simple docstring'''












class 					__a     ( __a       ):



							'''simple docstring'''












class 					__a     ( __a       ):



							'''simple docstring'''












def      lowerCAmelCase__			(		__magic_name__			,   __magic_name__      )						->Any:
			if expected_splits is None:
						logger.info("Unable to verify splits sizes."      )
						return
			if len(set(__magic_name__      ) - set(__magic_name__      )      ) > 0:
						raise ExpectedMoreSplits(str(set(__magic_name__      ) - set(__magic_name__      )      )      )
			if len(set(__magic_name__      ) - set(__magic_name__      )      ) > 0:
						raise UnexpectedSplits(str(set(__magic_name__      ) - set(__magic_name__      )      )      )
			__lowercase       =       [
			    {"expected": expected_splits[name], "recorded": recorded_splits[name]}
			    for name in expected_splits
			    if expected_splits[name].num_examples != recorded_splits[name].num_examples
			]
			if len(__magic_name__      ) > 0:
						raise NonMatchingSplitsSizesError(str(__magic_name__      )      )
			logger.info("All the splits matched successfully."      )



def      lowerCAmelCase__			(		__magic_name__			,   __magic_name__ = True      )						->dict:
			if record_checksum:
						__lowercase       =       shaaaa()
						with open(__magic_name__			,   "rb"      ) as f:
									for chunk in iter(lambda: f.read(1 << 2_0      )			,   b""      ):
												m.update(__magic_name__      )
									__lowercase       =       m.hexdigest()
			else:
						__lowercase       =       None
			return {"num_bytes": os.path.getsize(__magic_name__      ), "checksum": checksum}







def      lowerCAmelCase__			(		__magic_name__      )						->List[str]:
			if dataset_size and config.IN_MEMORY_MAX_SIZE:
						return dataset_size < config.IN_MEMORY_MAX_SIZE
			else:
						return False





