

'''simple docstring'''







import unittest

import torch

from diffusers import VQModel
from diffusers.utils import floats_tensor, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin


enable_full_determinism()


class 					A__      (      _snake_case						,						_snake_case						,						unittest.TestCase			):
    lowercase						=		VQModel
    lowercase						=		"sample"



    @property
    def 					snake_case_			(					self		,				UpperCamelCase__=(32, 32)       )						->      Optional[int]:





           '''simple docstring'''
           A_						=      4
           A_						=      3

           A_						=      floats_tensor((batch_size, num_channels) + sizes       ).to(UpperCamelCase__       )

           return {"sample": image}



    @property
    def 					snake_case_			(					self       )						->      List[Any]:





           '''simple docstring'''
           return (3, 32, 32)



    @property
    def 					snake_case_			(					self       )						->      Tuple:





           '''simple docstring'''
           return (3, 32, 32)



    def 					snake_case_			(					self       )						->      str:





           '''simple docstring'''
           A_						=      {
               """block_out_channels""": [32, 64],
               """in_channels""": 3,
               """out_channels""": 3,
               """down_block_types""": ["""DownEncoderBlock2D""", """DownEncoderBlock2D"""],
               """up_block_types""": ["""UpDecoderBlock2D""", """UpDecoderBlock2D"""],
               """latent_channels""": 3,
           }
           A_						=      self.dummy_input
           return init_dict, inputs_dict



    def 					snake_case_			(					self       )						->      Optional[Any]:





           '''simple docstring'''
           pass



    def 					snake_case_			(					self       )						->      List[Any]:





           '''simple docstring'''
           pass



    def 					snake_case_			(					self       )						->      Optional[int]:





           '''simple docstring'''
           A_					,			A_						=      VQModel.from_pretrained("""fusing/vqgan-dummy"""		,				output_loading_info=UpperCamelCase__       )
           self.assertIsNotNone(UpperCamelCase__       )
           self.assertEqual(len(loading_info["""missing_keys"""]       )		,				0       )

           model.to(UpperCamelCase__       )
           A_						=      model(**self.dummy_input       )

           assert image is not None, "Make sure output is not None"







    def 					snake_case_			(					self       )						->      List[str]:





           '''simple docstring'''
           A_						=      VQModel.from_pretrained("""fusing/vqgan-dummy"""       )
           model.to(UpperCamelCase__       ).eval()

           torch.manual_seed(0       )
           if torch.cuda.is_available():
                  torch.cuda.manual_seed_all(0       )

           A_						=      torch.randn(1		,				model.config.in_channels		,				model.config.sample_size		,				model.config.sample_size       )
           A_						=      image.to(UpperCamelCase__       )
           with torch.no_grad():
                  A_						=      model(UpperCamelCase__       ).sample

           A_						=      output[0, -1, -3:, -3:].flatten().cpu()
           # fmt: off
           A_						=      torch.tensor([-0.0153, -0.4044, -0.1880, -0.5161, -0.2418, -0.4072, -0.1612, -0.0633, -0.0143]       )
           # fmt: on
           self.assertTrue(torch.allclose(UpperCamelCase__		,				UpperCamelCase__		,				atol=1e-3       )       )



'''simple docstring'''







import tempfile

import torch

from diffusers import IPNDMScheduler

from .test_schedulers import SchedulerCommonTest


