

import json
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import yaml

from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType
from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION


UpperCAmelCase				: Dict         =  os.path.expanduser(
    os.getenv('HF_HOME', os.path.join(os.getenv('XDG_CACHE_HOME', '~/.cache'), 'huggingface'))
)
UpperCAmelCase				: Any         =  os.path.join(hf_cache_home, 'accelerate')
UpperCAmelCase				: List[Any]         =  os.path.join(cache_dir, 'default_config.yaml')
UpperCAmelCase				: Any         =  os.path.join(cache_dir, 'default_config.yaml')

# For backward compatibility: the default config is the json one if it's the only existing file.
if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file):
  UpperCAmelCase				: str         =  default_yaml_config_file
else:
  UpperCAmelCase				: Any         =  default_json_config_file







def      a__ (						a__		):




     """simple docstring"""


     if config_file is not None:
          if not os.path.isfile(a__		):
               raise FileNotFoundError(
                   F'The passed configuration file `{config_file}` does not exist. '
                   """Please pass an existing file to `accelerate launch`, or use the the default one """
                   """created through `accelerate config` and run `accelerate launch` """
                   """without the `--config_file` argument."""		)
     else:
          __SCREAMING_SNAKE_CASE						     =   default_config_file
     with open(a__   ,					"""r"""   ,					encoding="""utf-8"""		) as f:
          if config_file.endswith(""".json"""		):
               if (
                   json.load(a__		).get("""compute_environment"""   ,					ComputeEnvironment.LOCAL_MACHINE		)
                   == ComputeEnvironment.LOCAL_MACHINE
               ):
                    __SCREAMING_SNAKE_CASE						     =   ClusterConfig
               else:
                    __SCREAMING_SNAKE_CASE						     =   SageMakerConfig
               return config_class.from_json_file(json_file=a__		)
          else:
               if (
                   yaml.safe_load(a__		).get("""compute_environment"""   ,					ComputeEnvironment.LOCAL_MACHINE		)
                   == ComputeEnvironment.LOCAL_MACHINE
               ):
                    __SCREAMING_SNAKE_CASE						     =   ClusterConfig
               else:
                    __SCREAMING_SNAKE_CASE						     =   SageMakerConfig
               return config_class.from_yaml_file(yaml_file=a__		)







