





'''simple docstring'''

import sacrebleu as scb
from packaging import version
from sacrebleu import CHRF

import datasets


a   	=    "\\n@inproceedings{popovic-2015-chrf,\n    title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",\n    author = \"Popovi{\'c}, Maja\",\n    booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",\n    month = sep,\n    year = \"2015\",\n    address = \"Lisbon, Portugal\",\n    publisher = \"Association for Computational Linguistics\",\n    url = \"https://aclanthology.org/W15-3049\",\n    doi = \"10.18653/v1/W15-3049\",\n    pages = \"392--395\",\n}\n@inproceedings{popovic-2017-chrf,\n    title = \"chr{F}++: words helping character n-grams\",\n    author = \"Popovi{\'c}, Maja\",\n    booktitle = \"Proceedings of the Second Conference on Machine Translation\",\n    month = sep,\n    year = \"2017\",\n    address = \"Copenhagen, Denmark\",\n    publisher = \"Association for Computational Linguistics\",\n    url = \"https://aclanthology.org/W17-4770\",\n    doi = \"10.18653/v1/W17-4770\",\n    pages = \"612--618\",\n}\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"

a   	=    "\\nChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,\nand ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation\nthat is already present in sacrebleu.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.\n"

a   	=    "\nProduces ChrF(++) scores for hypotheses given reference translations.\n\nArgs:\n    predictions (list of str): The predicted sentences.\n    references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.\n    char_order (int): Character n-gram order. Defaults to `6`.\n    word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.\n    beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.\n    lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.\n    whitespace (bool): If `True`, include whitespaces when extracting character n-grams.\n    eps_smoothing (bool): If `True`, applies epsilon smoothing similar\n    to reference chrF++.py, NLTK and Moses implementations. If `False`,\n    it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.\n\nReturns:\n    'score' (float): The chrF (chrF++) score,\n    'char_order' (int): The character n-gram order,\n    'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,\n    'beta' (int): Determine the importance of recall w.r.t precision\n\nExamples:\n    Example 1--a simple example of calculating chrF:\n        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n        >>> chrf = datasets.load_metric(\"chrf\")\n        >>> results = chrf.compute(predictions=prediction, references=reference)\n        >>> print(results)\n        {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}\n\n    Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:\n        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n        >>> chrf = datasets.load_metric(\"chrf\")\n        >>> results = chrf.compute(predictions=prediction,\n        ...                         references=reference,\n        ...                         word_order=2)\n        >>> print(results)\n        {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}\n\n    Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:\n        >>> prediction = [\"The relationship between cats and dogs is not exactly friendly.\", \"a good bookshop is just a genteel black hole that knows how to read.\"]\n        >>> reference = [[\"The relationship between dogs and cats is not exactly friendly.\"], [\"A good bookshop is just a genteel Black Hole that knows how to read.\"]]\n        >>> chrf = datasets.load_metric(\"chrf\")\n        >>> results = chrf.compute(predictions=prediction,\n        ...                         references=reference,\n        ...                         word_order=2,\n        ...                         lowercase=True)\n        >>> print(results)\n        {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}\n"







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





   def   UpperCAmelCase__  (       self					:      Union[str, Any]     ):

      '''simple docstring'''

      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#chrf--chrf"""					,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#chrf--chrf"""]					,reference_urls=[
              """https://github.com/m-popovic/chrF""",
          ]					,)





   def   UpperCAmelCase__  (       self					:      str					,lowerCamelCase					:      List[str]					,lowerCamelCase					:      Any					,lowerCamelCase					:      int = CHRF.CHAR_ORDER					,lowerCamelCase					:      int = CHRF.WORD_ORDER					,lowerCamelCase					:      int = CHRF.BETA					,lowerCamelCase					:      bool = False					,lowerCamelCase					:      bool = False					,lowerCamelCase					:      bool = False					,):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							len(references[0]     )
      if any(len(lowerCamelCase     ) != references_per_prediction for refs in references     ):
         raise ValueError("""Sacrebleu requires the same number of references for each prediction"""     )
      __SCREAMING_SNAKE_CASE   				=							[[refs[i] for refs in references] for i in range(lowerCamelCase     )]

      __SCREAMING_SNAKE_CASE   				=							CHRF(lowerCamelCase					,lowerCamelCase					,lowerCamelCase					,lowerCamelCase					,lowerCamelCase					,lowerCamelCase     )
      __SCREAMING_SNAKE_CASE   				=							sb_chrf.corpus_score(lowerCamelCase					,lowerCamelCase     )

      return {
          "score": output.score,
          "char_order": output.char_order,
          "word_order": output.word_order,
          "beta": output.beta,
      }












