





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

_a						=   logging.get_logger(__name__)





def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case ,__snake_case=None ,__snake_case=None							)       ->   List[str]:







	'''simple docstring'''







	if "." in tensor_name:
		lowerCamelCase__              =	tensor_name.split('''.'''							)
		for split in splits[:-1]:
			lowerCamelCase__              =	getattr(__snake_case ,__snake_case							)
			if new_module is None:
				raise ValueError(F'{module} has no attribute {split}.'							)
			lowerCamelCase__              =	new_module
		lowerCamelCase__              =	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}.'							)
	lowerCamelCase__              =	tensor_name in module._buffers
	lowerCamelCase__              =	getattr(__snake_case ,__snake_case							)

	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}.'							)

	lowerCamelCase__              =	False
	lowerCamelCase__              =	False
	if is_buffer or not is_bitsandbytes_available():
		lowerCamelCase__              =	False
		lowerCamelCase__              =	False
	else:
		lowerCamelCase__              =	hasattr(bnb.nn ,'''Params4bit'''							) and isinstance(module._parameters[tensor_name] ,bnb.nn.Paramsabit							)
		lowerCamelCase__              =	isinstance(module._parameters[tensor_name] ,bnb.nn.IntaParams							)

	if is_abit or is_abit:
		lowerCamelCase__              =	module._parameters[tensor_name]
		if param.device.type != "cuda":
			if value is None:
				lowerCamelCase__              =	old_value.to(__snake_case							)
			elif isinstance(__snake_case ,torch.Tensor							):
				lowerCamelCase__              =	value.to('''cpu'''							)
				if value.dtype == torch.inta:
					lowerCamelCase__              =	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:
				lowerCamelCase__              =	torch.tensor(__snake_case ,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 ,__snake_case							) and fpaa_statistics is None:
				lowerCamelCase__              =	new_value.T

			lowerCamelCase__              =	old_value.__dict__
			if is_abit:
				lowerCamelCase__              =	bnb.nn.IntaParams(__snake_case ,requires_grad=__snake_case ,**__snake_case							).to(__snake_case							)
			elif is_abit:
				lowerCamelCase__              =	bnb.nn.Paramsabit(__snake_case ,requires_grad=__snake_case ,**__snake_case							).to(__snake_case							)

			lowerCamelCase__              =	new_value
			if fpaa_statistics is not None:
				setattr(module.weight ,'''SCB''' ,fpaa_statistics.to(__snake_case							)							)

	else:
		if value is None:
			lowerCamelCase__              =	old_value.to(__snake_case							)
		elif isinstance(__snake_case ,torch.Tensor							):
			lowerCamelCase__              =	value.to(__snake_case							)
		else:
			lowerCamelCase__              =	torch.tensor(__snake_case ,device=__snake_case							)

		if is_buffer:
			lowerCamelCase__              =	new_value
		else:
			lowerCamelCase__              =	nn.Parameter(__snake_case ,requires_grad=old_value.requires_grad							)
			lowerCamelCase__              =	new_value





def lowerCAmelCase__(__snake_case ,__snake_case=None ,__snake_case=None ,__snake_case=None ,__snake_case=False							)       ->   Tuple:







	'''simple docstring'''







	for name, module in model.named_children():
		if current_key_name is None:
			lowerCamelCase__              =	[]
		current_key_name.append(__snake_case							)

		if (isinstance(__snake_case ,nn.Linear							) or isinstance(__snake_case ,__snake_case							)) 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(__snake_case							) for key in modules_to_not_convert							):
				with init_empty_weights():
					if isinstance(__snake_case ,__snake_case							):
						lowerCamelCase__       ,			lowerCamelCase__              =	module.weight.shape
					else:
						lowerCamelCase__              =	module.in_features
						lowerCamelCase__              =	module.out_features

					if quantization_config.quantization_method() == "llm_int8":
						lowerCamelCase__              =	bnb.nn.LinearabitLt(
						    __snake_case ,__snake_case ,module.bias is not None ,has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight ,threshold=quantization_config.llm_inta_threshold ,)
						lowerCamelCase__              =	True
					else:
						if (
						    quantization_config.llm_inta_skip_modules is not None
						    and name in quantization_config.llm_inta_skip_modules
						):
							pass
						else:
							lowerCamelCase__              =	bnb.nn.Linearabit(
							    __snake_case ,__snake_case ,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 ,)
							lowerCamelCase__              =	True
                    # Store the module class in case we need to transpose the weight later
					lowerCamelCase__              =	type(__snake_case							)
					# Force requires grad to False to avoid unexpected errors
					model._modules[name].requires_grad_(__snake_case							)
		if len(list(module.children()							)							) > 0:
			lowerCamelCase__       ,			lowerCamelCase__              =	_replace_with_bnb_linear(
			    __snake_case ,__snake_case ,__snake_case ,__snake_case ,has_been_replaced=__snake_case ,)
		# Remove the last key for recursion
		current_key_name.pop(-1							)
	return model, has_been_replaced





