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


__SCREAMING_SNAKE_CASE						:   List[str]         =			logging.getLogger(__name__)
def  snake_case						(__lowercase ,      __lowercase ,      __lowercase = None ,      __lowercase = None ,      __lowercase = None ,      __lowercase = None ,      __lowercase = None ,      __lowercase = False ,      )	->	List[Any]:

						'''simple docstring'''



						_snake_case						:					Dict    =   bnb_quantization_config.load_in_abit
						_snake_case						:					Tuple    =   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."						)

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

						# add cpu modules to skip modules only for 4-bit modules
						if load_in_abit:
												bnb_quantization_config.skip_modules.extend(__lowercase						)
						_snake_case						:					Any    =   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:
												_snake_case						:					List[str]    =   []
						_snake_case						:					Dict    =   bnb_quantization_config.keep_in_fpaa_modules
						modules_to_not_convert.extend(__lowercase						)

						# compatibility with peft
						_snake_case						:					Optional[int]    =   load_in_abit
						_snake_case						:					Tuple    =   load_in_abit

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

												_snake_case						:					List[str]    =   get_quantized_model_device_map(
												    __lowercase ,      __lowercase ,      __lowercase ,      max_memory=__lowercase ,      no_split_module_classes=__lowercase ,      )
												if offload_state_dict is None and device_map is not None and "disk" in device_map.values():
																		_snake_case						:					str    =   True

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

												load_checkpoint_in_model(
												    __lowercase ,      __lowercase ,      __lowercase ,      dtype=bnb_quantization_config.torch_dtype ,      offload_folder=__lowercase ,      offload_state_dict=__lowercase ,      keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules ,      offload_abit_bnb=load_in_abit and offload ,      )
												return dispatch_model(__lowercase ,      device_map=__lowercase ,      offload_dir=__lowercase						)
