



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





					"""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 		_UpperCAmelCase				(      snake_case	,						snake_case=None	,						snake_case=None	,						snake_case=None	,						snake_case=False			):





					"""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 		_UpperCAmelCase				(      snake_case	,						snake_case=None	,						snake_case=None	,						snake_case=None			):





					"""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 		_UpperCAmelCase				(      *snake_case	,						**snake_case			):





					"""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 		_UpperCAmelCase				(      *snake_case	,						**snake_case			):





					"""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 		_UpperCAmelCase				(      snake_case			):





					"""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








"""simple docstring"""






def      snake_case__   (		):
			"""simple docstring"""
			return [list(range(1000 - i							,		-1000 - i							,		-1	)	) for i in range(1000	)]


_lowercase : str      						=						generate_large_matrix()
_lowercase : str      						=						(
    [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]],
    [[3, 2], [1, 0]],
    [[7, 7, 6]],
    [[7, 7, 6], [-1, -2, -3]],
    grid,
)






def      snake_case__   (		__lowerCamelCase				:    list[list[int]]	):
			"""simple docstring"""
			assert all(row == sorted(__lowerCamelCase							,		reverse=__lowerCamelCase	) for row in grid	)
			assert all(list(__lowerCamelCase	) == sorted(__lowerCamelCase							,		reverse=__lowerCamelCase	) for col in zip(*__lowerCamelCase	)	)






def      snake_case__   (		__lowerCamelCase				:    list[int]	):
			"""simple docstring"""
			lowerCamelCase__		:		int			=0
			lowerCamelCase__		:		Optional[int]			=len(__lowerCamelCase	) - 1

			# Edge cases such as no values or all numbers are negative.
			if not array or array[0] < 0:
						return 0

			while right + 1 > left:
						lowerCamelCase__		:		List[str]			=(left + right) // 2
						lowerCamelCase__		:		Union[str, Any]			=array[mid]

						# Num must be negative and the index must be greater than or equal to 0.
						if num < 0 and array[mid - 1] >= 0:
									return mid

						if num >= 0:
									lowerCamelCase__		:		Union[str, Any]			=mid + 1
						else:
									lowerCamelCase__		:		Dict			=mid - 1
    # No negative numbers so return the last index of the array + 1 which is the length.
			return len(__lowerCamelCase	)






def      snake_case__   (		__lowerCamelCase				:    list[list[int]]	):
			"""simple docstring"""
			lowerCamelCase__		:		Union[str, Any]			=0
			lowerCamelCase__		:		str			=len(grid[0]	)

			for i in range(len(__lowerCamelCase	)	):
						lowerCamelCase__		:		Any			=find_negative_index(grid[i][:bound]	)
						total += bound
			return (len(__lowerCamelCase	) * len(grid[0]	)) - total






def      snake_case__   (		__lowerCamelCase				:    list[list[int]]	):
			"""simple docstring"""
			return len([number for row in grid for number in row if number < 0]	)






def      snake_case__   (		__lowerCamelCase				:    list[list[int]]	):
			"""simple docstring"""
			lowerCamelCase__		:		Tuple			=0
			for row in grid:
						for i, number in enumerate(__lowerCamelCase	):
									if number < 0:
												total += len(__lowerCamelCase	) - i
												break
			return total






def      snake_case__   (		):
			"""simple docstring"""
			from timeit import timeit

			print('''Running benchmarks'''	)
			lowerCamelCase__		:		List[str]			=(
			    '''from __main__ import count_negatives_binary_search, '''
			    '''count_negatives_brute_force, count_negatives_brute_force_with_break, grid'''
			)
			for func in (
			    "count_negatives_binary_search",  # took 0.7727 seconds
			    "count_negatives_brute_force_with_break",  # took 4.6505 seconds
			    "count_negatives_brute_force",  # took 12.8160 seconds
			):
						lowerCamelCase__		:		Union[str, Any]			=timeit(f'''{func}(grid=grid)'''							,		setup=__lowerCamelCase							,		number=500	)
						print(f'''{func}() took {time:0.4f} seconds'''	)


if __name__ == "__main__":
		import doctest

		doctest.testmod()
		benchmark()




