



'''simple docstring'''






import torch

from diffusers import HeunDiscreteScheduler
from diffusers.utils import torch_device

from .test_schedulers import SchedulerCommonTest



class 				lowercase			(    _lowerCamelCase							):


 """simple docstring"""


 UpperCAmelCase		      =    (HeunDiscreteScheduler,)
 UpperCAmelCase		      =    10







 def _snake_case					(				self    ,**a_				)						->  Any:
        _UpperCAmelCase    :		int     	=					{
            """num_train_timesteps""": 1_100,
            """beta_start""": 0.0001,
            """beta_end""": 0.02,
            """beta_schedule""": """linear""",
        }

        config.update(**a_				)
        return config







 def _snake_case					(				self				)						->  Dict:
        for timesteps in [10, 50, 100, 1_000]:
               self.check_over_configs(num_train_timesteps=a_				)







 def _snake_case					(				self				)						->  Optional[Any]:
        for beta_start, beta_end in zip([0.0_0001, 0.0001, 0.001]    ,[0.0002, 0.002, 0.02]				):
               self.check_over_configs(beta_start=a_    ,beta_end=a_				)







 def _snake_case					(				self				)						->  Tuple:
        for schedule in ["linear", "scaled_linear", "exp"]:
               self.check_over_configs(beta_schedule=a_				)







 def _snake_case					(				self				)						->  str:
        for clip_sample_range in [1.0, 2.0, 3.0]:
               self.check_over_configs(clip_sample_range=a_    ,clip_sample=a_				)







 def _snake_case					(				self				)						->  str:
        for prediction_type in ["epsilon", "v_prediction", "sample"]:
               self.check_over_configs(prediction_type=a_				)







 def _snake_case					(				self				)						->  Any:
        _UpperCAmelCase    :		Any     	=					self.scheduler_classes[0]
        _UpperCAmelCase    :		str     	=					self.get_scheduler_config()
        _UpperCAmelCase    :		Optional[int]     	=					scheduler_class(**a_				)

        scheduler.set_timesteps(self.num_inference_steps				)

        _UpperCAmelCase    :		Optional[Any]     	=					self.dummy_model()
        _UpperCAmelCase    :		Union[str, Any]     	=					self.dummy_sample_deter * scheduler.init_noise_sigma
        _UpperCAmelCase    :		Any     	=					sample.to(a_				)

        for i, t in enumerate(scheduler.timesteps				):
               _UpperCAmelCase    :		Optional[Any]     	=					scheduler.scale_model_input(a_    ,a_				)

               _UpperCAmelCase    :		int     	=					model(a_    ,a_				)

               _UpperCAmelCase    :		Any     	=					scheduler.step(a_    ,a_    ,a_				)
               _UpperCAmelCase    :		List[str]     	=					output.prev_sample

        _UpperCAmelCase    :		Dict     	=					torch.sum(torch.abs(a_				)				)
        _UpperCAmelCase    :		Optional[int]     	=					torch.mean(torch.abs(a_				)				)

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







 def _snake_case					(				self				)						->  Optional[int]:
        _UpperCAmelCase    :		Union[str, Any]     	=					self.scheduler_classes[0]
        _UpperCAmelCase    :		List[Any]     	=					self.get_scheduler_config(prediction_type="""v_prediction"""				)
        _UpperCAmelCase    :		List[str]     	=					scheduler_class(**a_				)

        scheduler.set_timesteps(self.num_inference_steps				)

        _UpperCAmelCase    :		List[Any]     	=					self.dummy_model()
        _UpperCAmelCase    :		List[Any]     	=					self.dummy_sample_deter * scheduler.init_noise_sigma
        _UpperCAmelCase    :		Optional[int]     	=					sample.to(a_				)

        for i, t in enumerate(scheduler.timesteps				):
               _UpperCAmelCase    :		List[Any]     	=					scheduler.scale_model_input(a_    ,a_				)

               _UpperCAmelCase    :		int     	=					model(a_    ,a_				)

               _UpperCAmelCase    :		str     	=					scheduler.step(a_    ,a_    ,a_				)
               _UpperCAmelCase    :		int     	=					output.prev_sample

        _UpperCAmelCase    :		str     	=					torch.sum(torch.abs(a_				)				)
        _UpperCAmelCase    :		Optional[int]     	=					torch.mean(torch.abs(a_				)				)

        if torch_device in ["cpu", "mps"]:
               assert abs(result_sum.item() - 4.6_9_3_4E-0_7				) < 1E-2
               assert abs(result_mean.item() - 6.1_1_1_2E-1_0				) < 1E-3
        else:
               # CUDA
               assert abs(result_sum.item() - 4.6_9_3_4_2_8_6_5_0_1_7_0_9_7_2E-0_7				) < 1E-2
               assert abs(result_mean.item() - 0.0002				) < 1E-3







 def _snake_case					(				self				)						->  int:
        _UpperCAmelCase    :		List[Any]     	=					self.scheduler_classes[0]
        _UpperCAmelCase    :		Union[str, Any]     	=					self.get_scheduler_config()
        _UpperCAmelCase    :		Optional[int]     	=					scheduler_class(**a_				)

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

        _UpperCAmelCase    :		Any     	=					self.dummy_model()
        _UpperCAmelCase    :		Any     	=					self.dummy_sample_deter.to(a_				) * scheduler.init_noise_sigma

        for t in scheduler.timesteps:
               _UpperCAmelCase    :		List[Any]     	=					scheduler.scale_model_input(a_    ,a_				)

               _UpperCAmelCase    :		Tuple     	=					model(a_    ,a_				)

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

        _UpperCAmelCase    :		int     	=					torch.sum(torch.abs(a_				)				)
        _UpperCAmelCase    :		Any     	=					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() - 0.1233				) < 1E-2
               assert abs(result_mean.item() - 0.0002				) < 1E-3
        elif str(a_				).startswith("""mps"""				):
               # Larger tolerance on mps
               assert abs(result_mean.item() - 0.0002				) < 1E-2
        else:
               # CUDA
               assert abs(result_sum.item() - 0.1233				) < 1E-2
               assert abs(result_mean.item() - 0.0002				) < 1E-3







 def _snake_case					(				self				)						->  List[str]:
        _UpperCAmelCase    :		Dict     	=					self.scheduler_classes[0]
        _UpperCAmelCase    :		Any     	=					self.get_scheduler_config()
        _UpperCAmelCase    :		str     	=					scheduler_class(**a_    ,use_karras_sigmas=a_				)

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

        _UpperCAmelCase    :		int     	=					self.dummy_model()
        _UpperCAmelCase    :		Union[str, Any]     	=					self.dummy_sample_deter.to(a_				) * scheduler.init_noise_sigma
        _UpperCAmelCase    :		List[str]     	=					sample.to(a_				)

        for t in scheduler.timesteps:
               _UpperCAmelCase    :		Optional[Any]     	=					scheduler.scale_model_input(a_    ,a_				)

               _UpperCAmelCase    :		Optional[Any]     	=					model(a_    ,a_				)

               _UpperCAmelCase    :		Tuple     	=					scheduler.step(a_    ,a_    ,a_				)
               _UpperCAmelCase    :		Optional[int]     	=					output.prev_sample

        _UpperCAmelCase    :		Tuple     	=					torch.sum(torch.abs(a_				)				)
        _UpperCAmelCase    :		List[Any]     	=					torch.mean(torch.abs(a_				)				)

        assert abs(result_sum.item() - 0.0_0015				) < 1E-2
        assert abs(result_mean.item() - 1.9_8_6_9_5_5_4_5_3_5_0_3_4_6_9_5E-0_7				) < 1E-2








