

from math import sqrt







def 			A_      (    _UpperCAmelCase    ):
						assert isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ) and (
						    number >= 0
						), "'number' must been an int and positive"

						SCREAMING_SNAKE_CASE_: Optional[int]  		=       True

						# 0 and 1 are none primes.
						if number <= 1:
												SCREAMING_SNAKE_CASE_: List[Any]  		=       False

						for divisor in range(2				,	int(round(sqrt(_UpperCAmelCase    )    )    ) + 1    ):
												# if 'number' divisible by 'divisor' then sets 'status'
												# of false and break up the loop.
												if number % divisor == 0:
																		SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       False
																		break

    # precondition
						assert isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ), "'status' must been from type bool"

						return status







def 			A_      (    _UpperCAmelCase    ):
						assert isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ) and (n > 2), "'N' must been an int and > 2"

						# beginList: contains all natural numbers from 2 up to N
						SCREAMING_SNAKE_CASE_: List[str]  		=       list(range(2				,	n + 1    )    )

						SCREAMING_SNAKE_CASE_: Tuple  		=       []  # this list will be returns.

						# actual sieve of erathostenes
						for i in range(len(_UpperCAmelCase    )    ):
												for j in range(i + 1				,	len(_UpperCAmelCase    )    ):
																		if (begin_list[i] != 0) and (begin_list[j] % begin_list[i] == 0):
																								SCREAMING_SNAKE_CASE_: List[Any]  		=       0

    # filters actual prime numbers.
						SCREAMING_SNAKE_CASE_: str  		=       [x for x in begin_list if x != 0]

						# precondition
						assert isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ), "'ans' must been from type list"

						return ans







def 			A_      (    _UpperCAmelCase    ):
						assert isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ) and (n > 2), "'N' must been an int and > 2"

						SCREAMING_SNAKE_CASE_: List[str]  		=       []

						# iterates over all numbers between 2 up to N+1
						# if a number is prime then appends to list 'ans'
						for number in range(2				,	n + 1    ):
												if is_prime(_UpperCAmelCase    ):
																		ans.append(_UpperCAmelCase    )

    # precondition
						assert isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ), "'ans' must been from type list"

						return ans







def 			A_      (    _UpperCAmelCase    ):
						assert isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ) and number >= 0, "'number' must been an int and >= 0"

						SCREAMING_SNAKE_CASE_: Dict  		=       []  # this list will be returns of the function.

						# potential prime number factors.

						SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       2

						SCREAMING_SNAKE_CASE_: List[str]  		=       number

						if number == 0 or number == 1:
												ans.append(_UpperCAmelCase    )

						# if 'number' not prime then builds the prime factorization of 'number'
						elif not is_prime(_UpperCAmelCase    ):
												while quotient != 1:
																		if is_prime(_UpperCAmelCase    ) and (quotient % factor == 0):
																								ans.append(_UpperCAmelCase    )
																								quotient /= factor
																		else:
																								factor += 1

						else:
												ans.append(_UpperCAmelCase    )

						# precondition
						assert isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ), "'ans' must been from type list"

						return ans







def 			A_      (    _UpperCAmelCase    ):
						assert isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ) and (
						    number >= 0
						), "'number' bust been an int and >= 0"

						SCREAMING_SNAKE_CASE_: int  		=       0

						# prime factorization of 'number'
						SCREAMING_SNAKE_CASE_: List[Any]  		=       prime_factorization(_UpperCAmelCase    )

						SCREAMING_SNAKE_CASE_: Tuple  		=       max(_UpperCAmelCase    )

						# precondition
						assert isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ), "'ans' must been from type int"

						return ans







def 			A_      (    _UpperCAmelCase    ):
						assert isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ) and (
						    number >= 0
						), "'number' bust been an int and >= 0"

						SCREAMING_SNAKE_CASE_: Optional[Any]  		=       0

						# prime factorization of 'number'
						SCREAMING_SNAKE_CASE_: Dict  		=       prime_factorization(_UpperCAmelCase    )

						SCREAMING_SNAKE_CASE_: Dict  		=       min(_UpperCAmelCase    )

						# precondition
						assert isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ), "'ans' must been from type int"

						return ans







