"""simple docstring"""





from ..utils import (
    OptionalDependencyNotAvailable,
    is_flax_available,
    is_scipy_available,
    is_torch_available,
    is_torchsde_available,
)


try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       from ..utils.dummy_pt_objects import *  # noqa F403
else:
       from .scheduling_consistency_models import CMStochasticIterativeScheduler
       from .scheduling_ddim import DDIMScheduler
       from .scheduling_ddim_inverse import DDIMInverseScheduler
       from .scheduling_ddim_parallel import DDIMParallelScheduler
       from .scheduling_ddpm import DDPMScheduler
       from .scheduling_ddpm_parallel import DDPMParallelScheduler
       from .scheduling_deis_multistep import DEISMultistepScheduler
       from .scheduling_dpmsolver_multistep import DPMSolverMultistepScheduler
       from .scheduling_dpmsolver_multistep_inverse import DPMSolverMultistepInverseScheduler
       from .scheduling_dpmsolver_singlestep import DPMSolverSinglestepScheduler
       from .scheduling_euler_ancestral_discrete import EulerAncestralDiscreteScheduler
       from .scheduling_euler_discrete import EulerDiscreteScheduler
       from .scheduling_heun_discrete import HeunDiscreteScheduler
       from .scheduling_ipndm import IPNDMScheduler
       from .scheduling_k_dpm_2_ancestral_discrete import KDPMaAncestralDiscreteScheduler
       from .scheduling_k_dpm_2_discrete import KDPMaDiscreteScheduler
       from .scheduling_karras_ve import KarrasVeScheduler
       from .scheduling_pndm import PNDMScheduler
       from .scheduling_repaint import RePaintScheduler
       from .scheduling_sde_ve import ScoreSdeVeScheduler
       from .scheduling_sde_vp import ScoreSdeVpScheduler
       from .scheduling_unclip import UnCLIPScheduler
       from .scheduling_unipc_multistep import UniPCMultistepScheduler
       from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin
       from .scheduling_vq_diffusion import VQDiffusionScheduler

try:
       if not is_flax_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       from ..utils.dummy_flax_objects import *  # noqa F403
else:
       from .scheduling_ddim_flax import FlaxDDIMScheduler
       from .scheduling_ddpm_flax import FlaxDDPMScheduler
       from .scheduling_dpmsolver_multistep_flax import FlaxDPMSolverMultistepScheduler
       from .scheduling_karras_ve_flax import FlaxKarrasVeScheduler
       from .scheduling_lms_discrete_flax import FlaxLMSDiscreteScheduler
       from .scheduling_pndm_flax import FlaxPNDMScheduler
       from .scheduling_sde_ve_flax import FlaxScoreSdeVeScheduler
       from .scheduling_utils_flax import (
           FlaxKarrasDiffusionSchedulers,
           FlaxSchedulerMixin,
           FlaxSchedulerOutput,
           broadcast_to_shape_from_left,
       )


try:
       if not (is_torch_available() and is_scipy_available()):
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       from ..utils.dummy_torch_and_scipy_objects import *  # noqa F403
else:
       from .scheduling_lms_discrete import LMSDiscreteScheduler

try:
       if not (is_torch_available() and is_torchsde_available()):
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       from ..utils.dummy_torch_and_torchsde_objects import *  # noqa F403
else:
       from .scheduling_dpmsolver_sde import DPMSolverSDEScheduler


"""simple docstring"""





import shutil
import tempfile
import unittest
from unittest.mock import patch

from transformers import (
    DefaultFlowCallback,
    IntervalStrategy,
    PrinterCallback,
    ProgressCallback,
    Trainer,
    TrainerCallback,
    TrainingArguments,
    is_torch_available,
)
from transformers.testing_utils import require_torch


if is_torch_available():
       from transformers.trainer import DEFAULT_CALLBACKS

       from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel


class   UpperCAmelCase_			(					_a):


      def __init__(     self							) ->      Any:
             lowercase__    :	Tuple     					=			[]


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    **a							) ->      Any:
             self.events.append('on_init_end'							)


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    **a							) ->      Optional[int]:
             self.events.append('on_train_begin'							)


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    **a							) ->      List[str]:
             self.events.append('on_train_end'							)


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    **a							) ->      int:
             self.events.append('on_epoch_begin'							)


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    **a							) ->      Optional[Any]:
             self.events.append('on_epoch_end'							)


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    **a							) ->      int:
             self.events.append('on_step_begin'							)


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    **a							) ->      str:
             self.events.append('on_step_end'							)


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    **a							) ->      int:
             self.events.append('on_evaluate'							)


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    **a							) ->      Tuple:
             self.events.append('on_predict'							)


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    **a							) ->      Union[str, Any]:
             self.events.append('on_save'							)


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    **a							) ->      List[str]:
             self.events.append('on_log'							)


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    **a							) ->      Any:
             self.events.append('on_prediction_step'							)





