






"""simple docstring"""







import gc
import math
import unittest

import torch

from diffusers import UNetaDModel
from diffusers.utils import floats_tensor, logging, slow, torch_all_close, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from .test_modeling_common import ModelTesterMixin, UNetTesterMixin


lowerCAmelCase_	:    Optional[int]            =      logging.get_logger(__name__)

enable_full_determinism()





class   UpperCamelCase_ (       a_   ,					a_   ,					unittest.TestCase  ):
  _A       :					List[str]				=	UNetaDModel
  _A       :					Any				=	'sample'



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



         """simple docstring"""





         UpperCAmelCase	    =			4
         UpperCAmelCase	    =			3
         UpperCAmelCase	    =			(32, 32)

         UpperCAmelCase	    =			floats_tensor((batch_size, num_channels) + sizes				).to(snake_case__				)
         UpperCAmelCase	    =			torch.tensor([10]				).to(snake_case__				)

         return {"sample": noise, "timestep": time_step}



  @property
  def 		UpperCamelCase_				(      self				)			->			int:



         """simple docstring"""





         return (3, 32, 32)



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



         """simple docstring"""





         return (3, 32, 32)



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



         """simple docstring"""





         UpperCAmelCase	    =			{
             """block_out_channels""": (32, 64),
             """down_block_types""": ("""DownBlock2D""", """AttnDownBlock2D"""),
             """up_block_types""": ("""AttnUpBlock2D""", """UpBlock2D"""),
             """attention_head_dim""": 3,
             """out_channels""": 3,
             """in_channels""": 3,
             """layers_per_block""": 2,
             """sample_size""": 32,
         }
         UpperCAmelCase	    =			self.dummy_input
         return init_dict, inputs_dict





