





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


A       :   Optional[int]					= logging.getLogger(__name__)







def   __lowerCamelCase   (				__a  :torch.nn.Module       ,	__a  :BnbQuantizationConfig       ,	__a  :Union[str, os.PathLike] = None       ,	__a  :Optional[Dict[str, Union[int, str, torch.device]]] = None       ,	__a  :Optional[List[str]] = None       ,	__a  :Optional[Dict[Union[int, str], Union[int, str]]] = None       ,	__a  :Optional[Union[str, os.PathLike]] = None       ,	__a  :bool = False       ,	)						->							Dict:






		"""simple docstring"""

		A__     =  bnb_quantization_config.load_in_abit
		A__     =  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."""       )

		A__     =  []
		# custom device map
		if isinstance(_snake_case       ,	_snake_case       ) and len(device_map.keys()       ) > 1:
				A__     =  [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:
				A__     =  get_keys_to_not_convert(_snake_case       )

		# add cpu modules to skip modules only for 4-bit modules
		if load_in_abit:
				bnb_quantization_config.skip_modules.extend(_snake_case       )
		A__     =  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:
				A__     =  []
		A__     =  bnb_quantization_config.keep_in_fpaa_modules
		modules_to_not_convert.extend(_snake_case       )

		# compatibility with peft
		A__     =  load_in_abit
		A__     =  load_in_abit

		A__     =  get_parameter_device(_snake_case       )
		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."""       )
				A__     =  replace_with_bnb_layers(_snake_case       ,	_snake_case       ,	modules_to_not_convert=_snake_case       )
				# convert param to the right dtype
				A__     =  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:
										A__     =  name.replace(""".weight"""       ,	""""""       ).replace(""".bias"""       ,	""""""       )
										A__     =  getattr(_snake_case       ,	_snake_case       ,	_snake_case       )
										if param is not None:
												param.to(torch.floataa       )
						elif torch.is_floating_point(_snake_case       ):
								param.to(_snake_case       )
				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():
						A__     =  replace_with_bnb_layers(
						    _snake_case       ,	_snake_case       ,	modules_to_not_convert=_snake_case       )

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

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

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







