


'''simple docstring'''




import tempfile

import torch

from diffusers import PNDMScheduler

from .test_schedulers import SchedulerCommonTest

class 		UpperCAmelCase_      (  __lowercase		):
     lowerCamelCase				:	Tuple		=     (PNDMScheduler,)
     lowerCamelCase				:	Optional[int]		=     (('''num_inference_steps''', 50),)





     def 							__UpperCAmelCase      ( self       :      int    ,      **UpperCAmelCase__       :      List[str]    )				->  Dict:
        lowerCAmelCase     =			{
            'num_train_timesteps': 1_0_0_0,
            'beta_start': 0.0_001,
            'beta_end': 0.02,
            'beta_schedule': 'linear',
        }

        config.update(**UpperCAmelCase__    )
        return config





     def 							__UpperCAmelCase      ( self       :      Optional[int]    ,      UpperCAmelCase__       :      Any=0    ,      **UpperCAmelCase__       :      List[Any]    )				->  Tuple:
        lowerCAmelCase     =			dict(self.forward_default_kwargs    )
        lowerCAmelCase     =			kwargs.pop('num_inference_steps'    ,      UpperCAmelCase__    )
        lowerCAmelCase     =			self.dummy_sample
        lowerCAmelCase     =			0.1 * sample
        lowerCAmelCase     =			[residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]

        for scheduler_class in self.scheduler_classes:
           lowerCAmelCase     =			self.get_scheduler_config(**UpperCAmelCase__    )
           lowerCAmelCase     =			scheduler_class(**UpperCAmelCase__    )
           scheduler.set_timesteps(UpperCAmelCase__    )
           # copy over dummy past residuals
           lowerCAmelCase     =			dummy_past_residuals[:]

           with tempfile.TemporaryDirectory() as tmpdirname:
              scheduler.save_config(UpperCAmelCase__    )
              lowerCAmelCase     =			scheduler_class.from_pretrained(UpperCAmelCase__    )
              new_scheduler.set_timesteps(UpperCAmelCase__    )
              # copy over dummy past residuals
              lowerCAmelCase     =			dummy_past_residuals[:]

           lowerCAmelCase     =			scheduler.step_prk(UpperCAmelCase__    ,      UpperCAmelCase__    ,      UpperCAmelCase__    ,      **UpperCAmelCase__    ).prev_sample
           lowerCAmelCase     =			new_scheduler.step_prk(UpperCAmelCase__    ,      UpperCAmelCase__    ,      UpperCAmelCase__    ,      **UpperCAmelCase__    ).prev_sample

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

           lowerCAmelCase     =			scheduler.step_plms(UpperCAmelCase__    ,      UpperCAmelCase__    ,      UpperCAmelCase__    ,      **UpperCAmelCase__    ).prev_sample
           lowerCAmelCase     =			new_scheduler.step_plms(UpperCAmelCase__    ,      UpperCAmelCase__    ,      UpperCAmelCase__    ,      **UpperCAmelCase__    ).prev_sample

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





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





     def 							__UpperCAmelCase      ( self       :      Tuple    ,      UpperCAmelCase__       :      Optional[int]=0    ,      **UpperCAmelCase__       :      Tuple    )				->  List[str]:
        lowerCAmelCase     =			dict(self.forward_default_kwargs    )
        lowerCAmelCase     =			kwargs.pop('num_inference_steps'    ,      UpperCAmelCase__    )
        lowerCAmelCase     =			self.dummy_sample
        lowerCAmelCase     =			0.1 * sample
        lowerCAmelCase     =			[residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]

        for scheduler_class in self.scheduler_classes:
           lowerCAmelCase     =			self.get_scheduler_config()
           lowerCAmelCase     =			scheduler_class(**UpperCAmelCase__    )
           scheduler.set_timesteps(UpperCAmelCase__    )

           # copy over dummy past residuals (must be after setting timesteps)
           lowerCAmelCase     =			dummy_past_residuals[:]

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

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

           lowerCAmelCase     =			scheduler.step_prk(UpperCAmelCase__    ,      UpperCAmelCase__    ,      UpperCAmelCase__    ,      **UpperCAmelCase__    ).prev_sample
           lowerCAmelCase     =			new_scheduler.step_prk(UpperCAmelCase__    ,      UpperCAmelCase__    ,      UpperCAmelCase__    ,      **UpperCAmelCase__    ).prev_sample

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

           lowerCAmelCase     =			scheduler.step_plms(UpperCAmelCase__    ,      UpperCAmelCase__    ,      UpperCAmelCase__    ,      **UpperCAmelCase__    ).prev_sample
           lowerCAmelCase     =			new_scheduler.step_plms(UpperCAmelCase__    ,      UpperCAmelCase__    ,      UpperCAmelCase__    ,      **UpperCAmelCase__    ).prev_sample

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





     def 							__UpperCAmelCase      ( self       :      Dict    ,      **UpperCAmelCase__       :      Tuple    )				->  str:
        lowerCAmelCase     =			self.scheduler_classes[0]
        lowerCAmelCase     =			self.get_scheduler_config(**UpperCAmelCase__    )
        lowerCAmelCase     =			scheduler_class(**UpperCAmelCase__    )

        lowerCAmelCase     =			1_0
        lowerCAmelCase     =			self.dummy_model()
        lowerCAmelCase     =			self.dummy_sample_deter
        scheduler.set_timesteps(UpperCAmelCase__    )

        for i, t in enumerate(scheduler.prk_timesteps    ):
           lowerCAmelCase     =			model(UpperCAmelCase__    ,      UpperCAmelCase__    )
           lowerCAmelCase     =			scheduler.step_prk(UpperCAmelCase__    ,      UpperCAmelCase__    ,      UpperCAmelCase__    ).prev_sample

        for i, t in enumerate(scheduler.plms_timesteps    ):
           lowerCAmelCase     =			model(UpperCAmelCase__    ,      UpperCAmelCase__    )
           lowerCAmelCase     =			scheduler.step_plms(UpperCAmelCase__    ,      UpperCAmelCase__    ,      UpperCAmelCase__    ).prev_sample

        return sample





     def 							__UpperCAmelCase      ( self       :      Tuple    )				->  List[Any]:
        lowerCAmelCase     =			dict(self.forward_default_kwargs    )

        lowerCAmelCase     =			kwargs.pop('num_inference_steps'    ,      UpperCAmelCase__    )

        for scheduler_class in self.scheduler_classes:
           lowerCAmelCase     =			self.get_scheduler_config()
           lowerCAmelCase     =			scheduler_class(**UpperCAmelCase__    )

           lowerCAmelCase     =			self.dummy_sample
           lowerCAmelCase     =			0.1 * sample

           if num_inference_steps is not None and hasattr(UpperCAmelCase__    ,      'set_timesteps'    ):
              scheduler.set_timesteps(UpperCAmelCase__    )
           elif num_inference_steps is not None and not hasattr(UpperCAmelCase__    ,      'set_timesteps'    ):
              lowerCAmelCase     =			num_inference_steps

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

           lowerCAmelCase     =			scheduler.step_prk(UpperCAmelCase__    ,      0    ,      UpperCAmelCase__    ,      **UpperCAmelCase__    ).prev_sample
           lowerCAmelCase     =			scheduler.step_prk(UpperCAmelCase__    ,      1    ,      UpperCAmelCase__    ,      **UpperCAmelCase__    ).prev_sample

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

           lowerCAmelCase     =			scheduler.step_plms(UpperCAmelCase__    ,      0    ,      UpperCAmelCase__    ,      **UpperCAmelCase__    ).prev_sample
           lowerCAmelCase     =			scheduler.step_plms(UpperCAmelCase__    ,      1    ,      UpperCAmelCase__    ,      **UpperCAmelCase__    ).prev_sample

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





     def 							__UpperCAmelCase      ( self       :      int    )				->  Tuple:
        for timesteps in [1_0_0, 1_0_0_0]:
           self.check_over_configs(num_train_timesteps=UpperCAmelCase__    )





     def 							__UpperCAmelCase      ( self       :      Dict    )				->  Optional[int]:
        for steps_offset in [0, 1]:
           self.check_over_configs(steps_offset=UpperCAmelCase__    )

        lowerCAmelCase     =			self.scheduler_classes[0]
        lowerCAmelCase     =			self.get_scheduler_config(steps_offset=1    )
        lowerCAmelCase     =			scheduler_class(**UpperCAmelCase__    )
        scheduler.set_timesteps(1_0    )
        assert torch.equal(
            scheduler.timesteps    ,      torch.LongTensor(
                [9_0_1, 8_5_1, 8_5_1, 8_0_1, 8_0_1, 7_5_1, 7_5_1, 7_0_1, 7_0_1, 6_5_1, 6_5_1, 6_0_1, 6_0_1, 5_0_1, 4_0_1, 3_0_1, 2_0_1, 1_0_1, 1]    )    ,      )





     def 							__UpperCAmelCase      ( self       :      Optional[int]    )				->  Any:
        for beta_start, beta_end in zip([0.0_001, 0.001]    ,      [0.002, 0.02]    ):
           self.check_over_configs(beta_start=UpperCAmelCase__    ,      beta_end=UpperCAmelCase__    )





     def 							__UpperCAmelCase      ( self       :      Dict    )				->  Tuple:
        for schedule in ["linear", "squaredcos_cap_v2"]:
           self.check_over_configs(beta_schedule=UpperCAmelCase__    )





     def 							__UpperCAmelCase      ( self       :      List[Any]    )				->  int:
        for prediction_type in ["epsilon", "v_prediction"]:
           self.check_over_configs(prediction_type=UpperCAmelCase__    )





     def 							__UpperCAmelCase      ( self       :      Dict    )				->  Union[str, Any]:
        for t in [1, 5, 1_0]:
           self.check_over_forward(time_step=UpperCAmelCase__    )





     def 							__UpperCAmelCase      ( self       :      str    )				->  str:
        for t, num_inference_steps in zip([1, 5, 1_0]    ,      [1_0, 5_0, 1_0_0]    ):
           self.check_over_forward(num_inference_steps=UpperCAmelCase__    )





     def 							__UpperCAmelCase      ( self       :      Tuple    )				->  str:
        # earlier version of set_timesteps() caused an error indexing alpha's with inference steps as power of 3
        lowerCAmelCase     =			2_7

        for scheduler_class in self.scheduler_classes:
           lowerCAmelCase     =			self.dummy_sample
           lowerCAmelCase     =			0.1 * sample

           lowerCAmelCase     =			self.get_scheduler_config()
           lowerCAmelCase     =			scheduler_class(**UpperCAmelCase__    )

           scheduler.set_timesteps(UpperCAmelCase__    )

           # 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]    ):
              lowerCAmelCase     =			scheduler.step_prk(UpperCAmelCase__    ,      UpperCAmelCase__    ,      UpperCAmelCase__    ).prev_sample





     def 							__UpperCAmelCase      ( self       :      Union[str, Any]    )				->  int:
        with self.assertRaises(UpperCAmelCase__    ):
           lowerCAmelCase     =			self.scheduler_classes[0]
           lowerCAmelCase     =			self.get_scheduler_config()
           lowerCAmelCase     =			scheduler_class(**UpperCAmelCase__    )

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





     def 							__UpperCAmelCase      ( self       :      Optional[Any]    )				->  List[Any]:
        lowerCAmelCase     =			self.full_loop()
        lowerCAmelCase     =			torch.sum(torch.abs(UpperCAmelCase__    )    )
        lowerCAmelCase     =			torch.mean(torch.abs(UpperCAmelCase__    )    )

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





     def 							__UpperCAmelCase      ( self       :      List[Any]    )				->  List[Any]:
        lowerCAmelCase     =			self.full_loop(prediction_type='v_prediction'    )
        lowerCAmelCase     =			torch.sum(torch.abs(UpperCAmelCase__    )    )
        lowerCAmelCase     =			torch.mean(torch.abs(UpperCAmelCase__    )    )

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





     def 							__UpperCAmelCase      ( self       :      Dict    )				->  Optional[Any]:
        # We specify different beta, so that the first alpha is 0.99
        lowerCAmelCase     =			self.full_loop(set_alpha_to_one=UpperCAmelCase__    ,      beta_start=0.01    )
        lowerCAmelCase     =			torch.sum(torch.abs(UpperCAmelCase__    )    )
        lowerCAmelCase     =			torch.mean(torch.abs(UpperCAmelCase__    )    )

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





     def 							__UpperCAmelCase      ( self       :      Any    )				->  Optional[Any]:
        # We specify different beta, so that the first alpha is 0.99
        lowerCAmelCase     =			self.full_loop(set_alpha_to_one=UpperCAmelCase__    ,      beta_start=0.01    )
        lowerCAmelCase     =			torch.sum(torch.abs(UpperCAmelCase__    )    )
        lowerCAmelCase     =			torch.mean(torch.abs(UpperCAmelCase__    )    )

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









