





import importlib.metadata
import warnings
from copy import deepcopy

from packaging import version

from ..utils import logging
from .import_utils import is_accelerate_available, is_bitsandbytes_available


if is_bitsandbytes_available():
				import bitsandbytes as bnb
				import torch
				import torch.nn as nn

				from ..pytorch_utils import ConvaD

if is_accelerate_available():
				from accelerate import init_empty_weights
				from accelerate.utils import find_tied_parameters

UpperCAmelCase						:   Any			  =     logging.get_logger(__name__)







def  _SCREAMING_SNAKE_CASE				(   a					,						a					,						a					,						a=None					,						a=None  )      ->      Optional[Any]:
					# Recurse if needed
					if "." in tensor_name:
										__A	:						List[Any]       =				tensor_name.split('.'  )
										for split in splits[:-1]:
															__A	:						int       =				getattr(a					,						a  )
															if new_module is None:
																				raise ValueError(F"""{module} has no attribute {split}."""  )
															__A	:						Tuple       =				new_module
										__A	:						int       =				splits[-1]

					if tensor_name not in module._parameters and tensor_name not in module._buffers:
										raise ValueError(F"""{module} does not have a parameter or a buffer named {tensor_name}."""  )
					__A	:						Tuple       =				tensor_name in module._buffers
					__A	:						Tuple       =				getattr(a					,						a  )

					if old_value.device == torch.device('meta'  ) and device not in ["meta", torch.device('meta'  )] and value is None:
										raise ValueError(F"""{tensor_name} is on the meta device, we need a `value` to put in on {device}."""  )

					__A	:						Optional[Any]       =				False
					__A	:						List[str]       =				False
					if is_buffer or not is_bitsandbytes_available():
										__A	:						List[Any]       =				False
										__A	:						Dict       =				False
					else:
										__A	:						Optional[Any]       =				hasattr(bnb.nn					,						'Params4bit'  ) and isinstance(module._parameters[tensor_name]					,						bnb.nn.Paramsabit  )
										__A	:						Optional[int]       =				isinstance(module._parameters[tensor_name]					,						bnb.nn.IntaParams  )

					if is_abit or is_abit:
										__A	:						Optional[int]       =				module._parameters[tensor_name]
										if param.device.type != "cuda":
															if value is None:
																				__A	:						int       =				old_value.to(a  )
															elif isinstance(a					,						torch.Tensor  ):
																				__A	:						Dict       =				value.to('cpu'  )
																				if value.dtype == torch.inta:
																									__A	:						List[str]       =				version.parse(importlib.metadata.version('bitsandbytes'  )  ) > version.parse(
																									    '0.37.2'  )
																									if not is_abit_serializable:
																														raise ValueError(
																														    'Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. '
																														    'Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.'  )
															else:
																				__A	:						Union[str, Any]       =				torch.tensor(a					,						device='cpu'  )

															# Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization.
															# Since weights are saved in the correct "orientation", we skip transposing when loading.
															if issubclass(module.source_cls					,						a  ) and fpaa_statistics is None:
																				__A	:						Any       =				new_value.T

															__A	:						Union[str, Any]       =				old_value.__dict__
															if is_abit:
																				__A	:						Optional[Any]       =				bnb.nn.IntaParams(a					,						requires_grad=a					,						**a  ).to(a  )
															elif is_abit:
																				__A	:						Tuple       =				bnb.nn.Paramsabit(a					,						requires_grad=a					,						**a  ).to(a  )

															__A	:						Optional[int]       =				new_value
															if fpaa_statistics is not None:
																				setattr(module.weight					,						'SCB'					,						fpaa_statistics.to(a  )  )

					else:
										if value is None:
															__A	:						Dict       =				old_value.to(a  )
										elif isinstance(a					,						torch.Tensor  ):
															__A	:						Union[str, Any]       =				value.to(a  )
										else:
															__A	:						str       =				torch.tensor(a					,						device=a  )

										if is_buffer:
															__A	:						List[Any]       =				new_value
										else:
															__A	:						str       =				nn.Parameter(a					,						requires_grad=old_value.requires_grad  )
															__A	:						Optional[int]       =				new_value







