






'''simple docstring'''







import sacrebleu as scb
from packaging import version

import datasets


UpperCamelCase_					=				"\\n@inproceedings{post-2018-call,\n    title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n    author = \"Post, Matt\",\n    booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n    month = oct,\n    year = \"2018\",\n    address = \"Belgium, Brussels\",\n    publisher = \"Association for Computational Linguistics\",\n    url = \"https://www.aclweb.org/anthology/W18-6319\",\n    pages = \"186--191\",\n}\n"

UpperCamelCase_					=				"\\nSacreBLEU provides hassle-free computation of shareable, comparable, and reproducible BLEU scores.\nInspired by Rico Sennrich's `multi-bleu-detok.perl`, it produces the official WMT scores but works with plain text.\nIt also knows all the standard test sets and handles downloading, processing, and tokenization for you.\n\nSee the [README.md] file at https://github.com/mjpost/sacreBLEU for more information.\n"

UpperCamelCase_					=				"\nProduces BLEU scores along with its sufficient statistics\nfrom a source against one or more references.\n\nArgs:\n    predictions (`list` of `str`): list of translations to score. Each translation should be tokenized into a list of tokens.\n    references (`list` of `list` of `str`): A list of lists of references. The contents of the first sub-list are the references for the first prediction, the contents of the second sub-list are for the second prediction, etc. Note that there must be the same number of references for each prediction (i.e. all sub-lists must be of the same length).\n    smooth_method (`str`): The smoothing method to use, defaults to `'exp'`. Possible values are:\n        - `'none'`: no smoothing\n        - `'floor'`: increment zero counts\n        - `'add-k'`: increment num/denom by k for n>1\n        - `'exp'`: exponential decay\n    smooth_value (`float`): The smoothing value. Only valid when `smooth_method='floor'` (in which case `smooth_value` defaults to `0.1`) or `smooth_method='add-k'` (in which case `smooth_value` defaults to `1`).\n    tokenize (`str`): Tokenization method to use for BLEU. If not provided, defaults to `'zh'` for Chinese, `'ja-mecab'` for Japanese and `'13a'` (mteval) otherwise. Possible values are:\n        - `'none'`: No tokenization.\n        - `'zh'`: Chinese tokenization.\n        - `'13a'`: mimics the `mteval-v13a` script from Moses.\n        - `'intl'`: International tokenization, mimics the `mteval-v14` script from Moses\n        - `'char'`: Language-agnostic character-level tokenization.\n        - `'ja-mecab'`: Japanese tokenization. Uses the [MeCab tokenizer](https://pypi.org/project/mecab-python3).\n    lowercase (`bool`): If `True`, lowercases the input, enabling case-insensitivity. Defaults to `False`.\n    force (`bool`): If `True`, insists that your tokenized input is actually detokenized. Defaults to `False`.\n    use_effective_order (`bool`): If `True`, stops including n-gram orders for which precision is 0. This should be `True`, if sentence-level BLEU will be computed. Defaults to `False`.\n\nReturns:\n    'score': BLEU score,\n    'counts': Counts,\n    'totals': Totals,\n    'precisions': Precisions,\n    'bp': Brevity penalty,\n    'sys_len': predictions length,\n    'ref_len': reference length,\n\nExamples:\n\n    Example 1:\n        >>> predictions = [\"hello there general kenobi\", \"foo bar foobar\"]\n        >>> references = [[\"hello there general kenobi\", \"hello there !\"], [\"foo bar foobar\", \"foo bar foobar\"]]\n        >>> sacrebleu = datasets.load_metric(\"sacrebleu\")\n        >>> results = sacrebleu.compute(predictions=predictions, references=references)\n        >>> print(list(results.keys()))\n        ['score', 'counts', 'totals', 'precisions', 'bp', 'sys_len', 'ref_len']\n        >>> print(round(results[\"score\"], 1))\n        100.0\n\n    Example 2:\n        >>> predictions = [\"hello there general kenobi\",\n        ...                 \"on our way to ankh morpork\"]\n        >>> references = [[\"hello there general kenobi\", \"hello there !\"],\n        ...                 [\"goodbye ankh morpork\", \"ankh morpork\"]]\n        >>> sacrebleu = datasets.load_metric(\"sacrebleu\")\n        >>> results = sacrebleu.compute(predictions=predictions,\n        ...                             references=references)\n        >>> print(list(results.keys()))\n        ['score', 'counts', 'totals', 'precisions', 'bp', 'sys_len', 'ref_len']\n        >>> print(round(results[\"score\"], 1))\n        39.8\n"




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

      '''simple docstring'''





      def 							lowerCamelCase     (					self						):
             if version.parse(scb.__version__						) < version.parse('''1.4.12'''						):
                    raise ImportWarning(
                        '''To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn\'t match this condition.\n'''
                        '''You can install it with `pip install "sacrebleu>=1.4.12"`.'''						)
             return datasets.MetricInfo(
                 description=_DESCRIPTION  ,		citation=_CITATION  ,		homepage='''https://github.com/mjpost/sacreBLEU'''  ,		inputs_description=_KWARGS_DESCRIPTION  ,		features=datasets.Features(
                     {
                         '''predictions''': datasets.Value('''string'''  ,		id='''sequence'''						),
                         '''references''': datasets.Sequence(datasets.Value('''string'''  ,		id='''sequence'''						)  ,		id='''references'''						),
                     }						)  ,		codebase_urls=['''https://github.com/mjpost/sacreBLEU''']  ,		reference_urls=[
                     '''https://github.com/mjpost/sacreBLEU''',
                     '''https://en.wikipedia.org/wiki/BLEU''',
                     '''https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213''',
                 ]  ,		)




      def 							lowerCamelCase     (					self  ,		_UpperCAmelCase  ,		_UpperCAmelCase  ,		_UpperCAmelCase="exp"  ,		_UpperCAmelCase=None  ,		_UpperCAmelCase=False  ,		_UpperCAmelCase=False  ,		_UpperCAmelCase=None  ,		_UpperCAmelCase=False  ,		):
             UpperCAmelCase__	:   Union[str, Any]												=	len(references[0]						)
             if any(len(_UpperCAmelCase						) != references_per_prediction for refs in references						):
                    raise ValueError('''Sacrebleu requires the same number of references for each prediction'''						)
             UpperCAmelCase__	:   int												=	[[refs[i] for refs in references] for i in range(_UpperCAmelCase						)]
             UpperCAmelCase__	:   Tuple												=	scb.corpus_bleu(
                 _UpperCAmelCase  ,		_UpperCAmelCase  ,		smooth_method=_UpperCAmelCase  ,		smooth_value=_UpperCAmelCase  ,		force=_UpperCAmelCase  ,		lowercase=_UpperCAmelCase  ,		use_effective_order=_UpperCAmelCase  ,		**({'''tokenize''': tokenize} if tokenize else {})  ,		)
             UpperCAmelCase__	:   Optional[int]												=	{
                 '''score''': output.score,
                 '''counts''': output.counts,
                 '''totals''': output.totals,
                 '''precisions''': output.precisions,
                 '''bp''': output.bp,
                 '''sys_len''': output.sys_len,
                 '''ref_len''': output.ref_len,
             }
             return output_dict