'''simple docstring'''




import datasets

from .nmt_bleu import compute_bleu  # From: https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py


__snake_case    						="""\
@INPROCEEDINGS{Papineni02bleu:a,
    author = {Kishore Papineni and Salim Roukos and Todd Ward and Wei-jing Zhu},
    title = {BLEU: a Method for Automatic Evaluation of Machine Translation},
    booktitle = {},
    year = {2002},
    pages = {311--318}
}
@inproceedings{lin-och-2004-orange,
    title = \"{ORANGE}: a Method for Evaluating Automatic Evaluation Metrics for Machine Translation\",
    author = \"Lin, Chin-Yew  and
      Och, Franz Josef\",
    booktitle = \"{COLING} 2004: Proceedings of the 20th International Conference on Computational Linguistics\",
    month = \"aug 23{--}aug 27\",
    year = \"2004\",
    address = \"Geneva, Switzerland\",
    publisher = \"COLING\",
    url = \"https://www.aclweb.org/anthology/C04-1072\",
    pages = \"501--507\",
}
"""

__snake_case    						="""\
BLEU (bilingual evaluation understudy) is an algorithm for evaluating the quality of text which has been machine-translated from one natural language to another.
Quality is considered to be the correspondence between a machine's output and that of a human: \"the closer a machine translation is to a professional human translation,
the better it is\" – this is the central idea behind BLEU. BLEU was one of the first metrics to claim a high correlation with human judgements of quality, and
remains one of the most popular automated and inexpensive metrics.

Scores are calculated for individual translated segments—generally sentences—by comparing them with a set of good quality reference translations.
Those scores are then averaged over the whole corpus to reach an estimate of the translation's overall quality. Intelligibility or grammatical correctness
are not taken into account[citation needed].

BLEU's output is always a number between 0 and 1. This value indicates how similar the candidate text is to the reference texts, with values closer to 1
representing more similar texts. Few human translations will attain a score of 1, since this would indicate that the candidate is identical to one of the
reference translations. For this reason, it is not necessary to attain a score of 1. Because there are more opportunities to match, adding additional
reference translations will increase the BLEU score.
"""

