
import tempfile

import torch

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

from .test_schedulers import SchedulerCommonTest





class   __UpperCamelCase				(    A__   ):






     """simple docstring"""







     lowerCAmelCase_     =	(DPMSolverMultistepScheduler,)
     lowerCAmelCase_     =	(('''num_inference_steps''', 25),)



     def 				UpperCAmelCase__    (							self    :    Union[str, Any]      ,		**_A    :    Optional[Any]				):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE     :					Any			=						{
           "num_train_timesteps": 1000,
           "beta_start": 0.00_01,
           "beta_end": 0.02,
           "beta_schedule": "linear",
           "solver_order": 2,
           "prediction_type": "epsilon",
           "thresholding": False,
           "sample_max_value": 1.0,
           "algorithm_type": "dpmsolver++",
           "solver_type": "midpoint",
           "lower_order_final": False,
           "lambda_min_clipped": -float('''inf'''				),
           "variance_type": None,
       }

       config.update(**_A				)
       return config



     def 				UpperCAmelCase__    (							self    :    Any      ,		_A    :    Tuple=0      ,		**_A    :    Optional[int]				):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE     :					int			=						dict(self.forward_default_kwargs				)
       __SCREAMING_SNAKE_CASE     :					List[str]			=						kwargs.pop('''num_inference_steps'''      ,		_A				)
       __SCREAMING_SNAKE_CASE     :					List[str]			=						self.dummy_sample
       __SCREAMING_SNAKE_CASE     :					str			=						0.1 * sample
       __SCREAMING_SNAKE_CASE     :					Tuple			=						[residual + 0.2, residual + 0.15, residual + 0.10]

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

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

         __SCREAMING_SNAKE_CASE     :					str			=						sample, sample
         for t in range(_A      ,		time_step + scheduler.config.solver_order + 1				):
           __SCREAMING_SNAKE_CASE     :					List[str]			=						scheduler.step(_A      ,		_A      ,		_A      ,		**_A				).prev_sample
           __SCREAMING_SNAKE_CASE     :					Any			=						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 				UpperCAmelCase__    (							self    :    Any				):







       """simple docstring"""




       pass



     def 				UpperCAmelCase__    (							self    :    Dict      ,		_A    :    List[str]=0      ,		**_A    :    Union[str, Any]				):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE     :					Optional[int]			=						dict(self.forward_default_kwargs				)
       __SCREAMING_SNAKE_CASE     :					Tuple			=						kwargs.pop('''num_inference_steps'''      ,		_A				)
       __SCREAMING_SNAKE_CASE     :					int			=						self.dummy_sample
       __SCREAMING_SNAKE_CASE     :					str			=						0.1 * sample
       __SCREAMING_SNAKE_CASE     :					Dict			=						[residual + 0.2, residual + 0.15, residual + 0.10]

       for scheduler_class in self.scheduler_classes:
         __SCREAMING_SNAKE_CASE     :					Optional[Any]			=						self.get_scheduler_config()
         __SCREAMING_SNAKE_CASE     :					str			=						scheduler_class(**_A				)
         scheduler.set_timesteps(_A				)

         # copy over dummy past residuals (must be after setting timesteps)
         __SCREAMING_SNAKE_CASE     :					Union[str, Any]			=						dummy_past_residuals[: scheduler.config.solver_order]

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

         __SCREAMING_SNAKE_CASE     :					Dict			=						scheduler.step(_A      ,		_A      ,		_A      ,		**_A				).prev_sample
         __SCREAMING_SNAKE_CASE     :					List[Any]			=						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 				UpperCAmelCase__    (							self    :    Tuple      ,		_A    :    List[Any]=None      ,		**_A    :    int				):







       """simple docstring"""




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

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

       for i, t in enumerate(scheduler.timesteps				):
         __SCREAMING_SNAKE_CASE     :					List[str]			=						model(_A      ,		_A				)
         __SCREAMING_SNAKE_CASE     :					Tuple			=						scheduler.step(_A      ,		_A      ,		_A				).prev_sample

       return sample



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







       """simple docstring"""




       __SCREAMING_SNAKE_CASE     :					str			=						dict(self.forward_default_kwargs				)

       __SCREAMING_SNAKE_CASE     :					List[str]			=						kwargs.pop('''num_inference_steps'''      ,		_A				)

       for scheduler_class in self.scheduler_classes:
         __SCREAMING_SNAKE_CASE     :					Optional[int]			=						self.get_scheduler_config()
         __SCREAMING_SNAKE_CASE     :					Dict			=						scheduler_class(**_A				)

         __SCREAMING_SNAKE_CASE     :					int			=						self.dummy_sample
         __SCREAMING_SNAKE_CASE     :					Tuple			=						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'''				):
           __SCREAMING_SNAKE_CASE     :					Optional[int]			=						num_inference_steps

         # copy over dummy past residuals (must be done after set_timesteps)
         __SCREAMING_SNAKE_CASE     :					Tuple			=						[residual + 0.2, residual + 0.15, residual + 0.10]
         __SCREAMING_SNAKE_CASE     :					Dict			=						dummy_past_residuals[: scheduler.config.solver_order]

         __SCREAMING_SNAKE_CASE     :					Any			=						scheduler.timesteps[5]
         __SCREAMING_SNAKE_CASE     :					Dict			=						scheduler.timesteps[6]

         __SCREAMING_SNAKE_CASE     :					List[Any]			=						scheduler.step(_A      ,		_A      ,		_A      ,		**_A				).prev_sample
         __SCREAMING_SNAKE_CASE     :					int			=						scheduler.step(_A      ,		_A      ,		_A      ,		**_A				).prev_sample

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



     def 				UpperCAmelCase__    (							self    :    Tuple				):







       """simple docstring"""




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



     def 				UpperCAmelCase__    (							self    :    List[Any]				):







       """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 				UpperCAmelCase__    (							self    :    Optional[Any]				):







       """simple docstring"""




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



     def 				UpperCAmelCase__    (							self    :    int				):







       """simple docstring"""




       for algorithm_type in ["dpmsolver", "dpmsolver++", "sde-dpmsolver", "sde-dpmsolver++"]:
         for solver_type in ["midpoint", "heun"]:
           for order in [1, 2, 3]:
             for prediction_type in ["epsilon", "sample"]:
               if algorithm_type in ["sde-dpmsolver", "sde-dpmsolver++"]:
                 if order == 3:
                   continue
               else:
                 self.check_over_configs(
                     solver_order=_A      ,		solver_type=_A      ,		prediction_type=_A      ,		algorithm_type=_A      ,		)
               __SCREAMING_SNAKE_CASE     :					Dict			=						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 				UpperCAmelCase__    (							self    :    List[str]				):







       """simple docstring"""




       self.check_over_configs(lower_order_final=_A				)
       self.check_over_configs(lower_order_final=_A				)



     def 				UpperCAmelCase__    (							self    :    Dict				):







       """simple docstring"""




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



     def 				UpperCAmelCase__    (							self    :    Optional[int]				):







       """simple docstring"""




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



     def 				UpperCAmelCase__    (							self    :    Optional[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 				UpperCAmelCase__    (							self    :    int				):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE     :					Dict			=						self.full_loop()
       __SCREAMING_SNAKE_CASE     :					Optional[int]			=						torch.mean(torch.abs(_A				)				)

       assert abs(result_mean.item() - 0.33_01				) < 1e-3



     def 				UpperCAmelCase__    (							self    :    Any				):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE     :					int			=						self.full_loop(thresholding=_A      ,		dynamic_thresholding_ratio=0.87      ,		sample_max_value=0.5				)
       __SCREAMING_SNAKE_CASE     :					List[Any]			=						torch.mean(torch.abs(_A				)				)

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



     def 				UpperCAmelCase__    (							self    :    Optional[Any]				):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE     :					Union[str, Any]			=						self.full_loop(prediction_type='''v_prediction'''				)
       __SCREAMING_SNAKE_CASE     :					Optional[Any]			=						torch.mean(torch.abs(_A				)				)

       assert abs(result_mean.item() - 0.22_51				) < 1e-3



     def 				UpperCAmelCase__    (							self    :    List[str]				):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE     :					List[Any]			=						self.full_loop(prediction_type='''v_prediction'''      ,		use_karras_sigmas=_A				)
       __SCREAMING_SNAKE_CASE     :					List[str]			=						torch.mean(torch.abs(_A				)				)

       assert abs(result_mean.item() - 0.20_96				) < 1e-3



     def 				UpperCAmelCase__    (							self    :    Tuple				):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE     :					List[Any]			=						DPMSolverMultistepScheduler(**self.get_scheduler_config()				)
       __SCREAMING_SNAKE_CASE     :					List[Any]			=						self.full_loop(scheduler=_A				)
       __SCREAMING_SNAKE_CASE     :					List[Any]			=						torch.mean(torch.abs(_A				)				)

       assert abs(result_mean.item() - 0.33_01				) < 1e-3

       __SCREAMING_SNAKE_CASE     :					Dict			=						DPMSolverSinglestepScheduler.from_config(scheduler.config				)
       __SCREAMING_SNAKE_CASE     :					Union[str, Any]			=						UniPCMultistepScheduler.from_config(scheduler.config				)
       __SCREAMING_SNAKE_CASE     :					Union[str, Any]			=						DEISMultistepScheduler.from_config(scheduler.config				)
       __SCREAMING_SNAKE_CASE     :					int			=						DPMSolverMultistepScheduler.from_config(scheduler.config				)

       __SCREAMING_SNAKE_CASE     :					int			=						self.full_loop(scheduler=_A				)
       __SCREAMING_SNAKE_CASE     :					List[Any]			=						torch.mean(torch.abs(_A				)				)

       assert abs(result_mean.item() - 0.33_01				) < 1e-3



     def 				UpperCAmelCase__    (							self    :    int				):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE     :					Tuple			=						self.scheduler_classes[0]
       __SCREAMING_SNAKE_CASE     :					List[str]			=						self.get_scheduler_config(thresholding=_A      ,		dynamic_thresholding_ratio=0				)
       __SCREAMING_SNAKE_CASE     :					List[str]			=						scheduler_class(**_A				)

       __SCREAMING_SNAKE_CASE     :					int			=						10
       __SCREAMING_SNAKE_CASE     :					List[str]			=						self.dummy_model()
       __SCREAMING_SNAKE_CASE     :					List[Any]			=						self.dummy_sample_deter.half()
       scheduler.set_timesteps(_A				)

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

       assert sample.dtype == torch.floataa




     def 				UpperCAmelCase__    (							self    :    Tuple      ,		**_A    :    List[str]				):







       """simple docstring"""




       for scheduler_class in self.scheduler_classes:
         __SCREAMING_SNAKE_CASE     :					int			=						self.get_scheduler_config(**_A				)
         __SCREAMING_SNAKE_CASE     :					Union[str, Any]			=						scheduler_class(**_A				)

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


import unittest

from transformers import load_tool

from .test_tools_common import ToolTesterMixin


lowercase_											=	"""
Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf originally as a company that developed a chatbot app targeted at teenagers.[2] After open-sourcing the model behind the chatbot, the company pivoted to focus on being a platform for machine learning.

In March 2021, Hugging Face raised $40 million in a Series B funding round.[3]

On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model.[4] In 2022, the workshop concluded with the announcement of BLOOM, a multilingual large language model with 176 billion parameters.[5]
"""





class   __UpperCamelCase				(    unittest.TestCase				,		lowerCAmelCase__   ):






     """simple docstring"""







     def 				UpperCAmelCase__    (							self    :    Optional[Any]				):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE     :					int			=						load_tool('''summarization'''				)
       self.tool.setup()
       __SCREAMING_SNAKE_CASE     :					Any			=						load_tool('''summarization'''      ,		remote=_A				)



     def 				UpperCAmelCase__    (							self    :    Tuple				):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE     :					Dict			=						self.tool(_A				)
       self.assertEqual(
           _A      ,		'''Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf. In March 2021, Hugging Face raised $40 million in a Series B funding round. On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model. In 2022, the workshop concluded with the announcement of BLOOM.'''      ,		)



     def 				UpperCAmelCase__    (							self    :    List[str]				):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE     :					Optional[Any]			=						self.remote_tool(_A				)
       self.assertEqual(
           _A      ,		'''Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf. In March 2021, Hugging Face raised $40 million in a Series B funding round. On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model. In 2022, the workshop concluded with the announcement of BLOOM.'''      ,		)



     def 				UpperCAmelCase__    (							self    :    List[str]				):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE     :					Dict			=						self.tool(text=_A				)
       self.assertEqual(
           _A      ,		'''Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf. In March 2021, Hugging Face raised $40 million in a Series B funding round. On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model. In 2022, the workshop concluded with the announcement of BLOOM.'''      ,		)




     def 				UpperCAmelCase__    (							self    :    Optional[int]				):







       """simple docstring"""




       __SCREAMING_SNAKE_CASE     :					str			=						self.remote_tool(text=_A				)
       self.assertEqual(
           _A      ,		'''Hugging Face was founded in 2016 by French entrepreneurs Clément Delangue, Julien Chaumond, and Thomas Wolf. In March 2021, Hugging Face raised $40 million in a Series B funding round. On April 28, 2021, the company launched the BigScience Research Workshop in collaboration with several other research groups to release an open large language model. In 2022, the workshop concluded with the announcement of BLOOM.'''      ,		)
