



'''simple docstring'''






import random
import unittest

import torch

from diffusers import IFInpaintingSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin



@skip_mps
class 							lowercase       (  _lowerCamelCase					,					_lowerCamelCase					,					unittest.TestCase				):


 """simple docstring"""


 UpperCAmelCase							=  IFInpaintingSuperResolutionPipeline
 UpperCAmelCase							=  TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"""width""", """height"""}
 UpperCAmelCase							=  TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({"""original_image"""}				)
 UpperCAmelCase							=  PipelineTesterMixin.required_optional_params - {"""latents"""}







 def _snake_case (							self							)		->   str:
        return self._get_superresolution_dummy_components()







 def _snake_case (							self  ,a_  ,a_=0							)		->   Dict:
        if str(a_							).startswith("""mps"""							):
               _UpperCAmelCase  :						int			     = torch.manual_seed(a_							)
        else:
               _UpperCAmelCase  :						Tuple			     = torch.Generator(device=a_							).manual_seed(a_							)

        _UpperCAmelCase  :						Optional[int]			     = floats_tensor((1, 3, 16, 16)  ,rng=random.Random(a_							)							).to(a_							)
        _UpperCAmelCase  :						List[str]			     = floats_tensor((1, 3, 32, 32)  ,rng=random.Random(a_							)							).to(a_							)
        _UpperCAmelCase  :						int			     = floats_tensor((1, 3, 32, 32)  ,rng=random.Random(a_							)							).to(a_							)

        _UpperCAmelCase  :						str			     = {
            """prompt""": """A painting of a squirrel eating a burger""",
            """image""": image,
            """original_image""": original_image,
            """mask_image""": mask_image,
            """generator""": generator,
            """num_inference_steps""": 2,
            """output_type""": """numpy""",
        }

        return inputs







 @unittest.skipIf(
     torch_device != """cuda""" or not is_xformers_available()  ,reason="""XFormers attention is only available with CUDA and `xformers` installed"""  ,)
 def _snake_case (							self							)		->   Union[str, Any]:
        self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3							)







 def _snake_case (							self							)		->   str:
        self._test_save_load_optional_components()







 @unittest.skipIf(torch_device != """cuda"""  ,reason="""float16 requires CUDA"""							)
 def _snake_case (							self							)		->   Optional[Any]:
        # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
        super().test_save_load_floataa(expected_max_diff=1E-1							)







 def _snake_case (							self							)		->   Union[str, Any]:
        self._test_attention_slicing_forward_pass(expected_max_diff=1E-2							)







 def _snake_case (							self							)		->   Optional[int]:
        self._test_save_load_local()







 def _snake_case (							self							)		->   Optional[Any]:
        self._test_inference_batch_single_identical(
            expected_max_diff=1E-2  ,)








'''simple docstring'''






import tempfile

import torch

from diffusers import IPNDMScheduler

from .test_schedulers import SchedulerCommonTest



