





import tempfile

import torch

from diffusers import (
    DEISMultistepScheduler,
    DPMSolverMultistepScheduler,
    DPMSolverSinglestepScheduler,
    UniPCMultistepScheduler,
)

from .test_schedulers import SchedulerCommonTest

class 		SCREAMING_SNAKE_CASE__    (	_UpperCAmelCase  ):
      A_						:    Union[str, Any]							=   (DPMSolverSinglestepScheduler,)
      A_						:    Union[str, Any]							=   (('num_inference_steps', 25),)


      def        a			(self	:				Dict    ,      **a__	:				Tuple				):





         """simple docstring"""



         __snake_case								=       {
             '''num_train_timesteps''': 1000,
             '''beta_start''': 0.0_0_0_1,
             '''beta_end''': 0.0_2,
             '''beta_schedule''': '''linear''',
             '''solver_order''': 2,
             '''prediction_type''': '''epsilon''',
             '''thresholding''': False,
             '''sample_max_value''': 1.0,
             '''algorithm_type''': '''dpmsolver++''',
             '''solver_type''': '''midpoint''',
             '''lambda_min_clipped''': -float('''inf'''				),
             '''variance_type''': None,
         }

         config.update(**a__				)
         return config


      def        a			(self	:				str    ,      a__	:				Any=0    ,      **a__	:				Tuple				):





         """simple docstring"""



         __snake_case								=       dict(self.forward_default_kwargs				)
         __snake_case								=       kwargs.pop('''num_inference_steps'''    ,      a__				)
         __snake_case								=       self.dummy_sample
         __snake_case								=       0.1 * sample
         __snake_case								=       [residual + 0.2, residual + 0.1_5, residual + 0.1_0]

         for scheduler_class in self.scheduler_classes:
            __snake_case								=       self.get_scheduler_config(**a__				)
            __snake_case								=       scheduler_class(**a__				)
            scheduler.set_timesteps(a__				)
            # copy over dummy past residuals
            __snake_case								=       dummy_past_residuals[: scheduler.config.solver_order]

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

            __snake_case	,     __snake_case								=       sample, sample
            for t in range(a__    ,      time_step + scheduler.config.solver_order + 1				):
               __snake_case								=       scheduler.step(a__    ,      a__    ,      a__    ,      **a__				).prev_sample
               __snake_case								=       new_scheduler.step(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]				):





         """simple docstring"""



         pass


      def        a			(self	:				List[Any]    ,      a__	:				Dict=0    ,      **a__	:				List[str]				):





         """simple docstring"""



         __snake_case								=       dict(self.forward_default_kwargs				)
         __snake_case								=       kwargs.pop('''num_inference_steps'''    ,      a__				)
         __snake_case								=       self.dummy_sample
         __snake_case								=       0.1 * sample
         __snake_case								=       [residual + 0.2, residual + 0.1_5, residual + 0.1_0]

         for scheduler_class in self.scheduler_classes:
            __snake_case								=       self.get_scheduler_config()
            __snake_case								=       scheduler_class(**a__				)
            scheduler.set_timesteps(a__				)

            # copy over dummy past residuals (must be after setting timesteps)
            __snake_case								=       dummy_past_residuals[: scheduler.config.solver_order]

            with tempfile.TemporaryDirectory() as tmpdirname:
               scheduler.save_config(a__				)
               __snake_case								=       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)
               __snake_case								=       dummy_past_residuals[: new_scheduler.config.solver_order]

            __snake_case								=       scheduler.step(a__    ,      a__    ,      a__    ,      **a__				).prev_sample
            __snake_case								=       new_scheduler.step(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    ,      a__	:				Tuple=None    ,      **a__	:				List[str]				):





         """simple docstring"""



         if scheduler is None:
            __snake_case								=       self.scheduler_classes[0]
            __snake_case								=       self.get_scheduler_config(**a__				)
            __snake_case								=       scheduler_class(**a__				)

         __snake_case								=       self.scheduler_classes[0]
         __snake_case								=       self.get_scheduler_config(**a__				)
         __snake_case								=       scheduler_class(**a__				)

         __snake_case								=       10
         __snake_case								=       self.dummy_model()
         __snake_case								=       self.dummy_sample_deter
         scheduler.set_timesteps(a__				)

         for i, t in enumerate(scheduler.timesteps				):
            __snake_case								=       model(a__    ,      a__				)
            __snake_case								=       scheduler.step(a__    ,      a__    ,      a__				).prev_sample

         return sample


      def        a			(self	:				str				):





         """simple docstring"""



         __snake_case								=       DPMSolverSinglestepScheduler(**self.get_scheduler_config()				)
         __snake_case								=       50
         __snake_case								=       self.dummy_model()
         __snake_case								=       self.dummy_sample_deter
         scheduler.set_timesteps(a__				)

         # make sure that the first t is uneven
         for i, t in enumerate(scheduler.timesteps[3:]				):
            __snake_case								=       model(a__    ,      a__				)
            __snake_case								=       scheduler.step(a__    ,      a__    ,      a__				).prev_sample

         __snake_case								=       torch.mean(torch.abs(a__				)				)

         assert abs(result_mean.item() - 0.2_5_7_4				) < 1E-3


      def        a			(self	:				int				):





         """simple docstring"""



         for timesteps in [25, 50, 100, 999, 1000]:
            self.check_over_configs(num_train_timesteps=a__				)


      def        a			(self	:				List[str]				):





         """simple docstring"""



         __snake_case								=       DPMSolverSinglestepScheduler(**self.get_scheduler_config()				)
         __snake_case								=       self.full_loop(scheduler=a__				)
         __snake_case								=       torch.mean(torch.abs(a__				)				)

         assert abs(result_mean.item() - 0.2_7_9_1				) < 1E-3

         __snake_case								=       DEISMultistepScheduler.from_config(scheduler.config				)
         __snake_case								=       DPMSolverMultistepScheduler.from_config(scheduler.config				)
         __snake_case								=       UniPCMultistepScheduler.from_config(scheduler.config				)
         __snake_case								=       DPMSolverSinglestepScheduler.from_config(scheduler.config				)

         __snake_case								=       self.full_loop(scheduler=a__				)
         __snake_case								=       torch.mean(torch.abs(a__				)				)

         assert abs(result_mean.item() - 0.2_7_9_1				) < 1E-3


      def        a			(self	:				List[str]				):





         """simple docstring"""



         self.check_over_configs(thresholding=a__				)
         for order in [1, 2, 3]:
            for solver_type in ["midpoint", "heun"]:
               for threshold in [0.5, 1.0, 2.0]:
                  for prediction_type in ["epsilon", "sample"]:
                     self.check_over_configs(
                         thresholding=a__    ,      prediction_type=a__    ,      sample_max_value=a__    ,      algorithm_type='''dpmsolver++'''    ,      solver_order=a__    ,      solver_type=a__    ,      )


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





         """simple docstring"""



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


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





         """simple docstring"""



         for algorithm_type in ["dpmsolver", "dpmsolver++"]:
            for solver_type in ["midpoint", "heun"]:
               for order in [1, 2, 3]:
                  for prediction_type in ["epsilon", "sample"]:
                     self.check_over_configs(
                         solver_order=a__    ,      solver_type=a__    ,      prediction_type=a__    ,      algorithm_type=a__    ,      )
                     __snake_case								=       self.full_loop(
                         solver_order=a__    ,      solver_type=a__    ,      prediction_type=a__    ,      algorithm_type=a__    ,      )
                     assert not torch.isnan(a__				).any(), "Samples have nan numbers"


      def        a			(self	:				List[str]				):





         """simple docstring"""



         self.check_over_configs(lower_order_final=a__				)
         self.check_over_configs(lower_order_final=a__				)


      def        a			(self	:				Optional[Any]				):





         """simple docstring"""



         self.check_over_configs(lambda_min_clipped=-float('''inf'''				)				)
         self.check_over_configs(lambda_min_clipped=-5.1				)


      def        a			(self	:				Tuple				):





         """simple docstring"""



         self.check_over_configs(variance_type=a__				)
         self.check_over_configs(variance_type='''learned_range'''				)


      def        a			(self	:				int				):





         """simple docstring"""



         for num_inference_steps in [1, 2, 3, 5, 10, 50, 100, 999, 1000]:
            self.check_over_forward(num_inference_steps=a__    ,      time_step=0				)


      def        a			(self	:				Optional[Any]				):





         """simple docstring"""



         __snake_case								=       self.full_loop()
         __snake_case								=       torch.mean(torch.abs(a__				)				)

         assert abs(result_mean.item() - 0.2_7_9_1				) < 1E-3


      def        a			(self	:				int				):





         """simple docstring"""



         __snake_case								=       self.full_loop(use_karras_sigmas=a__				)
         __snake_case								=       torch.mean(torch.abs(a__				)				)

         assert abs(result_mean.item() - 0.2_2_4_8				) < 1E-3


      def        a			(self	:				Tuple				):





         """simple docstring"""



         __snake_case								=       self.full_loop(prediction_type='''v_prediction'''				)
         __snake_case								=       torch.mean(torch.abs(a__				)				)

         assert abs(result_mean.item() - 0.1_4_5_3				) < 1E-3


      def        a			(self	:				List[Any]				):





         """simple docstring"""



         __snake_case								=       self.full_loop(prediction_type='''v_prediction'''    ,      use_karras_sigmas=a__				)
         __snake_case								=       torch.mean(torch.abs(a__				)				)

         assert abs(result_mean.item() - 0.0_6_4_9				) < 1E-3


      def        a			(self	:				int				):





         """simple docstring"""



         __snake_case								=       self.scheduler_classes[0]
         __snake_case								=       self.get_scheduler_config(thresholding=a__    ,      dynamic_thresholding_ratio=0				)
         __snake_case								=       scheduler_class(**a__				)

         __snake_case								=       10
         __snake_case								=       self.dummy_model()
         __snake_case								=       self.dummy_sample_deter.half()
         scheduler.set_timesteps(a__				)

         for i, t in enumerate(scheduler.timesteps				):
            __snake_case								=       model(a__    ,      a__				)
            __snake_case								=       scheduler.step(a__    ,      a__    ,      a__				).prev_sample

         assert sample.dtype == torch.floataa