class 					A__      (      _snake_case			):
    lowercase						=		(IPNDMScheduler,)
    lowercase						=		(("num_inference_steps", 50),)



    def 					snake_case_			(					self		,				**UpperCamelCase__       )						->      Optional[Any]:





           '''simple docstring'''
           A_						=      {"""num_train_timesteps""": 1000}
           config.update(**UpperCamelCase__       )
           return config



    def 					snake_case_			(					self		,				UpperCamelCase__=0		,				**UpperCamelCase__       )						->      str:





           '''simple docstring'''
           A_						=      dict(self.forward_default_kwargs       )
           A_						=      kwargs.pop("""num_inference_steps"""		,				UpperCamelCase__       )
           A_						=      self.dummy_sample
           A_						=      0.1 * sample
           A_						=      [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]

           for scheduler_class in self.scheduler_classes:
                  A_						=      self.get_scheduler_config(**UpperCamelCase__       )
                  A_						=      scheduler_class(**UpperCamelCase__       )
                  scheduler.set_timesteps(UpperCamelCase__       )
                  # copy over dummy past residuals
                  A_						=      dummy_past_residuals[:]

                  if time_step is None:
                         A_						=      scheduler.timesteps[len(scheduler.timesteps       ) // 2]

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

                  A_						=      scheduler.step(UpperCamelCase__		,				UpperCamelCase__		,				UpperCamelCase__		,				**UpperCamelCase__       ).prev_sample
                  A_						=      new_scheduler.step(UpperCamelCase__		,				UpperCamelCase__		,				UpperCamelCase__		,				**UpperCamelCase__       ).prev_sample

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

                  A_						=      scheduler.step(UpperCamelCase__		,				UpperCamelCase__		,				UpperCamelCase__		,				**UpperCamelCase__       ).prev_sample
                  A_						=      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 					snake_case_			(					self       )						->      Optional[int]:





           '''simple docstring'''
           pass



    def 					snake_case_			(					self		,				UpperCamelCase__=0		,				**UpperCamelCase__       )						->      str:





           '''simple docstring'''
           A_						=      dict(self.forward_default_kwargs       )
           A_						=      kwargs.pop("""num_inference_steps"""		,				UpperCamelCase__       )
           A_						=      self.dummy_sample
           A_						=      0.1 * sample
           A_						=      [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]

           for scheduler_class in self.scheduler_classes:
                  A_						=      self.get_scheduler_config()
                  A_						=      scheduler_class(**UpperCamelCase__       )
                  scheduler.set_timesteps(UpperCamelCase__       )

                  # copy over dummy past residuals (must be after setting timesteps)
                  A_						=      dummy_past_residuals[:]

                  if time_step is None:
                         A_						=      scheduler.timesteps[len(scheduler.timesteps       ) // 2]

                  with tempfile.TemporaryDirectory() as tmpdirname:
                         scheduler.save_config(UpperCamelCase__       )
                         A_						=      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)
                         A_						=      dummy_past_residuals[:]

                  A_						=      scheduler.step(UpperCamelCase__		,				UpperCamelCase__		,				UpperCamelCase__		,				**UpperCamelCase__       ).prev_sample
                  A_						=      new_scheduler.step(UpperCamelCase__		,				UpperCamelCase__		,				UpperCamelCase__		,				**UpperCamelCase__       ).prev_sample

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

                  A_						=      scheduler.step(UpperCamelCase__		,				UpperCamelCase__		,				UpperCamelCase__		,				**UpperCamelCase__       ).prev_sample
                  A_						=      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 					snake_case_			(					self		,				**UpperCamelCase__       )						->      Tuple:





           '''simple docstring'''
           A_						=      self.scheduler_classes[0]
           A_						=      self.get_scheduler_config(**UpperCamelCase__       )
           A_						=      scheduler_class(**UpperCamelCase__       )

           A_						=      10
           A_						=      self.dummy_model()
           A_						=      self.dummy_sample_deter
           scheduler.set_timesteps(UpperCamelCase__       )

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

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

           return sample



    def 					snake_case_			(					self       )						->      Union[str, Any]:





           '''simple docstring'''
           A_						=      dict(self.forward_default_kwargs       )

           A_						=      kwargs.pop("""num_inference_steps"""		,				UpperCamelCase__       )

           for scheduler_class in self.scheduler_classes:
                  A_						=      self.get_scheduler_config()
                  A_						=      scheduler_class(**UpperCamelCase__       )

                  A_						=      self.dummy_sample
                  A_						=      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"""       ):
                         A_						=      num_inference_steps

                  # copy over dummy past residuals (must be done after set_timesteps)
                  A_						=      [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]
                  A_						=      dummy_past_residuals[:]

                  A_						=      scheduler.timesteps[5]
                  A_						=      scheduler.timesteps[6]

                  A_						=      scheduler.step(UpperCamelCase__		,				UpperCamelCase__		,				UpperCamelCase__		,				**UpperCamelCase__       ).prev_sample
                  A_						=      scheduler.step(UpperCamelCase__		,				UpperCamelCase__		,				UpperCamelCase__		,				**UpperCamelCase__       ).prev_sample

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

                  A_						=      scheduler.step(UpperCamelCase__		,				UpperCamelCase__		,				UpperCamelCase__		,				**UpperCamelCase__       ).prev_sample
                  A_						=      scheduler.step(UpperCamelCase__		,				UpperCamelCase__		,				UpperCamelCase__		,				**UpperCamelCase__       ).prev_sample

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



    def 					snake_case_			(					self       )						->      Any:





           '''simple docstring'''
           for timesteps in [100, 1000]:
                  self.check_over_configs(num_train_timesteps=UpperCamelCase__		,				time_step=UpperCamelCase__       )



    def 					snake_case_			(					self       )						->      Any:





           '''simple docstring'''
           for t, num_inference_steps in zip([1, 5, 10]		,				[10, 50, 100]       ):
                  self.check_over_forward(num_inference_steps=UpperCamelCase__		,				time_step=UpperCamelCase__       )







    def 					snake_case_			(					self       )						->      Dict:





           '''simple docstring'''
           A_						=      self.full_loop()
           A_						=      torch.mean(torch.abs(UpperCamelCase__       )       )

           assert abs(result_mean.item() - 2540529       ) < 10
