





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

A   : Any			=				logging.get_logger(__name__)







def        __lowerCamelCase (							__a       :int   ,					__a       :Optional[Any]   ,					__a       :Any   ,					__a       :int=None   ,					__a       :List[Any]=None   )		->    Dict:






		"""simple docstring"""

		if "." in tensor_name:
				A__  				=       tensor_name.split("""."""   )
				for split in splits[:-1]:
						A__  				=       getattr(__a   ,					__a   )
						if new_module is None:
								raise ValueError(F'{module} has no attribute {split}.'   )
						A__  				=       new_module
				A__  				=       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}.'   )
		A__  				=       tensor_name in module._buffers
		A__  				=       getattr(__a   ,					__a   )

		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}.'   )

		A__  				=       False
		A__  				=       False
		if is_buffer or not is_bitsandbytes_available():
				A__  				=       False
				A__  				=       False
		else:
				A__  				=       hasattr(bnb.nn   ,					"""Params4bit"""   ) and isinstance(module._parameters[tensor_name]   ,					bnb.nn.Paramsabit   )
				A__  				=       isinstance(module._parameters[tensor_name]   ,					bnb.nn.IntaParams   )

		if is_abit or is_abit:
				A__  				=       module._parameters[tensor_name]
				if param.device.type != "cuda":
						if value is None:
								A__  				=       old_value.to(__a   )
						elif isinstance(__a   ,					torch.Tensor   ):
								A__  				=       value.to("""cpu"""   )
								if value.dtype == torch.inta:
										A__  				=       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:
								A__  				=       torch.tensor(__a   ,					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   ,					__a   ) and fpaa_statistics is None:
								A__  				=       new_value.T

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

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

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

				if is_buffer:
						A__  				=       new_value
				else:
						A__  				=       nn.Parameter(__a   ,					requires_grad=old_value.requires_grad   )
						A__  				=       new_value







def        __lowerCamelCase (							__a       :Optional[int]   ,					__a       :Dict=None   ,					__a       :List[str]=None   ,					__a       :str=None   ,					__a       :Optional[Any]=False   )		->    Dict:






		"""simple docstring"""

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

				if (isinstance(__a   ,					nn.Linear   ) or isinstance(__a   ,					__a   )) 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(__a   ) for key in modules_to_not_convert   ):
								with init_empty_weights():
										if isinstance(__a   ,					__a   ):
												A__				,      A__  				=       module.weight.shape
										else:
												A__  				=       module.in_features
												A__  				=       module.out_features

										if quantization_config.quantization_method() == "llm_int8":
												A__  				=       bnb.nn.LinearabitLt(
												    __a   ,					__a   ,					module.bias is not None   ,					has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight   ,					threshold=quantization_config.llm_inta_threshold   ,					)
												A__  				=       True
										else:
												if (
												    quantization_config.llm_inta_skip_modules is not None
												    and name in quantization_config.llm_inta_skip_modules
												):
														pass
												else:
														A__  				=       bnb.nn.Linearabit(
														    __a   ,					__a   ,					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   ,					)
														A__  				=       True
                    # Store the module class in case we need to transpose the weight later
										A__  				=       type(__a   )
										# Force requires grad to False to avoid unexpected errors
										model._modules[name].requires_grad_(__a   )
				if len(list(module.children()   )   ) > 0:
						A__				,      A__  				=       _replace_with_bnb_linear(
						    __a   ,					__a   ,					__a   ,					__a   ,					has_been_replaced=__a   ,					)
				# Remove the last key for recursion
				current_key_name.pop(-1   )
		return model, has_been_replaced







def        __lowerCamelCase (							__a       :List[Any]   ,					__a       :Optional[Any]=None   ,					__a       :int=None   ,					__a       :int=None   )		->    List[Any]:






		"""simple docstring"""

		A__  				=       ["""lm_head"""] if modules_to_not_convert is None else modules_to_not_convert
		A__				,      A__  				=       _replace_with_bnb_linear(
		    __a   ,					__a   ,					__a   ,					__a   )

		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        __lowerCamelCase (							*__a       :int   ,					**__a       :Any   )		->    List[Any]:






		"""simple docstring"""

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







def        __lowerCamelCase (							*__a       :Any   ,					**__a       :Optional[Any]   )		->    Dict:






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







def        __lowerCamelCase (							__a       :int   )		->    Dict:






		"""simple docstring"""

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

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

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

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

		return filtered_module_names










from typing import Dict, List, Optional, Union

import numpy as np

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


if is_vision_available():
					import PIL


A   : int			=				logging.get_logger(__name__)


