


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

import sentencepiece as spm

from ...tokenization_utils import AddedToken, BatchEncoding, PreTrainedTokenizer
from ...utils import logging


__UpperCAmelCase      :Dict			    =       logging.get_logger(__name__)

__UpperCAmelCase      :List[str]			    =       "▁"

__UpperCAmelCase      :Any			    =       {"vocab_file": "sentencepiece.bpe.model"}

__UpperCAmelCase      :List[Any]			    =       {
    "vocab_file": {
        "facebook/mbart-large-50-one-to-many-mmt": (
            "https://huggingface.co/facebook/mbart-large-50-one-to-many-mmt/resolve/main/sentencepiece.bpe.model"
        ),
    }
}

__UpperCAmelCase      :Tuple			    =       {
    "facebook/mbart-large-50-one-to-many-mmt": 1_0_2_4,
}

# fmt: off
__UpperCAmelCase      :List[Any]			    =       ["ar_AR", "cs_CZ", "de_DE", "en_XX", "es_XX", "et_EE", "fi_FI", "fr_XX", "gu_IN", "hi_IN", "it_IT", "ja_XX", "kk_KZ", "ko_KR", "lt_LT", "lv_LV", "my_MM", "ne_NP", "nl_XX", "ro_RO", "ru_RU", "si_LK", "tr_TR", "vi_VN", "zh_CN", "af_ZA", "az_AZ", "bn_IN", "fa_IR", "he_IL", "hr_HR", "id_ID", "ka_GE", "km_KH", "mk_MK", "ml_IN", "mn_MN", "mr_IN", "pl_PL", "ps_AF", "pt_XX", "sv_SE", "sw_KE", "ta_IN", "te_IN", "th_TH", "tl_XX", "uk_UA", "ur_PK", "xh_ZA", "gl_ES", "sl_SI"]



