# 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


__UpperCamelCase	: Optional[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(42)

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

__UpperCamelCase	: List[str]    		=  'zero2'
__UpperCamelCase	: Any    		=  'zero3'
__UpperCamelCase	: Any    		=  [ZEROa, ZEROa]
def    A			(					_lowercase	,						_lowercase	,						_lowercase		):
						# 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							:					int           =							parameterized.to_safe_name('''_'''.join(str(_lowercase		) for x in param.args		)		)
						return f"""{func.__name__}_{param_based_name}"""


# Cartesian-product of zero stages with models to test
__UpperCamelCase	: Optional[int]    		=  list(itertools.product(stages, models.keys()))





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


						@parameterized.expand(UpperCamelCase__					,	name_func=UpperCamelCase__		)
						def  __A ( self			:       Union[str, Any]					,	UpperCamelCase__			:       List[Any]					,	UpperCamelCase__			:       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  __A ( self			:       List[str]					,	UpperCamelCase__			:       Tuple					,	UpperCamelCase__			:       int		):





												'''simple docstring'''





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


						@parameterized.expand(UpperCamelCase__					,	name_func=UpperCamelCase__		)
						def  __A ( self			:       Dict					,	UpperCamelCase__			:       Optional[Any]					,	UpperCamelCase__			:       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  __A ( self			:       Dict					,	UpperCamelCase__			:       Optional[Any]					,	UpperCamelCase__			:       str		):





												'''simple docstring'''





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


						def  __A ( self			:       Optional[Any]					,	UpperCamelCase__			:       Tuple		):





												'''simple docstring'''





												pass


						def  __A ( self			:       Tuple					,	UpperCamelCase__			:       str					,	UpperCamelCase__			:       str					,	UpperCamelCase__			:       int = 10					,	UpperCamelCase__			:       bool = True					,	UpperCamelCase__			:       bool = True					,	UpperCamelCase__			:       bool = True					,	):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					str           =							models[model]

												SCREAMING_SNAKE_CASE							:					Optional[int]           =							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  __A ( self			:       str					,	UpperCamelCase__			:       str					,	UpperCamelCase__			:       str					,	UpperCamelCase__			:       int = 10					,	UpperCamelCase__			:       int = 1					,	UpperCamelCase__			:       bool = True					,	UpperCamelCase__			:       bool = True					,	):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					str           =							self.get_auto_remove_tmp_dir('''./xxx'''					,	after=UpperCamelCase__		)
												SCREAMING_SNAKE_CASE							:					Optional[int]           =							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
												SCREAMING_SNAKE_CASE							:					Optional[int]           =							f"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split()
												SCREAMING_SNAKE_CASE							:					Optional[int]           =							[f"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""]
												SCREAMING_SNAKE_CASE							:					List[str]           =							self.get_launcher(UpperCamelCase__		)

												SCREAMING_SNAKE_CASE							:					Tuple           =							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  __A ( self			:       Any					,	UpperCamelCase__			:       Any=False		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					int           =							min(2					,	get_gpu_count()		) if distributed else 1
												return f"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()






from __future__ import annotations

from typing import Any





class       lowercase__		(     UpperCamelCase_):
						pass






class       lowercase__		:


						def __init__( self			:       Union[str, Any]					,	UpperCamelCase__			:       Any		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					Any           =							data
												SCREAMING_SNAKE_CASE							:					Node | None           =							None


						def __iter__( self			:       Any		):





												'''simple docstring'''





												SCREAMING_SNAKE_CASE							:					List[str]           =							self
												SCREAMING_SNAKE_CASE							:					Tuple           =							[]
												while node:
																		if node in visited:
																								raise ContainsLoopError
																		visited.append(UpperCamelCase__		)
																		yield node.data
																		SCREAMING_SNAKE_CASE							:					Dict           =							node.next_node



						@property
						def  __A ( self			:       Optional[int]		):





												'''simple docstring'''





												try:
																		list(self		)
																		return False
												except ContainsLoopError:
																		return True


if __name__ == "__main__":
					__UpperCamelCase	: List[Any]    		=  Node(1)
					__UpperCamelCase	: str    		=  Node(2)
					__UpperCamelCase	: Dict    		=  Node(3)
					__UpperCamelCase	: List[Any]    		=  Node(4)
					print(root_node.has_loop)  # False
					__UpperCamelCase	: int    		=  root_node.next_node
					print(root_node.has_loop)  # True

					__UpperCamelCase	: Union[str, Any]    		=  Node(5)
					__UpperCamelCase	: Union[str, Any]    		=  Node(6)
					__UpperCamelCase	: List[Any]    		=  Node(5)
					__UpperCamelCase	: List[str]    		=  Node(6)
					print(root_node.has_loop)  # False

					__UpperCamelCase	: List[Any]    		=  Node(1)
					print(root_node.has_loop)  # False





