




import logging
import os
from typing import Dict, List, Optional, Union

import torch
import torch.nn as nn

from accelerate.utils.imports import (
    is_abit_bnb_available,
    is_abit_bnb_available,
    is_bnb_available,
)

from ..big_modeling import dispatch_model, init_empty_weights
from .dataclasses import BnbQuantizationConfig
from .modeling import (
    find_tied_parameters,
    get_balanced_memory,
    infer_auto_device_map,
    load_checkpoint_in_model,
    offload_weight,
    set_module_tensor_to_device,
)


if is_bnb_available():
   import bitsandbytes as bnb

from copy import deepcopy


lowerCamelCase__					:  Dict      							=				logging.getLogger(__name__)

def    UpperCAmelCase_				( __UpperCAmelCase		:      torch.nn.Module     ,     __UpperCAmelCase		:      BnbQuantizationConfig     ,     __UpperCAmelCase		:      Union[str, os.PathLike] = None     ,     __UpperCAmelCase		:      Optional[Dict[str, Union[int, str, torch.device]]] = None     ,     __UpperCAmelCase		:      Optional[List[str]] = None     ,     __UpperCAmelCase		:      Optional[Dict[Union[int, str], Union[int, str]]] = None     ,     __UpperCAmelCase		:      Optional[Union[str, os.PathLike]] = None     ,     __UpperCAmelCase		:      bool = False     ,     )   ->					List[Any]:
      SCREAMING_SNAKE_CASE_      		=     bnb_quantization_config.load_in_abit
      SCREAMING_SNAKE_CASE_      		=     bnb_quantization_config.load_in_abit

      if load_in_abit and not is_abit_bnb_available():
            raise ImportError(
                'You have a version of `bitsandbytes` that is not compatible with 8bit quantization,'
                ' make sure you have the latest version of `bitsandbytes` installed.'				)
      if load_in_abit and not is_abit_bnb_available():
            raise ValueError(
                'You have a version of `bitsandbytes` that is not compatible with 4bit quantization,'
                'make sure you have the latest version of `bitsandbytes` installed.'				)

      SCREAMING_SNAKE_CASE_      		=     []
      # custom device map
      if isinstance(__UpperCAmelCase     ,     __UpperCAmelCase				) and len(device_map.keys()				) > 1:
            SCREAMING_SNAKE_CASE_      		=     [key for key, value in device_map.items() if value in ['disk', 'cpu']]

      # We keep some modules such as the lm_head in their original dtype for numerical stability reasons
      if bnb_quantization_config.skip_modules is None:
            SCREAMING_SNAKE_CASE_      		=     get_keys_to_not_convert(__UpperCAmelCase				)

      # add cpu modules to skip modules only for 4-bit modules
      if load_in_abit:
            bnb_quantization_config.skip_modules.extend(__UpperCAmelCase				)
      SCREAMING_SNAKE_CASE_      		=     bnb_quantization_config.skip_modules

      # We add the modules we want to keep in full precision
      if bnb_quantization_config.keep_in_fpaa_modules is None:
            SCREAMING_SNAKE_CASE_      		=     []
      SCREAMING_SNAKE_CASE_      		=     bnb_quantization_config.keep_in_fpaa_modules
      modules_to_not_convert.extend(__UpperCAmelCase				)

      # compatibility with peft
      SCREAMING_SNAKE_CASE_      		=     load_in_abit
      SCREAMING_SNAKE_CASE_      		=     load_in_abit

      SCREAMING_SNAKE_CASE_      		=     get_parameter_device(__UpperCAmelCase				)
      if model_device.type != "meta":
            # quantization of an already loaded model
            logger.warning(
                'It is not recommended to quantize a loaded model. '
                'The model should be instantiated under the `init_empty_weights` context manager.'				)
            SCREAMING_SNAKE_CASE_      		=     replace_with_bnb_layers(__UpperCAmelCase     ,     __UpperCAmelCase     ,     modules_to_not_convert=__UpperCAmelCase				)
            # convert param to the right dtype
            SCREAMING_SNAKE_CASE_      		=     bnb_quantization_config.torch_dtype
            for name, param in model.state_dict().items():
                  if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules				):
                        param.to(torch.floataa				)
                        if param.dtype != torch.floataa:
                              SCREAMING_SNAKE_CASE_      		=     name.replace('.weight'     ,     ''				).replace('.bias'     ,     ''				)
                              SCREAMING_SNAKE_CASE_      		=     getattr(__UpperCAmelCase     ,     __UpperCAmelCase     ,     __UpperCAmelCase				)
                              if param is not None:
                                    param.to(torch.floataa				)
                  elif torch.is_floating_point(__UpperCAmelCase				):
                        param.to(__UpperCAmelCase				)
            if model_device.type == "cuda":
                  # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda
                  model.cuda(torch.cuda.current_device()				)
                  torch.cuda.empty_cache()
            elif torch.cuda.is_available():
                  model.to(torch.cuda.current_device()				)
            else:
                  raise RuntimeError('No GPU found. A GPU is needed for quantization.'				)
            logger.info(
                f"The model device type is {model_device.type}. However, cuda is needed for quantization."
                'We move the model to cuda.'				)
            return model

      elif weights_location is None:
            raise RuntimeError(
                f"`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} "				)

      else:
            with init_empty_weights():
                  SCREAMING_SNAKE_CASE_      		=     replace_with_bnb_layers(
                      __UpperCAmelCase     ,     __UpperCAmelCase     ,     modules_to_not_convert=__UpperCAmelCase				)

            SCREAMING_SNAKE_CASE_      		=     get_quantized_model_device_map(
                __UpperCAmelCase     ,     __UpperCAmelCase     ,     __UpperCAmelCase     ,     max_memory=__UpperCAmelCase     ,     no_split_module_classes=__UpperCAmelCase     ,     )
            if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
                  SCREAMING_SNAKE_CASE_      		=     True

            SCREAMING_SNAKE_CASE_      		=     any(x in list(device_map.values()				) for x in ['cpu', 'disk']				)

            load_checkpoint_in_model(
                __UpperCAmelCase     ,     __UpperCAmelCase     ,     __UpperCAmelCase     ,     dtype=bnb_quantization_config.torch_dtype     ,     offload_folder=__UpperCAmelCase     ,     offload_state_dict=__UpperCAmelCase     ,     keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules     ,     offload_abit_bnb=load_in_abit and offload     ,     )
            return dispatch_model(__UpperCAmelCase     ,     device_map=__UpperCAmelCase     ,     offload_dir=__UpperCAmelCase				)