def   __lowerCamelCase   (				__a  :Optional[int]       ,	__a  :Optional[Any]       ,	__a  :Tuple=None       ,	__a  :Union[str, Any]=None       ,	__a  :Tuple=None       )						->							Optional[Any]:






		"""simple docstring"""

		if device_map is None:
				if torch.cuda.is_available():
						A__     =  {"""""": 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(_snake_case       ,	_snake_case       ):
				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\'."""       )

				A__     =  {}
				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       )
				    }       )

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

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

				A__     =  max_memory
				A__     =  infer_auto_device_map(_snake_case       ,	**_snake_case       )

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

				A__     =  {
				    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(
										    """
                        Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit
                        the quantized model. If you want to dispatch the model on the CPU or the disk while keeping
                        these modules in `torch_dtype`, you need to pass a custom `device_map` to
                        `load_and_quantize_model`. Check
                        https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk
                        for more details.
                        """       )
								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   __lowerCamelCase   (				__a  :Any       ,	__a  :Tuple       ,	__a  :Dict=None       ,	__a  :Optional[Any]=None       )						->							int:






		"""simple docstring"""

		if modules_to_not_convert is None:
				A__     =  []

		A__ ,     A__     =  _replace_with_bnb_layers(
		    _snake_case       ,	_snake_case       ,	_snake_case       ,	_snake_case       )
		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   __lowerCamelCase   (				__a  :str       ,	__a  :Any       ,	__a  :List[str]=None       ,	__a  :Optional[int]=None       ,	)						->							int:






		"""simple docstring"""

		A__     =  False
		for name, module in model.named_children():
				if current_key_name is None:
						A__     =  []
				current_key_name.append(_snake_case       )
				if isinstance(_snake_case       ,	nn.Linear       ) and name not in modules_to_not_convert:
						# Check if the current key is not in the `modules_to_not_convert`
						A__     =  """.""".join(_snake_case       )
						A__     =  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:
										A__     =  False
										break
						if proceed:
								# Load bnb module with empty weight and replace ``nn.Linear` module
								if bnb_quantization_config.load_in_abit:
										A__     =  bnb.nn.LinearabitLt(
										    module.in_features       ,	module.out_features       ,	module.bias is not None       ,	has_fpaa_weights=_snake_case       ,	threshold=bnb_quantization_config.llm_inta_threshold       ,	)
								elif bnb_quantization_config.load_in_abit:
										A__     =  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"""       )
								A__     =  module.weight.data
								if module.bias is not None:
										A__     =  module.bias.data
								bnb_module.requires_grad_(_snake_case       )
								setattr(_snake_case       ,	_snake_case       ,	_snake_case       )
								A__     =  True
				if len(list(module.children()       )       ) > 0:
						A__ ,     A__     =  _replace_with_bnb_layers(
						    _snake_case       ,	_snake_case       ,	_snake_case       ,	_snake_case       )
						A__     =  has_been_replaced | _has_been_replaced
				# Remove the last key for recursion
				current_key_name.pop(-1       )
		return model, has_been_replaced







def   __lowerCamelCase   (				__a  :Tuple       )						->							List[str]:






		"""simple docstring"""

		with init_empty_weights():
				A__     =  deepcopy(_snake_case       )  # this has 0 cost since it is done inside `init_empty_weights` context manager`

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

		# Check if it is a base model
		A__     =  False
		if hasattr(_snake_case       ,	"""base_model_prefix"""       ):
				A__     =  not hasattr(_snake_case       ,	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
		A__     =  list(model.named_children()       )
		A__     =  [list_modules[-1][0]]

		# add last module together with tied weights
		A__     =  set(_snake_case       ) - set(_snake_case       )
		A__     =  list(set(_snake_case       )       ) + list(_snake_case       )

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

		return filtered_module_names







def   __lowerCamelCase   (				__a  :int       )						->							Union[str, Any]:






		"""simple docstring"""

		for m in model.modules():
				if isinstance(_snake_case       ,	bnb.nn.Linearabit       ):
						return True
		return False







def   __lowerCamelCase   (				__a  :nn.Module       )						->							int:






		"""simple docstring"""

		return next(parameter.parameters()       ).device







def   __lowerCamelCase   (				__a  :Any       ,	__a  :Optional[Any]       ,	__a  :Optional[int]       ,	__a  :Optional[int]       ,	__a  :List[str]       ,	__a  :Dict       ,	__a  :Optional[int]       )						->							Dict:






		"""simple docstring"""

		if fpaa_statistics is None:
				set_module_tensor_to_device(_snake_case       ,	_snake_case       ,	0       ,	dtype=_snake_case       ,	value=_snake_case       )
				A__     =  param_name
				A__     =  model
				if "." in tensor_name:
						A__     =  tensor_name.split("""."""       )
						for split in splits[:-1]:
								A__     =  getattr(_snake_case       ,	_snake_case       )
								if new_module is None:
										raise ValueError(F'{module} has no attribute {split}.'       )
								A__     =  new_module
						A__     =  splits[-1]
				# offload weights
				A__     =  False
				offload_weight(module._parameters[tensor_name]       ,	_snake_case       ,	_snake_case       ,	index=_snake_case       )
				if hasattr(module._parameters[tensor_name]       ,	"""SCB"""       ):
						offload_weight(
						    module._parameters[tensor_name].SCB       ,	param_name.replace("""weight"""       ,	"""SCB"""       )       ,	_snake_case       ,	index=_snake_case       ,	)
		else:
				offload_weight(_snake_case       ,	_snake_case       ,	_snake_case       ,	index=_snake_case       )
				offload_weight(_snake_case       ,	param_name.replace("""weight"""       ,	"""SCB"""       )       ,	_snake_case       ,	index=_snake_case       )

		set_module_tensor_to_device(_snake_case       ,	_snake_case       ,	"""meta"""       ,	dtype=_snake_case       ,	value=torch.empty(*param.size()       )       )








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

import sentencepiece as spm

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


UpperCAmelCase_		 =					logging.get_logger(__name__)

UpperCAmelCase_		 =					"""▁"""

UpperCAmelCase_		 =					{"""vocab_file""": """sentencepiece.bpe.model""", """monolingual_vocab_file""": """dict.txt"""}

UpperCAmelCase_		 =					{
    """vocab_file""": {
        """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/sentencepiece.bpe.model""",
    },
    """monolingual_vocab_file""": {
        """vinai/bartpho-syllable""": """https://huggingface.co/vinai/bartpho-syllable/resolve/main/dict.txt""",
    },
}

UpperCAmelCase_		 =					{"""vinai/bartpho-syllable""": 1_0_2_4}


