






import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
     import torch

if is_vision_available():
     from PIL import Image

     from transformers import ViTImageProcessor




class    lowercase_    (unittest.TestCase     ):






      def __init__(    self     ,     a_     ,     a_=1_3     ,     a_=3     ,     a_=2_2_4     ,     a_=3_0     ,     a_=4_0_0     ,     a_=True     ,     a_=None     ,     a_=True     ,     a_=[0.5, 0.5, 0.5]     ,     a_=[0.5, 0.5, 0.5]     ,     )	->Any:







        '''simple docstring'''


        _a							=	size if size is not None else {"height": 1_8, "width": 1_8}
        _a							=	parent
        _a							=	batch_size
        _a							=	num_channels
        _a							=	image_size
        _a							=	min_resolution
        _a							=	max_resolution
        _a							=	do_resize
        _a							=	size
        _a							=	do_normalize
        _a							=	image_mean
        _a							=	image_std






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







        '''simple docstring'''


        return {
            "image_mean": self.image_mean,
            "image_std": self.image_std,
            "do_normalize": self.do_normalize,
            "do_resize": self.do_resize,
            "size": self.size,
        }







@require_torch
@require_vision
class    lowercase_    (a__,    unittest.TestCase     ):
      A__	:		Union[str, Any]       			=				ViTImageProcessor if is_vision_available() else None






      def 			lowerCamelCase__    (    self	)	->str:







        '''simple docstring'''


        _a							=	EfficientFormerImageProcessorTester(self	)






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







        '''simple docstring'''


        return self.image_proc_tester.prepare_image_processor_dict()






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







        '''simple docstring'''


        _a							=	self.image_processing_class(**self.image_processor_dict	)
        self.assertTrue(hasattr(lowerCamelCase_     ,     "image_mean"	)	)
        self.assertTrue(hasattr(lowerCamelCase_     ,     "image_std"	)	)
        self.assertTrue(hasattr(lowerCamelCase_     ,     "do_normalize"	)	)
        self.assertTrue(hasattr(lowerCamelCase_     ,     "do_resize"	)	)
        self.assertTrue(hasattr(lowerCamelCase_     ,     "size"	)	)






      def 			lowerCamelCase__    (    self	)	->Tuple:







        '''simple docstring'''


        pass






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







        '''simple docstring'''


        _a							=	self.image_processing_class(**self.image_processor_dict	)
        # create random PIL images
        _a							=	prepare_image_inputs(self.image_proc_tester     ,     equal_resolution=lowerCamelCase_	)
        for image in image_inputs:
          self.assertIsInstance(lowerCamelCase_     ,     Image.Image	)

        # Test not batched input
        _a							=	image_processor(image_inputs[0]     ,     return_tensors="pt"	).pixel_values
        self.assertEqual(
            encoded_images.shape     ,     (
                1,
                self.image_proc_tester.num_channels,
                self.image_proc_tester.size["height"],
                self.image_proc_tester.size["width"],
            )     ,     )

        # Test batched
        _a							=	image_processor(lowerCamelCase_     ,     return_tensors="pt"	).pixel_values
        self.assertEqual(
            encoded_images.shape     ,     (
                self.image_proc_tester.batch_size,
                self.image_proc_tester.num_channels,
                self.image_proc_tester.size["height"],
                self.image_proc_tester.size["width"],
            )     ,     )






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







        '''simple docstring'''


        _a							=	self.image_processing_class(**self.image_processor_dict	)
        # create random numpy tensors
        _a							=	prepare_image_inputs(self.image_proc_tester     ,     equal_resolution=lowerCamelCase_     ,     numpify=lowerCamelCase_	)
        for image in image_inputs:
          self.assertIsInstance(lowerCamelCase_     ,     np.ndarray	)

        # Test not batched input
        _a							=	image_processor(image_inputs[0]     ,     return_tensors="pt"	).pixel_values
        self.assertEqual(
            encoded_images.shape     ,     (
                1,
                self.image_proc_tester.num_channels,
                self.image_proc_tester.size["height"],
                self.image_proc_tester.size["width"],
            )     ,     )

        # Test batched
        _a							=	image_processor(lowerCamelCase_     ,     return_tensors="pt"	).pixel_values
        self.assertEqual(
            encoded_images.shape     ,     (
                self.image_proc_tester.batch_size,
                self.image_proc_tester.num_channels,
                self.image_proc_tester.size["height"],
                self.image_proc_tester.size["width"],
            )     ,     )






      def 			lowerCamelCase__    (    self	)	->int:







        '''simple docstring'''


        _a							=	self.image_processing_class(**self.image_processor_dict	)
        # create random PyTorch tensors
        _a							=	prepare_image_inputs(self.image_proc_tester     ,     equal_resolution=lowerCamelCase_     ,     torchify=lowerCamelCase_	)
        for image in image_inputs:
          self.assertIsInstance(lowerCamelCase_     ,     torch.Tensor	)

        # Test not batched input
        _a							=	image_processor(image_inputs[0]     ,     return_tensors="pt"	).pixel_values
        self.assertEqual(
            encoded_images.shape     ,     (
                1,
                self.image_proc_tester.num_channels,
                self.image_proc_tester.size["height"],
                self.image_proc_tester.size["width"],
            )     ,     )

        # Test batched
        _a							=	image_processor(lowerCamelCase_     ,     return_tensors="pt"	).pixel_values
        self.assertEqual(
            encoded_images.shape     ,     (
                self.image_proc_tester.batch_size,
                self.image_proc_tester.num_channels,
                self.image_proc_tester.size["height"],
                self.image_proc_tester.size["width"],
            )     ,     )