def    UpperCAmelCase_				( __UpperCAmelCase		:      int     ,     __UpperCAmelCase		:      Any     ,     __UpperCAmelCase		:      Optional[Any]=None     ,     __UpperCAmelCase		:      Dict=None     ,     __UpperCAmelCase		:      Optional[int]=None				)   ->					Any:
      if device_map is None:
            if torch.cuda.is_available():
                  SCREAMING_SNAKE_CASE_      		=     {'': torch.cuda.current_device()}
            else:
                  raise RuntimeError('No GPU found. A GPU is needed for quantization.'				)
            logger.info('The device_map was not initialized.' 'Setting device_map to `{\'\':torch.cuda.current_device()}`.'				)

      if isinstance(__UpperCAmelCase     ,     __UpperCAmelCase				):
            if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
                  raise ValueError(
                      'If passing a string for `device_map`, please choose \'auto\', \'balanced\', \'balanced_low_0\' or '
                      '\'sequential\'.'				)

            SCREAMING_SNAKE_CASE_      		=     {}
            special_dtypes.update(
                {
                    name: bnb_quantization_config.torch_dtype
                    for name, _ in model.named_parameters()
                    if any(m in name for m in bnb_quantization_config.skip_modules				)
                }				)
            special_dtypes.update(
                {
                    name: torch.floataa
                    for name, _ in model.named_parameters()
                    if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules				)
                }				)

            SCREAMING_SNAKE_CASE_      		=     {}
            SCREAMING_SNAKE_CASE_      		=     special_dtypes
            SCREAMING_SNAKE_CASE_      		=     no_split_module_classes
            SCREAMING_SNAKE_CASE_      		=     bnb_quantization_config.target_dtype

            # get max_memory for each device.
            if device_map != "sequential":
                  SCREAMING_SNAKE_CASE_      		=     get_balanced_memory(
                      __UpperCAmelCase     ,     low_zero=(device_map == 'balanced_low_0')     ,     max_memory=__UpperCAmelCase     ,     **__UpperCAmelCase     ,     )

            SCREAMING_SNAKE_CASE_      		=     max_memory
            SCREAMING_SNAKE_CASE_      		=     infer_auto_device_map(__UpperCAmelCase     ,     **__UpperCAmelCase				)

      if isinstance(__UpperCAmelCase     ,     __UpperCAmelCase				):
            # check if don't have any quantized module on the cpu
            SCREAMING_SNAKE_CASE_      		=     bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules

            SCREAMING_SNAKE_CASE_      		=     {
                key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert
            }
            for device in ["cpu", "disk"]:
                  if device in device_map_without_some_modules.values():
                        if bnb_quantization_config.load_in_abit:
                              raise ValueError(
                                  '\n                        Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n                        the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n                        these modules in `torch_dtype`, you need to pass a custom `device_map` to\n                        `load_and_quantize_model`. Check\n                        https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n                        for more details.\n                        '				)
                        else:
                              logger.info(
                                  'Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit'				)
            del device_map_without_some_modules
      return device_map