'''simple docstring'''







# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

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_					=				os.path.expanduser(
    os.getenv("HF_HOME", os.path.join(os.getenv("XDG_CACHE_HOME", "~/.cache"), "huggingface"))
)
UpperCamelCase_					=				os.path.join(hf_cache_home, "accelerate")
UpperCamelCase_					=				os.path.join(cache_dir, "default_config.yaml")
UpperCamelCase_					=				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_					=				default_yaml_config_file
else:
  UpperCamelCase_					=				default_json_config_file






def  lowerCAmelCase__		(					a_  :     List[Any]			)   -> Optional[Any]:
       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:
              UpperCAmelCase__	:   Dict												=	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
                     ):
                            UpperCAmelCase__	:   Optional[Any]												=	ClusterConfig
                     else:
                            UpperCAmelCase__	:   Dict												=	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
                     ):
                            UpperCAmelCase__	:   Dict												=	ClusterConfig
                     else:
                            UpperCAmelCase__	:   int												=	SageMakerConfig
                     return config_class.from_yaml_file(yaml_file=a_			)




@dataclass
class 					__UpperCAmelCase :

      '''simple docstring'''





      SCREAMING_SNAKE_CASE				:    ComputeEnvironment
      SCREAMING_SNAKE_CASE				:    Union[DistributedType, SageMakerDistributedType]
      SCREAMING_SNAKE_CASE				:    str
      SCREAMING_SNAKE_CASE				:    bool




      def 							lowerCamelCase     (					self						):
             UpperCAmelCase__	:   List[Any]												=	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(_UpperCAmelCase  ,		_UpperCAmelCase						):
                           UpperCAmelCase__	:   Union[str, Any]												=	value.value
                    if isinstance(_UpperCAmelCase  ,		_UpperCAmelCase						) and not bool(_UpperCAmelCase						):
                           UpperCAmelCase__	:   Optional[int]												=	None
             UpperCAmelCase__	:   Optional[Any]												=	{k: v for k, v in result.items() if v is not None}
             return result




      @classmethod
      def 							lowerCamelCase     (					cls  ,		_UpperCAmelCase=None						):
             UpperCAmelCase__	:   str												=	default_json_config_file if json_file is None else json_file
             with open(_UpperCAmelCase  ,		'''r'''  ,		encoding='''utf-8'''						) as f:
                    UpperCAmelCase__	:   Optional[int]												=	json.load(_UpperCAmelCase						)
             if "compute_environment" not in config_dict:
                    UpperCAmelCase__	:   List[str]												=	ComputeEnvironment.LOCAL_MACHINE
             if "mixed_precision" not in config_dict:
                    UpperCAmelCase__	:   Dict												=	'''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.
                    UpperCAmelCase__	:   int												=	config_dict.pop('''dynamo_backend'''						)
                    UpperCAmelCase__	:   int												=	{} if dynamo_backend == '''NO''' else {'''dynamo_backend''': dynamo_backend}
             if "use_cpu" not in config_dict:
                    UpperCAmelCase__	:   Optional[Any]												=	False
             return cls(**_UpperCAmelCase						)




      def 							lowerCamelCase     (					self  ,		_UpperCAmelCase						):
             with open(_UpperCAmelCase  ,		'''w'''  ,		encoding='''utf-8'''						) as f:
                    UpperCAmelCase__	:   Any												=	json.dumps(self.to_dict()  ,		indent=2  ,		sort_keys=_UpperCAmelCase						) + '''\n'''
                    f.write(_UpperCAmelCase						)




      @classmethod
      def 							lowerCamelCase     (					cls  ,		_UpperCAmelCase=None						):
             UpperCAmelCase__	:   List[Any]												=	default_yaml_config_file if yaml_file is None else yaml_file
             with open(_UpperCAmelCase  ,		'''r'''  ,		encoding='''utf-8'''						) as f:
                    UpperCAmelCase__	:   str												=	yaml.safe_load(_UpperCAmelCase						)
             if "compute_environment" not in config_dict:
                    UpperCAmelCase__	:   List[Any]												=	ComputeEnvironment.LOCAL_MACHINE

             if "mixed_precision" not in config_dict:
                    UpperCAmelCase__	:   Tuple												=	'''fp16''' if ('''fp16''' in config_dict and config_dict['''fp16''']) else None
             if isinstance(config_dict['''mixed_precision''']  ,		_UpperCAmelCase						) and not config_dict["mixed_precision"]:
                    UpperCAmelCase__	:   Any												=	'''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.
                    UpperCAmelCase__	:   Optional[int]												=	config_dict.pop('''dynamo_backend'''						)
                    UpperCAmelCase__	:   Dict												=	{} if dynamo_backend == '''NO''' else {'''dynamo_backend''': dynamo_backend}
             if "use_cpu" not in config_dict:
                    UpperCAmelCase__	:   List[str]												=	False
             return cls(**_UpperCAmelCase						)




      def 							lowerCamelCase     (					self  ,		_UpperCAmelCase						):
             with open(_UpperCAmelCase  ,		'''w'''  ,		encoding='''utf-8'''						) as f:
                    yaml.safe_dump(self.to_dict()  ,		_UpperCAmelCase						)




      def 							lowerCamelCase     (					self						):
             if isinstance(self.compute_environment  ,		_UpperCAmelCase						):
                    UpperCAmelCase__	:   Tuple												=	ComputeEnvironment(self.compute_environment						)
             if isinstance(self.distributed_type  ,		_UpperCAmelCase						):
                    if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
                           UpperCAmelCase__	:   Optional[Any]												=	SageMakerDistributedType(self.distributed_type						)
                    else:
                           UpperCAmelCase__	:   Dict												=	DistributedType(self.distributed_type						)
             if self.dynamo_config is None:
                    UpperCAmelCase__	:   Optional[Any]												=	{}