class 							lowercase       (  _lowerCamelCase				):


 """simple docstring"""


 UpperCAmelCase							=  (IPNDMScheduler,)
 UpperCAmelCase							=  (("""num_inference_steps""", 50),)







 def _snake_case (							self  ,**a_							)		->   Optional[int]:
        _UpperCAmelCase  :						str			     = {"""num_train_timesteps""": 1_000}
        config.update(**a_							)
        return config







 def _snake_case (							self  ,a_=0  ,**a_							)		->   List[str]:
        _UpperCAmelCase  :						Any			     = dict(self.forward_default_kwargs							)
        _UpperCAmelCase  :						Any			     = kwargs.pop("""num_inference_steps"""  ,a_							)
        _UpperCAmelCase  :						Union[str, Any]			     = self.dummy_sample
        _UpperCAmelCase  :						Union[str, Any]			     = 0.1 * sample
        _UpperCAmelCase  :						List[str]			     = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]

        for scheduler_class in self.scheduler_classes:
               _UpperCAmelCase  :						str			     = self.get_scheduler_config(**a_							)
               _UpperCAmelCase  :						List[str]			     = scheduler_class(**a_							)
               scheduler.set_timesteps(a_							)
               # copy over dummy past residuals
               _UpperCAmelCase  :						str			     = dummy_past_residuals[:]

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

               with tempfile.TemporaryDirectory() as tmpdirname:
                      scheduler.save_config(a_							)
                      _UpperCAmelCase  :						List[str]			     = scheduler_class.from_pretrained(a_							)
                      new_scheduler.set_timesteps(a_							)
                      # copy over dummy past residuals
                      _UpperCAmelCase  :						Tuple			     = dummy_past_residuals[:]

               _UpperCAmelCase  :						Dict			     = scheduler.step(a_  ,a_  ,a_  ,**a_							).prev_sample
               _UpperCAmelCase  :						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"

               _UpperCAmelCase  :						str			     = scheduler.step(a_  ,a_  ,a_  ,**a_							).prev_sample
               _UpperCAmelCase  :						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 _snake_case (							self							)		->   Any:
        pass







 def _snake_case (							self  ,a_=0  ,**a_							)		->   Dict:
        _UpperCAmelCase  :						str			     = dict(self.forward_default_kwargs							)
        _UpperCAmelCase  :						Union[str, Any]			     = kwargs.pop("""num_inference_steps"""  ,a_							)
        _UpperCAmelCase  :						Optional[int]			     = self.dummy_sample
        _UpperCAmelCase  :						Tuple			     = 0.1 * sample
        _UpperCAmelCase  :						Optional[Any]			     = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]

        for scheduler_class in self.scheduler_classes:
               _UpperCAmelCase  :						Optional[Any]			     = self.get_scheduler_config()
               _UpperCAmelCase  :						Dict			     = scheduler_class(**a_							)
               scheduler.set_timesteps(a_							)

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

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

               with tempfile.TemporaryDirectory() as tmpdirname:
                      scheduler.save_config(a_							)
                      _UpperCAmelCase  :						str			     = 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)
                      _UpperCAmelCase  :						Dict			     = dummy_past_residuals[:]

               _UpperCAmelCase  :						Tuple			     = scheduler.step(a_  ,a_  ,a_  ,**a_							).prev_sample
               _UpperCAmelCase  :						str			     = new_scheduler.step(a_  ,a_  ,a_  ,**a_							).prev_sample

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

               _UpperCAmelCase  :						str			     = scheduler.step(a_  ,a_  ,a_  ,**a_							).prev_sample
               _UpperCAmelCase  :						str			     = 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 _snake_case (							self  ,**a_							)		->   List[Any]:
        _UpperCAmelCase  :						int			     = self.scheduler_classes[0]
        _UpperCAmelCase  :						List[str]			     = self.get_scheduler_config(**a_							)
        _UpperCAmelCase  :						List[Any]			     = scheduler_class(**a_							)

        _UpperCAmelCase  :						List[Any]			     = 10
        _UpperCAmelCase  :						Dict			     = self.dummy_model()
        _UpperCAmelCase  :						Dict			     = self.dummy_sample_deter
        scheduler.set_timesteps(a_							)

        for i, t in enumerate(scheduler.timesteps							):
               _UpperCAmelCase  :						Optional[Any]			     = model(a_  ,a_							)
               _UpperCAmelCase  :						Tuple			     = scheduler.step(a_  ,a_  ,a_							).prev_sample

        for i, t in enumerate(scheduler.timesteps							):
               _UpperCAmelCase  :						List[str]			     = model(a_  ,a_							)
               _UpperCAmelCase  :						int			     = scheduler.step(a_  ,a_  ,a_							).prev_sample

        return sample







 def _snake_case (							self							)		->   Optional[Any]:
        _UpperCAmelCase  :						int			     = dict(self.forward_default_kwargs							)

        _UpperCAmelCase  :						Optional[Any]			     = kwargs.pop("""num_inference_steps"""  ,a_							)

        for scheduler_class in self.scheduler_classes:
               _UpperCAmelCase  :						int			     = self.get_scheduler_config()
               _UpperCAmelCase  :						List[str]			     = scheduler_class(**a_							)

               _UpperCAmelCase  :						Optional[int]			     = self.dummy_sample
               _UpperCAmelCase  :						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"""							):
                      _UpperCAmelCase  :						Optional[Any]			     = num_inference_steps

               # copy over dummy past residuals (must be done after set_timesteps)
               _UpperCAmelCase  :						Union[str, Any]			     = [residual + 0.2, residual + 0.15, residual + 0.1, residual + 0.05]
               _UpperCAmelCase  :						Optional[int]			     = dummy_past_residuals[:]

               _UpperCAmelCase  :						Tuple			     = scheduler.timesteps[5]
               _UpperCAmelCase  :						Optional[Any]			     = scheduler.timesteps[6]

               _UpperCAmelCase  :						Optional[Any]			     = scheduler.step(a_  ,a_  ,a_  ,**a_							).prev_sample
               _UpperCAmelCase  :						Optional[int]			     = scheduler.step(a_  ,a_  ,a_  ,**a_							).prev_sample

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

               _UpperCAmelCase  :						Dict			     = scheduler.step(a_  ,a_  ,a_  ,**a_							).prev_sample
               _UpperCAmelCase  :						Any			     = scheduler.step(a_  ,a_  ,a_  ,**a_							).prev_sample

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







 def _snake_case (							self							)		->   List[Any]:
        for timesteps in [100, 1_000]:
               self.check_over_configs(num_train_timesteps=a_  ,time_step=a_							)







 def _snake_case (							self							)		->   int:
        for t, num_inference_steps in zip([1, 5, 10]  ,[10, 50, 100]							):
               self.check_over_forward(num_inference_steps=a_  ,time_step=a_							)







 def _snake_case (							self							)		->   Optional[Any]:
        _UpperCAmelCase  :						Union[str, Any]			     = self.full_loop()
        _UpperCAmelCase  :						Any			     = torch.mean(torch.abs(a_							)							)

        assert abs(result_mean.item() - 2_540_529							) < 10



