



"""simple docstring"""







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_   						=   logging.get_logger(__name__)



def      __UpperCAmelCase      (    __lowerCamelCase						,     __lowerCamelCase						,     __lowerCamelCase						,     __lowerCamelCase=None						,     __lowerCamelCase=None	)							->      Tuple:
		# Recurse if needed
		if "." in tensor_name:
				lowercase__   :    List[str]				=			tensor_name.split('''.'''	)
				for split in splits[:-1]:
						lowercase__   :    List[Any]				=			getattr(__lowerCamelCase						,     __lowerCamelCase	)
						if new_module is None:
								raise ValueError(f"""{module} has no attribute {split}."""	)
						lowercase__   :    Optional[int]				=			new_module
				lowercase__   :    Tuple				=			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}."""	)
		lowercase__   :    List[Any]				=			tensor_name in module._buffers
		lowercase__   :    Any				=			getattr(__lowerCamelCase						,     __lowerCamelCase	)

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

		lowercase__   :    Any				=			False
		lowercase__   :    List[str]				=			False
		if is_buffer or not is_bitsandbytes_available():
				lowercase__   :    Union[str, Any]				=			False
				lowercase__   :    str				=			False
		else:
				lowercase__   :    Any				=			hasattr(bnb.nn						,     '''Params4bit'''	) and isinstance(module._parameters[tensor_name]						,     bnb.nn.Paramsabit	)
				lowercase__   :    int				=			isinstance(module._parameters[tensor_name]						,     bnb.nn.IntaParams	)

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

						lowercase__   :    str				=			old_value.__dict__
						if is_abit:
								lowercase__   :    Union[str, Any]				=			bnb.nn.IntaParams(__lowerCamelCase						,     requires_grad=__lowerCamelCase						,     **__lowerCamelCase	).to(__lowerCamelCase	)
						elif is_abit:
								lowercase__   :    Optional[int]				=			bnb.nn.Paramsabit(__lowerCamelCase						,     requires_grad=__lowerCamelCase						,     **__lowerCamelCase	).to(__lowerCamelCase	)

						lowercase__   :    Tuple				=			new_value
						if fpaa_statistics is not None:
								setattr(module.weight						,     '''SCB'''						,     fpaa_statistics.to(__lowerCamelCase	)	)

		else:
				if value is None:
						lowercase__   :    Union[str, Any]				=			old_value.to(__lowerCamelCase	)
				elif isinstance(__lowerCamelCase						,     torch.Tensor	):
						lowercase__   :    List[Any]				=			value.to(__lowerCamelCase	)
				else:
						lowercase__   :    Optional[Any]				=			torch.tensor(__lowerCamelCase						,     device=__lowerCamelCase	)

				if is_buffer:
						lowercase__   :    Tuple				=			new_value
				else:
						lowercase__   :    List[Any]				=			nn.Parameter(__lowerCamelCase						,     requires_grad=old_value.requires_grad	)
						lowercase__   :    int				=			new_value



def      __UpperCAmelCase      (    __lowerCamelCase						,     __lowerCamelCase=None						,     __lowerCamelCase=None						,     __lowerCamelCase=None						,     __lowerCamelCase=False	)							->      List[str]:
		for name, module in model.named_children():
				if current_key_name is None:
						lowercase__   :    Tuple				=			[]
				current_key_name.append(__lowerCamelCase	)

				if (isinstance(__lowerCamelCase						,     nn.Linear	) or isinstance(__lowerCamelCase						,     __lowerCamelCase	)) 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(__lowerCamelCase	) for key in modules_to_not_convert	):
								with init_empty_weights():
										if isinstance(__lowerCamelCase						,     __lowerCamelCase	):
												lowercase__		,			lowercase__   :    str				=			module.weight.shape
										else:
												lowercase__   :    str				=			module.in_features
												lowercase__   :    Union[str, Any]				=			module.out_features

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



def      __UpperCAmelCase      (    __lowerCamelCase						,     __lowerCamelCase=None						,     __lowerCamelCase=None						,     __lowerCamelCase=None	)							->      Optional[Any]:
		lowercase__   :    Dict				=			['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert
		lowercase__		,			lowercase__   :    str				=			_replace_with_bnb_linear(
		    __lowerCamelCase						,     __lowerCamelCase						,     __lowerCamelCase						,     __lowerCamelCase	)

		if not has_been_replaced:
				logger.warning(
				    '''You are loading your model in 8bit or 4bit but no linear modules were found in your model.'''
				    ''' Please double check your model architecture, or submit an issue on github if you think this is'''
				    ''' a bug.'''	)

		return model



def      __UpperCAmelCase      (    *__lowerCamelCase						,     **__lowerCamelCase	)							->      Union[str, Any]:
		warnings.warn(
		    '''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead'''						,     __lowerCamelCase						,     )
		return replace_with_bnb_linear(*__lowerCamelCase						,     **__lowerCamelCase	)



def      __UpperCAmelCase      (    *__lowerCamelCase						,     **__lowerCamelCase	)							->      str:
		warnings.warn(
		    '''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead'''						,     __lowerCamelCase						,     )
		return set_module_quantized_tensor_to_device(*__lowerCamelCase						,     **__lowerCamelCase	)





def      __UpperCAmelCase      (    __lowerCamelCase	)							->      Optional[Any]:
		lowercase__   :    List[str]				=			deepcopy(__lowerCamelCase	)  # this has 0 cost since it is done inside `init_empty_weights` context manager`
		tied_model.tie_weights()

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

		# Check if it is a base model
		lowercase__   :    Optional[Any]				=			not hasattr(__lowerCamelCase						,     model.base_model_prefix	)

		# Ignore this for base models (BertModel, GPT2Model, etc.)
		if (not has_tied_params) and is_base_model:
				return []

		# otherwise they have an attached head
		lowercase__   :    Optional[int]				=			list(model.named_children()	)
		lowercase__   :    int				=			[list_modules[-1][0]]

		# add last module together with tied weights
		lowercase__   :    int				=			set(__lowerCamelCase	) - set(__lowerCamelCase	)
		lowercase__   :    Dict				=			list(set(__lowerCamelCase	)	) + list(__lowerCamelCase	)

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

		return filtered_module_names





'''simple docstring'''





from typing import Dict, Optional

import numpy as np

import datasets


lowercase_		       =  "\nIoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union\nbetween the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,\nthe mean IoU of the image is calculated by taking the IoU of each class and averaging them.\n"

lowercase_		       =  "\nArgs:\n    predictions (`List[ndarray]`):\n        List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n    references (`List[ndarray]`):\n        List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n    num_labels (`int`):\n        Number of classes (categories).\n    ignore_index (`int`):\n        Index that will be ignored during evaluation.\n    nan_to_num (`int`, *optional*):\n        If specified, NaN values will be replaced by the number defined by the user.\n    label_map (`dict`, *optional*):\n        If specified, dictionary mapping old label indices to new label indices.\n    reduce_labels (`bool`, *optional*, defaults to `False`):\n        Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,\n        and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.\n\nReturns:\n    `Dict[str, float | ndarray]` comprising various elements:\n    - *mean_iou* (`float`):\n        Mean Intersection-over-Union (IoU averaged over all categories).\n    - *mean_accuracy* (`float`):\n        Mean accuracy (averaged over all categories).\n    - *overall_accuracy* (`float`):\n        Overall accuracy on all images.\n    - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):\n        Per category accuracy.\n    - *per_category_iou* (`ndarray` of shape `(num_labels,)`):\n        Per category IoU.\n\nExamples:\n\n    >>> import numpy as np\n\n    >>> mean_iou = datasets.load_metric(\"mean_iou\")\n\n    >>> # suppose one has 3 different segmentation maps predicted\n    >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])\n    >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])\n\n    >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])\n    >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])\n\n    >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])\n    >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])\n\n    >>> predicted = [predicted_1, predicted_2, predicted_3]\n    >>> ground_truth = [actual_1, actual_2, actual_3]\n\n    >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)\n    >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n    {'mean_iou': 0.47750000000000004, 'mean_accuracy': 0.5916666666666666, 'overall_accuracy': 0.5263157894736842, 'per_category_iou': array([0.   , 0.   , 0.375, 0.4  , 0.5  , 0.   , 0.5  , 1.   , 1.   , 1.   ]), 'per_category_accuracy': array([0.        , 0.        , 0.75      , 0.66666667, 1.        , 0.        , 0.5       , 1.        , 1.        , 1.        ])}\n"

lowercase_		       =  "\\n@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,\nauthor = {{MMSegmentation Contributors}},\nlicense = {Apache-2.0},\nmonth = {7},\ntitle = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},\nurl = {https://github.com/open-mmlab/mmsegmentation},\nyear = {2020}\n}"




def lowerCAmelCase  (__A  ,	__A  ,	__A  ,	__A  ,	__A = None  ,	__A = False  ,	):



     """simple docstring"""



     if label_map is not None:
          for old_id, new_id in label_map.items():
               _a      =  new_id

    # turn into Numpy arrays
     _a      =  np.array(__A)
     _a      =  np.array(__A)

     if reduce_labels:
          _a      =  255
          _a      =  label - 1
          _a      =  255

     _a      =  label != ignore_index
     _a      =  np.not_equal(__A  ,	__A)
     _a      =  pred_label[mask]
     _a      =  np.array(__A)[mask]

     _a      =  pred_label[pred_label == label]

     _a      =  np.histogram(__A  ,	bins=__A  ,	range=(0, num_labels - 1))[0]
     _a      =  np.histogram(__A  ,	bins=__A  ,	range=(0, num_labels - 1))[0]
     _a      =  np.histogram(__A  ,	bins=__A  ,	range=(0, num_labels - 1))[0]

     _a      =  area_pred_label + area_label - area_intersect

     return area_intersect, area_union, area_pred_label, area_label




def lowerCAmelCase  (__A  ,	__A  ,	__A  ,	__A  ,	__A = None  ,	__A = False  ,	):



     """simple docstring"""



     _a      =  np.zeros((num_labels,)  ,	dtype=np.floataa)
     _a      =  np.zeros((num_labels,)  ,	dtype=np.floataa)
     _a      =  np.zeros((num_labels,)  ,	dtype=np.floataa)
     _a      =  np.zeros((num_labels,)  ,	dtype=np.floataa)
     for result, gt_seg_map in zip(__A  ,	__A):
          _a  ,    _a  ,    _a  ,    _a      =  intersect_and_union(
              __A  ,	__A  ,	__A  ,	__A  ,	__A  ,	__A)
          total_area_intersect += area_intersect
          total_area_union += area_union
          total_area_pred_label += area_pred_label
          total_area_label += area_label
     return total_area_intersect, total_area_union, total_area_pred_label, total_area_label




def lowerCAmelCase  (__A  ,	__A  ,	__A  ,	__A  ,	__A = None  ,	__A = None  ,	__A = False  ,	):



     """simple docstring"""



     _a  ,    _a  ,    _a  ,    _a      =  total_intersect_and_union(
         __A  ,	__A  ,	__A  ,	__A  ,	__A  ,	__A)

     # compute metrics
     _a      =  {}

     _a      =  total_area_intersect.sum() / total_area_label.sum()
     _a      =  total_area_intersect / total_area_union
     _a      =  total_area_intersect / total_area_label

     _a      =  np.nanmean(__A)
     _a      =  np.nanmean(__A)
     _a      =  all_acc
     _a      =  iou
     _a      =  acc

     if nan_to_num is not None:
          _a      =  {metric: np.nan_to_num(__A  ,	nan=__A) for metric, metric_value in metrics.items()}

     return metrics






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION   ,   _KWARGS_DESCRIPTION						)
class __A			(  datasets.Metric						):



 '''simple docstring'''







 def 					a__  (self       )    ->     List[str]:


      """simple docstring"""



      return datasets.MetricInfo(
          description=_DESCRIPTION ,   citation=_CITATION ,   inputs_description=_KWARGS_DESCRIPTION ,   features=datasets.Features(
              # 1st Seq - height dim, 2nd - width dim
              {
                  '''predictions''': datasets.Sequence(datasets.Sequence(datasets.Value('''uint16'''       )       )       ),
                  '''references''': datasets.Sequence(datasets.Sequence(datasets.Value('''uint16'''       )       )       ),
              }       ) ,   reference_urls=[
              '''https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py'''
          ] ,   )



 def 					a__  (self ,   A ,   A ,   A ,   A ,   A = None ,   A = None ,   A = False ,   )    ->     List[Any]:


      """simple docstring"""



      _a      =  mean_iou(
          results=A ,   gt_seg_maps=A ,   num_labels=A ,   ignore_index=A ,   nan_to_num=A ,   label_map=A ,   reduce_labels=A ,   )
      return iou_result