"""simple docstring"""




import torch

from diffusers import KDPMaDiscreteScheduler
from diffusers.utils import torch_device

from .test_schedulers import SchedulerCommonTest




class    lowercase_    (_UpperCAmelCase     ):
      A__	:		Tuple       			=				(KDPMaDiscreteScheduler,)
      A__	:		Tuple       			=				10






      def 			lowerCamelCase__    (    self     ,     **a_	)	->List[str]:







        '''simple docstring'''


        _a							=	{
            "num_train_timesteps": 1_1_0_0,
            "beta_start": 0.0_001,
            "beta_end": 0.02,
            "beta_schedule": "linear",
        }

        config.update(**a_	)
        return config






      def 			lowerCamelCase__    (    self	)	->Tuple:







        '''simple docstring'''


        for timesteps in [1_0, 5_0, 1_0_0, 1_0_0_0]:
          self.check_over_configs(num_train_timesteps=a_	)






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







        '''simple docstring'''


        for beta_start, beta_end in zip([0.00_001, 0.0_001, 0.001]     ,     [0.0_002, 0.002, 0.02]	):
          self.check_over_configs(beta_start=a_     ,     beta_end=a_	)






      def 			lowerCamelCase__    (    self	)	->Any:







        '''simple docstring'''


        for schedule in ["linear", "scaled_linear"]:
          self.check_over_configs(beta_schedule=a_	)






      def 			lowerCamelCase__    (    self	)	->int:







        '''simple docstring'''


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






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







        '''simple docstring'''


        _a							=	self.scheduler_classes[0]
        _a							=	self.get_scheduler_config(prediction_type="v_prediction"	)
        _a							=	scheduler_class(**a_	)

        scheduler.set_timesteps(self.num_inference_steps	)

        _a							=	self.dummy_model()
        _a							=	self.dummy_sample_deter * scheduler.init_noise_sigma
        _a							=	sample.to(a_	)

        for i, t in enumerate(scheduler.timesteps	):
          _a							=	scheduler.scale_model_input(a_     ,     a_	)

          _a							=	model(a_     ,     a_	)

          _a							=	scheduler.step(a_     ,     a_     ,     a_	)
          _a							=	output.prev_sample

        _a							=	torch.sum(torch.abs(a_	)	)
        _a							=	torch.mean(torch.abs(a_	)	)

        if torch_device in ["cpu", "mps"]:
          assert abs(result_sum.item() - 4.6_934E-07	) < 1E-2
          assert abs(result_mean.item() - 6.1_112E-10	) < 1E-3
        else:
          # CUDA
          assert abs(result_sum.item() - 4.693_428_650_170_972E-07	) < 1E-2
          assert abs(result_mean.item() - 0.0_002	) < 1E-3






      def 			lowerCamelCase__    (    self	)	->Any:







        '''simple docstring'''


        if torch_device == "mps":
          return
        _a							=	self.scheduler_classes[0]
        _a							=	self.get_scheduler_config()
        _a							=	scheduler_class(**a_	)

        scheduler.set_timesteps(self.num_inference_steps	)

        _a							=	self.dummy_model()
        _a							=	self.dummy_sample_deter * scheduler.init_noise_sigma
        _a							=	sample.to(a_	)

        for i, t in enumerate(scheduler.timesteps	):
          _a							=	scheduler.scale_model_input(a_     ,     a_	)

          _a							=	model(a_     ,     a_	)

          _a							=	scheduler.step(a_     ,     a_     ,     a_	)
          _a							=	output.prev_sample

        _a							=	torch.sum(torch.abs(a_	)	)
        _a							=	torch.mean(torch.abs(a_	)	)

        if torch_device in ["cpu", "mps"]:
          assert abs(result_sum.item() - 20.4_125	) < 1E-2
          assert abs(result_mean.item() - 0.0_266	) < 1E-3
        else:
          # CUDA
          assert abs(result_sum.item() - 20.4_125	) < 1E-2
          assert abs(result_mean.item() - 0.0_266	) < 1E-3






      def 			lowerCamelCase__    (    self	)	->int:







        '''simple docstring'''


        if torch_device == "mps":
          return
        _a							=	self.scheduler_classes[0]
        _a							=	self.get_scheduler_config()
        _a							=	scheduler_class(**a_	)

        scheduler.set_timesteps(self.num_inference_steps     ,     device=a_	)

        _a							=	self.dummy_model()
        _a							=	self.dummy_sample_deter.to(a_	) * scheduler.init_noise_sigma

        for t in scheduler.timesteps:
          _a							=	scheduler.scale_model_input(a_     ,     a_	)

          _a							=	model(a_     ,     a_	)

          _a							=	scheduler.step(a_     ,     a_     ,     a_	)
          _a							=	output.prev_sample

        _a							=	torch.sum(torch.abs(a_	)	)
        _a							=	torch.mean(torch.abs(a_	)	)

        if str(a_	).startswith("cpu"	):
          # The following sum varies between 148 and 156 on mps. Why?
          assert abs(result_sum.item() - 20.4_125	) < 1E-2
          assert abs(result_mean.item() - 0.0_266	) < 1E-3
        else:
          # CUDA
          assert abs(result_sum.item() - 20.4_125	) < 1E-2
          assert abs(result_mean.item() - 0.0_266	) < 1E-3