@dataclass
class 					__UpperCAmelCase (		UpperCamelCase__	):

      '''simple docstring'''





      SCREAMING_SNAKE_CASE				:    int
      SCREAMING_SNAKE_CASE				:    int				       =					0
      SCREAMING_SNAKE_CASE				:    int				       =					1
      SCREAMING_SNAKE_CASE				:    Optional[str]				       =					None
      SCREAMING_SNAKE_CASE				:    Optional[str]				       =					None
      SCREAMING_SNAKE_CASE				:    Optional[int]				       =					None
      SCREAMING_SNAKE_CASE				:    Optional[str]				       =					"static"
      SCREAMING_SNAKE_CASE				:    Optional[bool]				       =					False
      SCREAMING_SNAKE_CASE				:    str				       =					"main"

      # args for deepspeed_plugin
      SCREAMING_SNAKE_CASE				:    dict				       =					None
      # args for fsdp
      SCREAMING_SNAKE_CASE				:    dict				       =					None
      # args for megatron_lm
      SCREAMING_SNAKE_CASE				:    dict				       =					None
      # args for ipex
      SCREAMING_SNAKE_CASE				:    dict				       =					None
      # args for TPU
      SCREAMING_SNAKE_CASE				:    bool				       =					False

      # args for TPU pods
      SCREAMING_SNAKE_CASE				:    str				       =					None
      SCREAMING_SNAKE_CASE				:    str				       =					None
      SCREAMING_SNAKE_CASE				:    bool				       =					False
      SCREAMING_SNAKE_CASE				:    bool				       =					False
      SCREAMING_SNAKE_CASE				:    str				       =					None
      SCREAMING_SNAKE_CASE				:    List[str]				       =					None
      SCREAMING_SNAKE_CASE				:    List[str]				       =					None
      SCREAMING_SNAKE_CASE				:    List[str]				       =					None

      # args for dynamo
      SCREAMING_SNAKE_CASE				:    dict				       =					None




      def 							lowerCamelCase     (					self						):
             if self.deepspeed_config is None:
                    UpperCAmelCase__	:   Union[str, Any]												=	{}
             if self.fsdp_config is None:
                    UpperCAmelCase__	:   Any												=	{}
             if self.megatron_lm_config is None:
                    UpperCAmelCase__	:   Tuple												=	{}
             if self.ipex_config is None:
                    UpperCAmelCase__	:   List[str]												=	{}
             return super().__post_init__()