class   UpperCamelCase_ (       a_   ,					a_   ,					unittest.TestCase  ):
  _A       :					Optional[Any]				=	UNetaDModel
  _A       :					Tuple				=	'sample'



  @property
  def 		UpperCamelCase_				(      self				)			->			int:



         """simple docstring"""





         UpperCAmelCase	    =			4
         UpperCAmelCase	    =			4
         UpperCAmelCase	    =			(32, 32)

         UpperCAmelCase	    =			floats_tensor((batch_size, num_channels) + sizes				).to(snake_case__				)
         UpperCAmelCase	    =			torch.tensor([10]				).to(snake_case__				)

         return {"sample": noise, "timestep": time_step}



  @property
  def 		UpperCamelCase_				(      self				)			->			Dict:



         """simple docstring"""





         return (4, 32, 32)



  @property
  def 		UpperCamelCase_				(      self				)			->			Optional[int]:



         """simple docstring"""





         return (4, 32, 32)



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



         """simple docstring"""





         UpperCAmelCase	    =			{
             """sample_size""": 32,
             """in_channels""": 4,
             """out_channels""": 4,
             """layers_per_block""": 2,
             """block_out_channels""": (32, 64),
             """attention_head_dim""": 32,
             """down_block_types""": ("""DownBlock2D""", """DownBlock2D"""),
             """up_block_types""": ("""UpBlock2D""", """UpBlock2D"""),
         }
         UpperCAmelCase	    =			self.dummy_input
         return init_dict, inputs_dict



  def 		UpperCamelCase_				(      self				)			->			Dict:



         """simple docstring"""





         UpperCAmelCase    ,       UpperCAmelCase	    =			UNetaDModel.from_pretrained("""fusing/unet-ldm-dummy-update""" ,		output_loading_info=snake_case__				)

         self.assertIsNotNone(snake_case__				)
         self.assertEqual(len(loading_info["""missing_keys"""]				) ,		0				)

         model.to(snake_case__				)
         UpperCAmelCase	    =			model(**self.dummy_input				).sample

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



  @unittest.skipIf(torch_device != """cuda""" ,		"""This test is supposed to run on GPU"""				)
  def 		UpperCamelCase_				(      self				)			->			int:



         """simple docstring"""





         UpperCAmelCase    ,       UpperCAmelCase	    =			UNetaDModel.from_pretrained("""fusing/unet-ldm-dummy-update""" ,		output_loading_info=snake_case__				)
         model.to(snake_case__				)
         UpperCAmelCase	    =			model(**self.dummy_input				).sample

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



  @unittest.skipIf(torch_device != """cuda""" ,		"""This test is supposed to run on GPU"""				)
  def 		UpperCamelCase_				(      self				)			->			Tuple:



         """simple docstring"""





         UpperCAmelCase    ,       UpperCAmelCase	    =			UNetaDModel.from_pretrained("""fusing/unet-ldm-dummy-update""" ,		output_loading_info=snake_case__				)
         model_accelerate.to(snake_case__				)
         model_accelerate.eval()

         UpperCAmelCase	    =			torch.randn(
             1 ,		model_accelerate.config.in_channels ,		model_accelerate.config.sample_size ,		model_accelerate.config.sample_size ,		generator=torch.manual_seed(0				) ,		)
         UpperCAmelCase	    =			noise.to(snake_case__				)
         UpperCAmelCase	    =			torch.tensor([10] * noise.shape[0]				).to(snake_case__				)

         UpperCAmelCase	    =			model_accelerate(snake_case__ ,		snake_case__				)["""sample"""]

         # two models don't need to stay in the device at the same time
         del model_accelerate
         torch.cuda.empty_cache()
         gc.collect()

         UpperCAmelCase    ,       UpperCAmelCase	    =			UNetaDModel.from_pretrained(
             """fusing/unet-ldm-dummy-update""" ,		output_loading_info=snake_case__ ,		low_cpu_mem_usage=snake_case__				)
         model_normal_load.to(snake_case__				)
         model_normal_load.eval()
         UpperCAmelCase	    =			model_normal_load(snake_case__ ,		snake_case__				)["""sample"""]

         assert torch_all_close(snake_case__ ,		snake_case__ ,		rtol=1e-3				)



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



         """simple docstring"""





         UpperCAmelCase	    =			UNetaDModel.from_pretrained("""fusing/unet-ldm-dummy-update"""				)
         model.eval()
         model.to(snake_case__				)

         UpperCAmelCase	    =			torch.randn(
             1 ,		model.config.in_channels ,		model.config.sample_size ,		model.config.sample_size ,		generator=torch.manual_seed(0				) ,		)
         UpperCAmelCase	    =			noise.to(snake_case__				)
         UpperCAmelCase	    =			torch.tensor([10] * noise.shape[0]				).to(snake_case__				)

         with torch.no_grad():
                UpperCAmelCase	    =			model(snake_case__ ,		snake_case__				).sample

         UpperCAmelCase	    =			output[0, -1, -3:, -3:].flatten().cpu()
         # fmt: off
         UpperCAmelCase	    =			torch.tensor([-13.3_258, -20.1_100, -15.9_873, -17.6_617, -23.0_596, -17.9_419, -13.3_675, -16.1_889, -12.3_800]				)
         # fmt: on

         self.assertTrue(torch_all_close(snake_case__ ,		snake_case__ ,		rtol=1e-3				)				)