def lowerCAmelCase__(__snake_case ,__snake_case=None ,__snake_case=None ,__snake_case=None							)       ->   Dict:







	'''simple docstring'''







	lowerCamelCase__              =	['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert
	lowerCamelCase__       ,			lowerCamelCase__              =	_replace_with_bnb_linear(
	    __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.'''
		    ''' Please double check your model architecture, or submit an issue on github if you think this is'''
		    ''' a bug.'''							)

	return model





def lowerCAmelCase__(*__snake_case ,**__snake_case							)       ->   Optional[int]:







	'''simple docstring'''







	warnings.warn(
	    '''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead''' ,__snake_case ,)
	return replace_with_bnb_linear(*__snake_case ,**__snake_case							)





def lowerCAmelCase__(*__snake_case ,**__snake_case							)       ->   Optional[int]:







	'''simple docstring'''







	warnings.warn(
	    '''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead''' ,__snake_case ,)
	return set_module_quantized_tensor_to_device(*__snake_case ,**__snake_case							)





def lowerCAmelCase__(__snake_case							)       ->   Optional[int]:







	'''simple docstring'''







	lowerCamelCase__              =	deepcopy(__snake_case							)  # this has 0 cost since it is done inside `init_empty_weights` context manager`
	tied_model.tie_weights()

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

	# Check if it is a base model
	lowerCamelCase__              =	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
	lowerCamelCase__              =	list(model.named_children()							)
	lowerCamelCase__              =	[list_modules[-1][0]]

	# add last module together with tied weights
	lowerCamelCase__              =	set(__snake_case							) - set(__snake_case							)
	lowerCamelCase__              =	list(set(__snake_case							)							) + list(__snake_case							)

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

	return filtered_module_names










import timeit

import numpy as np

import datasets
from datasets.arrow_writer import ArrowWriter
from datasets.features.features import _ArrayXD





def lowerCAmelCase__(__snake_case							)       ->   Union[str, Any]:







	'''simple docstring'''







	def wrapper(*__snake_case ,**__snake_case							):
		lowerCamelCase__              =	timeit.default_timer()
		lowerCamelCase__              =	func(*__snake_case ,**__snake_case							)
		lowerCamelCase__              =	timeit.default_timer() - starttime
		return delta

	lowerCamelCase__              =	func.__name__

	return wrapper





def lowerCAmelCase__(__snake_case ,__snake_case=100 ,__snake_case=None							)       ->   Optional[Any]:







	'''simple docstring'''







	lowerCamelCase__              =	[]
	lowerCamelCase__              =	seq_shapes or {}
	for i in range(__snake_case							):
		lowerCamelCase__              =	{}
		for col_id, (k, v) in enumerate(features.items()							):
			if isinstance(__snake_case ,_ArrayXD							):
				lowerCamelCase__              =	np.random.rand(*v.shape							).astype(v.dtype							)
			elif isinstance(__snake_case ,datasets.Value							):
				if v.dtype == "string":
					lowerCamelCase__              =	'''The small grey turtle was surprisingly fast when challenged.'''
				else:
					lowerCamelCase__              =	np.random.randint(10 ,size=1							).astype(v.dtype							).item()
			elif isinstance(__snake_case ,datasets.Sequence							):
				while isinstance(__snake_case ,datasets.Sequence							):
					lowerCamelCase__              =	v.feature
				lowerCamelCase__              =	seq_shapes[k]
				lowerCamelCase__              =	np.random.rand(*__snake_case							).astype(v.dtype							)
			lowerCamelCase__              =	data

		dummy_data.append((i, example)							)

	return dummy_data





def lowerCAmelCase__(__snake_case ,__snake_case ,__snake_case=100 ,__snake_case=None							)       ->   str:







	'''simple docstring'''







	lowerCamelCase__              =	generate_examples(__snake_case ,num_examples=__snake_case ,seq_shapes=__snake_case							)

	with ArrowWriter(features=__snake_case ,path=__snake_case							) as writer:
		for key, record in dummy_data:
			lowerCamelCase__              =	features.encode_example(__snake_case							)
			writer.write(__snake_case							)

		lowerCamelCase__       ,			lowerCamelCase__              =	writer.finalize()

	if not num_final_examples == num_examples:
		raise ValueError(
		    F'Error writing the dataset, wrote {num_final_examples} examples but should have written {num_examples}.'							)

	lowerCamelCase__              =	datasets.Dataset.from_file(filename=__snake_case ,info=datasets.DatasetInfo(features=__snake_case							)							)

	return dataset