@dataclass
class 		lowerCAmelCase__     :



 """simple docstring"""



 lowerCAmelCase__						      =   42
 lowerCAmelCase__						      =   42
 lowerCAmelCase__						      =   42
 lowerCAmelCase__						      =   42
 def    UpperCAmelCase__	(	self      : Optional[int]    )						->				List[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE						     =   self.__dict__
      # For serialization, it's best to convert Enums to strings (or their underlying value type).
      for key, value in result.items():
           if isinstance(__A      ,							__A    ):
                __SCREAMING_SNAKE_CASE						     =   value.value
           if isinstance(__A      ,							__A    ) and not bool(__A    ):
                __SCREAMING_SNAKE_CASE						     =   None
      __SCREAMING_SNAKE_CASE						     =   {k: v for k, v in result.items() if v is not None}
      return result
 @classmethod
 def    UpperCAmelCase__	(	cls      : List[Any]      ,							__SCREAMING_SNAKE_CASE      : Any=None    )						->				List[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE						     =   default_json_config_file if json_file is None else json_file
      with open(__A      ,							"""r"""      ,							encoding="""utf-8"""    ) as f:
           __SCREAMING_SNAKE_CASE						     =   json.load(__A    )
      if "compute_environment" not in config_dict:
           __SCREAMING_SNAKE_CASE						     =   ComputeEnvironment.LOCAL_MACHINE
      if "mixed_precision" not in config_dict:
           __SCREAMING_SNAKE_CASE						     =   """fp16""" if ("""fp16""" in config_dict and config_dict["""fp16"""]) else None
      if "fp16" in config_dict:  # Convert the config to the new format.
           del config_dict["fp16"]
      if "dynamo_backend" in config_dict:  # Convert the config to the new format.
           __SCREAMING_SNAKE_CASE						     =   config_dict.pop("""dynamo_backend"""    )
           __SCREAMING_SNAKE_CASE						     =   {} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
      if "use_cpu" not in config_dict:
           __SCREAMING_SNAKE_CASE						     =   False
      return cls(**__A    )
 def    UpperCAmelCase__	(	self      : List[Any]      ,							__SCREAMING_SNAKE_CASE      : str    )						->				int:


      """simple docstring"""




      with open(__A      ,							"""w"""      ,							encoding="""utf-8"""    ) as f:
           __SCREAMING_SNAKE_CASE						     =   json.dumps(self.to_dict()      ,							indent=2      ,							sort_keys=__A    ) + """\n"""
           f.write(__A    )
 @classmethod
 def    UpperCAmelCase__	(	cls      : Dict      ,							__SCREAMING_SNAKE_CASE      : Any=None    )						->				List[str]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE						     =   default_yaml_config_file if yaml_file is None else yaml_file
      with open(__A      ,							"""r"""      ,							encoding="""utf-8"""    ) as f:
           __SCREAMING_SNAKE_CASE						     =   yaml.safe_load(__A    )
      if "compute_environment" not in config_dict:
           __SCREAMING_SNAKE_CASE						     =   ComputeEnvironment.LOCAL_MACHINE

      if "mixed_precision" not in config_dict:
           __SCREAMING_SNAKE_CASE						     =   """fp16""" if ("""fp16""" in config_dict and config_dict["""fp16"""]) else None
      if isinstance(config_dict["""mixed_precision"""]      ,							__A    ) and not config_dict["mixed_precision"]:
           __SCREAMING_SNAKE_CASE						     =   """no"""
      if "fp16" in config_dict:  # Convert the config to the new format.
           del config_dict["fp16"]
      if "dynamo_backend" in config_dict:  # Convert the config to the new format.
           __SCREAMING_SNAKE_CASE						     =   config_dict.pop("""dynamo_backend"""    )
           __SCREAMING_SNAKE_CASE						     =   {} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
      if "use_cpu" not in config_dict:
           __SCREAMING_SNAKE_CASE						     =   False
      return cls(**__A    )
 def    UpperCAmelCase__	(	self      : Any      ,							__SCREAMING_SNAKE_CASE      : Optional[Any]    )						->				Optional[Any]:


      """simple docstring"""




      with open(__A      ,							"""w"""      ,							encoding="""utf-8"""    ) as f:
           yaml.safe_dump(self.to_dict()      ,							__A    )


 def    UpperCAmelCase__	(	self      : Tuple    )						->				Dict:


      """simple docstring"""




      if isinstance(self.compute_environment      ,							__A    ):
           __SCREAMING_SNAKE_CASE						     =   ComputeEnvironment(self.compute_environment    )
      if isinstance(self.distributed_type      ,							__A    ):
           if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
                __SCREAMING_SNAKE_CASE						     =   SageMakerDistributedType(self.distributed_type    )
           else:
                __SCREAMING_SNAKE_CASE						     =   DistributedType(self.distributed_type    )
      if self.dynamo_config is None:
           __SCREAMING_SNAKE_CASE						     =   {}







@dataclass
class 		lowerCAmelCase__     (   _SCREAMING_SNAKE_CASE      ):



 """simple docstring"""



 lowerCAmelCase__						      =   42
 lowerCAmelCase__						      =   0
 lowerCAmelCase__						      =   1
 lowerCAmelCase__						      =   None
 lowerCAmelCase__						      =   None
 lowerCAmelCase__						      =   None
 lowerCAmelCase__						      =   "static"
 lowerCAmelCase__						      =   False
 lowerCAmelCase__						      =   "main"

 # args for deepspeed_plugin
 lowerCAmelCase__						      =   None
 # args for fsdp
 lowerCAmelCase__						      =   None
 # args for megatron_lm
 lowerCAmelCase__						      =   None
 # args for ipex
 lowerCAmelCase__						      =   None
 # args for TPU
 lowerCAmelCase__						      =   False

 # args for TPU pods
 lowerCAmelCase__						      =   None
 lowerCAmelCase__						      =   None
 lowerCAmelCase__						      =   False
 lowerCAmelCase__						      =   False
 lowerCAmelCase__						      =   None
 lowerCAmelCase__						      =   None
 lowerCAmelCase__						      =   None
 lowerCAmelCase__						      =   None

 # args for dynamo
 lowerCAmelCase__						      =   None
 def    UpperCAmelCase__	(	self      : Optional[int]    )						->				Optional[Any]:


      """simple docstring"""




      if self.deepspeed_config is None:
           __SCREAMING_SNAKE_CASE						     =   {}
      if self.fsdp_config is None:
           __SCREAMING_SNAKE_CASE						     =   {}
      if self.megatron_lm_config is None:
           __SCREAMING_SNAKE_CASE						     =   {}
      if self.ipex_config is None:
           __SCREAMING_SNAKE_CASE						     =   {}
      return super().__post_init__()







@dataclass
class 		lowerCAmelCase__     (   _SCREAMING_SNAKE_CASE      ):



 """simple docstring"""



 lowerCAmelCase__						      =   42
 lowerCAmelCase__						      =   42
 lowerCAmelCase__						      =   None
 lowerCAmelCase__						      =   None
 lowerCAmelCase__						      =   "us-east-1"
 lowerCAmelCase__						      =   1
 lowerCAmelCase__						      =   "all"
 lowerCAmelCase__						      =   F'accelerate-sagemaker-{num_machines}'
 lowerCAmelCase__						      =   SAGEMAKER_PYTORCH_VERSION
 lowerCAmelCase__						      =   SAGEMAKER_TRANSFORMERS_VERSION
 lowerCAmelCase__						      =   SAGEMAKER_PYTHON_VERSION
 lowerCAmelCase__						      =   None
 lowerCAmelCase__						      =   None
 lowerCAmelCase__						      =   None
 lowerCAmelCase__						      =   None









'''simple docstring'''



from sklearn.metrics import precision_score

import datasets


UpperCAmelCase				: Optional[int]         =  '\nPrecision is the fraction of correctly labeled positive examples out of all of the examples that were labeled as positive. It is computed via the equation:\nPrecision = TP / (TP + FP)\nwhere TP is the True positives (i.e. the examples correctly labeled as positive) and FP is the False positive examples (i.e. the examples incorrectly labeled as positive).\n'


UpperCAmelCase				: Optional[int]         =  '\nArgs:\n    predictions (`list` of `int`): Predicted class labels.\n    references (`list` of `int`): Actual class labels.\n    labels (`list` of `int`): The set of labels to include when `average` is not set to `\'binary\'`. If `average` is `None`, it should be the label order. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n    pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n    average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `\'binary\'`.\n\n        - \'binary\': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n        - \'micro\': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n        - \'macro\': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n        - \'weighted\': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `\'macro\'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n        - \'samples\': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n    sample_weight (`list` of `float`): Sample weights Defaults to None.\n    zero_division (`int` or `string`): Sets the value to return when there is a zero division. Defaults to \'warn\'.\n\n        - 0: Returns 0 when there is a zero division.\n        - 1: Returns 1 when there is a zero division.\n        - \'warn\': Raises warnings and then returns 0 when there is a zero division.\n\nReturns:\n    precision (`float` or `array` of `float`): Precision score or list of precision scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate that fewer negative examples were incorrectly labeled as positive, which means that, generally, higher scores are better.\n\nExamples:\n\n    Example 1-A simple binary example\n        >>> precision_metric = datasets.load_metric("precision")\n        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n        >>> print(results)\n        {\'precision\': 0.5}\n\n    Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n        >>> precision_metric = datasets.load_metric("precision")\n        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n        >>> print(round(results[\'precision\'], 2))\n        0.67\n\n    Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n        >>> precision_metric = datasets.load_metric("precision")\n        >>> results = precision_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n        >>> print(results)\n        {\'precision\': 0.23529411764705882}\n\n    Example 4-A multiclass example, with different values for the `average` input.\n        >>> predictions = [0, 2, 1, 0, 0, 1]\n        >>> references = [0, 1, 2, 0, 1, 2]\n        >>> results = precision_metric.compute(predictions=predictions, references=references, average=\'macro\')\n        >>> print(results)\n        {\'precision\': 0.2222222222222222}\n        >>> results = precision_metric.compute(predictions=predictions, references=references, average=\'micro\')\n        >>> print(results)\n        {\'precision\': 0.3333333333333333}\n        >>> results = precision_metric.compute(predictions=predictions, references=references, average=\'weighted\')\n        >>> print(results)\n        {\'precision\': 0.2222222222222222}\n        >>> results = precision_metric.compute(predictions=predictions, references=references, average=None)\n        >>> print([round(res, 2) for res in results[\'precision\']])\n        [0.67, 0.0, 0.0]\n'


UpperCAmelCase				: Union[str, Any]         =  '\n@article{scikit-learn,\n    title={Scikit-learn: Machine Learning in {P}ython},\n    author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n    and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n    and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n    Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n    journal={Journal of Machine Learning Research},\n    volume={12},\n    pages={2825--2830},\n    year={2011}\n}\n'







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



 """simple docstring"""



 def    UpperCAmelCase__	(	self      : List[str]    )						->				Dict:


      """simple docstring"""




      return datasets.MetricInfo(
          description=_DESCRIPTION      ,							citation=_CITATION      ,							inputs_description=_KWARGS_DESCRIPTION      ,							features=datasets.Features(
              {
                  """predictions""": datasets.Sequence(datasets.Value("""int32"""    )    ),
                  """references""": datasets.Sequence(datasets.Value("""int32"""    )    ),
              }
              if self.config_name == """multilabel"""
              else {
                  """predictions""": datasets.Value("""int32"""    ),
                  """references""": datasets.Value("""int32"""    ),
              }    )      ,							reference_urls=["""https://scikit-learn.org/stable/modules/generated/sklearn.metrics.precision_score.html"""]      ,							)


 def    UpperCAmelCase__	(	self      : List[Any]      ,							__SCREAMING_SNAKE_CASE      : List[str]      ,							__SCREAMING_SNAKE_CASE      : Dict      ,							__SCREAMING_SNAKE_CASE      : Union[str, Any]=None      ,							__SCREAMING_SNAKE_CASE      : List[Any]=1      ,							__SCREAMING_SNAKE_CASE      : Tuple="binary"      ,							__SCREAMING_SNAKE_CASE      : Any=None      ,							__SCREAMING_SNAKE_CASE      : Tuple="warn"      ,							)						->				List[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE						     =   precision_score(
          __SCREAMING_SNAKE_CASE      ,							__SCREAMING_SNAKE_CASE      ,							labels=__SCREAMING_SNAKE_CASE      ,							pos_label=__SCREAMING_SNAKE_CASE      ,							average=__SCREAMING_SNAKE_CASE      ,							sample_weight=__SCREAMING_SNAKE_CASE      ,							zero_division=__SCREAMING_SNAKE_CASE      ,							)
      return {"precision": float(__SCREAMING_SNAKE_CASE    ) if score.size == 1 else score}






