






'''simple docstring'''



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

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


__UpperCamelCase   :							Dict         =   logging.get_logger(__name__)


__UpperCamelCase   :							List[str]         =   {
    """Salesforce/codegen-350M-nl""": """https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json""",
    """Salesforce/codegen-350M-multi""": """https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json""",
    """Salesforce/codegen-350M-mono""": """https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json""",
    """Salesforce/codegen-2B-nl""": """https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json""",
    """Salesforce/codegen-2B-multi""": """https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json""",
    """Salesforce/codegen-2B-mono""": """https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json""",
    """Salesforce/codegen-6B-nl""": """https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json""",
    """Salesforce/codegen-6B-multi""": """https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json""",
    """Salesforce/codegen-6B-mono""": """https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json""",
    """Salesforce/codegen-16B-nl""": """https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json""",
    """Salesforce/codegen-16B-multi""": """https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json""",
    """Salesforce/codegen-16B-mono""": """https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json""",
}
class 				__SCREAMING_SNAKE_CASE							(				_lowerCAmelCase  ):
      __a	       ="codegen"
      __a	       ={
          "max_position_embeddings": "n_positions",
          "hidden_size": "n_embd",
          "num_attention_heads": "n_head",
          "num_hidden_layers": "n_layer",
      }




      def __init__(	self			, lowerCamelCase=5_0400			, lowerCamelCase=2048			, lowerCamelCase=2048			, lowerCamelCase=4096			, lowerCamelCase=28			, lowerCamelCase=16			, lowerCamelCase=64			, lowerCamelCase=None			, lowerCamelCase="gelu_new"			, lowerCamelCase=0.0			, lowerCamelCase=0.0			, lowerCamelCase=0.0			, lowerCamelCase=1e-5			, lowerCamelCase=0.02			, lowerCamelCase=True			, lowerCamelCase=5_0256			, lowerCamelCase=5_0256			, lowerCamelCase=False			, **lowerCamelCase			, )				->int:



         '''simple docstring'''
         __a					  =     vocab_size
         __a					  =     n_ctx
         __a					  =     n_positions
         __a					  =     n_embd
         __a					  =     n_layer
         __a					  =     n_head
         __a					  =     n_inner
         __a					  =     rotary_dim
         __a					  =     activation_function
         __a					  =     resid_pdrop
         __a					  =     embd_pdrop
         __a					  =     attn_pdrop
         __a					  =     layer_norm_epsilon
         __a					  =     initializer_range
         __a					  =     use_cache

         __a					  =     bos_token_id
         __a					  =     eos_token_id

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







