






import os
import sys
import warnings
from dataclasses import dataclass, field
from io import BytesIO
from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union

import numpy as np
import pyarrow as pa

from .. import config
from ..download.streaming_download_manager import xopen
from ..table import array_cast
from ..utils.file_utils import is_local_path
from ..utils.py_utils import first_non_null_value, no_op_if_value_is_null, string_to_dict


if TYPE_CHECKING:
		import PIL.Image

		from .features import FeatureType


__magic_name__:	Optional[List[str]]							=      None
__magic_name__:	int							=      """<""" if sys.byteorder == """little""" else """>"""
# Origin: https://github.com/python-pillow/Pillow/blob/698951e19e19972aeed56df686868f1329981c12/src/PIL/Image.py#L3126 minus "|i1" which values are not preserved correctly when saving and loading an image
__magic_name__:	Union[str, Any]							=      [
    np.dtype("|b1"),
    np.dtype("|u1"),
    np.dtype("<u2"),
    np.dtype(">u2"),
    np.dtype("<i2"),
    np.dtype(">i2"),
    np.dtype("<u4"),
    np.dtype(">u4"),
    np.dtype("<i4"),
    np.dtype(">i4"),
    np.dtype("<f4"),
    np.dtype(">f4"),
    np.dtype("<f8"),
    np.dtype(">f8"),
]