'''simple docstring'''






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


if is_torch_available():
   import torch

if is_vision_available():
   from PIL import Image

   from transformers import BlipImageProcessor



class 				lowercase			(    unittest.TestCase							):


 """simple docstring"""


 def __init__(				self    ,a_    ,a_=7    ,a_=3    ,a_=18    ,a_=30    ,a_=400    ,a_=True    ,a_=None    ,a_=True    ,a_=False    ,a_=[0.4814_5466, 0.457_8275, 0.4082_1073]    ,a_=[0.2686_2954, 0.2613_0258, 0.2757_7711]    ,a_=True    ,)						->  Optional[int]:
        _UpperCAmelCase    :		Dict     	=					size if size is not None else {"""height""": 20, """width""": 20}
        _UpperCAmelCase    :		Dict     	=					parent
        _UpperCAmelCase    :		Tuple     	=					batch_size
        _UpperCAmelCase    :		Optional[int]     	=					num_channels
        _UpperCAmelCase    :		int     	=					image_size
        _UpperCAmelCase    :		List[Any]     	=					min_resolution
        _UpperCAmelCase    :		str     	=					max_resolution
        _UpperCAmelCase    :		Tuple     	=					do_resize
        _UpperCAmelCase    :		Union[str, Any]     	=					size
        _UpperCAmelCase    :		int     	=					do_normalize
        _UpperCAmelCase    :		List[str]     	=					image_mean
        _UpperCAmelCase    :		Any     	=					image_std
        _UpperCAmelCase    :		Union[str, Any]     	=					do_pad
        _UpperCAmelCase    :		Tuple     	=					do_convert_rgb







 def _snake_case					(				self				)						->  List[str]:
        return {
            "do_resize": self.do_resize,
            "size": self.size,
            "do_normalize": self.do_normalize,
            "image_mean": self.image_mean,
            "image_std": self.image_std,
            "do_convert_rgb": self.do_convert_rgb,
            "do_pad": self.do_pad,
        }







 def _snake_case					(				self    ,a_=False    ,a_=False    ,a_=False				)						->  Dict:
        assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

        if equal_resolution:
               _UpperCAmelCase    :		Union[str, Any]     	=					[]
               for i in range(self.batch_size				):
                      image_inputs.append(
                          np.random.randint(
                              255    ,size=(self.num_channels, self.max_resolution, self.max_resolution)    ,dtype=np.uinta				)				)
        else:
               _UpperCAmelCase    :		Optional[int]     	=					[]
               for i in range(self.batch_size				):
                      _UpperCAmelCase	,_UpperCAmelCase    :		int     	=					np.random.choice(np.arange(self.min_resolution    ,self.max_resolution				)    ,2				)
                      image_inputs.append(np.random.randint(255    ,size=(self.num_channels, width, height)    ,dtype=np.uinta				)				)

        if not numpify and not torchify:
               # PIL expects the channel dimension as last dimension
               _UpperCAmelCase    :		Any     	=					[Image.fromarray(np.moveaxis(a_    ,0    ,-1				)				) for x in image_inputs]

        if torchify:
               _UpperCAmelCase    :		Optional[int]     	=					[torch.from_numpy(a_				) for x in image_inputs]

        return image_inputs