import re
import string

import numpy as np

import datasets


snake_case_           =      '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n'

snake_case_           =      '\nArgs:\n    predictions: List of predicted texts.\n    references: List of reference texts.\n    regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n        ignore when calculating the exact matches. Note: these regexes are removed\n        from the input data before the changes based on the options below (e.g. ignore_case,\n        ignore_punctuation, ignore_numbers) are applied.\n    ignore_case: Boolean, defaults to False. If true, turns everything\n        to lowercase so that capitalization differences are ignored.\n    ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\n    ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\nReturns:\n    exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results["exact_match"], 1))\n    25.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results["exact_match"], 1))\n    50.0\n\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results["exact_match"], 1))\n    75.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n    >>> print(round(results["exact_match"], 1))\n    100.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n    >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results["exact_match"], 1))\n    33.3\n\n'

snake_case_           =      '\n'

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


      def        a			(self	:				Optional[Any]				):





         """simple docstring"""



         return datasets.MetricInfo(
             description=_DESCRIPTION    ,      citation=_CITATION    ,      inputs_description=_KWARGS_DESCRIPTION    ,      features=datasets.Features(
                 {
                     '''predictions''': datasets.Value('''string'''    ,      id='''sequence'''				),
                     '''references''': datasets.Value('''string'''    ,      id='''sequence'''				),
                 }				)    ,      reference_urls=[]    ,      )


      def        a			(self	:				List[Any]    ,      a__	:				int    ,      a__	:				Optional[int]    ,      a__	:				Optional[Any]=None    ,      a__	:				Any=False    ,      a__	:				Dict=False    ,      a__	:				Tuple=False    ,      ):





         """simple docstring"""



         if regexes_to_ignore is not None:
            for s in regexes_to_ignore:
               __snake_case								=       np.array([re.sub(a__    ,      ''''''    ,      a__				) for x in predictions]				)
               __snake_case								=       np.array([re.sub(a__    ,      ''''''    ,      a__				) for x in references]				)
         else:
            __snake_case								=       np.asarray(a__				)
            __snake_case								=       np.asarray(a__				)

         if ignore_case:
            __snake_case								=       np.char.lower(a__				)
            __snake_case								=       np.char.lower(a__				)

         if ignore_punctuation:
            __snake_case								=       string.punctuation.maketrans(''''''    ,      ''''''    ,      string.punctuation				)
            __snake_case								=       np.char.translate(a__    ,      table=a__				)
            __snake_case								=       np.char.translate(a__    ,      table=a__				)

         if ignore_numbers:
            __snake_case								=       string.digits.maketrans(''''''    ,      ''''''    ,      string.digits				)
            __snake_case								=       np.char.translate(a__    ,      table=a__				)
            __snake_case								=       np.char.translate(a__    ,      table=a__				)

         __snake_case								=       predictions == references

         return {"exact_match": np.mean(a__				) * 100}