@dataclass
class 			snake_case__   :
	lowercase__		:	List[Any]				 =       True
	lowercase__		:	Optional[int]				 =       None
	# Automatically constructed
	lowercase__		:	Dict				 =       '''PIL.Image.Image'''
	lowercase__		:	Dict				 =       pa.struct({'''bytes''': pa.binary(), '''path''': pa.string()} )
	lowercase__		:	List[str]				 =       field(default='''Image'''		,    init=UpperCAmelCase__		,    repr=UpperCAmelCase__ )
	def __call__(							self					)				-> List[str]:
							return self.pa_type
	def      __magic_name__							(							self     ,  lowerCAmelCase__					)				-> dict:

							if config.PIL_AVAILABLE:
													import PIL.Image
							else:
													raise ImportError("""To support encoding images, please install \'Pillow\'."""					)

							if isinstance(UpperCAmelCase__     ,  UpperCAmelCase__					):
													__magic_name__     :  Dict  		=   np.array(UpperCAmelCase__					)

							if isinstance(UpperCAmelCase__     ,  UpperCAmelCase__					):
													return {"path": value, "bytes": None}
							elif isinstance(UpperCAmelCase__     ,  UpperCAmelCase__					):
													return {"path": None, "bytes": value}
							elif isinstance(UpperCAmelCase__     ,  np.ndarray					):
													# convert the image array to PNG/TIFF bytes
													return encode_np_array(UpperCAmelCase__					)
							elif isinstance(UpperCAmelCase__     ,  PIL.Image.Image					):
													# convert the PIL image to bytes (default format is PNG/TIFF)
													return encode_pil_image(UpperCAmelCase__					)
							elif value.get("""path"""					) is not None and os.path.isfile(value["""path"""]					):
													# we set "bytes": None to not duplicate the data if they're already available locally
													return {"bytes": None, "path": value.get("""path"""					)}
							elif value.get("""bytes"""					) is not None or value.get("""path"""					) is not None:
													# store the image bytes, and path is used to infer the image format using the file extension
													return {"bytes": value.get("""bytes"""					), "path": value.get("""path"""					)}
							else:
													raise ValueError(
													    F'An image sample should have one of \'path\' or \'bytes\' but they are missing or None in {value}.'					)
	def      __magic_name__							(							self     ,  lowerCAmelCase__     ,  lowerCAmelCase__=None					)				-> "PIL.Image.Image":

							if not self.decode:
													raise RuntimeError("""Decoding is disabled for this feature. Please use Image(decode=True) instead."""					)

							if config.PIL_AVAILABLE:
													import PIL.Image
							else:
													raise ImportError("""To support decoding images, please install \'Pillow\'."""					)

							if token_per_repo_id is None:
													__magic_name__     :  List[str]  		=   {}

							__magic_name__		,__magic_name__     :  Optional[int]  		=   value["""path"""], value["""bytes"""]
							if bytes_ is None:
													if path is None:
																			raise ValueError(F'An image should have one of \'path\' or \'bytes\' but both are None in {value}.'					)
													else:
																			if is_local_path(UpperCAmelCase__					):
																									__magic_name__     :  List[str]  		=   PIL.Image.open(UpperCAmelCase__					)
																			else:
																									__magic_name__     :  Optional[Any]  		=   path.split("""::"""					)[-1]
																									try:
																															__magic_name__     :  str  		=   string_to_dict(UpperCAmelCase__     ,  config.HUB_DATASETS_URL					)["""repo_id"""]
																															__magic_name__     :  Optional[Any]  		=   token_per_repo_id.get(UpperCAmelCase__					)
																									except ValueError:
																															__magic_name__     :  Optional[Any]  		=   None
																									with xopen(UpperCAmelCase__     ,  """rb"""     ,  use_auth_token=UpperCAmelCase__					) as f:
																															__magic_name__     :  Optional[int]  		=   BytesIO(f.read()					)
																									__magic_name__     :  List[str]  		=   PIL.Image.open(bytes_					)
							else:
													__magic_name__     :  List[Any]  		=   PIL.Image.open(BytesIO(bytes_					)					)
							image.load()  # to avoid "Too many open files" errors
							return image
	def      __magic_name__							(							self					)				-> Union["FeatureType", Dict[str, "FeatureType"]]:
							from .features import Value

							return (
							    self
							    if self.decode
							    else {
							        "bytes": Value("""binary"""					),
							        "path": Value("""string"""					),
							    }
							)
	def      __magic_name__							(							self     ,  lowerCAmelCase__					)				-> pa.StructArray:

							if pa.types.is_string(storage.type					):
													__magic_name__     :  Dict  		=   pa.array([None] * len(UpperCAmelCase__					)     ,  type=pa.binary()					)
													__magic_name__     :  Union[str, Any]  		=   pa.StructArray.from_arrays([bytes_array, storage]     ,  ["""bytes""", """path"""]     ,  mask=storage.is_null()					)
							elif pa.types.is_binary(storage.type					):
													__magic_name__     :  Dict  		=   pa.array([None] * len(UpperCAmelCase__					)     ,  type=pa.string()					)
													__magic_name__     :  str  		=   pa.StructArray.from_arrays([storage, path_array]     ,  ["""bytes""", """path"""]     ,  mask=storage.is_null()					)
							elif pa.types.is_struct(storage.type					):
													if storage.type.get_field_index("""bytes"""					) >= 0:
																			__magic_name__     :  str  		=   storage.field("""bytes"""					)
													else:
																			__magic_name__     :  int  		=   pa.array([None] * len(UpperCAmelCase__					)     ,  type=pa.binary()					)
													if storage.type.get_field_index("""path"""					) >= 0:
																			__magic_name__     :  List[str]  		=   storage.field("""path"""					)
													else:
																			__magic_name__     :  Optional[Any]  		=   pa.array([None] * len(UpperCAmelCase__					)     ,  type=pa.string()					)
													__magic_name__     :  str  		=   pa.StructArray.from_arrays([bytes_array, path_array]     ,  ["""bytes""", """path"""]     ,  mask=storage.is_null()					)
							elif pa.types.is_list(storage.type					):
													__magic_name__     :  Tuple  		=   pa.array(
													    [encode_np_array(np.array(UpperCAmelCase__					)					)["""bytes"""] if arr is not None else None for arr in storage.to_pylist()]     ,  type=pa.binary()     ,  )
													__magic_name__     :  Any  		=   pa.array([None] * len(UpperCAmelCase__					)     ,  type=pa.string()					)
													__magic_name__     :  List[Any]  		=   pa.StructArray.from_arrays(
													    [bytes_array, path_array]     ,  ["""bytes""", """path"""]     ,  mask=bytes_array.is_null()					)
							return array_cast(UpperCAmelCase__     ,  self.pa_type					)







	def      __magic_name__							(							self     ,  lowerCAmelCase__					)				-> pa.StructArray:

							@no_op_if_value_is_null
							def path_to_bytes(lowerCAmelCase__					):
													with xopen(UpperCAmelCase__     ,  """rb"""					) as f:
																			__magic_name__     :  List[str]  		=   f.read()
													return bytes_

							__magic_name__     :  List[Any]  		=   pa.array(
							    [
							        (path_to_bytes(x["""path"""]					) if x["""bytes"""] is None else x["""bytes"""]) if x is not None else None
							        for x in storage.to_pylist()
							    ]     ,  type=pa.binary()     ,  )
							__magic_name__     :  Optional[Any]  		=   pa.array(
							    [os.path.basename(UpperCAmelCase__					) if path is not None else None for path in storage.field("""path"""					).to_pylist()]     ,  type=pa.string()     ,  )
							__magic_name__     :  Union[str, Any]  		=   pa.StructArray.from_arrays([bytes_array, path_array]     ,  ["""bytes""", """path"""]     ,  mask=bytes_array.is_null()					)
							return array_cast(UpperCAmelCase__     ,  self.pa_type					)



