"""simple docstring"""




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

__lowerCAmelCase    :							int													=						logging.get_logger(__name__)







def 							_UpperCAmelCase		(       lowerCamelCase__			,  lowerCamelCase__			,  lowerCamelCase__			,  lowerCamelCase__=None			,  lowerCamelCase__=None     ):





		"""simple docstring"""




		if "." in tensor_name:
				lowerCAmelCase__        =   tensor_name.split("""."""     )
				for split in splits[:-1]:
						lowerCAmelCase__        =   getattr(lowerCamelCase__			,  lowerCamelCase__     )
						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(lowerCamelCase__			,  lowerCamelCase__     )

		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(lowerCamelCase__     )
						elif isinstance(lowerCamelCase__			,  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(lowerCamelCase__			,  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			,  lowerCamelCase__     ) and fpaa_statistics is None:
								lowerCAmelCase__        =   new_value.T

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

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

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

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







def 							_UpperCAmelCase		(       lowerCamelCase__			,  lowerCamelCase__=None			,  lowerCamelCase__=None			,  lowerCamelCase__=None			,  lowerCamelCase__=False     ):





		"""simple docstring"""




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

				if (isinstance(lowerCamelCase__			,  nn.Linear     ) or isinstance(lowerCamelCase__			,  lowerCamelCase__     )) 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(lowerCamelCase__     ) for key in modules_to_not_convert     ):
								with init_empty_weights():
										if isinstance(lowerCamelCase__			,  lowerCamelCase__     ):
												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(
												    lowerCamelCase__			,  lowerCamelCase__			,  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(
														    lowerCamelCase__			,  lowerCamelCase__			,  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(lowerCamelCase__     )
										# Force requires grad to False to avoid unexpected errors
										model._modules[name].requires_grad_(lowerCamelCase__     )
				if len(list(module.children()     )     ) > 0:
						lowerCAmelCase__   ,					lowerCAmelCase__        =   _replace_with_bnb_linear(
						    lowerCamelCase__			,  lowerCamelCase__			,  lowerCamelCase__			,  lowerCamelCase__			,  has_been_replaced=lowerCamelCase__			,  )
				# Remove the last key for recursion
				current_key_name.pop(-1     )
		return model, has_been_replaced







def 							_UpperCAmelCase		(       lowerCamelCase__			,  lowerCamelCase__=None			,  lowerCamelCase__=None			,  lowerCamelCase__=None     ):





		"""simple docstring"""




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

		return model







def 							_UpperCAmelCase		(       *lowerCamelCase__			,  **lowerCamelCase__     ):





		"""simple docstring"""




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







def 							_UpperCAmelCase		(       *lowerCamelCase__			,  **lowerCamelCase__     ):





		"""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"""			,  lowerCamelCase__			,  )
		return set_module_quantized_tensor_to_device(*lowerCamelCase__			,  **lowerCamelCase__     )







def 							_UpperCAmelCase		(       lowerCamelCase__     ):





		"""simple docstring"""




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

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

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

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

		# 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(lowerCamelCase__			,  """"""     )
				filtered_module_names.append(lowerCamelCase__     )

		return filtered_module_names





"""simple docstring"""




from __future__ import annotations

from math import gcd







def 							_UpperCAmelCase		(       lowerCamelCase__			,  lowerCamelCase__ = 2			,  lowerCamelCase__ = 1			,  lowerCamelCase__ = 3			,  ):





		"""simple docstring"""




		if num < 2:
				raise ValueError("""The input value cannot be less than 2"""     )

		# Because of the relationship between ``f(f(x))`` and ``f(x)``, this
		# algorithm struggles to find factors that are divisible by two.
		# As a workaround, we specifically check for two and even inputs.
		#   See: https://math.stackexchange.com/a/2856214/165820
		if num > 2 and num % 2 == 0:
				return 2

		# Pollard's Rho algorithm requires a function that returns pseudorandom
		# values between 0 <= X < ``num``.  It doesn't need to be random in the
		# sense that the output value is cryptographically secure or difficult
		# to calculate, it only needs to be random in the sense that all output
		# values should be equally likely to appear.
		# For this reason, Pollard suggested using ``f(x) = (x**2 - 1) % num``
		# However, the success of Pollard's algorithm isn't guaranteed and is
		# determined in part by the initial seed and the chosen random function.
		# To make retries easier, we will instead use ``f(x) = (x**2 + C) % num``
		# where ``C`` is a value that we can modify between each attempt.
		def rand_fn(lowerCamelCase__			,  lowerCamelCase__			,  lowerCamelCase__     ) -> int:
				return (pow(lowerCamelCase__			,  2     ) + step) % modulus

		for _ in range(lowerCamelCase__     ):
				# These track the position within the cycle detection logic.
				lowerCAmelCase__        =   seed
				lowerCAmelCase__        =   seed

				while True:
						# At each iteration, the tortoise moves one step and the hare moves two.
						lowerCAmelCase__        =   rand_fn(lowerCamelCase__			,  lowerCamelCase__			,  lowerCamelCase__     )
						lowerCAmelCase__        =   rand_fn(lowerCamelCase__			,  lowerCamelCase__			,  lowerCamelCase__     )
						lowerCAmelCase__        =   rand_fn(lowerCamelCase__			,  lowerCamelCase__			,  lowerCamelCase__     )

						# At some point both the tortoise and the hare will enter a cycle whose
						# length ``p`` is a divisor of ``num``.  Once in that cycle, at some point
						# the tortoise and hare will end up on the same value modulo ``p``.
						# We can detect when this happens because the position difference between
						# the tortoise and the hare will share a common divisor with ``num``.
						lowerCAmelCase__        =   gcd(hare - tortoise			,  lowerCamelCase__     )

						if divisor == 1:
								# No common divisor yet, just keep searching.
								continue
						else:
								# We found a common divisor!
								if divisor == num:
										# Unfortunately, the divisor is ``num`` itself and is useless.
										break
								else:
										# The divisor is a nontrivial factor of ``num``!
										return divisor

        # If we made it here, then this attempt failed.
        # We need to pick a new starting seed for the tortoise and hare
        # in addition to a new step value for the random function.
        # To keep this example implementation deterministic, the
        # new values will be generated based on currently available
        # values instead of using something like ``random.randint``.

        # We can use the hare's position as the new seed.
        # This is actually what Richard Brent's the "optimized" variant does.
				lowerCAmelCase__        =   hare

				# The new step value for the random function can just be incremented.
				# At first the results will be similar to what the old function would
				# have produced, but the value will quickly diverge after a bit.
				step += 1

		# We haven't found a divisor within the requested number of attempts.
		# We were unlucky or ``num`` itself is actually prime.
		return None


if __name__ == "__main__":
			import argparse

			__lowerCAmelCase    :							Union[str, Any]													=						argparse.ArgumentParser()
			parser.add_argument(
			    "num",
			    type=int,
			    help="The value to find a divisor of",
			)
			parser.add_argument(
			    "--attempts",
			    type=int,
			    default=3,
			    help="The number of attempts before giving up",
			)
			__lowerCAmelCase    :							List[str]													=						parser.parse_args()

			__lowerCAmelCase    :							Dict													=						pollard_rho(args.num, attempts=args.attempts)
			if divisor is None:
						print(F"{args.num} is probably prime")
			else:
						__lowerCAmelCase    :							List[str]													=						args.num // divisor
						print(F"{args.num} = {divisor} * {quotient}")




