"""simple docstring"""




import copy
import importlib.metadata
import json
import os
from dataclasses import dataclass
from typing import Any, Dict, Union

from packaging import version

from ..utils import is_torch_available, logging


if is_torch_available():
     import torch


_a      :		Union[str, Any]           =   logging.get_logger(__name__)
@dataclass
class 						__A							:






     def __init__(		self				,     a__=False				,     a__=False				,     a__=6.0				,     a__=None				,     a__=False				,     a__=False				,     a__=None				,     a__="fp4"				,     a__=False				,     **a__				,     ):
       _lowerCAmelCase						:       Optional[int]  			=     load_in_abit
       _lowerCAmelCase						:       Optional[int]  			=     load_in_abit
       _lowerCAmelCase						:       Optional[Any]  			=     llm_inta_threshold
       _lowerCAmelCase						:       Optional[Any]  			=     llm_inta_skip_modules
       _lowerCAmelCase						:       int  			=     llm_inta_enable_fpaa_cpu_offload
       _lowerCAmelCase						:       Dict  			=     llm_inta_has_fpaa_weight
       _lowerCAmelCase						:       Optional[int]  			=     bnb_abit_quant_type
       _lowerCAmelCase						:       Tuple  			=     bnb_abit_use_double_quant

       if bnb_abit_compute_dtype is None:
         _lowerCAmelCase						:       List[str]  			=     torch.floataa
       elif isinstance(UpperCAmelCase__				,     UpperCAmelCase__  ):
         _lowerCAmelCase						:       Tuple  			=     getattr(UpperCAmelCase__				,     UpperCAmelCase__  )
       elif isinstance(UpperCAmelCase__				,     torch.dtype  ):
         _lowerCAmelCase						:       Optional[int]  			=     bnb_abit_compute_dtype
       else:
         raise ValueError("""bnb_4bit_compute_dtype must be a string or a torch.dtype"""  )

       self.post_init()






     def     __A  (		self  ):
       if not isinstance(self.llm_inta_threshold				,     UpperCAmelCase__  ):
         raise ValueError("""llm_int8_threshold must be a float"""  )

       if self.llm_inta_skip_modules is not None and not isinstance(self.llm_inta_skip_modules				,     UpperCAmelCase__  ):
         raise ValueError("""llm_int8_skip_modules must be a list of strings"""  )
       if not isinstance(self.llm_inta_enable_fpaa_cpu_offload				,     UpperCAmelCase__  ):
         raise ValueError("""llm_int8_enable_fp32_cpu_offload must be a boolean"""  )

       if not isinstance(self.llm_inta_has_fpaa_weight				,     UpperCAmelCase__  ):
         raise ValueError("""llm_int8_has_fp16_weight must be a boolean"""  )

       if self.bnb_abit_compute_dtype is not None and not isinstance(self.bnb_abit_compute_dtype				,     torch.dtype  ):
         raise ValueError("""bnb_4bit_compute_dtype must be torch.dtype"""  )

       if not isinstance(self.bnb_abit_quant_type				,     UpperCAmelCase__  ):
         raise ValueError("""bnb_4bit_quant_type must be a string"""  )

       if not isinstance(self.bnb_abit_use_double_quant				,     UpperCAmelCase__  ):
         raise ValueError("""bnb_4bit_use_double_quant must be a boolean"""  )

       if self.load_in_abit and not version.parse(importlib.metadata.version("""bitsandbytes"""  )  ) >= version.parse(
           """0.39.0"""  ):
         raise ValueError(
             """4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version"""  )






     def     __A  (		self  ):
       return self.load_in_abit or self.load_in_abit






     def     __A  (		self  ):
       if self.load_in_abit:
         return "llm_int8"
       elif self.load_in_abit and self.bnb_abit_quant_type == "fp4":
         return "fp4"
       elif self.load_in_abit and self.bnb_abit_quant_type == "nf4":
         return "nf4"
       else:
         return None






     @classmethod
     def     __A  (		cls				,     a__				,     a__				,     **a__  ):
       _lowerCAmelCase						:       Any  			=     cls(**UpperCAmelCase__  )

       _lowerCAmelCase						:       Optional[int]  			=     []
       for key, value in kwargs.items():
         if hasattr(UpperCAmelCase__				,     UpperCAmelCase__  ):
           setattr(UpperCAmelCase__				,     UpperCAmelCase__				,     UpperCAmelCase__  )
           to_remove.append(UpperCAmelCase__  )
       for key in to_remove:
         kwargs.pop(UpperCAmelCase__				,     UpperCAmelCase__  )

       if return_unused_kwargs:
         return config, kwargs
       else:
         return config






     def     __A  (		self				,     a__  ):
       with open(UpperCAmelCase__				,     """w"""				,     encoding="""utf-8"""  ) as writer:
         _lowerCAmelCase						:       str  			=     self.to_dict()
         _lowerCAmelCase						:       str  			=     json.dumps(UpperCAmelCase__				,     indent=2				,     sort_keys=UpperCAmelCase__  ) + """\n"""

         writer.write(UpperCAmelCase__  )






     def     __A  (		self  ):
       _lowerCAmelCase						:       Optional[int]  			=     copy.deepcopy(self.__dict__  )
       _lowerCAmelCase						:       Optional[int]  			=     str(output["""bnb_4bit_compute_dtype"""]  ).split("""."""  )[1]

       return output






     def __repr__(		self  ):
       return F"{self.__class__.__name__} {self.to_json_string()}"






     def     __A  (		self				,     a__ = True  ):
       if use_diff is True:
         _lowerCAmelCase						:       Any  			=     self.to_diff_dict()
       else:
         _lowerCAmelCase						:       Any  			=     self.to_dict()
       return json.dumps(UpperCAmelCase__				,     indent=2				,     sort_keys=UpperCAmelCase__  ) + "\n"






     def     __A  (		self  ):
       _lowerCAmelCase						:       str  			=     self.to_dict()

       # get the default config dict
       _lowerCAmelCase						:       Dict  			=     BitsAndBytesConfig().to_dict()

       _lowerCAmelCase						:       Dict  			=     {}

       # only serialize values that differ from the default config
       for key, value in config_dict.items():
         if value != default_config_dict[key]:
           _lowerCAmelCase						:       Dict  			=     value

       return serializable_config_dict








