"""simple docstring"""







import tempfile
import unittest

import torch

from diffusers import UNetaDConditionModel
from diffusers.training_utils import EMAModel
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps, torch_device


enable_full_determinism()






class 							__snake_case(					unittest.TestCase	):


    '''simple docstring'''





    _UpperCAmelCase       =			'''hf-internal-testing/tiny-stable-diffusion-pipe'''
    _UpperCAmelCase       =			1
    _UpperCAmelCase       =			7_7
    _UpperCAmelCase       =			3_2
    _UpperCAmelCase       =			4
    _UpperCAmelCase       =			6_4
    _UpperCAmelCase       =			torch.manual_seed(0	)
    def 						_a							(  self					,       __lowerCamelCase=0.99_99	):




         '''simple docstring'''



         __A					:					Optional[int]								=		UNetaDConditionModel.from_pretrained(self.model_id					,       subfolder='unet'	)
         __A					:					int								=		unet.to(A_	)
         __A					:					Union[str, Any]								=		EMAModel(unet.parameters()					,       decay=A_					,       model_cls=A_					,       model_config=unet.config	)
         return unet, ema_unet
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					Optional[int]								=		torch.randn(
             self.batch_size					,       self.num_in_channels					,       self.latent_height					,       self.latent_width					,       generator=self.generator	).to(A_	)
         __A					:					Optional[int]								=		torch.randint(0					,       1000					,       size=(self.batch_size,)					,       generator=self.generator	).to(A_	)
         __A					:					Any								=		torch.randn(
             self.batch_size					,       self.prompt_length					,       self.text_encoder_hidden_dim					,       generator=self.generator	).to(A_	)
         return noisy_latents, timesteps, encoder_hidden_states
    def 						_a							(  self					,       __lowerCamelCase	):




         '''simple docstring'''



         __A					:					Dict								=		{}
         for k, param in unet.state_dict().items():
              __A					:					List[Any]								=		torch.randn_like(A_	) + (param * torch.randn_like(A_	))
              updated_state_dict.update({k: updated_param}	)
         unet.load_state_dict(A_	)
         return unet
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					Tuple								=		self.get_models()
         # Take the first (hypothetical) EMA step.
         ema_unet.step(unet.parameters()	)
         assert ema_unet.optimization_step == 1

         # Take two more.
         for _ in range(2	):
              ema_unet.step(unet.parameters()	)
         assert ema_unet.optimization_step == 3
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					Dict								=		self.get_models()
         # Since the `unet` is not being updated (i.e., backprop'd)
         # there won't be any difference between the `params` of `unet`
         # and `ema_unet` even if we call `ema_unet.step(unet.parameters())`.
         ema_unet.step(unet.parameters()	)
         __A					:					List[Any]								=		list(unet.parameters()	)
         for s_param, param in zip(ema_unet.shadow_params					,       A_	):
              assert torch.allclose(A_					,       A_	)

         # The above holds true even if we call `ema.step()` multiple times since
         # `unet` params are still not being updated.
         for _ in range(4	):
              ema_unet.step(unet.parameters()	)
         for s_param, param in zip(ema_unet.shadow_params					,       A_	):
              assert torch.allclose(A_					,       A_	)
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					List[Any]								=		self.get_models()
         # Here we simulate the parameter updates for `unet`. Since there might
         # be some parameters which are initialized to zero we take extra care to
         # initialize their values to something non-zero before the multiplication.
         __A					:					str								=		self.simulate_backprop(A_	)

         # Take the EMA step.
         ema_unet.step(unet_pseudo_updated_step_one.parameters()	)

         # Now the EMA'd parameters won't be equal to the original model parameters.
         __A					:					Dict								=		list(unet_pseudo_updated_step_one.parameters()	)
         for s_param, param in zip(ema_unet.shadow_params					,       A_	):
              assert ~torch.allclose(A_					,       A_	)

         # Ensure this is the case when we take multiple EMA steps.
         for _ in range(4	):
              ema_unet.step(unet.parameters()	)
         for s_param, param in zip(ema_unet.shadow_params					,       A_	):
              assert ~torch.allclose(A_					,       A_	)
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					int								=		self.get_models()

         # First backprop + EMA
         __A					:					Dict								=		self.simulate_backprop(A_	)
         ema_unet.step(unet_step_one.parameters()	)
         __A					:					str								=		ema_unet.shadow_params

         # Second backprop + EMA
         __A					:					Any								=		self.simulate_backprop(A_	)
         ema_unet.step(unet_step_two.parameters()	)
         __A					:					Union[str, Any]								=		ema_unet.shadow_params

         for step_one, step_two in zip(A_					,       A_	):
              assert ~torch.allclose(A_					,       A_	)
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					int								=		self.get_models(decay=0.0	)
         __A					:					int								=		self.simulate_backprop(A_	)
         ema_unet.step(unet_step_one.parameters()	)
         __A					:					str								=		ema_unet.shadow_params

         __A					:					Optional[int]								=		self.simulate_backprop(A_	)
         ema_unet.step(unet_step_two.parameters()	)
         __A					:					Union[str, Any]								=		ema_unet.shadow_params

         for step_one, step_two in zip(A_					,       A_	):
              assert torch.allclose(A_					,       A_	)

    @skip_mps
    def 						_a							(  self	):




         '''simple docstring'''



         __A					:					str								=		self.get_models()
         __A					:					Optional[int]								=		self.get_dummy_inputs()

         with tempfile.TemporaryDirectory() as tmpdir:
              ema_unet.save_pretrained(A_	)
              __A					:					Union[str, Any]								=		UNetaDConditionModel.from_pretrained(A_					,       model_cls=A_	)
              __A					:					str								=		loaded_unet.to(unet.device	)

         # Since no EMA step has been performed the outputs should match.
         __A					:					Optional[Any]								=		unet(A_					,       A_					,       A_	).sample
         __A					:					Optional[int]								=		loaded_unet(A_					,       A_					,       A_	).sample

         assert torch.allclose(A_					,       A_					,       atol=1e-4	)






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 CLIPImageProcessor