def 			A_      (    _UpperCAmelCase    ):
						assert isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ), "'number' must been an int"
						assert isinstance(number % 2 == 0				,	_UpperCAmelCase    ), "compare bust been from type bool"

						return number % 2 == 0







def 			A_      (    _UpperCAmelCase    ):
						assert isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ), "'number' must been an int"
						assert isinstance(number % 2 != 0				,	_UpperCAmelCase    ), "compare bust been from type bool"

						return number % 2 != 0







def 			A_      (    _UpperCAmelCase    ):
						assert (
						    isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ) and (number > 2) and is_even(_UpperCAmelCase    )
						), "'number' must been an int, even and > 2"

						SCREAMING_SNAKE_CASE_: Dict  		=       []  # this list will returned

						# creates a list of prime numbers between 2 up to 'number'
						SCREAMING_SNAKE_CASE_: Optional[int]  		=       get_prime_numbers(_UpperCAmelCase    )
						SCREAMING_SNAKE_CASE_: str  		=       len(_UpperCAmelCase    )

						# run variable for while-loops.
						SCREAMING_SNAKE_CASE_: Any  		=       0
						SCREAMING_SNAKE_CASE_: List[str]  		=       None

						# exit variable. for break up the loops
						SCREAMING_SNAKE_CASE_: int  		=       True

						while i < len_pn and loop:
												SCREAMING_SNAKE_CASE_: str  		=       i + 1

												while j < len_pn and loop:
																		if prime_numbers[i] + prime_numbers[j] == number:
																								SCREAMING_SNAKE_CASE_: Any  		=       False
																								ans.append(prime_numbers[i]    )
																								ans.append(prime_numbers[j]    )

																		j += 1

												i += 1

						# precondition
						assert (
						    isinstance(_UpperCAmelCase				,	_UpperCAmelCase    )
						    and (len(_UpperCAmelCase    ) == 2)
						    and (ans[0] + ans[1] == number)
						    and is_prime(ans[0]    )
						    and is_prime(ans[1]    )
						), "'ans' must contains two primes. And sum of elements must been eq 'number'"

						return ans







def 			A_      (    _UpperCAmelCase				,	_UpperCAmelCase    ):
						assert (
						    isinstance(_UpperCAmelCase				,	_UpperCAmelCase    )
						    and isinstance(_UpperCAmelCase				,	_UpperCAmelCase    )
						    and (numbera >= 0)
						    and (numbera >= 0)
						), "'number1' and 'number2' must been positive integer."

						SCREAMING_SNAKE_CASE_: Dict  		=       0

						while numbera != 0:
												SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       numbera % numbera
												SCREAMING_SNAKE_CASE_: List[str]  		=       numbera
												SCREAMING_SNAKE_CASE_: Tuple  		=       rest

						# precondition
						assert isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ) and (
						    numbera >= 0
						), "'number' must been from type int and positive"

						return numbera