@require_torch
@require_vision
class 				lowercase			(    _lowerCamelCase   ,   unittest.TestCase							):


 """simple docstring"""


 UpperCAmelCase		      =    BlipImageProcessor if is_vision_available() else None







 def _snake_case					(				self				)						->  List[Any]:
        _UpperCAmelCase    :		Dict     	=					BlipImageProcessingTester(self				)







 @property
 def _snake_case					(				self				)						->  str:
        return self.image_processor_tester.prepare_image_processor_dict()







 def _snake_case					(				self				)						->  Tuple:
        _UpperCAmelCase    :		List[str]     	=					self.image_processing_class(**self.image_processor_dict				)
        self.assertTrue(hasattr(a_    ,"""do_resize"""				)				)
        self.assertTrue(hasattr(a_    ,"""size"""				)				)
        self.assertTrue(hasattr(a_    ,"""do_normalize"""				)				)
        self.assertTrue(hasattr(a_    ,"""image_mean"""				)				)
        self.assertTrue(hasattr(a_    ,"""image_std"""				)				)
        self.assertTrue(hasattr(a_    ,"""do_convert_rgb"""				)				)







 def _snake_case					(				self				)						->  Any:
        pass







 def _snake_case					(				self				)						->  Union[str, Any]:
        # Initialize image_processor
        _UpperCAmelCase    :		List[str]     	=					self.image_processing_class(**self.image_processor_dict				)
        # create random PIL images
        _UpperCAmelCase    :		str     	=					self.image_processor_tester.prepare_inputs(equal_resolution=a_				)
        for image in image_inputs:
               self.assertIsInstance(a_    ,Image.Image				)

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

        # Test batched
        _UpperCAmelCase    :		List[str]     	=					image_processor(a_    ,return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape    ,(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )    ,)







 def _snake_case					(				self				)						->  Optional[Any]:
        # Initialize image_processor
        _UpperCAmelCase    :		str     	=					self.image_processing_class(**self.image_processor_dict				)
        # create random numpy tensors
        _UpperCAmelCase    :		str     	=					self.image_processor_tester.prepare_inputs(equal_resolution=a_    ,numpify=a_				)
        for image in image_inputs:
               self.assertIsInstance(a_    ,np.ndarray				)

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

        # Test batched
        _UpperCAmelCase    :		int     	=					image_processor(a_    ,return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape    ,(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )    ,)







 def _snake_case					(				self				)						->  List[str]:
        # Initialize image_processor
        _UpperCAmelCase    :		Dict     	=					self.image_processing_class(**self.image_processor_dict				)
        # create random PyTorch tensors
        _UpperCAmelCase    :		Union[str, Any]     	=					self.image_processor_tester.prepare_inputs(equal_resolution=a_    ,torchify=a_				)
        for image in image_inputs:
               self.assertIsInstance(a_    ,torch.Tensor				)

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

        # Test batched
        _UpperCAmelCase    :		Optional[Any]     	=					image_processor(a_    ,return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape    ,(
                self.image_processor_tester.batch_size,
                self.image_processor_tester.num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )    ,)