class 	lowerCamelCase__	(       _A):



 """simple docstring"""

 a__					: int =  VOCAB_FILES_NAMES
 a__					: Tuple =  PRETRAINED_VOCAB_FILES_MAP
 a__					: Optional[int] =  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
 a__					: Tuple =  ["input_ids", "attention_mask"]

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

    _A      =       {} if sp_model_kwargs is None else sp_model_kwargs

    super().__init__(
        bos_token=__lowerCAmelCase			,						eos_token=__lowerCAmelCase			,						unk_token=__lowerCAmelCase			,						sep_token=__lowerCAmelCase			,						cls_token=__lowerCAmelCase			,						pad_token=__lowerCAmelCase			,						mask_token=__lowerCAmelCase			,						sp_model_kwargs=self.sp_model_kwargs			,						**__lowerCAmelCase			,						)

    _A      =       vocab_file
    _A      =       monolingual_vocab_file
    _A      =       spm.SentencePieceProcessor(**self.sp_model_kwargs      )
    self.sp_model.Load(str(__lowerCAmelCase      )      )

    # Load the reduced vocab

    # Keep order of special tokens for backward compatibility
    _A      =       {}
    _A      =       0
    for token in [bos_token, pad_token, eos_token, unk_token, sep_token, cls_token]:
       if str(__lowerCAmelCase      ) not in self.fairseq_tokens_to_ids:
          _A      =       cnt
          cnt += 1
    with open(__lowerCAmelCase			,						'''r'''			,						encoding='''utf-8'''      ) as f:
       for line in f.readlines():
          _A      =       line.strip().split()[0]
          _A      =       len(self.fairseq_tokens_to_ids      )
    if str(__lowerCAmelCase      ) not in self.fairseq_tokens_to_ids:
       _A      =       len(self.fairseq_tokens_to_ids      )

    _A      =       {v: k for k, v in self.fairseq_tokens_to_ids.items()}

 def __getstate__(    self					:					Any      )   ->	List[Any]:
    _A      =       self.__dict__.copy()
    _A      =       None
    _A      =       self.sp_model.serialized_model_proto()
    return state

 def __setstate__(    self					:					Union[str, Any]			,						__lowerCAmelCase					:					Dict      )   ->	List[Any]:
    _A      =       d

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

    _A      =       spm.SentencePieceProcessor(**self.sp_model_kwargs      )
    self.sp_model.LoadFromSerializedProto(self.sp_model_proto      )

 def     snake_case_      (    self					:					Optional[Any]			,						__lowerCAmelCase					:					List[int]			,						__lowerCAmelCase					:					Optional[List[int]] = None      )   ->	List[int]:

    if token_ids_a is None:
       return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
    _A      =       [self.cls_token_id]
    _A      =       [self.sep_token_id]
    return cls + token_ids_a + sep + sep + token_ids_a + sep

 def     snake_case_      (    self					:					List[Any]			,						__lowerCAmelCase					:					List[int]			,						__lowerCAmelCase					:					Optional[List[int]] = None			,						__lowerCAmelCase					:					bool = False      )   ->	List[int]:

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

    if token_ids_a is None:
       return [1] + ([0] * len(__lowerCAmelCase      )) + [1]
    return [1] + ([0] * len(__lowerCAmelCase      )) + [1, 1] + ([0] * len(__lowerCAmelCase      )) + [1]

 def     snake_case_      (    self					:					Any			,						__lowerCAmelCase					:					List[int]			,						__lowerCAmelCase					:					Optional[List[int]] = None      )   ->	List[int]:
    _A      =       [self.sep_token_id]
    _A      =       [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]

 @property
 def     snake_case_      (    self					:					Optional[int]      )   ->	Union[str, Any]:
    return len(self.fairseq_ids_to_tokens      )

 def     snake_case_      (    self					:					Dict      )   ->	Optional[Any]:
    _A      =       {self.convert_ids_to_tokens(__lowerCAmelCase      ): i for i in range(self.vocab_size      )}
    vocab.update(self.added_tokens_encoder      )
    return vocab

 def     snake_case_      (    self					:					List[str]			,						__lowerCAmelCase					:					str      )   ->	List[str]:
    return self.sp_model.encode(__lowerCAmelCase			,						out_type=__lowerCAmelCase      )

 def     snake_case_      (    self					:					str			,						__lowerCAmelCase					:					Optional[Any]      )   ->	Dict:
    if token in self.fairseq_tokens_to_ids:
       return self.fairseq_tokens_to_ids[token]
    else:
       return self.unk_token_id

 def     snake_case_      (    self					:					int			,						__lowerCAmelCase					:					Optional[int]      )   ->	List[str]:
    return self.fairseq_ids_to_tokens[index]

 def     snake_case_      (    self					:					List[str]			,						__lowerCAmelCase					:					Union[str, Any]      )   ->	Tuple:
    _A      =       ''''''.join(__lowerCAmelCase      ).replace(__lowerCAmelCase			,						''' '''      ).strip()
    return out_string

 def     snake_case_      (    self					:					str			,						__lowerCAmelCase					:					str			,						__lowerCAmelCase					:					Optional[str] = None      )   ->	Tuple[str]:
    if not os.path.isdir(__lowerCAmelCase      ):
       logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''      )
       return
    _A      =       os.path.join(
        __lowerCAmelCase			,						(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']      )
    _A      =       os.path.join(
        __lowerCAmelCase			,						(filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''monolingual_vocab_file''']			,						)

    if os.path.abspath(self.vocab_file      ) != os.path.abspath(__lowerCAmelCase      ) and os.path.isfile(self.vocab_file      ):
       copyfile(self.vocab_file			,						__lowerCAmelCase      )
    elif not os.path.isfile(self.vocab_file      ):
       with open(__lowerCAmelCase			,						'''wb'''      ) as fi:
          _A      =       self.sp_model.serialized_model_proto()
          fi.write(__lowerCAmelCase      )

    if os.path.abspath(self.monolingual_vocab_file      ) != os.path.abspath(
        __lowerCAmelCase      ) and os.path.isfile(self.monolingual_vocab_file      ):
       copyfile(self.monolingual_vocab_file			,						__lowerCAmelCase      )
    elif not os.path.isfile(self.monolingual_vocab_file      ):
       with open(__lowerCAmelCase			,						'''w'''			,						encoding='''utf-8'''      ) as fp:
          for token in self.fairseq_tokens_to_ids:
             if token not in self.all_special_tokens:
                fp.write(f'''{str(__lowerCAmelCase      )} \n'''      )

    return out_vocab_file, out_monolingual_vocab_file