'''simple docstring'''

from collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional

from packaging import version


if TYPE_CHECKING:
    from ... import PreTrainedTokenizer, TensorType

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import is_torch_available, logging


a   	=    logging.get_logger(__name__)

a   	=    {
    "bigscience/bloom": "https://huggingface.co/bigscience/bloom/resolve/main/config.json",
    "bigscience/bloom-560m": "https://huggingface.co/bigscience/bloom-560m/blob/main/config.json",
    "bigscience/bloom-1b1": "https://huggingface.co/bigscience/bloom-1b1/blob/main/config.json",
    "bigscience/bloom-1b7": "https://huggingface.co/bigscience/bloom-1b7/blob/main/config.json",
    "bigscience/bloom-3b": "https://huggingface.co/bigscience/bloom-3b/blob/main/config.json",
    "bigscience/bloom-7b1": "https://huggingface.co/bigscience/bloom-7b1/blob/main/config.json",
}







class __a			( _snake_case      ):
   __UpperCamelCase :			List[str]						   =						'bloom'
   __UpperCamelCase :			Optional[Any]						   =						['past_key_values']
   __UpperCamelCase :			Optional[int]						   =						{
       'num_hidden_layers': 'n_layer',
       'num_attention_heads': 'n_head',
   }





   def __init__(       self					:      Union[str, Any]					,lowerCamelCase					:      str=25_0880					,lowerCamelCase					:      List[Any]=64					,lowerCamelCase					:      Optional[Any]=2					,lowerCamelCase					:      Tuple=8					,lowerCamelCase					:      Union[str, Any]=1E-5					,lowerCamelCase					:      Optional[Any]=0.02					,lowerCamelCase					:      str=True					,lowerCamelCase					:      List[Any]=1					,lowerCamelCase					:      Union[str, Any]=2					,lowerCamelCase					:      Optional[int]=False					,lowerCamelCase					:      Optional[int]=0.0					,lowerCamelCase					:      List[Any]=0.0					,lowerCamelCase					:      Optional[Any]=1					,lowerCamelCase					:      Tuple=False					,**lowerCamelCase					:      str					,):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							vocab_size
      # Backward compatibility with n_embed kwarg
      __SCREAMING_SNAKE_CASE   				=							kwargs.pop("""n_embed"""					,lowerCamelCase     )
      __SCREAMING_SNAKE_CASE   				=							hidden_size if n_embed is None else n_embed
      __SCREAMING_SNAKE_CASE   				=							n_layer
      __SCREAMING_SNAKE_CASE   				=							n_head
      __SCREAMING_SNAKE_CASE   				=							layer_norm_epsilon
      __SCREAMING_SNAKE_CASE   				=							initializer_range
      __SCREAMING_SNAKE_CASE   				=							use_cache
      __SCREAMING_SNAKE_CASE   				=							pretraining_tp
      __SCREAMING_SNAKE_CASE   				=							apply_residual_connection_post_layernorm
      __SCREAMING_SNAKE_CASE   				=							hidden_dropout
      __SCREAMING_SNAKE_CASE   				=							attention_dropout

      __SCREAMING_SNAKE_CASE   				=							bos_token_id
      __SCREAMING_SNAKE_CASE   				=							eos_token_id
      __SCREAMING_SNAKE_CASE   				=							slow_but_exact

      super().__init__(bos_token_id=lowerCamelCase					,eos_token_id=lowerCamelCase					,**lowerCamelCase     )