def        UpperCamelCase		(			):






						"""simple docstring"""







						if config.PIL_AVAILABLE:
												import PIL.Image
						else:
												raise ImportError("""To support encoding images, please install \'Pillow\'."""					)

						global _IMAGE_COMPRESSION_FORMATS
						if _IMAGE_COMPRESSION_FORMATS is None:
												PIL.Image.init()
												__magic_name__     :  Dict  		=   list(set(PIL.Image.OPEN.keys()					) & set(PIL.Image.SAVE.keys()					)					)
						return _IMAGE_COMPRESSION_FORMATS

def        UpperCamelCase		(			_A					):






						"""simple docstring"""







						__magic_name__     :  str  		=   BytesIO()
						if image.format in list_image_compression_formats():
												__magic_name__     :  List[str]  		=   image.format
						else:
												__magic_name__     :  List[str]  		=   """PNG""" if image.mode in ["""1""", """L""", """LA""", """RGB""", """RGBA"""] else """TIFF"""
						image.save(lowercase_,       format=lowercase_					)
						return buffer.getvalue()

def        UpperCamelCase		(			_A					):






						"""simple docstring"""







						if hasattr(lowercase_,       """filename"""					) and image.filename != "":
												return {"path": image.filename, "bytes": None}
						else:
												return {"path": None, "bytes": image_to_bytes(lowercase_					)}

def        UpperCamelCase		(			_A					):






						"""simple docstring"""







						if config.PIL_AVAILABLE:
												import PIL.Image
						else:
												raise ImportError("""To support encoding images, please install \'Pillow\'."""					)

						__magic_name__     :  Union[str, Any]  		=   array.dtype
						__magic_name__     :  List[str]  		=   dtype.byteorder if dtype.byteorder != """=""" else _NATIVE_BYTEORDER
						__magic_name__     :  List[Any]  		=   dtype.kind
						__magic_name__     :  Dict  		=   dtype.itemsize

						__magic_name__     :  Dict  		=   None

						# Multi-channel array case (only np.dtype("|u1") is allowed)
						if array.shape[2:]:
												__magic_name__     :  Tuple  		=   np.dtype("""|u1"""					)
												if dtype_kind not in ["u", "i"]:
																		raise TypeError(
																		    f'Unsupported array dtype {dtype} for image encoding. Only {dest_dtype} is supported for multi-channel arrays.'					)
												if dtype is not dest_dtype:
																		warnings.warn(f'Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\''					)
    # Exact match
						elif dtype in _VALID_IMAGE_ARRAY_DTPYES:
												__magic_name__     :  List[str]  		=   dtype
						else:  # Downcast the type within the kind (np.can_cast(from_type, to_type, casting="same_kind") doesn't behave as expected, so do it manually)
												while dtype_itemsize >= 1:
																		__magic_name__     :  Optional[Any]  		=   dtype_byteorder + dtype_kind + str(lowercase_					)
																		__magic_name__     :  List[Any]  		=   np.dtype(lowercase_					)
																		if dest_dtype in _VALID_IMAGE_ARRAY_DTPYES:
																								warnings.warn(f'Downcasting array dtype {dtype} to {dest_dtype} to be compatible with \'Pillow\''					)
																								break
																		else:
																								dtype_itemsize //= 2

						if dest_dtype is None:
												raise TypeError(
												    f'Cannot convert dtype {dtype} to a valid image dtype. Valid image dtypes: {_VALID_IMAGE_ARRAY_DTPYES}'					)
						__magic_name__     :  Union[str, Any]  		=   PIL.Image.fromarray(array.astype(lowercase_					)					)
						return {"path": None, "bytes": image_to_bytes(lowercase_					)}