class      a    (		_a	):


     """simple docstring"""






     SCREAMING_SNAKE_CASE	:			Union[str, Any]							       =       VOCAB_FILES_NAMES
     SCREAMING_SNAKE_CASE	:			Tuple							       =       PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
     SCREAMING_SNAKE_CASE	:			str							       =       PRETRAINED_VOCAB_FILES_MAP
     SCREAMING_SNAKE_CASE	:			Any							       =       ["input_ids", "attention_mask"]

     SCREAMING_SNAKE_CASE	:			List[int]							       =       []
     SCREAMING_SNAKE_CASE	:			List[int]							       =       []

     def __init__(    self					:		Dict							,			snake_case					:		Dict							,			snake_case					:		List[Any]=None							,			snake_case					:		Tuple=None							,			snake_case					:		int="</s>"							,			snake_case					:		Tuple="</s>"							,			snake_case					:		Any="<s>"							,			snake_case					:		Tuple="<unk>"							,			snake_case					:		Any="<pad>"							,			snake_case					:		str="<mask>"							,			snake_case					:		Optional[Dict[str, Any]] = None							,			**snake_case					:		Optional[int]							,			)						->							None:
          # Mask token behave like a normal word, i.e. include the space before it
          __UpperCAmelCase     :			str  							=      AddedToken(snake_case							,			lstrip=snake_case							,			rstrip=snake_case      ) if isinstance(snake_case							,			snake_case      ) else mask_token

          __UpperCAmelCase     :			Optional[int]  							=      {} if sp_model_kwargs is None else sp_model_kwargs

          __UpperCAmelCase     :			List[Any]  							=      kwargs.get('''additional_special_tokens'''							,			[]      )
          kwargs["additional_special_tokens"] += [
              code for code in FAIRSEQ_LANGUAGE_CODES if code not in kwargs["additional_special_tokens"]
          ]

          super().__init__(
              src_lang=snake_case							,			tgt_lang=snake_case							,			eos_token=snake_case							,			unk_token=snake_case							,			sep_token=snake_case							,			cls_token=snake_case							,			pad_token=snake_case							,			mask_token=snake_case							,			sp_model_kwargs=self.sp_model_kwargs							,			**snake_case							,			)

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

          # Original fairseq vocab and spm vocab must be "aligned":
          # Vocab    |    0    |    1    |   2    |    3    |  4  |  5  |  6  |   7   |   8   |  9
          # -------- | ------- | ------- | ------ | ------- | --- | --- | --- | ----- | ----- | ----
          # fairseq  | '<s>'   | '<pad>' | '</s>' | '<unk>' | ',' | '.' | '▁' | 's'   | '▁de' | '-'
          # spm      | '<unk>' | '<s>'   | '</s>' | ','     | '.' | '▁' | 's' | '▁de' | '-'   | '▁a'

          # Mimic fairseq token-to-id alignment for the first 4 token
          __UpperCAmelCase     :			Tuple  							=      {'''<s>''': 0, '''<pad>''': 1, '''</s>''': 2, '''<unk>''': 3}

          # The first "real" token "," has position 4 in the original fairseq vocab and position 3 in the spm vocab
          __UpperCAmelCase     :			List[Any]  							=      1

          __UpperCAmelCase     :			str  							=      len(self.sp_model      )
          __UpperCAmelCase     :			Dict  							=      {
              code: self.sp_model_size + i + self.fairseq_offset for i, code in enumerate(snake_case      )
          }
          __UpperCAmelCase     :			Optional[Any]  							=      {v: k for k, v in self.lang_code_to_id.items()}
          __UpperCAmelCase     :			List[Any]  							=      len(self.sp_model      ) + len(self.lang_code_to_id      ) + self.fairseq_offset

          self.fairseq_tokens_to_ids.update(self.lang_code_to_id      )
          __UpperCAmelCase     :			Optional[Any]  							=      {v: k for k, v in self.fairseq_tokens_to_ids.items()}

          __UpperCAmelCase     :			Dict  							=      src_lang if src_lang is not None else '''en_XX'''
          __UpperCAmelCase     :			str  							=      self.lang_code_to_id[self._src_lang]
          __UpperCAmelCase     :			int  							=      tgt_lang
          self.set_src_lang_special_tokens(self._src_lang      )

     @property
     def 			lowerCamelCase__			(    self					:		str      )						->							int:
          return len(self.sp_model      ) + len(self.lang_code_to_id      ) + self.fairseq_offset + 1  # Plus 1 for the mask token

     @property
     def 			lowerCamelCase__			(    self					:		Optional[Any]      )						->							str:
          return self._src_lang

     @src_lang.setter
     def 			lowerCamelCase__			(    self					:		Optional[Any]							,			snake_case					:		str      )						->							None:
          __UpperCAmelCase     :			str  							=      new_src_lang
          self.set_src_lang_special_tokens(self._src_lang      )

     def __getstate__(    self					:		Optional[Any]      )						->							Dict:
          __UpperCAmelCase     :			Tuple  							=      self.__dict__.copy()
          __UpperCAmelCase     :			Union[str, Any]  							=      None
          return state

     def __setstate__(    self					:		Dict							,			snake_case					:		Dict      )						->							None:
          __UpperCAmelCase     :			Dict  							=      d

          # for backward compatibility
          if not hasattr(self							,			'''sp_model_kwargs'''      ):
               __UpperCAmelCase     :			Tuple  							=      {}

          __UpperCAmelCase     :			Tuple  							=      spm.SentencePieceProcessor(**self.sp_model_kwargs      )
          self.sp_model.Load(self.vocab_file      )

     def 			lowerCamelCase__			(    self					:		int      )						->							Dict:
          __UpperCAmelCase     :			List[str]  							=      {self.convert_ids_to_tokens(snake_case      ): i for i in range(self.vocab_size      )}
          vocab.update(self.added_tokens_encoder      )
          return vocab

     def 			lowerCamelCase__			(    self					:		Union[str, Any]							,			snake_case					:		str      )						->							List[str]:
          return self.sp_model.encode(snake_case							,			out_type=snake_case      )

     def 			lowerCamelCase__			(    self					:		List[Any]							,			snake_case					:		str      )						->							int:
          if token in self.fairseq_tokens_to_ids:
               return self.fairseq_tokens_to_ids[token]
          __UpperCAmelCase     :			Union[str, Any]  							=      self.sp_model.PieceToId(snake_case      )

          # Need to return unknown token if the SP model returned 0
          return spm_id + self.fairseq_offset if spm_id else self.unk_token_id

     def 			lowerCamelCase__			(    self					:		Optional[Any]							,			snake_case					:		int      )						->							str:
          if index in self.fairseq_ids_to_tokens:
               return self.fairseq_ids_to_tokens[index]
          return self.sp_model.IdToPiece(index - self.fairseq_offset      )

     def 			lowerCamelCase__			(    self					:		Optional[Any]							,			snake_case					:		List[Any]      )						->							Tuple:
          __UpperCAmelCase     :			str  							=      []
          __UpperCAmelCase     :			str  							=      ''''''
          __UpperCAmelCase     :			Dict  							=      False
          for token in tokens:
               # make sure that special tokens are not decoded using sentencepiece model
               if token in self.all_special_tokens:
                    if not prev_is_special:
                         out_string += " "
                    out_string += self.sp_model.decode(snake_case      ) + token
                    __UpperCAmelCase     :			Union[str, Any]  							=      True
                    __UpperCAmelCase     :			Optional[int]  							=      []
               else:
                    current_sub_tokens.append(snake_case      )
                    __UpperCAmelCase     :			List[Any]  							=      False
          out_string += self.sp_model.decode(snake_case      )
          return out_string.strip()

     def 			lowerCamelCase__			(    self					:		List[str]							,			snake_case					:		str							,			snake_case					:		Optional[str] = None      )						->							Tuple[str]:
          if not os.path.isdir(snake_case      ):
               logger.error(f'Vocabulary path ({save_directory}) should be a directory'      )
               return
          __UpperCAmelCase     :			List[str]  							=      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:
                    __UpperCAmelCase     :			str  							=      self.sp_model.serialized_model_proto()
                    fi.write(snake_case      )

          return (out_vocab_file,)

     def 			lowerCamelCase__			(    self					:		List[str]							,			snake_case					:		List[int]							,			snake_case					:		Optional[List[int]] = None							,			snake_case					:		bool = False      )						->							List[int]:

          if already_has_special_tokens:
               return super().get_special_tokens_mask(
                   token_ids_a=snake_case							,			token_ids_a=snake_case							,			already_has_special_tokens=snake_case      )

          __UpperCAmelCase     :			List[Any]  							=      [1] * len(self.prefix_tokens      )
          __UpperCAmelCase     :			str  							=      [1] * len(self.suffix_tokens      )
          if token_ids_a is None:
               return prefix_ones + ([0] * len(snake_case      )) + suffix_ones
          return prefix_ones + ([0] * len(snake_case      )) + ([0] * len(snake_case      )) + suffix_ones

     def 			lowerCamelCase__			(    self					:		Tuple							,			snake_case					:		List[int]							,			snake_case					:		Optional[List[int]] = None      )						->							List[int]:
          if token_ids_a is None:
               return self.prefix_tokens + token_ids_a + self.suffix_tokens
          # We don't expect to process pairs, but leave the pair logic for API consistency
          return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens

     def 			lowerCamelCase__			(    self					:		List[str]							,			snake_case					:		Optional[Any]							,			snake_case					:		str							,			snake_case					:		Optional[str]							,			snake_case					:		Optional[str]							,			**snake_case					:		int      )						->							str:
          if src_lang is None or tgt_lang is None:
               raise ValueError('''Translation requires a `src_lang` and a `tgt_lang` for this model'''      )
          __UpperCAmelCase     :			Tuple  							=      src_lang
          __UpperCAmelCase     :			Any  							=      self(snake_case							,			add_special_tokens=snake_case							,			return_tensors=snake_case							,			**snake_case      )
          __UpperCAmelCase     :			Tuple  							=      self.convert_tokens_to_ids(snake_case      )
          __UpperCAmelCase     :			List[Any]  							=      tgt_lang_id
          return inputs

     def 			lowerCamelCase__			(    self					:		Union[str, Any]							,			snake_case					:		List[str]							,			snake_case					:		str = "en_XX"							,			snake_case					:		Optional[List[str]] = None							,			snake_case					:		str = "ro_RO"							,			**snake_case					:		int							,			)						->							BatchEncoding:
          __UpperCAmelCase     :			List[Any]  							=      src_lang
          __UpperCAmelCase     :			str  							=      tgt_lang
          return super().prepare_seqaseq_batch(snake_case							,			snake_case							,			**snake_case      )

     def 			lowerCamelCase__			(    self					:		List[Any]      )						->							List[Any]:
          return self.set_src_lang_special_tokens(self.src_lang      )

     def 			lowerCamelCase__			(    self					:		Any      )						->							str:
          return self.set_tgt_lang_special_tokens(self.tgt_lang      )

     def 			lowerCamelCase__			(    self					:		Union[str, Any]							,			snake_case					:		str      )						->							None:
          __UpperCAmelCase     :			Optional[Any]  							=      self.lang_code_to_id[src_lang]
          __UpperCAmelCase     :			List[Any]  							=      [self.cur_lang_code_id]
          __UpperCAmelCase     :			Any  							=      [self.eos_token_id]






     def 			lowerCamelCase__			(    self					:		int							,			snake_case					:		str      )						->							None:
          __UpperCAmelCase     :			Union[str, Any]  							=      self.lang_code_to_id[tgt_lang]
          __UpperCAmelCase     :			str  							=      [self.cur_lang_code_id]
          __UpperCAmelCase     :			Any  							=      [self.eos_token_id]