class   A      (SCREAMING_SNAKE_CASE   ):
			'''simple docstring'''




			__lowerCamelCase     :	Optional[Any]          =   ['''pixel_values''']






			def __init__(      self       :   Dict							,     __lowerCAmelCase       :   bool = True							,     __lowerCAmelCase       :   Dict[str, int] = None							,     __lowerCAmelCase       :   int = 0.9							,     __lowerCAmelCase       :   PILImageResampling = PILImageResampling.BICUBIC							,     __lowerCAmelCase       :   bool = True							,     __lowerCAmelCase       :   Dict[str, int] = None							,     __lowerCAmelCase       :   Union[int, float] = 1 / 2_55							,     __lowerCAmelCase       :   bool = True							,     __lowerCAmelCase       :   bool = True							,     __lowerCAmelCase       :   Optional[Union[float, List[float]]] = None							,     __lowerCAmelCase       :   Optional[Union[float, List[float]]] = None							,     **__lowerCAmelCase       :   Optional[int]							,     )     ->     None:







					"""simple docstring"""






					super().__init__(**__lowerCAmelCase       )
					A__  				=       size if size is not None else {"""shortest_edge""": 2_24}
					A__  				=       get_size_dict(__lowerCAmelCase							,     default_to_square=__lowerCAmelCase       )
					A__  				=       crop_size if crop_size is not None else {"""height""": 2_24, """width""": 2_24}
					A__  				=       get_size_dict(__lowerCAmelCase							,     param_name="""crop_size"""       )

					A__  				=       do_resize
					A__  				=       size
					A__  				=       crop_pct
					A__  				=       resample
					A__  				=       do_center_crop
					A__  				=       crop_size
					A__  				=       do_rescale
					A__  				=       rescale_factor
					A__  				=       do_normalize
					A__  				=       image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
					A__  				=       image_std if image_std is not None else IMAGENET_DEFAULT_STD






			def        a_	(      self       :   int							,     __lowerCAmelCase       :   np.ndarray							,     __lowerCAmelCase       :   Dict[str, int]							,     __lowerCAmelCase       :   Optional[float] = None							,     __lowerCAmelCase       :   PILImageResampling = PILImageResampling.BICUBIC							,     __lowerCAmelCase       :   Optional[Union[str, ChannelDimension]] = None							,     **__lowerCAmelCase       :   int							,     )     ->     np.ndarray:







					"""simple docstring"""






					A__  				=       get_size_dict(__lowerCAmelCase							,     default_to_square=__lowerCAmelCase       )
					if "shortest_edge" not in size and ("height" not in size or "width" not in size):
							raise ValueError(f'size must contain \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}'       )
					if crop_pct is not None:
							if "shortest_edge" in size:
									A__  				=       int(size["""shortest_edge"""] / crop_pct       )
							elif "height" in size and "width" in size:
									if size["height"] == size["width"]:
											A__  				=       int(size["""height"""] / crop_pct       )
									else:
											A__  				=       (int(size["""height"""] / crop_pct       ), int(size["""width"""] / crop_pct       ))
							else:
									raise ValueError("""Invalid size for resize: {}""".format(__lowerCAmelCase       )       )

							A__  				=       get_resize_output_image_size(__lowerCAmelCase							,     size=__lowerCAmelCase							,     default_to_square=__lowerCAmelCase       )
					else:
							if "shortest_edge" in size:
									A__  				=       get_resize_output_image_size(__lowerCAmelCase							,     size=size["""shortest_edge"""]							,     default_to_square=__lowerCAmelCase       )
							elif "height" in size and "width" in size:
									A__  				=       (size["""height"""], size["""width"""])
							else:
									raise ValueError("""Invalid size for resize: {}""".format(__lowerCAmelCase       )       )

					return resize(__lowerCAmelCase							,     size=__lowerCAmelCase							,     resample=__lowerCAmelCase							,     data_format=__lowerCAmelCase							,     **__lowerCAmelCase       )






			def        a_	(      self       :   Optional[Any]							,     __lowerCAmelCase       :   np.ndarray							,     __lowerCAmelCase       :   Dict[str, int]							,     __lowerCAmelCase       :   Optional[Union[str, ChannelDimension]] = None							,     **__lowerCAmelCase       :   Optional[Any]							,     )     ->     np.ndarray:







					"""simple docstring"""






					A__  				=       get_size_dict(__lowerCAmelCase       )
					if "height" not in size or "width" not in size:
							raise ValueError(f'size must contain \'height\' and \'width\' as keys. Got {size.keys()}'       )
					return center_crop(__lowerCAmelCase							,     size=(size["""height"""], size["""width"""])							,     data_format=__lowerCAmelCase							,     **__lowerCAmelCase       )






			def        a_	(      self       :   str							,     __lowerCAmelCase       :   np.ndarray							,     __lowerCAmelCase       :   Union[int, float]							,     __lowerCAmelCase       :   Optional[Union[str, ChannelDimension]] = None							,     **__lowerCAmelCase       :   Dict							,     )     ->     List[str]:







					"""simple docstring"""






					return rescale(__lowerCAmelCase							,     scale=__lowerCAmelCase							,     data_format=__lowerCAmelCase							,     **__lowerCAmelCase       )






			def        a_	(      self       :   int							,     __lowerCAmelCase       :   np.ndarray							,     __lowerCAmelCase       :   Union[float, List[float]]							,     __lowerCAmelCase       :   Union[float, List[float]]							,     __lowerCAmelCase       :   Optional[Union[str, ChannelDimension]] = None							,     **__lowerCAmelCase       :   int							,     )     ->     np.ndarray:







					"""simple docstring"""






					return normalize(__lowerCAmelCase							,     mean=__lowerCAmelCase							,     std=__lowerCAmelCase							,     data_format=__lowerCAmelCase							,     **__lowerCAmelCase       )







			def        a_	(      self       :   Optional[Any]							,     __lowerCAmelCase       :   ImageInput							,     __lowerCAmelCase       :   bool = None							,     __lowerCAmelCase       :   Dict[str, int] = None							,     __lowerCAmelCase       :   int = None							,     __lowerCAmelCase       :   PILImageResampling = None							,     __lowerCAmelCase       :   bool = None							,     __lowerCAmelCase       :   Dict[str, int] = None							,     __lowerCAmelCase       :   bool = None							,     __lowerCAmelCase       :   float = None							,     __lowerCAmelCase       :   bool = None							,     __lowerCAmelCase       :   Optional[Union[float, List[float]]] = None							,     __lowerCAmelCase       :   Optional[Union[float, List[float]]] = None							,     __lowerCAmelCase       :   Optional[Union[str, TensorType]] = None							,     __lowerCAmelCase       :   ChannelDimension = ChannelDimension.FIRST							,     **__lowerCAmelCase       :   Tuple							,     )     ->     PIL.Image.Image:







					"""simple docstring"""






					A__  				=       do_resize if do_resize is not None else self.do_resize
					A__  				=       crop_pct if crop_pct is not None else self.crop_pct
					A__  				=       resample if resample is not None else self.resample
					A__  				=       do_center_crop if do_center_crop is not None else self.do_center_crop
					A__  				=       do_rescale if do_rescale is not None else self.do_rescale
					A__  				=       rescale_factor if rescale_factor is not None else self.rescale_factor
					A__  				=       do_normalize if do_normalize is not None else self.do_normalize
					A__  				=       image_mean if image_mean is not None else self.image_mean
					A__  				=       image_std if image_std is not None else self.image_std

					A__  				=       size if size is not None else self.size
					A__  				=       get_size_dict(__lowerCAmelCase							,     default_to_square=__lowerCAmelCase       )
					A__  				=       crop_size if crop_size is not None else self.crop_size
					A__  				=       get_size_dict(__lowerCAmelCase							,     param_name="""crop_size"""       )

					A__  				=       make_list_of_images(__lowerCAmelCase       )

					if not valid_images(__lowerCAmelCase       ):
							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 or resample is None:
							raise ValueError("""Size and resample must be specified if do_resize is True."""       )

					if do_center_crop and crop_pct is None:
							raise ValueError("""Crop_pct must be specified if do_center_crop is True."""       )

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

					if do_normalize and (image_mean is None or image_std is None):
							raise ValueError("""Image mean and std must be specified if do_normalize is True."""       )

					# All transformations expect numpy arrays.
					A__  				=       [to_numpy_array(__lowerCAmelCase       ) for image in images]

					if do_resize:
							A__  				=       [self.resize(image=__lowerCAmelCase							,     size=__lowerCAmelCase							,     crop_pct=__lowerCAmelCase							,     resample=__lowerCAmelCase       ) for image in images]

					if do_center_crop:
							A__  				=       [self.center_crop(image=__lowerCAmelCase							,     size=__lowerCAmelCase       ) for image in images]

					if do_rescale:
							A__  				=       [self.rescale(image=__lowerCAmelCase							,     scale=__lowerCAmelCase       ) for image in images]

					if do_normalize:
							A__  				=       [self.normalize(image=__lowerCAmelCase							,     mean=__lowerCAmelCase							,     std=__lowerCAmelCase       ) for image in images]

					A__  				=       [to_channel_dimension_format(__lowerCAmelCase							,     __lowerCAmelCase       ) for image in images]

					A__  				=       {"""pixel_values""": images}
					return BatchFeature(data=__lowerCAmelCase							,     tensor_type=__lowerCAmelCase       )



