





# 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


SCREAMING_SNAKE_CASE__							:      List[str]         =    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)

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

SCREAMING_SNAKE_CASE__							:      Any         =    """zero2"""
SCREAMING_SNAKE_CASE__							:      Dict         =    """zero3"""
SCREAMING_SNAKE_CASE__							:      str         =    [ZEROa, ZEROa]






def    _A	(   lowerCamelCase				,			lowerCamelCase				,			lowerCamelCase ):
   # 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
   a__						:    Optional[Any]   		=	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
SCREAMING_SNAKE_CASE__							:      Union[str, Any]         =    list(itertools.product(stages, models.keys()))







@slow
@require_deepspeed
@require_torch_gpu
class 	__lowerCAmelCase      (       _UpperCamelCase	):





   @parameterized.expand(snake_case       ,      name_func=snake_case   )
   def 						_snake_case			(			self       ,      snake_case       ,      snake_case   )					->	Dict:
      """simple docstring"""





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





   @require_torch_multi_gpu
   @parameterized.expand(snake_case       ,      name_func=snake_case   )
   def 						_snake_case			(			self       ,      snake_case       ,      snake_case   )					->	str:
      """simple docstring"""





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





   @parameterized.expand(snake_case       ,      name_func=snake_case   )
   def 						_snake_case			(			self       ,      snake_case       ,      snake_case   )					->	List[str]:
      """simple docstring"""





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





   @require_torch_multi_gpu
   @parameterized.expand(snake_case       ,      name_func=snake_case   )
   def 						_snake_case			(			self       ,      snake_case       ,      snake_case   )					->	List[str]:
      """simple docstring"""





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





   def 						_snake_case			(			self       ,      snake_case   )					->	str:
      """simple docstring"""





      pass





   def 						_snake_case			(			self       ,      snake_case       ,      snake_case       ,      snake_case = 10       ,      snake_case = True       ,      snake_case = True       ,      snake_case = True       ,      )					->	str:
      """simple docstring"""





      a__						:    Tuple   		=	models[model]

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

      self.do_checks(snake_case   )

      return output_dir





   def 						_snake_case			(			self       ,      snake_case       ,      snake_case       ,      snake_case = 10       ,      snake_case = 1       ,      snake_case = True       ,      snake_case = True       ,      )					->	Optional[Any]:
      """simple docstring"""





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

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

      return output_dir





   def 						_snake_case			(			self       ,      snake_case=False   )					->	List[Any]:
      """simple docstring"""





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








import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple

import sentencepiece as spm

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


SCREAMING_SNAKE_CASE__							:      Tuple         =    logging.get_logger(__name__)


SCREAMING_SNAKE_CASE__							:      int         =    """▁"""

SCREAMING_SNAKE_CASE__							:      Union[str, Any]         =    {"""vocab_file""": """spiece.model"""}

SCREAMING_SNAKE_CASE__							:      Optional[int]         =    {
    """vocab_file""": {
        """google/reformer-crime-and-punishment""": (
            """https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model"""
        )
    }
}

SCREAMING_SNAKE_CASE__							:      Optional[Any]         =    {
    """google/reformer-crime-and-punishment""": 5_2_4_2_8_8,
}







class 	__lowerCAmelCase      (       _UpperCamelCase	):
   _UpperCamelCase			:    List[Any]  		=					VOCAB_FILES_NAMES
   _UpperCamelCase			:    Any  		=					PRETRAINED_VOCAB_FILES_MAP
   _UpperCamelCase			:    Any  		=					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   _UpperCamelCase			:    Tuple  		=					["""input_ids""", """attention_mask"""]





   def __init__(			self       ,      snake_case       ,      snake_case="</s>"       ,      snake_case="<unk>"       ,      snake_case=[]       ,      snake_case = None       ,      **snake_case       ,      )					->	None:
      """simple docstring"""





      a__						:    Optional[Any]   		=	{} if sp_model_kwargs is None else sp_model_kwargs

      super().__init__(
          eos_token=snake_case       ,      unk_token=snake_case       ,      additional_special_tokens=snake_case       ,      sp_model_kwargs=self.sp_model_kwargs       ,      **snake_case       ,      )

      a__						:    Union[str, Any]   		=	vocab_file
      a__						:    Optional[Any]   		=	spm.SentencePieceProcessor(**self.sp_model_kwargs   )
      self.sp_model.Load(snake_case   )





   @property
   def 						_snake_case			(			self   )					->	str:
      """simple docstring"""





      return self.sp_model.get_piece_size()





   def 						_snake_case			(			self   )					->	Dict[str, int]:
      """simple docstring"""





      a__						:    Dict   		=	{self.convert_ids_to_tokens(snake_case   ): i for i in range(self.vocab_size   )}
      vocab.update(self.added_tokens_encoder   )
      return vocab





   def __getstate__(			self   )					->	Any:
      """simple docstring"""





      a__						:    Tuple   		=	self.__dict__.copy()
      a__						:    Optional[int]   		=	None
      return state





   def __setstate__(			self       ,      snake_case   )					->	Union[str, Any]:
      """simple docstring"""





      a__						:    List[Any]   		=	d

      # for backward compatibility
      if not hasattr(self       ,      "sp_model_kwargs"   ):
         a__						:    List[Any]   		=	{}

      a__						:    int   		=	spm.SentencePieceProcessor(**self.sp_model_kwargs   )
      self.sp_model.Load(self.vocab_file   )





   def 						_snake_case			(			self       ,      snake_case   )					->	List[str]:
      """simple docstring"""





      return self.sp_model.encode(snake_case       ,      out_type=snake_case   )





   def 						_snake_case			(			self       ,      snake_case   )					->	Union[str, Any]:
      """simple docstring"""





      return self.sp_model.piece_to_id(snake_case   )





   def 						_snake_case			(			self       ,      snake_case   )					->	Any:
      """simple docstring"""





      if index < self.sp_model.get_piece_size():
         a__						:    Optional[Any]   		=	self.sp_model.IdToPiece(snake_case   )
      return token





   def 						_snake_case			(			self       ,      snake_case   )					->	Any:
      """simple docstring"""





      a__						:    int   		=	[]
      a__						:    Dict   		=	""
      for token in tokens:
         # make sure that special tokens are not decoded using sentencepiece model
         if token in self.all_special_tokens:
            out_string += self.sp_model.decode(snake_case   ) + token
            a__						:    Dict   		=	[]
         else:
            current_sub_tokens.append(snake_case   )
      out_string += self.sp_model.decode(snake_case   )
      return out_string.strip()





   def 						_snake_case			(			self       ,      snake_case       ,      snake_case = None   )					->	Tuple[str]:
      """simple docstring"""





      if not os.path.isdir(snake_case   ):
         logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""   )
         return
      a__						:    Tuple   		=	os.path.join(
          snake_case       ,      (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]   )

      if os.path.abspath(self.vocab_file   ) != os.path.abspath(snake_case   ) and os.path.isfile(self.vocab_file   ):
         copyfile(self.vocab_file       ,      snake_case   )
      elif not os.path.isfile(self.vocab_file   ):
         with open(snake_case       ,      "wb"   ) as fi:
            a__						:    str   		=	self.sp_model.serialized_model_proto()
            fi.write(snake_case   )

      return (out_vocab_file,)

