'''simple docstring'''




import math
import time

from transformers import Trainer, is_torch_tpu_available
from transformers.trainer_utils import PredictionOutput, speed_metrics


if is_torch_tpu_available(check_device=False):
  import torch_xla.core.xla_model as xm
  import torch_xla.debug.metrics as met




class    a__				(       UpperCAmelCase__			):






     def __init__(			self		:		Union[str, Any]  ,    *a		:		Optional[Any]  ,    a		:		Optional[Any]=None  ,    a		:		List[Any]=None  ,    **a		:		List[str]   ):





         """simple docstring"""



         super().__init__(*a  ,    **a   )
         __lowerCamelCase          =  eval_examples
         __lowerCamelCase          =  post_process_function






     def        SCREAMING_SNAKE_CASE__       (			self		:		str  ,    a		:		int=None  ,    a		:		Union[str, Any]=None  ,    a		:		Any=None  ,    a		:		str = "eval"   ):





         """simple docstring"""



         __lowerCamelCase          =  self.eval_dataset if eval_dataset is None else eval_dataset
         __lowerCamelCase          =  self.get_eval_dataloader(a   )
         __lowerCamelCase          =  self.eval_examples if eval_examples is None else eval_examples

         # Temporarily disable metric computation, we will do it in the loop here.
         __lowerCamelCase          =  self.compute_metrics
         __lowerCamelCase          =  None
         __lowerCamelCase          =  self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
         __lowerCamelCase          =  time.time()
         try:
             __lowerCamelCase          =  eval_loop(
                 a  ,    description='''Evaluation'''  ,    prediction_loss_only=True if compute_metrics is None else None  ,    ignore_keys=a  ,    metric_key_prefix=a  ,    )
         finally:
             __lowerCamelCase          =  compute_metrics
         __lowerCamelCase          =  self.args.eval_batch_size * self.args.world_size
         if f"""{metric_key_prefix}_jit_compilation_time""" in output.metrics:
             start_time += output.metrics[f"""{metric_key_prefix}_jit_compilation_time"""]
         output.metrics.update(
             speed_metrics(
                 a  ,    a  ,    num_samples=output.num_samples  ,    num_steps=math.ceil(output.num_samples / total_batch_size   )  ,    )   )
         if self.post_process_function is not None and self.compute_metrics is not None and self.args.should_save:
             # Only the main node write the results by default
             __lowerCamelCase          =  self.post_process_function(a  ,    a  ,    output.predictions   )
             __lowerCamelCase          =  self.compute_metrics(a   )

             # Prefix all keys with metric_key_prefix + '_'
             for key in list(metrics.keys()   ):
                 if not key.startswith(f"""{metric_key_prefix}_"""   ):
                     __lowerCamelCase          =  metrics.pop(a   )
             metrics.update(output.metrics   )
         else:
             __lowerCamelCase          =  output.metrics

         if self.args.should_log:
             # Only the main node log the results by default
             self.log(a   )

         if self.args.tpu_metrics_debug or self.args.debug:
             # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.)
             xm.master_print(met.metrics_report()   )

         __lowerCamelCase          =  self.callback_handler.on_evaluate(self.args  ,    self.state  ,    self.control  ,    a   )
         return metrics






     def        SCREAMING_SNAKE_CASE__       (			self		:		Tuple  ,    a		:		List[str]  ,    a		:		List[str]  ,    a		:		List[str]=None  ,    a		:		str = "test"   ):





         """simple docstring"""



         __lowerCamelCase          =  self.get_test_dataloader(a   )

         # Temporarily disable metric computation, we will do it in the loop here.
         __lowerCamelCase          =  self.compute_metrics
         __lowerCamelCase          =  None
         __lowerCamelCase          =  self.prediction_loop if self.args.use_legacy_prediction_loop else self.evaluation_loop
         __lowerCamelCase          =  time.time()
         try:
             __lowerCamelCase          =  eval_loop(
                 a  ,    description='''Prediction'''  ,    prediction_loss_only=True if compute_metrics is None else None  ,    ignore_keys=a  ,    metric_key_prefix=a  ,    )
         finally:
             __lowerCamelCase          =  compute_metrics
         __lowerCamelCase          =  self.args.eval_batch_size * self.args.world_size
         if f"""{metric_key_prefix}_jit_compilation_time""" in output.metrics:
             start_time += output.metrics[f"""{metric_key_prefix}_jit_compilation_time"""]
         output.metrics.update(
             speed_metrics(
                 a  ,    a  ,    num_samples=output.num_samples  ,    num_steps=math.ceil(output.num_samples / total_batch_size   )  ,    )   )

         if self.post_process_function is None or self.compute_metrics is None:
             return output

         __lowerCamelCase          =  self.post_process_function(a  ,    a  ,    output.predictions  ,    '''predict'''   )
         __lowerCamelCase          =  self.compute_metrics(a   )

         # Prefix all keys with metric_key_prefix + '_'
         for key in list(metrics.keys()   ):
             if not key.startswith(f"""{metric_key_prefix}_"""   ):
                 __lowerCamelCase          =  metrics.pop(a   )
         metrics.update(output.metrics   )
         return PredictionOutput(predictions=predictions.predictions  ,    label_ids=predictions.label_ids  ,    metrics=a   )