class 				__SCREAMING_SNAKE_CASE							(				_lowerCAmelCase  ):




      def __init__(	self			, lowerCamelCase			, lowerCamelCase = "default"			, lowerCamelCase = None			, lowerCamelCase = False			, )				->Tuple:



         '''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?
            __a					  =     0




      @property
      def 			__UpperCamelCase				(	self   )				->Mapping[str, Mapping[int, str]]:



         '''simple docstring'''
         __a					  =     OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}}   )
         if self.use_past:
            self.fill_with_past_key_values_(lowerCamelCase			, direction='inputs'   )
            __a					  =     {0: 'batch', 1: 'past_sequence + sequence'}
         else:
            __a					  =     {0: 'batch', 1: 'sequence'}

         return common_inputs




      @property
      def 			__UpperCamelCase				(	self   )				->int:



         '''simple docstring'''
         return self._config.n_layer




      @property
      def 			__UpperCamelCase				(	self   )				->int:



         '''simple docstring'''
         return self._config.n_head




      def 			__UpperCamelCase				(	self			, lowerCamelCase			, lowerCamelCase = -1			, lowerCamelCase = -1			, lowerCamelCase = False			, lowerCamelCase = None			, )				->Mapping[str, Any]:



         '''simple docstring'''
         __a					  =     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()
         __a					  =     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

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

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

         return ordered_inputs






      @property
      def 			__UpperCamelCase				(	self   )				->int:



         '''simple docstring'''
         return 13







'''simple docstring'''



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

import datasets


__UpperCamelCase   :							List[str]         =   """\
@inproceedings{popovic-2015-chrf,
    title = \"chr{F}: character n-gram {F}-score for automatic {MT} evaluation\",
    author = \"Popovi{\'c}, Maja\",
    booktitle = \"Proceedings of the Tenth Workshop on Statistical Machine Translation\",
    month = sep,
    year = \"2015\",
    address = \"Lisbon, Portugal\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://aclanthology.org/W15-3049\",
    doi = \"10.18653/v1/W15-3049\",
    pages = \"392--395\",
}
@inproceedings{popovic-2017-chrf,
    title = \"chr{F}++: words helping character n-grams\",
    author = \"Popovi{\'c}, Maja\",
    booktitle = \"Proceedings of the Second Conference on Machine Translation\",
    month = sep,
    year = \"2017\",
    address = \"Copenhagen, Denmark\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://aclanthology.org/W17-4770\",
    doi = \"10.18653/v1/W17-4770\",
    pages = \"612--618\",
}
@inproceedings{post-2018-call,
    title = \"A Call for Clarity in Reporting {BLEU} Scores\",
    author = \"Post, Matt\",
    booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",
    month = oct,
    year = \"2018\",
    address = \"Belgium, Brussels\",
    publisher = \"Association for Computational Linguistics\",
    url = \"https://www.aclweb.org/anthology/W18-6319\",
    pages = \"186--191\",
}
"""

__UpperCamelCase   :							Union[str, Any]         =   """\
ChrF and ChrF++ are two MT evaluation metrics. They both use the F-score statistic for character n-gram matches,
and ChrF++ adds word n-grams as well which correlates more strongly with direct assessment. We use the implementation
that is already present in sacrebleu.

The implementation here is slightly different from sacrebleu in terms of the required input format. The length of
the references and hypotheses lists need to be the same, so you may need to transpose your references compared to
sacrebleu's required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534

See the README.md file at https://github.com/mjpost/sacreBLEU#chrf--chrf for more information.
"""

__UpperCamelCase   :							str         =   """
Produces ChrF(++) scores for hypotheses given reference translations.

Args:
    predictions (list of str): The predicted sentences.
    references (list of list of str): The references. There should be one reference sub-list for each prediction sentence.
    char_order (int): Character n-gram order. Defaults to `6`.
    word_order (int): Word n-gram order. If equals to `2`, the metric is referred to as chrF++. Defaults to `0`.
    beta (int): Determine the importance of recall w.r.t precision. Defaults to `2`.
    lowercase (bool): if `True`, enables case-insensitivity. Defaults to `False`.
    whitespace (bool): If `True`, include whitespaces when extracting character n-grams.
    eps_smoothing (bool): If `True`, applies epsilon smoothing similar
    to reference chrF++.py, NLTK and Moses implementations. If `False`,
    it takes into account effective match order similar to sacreBLEU < 2.0.0. Defaults to `False`.

Returns:
    'score' (float): The chrF (chrF++) score,
    'char_order' (int): The character n-gram order,
    'word_order' (int): The word n-gram order. If equals to 2, the metric is referred to as chrF++,
    'beta' (int): Determine the importance of recall w.r.t precision

Examples:
    Example 1--a simple example of calculating chrF:
        >>> 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.\"]
        >>> 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.\"]]
        >>> chrf = datasets.load_metric(\"chrf\")
        >>> results = chrf.compute(predictions=prediction, references=reference)
        >>> print(results)
        {'score': 84.64214891738334, 'char_order': 6, 'word_order': 0, 'beta': 2}

    Example 2--the same example, but with the argument word_order=2, to calculate chrF++ instead of chrF:
        >>> 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.\"]
        >>> 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.\"]]
        >>> chrf = datasets.load_metric(\"chrf\")
        >>> results = chrf.compute(predictions=prediction,
        ...                         references=reference,
        ...                         word_order=2)
        >>> print(results)
        {'score': 82.87263732906315, 'char_order': 6, 'word_order': 2, 'beta': 2}

    Example 3--the same chrF++ example as above, but with `lowercase=True` to normalize all case:
        >>> 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.\"]
        >>> 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.\"]]
        >>> chrf = datasets.load_metric(\"chrf\")
        >>> results = chrf.compute(predictions=prediction,
        ...                         references=reference,
        ...                         word_order=2,
        ...                         lowercase=True)
        >>> print(results)
        {'score': 92.12853119829202, 'char_order': 6, 'word_order': 2, 'beta': 2}
"""
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION   ,   _KWARGS_DESCRIPTION  )
class 				__SCREAMING_SNAKE_CASE							(				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			, lowerCamelCase			, lowerCamelCase			, lowerCamelCase = CHRF.CHAR_ORDER			, lowerCamelCase = CHRF.WORD_ORDER			, lowerCamelCase = CHRF.BETA			, lowerCamelCase = False			, lowerCamelCase = False			, lowerCamelCase = False			, )				->Union[str, Any]:



         '''simple docstring'''
         __a					  =     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'   )
         __a					  =     [[refs[i] for refs in references] for i in range(lowerCamelCase   )]

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

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