




# 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_									=	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_									=	{'base': 'patrickvonplaten/wav2vec2_tiny_random', 'robust': 'patrickvonplaten/wav2vec2_tiny_random_robust'}

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




def 					lowerCamelCase__       (						A__       :					int  ,			A__       :					Union[str, Any]  ,			A__       :					List[Any]	):





       '''simple docstring'''



       __lowerCamelCase   =						parameterized.to_safe_name("""_""".join(str(A__	) for x in param.args	)	)
       return f'{func.__name__}_{param_based_name}'


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





@slow
@require_deepspeed
@require_torch_gpu
class     lowerCamelCase__(					__lowerCamelCase):
      @parameterized.expand(UpperCamelCase_    ,       name_func=UpperCamelCase_   )
      def 			lowerCAmelCase__						(				self: List[Any]    ,       UpperCamelCase_: List[str]    ,       UpperCamelCase_: int   ):
             self.run_and_check(
                 stage=UpperCamelCase_    ,       model=UpperCamelCase_    ,       distributed=UpperCamelCase_    ,       fpaa=UpperCamelCase_    ,       )
      @require_torch_multi_gpu
      @parameterized.expand(UpperCamelCase_    ,       name_func=UpperCamelCase_   )
      def 			lowerCAmelCase__						(				self: List[str]    ,       UpperCamelCase_: Optional[Any]    ,       UpperCamelCase_: Optional[Any]   ):
             self.run_and_check(
                 stage=UpperCamelCase_    ,       model=UpperCamelCase_    ,       distributed=UpperCamelCase_    ,       fpaa=UpperCamelCase_    ,       )
      @parameterized.expand(UpperCamelCase_    ,       name_func=UpperCamelCase_   )
      def 			lowerCAmelCase__						(				self: Optional[int]    ,       UpperCamelCase_: int    ,       UpperCamelCase_: List[Any]   ):
             self.run_and_check(
                 stage=UpperCamelCase_    ,       model=UpperCamelCase_    ,       distributed=UpperCamelCase_    ,       fpaa=UpperCamelCase_    ,       )
      @require_torch_multi_gpu
      @parameterized.expand(UpperCamelCase_    ,       name_func=UpperCamelCase_   )
      def 			lowerCAmelCase__						(				self: List[str]    ,       UpperCamelCase_: List[str]    ,       UpperCamelCase_: List[str]   ):
             self.run_and_check(
                 stage=UpperCamelCase_    ,       model=UpperCamelCase_    ,       distributed=UpperCamelCase_    ,       fpaa=UpperCamelCase_    ,       )
      def 			lowerCAmelCase__						(				self: Optional[Any]    ,       UpperCamelCase_: str   ):
             # 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 			lowerCAmelCase__						(				self: List[str]    ,       UpperCamelCase_: str    ,       UpperCamelCase_: str    ,       UpperCamelCase_: int = 10    ,       UpperCamelCase_: bool = True    ,       UpperCamelCase_: bool = True    ,       UpperCamelCase_: bool = True    ,       ):
             __lowerCamelCase   =						models[model]

             __lowerCamelCase   =						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 			lowerCAmelCase__						(				self: Optional[Any]    ,       UpperCamelCase_: str    ,       UpperCamelCase_: str    ,       UpperCamelCase_: int = 10    ,       UpperCamelCase_: int = 1    ,       UpperCamelCase_: bool = True    ,       UpperCamelCase_: bool = True    ,       ):
             __lowerCamelCase   =						self.get_auto_remove_tmp_dir("""./xxx"""    ,       after=UpperCamelCase_   )
             __lowerCamelCase   =						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(UpperCamelCase_   )}\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
             __lowerCamelCase   =						F'--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json'.split()
             __lowerCamelCase   =						[F'{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py']
             __lowerCamelCase   =						self.get_launcher(UpperCamelCase_   )

             __lowerCamelCase   =						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 			lowerCAmelCase__						(				self: Tuple    ,       UpperCamelCase_: Optional[Any]=False   ):
             # 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)
             __lowerCamelCase   =						min(2    ,       get_gpu_count()   ) if distributed else 1
             return F'deepspeed --num_nodes 1 --num_gpus {num_gpus}'.split()







from tempfile import TemporaryDirectory
from unittest import TestCase
from unittest.mock import MagicMock, patch

from transformers import AutoModel, TFAutoModel
from transformers.onnx import FeaturesManager
from transformers.testing_utils import SMALL_MODEL_IDENTIFIER, require_tf, require_torch





