


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


snake_case				:    List[str]       				=     logging.getLogger(__name__)
def 				__lowerCamelCase						( UpperCAmelCase_						:		torch.nn.Module ,  UpperCAmelCase_						:		BnbQuantizationConfig ,  UpperCAmelCase_						:		Union[str, os.PathLike] = None ,  UpperCAmelCase_						:		Optional[Dict[str, Union[int, str, torch.device]]] = None ,  UpperCAmelCase_						:		Optional[List[str]] = None ,  UpperCAmelCase_						:		Optional[Dict[Union[int, str], Union[int, str]]] = None ,  UpperCAmelCase_						:		Optional[Union[str, os.PathLike]] = None ,  UpperCAmelCase_						:		bool = False ,  ):




      """simple docstring"""





      a						:List[Any] 							=       bnb_quantization_config.load_in_abit
      a						:List[Any] 							=       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						:Tuple 							=       []
      # custom device map
      if isinstance(UpperCAmelCase_ ,  UpperCAmelCase_						) and len(device_map.keys()						) > 1:
            a						:str 							=       [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						:Optional[Any] 							=       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						:Tuple 							=       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						:List[str] 							=       []
      a						:str 							=       bnb_quantization_config.keep_in_fpaa_modules
      modules_to_not_convert.extend(UpperCAmelCase_						)

      # compatibility with peft
      a						:str 							=       load_in_abit
      a						:Optional[Any] 							=       load_in_abit

      a						:List[str] 							=       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						:Any 							=       replace_with_bnb_layers(UpperCAmelCase_ ,  UpperCAmelCase_ ,  modules_to_not_convert=UpperCAmelCase_						)
            # convert param to the right dtype
            a						:Any 							=       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						:List[Any] 							=       name.replace('''.weight''' ,  ''''''						).replace('''.bias''' ,  ''''''						)
                              a						:Tuple 							=       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						:Any 							=       replace_with_bnb_layers(
                      UpperCAmelCase_ ,  UpperCAmelCase_ ,  modules_to_not_convert=UpperCAmelCase_						)

            a						:Dict 							=       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						:Optional[int] 							=       True

            a						:int 							=       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 				__lowerCamelCase						( UpperCAmelCase_						:		List[str] ,  UpperCAmelCase_						:		Optional[Any] ,  UpperCAmelCase_						:		Optional[Any]=None ,  UpperCAmelCase_						:		str=None ,  UpperCAmelCase_						:		str=None						):




      """simple docstring"""





      if device_map is None:
            if torch.cuda.is_available():
                  a						:Any 							=       {'''''': 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						:Dict 							=       {}
            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						:Union[str, Any] 							=       special_dtypes
            a						:List[Any] 							=       no_split_module_classes
            a						:Optional[int] 							=       bnb_quantization_config.target_dtype

            # get max_memory for each device.
            if device_map != "sequential":
                  a						:List[Any] 							=       get_balanced_memory(
                      UpperCAmelCase_ ,  low_zero=(device_map == '''balanced_low_0''') ,  max_memory=UpperCAmelCase_ ,  **UpperCAmelCase_ ,  )

            a						:List[str] 							=       max_memory
            a						:Dict 							=       infer_auto_device_map(UpperCAmelCase_ ,  **UpperCAmelCase_						)

      if isinstance(UpperCAmelCase_ ,  UpperCAmelCase_						):
            # check if don't have any quantized module on the cpu
            a						:str 							=       bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules

            a						:Union[str, 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 				__lowerCamelCase						( UpperCAmelCase_						:		int ,  UpperCAmelCase_						:		Optional[Any] ,  UpperCAmelCase_						:		List[Any]=None ,  UpperCAmelCase_						:		str=None						):




      """simple docstring"""





      if modules_to_not_convert is None:
            a						:Tuple 							=       []

      a							,				a						:List[str] 							=       _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 				__lowerCamelCase						( UpperCAmelCase_						:		Optional[Any] ,  UpperCAmelCase_						:		Any ,  UpperCAmelCase_						:		str=None ,  UpperCAmelCase_						:		Any=None ,  ):




      """simple docstring"""





      a						:Optional[int] 							=       False
      for name, module in model.named_children():
            if current_key_name is None:
                  a						:Tuple 							=       []
            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						:Dict 							=       '''.'''.join(UpperCAmelCase_						)
                  a						:Optional[int] 							=       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						:int 							=       False
                              break
                  if proceed:
                        # Load bnb module with empty weight and replace ``nn.Linear` module
                        if bnb_quantization_config.load_in_abit:
                              a						:Any 							=       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						:Dict 							=       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						:List[str] 							=       module.weight.data
                        if module.bias is not None:
                              a						:Tuple 							=       module.bias.data
                        bnb_module.requires_grad_(UpperCAmelCase_						)
                        setattr(UpperCAmelCase_ ,  UpperCAmelCase_ ,  UpperCAmelCase_						)
                        a						:Dict 							=       True
            if len(list(module.children()						)						) > 0:
                  a							,				a						:List[str] 							=       _replace_with_bnb_layers(
                      UpperCAmelCase_ ,  UpperCAmelCase_ ,  UpperCAmelCase_ ,  UpperCAmelCase_						)
                  a						:Dict 							=       has_been_replaced | _has_been_replaced
            # Remove the last key for recursion
            current_key_name.pop(-1						)
      return model, has_been_replaced
def 				__lowerCamelCase						( UpperCAmelCase_						:		str						):




      """simple docstring"""





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

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

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

      # add last module together with tied weights
      a						:Tuple 							=       set(UpperCAmelCase_						) - set(UpperCAmelCase_						)
      a						:List[Any] 							=       list(set(UpperCAmelCase_						)						) + list(UpperCAmelCase_						)

      # remove ".weight" from the keys
      a						:List[str] 							=       ['''.weight''', '''.bias''']
      a						:Union[str, Any] 							=       []
      for name in list_untouched:
            for name_to_remove in names_to_remove:
                  if name_to_remove in name:
                        a						:Any 							=       name.replace(UpperCAmelCase_ ,  ''''''						)
            filtered_module_names.append(UpperCAmelCase_						)

      return filtered_module_names
def 				__lowerCamelCase						( UpperCAmelCase_						:		Dict						):




      """simple docstring"""





      for m in model.modules():
            if isinstance(UpperCAmelCase_ ,  bnb.nn.Linearabit						):
                  return True
      return False
def 				__lowerCamelCase						( UpperCAmelCase_						:		nn.Module						):




      """simple docstring"""





      return next(parameter.parameters()						).device






def 				__lowerCamelCase						( UpperCAmelCase_						:		List[str] ,  UpperCAmelCase_						:		Dict ,  UpperCAmelCase_						:		str ,  UpperCAmelCase_						:		Any ,  UpperCAmelCase_						:		List[str] ,  UpperCAmelCase_						:		Dict ,  UpperCAmelCase_						:		List[Any]						):




      """simple docstring"""





      if fpaa_statistics is None:
            set_module_tensor_to_device(UpperCAmelCase_ ,  UpperCAmelCase_ ,  0 ,  dtype=UpperCAmelCase_ ,  value=UpperCAmelCase_						)
            a						:Tuple 							=       param_name
            a						:Optional[Any] 							=       model
            if "." in tensor_name:
                  a						:str 							=       tensor_name.split('''.'''						)
                  for split in splits[:-1]:
                        a						:Dict 							=       getattr(UpperCAmelCase_ ,  UpperCAmelCase_						)
                        if new_module is None:
                              raise ValueError(F'''{module} has no attribute {split}.'''						)
                        a						:List[Any] 							=       new_module
                  a						:List[Any] 							=       splits[-1]
            # offload weights
            a						:Optional[Any] 							=       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()						)						)









from __future__ import annotations
def 				__lowerCamelCase						( UpperCAmelCase_						:		str ,  UpperCAmelCase_						:		list[str] | None = None ,  UpperCAmelCase_						:		dict[str, float] | None = None ,  UpperCAmelCase_						:		bool = False ,  ):




      """simple docstring"""





      a						:str 							=       cipher_alphabet or [chr(UpperCAmelCase_						) for i in range(97 ,  123						)]

      # If the argument is None or the user provided an empty dictionary
      if not frequencies_dict:
            # Frequencies of letters in the english language (how much they show up)
            a						:List[Any] 							=       {
                '''a''': 0.08497,
                '''b''': 0.01492,
                '''c''': 0.02202,
                '''d''': 0.04253,
                '''e''': 0.11162,
                '''f''': 0.02228,
                '''g''': 0.02015,
                '''h''': 0.06094,
                '''i''': 0.07546,
                '''j''': 0.00153,
                '''k''': 0.01292,
                '''l''': 0.04025,
                '''m''': 0.02406,
                '''n''': 0.06749,
                '''o''': 0.07507,
                '''p''': 0.01929,
                '''q''': 0.00095,
                '''r''': 0.07587,
                '''s''': 0.06327,
                '''t''': 0.09356,
                '''u''': 0.02758,
                '''v''': 0.00978,
                '''w''': 0.02560,
                '''x''': 0.00150,
                '''y''': 0.01994,
                '''z''': 0.00077,
            }
      else:
            # Custom frequencies dictionary
            a						:Dict 							=       frequencies_dict

      if not case_sensitive:
            a						:Union[str, Any] 							=       ciphertext.lower()

      # Chi squared statistic values
      a						:dict[int, tuple[float, str]] 							=       {}

      # cycle through all of the shifts
      for shift in range(len(UpperCAmelCase_						)						):
            a						:int 							=       ''''''

            # decrypt the message with the shift
            for letter in ciphertext:
                  try:
                        # Try to index the letter in the alphabet
                        a						:Dict 							=       (alphabet_letters.index(letter.lower()						) - shift) % len(
                            UpperCAmelCase_						)
                        decrypted_with_shift += (
                            alphabet_letters[new_key].upper()
                            if case_sensitive and letter.isupper()
                            else alphabet_letters[new_key]
                        )
                  except ValueError:
                        # Append the character if it isn't in the alphabet
                        decrypted_with_shift += letter

            a						:List[Any] 							=       0.0

            # Loop through each letter in the decoded message with the shift
            for letter in decrypted_with_shift:
                  if case_sensitive:
                        a						:Optional[int] 							=       letter.lower()
                        if letter in frequencies:
                              # Get the amount of times the letter occurs in the message
                              a						:List[Any] 							=       decrypted_with_shift.lower().count(UpperCAmelCase_						)

                              # Get the excepcted amount of times the letter should appear based
                              # on letter frequencies
                              a						:Dict 							=       frequencies[letter] * occurrences

                              # Complete the chi squared statistic formula
                              a						:Any 							=       ((occurrences - expected) ** 2) / expected

                              # Add the margin of error to the total chi squared statistic
                              chi_squared_statistic += chi_letter_value
                  else:
                        if letter.lower() in frequencies:
                              # Get the amount of times the letter occurs in the message
                              a						:int 							=       decrypted_with_shift.count(UpperCAmelCase_						)

                              # Get the excepcted amount of times the letter should appear based
                              # on letter frequencies
                              a						:Tuple 							=       frequencies[letter] * occurrences

                              # Complete the chi squared statistic formula
                              a						:Optional[Any] 							=       ((occurrences - expected) ** 2) / expected

                              # Add the margin of error to the total chi squared statistic
                              chi_squared_statistic += chi_letter_value

        # Add the data to the chi_squared_statistic_values dictionary
            a						:Optional[Any] 							=       (
                chi_squared_statistic,
                decrypted_with_shift,
            )

      # Get the most likely cipher by finding the cipher with the smallest chi squared
      # statistic
      def chi_squared_statistic_values_sorting_key(UpperCAmelCase_						:		int						) -> tuple[float, str]:
            return chi_squared_statistic_values[key]

      a						:int 							=       min(
          UpperCAmelCase_ ,  key=UpperCAmelCase_ ,  )

      # Get all the data from the most likely cipher (key, decoded message)
      (
          (
          a
      )							,				(
          a
      )							,				
      )						:Optional[int] 							=       chi_squared_statistic_values[most_likely_cipher]

      # Return the data on the most likely shift
      return (
          most_likely_cipher,
          most_likely_cipher_chi_squared_value,
          decoded_most_likely_cipher,
      )