class   UpperCamelCase_ (       a_   ,					a_   ,					unittest.TestCase  ):
  _A       :					int				=	UNetaDModel
  _A       :					Dict				=	'sample'



  @property
  def 		UpperCamelCase_				(      self ,		snake_case__=(32, 32)				)			->			List[str]:



         """simple docstring"""





         UpperCAmelCase	    =			4
         UpperCAmelCase	    =			3

         UpperCAmelCase	    =			floats_tensor((batch_size, num_channels) + sizes				).to(snake_case__				)
         UpperCAmelCase	    =			torch.tensor(batch_size * [10]				).to(dtype=torch.intaa ,		device=snake_case__				)

         return {"sample": noise, "timestep": time_step}



  @property
  def 		UpperCamelCase_				(      self				)			->			Dict:



         """simple docstring"""





         return (3, 32, 32)



  @property
  def 		UpperCamelCase_				(      self				)			->			Dict:



         """simple docstring"""





         return (3, 32, 32)



  def 		UpperCamelCase_				(      self				)			->			Dict:



         """simple docstring"""





         UpperCAmelCase	    =			{
             """block_out_channels""": [32, 64, 64, 64],
             """in_channels""": 3,
             """layers_per_block""": 1,
             """out_channels""": 3,
             """time_embedding_type""": """fourier""",
             """norm_eps""": 1e-6,
             """mid_block_scale_factor""": math.sqrt(2.0				),
             """norm_num_groups""": None,
             """down_block_types""": [
                 """SkipDownBlock2D""",
                 """AttnSkipDownBlock2D""",
                 """SkipDownBlock2D""",
                 """SkipDownBlock2D""",
             ],
             """up_block_types""": [
                 """SkipUpBlock2D""",
                 """SkipUpBlock2D""",
                 """AttnSkipUpBlock2D""",
                 """SkipUpBlock2D""",
             ],
         }
         UpperCAmelCase	    =			self.dummy_input
         return init_dict, inputs_dict



  @slow
  def 		UpperCamelCase_				(      self				)			->			List[str]:



         """simple docstring"""





         UpperCAmelCase    ,       UpperCAmelCase	    =			UNetaDModel.from_pretrained("""google/ncsnpp-celebahq-256""" ,		output_loading_info=snake_case__				)
         self.assertIsNotNone(snake_case__				)
         self.assertEqual(len(loading_info["""missing_keys"""]				) ,		0				)

         model.to(snake_case__				)
         UpperCAmelCase	    =			self.dummy_input
         UpperCAmelCase	    =			floats_tensor((4, 3) + (2_56, 2_56)				).to(snake_case__				)
         UpperCAmelCase	    =			noise
         UpperCAmelCase	    =			model(**snake_case__				)

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



  @slow
  def 		UpperCamelCase_				(      self				)			->			Any:



         """simple docstring"""





         UpperCAmelCase	    =			UNetaDModel.from_pretrained("""google/ncsnpp-celebahq-256"""				)
         model.to(snake_case__				)

         UpperCAmelCase	    =			4
         UpperCAmelCase	    =			3
         UpperCAmelCase	    =			(2_56, 2_56)

         UpperCAmelCase	    =			torch.ones((batch_size, num_channels) + sizes				).to(snake_case__				)
         UpperCAmelCase	    =			torch.tensor(batch_size * [1e-4]				).to(snake_case__				)

         with torch.no_grad():
                UpperCAmelCase	    =			model(snake_case__ ,		snake_case__				).sample

         UpperCAmelCase	    =			output[0, -3:, -3:, -1].flatten().cpu()
         # fmt: off
         UpperCAmelCase	    =			torch.tensor([-4_842.8_691, -6_499.6_631, -3_800.1_953, -7_978.2_686, -10_980.7_129, -20_028.8_535, 8_148.2_822, 2_342.2_905, 567.7_608]				)
         # fmt: on

         self.assertTrue(torch_all_close(snake_case__ ,		snake_case__ ,		rtol=1e-2				)				)



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



         """simple docstring"""





         UpperCAmelCase	    =			UNetaDModel.from_pretrained("""fusing/ncsnpp-ffhq-ve-dummy-update"""				)
         model.to(snake_case__				)

         UpperCAmelCase	    =			4
         UpperCAmelCase	    =			3
         UpperCAmelCase	    =			(32, 32)

         UpperCAmelCase	    =			torch.ones((batch_size, num_channels) + sizes				).to(snake_case__				)
         UpperCAmelCase	    =			torch.tensor(batch_size * [1e-4]				).to(snake_case__				)

         with torch.no_grad():
                UpperCAmelCase	    =			model(snake_case__ ,		snake_case__				).sample

         UpperCAmelCase	    =			output[0, -3:, -3:, -1].flatten().cpu()
         # fmt: off
         UpperCAmelCase	    =			torch.tensor([-0.0_325, -0.0_900, -0.0_869, -0.0_332, -0.0_725, -0.0_270, -0.0_101, 0.0_227, 0.0_256]				)
         # fmt: on

         self.assertTrue(torch_all_close(snake_case__ ,		snake_case__ ,		rtol=1e-2				)				)



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



         """simple docstring"""





         pass








"""simple docstring"""







from typing import Dict, List, Optional, Union

import numpy as np