"""simple docstring"""







import warnings

from ...utils import is_sklearn_available, requires_backends


if is_sklearn_available():
		from scipy.stats import pearsonr, spearmanr
		from sklearn.metrics import fa_score, matthews_corrcoef


a__				:							Any						=     (
    '''This metric will be removed from the library soon, metrics should be handled with the 🤗 Evaluate '''
    '''library. You can have a look at this example script for pointers: '''
    '''https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py'''
)




def    UpperCAmelCase__       (lowerCAmelCase_  ,						lowerCAmelCase_   ):




					'''simple docstring'''


					warnings.warn(lowerCAmelCase_  ,						lowerCAmelCase_   )
					requires_backends(lowerCAmelCase_  ,						"sklearn"   )
					return (preds == labels).mean()




def    UpperCAmelCase__       (lowerCAmelCase_  ,						lowerCAmelCase_   ):




					'''simple docstring'''


					warnings.warn(lowerCAmelCase_  ,						lowerCAmelCase_   )
					requires_backends(lowerCAmelCase_  ,						"sklearn"   )
					__SCREAMING_SNAKE_CASE						   =				simple_accuracy(lowerCAmelCase_  ,						lowerCAmelCase_   )
					__SCREAMING_SNAKE_CASE						   =				fa_score(y_true=lowerCAmelCase_  ,						y_pred=lowerCAmelCase_   )
					return {
					    "acc": acc,
					    "f1": fa,
					    "acc_and_f1": (acc + fa) / 2,
					}




def    UpperCAmelCase__       (lowerCAmelCase_  ,						lowerCAmelCase_   ):




					'''simple docstring'''


					warnings.warn(lowerCAmelCase_  ,						lowerCAmelCase_   )
					requires_backends(lowerCAmelCase_  ,						"sklearn"   )
					__SCREAMING_SNAKE_CASE						   =				pearsonr(lowerCAmelCase_  ,						lowerCAmelCase_   )[0]
					__SCREAMING_SNAKE_CASE						   =				spearmanr(lowerCAmelCase_  ,						lowerCAmelCase_   )[0]
					return {
					    "pearson": pearson_corr,
					    "spearmanr": spearman_corr,
					    "corr": (pearson_corr + spearman_corr) / 2,
					}




def    UpperCAmelCase__       (lowerCAmelCase_  ,						lowerCAmelCase_  ,						lowerCAmelCase_   ):




					'''simple docstring'''


					warnings.warn(lowerCAmelCase_  ,						lowerCAmelCase_   )
					requires_backends(lowerCAmelCase_  ,						"sklearn"   )
					assert len(lowerCAmelCase_   ) == len(lowerCAmelCase_   ), f"""Predictions and labels have mismatched lengths {len(lowerCAmelCase_   )} and {len(lowerCAmelCase_   )}"""
					if task_name == "cola":
										return {"mcc": matthews_corrcoef(lowerCAmelCase_  ,						lowerCAmelCase_   )}
					elif task_name == "sst-2":
										return {"acc": simple_accuracy(lowerCAmelCase_  ,						lowerCAmelCase_   )}
					elif task_name == "mrpc":
										return acc_and_fa(lowerCAmelCase_  ,						lowerCAmelCase_   )
					elif task_name == "sts-b":
										return pearson_and_spearman(lowerCAmelCase_  ,						lowerCAmelCase_   )
					elif task_name == "qqp":
										return acc_and_fa(lowerCAmelCase_  ,						lowerCAmelCase_   )
					elif task_name == "mnli":
										return {"mnli/acc": simple_accuracy(lowerCAmelCase_  ,						lowerCAmelCase_   )}
					elif task_name == "mnli-mm":
										return {"mnli-mm/acc": simple_accuracy(lowerCAmelCase_  ,						lowerCAmelCase_   )}
					elif task_name == "qnli":
										return {"acc": simple_accuracy(lowerCAmelCase_  ,						lowerCAmelCase_   )}
					elif task_name == "rte":
										return {"acc": simple_accuracy(lowerCAmelCase_  ,						lowerCAmelCase_   )}
					elif task_name == "wnli":
										return {"acc": simple_accuracy(lowerCAmelCase_  ,						lowerCAmelCase_   )}
					elif task_name == "hans":
										return {"acc": simple_accuracy(lowerCAmelCase_  ,						lowerCAmelCase_   )}
					else:
										raise KeyError(lowerCAmelCase_   )




def    UpperCAmelCase__       (lowerCAmelCase_  ,						lowerCAmelCase_  ,						lowerCAmelCase_   ):




					'''simple docstring'''


					warnings.warn(lowerCAmelCase_  ,						lowerCAmelCase_   )
					requires_backends(lowerCAmelCase_  ,						"sklearn"   )
					if len(lowerCAmelCase_   ) != len(lowerCAmelCase_   ):
										raise ValueError(f"""Predictions and labels have mismatched lengths {len(lowerCAmelCase_   )} and {len(lowerCAmelCase_   )}"""   )
					if task_name == "xnli":
										return {"acc": simple_accuracy(lowerCAmelCase_  ,						lowerCAmelCase_   )}
					else:
										raise KeyError(lowerCAmelCase_   )