def    UpperCAmelCase_				( __UpperCAmelCase		:      int     ,     __UpperCAmelCase		:      Tuple     ,     __UpperCAmelCase		:      Optional[Any]=None     ,     __UpperCAmelCase		:      List[str]=None				)   ->					str:

      if modules_to_not_convert is None:
            SCREAMING_SNAKE_CASE_      		=     []

      SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_      		=     _replace_with_bnb_layers(
          __UpperCAmelCase     ,     __UpperCAmelCase     ,     __UpperCAmelCase     ,     __UpperCAmelCase				)
      if not has_been_replaced:
            logger.warning(
                'You are loading your model in 8bit or 4bit but no linear modules were found in your model.'
                ' this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.'
                ' Please double check your model architecture, or submit an issue on github if you think this is'
                ' a bug.'				)
      return model

def    UpperCAmelCase_				( __UpperCAmelCase		:      Dict     ,     __UpperCAmelCase		:      List[str]     ,     __UpperCAmelCase		:      Any=None     ,     __UpperCAmelCase		:      Any=None     ,     )   ->					str:
      SCREAMING_SNAKE_CASE_      		=     False
      for name, module in model.named_children():
            if current_key_name is None:
                  SCREAMING_SNAKE_CASE_      		=     []
            current_key_name.append(__UpperCAmelCase				)
            if isinstance(__UpperCAmelCase     ,     nn.Linear				) and name not in modules_to_not_convert:
                  # Check if the current key is not in the `modules_to_not_convert`
                  SCREAMING_SNAKE_CASE_      		=     '.'.join(__UpperCAmelCase				)
                  SCREAMING_SNAKE_CASE_      		=     True
                  for key in modules_to_not_convert:
                        if (
                            (key in current_key_name_str) and (key + "." in current_key_name_str)
                        ) or key == current_key_name_str:
                              SCREAMING_SNAKE_CASE_      		=     False
                              break
                  if proceed:
                        # Load bnb module with empty weight and replace ``nn.Linear` module
                        if bnb_quantization_config.load_in_abit:
                              SCREAMING_SNAKE_CASE_      		=     bnb.nn.LinearabitLt(
                                  module.in_features     ,     module.out_features     ,     module.bias is not None     ,     has_fpaa_weights=__UpperCAmelCase     ,     threshold=bnb_quantization_config.llm_inta_threshold     ,     )
                        elif bnb_quantization_config.load_in_abit:
                              SCREAMING_SNAKE_CASE_      		=     bnb.nn.Linearabit(
                                  module.in_features     ,     module.out_features     ,     module.bias is not None     ,     bnb_quantization_config.bnb_abit_compute_dtype     ,     compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant     ,     quant_type=bnb_quantization_config.bnb_abit_quant_type     ,     )
                        else:
                              raise ValueError('load_in_8bit and load_in_4bit can\'t be both False'				)
                        SCREAMING_SNAKE_CASE_      		=     module.weight.data
                        if module.bias is not None:
                              SCREAMING_SNAKE_CASE_      		=     module.bias.data
                        bnb_module.requires_grad_(__UpperCAmelCase				)
                        setattr(__UpperCAmelCase     ,     __UpperCAmelCase     ,     __UpperCAmelCase				)
                        SCREAMING_SNAKE_CASE_      		=     True
            if len(list(module.children()				)				) > 0:
                  SCREAMING_SNAKE_CASE_		,					SCREAMING_SNAKE_CASE_      		=     _replace_with_bnb_layers(
                      __UpperCAmelCase     ,     __UpperCAmelCase     ,     __UpperCAmelCase     ,     __UpperCAmelCase				)
                  SCREAMING_SNAKE_CASE_      		=     has_been_replaced | _has_been_replaced
            # Remove the last key for recursion
            current_key_name.pop(-1				)
      return model, has_been_replaced