@require_torch
class   UpperCAmelCase_			(					unittest.TestCase):


      def 	_UpperCAmelCase (     self							) ->      str:
             lowercase__    :	str     					=			tempfile.mkdtemp()


      def 	_UpperCAmelCase (     self							) ->      Dict:
             shutil.rmtree(self.output_dir							)


      def 	_UpperCAmelCase (     self	,    a=0	,    a=0	,    a=6_4	,    a=6_4	,    a=None	,    a=False	,    **a							) ->      int:
             # disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure
             # its set to False since the tests later on depend on its value.
             lowercase__    :	str     					=			RegressionDataset(length=a							)
             lowercase__    :	Any     					=			RegressionDataset(length=a							)
             lowercase__    :	Optional[Any]     					=			RegressionModelConfig(a=a	,    b=a							)
             lowercase__    :	Union[str, Any]     					=			RegressionPreTrainedModel(a							)

             lowercase__    :	Tuple     					=			TrainingArguments(self.output_dir	,    disable_tqdm=a	,    report_to=[]	,    **a							)
             return Trainer(
                 a	,    a	,    train_dataset=a	,    eval_dataset=a	,    callbacks=a	,    )


      def 	_UpperCAmelCase (     self	,    a	,    a							) ->      Union[str, Any]:
             self.assertEqual(len(a							)	,    len(a							)							)

             # Order doesn't matter
             lowercase__    :	Optional[int]     					=			sorted(a	,    key=lambda a							: cb.__name__ if isinstance(a	,    a							) else cb.__class__.__name__							)
             lowercase__    :	Tuple     					=			sorted(a	,    key=lambda a							: cb.__name__ if isinstance(a	,    a							) else cb.__class__.__name__							)

             for cba, cba in zip(a	,    a							):
                    if isinstance(a	,    a							) and isinstance(a	,    a							):
                           self.assertEqual(a	,    a							)
                    elif isinstance(a	,    a							) and not isinstance(a	,    a							):
                           self.assertEqual(a	,    cba.__class__							)
                    elif not isinstance(a	,    a							) and isinstance(a	,    a							):
                           self.assertEqual(cba.__class__	,    a							)
                    else:
                           self.assertEqual(a	,    a							)


      def 	_UpperCAmelCase (     self	,    a							) ->      Optional[Any]:
             lowercase__    :	Dict     					=			['on_init_end', 'on_train_begin']
             lowercase__    :	List[Any]     					=			0
             lowercase__    :	Optional[int]     					=			len(trainer.get_eval_dataloader()							)
             lowercase__    :	Tuple     					=			['on_prediction_step'] * len(trainer.get_eval_dataloader()							) + ['on_log', 'on_evaluate']
             for _ in range(trainer.state.num_train_epochs							):
                    expected_events.append('on_epoch_begin'							)
                    for _ in range(a							):
                           step += 1
                           expected_events += ["on_step_begin", "on_step_end"]
                           if step % trainer.args.logging_steps == 0:
                                  expected_events.append('on_log'							)
                           if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0:
                                  expected_events += evaluation_events.copy()
                           if step % trainer.args.save_steps == 0:
                                  expected_events.append('on_save'							)
                    expected_events.append('on_epoch_end'							)
                    if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH:
                           expected_events += evaluation_events.copy()
             expected_events += ["on_log", "on_train_end"]
             return expected_events


      def 	_UpperCAmelCase (     self							) ->      Union[str, Any]:
             lowercase__    :	int     					=			self.get_trainer()
             lowercase__    :	str     					=			DEFAULT_CALLBACKS.copy() + [ProgressCallback]
             self.check_callbacks_equality(trainer.callback_handler.callbacks	,    a							)

             # Callbacks passed at init are added to the default callbacks
             lowercase__    :	str     					=			self.get_trainer(callbacks=[MyTestTrainerCallback]							)
             expected_callbacks.append(a							)
             self.check_callbacks_equality(trainer.callback_handler.callbacks	,    a							)

             # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback
             lowercase__    :	List[Any]     					=			self.get_trainer(disable_tqdm=a							)
             lowercase__    :	Optional[Any]     					=			DEFAULT_CALLBACKS.copy() + [PrinterCallback]
             self.check_callbacks_equality(trainer.callback_handler.callbacks	,    a							)


      def 	_UpperCAmelCase (     self							) ->      Any:
             lowercase__    :	int     					=			DEFAULT_CALLBACKS.copy() + [ProgressCallback]
             lowercase__    :	List[str]     					=			self.get_trainer()

             # We can add, pop, or remove by class name
             trainer.remove_callback(a							)
             expected_callbacks.remove(a							)
             self.check_callbacks_equality(trainer.callback_handler.callbacks	,    a							)

             lowercase__    :	Optional[Any]     					=			self.get_trainer()
             lowercase__    :	List[Any]     					=			trainer.pop_callback(a							)
             self.assertEqual(cb.__class__	,    a							)
             self.check_callbacks_equality(trainer.callback_handler.callbacks	,    a							)

             trainer.add_callback(a							)
             expected_callbacks.insert(0	,    a							)
             self.check_callbacks_equality(trainer.callback_handler.callbacks	,    a							)

             # We can also add, pop, or remove by instance
             lowercase__    :	int     					=			self.get_trainer()
             lowercase__    :	List[str]     					=			trainer.callback_handler.callbacks[0]
             trainer.remove_callback(a							)
             expected_callbacks.remove(a							)
             self.check_callbacks_equality(trainer.callback_handler.callbacks	,    a							)

             lowercase__    :	Tuple     					=			self.get_trainer()
             lowercase__    :	Dict     					=			trainer.callback_handler.callbacks[0]
             lowercase__    :	Union[str, Any]     					=			trainer.pop_callback(a							)
             self.assertEqual(a	,    a							)
             self.check_callbacks_equality(trainer.callback_handler.callbacks	,    a							)

             trainer.add_callback(a							)
             expected_callbacks.insert(0	,    a							)
             self.check_callbacks_equality(trainer.callback_handler.callbacks	,    a							)


      def 	_UpperCAmelCase (     self							) ->      Tuple:
             import warnings

             # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested
             warnings.simplefilter(action='ignore'	,    category=a							)

             lowercase__    :	Optional[Any]     					=			self.get_trainer(callbacks=[MyTestTrainerCallback]							)
             trainer.train()
             lowercase__    :	Any     					=			trainer.callback_handler.callbacks[-2].events
             self.assertEqual(a	,    self.get_expected_events(a							)							)

             # Independent log/save/eval
             lowercase__    :	List[str]     					=			self.get_trainer(callbacks=[MyTestTrainerCallback]	,    logging_steps=5							)
             trainer.train()
             lowercase__    :	int     					=			trainer.callback_handler.callbacks[-2].events
             self.assertEqual(a	,    self.get_expected_events(a							)							)

             lowercase__    :	Union[str, Any]     					=			self.get_trainer(callbacks=[MyTestTrainerCallback]	,    save_steps=5							)
             trainer.train()
             lowercase__    :	Union[str, Any]     					=			trainer.callback_handler.callbacks[-2].events
             self.assertEqual(a	,    self.get_expected_events(a							)							)

             lowercase__    :	List[str]     					=			self.get_trainer(callbacks=[MyTestTrainerCallback]	,    eval_steps=5	,    evaluation_strategy='steps'							)
             trainer.train()
             lowercase__    :	Optional[int]     					=			trainer.callback_handler.callbacks[-2].events
             self.assertEqual(a	,    self.get_expected_events(a							)							)

             lowercase__    :	int     					=			self.get_trainer(callbacks=[MyTestTrainerCallback]	,    evaluation_strategy='epoch'							)
             trainer.train()
             lowercase__    :	str     					=			trainer.callback_handler.callbacks[-2].events
             self.assertEqual(a	,    self.get_expected_events(a							)							)

             # A bit of everything
             lowercase__    :	Any     					=			self.get_trainer(
                 callbacks=[MyTestTrainerCallback]	,    logging_steps=3	,    save_steps=1_0	,    eval_steps=5	,    evaluation_strategy='steps'	,    )
             trainer.train()
             lowercase__    :	Any     					=			trainer.callback_handler.callbacks[-2].events
             self.assertEqual(a	,    self.get_expected_events(a							)							)

             # warning should be emitted for duplicated callbacks
             with patch('transformers.trainer_callback.logger.warning'							) as warn_mock:
                    lowercase__    :	str     					=			self.get_trainer(
                        callbacks=[MyTestTrainerCallback, MyTestTrainerCallback]	,    )
                    assert str(a							) in warn_mock.call_args[0][0]