@require_torch
@require_vision
class 				lowercase			(    _lowerCamelCase   ,   unittest.TestCase							):


 """simple docstring"""


 UpperCAmelCase		      =    BlipImageProcessor if is_vision_available() else None







 def _snake_case					(				self				)						->  Optional[Any]:
        _UpperCAmelCase    :		Optional[Any]     	=					BlipImageProcessingTester(self    ,num_channels=4				)
        _UpperCAmelCase    :		List[Any]     	=					3







 @property
 def _snake_case					(				self				)						->  int:
        return self.image_processor_tester.prepare_image_processor_dict()







 def _snake_case					(				self				)						->  Optional[Any]:
        _UpperCAmelCase    :		Optional[Any]     	=					self.image_processing_class(**self.image_processor_dict				)
        self.assertTrue(hasattr(a_    ,"""do_resize"""				)				)
        self.assertTrue(hasattr(a_    ,"""size"""				)				)
        self.assertTrue(hasattr(a_    ,"""do_normalize"""				)				)
        self.assertTrue(hasattr(a_    ,"""image_mean"""				)				)
        self.assertTrue(hasattr(a_    ,"""image_std"""				)				)
        self.assertTrue(hasattr(a_    ,"""do_convert_rgb"""				)				)







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







 def _snake_case					(				self				)						->  List[Any]:
        # Initialize image_processor
        _UpperCAmelCase    :		Any     	=					self.image_processing_class(**self.image_processor_dict				)
        # create random PIL images
        _UpperCAmelCase    :		Optional[Any]     	=					self.image_processor_tester.prepare_inputs(equal_resolution=a_				)
        for image in image_inputs:
               self.assertIsInstance(a_    ,Image.Image				)

        # Test not batched input
        _UpperCAmelCase    :		List[Any]     	=					image_processor(image_inputs[0]    ,return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape    ,(
                1,
                self.expected_encoded_image_num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )    ,)

        # Test batched
        _UpperCAmelCase    :		Dict     	=					image_processor(a_    ,return_tensors="""pt"""				).pixel_values
        self.assertEqual(
            encoded_images.shape    ,(
                self.image_processor_tester.batch_size,
                self.expected_encoded_image_num_channels,
                self.image_processor_tester.size["""height"""],
                self.image_processor_tester.size["""width"""],
            )    ,)