def    UpperCAmelCase_				( __UpperCAmelCase		:      List[str]				)   ->					List[str]:
      # Create a copy of the model
      with init_empty_weights():
            SCREAMING_SNAKE_CASE_      		=     deepcopy(__UpperCAmelCase				)  # this has 0 cost since it is done inside `init_empty_weights` context manager`

      SCREAMING_SNAKE_CASE_      		=     find_tied_parameters(__UpperCAmelCase				)
      # For compatibility with Accelerate < 0.18
      if isinstance(__UpperCAmelCase     ,     __UpperCAmelCase				):
            SCREAMING_SNAKE_CASE_      		=     sum(list(tied_params.values()				)     ,     []				) + list(tied_params.keys()				)
      else:
            SCREAMING_SNAKE_CASE_      		=     sum(__UpperCAmelCase     ,     []				)
      SCREAMING_SNAKE_CASE_      		=     len(__UpperCAmelCase				) > 0

      # Check if it is a base model
      SCREAMING_SNAKE_CASE_      		=     False
      if hasattr(__UpperCAmelCase     ,     'base_model_prefix'				):
            SCREAMING_SNAKE_CASE_      		=     not hasattr(__UpperCAmelCase     ,     model.base_model_prefix				)

      # Ignore this for base models (BertModel, GPT2Model, etc.)
      if (not has_tied_params) and is_base_model:
            return []

      # otherwise they have an attached head
      SCREAMING_SNAKE_CASE_      		=     list(model.named_children()				)
      SCREAMING_SNAKE_CASE_      		=     [list_modules[-1][0]]

      # add last module together with tied weights
      SCREAMING_SNAKE_CASE_      		=     set(__UpperCAmelCase				) - set(__UpperCAmelCase				)
      SCREAMING_SNAKE_CASE_      		=     list(set(__UpperCAmelCase				)				) + list(__UpperCAmelCase				)

      # remove ".weight" from the keys
      SCREAMING_SNAKE_CASE_      		=     ['.weight', '.bias']
      SCREAMING_SNAKE_CASE_      		=     []
      for name in list_untouched:
            for name_to_remove in names_to_remove:
                  if name_to_remove in name:
                        SCREAMING_SNAKE_CASE_      		=     name.replace(__UpperCAmelCase     ,     ''				)
            filtered_module_names.append(__UpperCAmelCase				)

      return filtered_module_names