__snake_case    						="""
Computes BLEU score of translated segments against one or more references.
Args:
    predictions: list of translations to score.
        Each translation should be tokenized into a list of tokens.
    references: list of lists of references for each translation.
        Each reference should be tokenized into a list of tokens.
    max_order: Maximum n-gram order to use when computing BLEU score.
    smooth: Whether or not to apply Lin et al. 2004 smoothing.
Returns:
    'bleu': bleu score,
    'precisions': geometric mean of n-gram precisions,
    'brevity_penalty': brevity penalty,
    'length_ratio': ratio of lengths,
    'translation_length': translation_length,
    'reference_length': reference_length
Examples:

    >>> predictions = [
    ...     [\"hello\", \"there\", \"general\", \"kenobi\"],                             # tokenized prediction of the first sample
    ...     [\"foo\", \"bar\", \"foobar\"]                                             # tokenized prediction of the second sample
    ... ]
    >>> references = [
    ...     [[\"hello\", \"there\", \"general\", \"kenobi\"], [\"hello\", \"there\", \"!\"]],  # tokenized references for the first sample (2 references)
    ...     [[\"foo\", \"bar\", \"foobar\"]]                                           # tokenized references for the second sample (1 reference)
    ... ]
    >>> bleu = datasets.load_metric(\"bleu\")
    >>> results = bleu.compute(predictions=predictions, references=references)
    >>> print(results[\"bleu\"])
    1.0
"""

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





     def 							__UpperCAmelCase      ( self       :      Tuple    )				->  int:
        return datasets.MetricInfo(
            description=_DESCRIPTION    ,      citation=_CITATION    ,      inputs_description=_KWARGS_DESCRIPTION    ,      features=datasets.Features(
                {
                    'predictions': datasets.Sequence(datasets.Value('string'    ,      id='token'    )    ,      id='sequence'    ),
                    'references': datasets.Sequence(
                        datasets.Sequence(datasets.Value('string'    ,      id='token'    )    ,      id='sequence'    )    ,      id='references'    ),
                }    )    ,      codebase_urls=['https://github.com/tensorflow/nmt/blob/master/nmt/scripts/bleu.py']    ,      reference_urls=[
                'https://en.wikipedia.org/wiki/BLEU',
                'https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213',
            ]    ,      )





     def 							__UpperCAmelCase      ( self       :      Optional[int]    ,      UpperCAmelCase__       :      Tuple    ,      UpperCAmelCase__       :      Any    ,      UpperCAmelCase__       :      Union[str, Any]=4    ,      UpperCAmelCase__       :      Optional[int]=False    )				->  int:
        lowerCAmelCase     =			compute_bleu(
            reference_corpus=UpperCAmelCase__    ,      translation_corpus=UpperCAmelCase__    ,      max_order=UpperCAmelCase__    ,      smooth=UpperCAmelCase__    )
        ((lowerCAmelCase)     ,  (lowerCAmelCase)     ,  (lowerCAmelCase)     ,  (lowerCAmelCase)     ,  (lowerCAmelCase)     ,  (lowerCAmelCase))     =			score
        return {
            "bleu": bleu,
            "precisions": precisions,
            "brevity_penalty": bp,
            "length_ratio": ratio,
            "translation_length": translation_length,
            "reference_length": reference_length,
        }