'''simple docstring'''



# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from pathlib import Path

import torch

from ...utils import is_npu_available, is_xpu_available
from .config_args import ClusterConfig, default_json_config_file
from .config_utils import SubcommandHelpFormatter


__UpperCAmelCase      :Tuple			    =       "Create a default config file for Accelerate with only a few flags set."




def      _a     (						_lowercase :     List[Any]="no"      , _lowercase :     str = default_json_config_file      , _lowercase :     bool = False  ):





     '''simple docstring'''






     __UpperCAmelCase     :			Dict  							=      Path(_lowercase  )
     path.parent.mkdir(parents=_lowercase      , exist_ok=_lowercase  )
     if path.exists():
          print(
              F'Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`.'  )
          return False
     __UpperCAmelCase     :			List[str]  							=      mixed_precision.lower()
     if mixed_precision not in ["no", "fp16", "bf16", "fp8"]:
          raise ValueError(
              F'`mixed_precision` should be one of \'no\', \'fp16\', \'bf16\', or \'fp8\'. Received {mixed_precision}'  )
     __UpperCAmelCase     :			int  							=      {
         '''compute_environment''': '''LOCAL_MACHINE''',
         '''mixed_precision''': mixed_precision,
     }
     if torch.cuda.is_available():
          __UpperCAmelCase     :			Optional[Any]  							=      torch.cuda.device_count()
          __UpperCAmelCase     :			List[str]  							=      num_gpus
          __UpperCAmelCase     :			int  							=      False
          if num_gpus > 1:
               __UpperCAmelCase     :			Any  							=      '''MULTI_GPU'''
          else:
               __UpperCAmelCase     :			int  							=      '''NO'''
     elif is_xpu_available() and use_xpu:
          __UpperCAmelCase     :			List[Any]  							=      torch.xpu.device_count()
          __UpperCAmelCase     :			List[Any]  							=      num_xpus
          __UpperCAmelCase     :			Optional[int]  							=      False
          if num_xpus > 1:
               __UpperCAmelCase     :			Any  							=      '''MULTI_XPU'''
          else:
               __UpperCAmelCase     :			Optional[Any]  							=      '''NO'''
     elif is_npu_available():
          __UpperCAmelCase     :			Dict  							=      torch.npu.device_count()
          __UpperCAmelCase     :			Any  							=      num_npus
          __UpperCAmelCase     :			Any  							=      False
          if num_npus > 1:
               __UpperCAmelCase     :			Dict  							=      '''MULTI_NPU'''
          else:
               __UpperCAmelCase     :			Optional[int]  							=      '''NO'''
     else:
          __UpperCAmelCase     :			List[str]  							=      0
          __UpperCAmelCase     :			Dict  							=      True
          __UpperCAmelCase     :			Dict  							=      1
          __UpperCAmelCase     :			Tuple  							=      '''NO'''
     __UpperCAmelCase     :			List[Any]  							=      ClusterConfig(**_lowercase  )
     config.to_json_file(_lowercase  )
     return path




