


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__  :int             =							logging.getLogger(__name__)

def 	lowerCAmelCase__			(      a__:		Optional[int]      ,  a__:		int      ,  a__:		str = None      ,  a__:		Optional[Any] = None      ,  a__:		Union[str, Any] = None      ,  a__:		List[str] = None      ,  a__:		int = None      ,  a__:		Optional[int] = False      ,  )  ->		Any:


							'''simple docstring'''





							_UpperCAmelCase					=      bnb_quantization_config.load_in_abit
							_UpperCAmelCase					=      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.'	)

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

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

							# compatibility with peft
							_UpperCAmelCase					=      load_in_abit
							_UpperCAmelCase					=      load_in_abit

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

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

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

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

def 	lowerCAmelCase__			(      a__:		Union[str, Any]      ,  a__:		str      ,  a__:		str=None      ,  a__:		Optional[int]=None      ,  a__:		Tuple=None	)  ->		Dict:


							'''simple docstring'''





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

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

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

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

														_UpperCAmelCase					=      max_memory
														_UpperCAmelCase					=      infer_auto_device_map(lowerCAmelCase__      ,  **lowerCAmelCase__	)

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

														_UpperCAmelCase					=      {
														    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 	lowerCAmelCase__			(      a__:		Optional[Any]      ,  a__:		Optional[Any]      ,  a__:		List[Any]=None      ,  a__:		Any=None	)  ->		int:


							'''simple docstring'''





							if modules_to_not_convert is None:
														_UpperCAmelCase					=      []

							_UpperCAmelCase		,	_UpperCAmelCase					=      _replace_with_bnb_layers(
							    lowerCAmelCase__      ,  lowerCAmelCase__      ,  lowerCAmelCase__      ,  lowerCAmelCase__	)
							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__:		List[str]      ,  a__:		int      ,  a__:		Tuple=None      ,  a__:		Any=None      ,  )  ->		List[str]:


							'''simple docstring'''





							_UpperCAmelCase					=      False
							for name, module in model.named_children():
														if current_key_name is None:
																					_UpperCAmelCase					=      []
														current_key_name.append(lowerCAmelCase__	)
														if isinstance(lowerCAmelCase__      ,  nn.Linear	) and name not in modules_to_not_convert:
																					# Check if the current key is not in the `modules_to_not_convert`
																					_UpperCAmelCase					=      '.'.join(lowerCAmelCase__	)
																					_UpperCAmelCase					=      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:
																																			_UpperCAmelCase					=      False
																																			break
																					if proceed:
																												# Load bnb module with empty weight and replace ``nn.Linear` module
																												if bnb_quantization_config.load_in_abit:
																																			_UpperCAmelCase					=      bnb.nn.LinearabitLt(
																																			    module.in_features      ,  module.out_features      ,  module.bias is not None      ,  has_fpaa_weights=lowerCAmelCase__      ,  threshold=bnb_quantization_config.llm_inta_threshold      ,  )
																												elif bnb_quantization_config.load_in_abit:
																																			_UpperCAmelCase					=      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'	)
																												_UpperCAmelCase					=      module.weight.data
																												if module.bias is not None:
																																			_UpperCAmelCase					=      module.bias.data
																												bnb_module.requires_grad_(lowerCAmelCase__	)
																												setattr(lowerCAmelCase__      ,  lowerCAmelCase__      ,  lowerCAmelCase__	)
																												_UpperCAmelCase					=      True
														if len(list(module.children()	)	) > 0:
																					_UpperCAmelCase		,	_UpperCAmelCase					=      _replace_with_bnb_layers(
																					    lowerCAmelCase__      ,  lowerCAmelCase__      ,  lowerCAmelCase__      ,  lowerCAmelCase__	)
																					_UpperCAmelCase					=      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__:		Optional[Any]	)  ->		str:


							'''simple docstring'''





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

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

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

							# add last module together with tied weights
							_UpperCAmelCase					=      set(lowerCAmelCase__	) - set(lowerCAmelCase__	)
							_UpperCAmelCase					=      list(set(lowerCAmelCase__	)	) + list(lowerCAmelCase__	)

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

							return filtered_module_names

def 	lowerCAmelCase__			(      a__:		List[Any]	)  ->		Optional[int]:


							'''simple docstring'''





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

def 	lowerCAmelCase__			(      a__:		List[Any]	)  ->		Tuple:


							'''simple docstring'''





							return next(parameter.parameters()	).device







def 	lowerCAmelCase__			(      a__:		List[str]      ,  a__:		List[str]      ,  a__:		List[Any]      ,  a__:		List[Any]      ,  a__:		Optional[int]      ,  a__:		Optional[int]      ,  a__:		Tuple	)  ->		Tuple:


							'''simple docstring'''





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

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




from importlib import import_module

from .logging import get_logger


lowerCAmelCase__  :Optional[Any]             =							get_logger(__name__)

