





import sys
from pathlib import Path


lowercase				:	Dict      						=  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)

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

lowercase				:	Optional[Any]      						=  """zero2"""
lowercase				:	List[str]      						=  """zero3"""
lowercase				:	Optional[Any]      						=  [ZEROa, ZEROa]



def A_     (		A__		,				A__		,				A__    )  ->		List[str]:
       a__						:     str			=    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
lowercase				:	Tuple      						=  list(itertools.product(stages, models.keys()))





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




   """simple docstring"""



   @parameterized.expand(__A ,  name_func=__A)
   def 							__lowercase		( self ,  lowercase ,  lowercase)      ->						str:







          '''simple docstring'''

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

   @require_torch_multi_gpu
   @parameterized.expand(__A ,  name_func=__A)
   def 							__lowercase		( self ,  lowercase ,  lowercase)      ->						List[Any]:







          '''simple docstring'''

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

   @parameterized.expand(__A ,  name_func=__A)
   def 							__lowercase		( self ,  lowercase ,  lowercase)      ->						str:







          '''simple docstring'''

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

   @require_torch_multi_gpu
   @parameterized.expand(__A ,  name_func=__A)
   def 							__lowercase		( self ,  lowercase ,  lowercase)      ->						Tuple:







          '''simple docstring'''

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

   def 							__lowercase		( self ,  lowercase)      ->						List[str]:







          '''simple docstring'''

          pass

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase = 10 ,  lowercase = True ,  lowercase = True ,  lowercase = True ,  )      ->						Tuple:







          '''simple docstring'''

          a__						:     Optional[Any]			=    models[model]

          a__						:     Tuple			=    self.run_trainer(
              stage=__A ,  model_name=__A ,  eval_steps=__A ,  num_train_epochs=1 ,  distributed=__A ,  fpaa=__A ,  )

          self.do_checks(__A)

          return output_dir

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase = 10 ,  lowercase = 1 ,  lowercase = True ,  lowercase = True ,  )      ->						List[str]:







          '''simple docstring'''

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

          a__						:     Union[str, Any]			=    launcher + script + args + ds_args
          # keep for quick debug
          # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
          execute_subprocess_async(__A ,  env=self.get_env())

          return output_dir

   def 							__lowercase		( self ,  lowercase=False)      ->						str:







          '''simple docstring'''

          a__						:     Any			=    min(2 ,  get_gpu_count()) if distributed else 1
          return F'deepspeed --num_nodes 1 --num_gpus {num_gpus}'.split()









import unittest

from transformers import is_tf_available
from transformers.testing_utils import require_tf


if is_tf_available():
    import tensorflow as tf
    from tensorflow.python.eager import context
    from tensorflow.python.framework import ops

    from transformers import GradientAccumulator, create_optimizer





@require_tf
class 			A__   (							unittest.TestCase     ):




   """simple docstring"""



   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase)      ->						List[str]:







          '''simple docstring'''

          self.assertEqual(len(lowercase) ,  len(lowercase))
          for a, b in zip(lowercase ,  lowercase):
                 self.assertAlmostEqual(lowercase ,  lowercase ,  delta=lowercase)

   def 							__lowercase		( self)      ->						Any:







          '''simple docstring'''

          a__						:     Tuple			=    GradientAccumulator()
          accumulator([tf.constant([1.0, 2.0])])
          accumulator([tf.constant([-2.0, 1.0])])
          accumulator([tf.constant([-1.0, 2.0])])
          with self.assertRaises(lowercase):
                 accumulator([tf.constant([1.0, 1.0]), tf.constant([2.0, 2.0])])
          self.assertEqual(accumulator.step ,  3)
          self.assertEqual(len(accumulator.gradients) ,  1)
          self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() ,  [-2.0, 5.0] ,  tol=1e-2)
          accumulator.reset()
          self.assertEqual(accumulator.step ,  0)
          self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist() ,  [0.0, 0.0] ,  tol=1e-2)

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







          '''simple docstring'''

          a__						:     Tuple			=    None
          ops.enable_eager_execution_internal()
          a__						:     Optional[int]			=    tf.config.list_physical_devices('CPU')
          if len(lowercase) == 1:
                 tf.config.set_logical_device_configuration(
                     physical_devices[0] ,  [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()])
          a__						:     int			=    tf.config.list_logical_devices(device_type='CPU')
          a__						:     Union[str, Any]			=    tf.distribute.MirroredStrategy(devices=devices[:2])

          with strategy.scope():
                 a__						:     str			=    GradientAccumulator()
                 a__						:     Tuple			=    tf.Variable([4.0, 3.0])
                 a__			,							a__						:     Tuple			=    create_optimizer(5e-5 ,  10 ,  5)
                 a__						:     Tuple			=    tf.Variable([0.0, 0.0] ,  trainable=lowercase)

          def accumulate_on_replica(lowercase):
                 accumulator([gradient])

          def apply_on_replica():
                 optimizer.apply_gradients(list(zip(accumulator.gradients ,  [variable])))

          @tf.function
          def accumulate(lowercase ,  lowercase):
                 with strategy.scope():
                        a__						:     Union[str, Any]			=    strategy.experimental_local_results(lowercase)
                        local_variables[0].assign(lowercase)
                        local_variables[1].assign(lowercase)
                        strategy.run(lowercase ,  args=(gradient_placeholder,))

          @tf.function
          def apply_grad():
                 with strategy.scope():
                        strategy.run(lowercase)

          def _check_local_values(lowercase ,  lowercase):
                 a__						:     Union[str, Any]			=    strategy.experimental_local_results(accumulator._gradients[0])
                 self.assertListAlmostEqual(values[0].value() ,  lowercase ,  tol=1e-2)
                 self.assertListAlmostEqual(values[1].value() ,  lowercase ,  tol=1e-2)

          accumulate([1.0, 2.0] ,  [-1.0, 1.0])
          accumulate([3.0, -1.0] ,  [-1.0, -1.0])
          accumulate([-2.0, 2.0] ,  [3.0, -2.0])
          self.assertEqual(accumulator.step ,  3)
          _check_local_values([2.0, 3.0] ,  [1.0, -2.0])
          apply_grad()
          self.assertListAlmostEqual(variable.value() ,  [4.0, 3.0] ,  tol=1e-2)
          accumulator.reset()
          self.assertEqual(accumulator.step ,  0)
          _check_local_values([0.0, 0.0] ,  [0.0, 0.0])


