





# 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	:					Tuple			  =					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	:					Optional[int]			  =					{"""base""": """patrickvonplaten/wav2vec2_tiny_random""", """robust""": """patrickvonplaten/wav2vec2_tiny_random_robust"""}

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



def 		A_    (					_lowerCAmelCase							,       _lowerCAmelCase							,       _lowerCAmelCase					)						->			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
 UpperCamelCase     : int	     =       parameterized.to_safe_name("_".join(str(_lowerCAmelCase					) for x in param.args					)					)
 return F"""{func.__name__}_{param_based_name}"""


# Cartesian-product of zero stages with models to test
__lowerCamelCase	:					List[Any]			  =					list(itertools.product(stages, models.keys()))



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





      @parameterized.expand(A_	,							name_func=A_       )
      def 	__UpperCamelCase(			self	,							A_	,							A_       ):
       '''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 	__UpperCamelCase(			self	,							A_	,							A_       ):
       '''simple docstring'''




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





      @parameterized.expand(A_	,							name_func=A_       )
      def 	__UpperCamelCase(			self	,							A_	,							A_       ):
       '''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 	__UpperCamelCase(			self	,							A_	,							A_       ):
       '''simple docstring'''




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





      def 	__UpperCamelCase(			self	,							A_       ):
       '''simple docstring'''




       pass





      def 	__UpperCamelCase(			self	,							A_	,							A_	,							A_ = 10	,							A_ = True	,							A_ = True	,							A_ = True	,							):
       '''simple docstring'''




       UpperCamelCase     : Dict	     =       models[model]

       UpperCamelCase     : List[str]	     =       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 	__UpperCamelCase(			self	,							A_	,							A_	,							A_ = 10	,							A_ = 1	,							A_ = True	,							A_ = True	,							):
       '''simple docstring'''




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

       UpperCamelCase     : List[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 	__UpperCamelCase(			self	,							A_=False       ):
       '''simple docstring'''




       UpperCamelCase     : Union[str, Any]	     =       min(2	,							get_gpu_count()       ) if distributed else 1
       return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()







import time
import warnings
from abc import ABC
from copy import deepcopy
from typing import Optional

import torch

from ..utils import add_start_docstrings, logging


__lowerCamelCase	:					List[str]			  =					logging.get_logger(__name__)


__lowerCamelCase	:					Any			  =					r"""
    Args:
        input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
            Indices of input sequence tokens in the vocabulary.

            Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
            [`PreTrainedTokenizer.__call__`] for details.

            [What are input IDs?](../glossary#input-ids)
        scores (`torch.FloatTensor` of shape `(batch_size, config.vocab_size)`):
            Prediction scores of a language modeling head. These can be scores for each vocabulary token before SoftMax
            or scores for each vocabulary token after SoftMax.
        kwargs (`Dict[str, Any]`, *optional*):
            Additional stopping criteria specific kwargs.

    Return:
        `bool`. `False` indicates we should continue, `True` indicates we should stop.

"""



class  A__       (	__snake_case      ):





      @add_start_docstrings(A_       )
      def __call__(			self	,							A_	,							A_	,							**A_       ):
       '''simple docstring'''




       raise NotImplementedError("StoppingCriteria needs to be subclassed"       )



class  A__       (	__snake_case      ):





      def __init__(			self	,							A_	,							A_ = None       ):
       '''simple docstring'''




       UpperCamelCase     : Union[str, Any]	     =       max_length
       UpperCamelCase     : Dict	     =       max_position_embeddings





      @add_start_docstrings(A_       )
      def __call__(			self	,							A_	,							A_	,							**A_       ):
       '''simple docstring'''




       UpperCamelCase     : int	     =       input_ids.shape[-1]
       UpperCamelCase     : str	     =       cur_len >= self.max_length
       if self.max_position_embeddings is not None and not is_done and cur_len >= self.max_position_embeddings:
        logger.warning_once(
            "This is a friendly reminder - the current text generation call will exceed the model's predefined "
            F"""maximum length ({self.max_position_embeddings}). Depending on the model, you may observe """
            "exceptions, performance degradation, or nothing at all."       )
       return is_done



class  A__       (	__snake_case      ):





      def __init__(			self	,							A_	,							A_       ):
       '''simple docstring'''




       warnings.warn(
           "The class `MaxNewTokensCriteria` is deprecated. "
           F"""Please use `MaxLengthCriteria(max_length={start_length + max_new_tokens})` """
           "with `max_length = start_length + max_new_tokens` instead."	,							A_	,							)
       UpperCamelCase     : Union[str, Any]	     =       start_length
       UpperCamelCase     : List[str]	     =       max_new_tokens
       UpperCamelCase     : Tuple	     =       start_length + max_new_tokens





      @add_start_docstrings(A_       )
      def __call__(			self	,							A_	,							A_	,							**A_       ):
       '''simple docstring'''




       return input_ids.shape[-1] >= self.max_length



class  A__       (	__snake_case      ):





      def __init__(			self	,							A_	,							A_ = None       ):
       '''simple docstring'''




       UpperCamelCase     : Optional[int]	     =       max_time
       UpperCamelCase     : Dict	     =       time.time() if initial_timestamp is None else initial_timestamp





      @add_start_docstrings(A_       )
      def __call__(			self	,							A_	,							A_	,							**A_       ):
       '''simple docstring'''




       return time.time() - self.initial_timestamp > self.max_time



class  A__       (	__snake_case      ):





      @add_start_docstrings(A_       )
      def __call__(			self	,							A_	,							A_	,							**A_       ):
       '''simple docstring'''




       return any(criteria(A_	,							A_       ) for criteria in self       )





      @property
      def 	__UpperCamelCase(			self       ):
       '''simple docstring'''




       for stopping_criterium in self:
        if isinstance(A_	,							A_       ):
         return stopping_criterium.max_length
        elif isinstance(A_	,							A_       ):
         return stopping_criterium.max_length
       return None



def 		A_    (					_lowerCAmelCase							,       _lowerCAmelCase					)						->			StoppingCriteriaList:
 UpperCamelCase     : Tuple	     =       stopping_criteria.max_length
 UpperCamelCase     : Union[str, Any]	     =       deepcopy(_lowerCAmelCase					)
 if stopping_max_length is not None and stopping_max_length != max_length:
  warnings.warn("You set different `max_length` for stopping criteria and `max_length` parameter"							,       _lowerCAmelCase					)
 elif stopping_max_length is None:
  new_stopping_criteria.append(MaxLengthCriteria(max_length=_lowerCAmelCase					)					)
 return new_stopping_criteria