def 			A_      (    _UpperCAmelCase				,	_UpperCAmelCase    ):
						assert (
						    isinstance(_UpperCAmelCase				,	_UpperCAmelCase    )
						    and isinstance(_UpperCAmelCase				,	_UpperCAmelCase    )
						    and (numbera >= 1)
						    and (numbera >= 1)
						), "'number1' and 'number2' must been positive integer."

						SCREAMING_SNAKE_CASE_: str  		=       1  # actual answer that will be return.

						# for kgV (x,1)
						if numbera > 1 and numbera > 1:
												# builds the prime factorization of 'number1' and 'number2'
												SCREAMING_SNAKE_CASE_: Optional[int]  		=       prime_factorization(_UpperCAmelCase    )
												SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       prime_factorization(_UpperCAmelCase    )

						elif numbera == 1 or numbera == 1:
												SCREAMING_SNAKE_CASE_: int  		=       []
												SCREAMING_SNAKE_CASE_: Any  		=       []
												SCREAMING_SNAKE_CASE_: str  		=       max(_UpperCAmelCase				,	_UpperCAmelCase    )

						SCREAMING_SNAKE_CASE_: str  		=       0
						SCREAMING_SNAKE_CASE_: str  		=       0

						SCREAMING_SNAKE_CASE_: Any  		=       []  # captured numbers int both 'primeFac1' and 'primeFac2'

						# iterates through primeFac1
						for n in prime_fac_a:
												if n not in done:
																		if n in prime_fac_a:
																								SCREAMING_SNAKE_CASE_: Any  		=       prime_fac_a.count(_UpperCAmelCase    )
																								SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       prime_fac_a.count(_UpperCAmelCase    )

																								for _ in range(max(_UpperCAmelCase				,	_UpperCAmelCase    )    ):
																														ans *= n

																		else:
																								SCREAMING_SNAKE_CASE_: int  		=       prime_fac_a.count(_UpperCAmelCase    )

																								for _ in range(_UpperCAmelCase    ):
																														ans *= n

																		done.append(_UpperCAmelCase    )

    # iterates through primeFac2
						for n in prime_fac_a:
												if n not in done:
																		SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       prime_fac_a.count(_UpperCAmelCase    )

																		for _ in range(_UpperCAmelCase    ):
																								ans *= n

																		done.append(_UpperCAmelCase    )

    # precondition
						assert isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ) and (
						    ans >= 0
						), "'ans' must been from type int and positive"

						return ans







def 			A_      (    _UpperCAmelCase    ):
						assert isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ) and (n >= 0), "'number' must been a positive int"

						SCREAMING_SNAKE_CASE_: List[str]  		=       0
						SCREAMING_SNAKE_CASE_: Any  		=       2  # this variable holds the answer

						while index < n:
												index += 1

												ans += 1  # counts to the next number

												# if ans not prime then
												# runs to the next prime number.
												while not is_prime(_UpperCAmelCase    ):
																		ans += 1

    # precondition
						assert isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ) and is_prime(
						    _UpperCAmelCase    ), "'ans' must been a prime number and from type int"

						return ans







def 			A_      (    _UpperCAmelCase				,	_UpperCAmelCase    ):
						assert (
						    is_prime(_UpperCAmelCase    ) and is_prime(_UpperCAmelCase    ) and (p_number_a < p_number_a)
						), "The arguments must been prime numbers and 'pNumber1' < 'pNumber2'"

						SCREAMING_SNAKE_CASE_: List[str]  		=       p_number_a + 1  # jump to the next number

						SCREAMING_SNAKE_CASE_: int  		=       []  # this list will be returns.

						# if number is not prime then
						# fetch the next prime number.
						while not is_prime(_UpperCAmelCase    ):
												number += 1

						while number < p_number_a:
												ans.append(_UpperCAmelCase    )

												number += 1

												# fetch the next prime number.
												while not is_prime(_UpperCAmelCase    ):
																		number += 1

    # precondition
						assert (
						    isinstance(_UpperCAmelCase				,	_UpperCAmelCase    )
						    and ans[0] != p_number_a
						    and ans[len(_UpperCAmelCase    ) - 1] != p_number_a
						), "'ans' must been a list without the arguments"

						# 'ans' contains not 'pNumber1' and 'pNumber2' !
						return ans







def 			A_      (    _UpperCAmelCase    ):
						assert isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ) and (n >= 1), "'n' must been int and >= 1"

						SCREAMING_SNAKE_CASE_: Optional[int]  		=       []  # will be returned.

						for divisor in range(1				,	n + 1    ):
												if n % divisor == 0:
																		ans.append(_UpperCAmelCase    )

    # precondition
						assert ans[0] == 1 and ans[len(_UpperCAmelCase    ) - 1] == n, "Error in function getDivisiors(...)"

						return ans