def    UpperCAmelCase_				( __UpperCAmelCase		:      Optional[int]				)   ->					Optional[Any]:
      for m in model.modules():
            if isinstance(__UpperCAmelCase     ,     bnb.nn.Linearabit				):
                  return True
      return False

def    UpperCAmelCase_				( __UpperCAmelCase		:      nn.Module				)   ->					List[str]:
      return next(parameter.parameters()				).device





def    UpperCAmelCase_				( __UpperCAmelCase		:      List[Any]     ,     __UpperCAmelCase		:      List[Any]     ,     __UpperCAmelCase		:      Tuple     ,     __UpperCAmelCase		:      Union[str, Any]     ,     __UpperCAmelCase		:      Optional[Any]     ,     __UpperCAmelCase		:      Dict     ,     __UpperCAmelCase		:      List[Any]				)   ->					Any:
      # if it is not quantized, we quantize and offload the quantized weights and the SCB stats
      if fpaa_statistics is None:
            set_module_tensor_to_device(__UpperCAmelCase     ,     __UpperCAmelCase     ,     0     ,     dtype=__UpperCAmelCase     ,     value=__UpperCAmelCase				)
            SCREAMING_SNAKE_CASE_      		=     param_name
            SCREAMING_SNAKE_CASE_      		=     model
            if "." in tensor_name:
                  SCREAMING_SNAKE_CASE_      		=     tensor_name.split('.'				)
                  for split in splits[:-1]:
                        SCREAMING_SNAKE_CASE_      		=     getattr(__UpperCAmelCase     ,     __UpperCAmelCase				)
                        if new_module is None:
                              raise ValueError(f"{module} has no attribute {split}."				)
                        SCREAMING_SNAKE_CASE_      		=     new_module
                  SCREAMING_SNAKE_CASE_      		=     splits[-1]
            # offload weights
            SCREAMING_SNAKE_CASE_      		=     False
            offload_weight(module._parameters[tensor_name]     ,     __UpperCAmelCase     ,     __UpperCAmelCase     ,     index=__UpperCAmelCase				)
            if hasattr(module._parameters[tensor_name]     ,     'SCB'				):
                  offload_weight(
                      module._parameters[tensor_name].SCB     ,     param_name.replace('weight'     ,     'SCB'				)     ,     __UpperCAmelCase     ,     index=__UpperCAmelCase     ,     )
      else:
            offload_weight(__UpperCAmelCase     ,     __UpperCAmelCase     ,     __UpperCAmelCase     ,     index=__UpperCAmelCase				)
            offload_weight(__UpperCAmelCase     ,     param_name.replace('weight'     ,     'SCB'				)     ,     __UpperCAmelCase     ,     index=__UpperCAmelCase				)

      set_module_tensor_to_device(__UpperCAmelCase     ,     __UpperCAmelCase     ,     'meta'     ,     dtype=__UpperCAmelCase     ,     value=torch.empty(*param.size()				)				)


"""simple docstring"""

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

from tokenizers import processors

from ...tokenization_utils import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging


if is_sentencepiece_available():
    from .tokenization_nllb import NllbTokenizer
else:
    _UpperCamelCase		     =    None


_UpperCamelCase		     =    logging.get_logger(__name__)


_UpperCamelCase		     =    {"""vocab_file""": """sentencepiece.bpe.model""", """tokenizer_file""": """tokenizer.json"""}

_UpperCamelCase		     =    {
    """vocab_file""": {
        """facebook/nllb-200-distilled-600M""": (
            """https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model"""
        ),
    },
    """tokenizer_file""": {
        """facebook/nllb-200-distilled-600M""": (
            """https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json"""
        ),
    },
}

_UpperCamelCase		     =    {
    """facebook/nllb-large-en-ro""": 1_0_2_4,
    """facebook/nllb-200-distilled-600M""": 1_0_2_4,
}

