




"""simple docstring"""




import sacrebleu as scb
from packaging import version
from sacrebleu import TER

import datasets


lowerCAmelCase_						=			'\\n@inproceedings{snover-etal-2006-study,\n    title = \"A Study of Translation Edit Rate with Targeted Human Annotation\",\n    author = \"Snover, Matthew  and\n      Dorr, Bonnie  and\n      Schwartz, Rich  and\n      Micciulla, Linnea  and\n      Makhoul, John\",\n    booktitle = \"Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers\",\n    month = aug # \" 8-12\",\n    year = \"2006\",\n    address = \"Cambridge, Massachusetts, USA\",\n    publisher = \"Association for Machine Translation in the Americas\",\n    url = \"https://aclanthology.org/2006.amta-papers.25\",\n    pages = \"223--231\",\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'

lowerCAmelCase_						=			'\\nTER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a\nhypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu\n(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found\nhere: https://github.com/jhclark/tercom.\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#ter for more information.\n'

lowerCAmelCase_						=			'\nProduces TER scores alongside the number of edits and reference length.\n\nArgs:\n    predictions (list of str): The system stream (a sequence of segments).\n    references (list of list of str): A list of one or more reference streams (each a sequence of segments).\n    normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n    ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n    support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,\n                                    as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.\n                                    Only applies if `normalized = True`. Defaults to `False`.\n    case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.\n\nReturns:\n    \'score\' (float): TER score (num_edits / sum_ref_lengths * 100)\n    \'num_edits\' (int): The cumulative number of edits\n    \'ref_length\' (float): The cumulative average reference length\n\nExamples:\n    Example 1:\n        >>> predictions = [\"does this sentence match??\",\n        ...                     \"what about this sentence?\",\n        ...                     \"What did the TER metric user say to the developer?\"]\n        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],\n        ...             [\"Your jokes are...\", \"...TERrible\"]]\n        >>> ter = datasets.load_metric(\"ter\")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         case_sensitive=True)\n        >>> print(results)\n        {\'score\': 150.0, \'num_edits\': 15, \'ref_length\': 10.0}\n\n    Example 2:\n        >>> predictions = [\"does this sentence match??\",\n        ...                     \"what about this sentence?\"]\n        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n        >>> ter = datasets.load_metric(\"ter\")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         case_sensitive=True)\n        >>> print(results)\n        {\'score\': 62.5, \'num_edits\': 5, \'ref_length\': 8.0}\n\n    Example 3:\n        >>> predictions = [\"does this sentence match??\",\n        ...                     \"what about this sentence?\"]\n        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n        >>> ter = datasets.load_metric(\"ter\")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         normalized=True,\n        ...                         case_sensitive=True)\n        >>> print(results)\n        {\'score\': 57.14285714285714, \'num_edits\': 6, \'ref_length\': 10.5}\n\n    Example 4:\n        >>> predictions = [\"does this sentence match??\",\n        ...                     \"what about this sentence?\"]\n        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"]]\n        >>> ter = datasets.load_metric(\"ter\")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         ignore_punct=True,\n        ...                         case_sensitive=False)\n        >>> print(results)\n        {\'score\': 0.0, \'num_edits\': 0, \'ref_length\': 8.0}\n\n    Example 5:\n        >>> predictions = [\"does this sentence match??\",\n        ...                    \"what about this sentence?\",\n        ...                    \"What did the TER metric user say to the developer?\"]\n        >>> references = [[\"does this sentence match\", \"does this sentence match!?!\"],\n        ...             [\"wHaT aBoUt ThIs SeNtEnCe?\", \"wHaT aBoUt ThIs SeNtEnCe?\"],\n        ...             [\"Your jokes are...\", \"...TERrible\"]]\n        >>> ter = datasets.load_metric(\"ter\")\n        >>> results = ter.compute(predictions=predictions,\n        ...                         references=references,\n        ...                         ignore_punct=True,\n        ...                         case_sensitive=False)\n        >>> print(results)\n        {\'score\': 100.0, \'num_edits\': 10, \'ref_length\': 10.0}\n'
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION      ,       _KWARGS_DESCRIPTION				)
class 						_A (  datasets.Metric				):






  def  __a      (  self		:     str				)		->   str:






       """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='''http://www.cs.umd.edu/~snover/tercom/'''				,						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#ter''']				,						reference_urls=[
               '''https://github.com/jhclark/tercom''',
           ]				,						)






  def  __a      (  self		:     Optional[int]				,						_A		:     Any				,						_A		:     List[Any]				,						_A		:     bool = False				,						_A		:     bool = False				,						_A		:     bool = False				,						_A		:     bool = False				,						)		->   Union[str, Any]:






       """simple docstring"""







       lowercase :       Optional[int]       =			len(references[0]				)
       if any(len(_a				) != references_per_prediction for refs in references				):
            raise ValueError('''Sacrebleu requires the same number of references for each prediction'''				)
       lowercase :       Optional[int]       =			[[refs[i] for refs in references] for i in range(_a				)]

       lowercase :       Dict       =			TER(
           normalized=_a				,						no_punct=_a				,						asian_support=_a				,						case_sensitive=_a				,						)
       lowercase :       Optional[Any]       =			sb_ter.corpus_score(_a				,						_a				)

       return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}





import tempfile

import torch

from diffusers import PNDMScheduler

from .test_schedulers import SchedulerCommonTest
class 						_A (  _lowerCamelCase				):
  _UpperCamelCase       :      Tuple			=      (PNDMScheduler,)
  _UpperCamelCase       :      Optional[int]			=      (('''num_inference_steps''', 5_0),)






  def  __a      (  self		:     Union[str, Any]				,						**_A		:     Optional[Any]				)		->   Optional[int]:






       """simple docstring"""







       lowercase :       List[str]       =			{
           '''num_train_timesteps''': 1_000,
           '''beta_start''': 0.0_001,
           '''beta_end''': 0.02,
           '''beta_schedule''': '''linear''',
       }

       config.update(**_A				)
       return config






  def  __a      (  self		:     Optional[Any]				,						_A		:     Any=0				,						**_A		:     int				)		->   Dict:






       """simple docstring"""







       lowercase :       List[Any]       =			dict(self.forward_default_kwargs				)
       lowercase :       Union[str, Any]       =			kwargs.pop('''num_inference_steps'''				,						_A				)
       lowercase :       Optional[Any]       =			self.dummy_sample
       lowercase :       str       =			0.1 * sample
       lowercase :       Union[str, Any]       =			[residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]

       for scheduler_class in self.scheduler_classes:
            lowercase :       Dict       =			self.get_scheduler_config(**_A				)
            lowercase :       int       =			scheduler_class(**_A				)
            scheduler.set_timesteps(_A				)
            # copy over dummy past residuals
            lowercase :       List[str]       =			dummy_past_residuals[:]

            with tempfile.TemporaryDirectory() as tmpdirname:
                 scheduler.save_config(_A				)
                 lowercase :       Union[str, Any]       =			scheduler_class.from_pretrained(_A				)
                 new_scheduler.set_timesteps(_A				)
                 # copy over dummy past residuals
                 lowercase :       int       =			dummy_past_residuals[:]

            lowercase :       List[str]       =			scheduler.step_prk(_A				,						_A				,						_A				,						**_A				).prev_sample
            lowercase :       List[Any]       =			new_scheduler.step_prk(_A				,						_A				,						_A				,						**_A				).prev_sample

            assert torch.sum(torch.abs(output - new_output				)				) < 1E-5, "Scheduler outputs are not identical"

            lowercase :       Dict       =			scheduler.step_plms(_A				,						_A				,						_A				,						**_A				).prev_sample
            lowercase :       List[Any]       =			new_scheduler.step_plms(_A				,						_A				,						_A				,						**_A				).prev_sample

            assert torch.sum(torch.abs(output - new_output				)				) < 1E-5, "Scheduler outputs are not identical"






  def  __a      (  self		:     int				)		->   List[str]:






       """simple docstring"""







       pass






  def  __a      (  self		:     Optional[Any]				,						_A		:     Optional[int]=0				,						**_A		:     str				)		->   Optional[Any]:






       """simple docstring"""







       lowercase :       Optional[int]       =			dict(self.forward_default_kwargs				)
       lowercase :       Optional[int]       =			kwargs.pop('''num_inference_steps'''				,						_A				)
       lowercase :       Union[str, Any]       =			self.dummy_sample
       lowercase :       Any       =			0.1 * sample
       lowercase :       int       =			[residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]

       for scheduler_class in self.scheduler_classes:
            lowercase :       List[str]       =			self.get_scheduler_config()
            lowercase :       List[str]       =			scheduler_class(**_A				)
            scheduler.set_timesteps(_A				)

            # copy over dummy past residuals (must be after setting timesteps)
            lowercase :       Union[str, Any]       =			dummy_past_residuals[:]

            with tempfile.TemporaryDirectory() as tmpdirname:
                 scheduler.save_config(_A				)
                 lowercase :       int       =			scheduler_class.from_pretrained(_A				)
                 # copy over dummy past residuals
                 new_scheduler.set_timesteps(_A				)

                 # copy over dummy past residual (must be after setting timesteps)
                 lowercase :       Optional[Any]       =			dummy_past_residuals[:]

            lowercase :       int       =			scheduler.step_prk(_A				,						_A				,						_A				,						**_A				).prev_sample
            lowercase :       Tuple       =			new_scheduler.step_prk(_A				,						_A				,						_A				,						**_A				).prev_sample

            assert torch.sum(torch.abs(output - new_output				)				) < 1E-5, "Scheduler outputs are not identical"

            lowercase :       Any       =			scheduler.step_plms(_A				,						_A				,						_A				,						**_A				).prev_sample
            lowercase :       Union[str, Any]       =			new_scheduler.step_plms(_A				,						_A				,						_A				,						**_A				).prev_sample

            assert torch.sum(torch.abs(output - new_output				)				) < 1E-5, "Scheduler outputs are not identical"






  def  __a      (  self		:     Union[str, Any]				,						**_A		:     Optional[int]				)		->   Any:






       """simple docstring"""







       lowercase :       str       =			self.scheduler_classes[0]
       lowercase :       Optional[int]       =			self.get_scheduler_config(**_A				)
       lowercase :       int       =			scheduler_class(**_A				)

       lowercase :       Any       =			10
       lowercase :       Optional[int]       =			self.dummy_model()
       lowercase :       Tuple       =			self.dummy_sample_deter
       scheduler.set_timesteps(_A				)

       for i, t in enumerate(scheduler.prk_timesteps				):
            lowercase :       List[str]       =			model(_A				,						_A				)
            lowercase :       Any       =			scheduler.step_prk(_A				,						_A				,						_A				).prev_sample

       for i, t in enumerate(scheduler.plms_timesteps				):
            lowercase :       Dict       =			model(_A				,						_A				)
            lowercase :       List[Any]       =			scheduler.step_plms(_A				,						_A				,						_A				).prev_sample

       return sample






  def  __a      (  self		:     List[Any]				)		->   List[str]:






       """simple docstring"""







       lowercase :       int       =			dict(self.forward_default_kwargs				)

       lowercase :       Union[str, Any]       =			kwargs.pop('''num_inference_steps'''				,						_A				)

       for scheduler_class in self.scheduler_classes:
            lowercase :       Optional[Any]       =			self.get_scheduler_config()
            lowercase :       List[Any]       =			scheduler_class(**_A				)

            lowercase :       Dict       =			self.dummy_sample
            lowercase :       str       =			0.1 * sample

            if num_inference_steps is not None and hasattr(_A				,						'''set_timesteps'''				):
                 scheduler.set_timesteps(_A				)
            elif num_inference_steps is not None and not hasattr(_A				,						'''set_timesteps'''				):
                 lowercase :       List[str]       =			num_inference_steps

            # copy over dummy past residuals (must be done after set_timesteps)
            lowercase :       Any       =			[residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]
            lowercase :       Optional[Any]       =			dummy_past_residuals[:]

            lowercase :       Optional[int]       =			scheduler.step_prk(_A				,						0				,						_A				,						**_A				).prev_sample
            lowercase :       str       =			scheduler.step_prk(_A				,						1				,						_A				,						**_A				).prev_sample

            self.assertEqual(output_a.shape				,						sample.shape				)
            self.assertEqual(output_a.shape				,						output_a.shape				)

            lowercase :       Dict       =			scheduler.step_plms(_A				,						0				,						_A				,						**_A				).prev_sample
            lowercase :       Tuple       =			scheduler.step_plms(_A				,						1				,						_A				,						**_A				).prev_sample

            self.assertEqual(output_a.shape				,						sample.shape				)
            self.assertEqual(output_a.shape				,						output_a.shape				)






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






       """simple docstring"""







       for timesteps in [100, 1_000]:
            self.check_over_configs(num_train_timesteps=_A				)






  def  __a      (  self		:     Tuple				)		->   Any:






       """simple docstring"""







       for steps_offset in [0, 1]:
            self.check_over_configs(steps_offset=_A				)

       lowercase :       str       =			self.scheduler_classes[0]
       lowercase :       int       =			self.get_scheduler_config(steps_offset=1				)
       lowercase :       Union[str, Any]       =			scheduler_class(**_A				)
       scheduler.set_timesteps(10				)
       assert torch.equal(
           scheduler.timesteps				,						torch.LongTensor(
               [901, 851, 851, 801, 801, 751, 751, 701, 701, 651, 651, 601, 601, 501, 401, 301, 201, 101, 1]				)				,						)






  def  __a      (  self		:     int				)		->   Optional[Any]:






       """simple docstring"""







       for beta_start, beta_end in zip([0.0_001, 0.001]				,						[0.002, 0.02]				):
            self.check_over_configs(beta_start=_A				,						beta_end=_A				)






  def  __a      (  self		:     List[str]				)		->   Tuple:






       """simple docstring"""







       for schedule in ["linear", "squaredcos_cap_v2"]:
            self.check_over_configs(beta_schedule=_A				)






  def  __a      (  self		:     List[str]				)		->   Optional[Any]:






       """simple docstring"""







       for prediction_type in ["epsilon", "v_prediction"]:
            self.check_over_configs(prediction_type=_A				)






  def  __a      (  self		:     Tuple				)		->   str:






       """simple docstring"""







       for t in [1, 5, 10]:
            self.check_over_forward(time_step=_A				)






  def  __a      (  self		:     List[Any]				)		->   str:






       """simple docstring"""







       for t, num_inference_steps in zip([1, 5, 10]				,						[10, 50, 100]				):
            self.check_over_forward(num_inference_steps=_A				)






  def  __a      (  self		:     str				)		->   List[Any]:






       """simple docstring"""







       lowercase :       str       =			27

       for scheduler_class in self.scheduler_classes:
            lowercase :       List[str]       =			self.dummy_sample
            lowercase :       Union[str, Any]       =			0.1 * sample

            lowercase :       int       =			self.get_scheduler_config()
            lowercase :       Union[str, Any]       =			scheduler_class(**_A				)

            scheduler.set_timesteps(_A				)

            # before power of 3 fix, would error on first step, so we only need to do two
            for i, t in enumerate(scheduler.prk_timesteps[:2]				):
                 lowercase :       Union[str, Any]       =			scheduler.step_prk(_A				,						_A				,						_A				).prev_sample






  def  __a      (  self		:     List[Any]				)		->   List[Any]:






       """simple docstring"""







       with self.assertRaises(_A				):
            lowercase :       Dict       =			self.scheduler_classes[0]
            lowercase :       Union[str, Any]       =			self.get_scheduler_config()
            lowercase :       Optional[int]       =			scheduler_class(**_A				)

            scheduler.step_plms(self.dummy_sample				,						1				,						self.dummy_sample				).prev_sample






  def  __a      (  self		:     str				)		->   Dict:






       """simple docstring"""







       lowercase :       List[str]       =			self.full_loop()
       lowercase :       List[Any]       =			torch.sum(torch.abs(_A				)				)
       lowercase :       Any       =			torch.mean(torch.abs(_A				)				)

       assert abs(result_sum.item() - 198.1_318				) < 1E-2
       assert abs(result_mean.item() - 0.2_580				) < 1E-3






  def  __a      (  self		:     Union[str, Any]				)		->   List[str]:






       """simple docstring"""







       lowercase :       List[str]       =			self.full_loop(prediction_type='''v_prediction'''				)
       lowercase :       Optional[int]       =			torch.sum(torch.abs(_A				)				)
       lowercase :       Tuple       =			torch.mean(torch.abs(_A				)				)

       assert abs(result_sum.item() - 67.3_986				) < 1E-2
       assert abs(result_mean.item() - 0.0_878				) < 1E-3






  def  __a      (  self		:     str				)		->   Optional[Any]:






       """simple docstring"""







       lowercase :       Any       =			self.full_loop(set_alpha_to_one=_A				,						beta_start=0.01				)
       lowercase :       List[str]       =			torch.sum(torch.abs(_A				)				)
       lowercase :       Optional[int]       =			torch.mean(torch.abs(_A				)				)

       assert abs(result_sum.item() - 230.0_399				) < 1E-2
       assert abs(result_mean.item() - 0.2_995				) < 1E-3






  def  __a      (  self		:     List[str]				)		->   Union[str, Any]:






       """simple docstring"""







       lowercase :       Union[str, Any]       =			self.full_loop(set_alpha_to_one=_A				,						beta_start=0.01				)
       lowercase :       int       =			torch.sum(torch.abs(_A				)				)
       lowercase :       int       =			torch.mean(torch.abs(_A				)				)

       assert abs(result_sum.item() - 186.9_482				) < 1E-2
       assert abs(result_mean.item() - 0.2_434				) < 1E-3