@dataclass
class 					__UpperCAmelCase (		UpperCamelCase__	):

      '''simple docstring'''





      SCREAMING_SNAKE_CASE				:    str
      SCREAMING_SNAKE_CASE				:    str
      SCREAMING_SNAKE_CASE				:    Optional[str]				       =					None
      SCREAMING_SNAKE_CASE				:    Optional[str]				       =					None
      SCREAMING_SNAKE_CASE				:    str				       =					"us-east-1"
      SCREAMING_SNAKE_CASE				:    int				       =					1
      SCREAMING_SNAKE_CASE				:    str				       =					"all"
      SCREAMING_SNAKE_CASE				:    str				       =					F"accelerate-sagemaker-{num_machines}"
      SCREAMING_SNAKE_CASE				:    str				       =					SAGEMAKER_PYTORCH_VERSION
      SCREAMING_SNAKE_CASE				:    str				       =					SAGEMAKER_TRANSFORMERS_VERSION
      SCREAMING_SNAKE_CASE				:    str				       =					SAGEMAKER_PYTHON_VERSION
      SCREAMING_SNAKE_CASE				:    str				       =					None
      SCREAMING_SNAKE_CASE				:    str				       =					None
      SCREAMING_SNAKE_CASE				:    dict				       =					None
      SCREAMING_SNAKE_CASE				:    dict				       =					None