from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict
from ...image_transforms import (
    center_crop,
    get_resize_output_image_size,
    normalize,
    rescale,
    resize,
    to_channel_dimension_format,
)
from ...image_utils import (
    IMAGENET_DEFAULT_MEAN,
    IMAGENET_DEFAULT_STD,
    ChannelDimension,
    ImageInput,
    PILImageResampling,
    make_list_of_images,
    to_numpy_array,
    valid_images,
)
from ...utils import TensorType, is_vision_available, logging


if is_vision_available():
 import PIL


lowerCAmelCase_	:    Union[str, Any]            =      logging.get_logger(__name__)





class   UpperCamelCase_ (       a_  ):
  _A       :					List[str]				=	['pixel_values']



  def __init__(      self ,		snake_case__ = True ,		snake_case__ = None ,		snake_case__ = 0.9 ,		snake_case__ = PILImageResampling.BICUBIC ,		snake_case__ = True ,		snake_case__ = None ,		snake_case__ = 1 / 2_55 ,		snake_case__ = True ,		snake_case__ = True ,		snake_case__ = None ,		snake_case__ = None ,		**snake_case__ ,		)			->			None:



         """simple docstring"""





         super().__init__(**snake_case__				)
         UpperCAmelCase	    =			size if size is not None else {"""shortest_edge""": 2_24}
         UpperCAmelCase	    =			get_size_dict(snake_case__ ,		default_to_square=snake_case__				)
         UpperCAmelCase	    =			crop_size if crop_size is not None else {"""height""": 2_24, """width""": 2_24}
         UpperCAmelCase	    =			get_size_dict(snake_case__ ,		param_name="""crop_size"""				)

         UpperCAmelCase	    =			do_resize
         UpperCAmelCase	    =			size
         UpperCAmelCase	    =			crop_pct
         UpperCAmelCase	    =			resample
         UpperCAmelCase	    =			do_center_crop
         UpperCAmelCase	    =			crop_size
         UpperCAmelCase	    =			do_rescale
         UpperCAmelCase	    =			rescale_factor
         UpperCAmelCase	    =			do_normalize
         UpperCAmelCase	    =			image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN
         UpperCAmelCase	    =			image_std if image_std is not None else IMAGENET_DEFAULT_STD



  def 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__ = None ,		snake_case__ = PILImageResampling.BICUBIC ,		snake_case__ = None ,		**snake_case__ ,		)			->			np.ndarray:



         """simple docstring"""





         UpperCAmelCase	    =			get_size_dict(snake_case__ ,		default_to_square=snake_case__				)
         if "shortest_edge" not in size and ("height" not in size or "width" not in size):
                raise ValueError(f'''size must contain \'height\' and \'width\' or \'shortest_edge\' as keys. Got {size.keys()}'''				)
         if crop_pct is not None:
                if "shortest_edge" in size:
                       UpperCAmelCase	    =			int(size["""shortest_edge"""] / crop_pct				)
                elif "height" in size and "width" in size:
                       if size["height"] == size["width"]:
                              UpperCAmelCase	    =			int(size["""height"""] / crop_pct				)
                       else:
                              UpperCAmelCase	    =			(int(size["""height"""] / crop_pct				), int(size["""width"""] / crop_pct				))
                else:
                       raise ValueError("""Invalid size for resize: {}""".format(snake_case__				)				)

                UpperCAmelCase	    =			get_resize_output_image_size(snake_case__ ,		size=snake_case__ ,		default_to_square=snake_case__				)
         else:
                if "shortest_edge" in size:
                       UpperCAmelCase	    =			get_resize_output_image_size(snake_case__ ,		size=size["""shortest_edge"""] ,		default_to_square=snake_case__				)
                elif "height" in size and "width" in size:
                       UpperCAmelCase	    =			(size["""height"""], size["""width"""])
                else:
                       raise ValueError("""Invalid size for resize: {}""".format(snake_case__				)				)

         return resize(snake_case__ ,		size=snake_case__ ,		resample=snake_case__ ,		data_format=snake_case__ ,		**snake_case__				)



  def 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__ = None ,		**snake_case__ ,		)			->			np.ndarray:



         """simple docstring"""





         UpperCAmelCase	    =			get_size_dict(snake_case__				)
         if "height" not in size or "width" not in size:
                raise ValueError(f'''size must contain \'height\' and \'width\' as keys. Got {size.keys()}'''				)
         return center_crop(snake_case__ ,		size=(size["""height"""], size["""width"""]) ,		data_format=snake_case__ ,		**snake_case__				)



  def 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__ = None ,		**snake_case__ ,		)			->			Tuple:



         """simple docstring"""





         return rescale(snake_case__ ,		scale=snake_case__ ,		data_format=snake_case__ ,		**snake_case__				)



  def 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ ,		snake_case__ ,		snake_case__ = None ,		**snake_case__ ,		)			->			np.ndarray:



         """simple docstring"""





         return normalize(snake_case__ ,		mean=snake_case__ ,		std=snake_case__ ,		data_format=snake_case__ ,		**snake_case__				)



  def 		UpperCamelCase_				(      self ,		snake_case__ ,		snake_case__ = None ,		snake_case__ = None ,		snake_case__ = None ,		snake_case__ = None ,		snake_case__ = None ,		snake_case__ = None ,		snake_case__ = None ,		snake_case__ = None ,		snake_case__ = None ,		snake_case__ = None ,		snake_case__ = None ,		snake_case__ = None ,		snake_case__ = ChannelDimension.FIRST ,		**snake_case__ ,		)			->			PIL.Image.Image:



         """simple docstring"""





         UpperCAmelCase	    =			do_resize if do_resize is not None else self.do_resize
         UpperCAmelCase	    =			crop_pct if crop_pct is not None else self.crop_pct
         UpperCAmelCase	    =			resample if resample is not None else self.resample
         UpperCAmelCase	    =			do_center_crop if do_center_crop is not None else self.do_center_crop
         UpperCAmelCase	    =			do_rescale if do_rescale is not None else self.do_rescale
         UpperCAmelCase	    =			rescale_factor if rescale_factor is not None else self.rescale_factor
         UpperCAmelCase	    =			do_normalize if do_normalize is not None else self.do_normalize
         UpperCAmelCase	    =			image_mean if image_mean is not None else self.image_mean
         UpperCAmelCase	    =			image_std if image_std is not None else self.image_std

         UpperCAmelCase	    =			size if size is not None else self.size
         UpperCAmelCase	    =			get_size_dict(snake_case__ ,		default_to_square=snake_case__				)
         UpperCAmelCase	    =			crop_size if crop_size is not None else self.crop_size
         UpperCAmelCase	    =			get_size_dict(snake_case__ ,		param_name="""crop_size"""				)

         UpperCAmelCase	    =			make_list_of_images(snake_case__				)

         if not valid_images(snake_case__				):
                raise ValueError(
                    """Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
                    """torch.Tensor, tf.Tensor or jax.ndarray."""				)

         if do_resize and size is None or resample is None:
                raise ValueError("""Size and resample must be specified if do_resize is True."""				)

         if do_center_crop and crop_pct is None:
                raise ValueError("""Crop_pct must be specified if do_center_crop is True."""				)

         if do_rescale and rescale_factor is None:
                raise ValueError("""Rescale factor must be specified if do_rescale is True."""				)

         if do_normalize and (image_mean is None or image_std is None):
                raise ValueError("""Image mean and std must be specified if do_normalize is True."""				)

         # All transformations expect numpy arrays.
         UpperCAmelCase	    =			[to_numpy_array(snake_case__				) for image in images]

         if do_resize:
                UpperCAmelCase	    =			[self.resize(image=snake_case__ ,		size=snake_case__ ,		crop_pct=snake_case__ ,		resample=snake_case__				) for image in images]

         if do_center_crop:
                UpperCAmelCase	    =			[self.center_crop(image=snake_case__ ,		size=snake_case__				) for image in images]

         if do_rescale:
                UpperCAmelCase	    =			[self.rescale(image=snake_case__ ,		scale=snake_case__				) for image in images]

         if do_normalize:
                UpperCAmelCase	    =			[self.normalize(image=snake_case__ ,		mean=snake_case__ ,		std=snake_case__				) for image in images]

         UpperCAmelCase	    =			[to_channel_dimension_format(snake_case__ ,		snake_case__				) for image in images]

         UpperCAmelCase	    =			{"""pixel_values""": images}
         return BatchFeature(data=snake_case__ ,		tensor_type=snake_case__				)