def  _SCREAMING_SNAKE_CASE				(   a					,						a=None					,						a=None					,						a=None					,						a=False  )      ->      str:
					for name, module in model.named_children():
										if current_key_name is None:
															__A	:						Optional[Any]       =				[]
										current_key_name.append(a  )

										if (isinstance(a					,						nn.Linear  ) or isinstance(a					,						a  )) and name not in modules_to_not_convert:
															# Check if the current key is not in the `modules_to_not_convert`
															if not any(key in '.'.join(a  ) for key in modules_to_not_convert  ):
																				with init_empty_weights():
																									if isinstance(a					,						a  ):
																														__A    ,				__A	:						str       =				module.weight.shape
																									else:
																														__A	:						int       =				module.in_features
																														__A	:						List[Any]       =				module.out_features

																									if quantization_config.quantization_method() == "llm_int8":
																														__A	:						int       =				bnb.nn.LinearabitLt(
																														    a					,						a					,						module.bias is not None					,						has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight					,						threshold=quantization_config.llm_inta_threshold					,						)
																														__A	:						List[Any]       =				True
																									else:
																														if (
																														    quantization_config.llm_inta_skip_modules is not None
																														    and name in quantization_config.llm_inta_skip_modules
																														):
																																			pass
																														else:
																																			__A	:						Any       =				bnb.nn.Linearabit(
																																			    a					,						a					,						module.bias is not None					,						quantization_config.bnb_abit_compute_dtype					,						compress_statistics=quantization_config.bnb_abit_use_double_quant					,						quant_type=quantization_config.bnb_abit_quant_type					,						)
																																			__A	:						Union[str, Any]       =				True
                    # Store the module class in case we need to transpose the weight later
																									__A	:						str       =				type(a  )
																									# Force requires grad to False to avoid unexpected errors
																									model._modules[name].requires_grad_(a  )
										if len(list(module.children()  )  ) > 0:
															__A    ,				__A	:						str       =				_replace_with_bnb_linear(
															    a					,						a					,						a					,						a					,						has_been_replaced=a					,						)
										# Remove the last key for recursion
										current_key_name.pop(-1  )
					return model, has_been_replaced







def  _SCREAMING_SNAKE_CASE				(   a					,						a=None					,						a=None					,						a=None  )      ->      Any:
					__A	:						Optional[int]       =				['lm_head'] if modules_to_not_convert is None else modules_to_not_convert
					__A    ,				__A	:						Optional[Any]       =				_replace_with_bnb_linear(
					    a					,						a					,						a					,						a  )

					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.'
										    ' Please double check your model architecture, or submit an issue on github if you think this is'
										    ' a bug.'  )

					return model







def  _SCREAMING_SNAKE_CASE				(   *a					,						**a  )      ->      str:
					warnings.warn(
					    '`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead'					,						a					,						)
					return replace_with_bnb_linear(*a					,						**a  )







def  _SCREAMING_SNAKE_CASE				(   *a					,						**a  )      ->      Tuple:
					warnings.warn(
					    '`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead'					,						a					,						)
					return set_module_quantized_tensor_to_device(*a					,						**a  )







def  _SCREAMING_SNAKE_CASE				(   a  )      ->      Dict:
					__A	:						str       =				deepcopy(a  )  # this has 0 cost since it is done inside `init_empty_weights` context manager`
					tied_model.tie_weights()

					__A	:						Tuple       =				find_tied_parameters(a  )
					# For compatibility with Accelerate < 0.18
					if isinstance(a					,						a  ):
										__A	:						Optional[int]       =				sum(list(tied_params.values()  )					,						[]  ) + list(tied_params.keys()  )
					else:
										__A	:						Dict       =				sum(a					,						[]  )
					__A	:						Optional[int]       =				len(a  ) > 0

					# Check if it is a base model
					__A	:						Dict       =				not hasattr(a					,						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	:						Tuple       =				list(model.named_children()  )
					__A	:						Optional[int]       =				[list_modules[-1][0]]

					# add last module together with tied weights
					__A	:						List[Any]       =				set(a  ) - set(a  )
					__A	:						int       =				list(set(a  )  ) + list(a  )

					# remove ".weight" from the keys
					__A	:						List[Any]       =				['.weight', '.bias']
					__A	:						int       =				[]
					for name in list_untouched:
										for name_to_remove in names_to_remove:
															if name_to_remove in name:
																				__A	:						int       =				name.replace(a					,						''  )
										filtered_module_names.append(a  )

					return filtered_module_names











from __future__ import annotations







def  _SCREAMING_SNAKE_CASE				(   a  )      ->      int:
					if not nums:
										return 0
					__A	:						Optional[int]       =				nums[0]
					__A	:						str       =				0
					for num in nums[1:]:
										__A    ,				__A	:						Tuple       =				(
										    max_excluding + num,
										    max(a					,						a  ),
										)
					return max(a					,						a  )


if __name__ == "__main__":
				import doctest

				doctest.testmod()