# fmt: off
_UpperCamelCase		     =    ["""ace_Arab""", """ace_Latn""", """acm_Arab""", """acq_Arab""", """aeb_Arab""", """afr_Latn""", """ajp_Arab""", """aka_Latn""", """amh_Ethi""", """apc_Arab""", """arb_Arab""", """ars_Arab""", """ary_Arab""", """arz_Arab""", """asm_Beng""", """ast_Latn""", """awa_Deva""", """ayr_Latn""", """azb_Arab""", """azj_Latn""", """bak_Cyrl""", """bam_Latn""", """ban_Latn""", """bel_Cyrl""", """bem_Latn""", """ben_Beng""", """bho_Deva""", """bjn_Arab""", """bjn_Latn""", """bod_Tibt""", """bos_Latn""", """bug_Latn""", """bul_Cyrl""", """cat_Latn""", """ceb_Latn""", """ces_Latn""", """cjk_Latn""", """ckb_Arab""", """crh_Latn""", """cym_Latn""", """dan_Latn""", """deu_Latn""", """dik_Latn""", """dyu_Latn""", """dzo_Tibt""", """ell_Grek""", """eng_Latn""", """epo_Latn""", """est_Latn""", """eus_Latn""", """ewe_Latn""", """fao_Latn""", """pes_Arab""", """fij_Latn""", """fin_Latn""", """fon_Latn""", """fra_Latn""", """fur_Latn""", """fuv_Latn""", """gla_Latn""", """gle_Latn""", """glg_Latn""", """grn_Latn""", """guj_Gujr""", """hat_Latn""", """hau_Latn""", """heb_Hebr""", """hin_Deva""", """hne_Deva""", """hrv_Latn""", """hun_Latn""", """hye_Armn""", """ibo_Latn""", """ilo_Latn""", """ind_Latn""", """isl_Latn""", """ita_Latn""", """jav_Latn""", """jpn_Jpan""", """kab_Latn""", """kac_Latn""", """kam_Latn""", """kan_Knda""", """kas_Arab""", """kas_Deva""", """kat_Geor""", """knc_Arab""", """knc_Latn""", """kaz_Cyrl""", """kbp_Latn""", """kea_Latn""", """khm_Khmr""", """kik_Latn""", """kin_Latn""", """kir_Cyrl""", """kmb_Latn""", """kon_Latn""", """kor_Hang""", """kmr_Latn""", """lao_Laoo""", """lvs_Latn""", """lij_Latn""", """lim_Latn""", """lin_Latn""", """lit_Latn""", """lmo_Latn""", """ltg_Latn""", """ltz_Latn""", """lua_Latn""", """lug_Latn""", """luo_Latn""", """lus_Latn""", """mag_Deva""", """mai_Deva""", """mal_Mlym""", """mar_Deva""", """min_Latn""", """mkd_Cyrl""", """plt_Latn""", """mlt_Latn""", """mni_Beng""", """khk_Cyrl""", """mos_Latn""", """mri_Latn""", """zsm_Latn""", """mya_Mymr""", """nld_Latn""", """nno_Latn""", """nob_Latn""", """npi_Deva""", """nso_Latn""", """nus_Latn""", """nya_Latn""", """oci_Latn""", """gaz_Latn""", """ory_Orya""", """pag_Latn""", """pan_Guru""", """pap_Latn""", """pol_Latn""", """por_Latn""", """prs_Arab""", """pbt_Arab""", """quy_Latn""", """ron_Latn""", """run_Latn""", """rus_Cyrl""", """sag_Latn""", """san_Deva""", """sat_Beng""", """scn_Latn""", """shn_Mymr""", """sin_Sinh""", """slk_Latn""", """slv_Latn""", """smo_Latn""", """sna_Latn""", """snd_Arab""", """som_Latn""", """sot_Latn""", """spa_Latn""", """als_Latn""", """srd_Latn""", """srp_Cyrl""", """ssw_Latn""", """sun_Latn""", """swe_Latn""", """swh_Latn""", """szl_Latn""", """tam_Taml""", """tat_Cyrl""", """tel_Telu""", """tgk_Cyrl""", """tgl_Latn""", """tha_Thai""", """tir_Ethi""", """taq_Latn""", """taq_Tfng""", """tpi_Latn""", """tsn_Latn""", """tso_Latn""", """tuk_Latn""", """tum_Latn""", """tur_Latn""", """twi_Latn""", """tzm_Tfng""", """uig_Arab""", """ukr_Cyrl""", """umb_Latn""", """urd_Arab""", """uzn_Latn""", """vec_Latn""", """vie_Latn""", """war_Latn""", """wol_Latn""", """xho_Latn""", """ydd_Hebr""", """yor_Latn""", """yue_Hant""", """zho_Hans""", """zho_Hant""", """zul_Latn"""]