def 			A_      (    _UpperCAmelCase    ):
						assert isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ) and (
						    number > 1
						), "'number' must been an int and >= 1"

						SCREAMING_SNAKE_CASE_: Optional[Any]  		=       get_divisors(_UpperCAmelCase    )

						# precondition
						assert (
						    isinstance(_UpperCAmelCase				,	_UpperCAmelCase    )
						    and (divisors[0] == 1)
						    and (divisors[len(_UpperCAmelCase    ) - 1] == number)
						), "Error in help-function getDivisiors(...)"

						# summed all divisors up to 'number' (exclusive), hence [:-1]
						return sum(divisors[:-1]    ) == number







def 			A_      (    _UpperCAmelCase				,	_UpperCAmelCase    ):
						assert (
						    isinstance(_UpperCAmelCase				,	_UpperCAmelCase    )
						    and isinstance(_UpperCAmelCase				,	_UpperCAmelCase    )
						    and (denominator != 0)
						), "The arguments must been from type int and 'denominator' != 0"

						# build the greatest common divisor of numerator and denominator.
						SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       gcd(abs(_UpperCAmelCase    )				,	abs(_UpperCAmelCase    )    )

						# precondition
						assert (
						    isinstance(_UpperCAmelCase				,	_UpperCAmelCase    )
						    and (numerator % gcd_of_fraction == 0)
						    and (denominator % gcd_of_fraction == 0)
						), "Error in function gcd(...,...)"

						return (numerator // gcd_of_fraction, denominator // gcd_of_fraction)







def 			A_      (    _UpperCAmelCase    ):
						assert isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ) and (n >= 0), "'n' must been a int and >= 0"

						SCREAMING_SNAKE_CASE_: Dict  		=       1  # this will be return.

						for factor in range(1				,	n + 1    ):
												ans *= factor

						return ans







def 			A_      (    _UpperCAmelCase    ):
						assert isinstance(_UpperCAmelCase				,	_UpperCAmelCase    ) and (n >= 0), "'n' must been an int and >= 0"

						SCREAMING_SNAKE_CASE_: Optional[int]  		=       0
						SCREAMING_SNAKE_CASE_: Tuple  		=       1
						SCREAMING_SNAKE_CASE_: Any  		=       1  # this will be return

						for _ in range(n - 1    ):
												SCREAMING_SNAKE_CASE_: Optional[int]  		=       ans
												ans += fiba
												SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       tmp

						return ans







"""simple docstring"""




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