class A__     (			unittest.TestCase			):



 """simple docstring"""







 def __init__(		self			:						Union[str, Any]  ,    A_			:						Optional[Any]  ,    A_			:						List[str]=7  ,    A_			:						Optional[Any]=3  ,    A_			:						int=1_8  ,    A_			:						List[Any]=3_0  ,    A_			:						str=4_0_0  ,    A_			:						Union[str, Any]=True  ,    A_			:						Union[str, Any]=None  ,    A_			:						Union[str, Any]=True  ,    A_			:						Optional[int]=None  ,    A_			:						List[str]=True  ,    A_			:						Union[str, Any]=[0.48145466, 0.4578275, 0.40821073]  ,    A_			:						int=[0.26862954, 0.26130258, 0.27577711]  ,    A_			:						Optional[int]=True  ,    ):






      '''simple docstring'''




      _lowerCAmelCase :       Optional[Any]	   =     size if size is not None else {"shortest_edge": 2_0}
      _lowerCAmelCase :       Union[str, Any]	   =     crop_size if crop_size is not None else {"height": 1_8, "width": 1_8}
      _lowerCAmelCase :       Tuple	   =     parent
      _lowerCAmelCase :       int	   =     batch_size
      _lowerCAmelCase :       str	   =     num_channels
      _lowerCAmelCase :       int	   =     image_size
      _lowerCAmelCase :       Optional[int]	   =     min_resolution
      _lowerCAmelCase :       Any	   =     max_resolution
      _lowerCAmelCase :       str	   =     do_resize
      _lowerCAmelCase :       Union[str, Any]	   =     size
      _lowerCAmelCase :       Optional[int]	   =     do_center_crop
      _lowerCAmelCase :       Union[str, Any]	   =     crop_size
      _lowerCAmelCase :       Optional[int]	   =     do_normalize
      _lowerCAmelCase :       Optional[int]	   =     image_mean
      _lowerCAmelCase :       int	   =     image_std
      _lowerCAmelCase :       Optional[Any]	   =     do_convert_rgb

 def  __magic_name__							(		self			:						Any							):






      '''simple docstring'''




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


 def  __magic_name__							(		self			:						List[Any]  ,    A_			:						List[Any]=False  ,    A_			:						Optional[Any]=False  ,    A_			:						Tuple=False							):






      '''simple docstring'''




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

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

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

      if torchify:
           _lowerCAmelCase :       Tuple	   =     [torch.from_numpy(A_							) for x in image_inputs]

      return image_inputs