class 		__a				:
		def __init__(      self      ,   _SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE=None						)			->	List[Any]:




									"""simple docstring"""





									_UpperCAmelCase					=      attrs or []
									if module is not None:
																for key in module.__dict__:
																							if key in attrs or not key.startswith('__'						):
																														setattr(self      ,   _SCREAMING_SNAKE_CASE      ,   getattr(_SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE						)						)
									_UpperCAmelCase					=      module._original_module if isinstance(_SCREAMING_SNAKE_CASE      ,   _PatchedModuleObj						) else module



class 		__a				:
		_a     :  Any           =     []
		def __init__(      self      ,   _SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE=None						)			->	Union[str, Any]:




									"""simple docstring"""





									_UpperCAmelCase					=      obj
									_UpperCAmelCase					=      target
									_UpperCAmelCase					=      new
									_UpperCAmelCase					=      target.split('.'						)[0]
									_UpperCAmelCase					=      {}
									_UpperCAmelCase					=      attrs or []
		def __enter__(      self						)			->	int:




									"""simple docstring"""





									*_UpperCAmelCase		,	_UpperCAmelCase					=      self.target.split('.'						)

									# Patch modules:
									# it's used to patch attributes of submodules like "os.path.join";
									# in this case we need to patch "os" and "os.path"

									for i in range(len(_SCREAMING_SNAKE_CASE						)						):
																try:
																							_UpperCAmelCase					=      import_module('.'.join(submodules[: i + 1]						)						)
																except ModuleNotFoundError:
																							continue
																# We iterate over all the globals in self.obj in case we find "os" or "os.path"
																for attr in self.obj.__dir__():
																							_UpperCAmelCase					=      getattr(self.obj      ,   _SCREAMING_SNAKE_CASE						)
																							# We don't check for the name of the global, but rather if its value *is* "os" or "os.path".
																							# This allows to patch renamed modules like "from os import path as ospath".
																							if obj_attr is submodule or (
																							    (isinstance(_SCREAMING_SNAKE_CASE      ,   _PatchedModuleObj						) and obj_attr._original_module is submodule)
																							):
																														_UpperCAmelCase					=      obj_attr
																														# patch at top level
																														setattr(self.obj      ,   _SCREAMING_SNAKE_CASE      ,   _PatchedModuleObj(_SCREAMING_SNAKE_CASE      ,   attrs=self.attrs						)						)
																														_UpperCAmelCase					=      getattr(self.obj      ,   _SCREAMING_SNAKE_CASE						)
																														# construct lower levels patches
																														for key in submodules[i + 1 :]:
																																					setattr(_SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE      ,   _PatchedModuleObj(getattr(_SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE						)      ,   attrs=self.attrs						)						)
																																					_UpperCAmelCase					=      getattr(_SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE						)
																														# finally set the target attribute
																														setattr(_SCREAMING_SNAKE_CASE      ,   _SCREAMING_SNAKE_CASE      ,   self.new						)

        # Patch attribute itself:
        # it's used for builtins like "open",
        # and also to patch "os.path.join" we may also need to patch "join"
        # itself if it was imported as "from os.path import join".

									if submodules:  # if it's an attribute of a submodule like "os.path.join"
																try:
																							_UpperCAmelCase					=      getattr(import_module('.'.join(_SCREAMING_SNAKE_CASE						)						)      ,   _SCREAMING_SNAKE_CASE						)
																except (AttributeError, ModuleNotFoundError):
																							return
																# We iterate over all the globals in self.obj in case we find "os.path.join"
																for attr in self.obj.__dir__():
																							# We don't check for the name of the global, but rather if its value *is* "os.path.join".
																							# This allows to patch renamed attributes like "from os.path import join as pjoin".
																							if getattr(self.obj      ,   _SCREAMING_SNAKE_CASE						) is attr_value:
																														_UpperCAmelCase					=      getattr(self.obj      ,   _SCREAMING_SNAKE_CASE						)
																														setattr(self.obj      ,   _SCREAMING_SNAKE_CASE      ,   self.new						)
									elif target_attr in globals()["__builtins__"]:  # if it'a s builtin like "open"
																_UpperCAmelCase					=      globals()['__builtins__'][target_attr]
																setattr(self.obj      ,   _SCREAMING_SNAKE_CASE      ,   self.new						)
									else:
																raise RuntimeError(f'''Tried to patch attribute {target_attr} instead of a submodule.'''						)
		def __exit__(      self      ,   *_SCREAMING_SNAKE_CASE						)			->	Union[str, Any]:




									"""simple docstring"""





									for attr in list(self.original						):
																setattr(self.obj      ,   _SCREAMING_SNAKE_CASE      ,   self.original.pop(_SCREAMING_SNAKE_CASE						)						)
		def      UpperCAmelCase__    (      self						)			->	Optional[int]:




									"""simple docstring"""





									self.__enter__()
									self._active_patches.append(self						)






		def      UpperCAmelCase__    (      self						)			->	str:




									"""simple docstring"""





									try:
																self._active_patches.remove(self						)
									except ValueError:
																# If the patch hasn't been started this will fail
																return None

									return self.__exit__()
