



'''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							:List[str]				    =					logging.getLogger(__name__)



def 	a			( lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__ = None						,      lowerCamelCase__ = None						,      lowerCamelCase__ = None						,      lowerCamelCase__ = None						,      lowerCamelCase__ = None						,      lowerCamelCase__ = False						,      ):
			'''simple docstring'''





			A_	:						str	=     bnb_quantization_config.load_in_abit
			A_	:						Optional[int]	=     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_	:						str	=     []
			# custom device map
			if isinstance(lowerCamelCase__						,      lowerCamelCase__    ) and len(device_map.keys()    ) > 1:
						A_	:						Dict	=     [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_	:						List[Any]	=     get_keys_to_not_convert(lowerCamelCase__    )

			# add cpu modules to skip modules only for 4-bit modules
			if load_in_abit:
						bnb_quantization_config.skip_modules.extend(lowerCamelCase__    )
			A_	:						int	=     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_	:						Optional[int]	=     []
			A_	:						int	=     bnb_quantization_config.keep_in_fpaa_modules
			modules_to_not_convert.extend(lowerCamelCase__    )

			# compatibility with peft
			A_	:						Dict	=     load_in_abit
			A_	:						Any	=     load_in_abit

			A_	:						Union[str, Any]	=     get_parameter_device(lowerCamelCase__    )
			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_	:						int	=     replace_with_bnb_layers(lowerCamelCase__						,      lowerCamelCase__						,      modules_to_not_convert=lowerCamelCase__    )
						# convert param to the right dtype
						A_	:						Tuple	=     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_	:						str	=     name.replace(""".weight"""						,      """"""    ).replace(""".bias"""						,      """"""    )
															A_	:						int	=     getattr(lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__    )
															if param is not None:
																		param.to(torch.floataa    )
									elif torch.is_floating_point(lowerCamelCase__    ):
												param.to(lowerCamelCase__    )
						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_	:						int	=     replace_with_bnb_layers(
									    lowerCamelCase__						,      lowerCamelCase__						,      modules_to_not_convert=lowerCamelCase__    )

						A_	:						List[Any]	=     get_quantized_model_device_map(
						    lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__						,      max_memory=lowerCamelCase__						,      no_split_module_classes=lowerCamelCase__						,      )
						if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
									A_	:						Dict	=     True

						A_	:						Tuple	=     any(x in list(device_map.values()    ) for x in ["""cpu""", """disk"""]    )

						load_checkpoint_in_model(
						    lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__						,      dtype=bnb_quantization_config.torch_dtype						,      offload_folder=lowerCamelCase__						,      offload_state_dict=lowerCamelCase__						,      keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules						,      offload_abit_bnb=load_in_abit and offload						,      )
						return dispatch_model(lowerCamelCase__						,      device_map=lowerCamelCase__						,      offload_dir=lowerCamelCase__    )



def 	a			( lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__=None						,      lowerCamelCase__=None						,      lowerCamelCase__=None    ):
			'''simple docstring'''





			if device_map is None:
						if torch.cuda.is_available():
									A_	:						str	=     {"""""": 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(lowerCamelCase__						,      lowerCamelCase__    ):
						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_	:						Any	=     {}
						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_	:						List[Any]	=     {}
						A_	:						List[Any]	=     special_dtypes
						A_	:						Optional[Any]	=     no_split_module_classes
						A_	:						List[str]	=     bnb_quantization_config.target_dtype

						# get max_memory for each device.
						if device_map != "sequential":
									A_	:						List[str]	=     get_balanced_memory(
									    lowerCamelCase__						,      low_zero=(device_map == """balanced_low_0""")						,      max_memory=lowerCamelCase__						,      **lowerCamelCase__						,      )

						A_	:						Optional[Any]	=     max_memory
						A_	:						Union[str, Any]	=     infer_auto_device_map(lowerCamelCase__						,      **lowerCamelCase__    )

			if isinstance(lowerCamelCase__						,      lowerCamelCase__    ):
						# check if don't have any quantized module on the cpu
						A_	:						List[Any]	=     bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules

						A_	:						List[Any]	=     {
						    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(
															    """
                        Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit
                        the quantized model. If you want to dispatch the model on the CPU or the disk while keeping
                        these modules in `torch_dtype`, you need to pass a custom `device_map` to
                        `load_and_quantize_model`. Check
                        https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk
                        for more details.
                        """    )
												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 	a			( lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__=None						,      lowerCamelCase__=None    ):
			'''simple docstring'''





			if modules_to_not_convert is None:
						A_	:						List[Any]	=     []

			A_,    A_	:						Optional[Any]	=     _replace_with_bnb_layers(
			    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."""
						    """ 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 	a			( lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__=None						,      lowerCamelCase__=None						,      ):
			'''simple docstring'''





			A_	:						Union[str, Any]	=     False
			for name, module in model.named_children():
						if current_key_name is None:
									A_	:						List[str]	=     []
						current_key_name.append(lowerCamelCase__    )
						if isinstance(lowerCamelCase__						,      nn.Linear    ) and name not in modules_to_not_convert:
									# Check if the current key is not in the `modules_to_not_convert`
									A_	:						Union[str, Any]	=     """.""".join(lowerCamelCase__    )
									A_	:						str	=     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_	:						Dict	=     False
															break
									if proceed:
												# Load bnb module with empty weight and replace ``nn.Linear` module
												if bnb_quantization_config.load_in_abit:
															A_	:						str	=     bnb.nn.LinearabitLt(
															    module.in_features						,      module.out_features						,      module.bias is not None						,      has_fpaa_weights=lowerCamelCase__						,      threshold=bnb_quantization_config.llm_inta_threshold						,      )
												elif bnb_quantization_config.load_in_abit:
															A_	:						List[Any]	=     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_	:						Tuple	=     module.weight.data
												if module.bias is not None:
															A_	:						List[Any]	=     module.bias.data
												bnb_module.requires_grad_(lowerCamelCase__    )
												setattr(lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__    )
												A_	:						List[str]	=     True
						if len(list(module.children()    )    ) > 0:
									A_,    A_	:						int	=     _replace_with_bnb_layers(
									    lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__    )
									A_	:						Optional[Any]	=     has_been_replaced | _has_been_replaced
						# Remove the last key for recursion
						current_key_name.pop(-1    )
			return model, has_been_replaced



def 	a			( lowerCamelCase__    ):
			'''simple docstring'''





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

			A_	:						List[Any]	=     find_tied_parameters(lowerCamelCase__    )
			# For compatibility with Accelerate < 0.18
			if isinstance(lowerCamelCase__						,      lowerCamelCase__    ):
						A_	:						Optional[int]	=     sum(list(tied_params.values()    )						,      []    ) + list(tied_params.keys()    )
			else:
						A_	:						Union[str, Any]	=     sum(lowerCamelCase__						,      []    )
			A_	:						Dict	=     len(lowerCamelCase__    ) > 0

			# Check if it is a base model
			A_	:						List[Any]	=     False
			if hasattr(lowerCamelCase__						,      """base_model_prefix"""    ):
						A_	:						Dict	=     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
			A_	:						List[Any]	=     list(model.named_children()    )
			A_	:						Optional[Any]	=     [list_modules[-1][0]]

			# add last module together with tied weights
			A_	:						Union[str, Any]	=     set(lowerCamelCase__    ) - set(lowerCamelCase__    )
			A_	:						Dict	=     list(set(lowerCamelCase__    )    ) + list(lowerCamelCase__    )

			# remove ".weight" from the keys
			A_	:						Optional[int]	=     [""".weight""", """.bias"""]
			A_	:						Any	=     []
			for name in list_untouched:
						for name_to_remove in names_to_remove:
									if name_to_remove in name:
												A_	:						str	=     name.replace(lowerCamelCase__						,      """"""    )
						filtered_module_names.append(lowerCamelCase__    )

			return filtered_module_names



def 	a			( lowerCamelCase__    ):
			'''simple docstring'''





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



def 	a			( lowerCamelCase__    ):
			'''simple docstring'''





			return next(parameter.parameters()    ).device



def 	a			( lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__    ):
			'''simple docstring'''





			if fpaa_statistics is None:
						set_module_tensor_to_device(lowerCamelCase__						,      lowerCamelCase__						,      0						,      dtype=lowerCamelCase__						,      value=lowerCamelCase__    )
						A_	:						Union[str, Any]	=     param_name
						A_	:						Dict	=     model
						if "." in tensor_name:
									A_	:						Tuple	=     tensor_name.split("""."""    )
									for split in splits[:-1]:
												A_	:						str	=     getattr(lowerCamelCase__						,      lowerCamelCase__    )
												if new_module is None:
															raise ValueError(f'{module} has no attribute {split}.'    )
												A_	:						Any	=     new_module
									A_	:						int	=     splits[-1]
						# offload weights
						A_	:						List[Any]	=     False
						offload_weight(module._parameters[tensor_name]						,      lowerCamelCase__						,      lowerCamelCase__						,      index=lowerCamelCase__    )
						if hasattr(module._parameters[tensor_name]						,      """SCB"""    ):
									offload_weight(
									    module._parameters[tensor_name].SCB						,      param_name.replace("""weight"""						,      """SCB"""    )						,      lowerCamelCase__						,      index=lowerCamelCase__						,      )
			else:
						offload_weight(lowerCamelCase__						,      lowerCamelCase__						,      lowerCamelCase__						,      index=lowerCamelCase__    )
						offload_weight(lowerCamelCase__						,      param_name.replace("""weight"""						,      """SCB"""    )						,      lowerCamelCase__						,      index=lowerCamelCase__    )

			set_module_tensor_to_device(lowerCamelCase__						,      lowerCamelCase__						,      """meta"""						,      dtype=lowerCamelCase__						,      value=torch.empty(*param.size()    )    )




'''simple docstring'''




import argparse
import struct
import unittest







class 	_lowerCAmelCase							:


	def __init__(self       ,      lowercase							):
				A_	:						List[str]	=     data

				# Initialize hash values
				A_	:						Tuple	=     [
				    0X6A09_E667,
				    0XBB67_AE85,
				    0X3C6E_F372,
				    0XA54F_F53A,
				    0X510E_527F,
				    0X9B05_688C,
				    0X1F83_D9AB,
				    0X5BE0_CD19,
				]

				# Initialize round constants
				A_	:						List[Any]	=     [
				    0X428A_2F98,
				    0X7137_4491,
				    0XB5C0_FBCF,
				    0XE9B5_DBA5,
				    0X3956_C25B,
				    0X59F1_11F1,
				    0X923F_82A4,
				    0XAB1C_5ED5,
				    0XD807_AA98,
				    0X1283_5B01,
				    0X2431_85BE,
				    0X550C_7DC3,
				    0X72BE_5D74,
				    0X80DE_B1FE,
				    0X9BDC_06A7,
				    0XC19B_F174,
				    0XE49B_69C1,
				    0XEFBE_4786,
				    0X0FC1_9DC6,
				    0X240C_A1CC,
				    0X2DE9_2C6F,
				    0X4A74_84AA,
				    0X5CB0_A9DC,
				    0X76F9_88DA,
				    0X983E_5152,
				    0XA831_C66D,
				    0XB003_27C8,
				    0XBF59_7FC7,
				    0XC6E0_0BF3,
				    0XD5A7_9147,
				    0X06CA_6351,
				    0X1429_2967,
				    0X27B7_0A85,
				    0X2E1B_2138,
				    0X4D2C_6DFC,
				    0X5338_0D13,
				    0X650A_7354,
				    0X766A_0ABB,
				    0X81C2_C92E,
				    0X9272_2C85,
				    0XA2BF_E8A1,
				    0XA81A_664B,
				    0XC24B_8B70,
				    0XC76C_51A3,
				    0XD192_E819,
				    0XD699_0624,
				    0XF40E_3585,
				    0X106A_A070,
				    0X19A4_C116,
				    0X1E37_6C08,
				    0X2748_774C,
				    0X34B0_BCB5,
				    0X391C_0CB3,
				    0X4ED8_AA4A,
				    0X5B9C_CA4F,
				    0X682E_6FF3,
				    0X748F_82EE,
				    0X78A5_636F,
				    0X84C8_7814,
				    0X8CC7_0208,
				    0X90BE_FFFA,
				    0XA450_6CEB,
				    0XBEF9_A3F7,
				    0XC671_78F2,
				]

				A_	:						Tuple	=     self.preprocessing(self.data							)
				self.final_hash()


	@staticmethod
	def     _a	(lowercase							):
				A_	:						Any	=     b"""\x80""" + (b"""\x00""" * (63 - (len(lowercase							) + 8) % 64))
				A_	:						Optional[Any]	=     struct.pack(""">Q"""       ,      (len(lowercase							) * 8)							)
				return data + padding + big_endian_integer


	def     _a	(self							):
				# Convert into blocks of 64 bytes
				A_	:						str	=     [
				    self.preprocessed_data[x : x + 64]
				    for x in range(0       ,      len(self.preprocessed_data							)       ,      64							)
				]

				for block in self.blocks:
							# Convert the given block into a list of 4 byte integers
							A_	:						Tuple	=     list(struct.unpack(""">16L"""       ,      lowercase							)							)
							# add 48 0-ed integers
							words += [0] * 48

							A_,    A_,    A_,    A_,    A_,    A_,    A_,    A_	:						Dict	=     self.hashes

							for index in range(0       ,      64							):
										if index > 15:
													# modify the zero-ed indexes at the end of the array
													A_	:						Optional[Any]	=     (
													    self.ror(words[index - 15]       ,      7							)
													    ^ self.ror(words[index - 15]       ,      18							)
													    ^ (words[index - 15] >> 3)
													)
													A_	:						Tuple	=     (
													    self.ror(words[index - 2]       ,      17							)
													    ^ self.ror(words[index - 2]       ,      19							)
													    ^ (words[index - 2] >> 10)
													)

													A_	:						Any	=     (
													    words[index - 16] + sa + words[index - 7] + sa
													) % 0X1_0000_0000

										# Compression
										A_	:						Union[str, Any]	=     self.ror(lowercase       ,      6							) ^ self.ror(lowercase       ,      11							) ^ self.ror(lowercase       ,      25							)
										A_	:						List[Any]	=     (e & f) ^ ((~e & 0XFFFF_FFFF) & g)
										A_	:						Dict	=     (
										    h + sa + ch + self.round_constants[index] + words[index]
										) % 0X1_0000_0000
										A_	:						List[str]	=     self.ror(lowercase       ,      2							) ^ self.ror(lowercase       ,      13							) ^ self.ror(lowercase       ,      22							)
										A_	:						str	=     (a & b) ^ (a & c) ^ (b & c)
										A_	:						int	=     (sa + maj) % 0X1_0000_0000

										A_,    A_,    A_,    A_,    A_,    A_,    A_,    A_	:						List[Any]	=     (
										    g,
										    f,
										    e,
										    ((d + tempa) % 0X1_0000_0000),
										    c,
										    b,
										    a,
										    ((tempa + tempa) % 0X1_0000_0000),
										)

							A_	:						int	=     [a, b, c, d, e, f, g, h]

							# Modify final values
							A_	:						Dict	=     [
							    ((element + mutated_hash_values[index]) % 0X1_0000_0000)
							    for index, element in enumerate(self.hashes							)
							]

				A_	:						Any	=     """""".join([hex(lowercase							)[2:].zfill(8							) for value in self.hashes]							)


	def     _a	(self       ,      lowercase       ,      lowercase							):
				return 0XFFFF_FFFF & (value << (32 - rotations)) | (value >> rotations)







class 	_lowerCAmelCase							(			unittest.TestCase ):


	def     _a	(self							):
				import hashlib

				A_	:						Optional[Any]	=     bytes("""Test String"""       ,      """utf-8"""							)
				self.assertEqual(SHAaaa(lowercase							).hash       ,      hashlib.shaaaa(lowercase							).hexdigest()							)






def 	a			( ):
			'''simple docstring'''





			import doctest

			doctest.testmod()

			A_	:						Any	=     argparse.ArgumentParser()
			parser.add_argument(
			    """-s"""						,      """--string"""						,      dest="""input_string"""						,      default="""Hello World!! Welcome to Cryptography"""						,      help="""Hash the string"""						,      )
			parser.add_argument(
			    """-f"""						,      """--file"""						,      dest="""input_file"""						,      help="""Hash contents of a file"""    )

			A_	:						List[str]	=     parser.parse_args()

			A_	:						Tuple	=     args.input_string

			# hash input should be a bytestring
			if args.input_file:
						with open(args.input_file						,      """rb"""    ) as f:
									A_	:						Union[str, Any]	=     f.read()
			else:
						A_	:						Optional[Any]	=     bytes(lowerCamelCase__						,      """utf-8"""    )

			print(SHAaaa(lowerCamelCase__    ).hash    )


if __name__ == "__main__":
						main()