class __a			( _snake_case      ):
   __UpperCamelCase :			int						   =						version.parse('1.12'      )





   def __init__(       self					:      Optional[int]					,lowerCamelCase					:      PretrainedConfig					,lowerCamelCase					:      str = "default"					,lowerCamelCase					:      List[PatchingSpec] = None					,lowerCamelCase					:      bool = False					,):

      '''simple docstring'''

      super().__init__(lowerCamelCase					,task=lowerCamelCase					,patching_specs=lowerCamelCase					,use_past=lowerCamelCase     )
      if not getattr(self._config					,"""pad_token_id"""					,lowerCamelCase     ):
         # TODO: how to do that better?
         __SCREAMING_SNAKE_CASE   				=							0





   @property
   def   UpperCAmelCase__  (       self					:      int     ):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							OrderedDict({"""input_ids""": {0: """batch""", 1: """sequence"""}}     )
      if self.use_past:
         # BLOOM stores values on dynamic axis 2. For more details see: https://github.com/huggingface/transformers/pull/18344
         self.fill_with_past_key_values_(lowerCamelCase					,direction="""inputs"""					,inverted_values_shape=lowerCamelCase     )
         __SCREAMING_SNAKE_CASE   				=							{0: """batch""", 1: """past_sequence + sequence"""}
      else:
         __SCREAMING_SNAKE_CASE   				=							{0: """batch""", 1: """sequence"""}

      return common_inputs





   @property
   def   UpperCAmelCase__  (       self					:      Tuple     ):

      '''simple docstring'''

      return self._config.n_layer





   @property
   def   UpperCAmelCase__  (       self					:      Dict     ):

      '''simple docstring'''

      return self._config.n_head





   @property
   def   UpperCAmelCase__  (       self					:      str     ):

      '''simple docstring'''

      return 1E-3





   def   UpperCAmelCase__  (       self					:      str					,lowerCamelCase					:      "PreTrainedTokenizer"					,lowerCamelCase					:      int = -1					,lowerCamelCase					:      int = -1					,lowerCamelCase					:      bool = False					,lowerCamelCase					:      Optional["TensorType"] = None					,):

      '''simple docstring'''

      __SCREAMING_SNAKE_CASE   				=							super(lowerCamelCase					,self     ).generate_dummy_inputs(
          lowerCamelCase					,batch_size=lowerCamelCase					,seq_length=lowerCamelCase					,is_pair=lowerCamelCase					,framework=lowerCamelCase     )

      # We need to order the input in the way they appears in the forward()
      __SCREAMING_SNAKE_CASE   				=							OrderedDict({"""input_ids""": common_inputs["""input_ids"""]}     )

      # Need to add the past_keys
      if self.use_past:
         if not is_torch_available():
            raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""     )
         else:
            import torch

            __SCREAMING_SNAKE_CASE				,  __SCREAMING_SNAKE_CASE   				=							common_inputs["""input_ids"""].shape
            # Not using the same length for past_key_values
            __SCREAMING_SNAKE_CASE   				=							seqlen + 2
            __SCREAMING_SNAKE_CASE   				=							self._config.hidden_size // self.num_attention_heads
            __SCREAMING_SNAKE_CASE   				=							(
                batch * self.num_attention_heads,
                head_dim,
                past_key_values_length,
            )
            __SCREAMING_SNAKE_CASE   				=							(
                batch * self.num_attention_heads,
                past_key_values_length,
                head_dim,
            )
            __SCREAMING_SNAKE_CASE   				=							[
                (torch.zeros(lowerCamelCase     ), torch.zeros(lowerCamelCase     )) for _ in range(self.num_layers     )
            ]

      __SCREAMING_SNAKE_CASE   				=							common_inputs["""attention_mask"""]
      if self.use_past:
         __SCREAMING_SNAKE_CASE   				=							ordered_inputs["""attention_mask"""].dtype
         __SCREAMING_SNAKE_CASE   				=							torch.cat(
             [ordered_inputs["""attention_mask"""], torch.ones(lowerCamelCase					,lowerCamelCase					,dtype=lowerCamelCase     )]					,dim=1     )

      return ordered_inputs





   @property
   def   UpperCAmelCase__  (       self					:      str     ):

      '''simple docstring'''

      return 13