def      UpperCAmelCase    (		UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ = None				,			UpperCamelCase__ = None				,			UpperCamelCase__ = None				,			UpperCamelCase__ = None				,			UpperCamelCase__ = None				,			UpperCamelCase__ = False				,			):






							"""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(UpperCamelCase__				,			UpperCamelCase__ ) 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(UpperCamelCase__ )

							# add cpu modules to skip modules only for 4-bit modules
							if load_in_abit:
														bnb_quantization_config.skip_modules.extend(UpperCamelCase__ )
							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(UpperCamelCase__ )

							# compatibility with peft
							A__		   =							load_in_abit
							A__		   =							load_in_abit

							A__		   =							get_parameter_device(UpperCamelCase__ )
							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(UpperCamelCase__				,			UpperCamelCase__				,			modules_to_not_convert=UpperCamelCase__ )
														# 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(UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ )
																																			if param is not None:
																																										param.to(torch.floataa )
																					elif torch.is_floating_point(UpperCamelCase__ ):
																												param.to(UpperCamelCase__ )
														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(
																					    UpperCamelCase__				,			UpperCamelCase__				,			modules_to_not_convert=UpperCamelCase__ )

														A__		   =							get_quantized_model_device_map(
														    UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			max_memory=UpperCamelCase__				,			no_split_module_classes=UpperCamelCase__				,			)
														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(
														    UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			dtype=bnb_quantization_config.torch_dtype				,			offload_folder=UpperCamelCase__				,			offload_state_dict=UpperCamelCase__				,			keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules				,			offload_abit_bnb=load_in_abit and offload				,			)
														return dispatch_model(UpperCamelCase__				,			device_map=UpperCamelCase__				,			offload_dir=UpperCamelCase__ )






def      UpperCAmelCase    (		UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__=None				,			UpperCamelCase__=None				,			UpperCamelCase__=None ):






							"""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(UpperCamelCase__				,			UpperCamelCase__ ):
														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(
																					    UpperCamelCase__				,			low_zero=(device_map == 'balanced_low_0')				,			max_memory=UpperCamelCase__				,			**UpperCamelCase__				,			)

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

							if isinstance(UpperCamelCase__				,			UpperCamelCase__ ):
														# 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(
																																			    '\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      UpperCAmelCase    (		UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__=None				,			UpperCamelCase__=None ):






							"""simple docstring"""





							if modules_to_not_convert is None:
														A__		   =							[]

							A__   ,     A__		   =							_replace_with_bnb_layers(
							    UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ )
							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      UpperCAmelCase    (		UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__=None				,			UpperCamelCase__=None				,			):






							"""simple docstring"""





							A__		   =							False
							for name, module in model.named_children():
														if current_key_name is None:
																					A__		   =							[]
														current_key_name.append(UpperCamelCase__ )
														if isinstance(UpperCamelCase__				,			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(UpperCamelCase__ )
																					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=UpperCamelCase__				,			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_(UpperCamelCase__ )
																												setattr(UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ )
																												A__		   =							True
														if len(list(module.children() ) ) > 0:
																					A__   ,     A__		   =							_replace_with_bnb_layers(
																					    UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ )
																					A__		   =							has_been_replaced | _has_been_replaced
														# Remove the last key for recursion
														current_key_name.pop(-1 )
							return model, has_been_replaced






def      UpperCAmelCase    (		UpperCamelCase__ ):






							"""simple docstring"""





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

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

							# Check if it is a base model
							A__		   =							False
							if hasattr(UpperCamelCase__				,			'base_model_prefix' ):
														A__		   =							not hasattr(UpperCamelCase__				,			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(UpperCamelCase__ ) - set(UpperCamelCase__ )
							A__		   =							list(set(UpperCamelCase__ ) ) + list(UpperCamelCase__ )

							# 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(UpperCamelCase__				,			'' )
														filtered_module_names.append(UpperCamelCase__ )

							return filtered_module_names






def      UpperCAmelCase    (		UpperCamelCase__ ):






							"""simple docstring"""





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






def      UpperCAmelCase    (		UpperCamelCase__ ):






							"""simple docstring"""





							return next(parameter.parameters() ).device






def      UpperCAmelCase    (		UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__ ):






							"""simple docstring"""





							if fpaa_statistics is None:
														set_module_tensor_to_device(UpperCamelCase__				,			UpperCamelCase__				,			0				,			dtype=UpperCamelCase__				,			value=UpperCamelCase__ )
														A__		   =							param_name
														A__		   =							model
														if "." in tensor_name:
																					A__		   =							tensor_name.split('.' )
																					for split in splits[:-1]:
																												A__		   =							getattr(UpperCamelCase__				,			UpperCamelCase__ )
																												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]				,			UpperCamelCase__				,			UpperCamelCase__				,			index=UpperCamelCase__ )
														if hasattr(module._parameters[tensor_name]				,			'SCB' ):
																					offload_weight(
																					    module._parameters[tensor_name].SCB				,			param_name.replace('weight'				,			'SCB' )				,			UpperCamelCase__				,			index=UpperCamelCase__				,			)
							else:
														offload_weight(UpperCamelCase__				,			UpperCamelCase__				,			UpperCamelCase__				,			index=UpperCamelCase__ )
														offload_weight(UpperCamelCase__				,			param_name.replace('weight'				,			'SCB' )				,			UpperCamelCase__				,			index=UpperCamelCase__ )

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