@require_torch
@require_tf
class     lowerCamelCase__(					__lowerCamelCase):
      def 			lowerCAmelCase__						(				self: List[Any]   ):
             __lowerCamelCase   =						SMALL_MODEL_IDENTIFIER
             __lowerCamelCase   =						"""pt"""
             __lowerCamelCase   =						"""tf"""
      def 			lowerCAmelCase__						(				self: Optional[Any]    ,       UpperCamelCase_: Optional[Any]   ):
             __lowerCamelCase   =						AutoModel.from_pretrained(self.test_model   )
             model_pt.save_pretrained(UpperCamelCase_   )
      def 			lowerCAmelCase__						(				self: Tuple    ,       UpperCamelCase_: Union[str, Any]   ):
             __lowerCamelCase   =						TFAutoModel.from_pretrained(self.test_model    ,       from_pt=UpperCamelCase_   )
             model_tf.save_pretrained(UpperCamelCase_   )
      def 			lowerCAmelCase__						(				self: Union[str, Any]   ):
             __lowerCamelCase   =						"""mock_framework"""

             # Framework provided - return whatever the user provides
             __lowerCamelCase   =						FeaturesManager.determine_framework(self.test_model    ,       UpperCamelCase_   )
             self.assertEqual(UpperCamelCase_    ,       UpperCamelCase_   )

             # Local checkpoint and framework provided - return provided framework
             # PyTorch checkpoint
             with TemporaryDirectory() as local_pt_ckpt:
                    self._setup_pt_ckpt(UpperCamelCase_   )
                    __lowerCamelCase   =						FeaturesManager.determine_framework(UpperCamelCase_    ,       UpperCamelCase_   )
                    self.assertEqual(UpperCamelCase_    ,       UpperCamelCase_   )

             # TensorFlow checkpoint
             with TemporaryDirectory() as local_tf_ckpt:
                    self._setup_tf_ckpt(UpperCamelCase_   )
                    __lowerCamelCase   =						FeaturesManager.determine_framework(UpperCamelCase_    ,       UpperCamelCase_   )
                    self.assertEqual(UpperCamelCase_    ,       UpperCamelCase_   )
      def 			lowerCAmelCase__						(				self: int   ):
             # PyTorch checkpoint
             with TemporaryDirectory() as local_pt_ckpt:
                    self._setup_pt_ckpt(UpperCamelCase_   )
                    __lowerCamelCase   =						FeaturesManager.determine_framework(UpperCamelCase_   )
                    self.assertEqual(UpperCamelCase_    ,       self.framework_pt   )

             # TensorFlow checkpoint
             with TemporaryDirectory() as local_tf_ckpt:
                    self._setup_tf_ckpt(UpperCamelCase_   )
                    __lowerCamelCase   =						FeaturesManager.determine_framework(UpperCamelCase_   )
                    self.assertEqual(UpperCamelCase_    ,       self.framework_tf   )

             # Invalid local checkpoint
             with TemporaryDirectory() as local_invalid_ckpt:
                    with self.assertRaises(UpperCamelCase_   ):
                           __lowerCamelCase   =						FeaturesManager.determine_framework(UpperCamelCase_   )




      def 			lowerCAmelCase__						(				self: Optional[int]   ):
             __lowerCamelCase   =						MagicMock(return_value=UpperCamelCase_   )
             with patch("""transformers.onnx.features.is_tf_available"""    ,       UpperCamelCase_   ):
                    __lowerCamelCase   =						FeaturesManager.determine_framework(self.test_model   )
                    self.assertEqual(UpperCamelCase_    ,       self.framework_pt   )

             # PyTorch not in environment -> use TensorFlow
             __lowerCamelCase   =						MagicMock(return_value=UpperCamelCase_   )
             with patch("""transformers.onnx.features.is_torch_available"""    ,       UpperCamelCase_   ):
                    __lowerCamelCase   =						FeaturesManager.determine_framework(self.test_model   )
                    self.assertEqual(UpperCamelCase_    ,       self.framework_tf   )

             # Both in environment -> use PyTorch
             __lowerCamelCase   =						MagicMock(return_value=UpperCamelCase_   )
             __lowerCamelCase   =						MagicMock(return_value=UpperCamelCase_   )
             with patch("""transformers.onnx.features.is_tf_available"""    ,       UpperCamelCase_   ), patch(
                 """transformers.onnx.features.is_torch_available"""    ,       UpperCamelCase_   ):
                    __lowerCamelCase   =						FeaturesManager.determine_framework(self.test_model   )
                    self.assertEqual(UpperCamelCase_    ,       self.framework_pt   )

             # Both not in environment -> raise error
             __lowerCamelCase   =						MagicMock(return_value=UpperCamelCase_   )
             __lowerCamelCase   =						MagicMock(return_value=UpperCamelCase_   )
             with patch("""transformers.onnx.features.is_tf_available"""    ,       UpperCamelCase_   ), patch(
                 """transformers.onnx.features.is_torch_available"""    ,       UpperCamelCase_   ):
                    with self.assertRaises(UpperCamelCase_   ):
                           __lowerCamelCase   =						FeaturesManager.determine_framework(self.test_model   )