class 			__a					(						__magic_name__       ):





       """simple docstring"""


       __UpperCamelCase					:      List[Any]    =						VOCAB_FILES_NAMES
       __UpperCamelCase					:      Dict    =						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       __UpperCamelCase					:      Dict    =						PRETRAINED_VOCAB_FILES_MAP
       __UpperCamelCase					:      int    =						['input_ids', 'attention_mask']
       __UpperCamelCase					:      Union[str, Any]    =						NllbTokenizer

       __UpperCamelCase					:      List[int]    =						[]
       __UpperCamelCase					:      List[int]    =						[]






       def __init__(   self			,					snake_case=None			,					snake_case=None			,					snake_case="<s>"			,					snake_case="</s>"			,					snake_case="</s>"			,					snake_case="<s>"			,					snake_case="<unk>"			,					snake_case="<pad>"			,					snake_case="<mask>"			,					snake_case=None			,					snake_case=None			,					snake_case=None			,					snake_case=False			,					**snake_case			,					):





        """simple docstring"""

        lowerCAmelCase__   :				List[Any] 			=				AddedToken(snake_case			,					lstrip=snake_case			,					rstrip=snake_case   ) if isinstance(snake_case			,					snake_case   ) else mask_token
        lowerCAmelCase__   :				Tuple 			=				legacy_behaviour
        super().__init__(
            vocab_file=snake_case			,					tokenizer_file=snake_case			,					bos_token=snake_case			,					eos_token=snake_case			,					sep_token=snake_case			,					cls_token=snake_case			,					unk_token=snake_case			,					pad_token=snake_case			,					mask_token=snake_case			,					src_lang=snake_case			,					tgt_lang=snake_case			,					additional_special_tokens=snake_case			,					legacy_behaviour=snake_case			,					**snake_case			,					)

        lowerCAmelCase__   :				Optional[int] 			=				vocab_file
        lowerCAmelCase__   :				int 			=				False if not self.vocab_file else True

        lowerCAmelCase__   :				Union[str, Any] 			=				FAIRSEQ_LANGUAGE_CODES.copy()

        if additional_special_tokens is not None:
         # Only add those special tokens if they are not already there.
         _additional_special_tokens.extend(
             [t for t in additional_special_tokens if t not in _additional_special_tokens]   )

        self.add_special_tokens({"additional_special_tokens": _additional_special_tokens}   )
        lowerCAmelCase__   :				Tuple 			=				{
            lang_code: self.convert_tokens_to_ids(snake_case   ) for lang_code in FAIRSEQ_LANGUAGE_CODES
        }

        lowerCAmelCase__   :				Union[str, Any] 			=				src_lang if src_lang is not None else "eng_Latn"
        lowerCAmelCase__   :				List[str] 			=				self.convert_tokens_to_ids(self._src_lang   )
        lowerCAmelCase__   :				Any 			=				tgt_lang
        self.set_src_lang_special_tokens(self._src_lang   )






       @property
       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        return self._src_lang






       @src_lang.setter
       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case   ):





        """simple docstring"""

        lowerCAmelCase__   :				Union[str, Any] 			=				new_src_lang
        self.set_src_lang_special_tokens(self._src_lang   )






       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case			,					snake_case = None   ):





        """simple docstring"""

        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 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case			,					snake_case = None   ):





        """simple docstring"""

        lowerCAmelCase__   :				Tuple 			=				[self.sep_token_id]
        lowerCAmelCase__   :				Dict 			=				[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]






       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case			,					snake_case			,					snake_case			,					snake_case			,					**snake_case   ):





        """simple docstring"""

        if src_lang is None or tgt_lang is None:
         raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model"   )
        lowerCAmelCase__   :				Any 			=				src_lang
        lowerCAmelCase__   :				Optional[Any] 			=				self(snake_case			,					add_special_tokens=snake_case			,					return_tensors=snake_case			,					**snake_case   )
        lowerCAmelCase__   :				str 			=				self.convert_tokens_to_ids(snake_case   )
        lowerCAmelCase__   :				Any 			=				tgt_lang_id
        return inputs






       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case			,					snake_case = "eng_Latn"			,					snake_case = None			,					snake_case = "fra_Latn"			,					**snake_case			,					):





        """simple docstring"""

        lowerCAmelCase__   :				int 			=				src_lang
        lowerCAmelCase__   :				str 			=				tgt_lang
        return super().prepare_seqaseq_batch(snake_case			,					snake_case			,					**snake_case   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        return self.set_src_lang_special_tokens(self.src_lang   )






       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        return self.set_tgt_lang_special_tokens(self.tgt_lang   )






       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case   ):





        """simple docstring"""

        lowerCAmelCase__   :				Tuple 			=				self.convert_tokens_to_ids(snake_case   )

        if self.legacy_behaviour:
         lowerCAmelCase__   :				Optional[int] 			=				[]
         lowerCAmelCase__   :				Optional[int] 			=				[self.eos_token_id, self.cur_lang_code]
        else:
         lowerCAmelCase__   :				int 			=				[self.cur_lang_code]
         lowerCAmelCase__   :				List[str] 			=				[self.eos_token_id]

        lowerCAmelCase__   :				Any 			=				self.convert_ids_to_tokens(self.prefix_tokens   )
        lowerCAmelCase__   :				str 			=				self.convert_ids_to_tokens(self.suffix_tokens   )

        lowerCAmelCase__   :				Tuple 			=				processors.TemplateProcessing(
            single=prefix_tokens_str + ["$A"] + suffix_tokens_str			,					pair=prefix_tokens_str + ["$A", "$B"] + suffix_tokens_str			,					special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str			,					self.prefix_tokens + self.suffix_tokens   )   )			,					)






       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case   ):





        """simple docstring"""

        lowerCAmelCase__   :				List[Any] 			=				self.convert_tokens_to_ids(snake_case   )
        if self.legacy_behaviour:
         lowerCAmelCase__   :				Dict 			=				[]
         lowerCAmelCase__   :				Dict 			=				[self.eos_token_id, self.cur_lang_code]
        else:
         lowerCAmelCase__   :				str 			=				[self.cur_lang_code]
         lowerCAmelCase__   :				Tuple 			=				[self.eos_token_id]

        lowerCAmelCase__   :				Any 			=				self.convert_ids_to_tokens(self.prefix_tokens   )
        lowerCAmelCase__   :				List[Any] 			=				self.convert_ids_to_tokens(self.suffix_tokens   )

        lowerCAmelCase__   :				Optional[int] 			=				processors.TemplateProcessing(
            single=prefix_tokens_str + ["$A"] + suffix_tokens_str			,					pair=prefix_tokens_str + ["$A", "$B"] + suffix_tokens_str			,					special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str			,					self.prefix_tokens + self.suffix_tokens   )   )			,					)






       def 			SCREAMING_SNAKE_CASE_	(   self			,					snake_case			,					snake_case = None   ):





        """simple docstring"""

        if not self.can_save_slow_tokenizer:
         raise ValueError(
             "Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
             "tokenizer."   )

        if not os.path.isdir(snake_case   ):
         logger.error(F"""Vocabulary path ({save_directory}) should be a directory."""   )
         return
        lowerCAmelCase__   :				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   ):
         copyfile(self.vocab_file			,					snake_case   )

        return (out_vocab_file,)