def      _a     (						_lowercase :     Union[str, Any]      , _lowercase :     str  ):





     '''simple docstring'''






     __UpperCAmelCase     :			Optional[int]  							=      parser.add_parser('''default'''      , parents=_lowercase      , help=_lowercase      , formatter_class=_lowercase  )
     parser.add_argument(
         '''--config_file'''      , default=_lowercase      , help=(
             '''The path to use to store the config file. Will default to a file named default_config.yaml in the cache '''
             '''location, which is the content of the environment `HF_HOME` suffixed with \'accelerate\', or if you don\'t have '''
             '''such an environment variable, your cache directory (\'~/.cache\' or the content of `XDG_CACHE_HOME`) suffixed '''
             '''with \'huggingface\'.'''
         )      , dest='''save_location'''      , )

     parser.add_argument(
         '''--mixed_precision'''      , choices=['''no''', '''fp16''', '''bf16''']      , type=_lowercase      , help='''Whether or not to use mixed precision training. '''
         '''Choose between FP16 and BF16 (bfloat16) training. '''
         '''BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.'''      , default='''no'''      , )
     parser.set_defaults(func=_lowercase  )
     return parser




def      _a     (						_lowercase :     List[Any]  ):





     '''simple docstring'''






     __UpperCAmelCase     :			str  							=      write_basic_config(args.mixed_precision      , args.save_location  )
     if config_file:
          print(F'accelerate configuration saved at {config_file}'  )