def        UpperCamelCase		(			_A					):






						"""simple docstring"""







						if config.PIL_AVAILABLE:
												import PIL.Image
						else:
												raise ImportError("""To support encoding images, please install \'Pillow\'."""					)

						if objs:
												__magic_name__		,__magic_name__     :  Union[str, Any]  		=   first_non_null_value(lowercase_					)
												if isinstance(lowercase_,       lowercase_					):
																		return [{"path": obj, "bytes": None} if obj is not None else None for obj in objs]
												if isinstance(lowercase_,       np.ndarray					):
																		__magic_name__     :  List[Any]  		=   no_op_if_value_is_null(lowercase_					)
																		return [obj_to_image_dict_func(lowercase_					) for obj in objs]
												elif isinstance(lowercase_,       PIL.Image.Image					):
																		__magic_name__     :  int  		=   no_op_if_value_is_null(lowercase_					)
																		return [obj_to_image_dict_func(lowercase_					) for obj in objs]
												else:
																		return objs
						else:
												return objs






import importlib.metadata
import warnings
from copy import deepcopy

from packaging import version

from ..utils import logging
from .import_utils import is_accelerate_available, is_bitsandbytes_available


if is_bitsandbytes_available():
  import bitsandbytes as bnb
  import torch
  import torch.nn as nn

  from ..pytorch_utils import ConvaD

if is_accelerate_available():
  from accelerate import init_empty_weights
  from accelerate.utils import find_tied_parameters

_lowerCamelCase      :						Union[str, Any]							=  logging.get_logger(__name__)







def SCREAMING_SNAKE_CASE							(			lowercase_					,							lowercase_					,							lowercase_					,							lowercase_=None					,							lowercase_=None		)  ->			Dict:



       """simple docstring"""

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

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

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

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

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

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







def SCREAMING_SNAKE_CASE							(			lowercase_					,							lowercase_=None					,							lowercase_=None					,							lowercase_=None					,							lowercase_=False		)  ->			Dict:



       """simple docstring"""

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

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







def SCREAMING_SNAKE_CASE							(			lowercase_					,							lowercase_=None					,							lowercase_=None					,							lowercase_=None		)  ->			Tuple:



       """simple docstring"""

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

       return model







def SCREAMING_SNAKE_CASE							(			*lowercase_					,							**lowercase_		)  ->			Dict:



       """simple docstring"""

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







def SCREAMING_SNAKE_CASE							(			*lowercase_					,							**lowercase_		)  ->			Optional[Any]:



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







def SCREAMING_SNAKE_CASE							(			lowercase_		)  ->			List[str]:



       """simple docstring"""

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

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

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

       # add last module together with tied weights
       A__ 					=       set(lowercase_		) - set(lowercase_		)
       A__ 					=       list(set(lowercase_		)		) + list(lowercase_		)

       # 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(lowercase_					,							''''''		)
              filtered_module_names.append(lowercase_		)

       return filtered_module_names