@require_torch
@require_vision
class A__     (			A	,		unittest.TestCase			):



 """simple docstring"""







 _lowercase  :       Any  			=    CLIPImageProcessor if is_vision_available() else None

 def  __magic_name__							(		self			:						Union[str, Any]							):






      '''simple docstring'''




      _lowerCAmelCase :       Tuple	   =     CLIPImageProcessingTester(self							)

 @property
 def  __magic_name__							(		self			:						List[Any]							):






      '''simple docstring'''




      return self.image_processor_tester.prepare_image_processor_dict()

 def  __magic_name__							(		self			:						Union[str, Any]							):






      '''simple docstring'''




      _lowerCAmelCase :       Optional[int]	   =     self.image_processing_class(**self.image_processor_dict							)
      self.assertTrue(hasattr(A_  ,    "do_resize"							)							)
      self.assertTrue(hasattr(A_  ,    "size"							)							)
      self.assertTrue(hasattr(A_  ,    "do_center_crop"							)							)
      self.assertTrue(hasattr(A_  ,    "center_crop"							)							)
      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  __magic_name__							(		self			:						Optional[int]							):






      '''simple docstring'''




      _lowerCAmelCase :       Union[str, Any]	   =     self.image_processing_class.from_dict(self.image_processor_dict							)
      self.assertEqual(image_processor.size  ,    {"shortest_edge": 2_0}							)
      self.assertEqual(image_processor.crop_size  ,    {"height": 1_8, "width": 1_8}							)

      _lowerCAmelCase :       List[Any]	   =     self.image_processing_class.from_dict(self.image_processor_dict  ,    size=4_2  ,    crop_size=8_4							)
      self.assertEqual(image_processor.size  ,    {"shortest_edge": 4_2}							)
      self.assertEqual(image_processor.crop_size  ,    {"height": 8_4, "width": 8_4}							)

 def  __magic_name__							(		self			:						Dict							):






      '''simple docstring'''




      pass

 def  __magic_name__							(		self			:						List[Any]							):






      '''simple docstring'''




      _lowerCAmelCase :       Optional[Any]	   =     self.image_processing_class(**self.image_processor_dict							)
      # create random PIL images
      _lowerCAmelCase :       Union[str, Any]	   =     self.image_processor_tester.prepare_inputs(equal_resolution=A_							)
      for image in image_inputs:
           self.assertIsInstance(A_  ,    Image.Image							)

      # Test not batched input
      _lowerCAmelCase :       Optional[Any]	   =     image_processing(image_inputs[0]  ,    return_tensors="pt"							).pixel_values
      self.assertEqual(
          encoded_images.shape  ,    (
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size["height"],
              self.image_processor_tester.crop_size["width"],
          )  ,    )

      # Test batched
      _lowerCAmelCase :       Optional[Any]	   =     image_processing(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.crop_size["height"],
              self.image_processor_tester.crop_size["width"],
          )  ,    )

 def  __magic_name__							(		self			:						List[Any]							):






      '''simple docstring'''




      _lowerCAmelCase :       List[Any]	   =     self.image_processing_class(**self.image_processor_dict							)
      # create random numpy tensors
      _lowerCAmelCase :       Dict	   =     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
      _lowerCAmelCase :       Optional[Any]	   =     image_processing(image_inputs[0]  ,    return_tensors="pt"							).pixel_values
      self.assertEqual(
          encoded_images.shape  ,    (
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size["height"],
              self.image_processor_tester.crop_size["width"],
          )  ,    )

      # Test batched
      _lowerCAmelCase :       Union[str, Any]	   =     image_processing(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.crop_size["height"],
              self.image_processor_tester.crop_size["width"],
          )  ,    )


 def  __magic_name__							(		self			:						Tuple							):






      '''simple docstring'''




      _lowerCAmelCase :       Any	   =     self.image_processing_class(**self.image_processor_dict							)
      # create random PyTorch tensors
      _lowerCAmelCase :       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
      _lowerCAmelCase :       Tuple	   =     image_processing(image_inputs[0]  ,    return_tensors="pt"							).pixel_values
      self.assertEqual(
          encoded_images.shape  ,    (
              1,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size["height"],
              self.image_processor_tester.crop_size["width"],
          )  ,    )

      # Test batched
      _lowerCAmelCase :       List[Any]	   =     image_processing(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.crop_size["height"],
              self.image_processor_tester.crop_size["width"],
          )  ,    )





@require_torch
@require_vision
class A__     (			A	,		unittest.TestCase			):



 """simple docstring"""







 _lowercase  :       List[str]  			=    CLIPImageProcessor if is_vision_available() else None

 def  __magic_name__							(		self			:						Tuple							):






      '''simple docstring'''




      _lowerCAmelCase :       int	   =     CLIPImageProcessingTester(self  ,    num_channels=4							)
      _lowerCAmelCase :       Tuple	   =     3

 @property
 def  __magic_name__							(		self			:						Optional[int]							):






      '''simple docstring'''




      return self.image_processor_tester.prepare_image_processor_dict()

 def  __magic_name__							(		self			:						Optional[int]							):






      '''simple docstring'''




      _lowerCAmelCase :       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_center_crop"							)							)
      self.assertTrue(hasattr(A_  ,    "center_crop"							)							)
      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  __magic_name__							(		self			:						Optional[Any]							):






      '''simple docstring'''




      pass


 def  __magic_name__							(		self			:						Any							):






      '''simple docstring'''




      _lowerCAmelCase :       Tuple	   =     self.image_processing_class(**self.image_processor_dict							)
      # create random PIL images
      _lowerCAmelCase :       Optional[int]	   =     self.image_processor_tester.prepare_inputs(equal_resolution=A_							)
      for image in image_inputs:
           self.assertIsInstance(A_  ,    Image.Image							)

      # Test not batched input
      _lowerCAmelCase :       Optional[Any]	   =     image_processing(image_inputs[0]  ,    return_tensors="pt"							).pixel_values
      self.assertEqual(
          encoded_images.shape  ,    (
              1,
              self.expected_encoded_image_num_channels,
              self.image_processor_tester.crop_size["height"],
              self.image_processor_tester.crop_size["width"],
          )  ,    )

      # Test batched
      _lowerCAmelCase :       int	   =     image_processing(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.crop_size["height"],
              self.image_processor_tester.crop_size["width"],
          )  ,    )