'''simple docstring'''




import torch

from diffusers import DPMSolverSDEScheduler
from diffusers.utils import torch_device
from diffusers.utils.testing_utils import require_torchsde

from .test_schedulers import SchedulerCommonTest




@require_torchsde
class    a__				(       UpperCAmelCase__			):
     lowerCamelCase  :					Dict							=(DPMSolverSDEScheduler,)
     lowerCamelCase  :					List[str]							=1_0






     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[Any]  ,    **a		:		Optional[int]   ):





         """simple docstring"""



         __lowerCamelCase          =  {
             '''num_train_timesteps''': 11_00,
             '''beta_start''': 0.00_01,
             '''beta_end''': 0.02,
             '''beta_schedule''': '''linear''',
             '''noise_sampler_seed''': 0,
         }

         config.update(**a   )
         return config






     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[Any]   ):





         """simple docstring"""



         for timesteps in [10, 50, 1_00, 10_00]:
             self.check_over_configs(num_train_timesteps=a   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		str   ):





         """simple docstring"""



         for beta_start, beta_end in zip([0.0_00_01, 0.00_01, 0.0_01]  ,    [0.00_02, 0.0_02, 0.02]   ):
             self.check_over_configs(beta_start=a  ,    beta_end=a   )






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[Any]   ):





         """simple docstring"""



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






     def        SCREAMING_SNAKE_CASE__       (			self		:		str   ):





         """simple docstring"""



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






     def        SCREAMING_SNAKE_CASE__       (			self		:		Tuple   ):





         """simple docstring"""



         __lowerCamelCase          =  self.scheduler_classes[0]
         __lowerCamelCase          =  self.get_scheduler_config()
         __lowerCamelCase          =  scheduler_class(**a   )

         scheduler.set_timesteps(self.num_inference_steps   )

         __lowerCamelCase          =  self.dummy_model()
         __lowerCamelCase          =  self.dummy_sample_deter * scheduler.init_noise_sigma
         __lowerCamelCase          =  sample.to(a   )

         for i, t in enumerate(scheduler.timesteps   ):
             __lowerCamelCase          =  scheduler.scale_model_input(a  ,    a   )

             __lowerCamelCase          =  model(a  ,    a   )

             __lowerCamelCase          =  scheduler.step(a  ,    a  ,    a   )
             __lowerCamelCase          =  output.prev_sample

         __lowerCamelCase          =  torch.sum(torch.abs(a   )   )
         __lowerCamelCase          =  torch.mean(torch.abs(a   )   )

         if torch_device in ["mps"]:
             assert abs(result_sum.item() - 1_67.47_82_10_44_92_18_75   ) < 1e-2
             assert abs(result_mean.item() - 0.21_78_70_59_64_56_52_77   ) < 1e-3
         elif torch_device in ["cuda"]:
             assert abs(result_sum.item() - 1_71.59_35_21_11_81_64_06   ) < 1e-2
             assert abs(result_mean.item() - 0.2_23_42_90_68_92_29_96_52   ) < 1e-3
         else:
             assert abs(result_sum.item() - 1_62.52_38_34_22_85_15_62   ) < 1e-2
             assert abs(result_mean.item() - 0.2_11_61_95_70_85_13_26   ) < 1e-3






     def        SCREAMING_SNAKE_CASE__       (			self		:		List[str]   ):





         """simple docstring"""



         __lowerCamelCase          =  self.scheduler_classes[0]
         __lowerCamelCase          =  self.get_scheduler_config(prediction_type='''v_prediction'''   )
         __lowerCamelCase          =  scheduler_class(**a   )

         scheduler.set_timesteps(self.num_inference_steps   )

         __lowerCamelCase          =  self.dummy_model()
         __lowerCamelCase          =  self.dummy_sample_deter * scheduler.init_noise_sigma
         __lowerCamelCase          =  sample.to(a   )

         for i, t in enumerate(scheduler.timesteps   ):
             __lowerCamelCase          =  scheduler.scale_model_input(a  ,    a   )

             __lowerCamelCase          =  model(a  ,    a   )

             __lowerCamelCase          =  scheduler.step(a  ,    a  ,    a   )
             __lowerCamelCase          =  output.prev_sample

         __lowerCamelCase          =  torch.sum(torch.abs(a   )   )
         __lowerCamelCase          =  torch.mean(torch.abs(a   )   )

         if torch_device in ["mps"]:
             assert abs(result_sum.item() - 1_24.77_14_92_00_43_94_53   ) < 1e-2
             assert abs(result_mean.item() - 0.1_62_26_28_90_14_81_62_84   ) < 1e-3
         elif torch_device in ["cuda"]:
             assert abs(result_sum.item() - 1_28.1_66_33_60_59_57_03   ) < 1e-2
             assert abs(result_mean.item() - 0.1_66_88_32_60_01_16_72_97   ) < 1e-3
         else:
             assert abs(result_sum.item() - 1_19.8_48_75_48_82_81_25   ) < 1e-2
             assert abs(result_mean.item() - 0.15_60_53_06_62_53_66_21   ) < 1e-3






     def        SCREAMING_SNAKE_CASE__       (			self		:		Dict   ):





         """simple docstring"""



         __lowerCamelCase          =  self.scheduler_classes[0]
         __lowerCamelCase          =  self.get_scheduler_config()
         __lowerCamelCase          =  scheduler_class(**a   )

         scheduler.set_timesteps(self.num_inference_steps  ,    device=a   )

         __lowerCamelCase          =  self.dummy_model()
         __lowerCamelCase          =  self.dummy_sample_deter.to(a   ) * scheduler.init_noise_sigma

         for t in scheduler.timesteps:
             __lowerCamelCase          =  scheduler.scale_model_input(a  ,    a   )

             __lowerCamelCase          =  model(a  ,    a   )

             __lowerCamelCase          =  scheduler.step(a  ,    a  ,    a   )
             __lowerCamelCase          =  output.prev_sample

         __lowerCamelCase          =  torch.sum(torch.abs(a   )   )
         __lowerCamelCase          =  torch.mean(torch.abs(a   )   )

         if torch_device in ["mps"]:
             assert abs(result_sum.item() - 1_67.46_95_73_97_46_09_38   ) < 1e-2
             assert abs(result_mean.item() - 0.2_18_05_93_46_07_98_26_35   ) < 1e-3
         elif torch_device in ["cuda"]:
             assert abs(result_sum.item() - 1_71.59_35_36_37_69_53_12   ) < 1e-2
             assert abs(result_mean.item() - 0.2_23_42_90_83_82_41_57_71   ) < 1e-3
         else:
             assert abs(result_sum.item() - 1_62.52_38_34_22_85_15_62   ) < 1e-2
             assert abs(result_mean.item() - 0.2_11_61_95_70_85_13_26   ) < 1e-3






     def        SCREAMING_SNAKE_CASE__       (			self		:		Optional[int]   ):





         """simple docstring"""



         __lowerCamelCase          =  self.scheduler_classes[0]
         __lowerCamelCase          =  self.get_scheduler_config()
         __lowerCamelCase          =  scheduler_class(**a  ,    use_karras_sigmas=a   )

         scheduler.set_timesteps(self.num_inference_steps  ,    device=a   )

         __lowerCamelCase          =  self.dummy_model()
         __lowerCamelCase          =  self.dummy_sample_deter.to(a   ) * scheduler.init_noise_sigma
         __lowerCamelCase          =  sample.to(a   )

         for t in scheduler.timesteps:
             __lowerCamelCase          =  scheduler.scale_model_input(a  ,    a   )

             __lowerCamelCase          =  model(a  ,    a   )

             __lowerCamelCase          =  scheduler.step(a  ,    a  ,    a   )
             __lowerCamelCase          =  output.prev_sample

         __lowerCamelCase          =  torch.sum(torch.abs(a   )   )
         __lowerCamelCase          =  torch.mean(torch.abs(a   )   )

         if torch_device in ["mps"]:
             assert abs(result_sum.item() - 1_76.66_97_41_35_74_21_88   ) < 1e-2
             assert abs(result_mean.item() - 0.2_30_03_87_27_30_98_18_11   ) < 1e-2
         elif torch_device in ["cuda"]:
             assert abs(result_sum.item() - 1_77.63_65_35_64_45_31_25   ) < 1e-2
             assert abs(result_mean.item() - 0.2_30_03_87_27_30_98_18_11   ) < 1e-2
         else:
             assert abs(result_sum.item() - 1_70.3_13_52_23_38_86_72   ) < 1e-2
             assert abs(result_mean.item() - 0.2_30_03_87_27_30_98_18_11   ) < 1e-2
