






"""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 		_a   (						unittest.TestCase    ):





   '''simple docstring'''






   def __init__(    self ,      UpperCAmelCase_ ,      UpperCAmelCase_=7 ,      UpperCAmelCase_=3 ,      UpperCAmelCase_=18 ,      UpperCAmelCase_=30 ,      UpperCAmelCase_=400 ,      UpperCAmelCase_=True ,      UpperCAmelCase_=None ,      UpperCAmelCase_=True ,      UpperCAmelCase_=False ,      UpperCAmelCase_=[0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73] ,      UpperCAmelCase_=[0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11] ,      UpperCAmelCase_=True ,      )       ->					Optional[int]:




          '''simple docstring'''




          lowercase__:				int			  =			size if size is not None else {"""height""": 20, """width""": 20}
          lowercase__:				Any			  =			parent
          lowercase__:				int			  =			batch_size
          lowercase__:				str			  =			num_channels
          lowercase__:				str			  =			image_size
          lowercase__:				Union[str, Any]			  =			min_resolution
          lowercase__:				Any			  =			max_resolution
          lowercase__:				List[str]			  =			do_resize
          lowercase__:				Optional[int]			  =			size
          lowercase__:				List[Any]			  =			do_normalize
          lowercase__:				Optional[int]			  =			image_mean
          lowercase__:				List[Any]			  =			image_std
          lowercase__:				Optional[int]			  =			do_pad
          lowercase__:				Union[str, Any]			  =			do_convert_rgb





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




          '''simple docstring'''




          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 __lowercase				(    self ,      UpperCAmelCase_=False ,      UpperCAmelCase_=False ,      UpperCAmelCase_=False)       ->					List[str]:




          '''simple docstring'''




          assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time"

          if equal_resolution:
                 lowercase__:				Tuple			  =			[]
                 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:
                 lowercase__:				str			  =			[]
                 for i in range(self.batch_size):
                        lowercase__:				str			  =			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
                 lowercase__:				str			  =			[Image.fromarray(np.moveaxis(lowerCAmelCase__ ,      0 ,      -1)) for x in image_inputs]

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

          return image_inputs







@require_torch
@require_vision
class 		_a   (						__a				,     unittest.TestCase    ):





   '''simple docstring'''






   UpperCamelCase__			     =				BlipImageProcessor if is_vision_available() else None





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




          '''simple docstring'''




          lowercase__:				List[str]			  =			BlipImageProcessingTester(self)





   @property
   def __lowercase				(    self)       ->					str:




          '''simple docstring'''




          return self.image_processor_tester.prepare_image_processor_dict()





   def __lowercase				(    self)       ->					int:




          '''simple docstring'''




          lowercase__:				int			  =			self.image_processing_class(**self.image_processor_dict)
          self.assertTrue(hasattr(lowerCAmelCase__ ,      "do_resize"))
          self.assertTrue(hasattr(lowerCAmelCase__ ,      "size"))
          self.assertTrue(hasattr(lowerCAmelCase__ ,      "do_normalize"))
          self.assertTrue(hasattr(lowerCAmelCase__ ,      "image_mean"))
          self.assertTrue(hasattr(lowerCAmelCase__ ,      "image_std"))
          self.assertTrue(hasattr(lowerCAmelCase__ ,      "do_convert_rgb"))





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




          '''simple docstring'''




          pass





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




          '''simple docstring'''




          lowercase__:				Any			  =			self.image_processing_class(**self.image_processor_dict)
          # create random PIL images
          lowercase__:				int			  =			self.image_processor_tester.prepare_inputs(equal_resolution=lowerCAmelCase__)
          for image in image_inputs:
                 self.assertIsInstance(lowerCAmelCase__ ,      Image.Image)

          # Test not batched input
          lowercase__:				Any			  =			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
          lowercase__:				Optional[int]			  =			image_processor(lowerCAmelCase__ ,      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 __lowercase				(    self)       ->					Any:




          '''simple docstring'''




          lowercase__:				Dict			  =			self.image_processing_class(**self.image_processor_dict)
          # create random numpy tensors
          lowercase__:				Optional[int]			  =			self.image_processor_tester.prepare_inputs(equal_resolution=lowerCAmelCase__ ,      numpify=lowerCAmelCase__)
          for image in image_inputs:
                 self.assertIsInstance(lowerCAmelCase__ ,      np.ndarray)

          # Test not batched input
          lowercase__:				Optional[Any]			  =			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
          lowercase__:				Any			  =			image_processor(lowerCAmelCase__ ,      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 __lowercase				(    self)       ->					Optional[int]:




          '''simple docstring'''




          lowercase__:				Optional[Any]			  =			self.image_processing_class(**self.image_processor_dict)
          # create random PyTorch tensors
          lowercase__:				Optional[Any]			  =			self.image_processor_tester.prepare_inputs(equal_resolution=lowerCAmelCase__ ,      torchify=lowerCAmelCase__)
          for image in image_inputs:
                 self.assertIsInstance(lowerCAmelCase__ ,      torch.Tensor)

          # Test not batched input
          lowercase__:				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
          lowercase__:				List[str]			  =			image_processor(lowerCAmelCase__ ,      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 		_a   (						__a				,     unittest.TestCase    ):





   '''simple docstring'''






   UpperCamelCase__			     =				BlipImageProcessor if is_vision_available() else None





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




          '''simple docstring'''




          lowercase__:				Optional[int]			  =			BlipImageProcessingTester(self ,      num_channels=4)
          lowercase__:				Tuple			  =			3





   @property
   def __lowercase				(    self)       ->					Optional[Any]:




          '''simple docstring'''




          return self.image_processor_tester.prepare_image_processor_dict()





   def __lowercase				(    self)       ->					Tuple:




          '''simple docstring'''




          lowercase__:				Optional[Any]			  =			self.image_processing_class(**self.image_processor_dict)
          self.assertTrue(hasattr(lowerCAmelCase__ ,      "do_resize"))
          self.assertTrue(hasattr(lowerCAmelCase__ ,      "size"))
          self.assertTrue(hasattr(lowerCAmelCase__ ,      "do_normalize"))
          self.assertTrue(hasattr(lowerCAmelCase__ ,      "image_mean"))
          self.assertTrue(hasattr(lowerCAmelCase__ ,      "image_std"))
          self.assertTrue(hasattr(lowerCAmelCase__ ,      "do_convert_rgb"))





   def __lowercase				(    self)       ->					int:




          '''simple docstring'''




          pass





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




          '''simple docstring'''




          lowercase__:				Tuple			  =			self.image_processing_class(**self.image_processor_dict)
          # create random PIL images
          lowercase__:				List[str]			  =			self.image_processor_tester.prepare_inputs(equal_resolution=lowerCAmelCase__)
          for image in image_inputs:
                 self.assertIsInstance(lowerCAmelCase__ ,      Image.Image)

          # Test not batched input
          lowercase__:				Optional[int]			  =			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
          lowercase__:				List[str]			  =			image_processor(lowerCAmelCase__ ,      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"],
              ) ,      )








'''simple docstring'''

import torch

from diffusers import HeunDiscreteScheduler
from diffusers.utils import torch_device

from .test_schedulers import SchedulerCommonTest







class 	__lowerCAmelCase    (  __a				):
     snake_case   :    List[str]							      =      (HeunDiscreteScheduler,)
     snake_case   :    Optional[Any]							      =      1_0



     def     snake_case_ (self						,	**lowerCAmelCase__	):
          _UpperCAmelCase					:  Union[str, Any]         =    {
              """num_train_timesteps""": 1_1_0_0,
              """beta_start""": 0.0_0_0_1,
              """beta_end""": 0.0_2,
              """beta_schedule""": """linear""",
          }

          config.update(**lowerCAmelCase__	)
          return config



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



     def     snake_case_ (self	):
          for beta_start, beta_end in zip([0.0_0_0_0_1, 0.0_0_0_1, 0.0_0_1]						,	[0.0_0_0_2, 0.0_0_2, 0.0_2]	):
               self.check_over_configs(beta_start=lowerCAmelCase__						,	beta_end=lowerCAmelCase__	)



     def     snake_case_ (self	):
          for schedule in ["linear", "scaled_linear", "exp"]:
               self.check_over_configs(beta_schedule=lowerCAmelCase__	)



     def     snake_case_ (self	):
          for clip_sample_range in [1.0, 2.0, 3.0]:
               self.check_over_configs(clip_sample_range=lowerCAmelCase__						,	clip_sample=lowerCAmelCase__	)



     def     snake_case_ (self	):
          for prediction_type in ["epsilon", "v_prediction", "sample"]:
               self.check_over_configs(prediction_type=lowerCAmelCase__	)



     def     snake_case_ (self	):
          _UpperCAmelCase					:  Tuple         =    self.scheduler_classes[0]
          _UpperCAmelCase					:  Optional[int]         =    self.get_scheduler_config()
          _UpperCAmelCase					:  List[str]         =    scheduler_class(**lowerCAmelCase__	)

          scheduler.set_timesteps(self.num_inference_steps	)

          _UpperCAmelCase					:  str         =    self.dummy_model()
          _UpperCAmelCase					:  List[Any]         =    self.dummy_sample_deter * scheduler.init_noise_sigma
          _UpperCAmelCase					:  Tuple         =    sample.to(lowerCAmelCase__	)

          for i, t in enumerate(scheduler.timesteps	):
               _UpperCAmelCase					:  Union[str, Any]         =    scheduler.scale_model_input(lowerCAmelCase__						,	lowerCAmelCase__	)

               _UpperCAmelCase					:  Any         =    model(lowerCAmelCase__						,	lowerCAmelCase__	)

               _UpperCAmelCase					:  Tuple         =    scheduler.step(lowerCAmelCase__						,	lowerCAmelCase__						,	lowerCAmelCase__	)
               _UpperCAmelCase					:  Optional[Any]         =    output.prev_sample

          _UpperCAmelCase					:  Optional[Any]         =    torch.sum(torch.abs(lowerCAmelCase__	)	)
          _UpperCAmelCase					:  int         =    torch.mean(torch.abs(lowerCAmelCase__	)	)

          if torch_device in ["cpu", "mps"]:
               assert abs(result_sum.item() - 0.1_2_3_3	) < 1e-2
               assert abs(result_mean.item() - 0.0_0_0_2	) < 1e-3
          else:
               # CUDA
               assert abs(result_sum.item() - 0.1_2_3_3	) < 1e-2
               assert abs(result_mean.item() - 0.0_0_0_2	) < 1e-3



     def     snake_case_ (self	):
          _UpperCAmelCase					:  Optional[int]         =    self.scheduler_classes[0]
          _UpperCAmelCase					:  Any         =    self.get_scheduler_config(prediction_type="""v_prediction"""	)
          _UpperCAmelCase					:  Any         =    scheduler_class(**lowerCAmelCase__	)

          scheduler.set_timesteps(self.num_inference_steps	)

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

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

               _UpperCAmelCase					:  List[Any]         =    model(lowerCAmelCase__						,	lowerCAmelCase__	)

               _UpperCAmelCase					:  Optional[Any]         =    scheduler.step(lowerCAmelCase__						,	lowerCAmelCase__						,	lowerCAmelCase__	)
               _UpperCAmelCase					:  Union[str, Any]         =    output.prev_sample

          _UpperCAmelCase					:  Union[str, Any]         =    torch.sum(torch.abs(lowerCAmelCase__	)	)
          _UpperCAmelCase					:  str         =    torch.mean(torch.abs(lowerCAmelCase__	)	)

          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_0_0_2	) < 1e-3



     def     snake_case_ (self	):
          _UpperCAmelCase					:  Tuple         =    self.scheduler_classes[0]
          _UpperCAmelCase					:  Any         =    self.get_scheduler_config()
          _UpperCAmelCase					:  Optional[int]         =    scheduler_class(**lowerCAmelCase__	)

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

          _UpperCAmelCase					:  List[Any]         =    self.dummy_model()
          _UpperCAmelCase					:  Dict         =    self.dummy_sample_deter.to(lowerCAmelCase__	) * scheduler.init_noise_sigma

          for t in scheduler.timesteps:
               _UpperCAmelCase					:  Union[str, Any]         =    scheduler.scale_model_input(lowerCAmelCase__						,	lowerCAmelCase__	)

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

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

          _UpperCAmelCase					:  Any         =    torch.sum(torch.abs(lowerCAmelCase__	)	)
          _UpperCAmelCase					:  Optional[Any]         =    torch.mean(torch.abs(lowerCAmelCase__	)	)

          if str(lowerCAmelCase__	).startswith("""cpu"""	):
               # The following sum varies between 148 and 156 on mps. Why?
               assert abs(result_sum.item() - 0.1_2_3_3	) < 1e-2
               assert abs(result_mean.item() - 0.0_0_0_2	) < 1e-3
          elif str(lowerCAmelCase__	).startswith("""mps"""	):
               # Larger tolerance on mps
               assert abs(result_mean.item() - 0.0_0_0_2	) < 1e-2
          else:
               # CUDA
               assert abs(result_sum.item() - 0.1_2_3_3	) < 1e-2
               assert abs(result_mean.item() - 0.0_0_0_2	) < 1e-3



     def     snake_case_ (self	):
          _UpperCAmelCase					:  int         =    self.scheduler_classes[0]
          _UpperCAmelCase					:  str         =    self.get_scheduler_config()
          _UpperCAmelCase					:  Union[str, Any]         =    scheduler_class(**lowerCAmelCase__						,	use_karras_sigmas=lowerCAmelCase__	)

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

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

          for t in scheduler.timesteps:
               _UpperCAmelCase					:  Dict         =    scheduler.scale_model_input(lowerCAmelCase__						,	lowerCAmelCase__	)

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

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

          _UpperCAmelCase					:  Union[str, Any]         =    torch.sum(torch.abs(lowerCAmelCase__	)	)
          _UpperCAmelCase					:  List[Any]         =    torch.mean(torch.abs(lowerCAmelCase__	)	)

          assert abs(result_sum.item() - 0.0_0_0_1_5	) < 1e-2
          assert abs(result_mean.item() - 1.9_869_554_535_034_695e-07	) < 1e-2


