




import tempfile

import torch

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

from .test_schedulers import SchedulerCommonTest




class    __lowerCAmelCase       (							UpperCamelCase_):
       _a 					=						(UniPCMultistepScheduler,)
       _a 					=						(('''num_inference_steps''', 25),)






       def 					SCREAMING_SNAKE_CASE    (   self:					Any       ,					**_lowerCAmelCase:					Tuple				):
         lowercase    :Any      	=						{
             '''num_train_timesteps''': 10_00,
             '''beta_start''': 0.00_01,
             '''beta_end''': 0.02,
             '''beta_schedule''': '''linear''',
             '''solver_order''': 2,
             '''solver_type''': '''bh2''',
         }

         config.update(**UpperCamelCase__				)
         return config






       def 					SCREAMING_SNAKE_CASE    (   self:					Union[str, Any]       ,					_lowerCAmelCase:					Any=0       ,					**_lowerCAmelCase:					Any				):
         lowercase    :Optional[int]      	=						dict(self.forward_default_kwargs				)
         lowercase    :Union[str, Any]      	=						kwargs.pop("num_inference_steps"       ,					UpperCamelCase__				)
         lowercase    :Any      	=						self.dummy_sample
         lowercase    :Any      	=						0.1 * sample
         lowercase    :str      	=						[residual + 0.2, residual + 0.15, residual + 0.10]

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

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

           lowercase    :Optional[Any]      	=						sample, sample
           for t in range(UpperCamelCase__       ,					time_step + scheduler.config.solver_order + 1				):
             lowercase    :List[str]      	=						scheduler.step(UpperCamelCase__       ,					UpperCamelCase__       ,					UpperCamelCase__       ,					**UpperCamelCase__				).prev_sample
             lowercase    :Any      	=						new_scheduler.step(UpperCamelCase__       ,					UpperCamelCase__       ,					UpperCamelCase__       ,					**UpperCamelCase__				).prev_sample

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






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[Any]       ,					_lowerCAmelCase:					List[str]=0       ,					**_lowerCAmelCase:					Optional[int]				):
         lowercase    :Any      	=						dict(self.forward_default_kwargs				)
         lowercase    :Tuple      	=						kwargs.pop("num_inference_steps"       ,					UpperCamelCase__				)
         lowercase    :Optional[int]      	=						self.dummy_sample
         lowercase    :str      	=						0.1 * sample
         lowercase    :Dict      	=						[residual + 0.2, residual + 0.15, residual + 0.10]

         for scheduler_class in self.scheduler_classes:
           lowercase    :List[Any]      	=						self.get_scheduler_config()
           lowercase    :int      	=						scheduler_class(**UpperCamelCase__				)
           scheduler.set_timesteps(UpperCamelCase__				)

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

           with tempfile.TemporaryDirectory() as tmpdirname:
             scheduler.save_config(UpperCamelCase__				)
             lowercase    :List[Any]      	=						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)
             lowercase    :Union[str, Any]      	=						dummy_past_residuals[: new_scheduler.config.solver_order]

           lowercase    :Optional[int]      	=						scheduler.step(UpperCamelCase__       ,					UpperCamelCase__       ,					UpperCamelCase__       ,					**UpperCamelCase__				).prev_sample
           lowercase    :str      	=						new_scheduler.step(UpperCamelCase__       ,					UpperCamelCase__       ,					UpperCamelCase__       ,					**UpperCamelCase__				).prev_sample

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






       def 					SCREAMING_SNAKE_CASE    (   self:					Union[str, Any]       ,					_lowerCAmelCase:					List[Any]=None       ,					**_lowerCAmelCase:					Optional[int]				):





         if scheduler is None:
           lowercase    :Union[str, Any]      	=						self.scheduler_classes[0]
           lowercase    :Optional[Any]      	=						self.get_scheduler_config(**UpperCamelCase__				)
           lowercase    :str      	=						scheduler_class(**UpperCamelCase__				)

         lowercase    :int      	=						self.scheduler_classes[0]
         lowercase    :int      	=						self.get_scheduler_config(**UpperCamelCase__				)
         lowercase    :List[Any]      	=						scheduler_class(**UpperCamelCase__				)

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

         for i, t in enumerate(scheduler.timesteps				):
           lowercase    :Optional[int]      	=						model(UpperCamelCase__       ,					UpperCamelCase__				)
           lowercase    :Union[str, Any]      	=						scheduler.step(UpperCamelCase__       ,					UpperCamelCase__       ,					UpperCamelCase__				).prev_sample

         return sample






       def 					SCREAMING_SNAKE_CASE    (   self:					str				):
         lowercase    :Optional[Any]      	=						dict(self.forward_default_kwargs				)

         lowercase    :List[str]      	=						kwargs.pop("num_inference_steps"       ,					UpperCamelCase__				)

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

           lowercase    :Optional[Any]      	=						self.dummy_sample
           lowercase    :int      	=						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"				):
             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.10]
           lowercase    :int      	=						dummy_past_residuals[: scheduler.config.solver_order]

           lowercase    :List[str]      	=						scheduler.timesteps[5]
           lowercase    :Dict      	=						scheduler.timesteps[6]

           lowercase    :Optional[Any]      	=						scheduler.step(UpperCamelCase__       ,					UpperCamelCase__       ,					UpperCamelCase__       ,					**UpperCamelCase__				).prev_sample
           lowercase    :List[str]      	=						scheduler.step(UpperCamelCase__       ,					UpperCamelCase__       ,					UpperCamelCase__       ,					**UpperCamelCase__				).prev_sample

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






       def 					SCREAMING_SNAKE_CASE    (   self:					int				):
         lowercase    :Union[str, Any]      	=						UniPCMultistepScheduler(**self.get_scheduler_config()				)
         lowercase    :Optional[Any]      	=						self.full_loop(scheduler=UpperCamelCase__				)
         lowercase    :Any      	=						torch.mean(torch.abs(UpperCamelCase__				)				)

         assert abs(result_mean.item() - 0.24_64				) < 1e-3

         lowercase    :Dict      	=						DPMSolverSinglestepScheduler.from_config(scheduler.config				)
         lowercase    :Any      	=						DEISMultistepScheduler.from_config(scheduler.config				)
         lowercase    :Optional[int]      	=						DPMSolverMultistepScheduler.from_config(scheduler.config				)
         lowercase    :Any      	=						UniPCMultistepScheduler.from_config(scheduler.config				)

         lowercase    :str      	=						self.full_loop(scheduler=UpperCamelCase__				)
         lowercase    :Optional[int]      	=						torch.mean(torch.abs(UpperCamelCase__				)				)

         assert abs(result_mean.item() - 0.24_64				) < 1e-3






       def 					SCREAMING_SNAKE_CASE    (   self:					List[str]				):





         for timesteps in [25, 50, 1_00, 9_99, 10_00]:
           self.check_over_configs(num_train_timesteps=UpperCamelCase__				)






       def 					SCREAMING_SNAKE_CASE    (   self:					Any				):
         self.check_over_configs(thresholding=UpperCamelCase__				)
         for order in [1, 2, 3]:
           for solver_type in ["bh1", "bh2"]:
             for threshold in [0.5, 1.0, 2.0]:
               for prediction_type in ["epsilon", "sample"]:
                 self.check_over_configs(
                     thresholding=UpperCamelCase__       ,					prediction_type=UpperCamelCase__       ,					sample_max_value=UpperCamelCase__       ,					solver_order=UpperCamelCase__       ,					solver_type=UpperCamelCase__       ,					)






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[Any]				):





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






       def 					SCREAMING_SNAKE_CASE    (   self:					Dict				):





         for solver_type in ["bh1", "bh2"]:
           for order in [1, 2, 3]:
             for prediction_type in ["epsilon", "sample"]:
               self.check_over_configs(
                   solver_order=UpperCamelCase__       ,					solver_type=UpperCamelCase__       ,					prediction_type=UpperCamelCase__       ,					)
               lowercase    :str      	=						self.full_loop(
                   solver_order=UpperCamelCase__       ,					solver_type=UpperCamelCase__       ,					prediction_type=UpperCamelCase__       ,					)
               assert not torch.isnan(UpperCamelCase__				).any(), "Samples have nan numbers"






       def 					SCREAMING_SNAKE_CASE    (   self:					List[Any]				):
         self.check_over_configs(lower_order_final=UpperCamelCase__				)
         self.check_over_configs(lower_order_final=UpperCamelCase__				)






       def 					SCREAMING_SNAKE_CASE    (   self:					Optional[Any]				):





         for num_inference_steps in [1, 2, 3, 5, 10, 50, 1_00, 9_99, 10_00]:
           self.check_over_forward(num_inference_steps=UpperCamelCase__       ,					time_step=0				)






       def 					SCREAMING_SNAKE_CASE    (   self:					Union[str, Any]				):
         lowercase    :Dict      	=						self.full_loop()
         lowercase    :List[Any]      	=						torch.mean(torch.abs(UpperCamelCase__				)				)

         assert abs(result_mean.item() - 0.24_64				) < 1e-3






       def 					SCREAMING_SNAKE_CASE    (   self:					Dict				):
         lowercase    :Dict      	=						self.full_loop(prediction_type="v_prediction"				)
         lowercase    :List[str]      	=						torch.mean(torch.abs(UpperCamelCase__				)				)

         assert abs(result_mean.item() - 0.10_14				) < 1e-3






       def 					SCREAMING_SNAKE_CASE    (   self:					Tuple				):
         lowercase    :List[Any]      	=						self.scheduler_classes[0]
         lowercase    :Optional[Any]      	=						self.get_scheduler_config(thresholding=UpperCamelCase__       ,					dynamic_thresholding_ratio=0				)
         lowercase    :List[str]      	=						scheduler_class(**UpperCamelCase__				)

         lowercase    :List[str]      	=						10
         lowercase    :List[str]      	=						self.dummy_model()
         lowercase    :Union[str, Any]      	=						self.dummy_sample_deter.half()
         scheduler.set_timesteps(UpperCamelCase__				)

         for i, t in enumerate(scheduler.timesteps				):
           lowercase    :List[str]      	=						model(UpperCamelCase__       ,					UpperCamelCase__				)
           lowercase    :List[Any]      	=						scheduler.step(UpperCamelCase__       ,					UpperCamelCase__       ,					UpperCamelCase__				).prev_sample

         assert sample.dtype == torch.floataa






       def 					SCREAMING_SNAKE_CASE    (   self:					int       ,					**_lowerCAmelCase:					List[Any]				):





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

           scheduler.set_timesteps(scheduler.config.num_train_timesteps				)
           assert len(scheduler.timesteps.unique()				) == scheduler.num_inference_steps










def       UpperCAmelCase__  (     lowerCamelCase,			lowerCamelCase   ):
  if discount_rate < 0:
    raise ValueError("Discount rate cannot be negative"   )
  if not cash_flows:
    raise ValueError("Cash flows list cannot be empty"   )
  lowercase    :Dict      	=						sum(
      cash_flow / ((1 + discount_rate) ** i) for i, cash_flow in enumerate(lowerCamelCase   )   )
  return round(lowerCamelCase,			ndigits=2   )


if __name__ == "__main__":
     import doctest

     doctest.testmod()