def  snake_case						(__lowercase ,      __lowercase ,      __lowercase=None ,      __lowercase=None ,      __lowercase=None						)	->	Any:

						'''simple docstring'''



						if device_map is None:
												if torch.cuda.is_available():
																		_snake_case						:					List[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(__lowercase ,      __lowercase						):
												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'."						)

												_snake_case						:					str    =   {}
												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						)
												    }						)

												_snake_case						:					Dict    =   {}
												_snake_case						:					Tuple    =   special_dtypes
												_snake_case						:					Dict    =   no_split_module_classes
												_snake_case						:					List[str]    =   bnb_quantization_config.target_dtype

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

												_snake_case						:					int    =   max_memory
												_snake_case						:					Optional[int]    =   infer_auto_device_map(__lowercase ,      **__lowercase						)

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

												_snake_case						:					List[str]    =   {
												    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  snake_case						(__lowercase ,      __lowercase ,      __lowercase=None ,      __lowercase=None						)	->	int:

						'''simple docstring'''



						if modules_to_not_convert is None:
												_snake_case						:					Optional[int]    =   []

						_snake_case    ,_snake_case						:					Union[str, Any]    =   _replace_with_bnb_layers(
						    __lowercase ,      __lowercase ,      __lowercase ,      __lowercase						)
						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  snake_case						(__lowercase ,      __lowercase ,      __lowercase=None ,      __lowercase=None ,      )	->	Union[str, Any]:

						'''simple docstring'''



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

						'''simple docstring'''



						with init_empty_weights():
												_snake_case						:					Optional[int]    =   deepcopy(__lowercase						)  # this has 0 cost since it is done inside `init_empty_weights` context manager`

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

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

						# add last module together with tied weights
						_snake_case						:					int    =   set(__lowercase						) - set(__lowercase						)
						_snake_case						:					Any    =   list(set(__lowercase						)						) + list(__lowercase						)

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

						return filtered_module_names
def  snake_case						(__lowercase						)	->	Dict:

						'''simple docstring'''



						for m in model.modules():
												if isinstance(__lowercase ,      bnb.nn.Linearabit						):
																		return True
						return False
def  snake_case						(__lowercase						)	->	str:

						'''simple docstring'''



						return next(parameter.parameters()						).device

def  snake_case						(__lowercase ,      __lowercase ,      __lowercase ,      __lowercase ,      __lowercase ,      __lowercase ,      __lowercase						)	->	Any:

						'''simple docstring'''



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

						set_module_tensor_to_device(__lowercase ,      __lowercase ,      "meta" ,      dtype=__lowercase ,      value=torch.empty(*param.size()						)						)
from typing import Dict, List, Optional, Tuple, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    flip_channel_order,
    get_resize_output_image_size,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_torch_available, is_torch_tensor, is_vision_available, logging


if is_vision_available():
				import PIL

if is_torch_available():
				import torch


__SCREAMING_SNAKE_CASE						:   Optional[int]         =			logging.get_logger(__name__)



class        lowercase_   (					__snake_case		):
							_lowerCamelCase						=		['pixel_values']



							def __init__(						self				,    lowercase_ = True				,    lowercase_ = None				,    lowercase_ = PILImageResampling.BILINEAR				,    lowercase_ = True				,    lowercase_ = 1 / 255				,    lowercase_ = True				,    lowercase_ = None				,    lowercase_ = True				,    **lowercase_				,    ):
													super().__init__(**lowercase_    )
													_snake_case						:					Dict    =   size if size is not None else {"shortest_edge": 224}
													_snake_case						:					Optional[int]    =   get_size_dict(lowercase_				,    default_to_square=lowercase_    )
													_snake_case						:					Any    =   crop_size if crop_size is not None else {"height": 256, "width": 256}
													_snake_case						:					str    =   get_size_dict(lowercase_				,    param_name="crop_size"    )

													_snake_case						:					List[Any]    =   do_resize
													_snake_case						:					Tuple    =   size
													_snake_case						:					Union[str, Any]    =   resample
													_snake_case						:					str    =   do_rescale
													_snake_case						:					Dict    =   rescale_factor
													_snake_case						:					int    =   do_center_crop
													_snake_case						:					int    =   crop_size
													_snake_case						:					List[Any]    =   do_flip_channel_order



							def 	UpperCamelCase	(						self				,    lowercase_				,    lowercase_				,    lowercase_ = PIL.Image.BILINEAR				,    lowercase_ = None				,    **lowercase_				,    ):
													_snake_case						:					Optional[Any]    =   get_size_dict(lowercase_				,    default_to_square=lowercase_    )
													if "shortest_edge" not in size:
																			raise ValueError(f"""The `size` dictionary must contain the key `shortest_edge`. Got {size.keys()}"""    )
													_snake_case						:					int    =   get_resize_output_image_size(lowercase_				,    size=size["shortest_edge"]				,    default_to_square=lowercase_    )
													return resize(lowercase_				,    size=lowercase_				,    resample=lowercase_				,    data_format=lowercase_				,    **lowercase_    )



							def 	UpperCamelCase	(						self				,    lowercase_				,    lowercase_				,    lowercase_ = None				,    **lowercase_				,    ):
													_snake_case						:					List[str]    =   get_size_dict(lowercase_    )
													if "height" not in size or "width" not in size:
																			raise ValueError(f"""The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}"""    )
													return center_crop(lowercase_				,    size=(size["height"], size["width"])				,    data_format=lowercase_				,    **lowercase_    )



							def 	UpperCamelCase	(						self				,    lowercase_				,    lowercase_				,    lowercase_ = None				,    **lowercase_				,    ):
													return rescale(lowercase_				,    scale=lowercase_				,    data_format=lowercase_				,    **lowercase_    )



							def 	UpperCamelCase	(						self				,    lowercase_				,    lowercase_ = None    ):
													return flip_channel_order(lowercase_				,    data_format=lowercase_    )



							def 	UpperCamelCase	(						self				,    lowercase_				,    lowercase_ = None				,    lowercase_ = None				,    lowercase_ = None				,    lowercase_ = None				,    lowercase_ = None				,    lowercase_ = None				,    lowercase_ = None				,    lowercase_ = None				,    lowercase_ = None				,    lowercase_ = ChannelDimension.FIRST				,    **lowercase_				,    ):
													_snake_case						:					Dict    =   do_resize if do_resize is not None else self.do_resize
													_snake_case						:					Union[str, Any]    =   resample if resample is not None else self.resample
													_snake_case						:					Dict    =   do_rescale if do_rescale is not None else self.do_rescale
													_snake_case						:					str    =   rescale_factor if rescale_factor is not None else self.rescale_factor
													_snake_case						:					Optional[int]    =   do_center_crop if do_center_crop is not None else self.do_center_crop
													_snake_case						:					List[str]    =   (
													    do_flip_channel_order if do_flip_channel_order is not None else self.do_flip_channel_order
													)

													_snake_case						:					Optional[int]    =   size if size is not None else self.size
													_snake_case						:					Optional[int]    =   get_size_dict(lowercase_				,    default_to_square=lowercase_    )
													_snake_case						:					Optional[int]    =   crop_size if crop_size is not None else self.crop_size
													_snake_case						:					Union[str, Any]    =   get_size_dict(lowercase_				,    param_name="crop_size"    )

													_snake_case						:					Tuple    =   make_list_of_images(lowercase_    )

													if not valid_images(lowercase_    ):
																			raise ValueError(
																			    "Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, "
																			    "torch.Tensor, tf.Tensor or jax.ndarray."    )

													if do_resize and size is None:
																			raise ValueError("Size must be specified if do_resize is True."    )

													if do_rescale and rescale_factor is None:
																			raise ValueError("Rescale factor must be specified if do_rescale is True."    )

													if do_center_crop and crop_size is None:
																			raise ValueError("Crop size must be specified if do_center_crop is True."    )

													# All transformations expect numpy arrays.
													_snake_case						:					Tuple    =   [to_numpy_array(lowercase_    ) for image in images]

													if do_resize:
																			_snake_case						:					int    =   [self.resize(image=lowercase_				,    size=lowercase_				,    resample=lowercase_    ) for image in images]

													if do_center_crop:
																			_snake_case						:					List[Any]    =   [self.center_crop(image=lowercase_				,    size=lowercase_    ) for image in images]

													if do_rescale:
																			_snake_case						:					Optional[int]    =   [self.rescale(image=lowercase_				,    scale=lowercase_    ) for image in images]

													# the pretrained checkpoints assume images are BGR, not RGB
													if do_flip_channel_order:
																			_snake_case						:					int    =   [self.flip_channel_order(image=lowercase_    ) for image in images]

													_snake_case						:					str    =   [to_channel_dimension_format(lowercase_				,    lowercase_    ) for image in images]

													_snake_case						:					List[Any]    =   {"pixel_values": images}
													return BatchFeature(data=lowercase_				,    tensor_type=lowercase_    )



							def 	UpperCamelCase	(						self				,    lowercase_				,    lowercase_ = None    ):
													_snake_case						:					int    =   outputs.logits

													# Resize logits and compute semantic segmentation maps
													if target_sizes is not None:
																			if len(lowercase_    ) != len(lowercase_    ):
																									raise ValueError(
																									    "Make sure that you pass in as many target sizes as the batch dimension of the logits"    )

																			if is_torch_tensor(lowercase_    ):
																									_snake_case						:					Union[str, Any]    =   target_sizes.numpy()

																			_snake_case						:					int    =   []

																			for idx in range(len(lowercase_    )    ):
																									_snake_case						:					Optional[Any]    =   torch.nn.functional.interpolate(
																									    logits[idx].unsqueeze(dim=0    )				,    size=target_sizes[idx]				,    mode="bilinear"				,    align_corners=lowercase_    )
																									_snake_case						:					List[str]    =   resized_logits[0].argmax(dim=0    )
																									semantic_segmentation.append(lowercase_    )
													else:
																			_snake_case						:					List[Any]    =   logits.argmax(dim=1    )
																			_snake_case						:					Optional[Any]    =   [semantic_segmentation[i] for i in range(semantic_segmentation.shape[0]    )]

													return semantic_segmentation