






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

import datasets


A_       :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",
}
'''

A_       :Dict       =						'''\
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.
'''

A_       :Any       =						'''
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 				__A     (			datasets.Metric ):





				"""simple docstring"""







				def       __lowercase							( self    ):




									"""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       __lowercase							( self							,  lowerCamelCase__							,  lowerCamelCase__							,  lowerCamelCase__ = CHRF.CHAR_ORDER							,  lowerCamelCase__ = CHRF.WORD_ORDER							,  lowerCamelCase__ = CHRF.BETA							,  lowerCamelCase__ = False							,  lowerCamelCase__ = False							,  lowerCamelCase__ = False							,  ):




									"""simple docstring"""

									__UpperCamelCase      :					List[Any]       		=len(references[0]    )
									if any(len(lowercase_    ) != references_per_prediction for refs in references    ):
														raise ValueError('Sacrebleu requires the same number of references for each prediction'    )
									__UpperCamelCase      :					Dict       		=[[refs[i] for refs in references] for i in range(lowercase_    )]

									__UpperCamelCase      :					int       		=CHRF(lowercase_							,  lowercase_							,  lowercase_							,  lowercase_							,  lowercase_							,  lowercase_    )
									__UpperCamelCase      :					Tuple       		=sb_chrf.corpus_score(lowercase_							,  lowercase_    )

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




import unittest

from parameterized import parameterized

from transformers import OpenLlamaConfig, is_torch_available, set_seed
from transformers.testing_utils import require_torch, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch

       from transformers import OpenLlamaForCausalLM, OpenLlamaForSequenceClassification, OpenLlamaModel







class 						__magic_name__			:

   '''simple docstring'''




   def __init__(				self,    lowercase_,    lowercase_=13,    lowercase_=7,    lowercase_=True,    lowercase_=True,    lowercase_=False,    lowercase_=True,    lowercase_=99,    lowercase_=32,    lowercase_=5,    lowercase_=4,    lowercase_=37,    lowercase_="gelu",    lowercase_=0.1,    lowercase_=0.1,    lowercase_=512,    lowercase_=16,    lowercase_=2,    lowercase_=0.02,    lowercase_=3,    lowercase_=4,    lowercase_=None,    )							->    List[Any]:






     """simple docstring"""






     a__  =parent
     a__  =batch_size
     a__  =seq_length
     a__  =is_training
     a__  =use_input_mask
     a__  =use_token_type_ids
     a__  =use_labels
     a__  =vocab_size
     a__  =hidden_size
     a__  =num_hidden_layers
     a__  =num_attention_heads
     a__  =intermediate_size
     a__  =hidden_act
     a__  =hidden_dropout_prob
     a__  =attention_probs_dropout_prob
     a__  =max_position_embeddings
     a__  =type_vocab_size
     a__  =type_sequence_label_size
     a__  =initializer_range
     a__  =num_labels
     a__  =num_choices
     a__  =scope



   def  _UpperCAmelCase (				self       )							->    Optional[Any]:






     """simple docstring"""






     a__  =ids_tensor([self.batch_size, self.seq_length],    self.vocab_size       )

     a__  =None
     if self.use_input_mask:
       a__  =random_attention_mask([self.batch_size, self.seq_length]       )

     a__  =None
     if self.use_token_type_ids:
       a__  =ids_tensor([self.batch_size, self.seq_length],    self.type_vocab_size       )

     a__  =None
     a__  =None
     a__  =None
     if self.use_labels:
       a__  =ids_tensor([self.batch_size],    self.type_sequence_label_size       )
       a__  =ids_tensor([self.batch_size, self.seq_length],    self.num_labels       )
       a__  =ids_tensor([self.batch_size],    self.num_choices       )

     a__  =self.get_config()

     return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels



   def  _UpperCAmelCase (				self       )							->    List[str]:






     """simple docstring"""






     return OpenLlamaConfig(
         vocab_size=self.vocab_size,    hidden_size=self.hidden_size,    num_hidden_layers=self.num_hidden_layers,    num_attention_heads=self.num_attention_heads,    intermediate_size=self.intermediate_size,    hidden_act=self.hidden_act,    hidden_dropout_prob=self.hidden_dropout_prob,    attention_probs_dropout_prob=self.attention_probs_dropout_prob,    max_position_embeddings=self.max_position_embeddings,    type_vocab_size=self.type_vocab_size,    is_decoder=lowercase_,    initializer_range=self.initializer_range,    use_stable_embedding=lowercase_,    )



   def  _UpperCAmelCase (				self,    lowercase_,    lowercase_,    lowercase_,    lowercase_,    lowercase_,    lowercase_,    lowercase_       )							->    List[str]:






     """simple docstring"""






     a__  =OpenLlamaModel(config=lowercase_       )
     model.to(lowercase_       )
     model.eval()
     a__  =model(lowercase_,    attention_mask=lowercase_       )
     a__  =model(lowercase_       )
     self.parent.assertEqual(result.last_hidden_state.shape,    (self.batch_size, self.seq_length, self.hidden_size)       )



   def  _UpperCAmelCase (				self,    lowercase_,    lowercase_,    lowercase_,    lowercase_,    lowercase_,    lowercase_,    lowercase_,    lowercase_,    lowercase_,    )							->    Any:






     """simple docstring"""






     a__  =True
     a__  =OpenLlamaModel(lowercase_       )
     model.to(lowercase_       )
     model.eval()
     a__  =model(
         lowercase_,    attention_mask=lowercase_,    encoder_hidden_states=lowercase_,    encoder_attention_mask=lowercase_,    )
     a__  =model(
         lowercase_,    attention_mask=lowercase_,    encoder_hidden_states=lowercase_,    )
     a__  =model(lowercase_,    attention_mask=lowercase_       )
     self.parent.assertEqual(result.last_hidden_state.shape,    (self.batch_size, self.seq_length, self.hidden_size)       )



   def  _UpperCAmelCase (				self,    lowercase_,    lowercase_,    lowercase_,    lowercase_,    lowercase_,    lowercase_,    lowercase_,    lowercase_,    lowercase_,    )							->    List[str]:






     """simple docstring"""






     a__  =OpenLlamaForCausalLM(config=lowercase_       )
     model.to(lowercase_       )
     model.eval()
     a__  =model(lowercase_,    attention_mask=lowercase_,    labels=lowercase_       )
     self.parent.assertEqual(result.logits.shape,    (self.batch_size, self.seq_length, self.vocab_size)       )



   def  _UpperCAmelCase (				self,    lowercase_,    lowercase_,    lowercase_,    lowercase_,    lowercase_,    lowercase_,    lowercase_,    lowercase_,    lowercase_,    )							->    List[Any]:






     """simple docstring"""






     a__  =True
     a__  =True
     a__  =OpenLlamaForCausalLM(config=lowercase_       )
     model.to(lowercase_       )
     model.eval()

     # first forward pass
     a__  =model(
         lowercase_,    attention_mask=lowercase_,    encoder_hidden_states=lowercase_,    encoder_attention_mask=lowercase_,    use_cache=lowercase_,    )
     a__  =outputs.past_key_values

     # create hypothetical multiple next token and extent to next_input_ids
     a__  =ids_tensor((self.batch_size, 3),    config.vocab_size       )
     a__  =ids_tensor((self.batch_size, 3),    vocab_size=2       )

     # append to next input_ids and
     a__  =torch.cat([input_ids, next_tokens],    dim=-1       )
     a__  =torch.cat([input_mask, next_mask],    dim=-1       )

     a__  =model(
         lowercase_,    attention_mask=lowercase_,    encoder_hidden_states=lowercase_,    encoder_attention_mask=lowercase_,    output_hidden_states=lowercase_,    )['''hidden_states'''][0]
     a__  =model(
         lowercase_,    attention_mask=lowercase_,    encoder_hidden_states=lowercase_,    encoder_attention_mask=lowercase_,    past_key_values=lowercase_,    output_hidden_states=lowercase_,    )['''hidden_states'''][0]

     # select random slice
     a__  =ids_tensor((1,),    output_from_past.shape[-1]       ).item()
     a__  =output_from_no_past[:, -3:, random_slice_idx].detach()
     a__  =output_from_past[:, :, random_slice_idx].detach()

     self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1]       )

     # test that outputs are equal for slice
     self.parent.assertTrue(torch.allclose(lowercase_,    lowercase_,    atol=1E-3       )       )



   def  _UpperCAmelCase (				self       )							->    Optional[int]:






     """simple docstring"""






     a__  =self.prepare_config_and_inputs()
     (
         (
         a__
     ),      (
         a__
     ),      (
         a__
     ),      (
         a__
     ),      (
         a__
     ),      (
         a__
     ),      (
         a__
     ),      
     )  =config_and_inputs
     a__  ={'''input_ids''': input_ids, '''attention_mask''': input_mask}
     return config, inputs_dict







@require_torch
class 						__magic_name__			(							lowerCamelCase__		,       lowerCamelCase__		,       lowerCamelCase__		,       unittest.TestCase							):

   '''simple docstring'''




   lowerCamelCase__ :	Optional[Any]    =   (
       (OpenLlamaModel, OpenLlamaForCausalLM, OpenLlamaForSequenceClassification) if is_torch_available() else ()
   )
   lowerCamelCase__ :	Optional[Any]    =   (OpenLlamaForCausalLM,) if is_torch_available() else ()
   lowerCamelCase__ :	List[str]    =   (
       {
           'feature-extraction': OpenLlamaModel,
           'text-classification': OpenLlamaForSequenceClassification,
           'text-generation': OpenLlamaForCausalLM,
           'zero-shot': OpenLlamaForSequenceClassification,
       }
       if is_torch_available()
       else {}
   )
   lowerCamelCase__ :	int    =   False
   lowerCamelCase__ :	Any    =   False



   def  _UpperCAmelCase (				self       )							->    List[str]:






     """simple docstring"""






     a__  =OpenLlamaModelTester(self       )
     a__  =ConfigTester(self,    config_class=lowercase_,    hidden_size=37       )



   def  _UpperCAmelCase (				self       )							->    str:






     """simple docstring"""






     self.config_tester.run_common_tests()



   def  _UpperCAmelCase (				self       )							->    Optional[Any]:






     """simple docstring"""






     a__  =self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowercase_       )



   def  _UpperCAmelCase (				self       )							->    str:






     """simple docstring"""






     a__  =self.model_tester.prepare_config_and_inputs()
     for type in ["absolute", "relative_key", "relative_key_query"]:
       a__  =type
       self.model_tester.create_and_check_model(*lowercase_       )



   def  _UpperCAmelCase (				self       )							->    int:






     """simple docstring"""






     a__,      a__  =self.model_tester.prepare_config_and_inputs_for_common()
     a__  =3
     a__  =input_dict['''input_ids''']
     a__  =input_ids.ne(1       ).to(lowercase_       )
     a__  =ids_tensor([self.model_tester.batch_size],    self.model_tester.type_sequence_label_size       )
     a__  =OpenLlamaForSequenceClassification(lowercase_       )
     model.to(lowercase_       )
     model.eval()
     a__  =model(lowercase_,    attention_mask=lowercase_,    labels=lowercase_       )
     self.assertEqual(result.logits.shape,    (self.model_tester.batch_size, self.model_tester.num_labels)       )



   def  _UpperCAmelCase (				self       )							->    Any:






     """simple docstring"""






     a__,      a__  =self.model_tester.prepare_config_and_inputs_for_common()
     a__  =3
     a__  ='''single_label_classification'''
     a__  =input_dict['''input_ids''']
     a__  =input_ids.ne(1       ).to(lowercase_       )
     a__  =ids_tensor([self.model_tester.batch_size],    self.model_tester.type_sequence_label_size       )
     a__  =OpenLlamaForSequenceClassification(lowercase_       )
     model.to(lowercase_       )
     model.eval()
     a__  =model(lowercase_,    attention_mask=lowercase_,    labels=lowercase_       )
     self.assertEqual(result.logits.shape,    (self.model_tester.batch_size, self.model_tester.num_labels)       )



   def  _UpperCAmelCase (				self       )							->    Optional[int]:






     """simple docstring"""






     a__,      a__  =self.model_tester.prepare_config_and_inputs_for_common()
     a__  =3
     a__  ='''multi_label_classification'''
     a__  =input_dict['''input_ids''']
     a__  =input_ids.ne(1       ).to(lowercase_       )
     a__  =ids_tensor(
         [self.model_tester.batch_size, config.num_labels],    self.model_tester.type_sequence_label_size       ).to(torch.float       )
     a__  =OpenLlamaForSequenceClassification(lowercase_       )
     model.to(lowercase_       )
     model.eval()
     a__  =model(lowercase_,    attention_mask=lowercase_,    labels=lowercase_       )
     self.assertEqual(result.logits.shape,    (self.model_tester.batch_size, self.model_tester.num_labels)       )



   @unittest.skip('''Open-Llama buffers include complex numbers, which breaks this test'''       )
   def  _UpperCAmelCase (				self       )							->    List[str]:






     """simple docstring"""






     pass



   @parameterized.expand([('''linear''',), ('''dynamic''',)]       )
   def  _UpperCAmelCase (				self,    lowercase_       )							->    Optional[Any]:






     """simple docstring"""






     a__,      a__  =self.model_tester.prepare_config_and_inputs_for_common()
     a__  =ids_tensor([1, 10],    config.vocab_size       )
     a__  =ids_tensor([1, int(config.max_position_embeddings * 1.5       )],    config.vocab_size       )

     set_seed(42       )  # Fixed seed at init time so the two models get the same random weights
     a__  =OpenLlamaModel(lowercase_       )
     original_model.to(lowercase_       )
     original_model.eval()
     a__  =original_model(lowercase_       ).last_hidden_state
     a__  =original_model(lowercase_       ).last_hidden_state

     set_seed(42       )  # Fixed seed at init time so the two models get the same random weights
     a__  ={'''type''': scaling_type, '''factor''': 10.0}
     a__  =OpenLlamaModel(lowercase_       )
     scaled_model.to(lowercase_       )
     scaled_model.eval()
     a__  =scaled_model(lowercase_       ).last_hidden_state
     a__  =scaled_model(lowercase_       ).last_hidden_state

     # Dynamic scaling does not change the RoPE embeddings until it receives an input longer than the original
     # maximum sequence length, so the outputs for the short input should match.
     if scaling_type == "dynamic":
       self.assertTrue(torch.allclose(lowercase_,    lowercase_,    atol=1E-5       )       )
     else:
       self.assertFalse(torch.allclose(lowercase_,    lowercase_,    atol=1E-5       )       )

     # The output should be different for long inputs
     self.assertFalse(torch.allclose(lowercase_,    lowercase_,    atol=1E-5       )       )
