





# 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(4_2)

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

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






def 	lowerCamelCase_		(							_UpperCamelCase					,							_UpperCamelCase					,							_UpperCamelCase					)						->		Union[str, Any]:






				"""simple docstring"""


				snake_case_		:       Tuple           =    parameterized.to_safe_name('''_'''.join(str(_UpperCamelCase					) 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    __lowerCAmelCase			(     _a	):






			@parameterized.expand(__magic_name__   ,				name_func=__magic_name__       )
			def      lowerCamelCase    (self   ,				__magic_name__   ,				__magic_name__       )	->  Dict:


							'''simple docstring'''



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






			@require_torch_multi_gpu
			@parameterized.expand(__magic_name__   ,				name_func=__magic_name__       )
			def      lowerCamelCase    (self   ,				__magic_name__   ,				__magic_name__       )	->  int:


							'''simple docstring'''



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






			@parameterized.expand(__magic_name__   ,				name_func=__magic_name__       )
			def      lowerCamelCase    (self   ,				__magic_name__   ,				__magic_name__       )	->  List[Any]:


							'''simple docstring'''



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






			@require_torch_multi_gpu
			@parameterized.expand(__magic_name__   ,				name_func=__magic_name__       )
			def      lowerCamelCase    (self   ,				__magic_name__   ,				__magic_name__       )	->  Optional[Any]:


							'''simple docstring'''



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






			def      lowerCamelCase    (self   ,				__magic_name__       )	->  Dict:


							'''simple docstring'''



							pass






			def      lowerCamelCase    (self   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__ = 10   ,				__magic_name__ = True   ,				__magic_name__ = True   ,				__magic_name__ = True   ,				)	->  Any:


							'''simple docstring'''



							snake_case_		:       List[Any]           =    models[model]

							snake_case_		:       Optional[int]           =    self.run_trainer(
							    stage=__magic_name__   ,				model_name=__magic_name__   ,				eval_steps=__magic_name__   ,				num_train_epochs=1   ,				distributed=__magic_name__   ,				fpaa=__magic_name__   ,				)

							self.do_checks(__magic_name__       )

							return output_dir






			def      lowerCamelCase    (self   ,				__magic_name__   ,				__magic_name__   ,				__magic_name__ = 10   ,				__magic_name__ = 1   ,				__magic_name__ = True   ,				__magic_name__ = True   ,				)	->  Union[str, Any]:


							'''simple docstring'''



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

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

							return output_dir






			def      lowerCamelCase    (self   ,				__magic_name__=False       )	->  str:


							'''simple docstring'''



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






'''simple docstring'''


import json
from typing import List, Optional, Tuple

from tokenizers import pre_tokenizers, processors

from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_roberta import RobertaTokenizer


lowerCAmelCase_      :  Optional[Any]				     =  logging.get_logger(__name__)

lowerCAmelCase_      :  int				     =  {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'}

lowerCAmelCase_      :  Union[str, Any]				     =  {
    'vocab_file': {
        'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/vocab.json',
        'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/vocab.json',
        'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/vocab.json',
        'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/vocab.json',
        'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/vocab.json',
        'roberta-large-openai-detector': (
            'https://huggingface.co/roberta-large-openai-detector/resolve/main/vocab.json'
        ),
    },
    'merges_file': {
        'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/merges.txt',
        'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/merges.txt',
        'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/merges.txt',
        'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/merges.txt',
        'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/merges.txt',
        'roberta-large-openai-detector': (
            'https://huggingface.co/roberta-large-openai-detector/resolve/main/merges.txt'
        ),
    },
    'tokenizer_file': {
        'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/tokenizer.json',
        'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/tokenizer.json',
        'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/tokenizer.json',
        'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/tokenizer.json',
        'roberta-base-openai-detector': (
            'https://huggingface.co/roberta-base-openai-detector/resolve/main/tokenizer.json'
        ),
        'roberta-large-openai-detector': (
            'https://huggingface.co/roberta-large-openai-detector/resolve/main/tokenizer.json'
        ),
    },
}

lowerCAmelCase_      :  Union[str, Any]				     =  {
    'roberta-base': 512,
    'roberta-large': 512,
    'roberta-large-mnli': 512,
    'distilroberta-base': 512,
    'roberta-base-openai-detector': 512,
    'roberta-large-openai-detector': 512,
}







class      SCREAMING_SNAKE_CASE    (						snake_case_				):
      __magic_name__  :       int   							=					VOCAB_FILES_NAMES
      __magic_name__  :       List[str]   							=					PRETRAINED_VOCAB_FILES_MAP
      __magic_name__  :       str   							=					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      __magic_name__  :       List[str]   							=					['''input_ids''', '''attention_mask''']
      __magic_name__  :       Any   							=					RobertaTokenizer






      def __init__( self   :  Any						,						lowercase__   :  int=None						,						lowercase__   :  Union[str, Any]=None						,						lowercase__   :  List[Any]=None						,						lowercase__   :  int="replace"						,						lowercase__   :  Dict="<s>"						,						lowercase__   :  int="</s>"						,						lowercase__   :  Optional[Any]="</s>"						,						lowercase__   :  List[Any]="<s>"						,						lowercase__   :  Optional[int]="<unk>"						,						lowercase__   :  Tuple="<pad>"						,						lowercase__   :  Optional[Any]="<mask>"						,						lowercase__   :  List[Any]=False						,						lowercase__   :  Optional[Any]=True						,						**lowercase__   :  List[str]						,						):


           '''simple docstring'''

           super().__init__(
               lowercase__						,						lowercase__						,						tokenizer_file=lowercase__						,						errors=lowercase__						,						bos_token=lowercase__						,						eos_token=lowercase__						,						sep_token=lowercase__						,						cls_token=lowercase__						,						unk_token=lowercase__						,						pad_token=lowercase__						,						mask_token=lowercase__						,						add_prefix_space=lowercase__						,						trim_offsets=lowercase__						,						**lowercase__						,						)

           a_     :							Any     						=  json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__()       )
           if pre_tok_state.get("""add_prefix_space"""						,						lowercase__       ) != add_prefix_space:
                a_     :							List[Any]     						=  getattr(lowercase__						,						pre_tok_state.pop("""type"""       )       )
                a_     :							Optional[Any]     						=  add_prefix_space
                a_     :							List[str]     						=  pre_tok_class(**lowercase__       )

           a_     :							List[Any]     						=  add_prefix_space

           a_     :							Any     						=  """post_processor"""
           a_     :							Dict     						=  getattr(self.backend_tokenizer						,						lowercase__						,						lowercase__       )
           if tokenizer_component_instance:
                a_     :							Optional[Any]     						=  json.loads(tokenizer_component_instance.__getstate__()       )

                # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
                if "sep" in state:
                     a_     :							Dict     						=  tuple(state["""sep"""]       )
                if "cls" in state:
                     a_     :							List[str]     						=  tuple(state["""cls"""]       )

                a_     :							str     						=  False

                if state.get("""add_prefix_space"""						,						lowercase__       ) != add_prefix_space:
                     a_     :							Any     						=  add_prefix_space
                     a_     :							List[str]     						=  True

                if state.get("""trim_offsets"""						,						lowercase__       ) != trim_offsets:
                     a_     :							Optional[int]     						=  trim_offsets
                     a_     :							Tuple     						=  True

                if changes_to_apply:
                     a_     :							str     						=  getattr(lowercase__						,						state.pop("""type"""       )       )
                     a_     :							Union[str, Any]     						=  component_class(**lowercase__       )
                     setattr(self.backend_tokenizer						,						lowercase__						,						lowercase__       )






      @property
      def 							lowercase_						( self   :  List[str]       ):


           '''simple docstring'''

           if self._mask_token is None:
                if self.verbose:
                     logger.error("""Using mask_token, but it is not set yet."""       )
                return None
           return str(self._mask_token       )






      @mask_token.setter
      def 							lowercase_						( self   :  Union[str, Any]						,						lowercase__   :  Tuple       ):


           '''simple docstring'''

           a_     :							List[Any]     						=  AddedToken(lowercase__						,						lstrip=lowercase__						,						rstrip=lowercase__       ) if isinstance(lowercase__						,						lowercase__       ) else value
           a_     :							Union[str, Any]     						=  value






      def 							lowercase_						( self   :  Union[str, Any]						,						*lowercase__   :  Union[str, Any]						,						**lowercase__   :  Union[str, Any]       ):


           '''simple docstring'''

           a_     :							Any     						=  kwargs.get("""is_split_into_words"""						,						lowercase__       )
           assert self.add_prefix_space or not is_split_into_words, (
               F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
               "to use it with pretokenized inputs."
           )

           return super()._batch_encode_plus(*lowercase__						,						**lowercase__       )






      def 							lowercase_						( self   :  Dict						,						*lowercase__   :  int						,						**lowercase__   :  Dict       ):


           '''simple docstring'''

           a_     :							Any     						=  kwargs.get("""is_split_into_words"""						,						lowercase__       )

           assert self.add_prefix_space or not is_split_into_words, (
               F"You need to instantiate {self.__class__.__name__} with add_prefix_space=True "
               "to use it with pretokenized inputs."
           )

           return super()._encode_plus(*lowercase__						,						**lowercase__       )






      def 							lowercase_						( self   :  Dict						,						lowercase__   :  str						,						lowercase__   :  Optional[str] = None       ):


           '''simple docstring'''

           a_     :							str     						=  self._tokenizer.model.save(lowercase__						,						name=lowercase__       )
           return tuple(lowercase__       )






      def 							lowercase_						( self   :  Dict						,						lowercase__   :  List[Any]						,						lowercase__   :  int=None       ):


           '''simple docstring'''

           a_     :							int     						=  [self.bos_token_id] + token_ids_a + [self.eos_token_id]
           if token_ids_a is None:
                return output

           return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]






      def 							lowercase_						( self   :  List[str]						,						lowercase__   :  List[int]						,						lowercase__   :  Optional[List[int]] = None       ):


           '''simple docstring'''

           a_     :							Optional[Any]     						=  [self.sep_token_id]
           a_     :							Optional[int]     						=  [self.cls_token_id]

           if token_ids_a is None:
                return len(cls + token_ids_a + sep       ) * [0]
           return len(cls + token_ids_a + sep + sep + token_ids_a + sep       ) * [0]
