


# 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


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

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

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




def        snake_case_					(  snake_case      ,							snake_case      ,							snake_case					)  ->    List[str]:
       # 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__:       List[str]        =       parameterized.to_safe_name('_'.join(str(snake_case					) for x in param.args					)					)
       return f'{func.__name__}_{param_based_name}'


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





@slow
@require_deepspeed
@require_torch_gpu
class   __a      (   __UpperCamelCase				):
 @parameterized.expand(lowerCAmelCase__    ,			name_func=lowerCAmelCase__			)
 def 		SCREAMING_SNAKE_CASE__       (       self    ,			lowerCAmelCase__    ,			lowerCAmelCase__			) ->    Dict:




        '''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__			) ->    Tuple:




        '''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__			) ->    int:




        '''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__			) ->    str:




        '''simple docstring'''
        self.run_and_check(
            stage=lowerCAmelCase__    ,			model=lowerCAmelCase__    ,			distributed=lowerCAmelCase__    ,			fpaa=lowerCAmelCase__    ,			)
 def 		SCREAMING_SNAKE_CASE__       (       self    ,			lowerCAmelCase__			) ->    Optional[int]:




        '''simple docstring'''
        pass
 def 		SCREAMING_SNAKE_CASE__       (       self    ,			lowerCAmelCase__    ,			lowerCAmelCase__    ,			lowerCAmelCase__ = 10    ,			lowerCAmelCase__ = True    ,			lowerCAmelCase__ = True    ,			lowerCAmelCase__ = True    ,			) ->    Tuple:




        '''simple docstring'''
        lowercase__:       Dict        =       models[model]

        lowercase__:       Union[str, Any]        =       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    ,			) ->    str:




        '''simple docstring'''
        lowercase__:       int        =       self.get_auto_remove_tmp_dir('./xxx'    ,			after=lowerCAmelCase__			)
        lowercase__:       str        =       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(lowerCAmelCase__			)}\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
        lowercase__:       Dict        =       F'--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json'.split()
        lowercase__:       Optional[int]        =       [F'{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py']
        lowercase__:       Optional[Any]        =       self.get_launcher(lowerCAmelCase__			)

        lowercase__:       str        =       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			) ->    Union[str, Any]:




        '''simple docstring'''
        lowercase__:       Tuple        =       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 numpy import array, cos, cross, floataa, radians, sin
from numpy.typing import NDArray




def        snake_case_					(  snake_case      ,							snake_case      ,							snake_case = False					)  ->    list[float]:
       if radian_mode:
              return [magnitude * cos(snake_case					), magnitude * sin(snake_case					)]
       return [magnitude * cos(radians(snake_case					)					), magnitude * sin(radians(snake_case					)					)]




def        snake_case_					(  snake_case      ,							snake_case      ,							snake_case = 10**-1					)  ->    bool:
       lowercase__:       NDArray[floataa]        =       cross(snake_case      ,							snake_case					)
       lowercase__:       float        =       sum(snake_case					)
       return abs(snake_case					) < eps


if __name__ == "__main__":
 # Test to check if it works
 __lowerCAmelCase			=							array(
     [
         polar_force(718.4, 1_80 - 30),
         polar_force(879.54, 45),
         polar_force(1_00, -90),
     ]
 )

 __lowerCAmelCase			=							array([[0, 0], [0, 0], [0, 0]])

 assert in_static_equilibrium(forces, location)

 # Problem 1 in image_data/2D_problems.jpg
 __lowerCAmelCase			=							array(
     [
         polar_force(30 * 9.81, 15),
         polar_force(2_15, 1_80 - 45),
         polar_force(2_64, 90 - 30),
     ]
 )

 __lowerCAmelCase			=							array([[0, 0], [0, 0], [0, 0]])

 assert in_static_equilibrium(forces, location)

 # Problem in image_data/2D_problems_1.jpg
 __lowerCAmelCase			=							array([[0, -20_00], [0, -12_00], [0, 1_56_00], [0, -1_24_00]])

 __lowerCAmelCase			=							array([[0, 0], [6, 0], [10, 0], [12, 0]])

 assert in_static_equilibrium(forces, location)

 import doctest

 doctest.testmod()


