






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 TvltImageProcessor





def 						A_					(						lowercase_	,  lowercase_=1_0	,  lowercase_=1_0	,  lowercase_=False	,  lowercase_=False			)				->List[str]:







 """simple docstring"""

 SCREAMING_SNAKE_CASE				    =		[]
 for i in range(image_processor_tester.num_frames			):
  video.append(np.random.randint(2_5_5	,  size=(image_processor_tester.num_channels, width, height)	,  dtype=np.uinta			)			)

 if not numpify and not torchify:
  # PIL expects the channel dimension as last dimension
  SCREAMING_SNAKE_CASE				    =		[Image.fromarray(np.moveaxis(lowercase_	,  0	,  -1			)			) for frame in video]

 if torchify:
  SCREAMING_SNAKE_CASE				    =		[torch.from_numpy(lowercase_			) for frame in video]

 return video





def 						A_					(						lowercase_	,  lowercase_=False	,  lowercase_=False	,  lowercase_=False			)				->Any:







 """simple docstring"""

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

 SCREAMING_SNAKE_CASE				    =		[]
 for i in range(image_processor_tester.batch_size			):
  if equal_resolution:
   SCREAMING_SNAKE_CASE				    =		SCREAMING_SNAKE_CASE				    =		image_processor_tester.max_resolution
  else:
   SCREAMING_SNAKE_CASE    ,   SCREAMING_SNAKE_CASE				    =		np.random.choice(
       np.arange(image_processor_tester.min_resolution	,  image_processor_tester.max_resolution			)	,  2			)
   SCREAMING_SNAKE_CASE				    =		prepare_video(
       image_processor_tester=lowercase_	,  width=lowercase_	,  height=lowercase_	,  numpify=lowercase_	,  torchify=lowercase_	,  )
  video_inputs.append(lowercase_			)

 return video_inputs
class 	a_(		unittest.TestCase	):



     """simple docstring"""



     def __init__(		self					:	Any  ,  lowerCAmelCase__					:	int  ,  lowerCAmelCase__					:	int=7  ,  lowerCAmelCase__					:	Dict=3  ,  lowerCAmelCase__					:	Optional[int]=4  ,  lowerCAmelCase__					:	Any=1_8  ,  lowerCAmelCase__					:	Dict=3_0  ,  lowerCAmelCase__					:	Union[str, Any]=4_0_0  ,  lowerCAmelCase__					:	List[Any]=True  ,  lowerCAmelCase__					:	int=None  ,  lowerCAmelCase__					:	Optional[Any]=True  ,  lowerCAmelCase__					:	int=[0.5, 0.5, 0.5]  ,  lowerCAmelCase__					:	Tuple=[0.5, 0.5, 0.5]  ,  lowerCAmelCase__					:	Dict=True  ,  lowerCAmelCase__					:	Union[str, Any]=None  ,  )							->	Any:

      """simple docstring"""
      SCREAMING_SNAKE_CASE				    =		size if size is not None else {'shortest_edge': 1_8}
      SCREAMING_SNAKE_CASE				    =		crop_size if crop_size is not None else {'height': 1_8, 'width': 1_8}

      SCREAMING_SNAKE_CASE				    =		parent
      SCREAMING_SNAKE_CASE				    =		batch_size
      SCREAMING_SNAKE_CASE				    =		num_channels
      SCREAMING_SNAKE_CASE				    =		num_frames
      SCREAMING_SNAKE_CASE				    =		image_size
      SCREAMING_SNAKE_CASE				    =		min_resolution
      SCREAMING_SNAKE_CASE				    =		max_resolution
      SCREAMING_SNAKE_CASE				    =		do_resize
      SCREAMING_SNAKE_CASE				    =		size
      SCREAMING_SNAKE_CASE				    =		do_normalize
      SCREAMING_SNAKE_CASE				    =		image_mean
      SCREAMING_SNAKE_CASE				    =		image_std
      SCREAMING_SNAKE_CASE				    =		do_center_crop
      SCREAMING_SNAKE_CASE				    =		crop_size





     def     __UpperCamelCase						(		self					:	Optional[Any])							->	Optional[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,
          "do_center_crop": self.do_center_crop,
          "crop_size": self.crop_size,
      }

@require_torch
@require_vision
class 	a_(		lowercase__			,							unittest.TestCase	):



     """simple docstring"""



     __snake_case		:				int  					=TvltImageProcessor if is_vision_available() else None





     def     __UpperCamelCase						(		self					:	str)							->	Dict:

      """simple docstring"""
      SCREAMING_SNAKE_CASE				    =		TvltImageProcessorTester(self)





     @property
     def     __UpperCamelCase						(		self					:	List[str])							->	Tuple:

      """simple docstring"""
      return self.image_processor_tester.prepare_image_processor_dict()





     def     __UpperCamelCase						(		self					:	List[Any])							->	Optional[Any]:

      """simple docstring"""
      SCREAMING_SNAKE_CASE				    =		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__  ,  'do_center_crop'))
      self.assertTrue(hasattr(lowerCAmelCase__  ,  'size'))





     def     __UpperCamelCase						(		self					:	Tuple)							->	int:

      """simple docstring"""
      # Initialize image_processor
      SCREAMING_SNAKE_CASE				    =		self.image_processing_class(**self.image_processor_dict)
      # create random PIL videos
      SCREAMING_SNAKE_CASE				    =		prepare_video_inputs(self.image_processor_tester  ,  equal_resolution=lowerCAmelCase__)
      for video in video_inputs:
       self.assertIsInstance(lowerCAmelCase__  ,  lowerCAmelCase__)
       self.assertIsInstance(video[0]  ,  Image.Image)

      # Test not batched input
      SCREAMING_SNAKE_CASE				    =		image_processor(video_inputs[0]  ,  return_tensors='pt').pixel_values
      self.assertEqual(
          encoded_videos.shape  ,  (
              1,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['height'],
              self.image_processor_tester.crop_size['width'],
          )  ,  )

      # Test batched
      SCREAMING_SNAKE_CASE				    =		image_processor(lowerCAmelCase__  ,  return_tensors='pt').pixel_values
      self.assertEqual(
          encoded_videos.shape  ,  (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['height'],
              self.image_processor_tester.crop_size['width'],
          )  ,  )





     def     __UpperCamelCase						(		self					:	str)							->	Any:

      """simple docstring"""
      # Initialize image_processor
      SCREAMING_SNAKE_CASE				    =		self.image_processing_class(**self.image_processor_dict)
      # create random numpy tensors
      SCREAMING_SNAKE_CASE				    =		prepare_video_inputs(self.image_processor_tester  ,  equal_resolution=lowerCAmelCase__  ,  numpify=lowerCAmelCase__)
      for video in video_inputs:
       self.assertIsInstance(lowerCAmelCase__  ,  lowerCAmelCase__)
       self.assertIsInstance(video[0]  ,  np.ndarray)

      # Test not batched input
      SCREAMING_SNAKE_CASE				    =		image_processor(video_inputs[0]  ,  return_tensors='pt').pixel_values
      self.assertEqual(
          encoded_videos.shape  ,  (
              1,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['height'],
              self.image_processor_tester.crop_size['width'],
          )  ,  )

      # Test batched
      SCREAMING_SNAKE_CASE				    =		image_processor(lowerCAmelCase__  ,  return_tensors='pt').pixel_values
      self.assertEqual(
          encoded_videos.shape  ,  (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['height'],
              self.image_processor_tester.crop_size['width'],
          )  ,  )





     def     __UpperCamelCase						(		self					:	Tuple)							->	Optional[Any]:

      """simple docstring"""
      # Initialize image_processor
      SCREAMING_SNAKE_CASE				    =		self.image_processing_class(**self.image_processor_dict)
      # create random PyTorch tensors
      SCREAMING_SNAKE_CASE				    =		prepare_video_inputs(self.image_processor_tester  ,  equal_resolution=lowerCAmelCase__  ,  torchify=lowerCAmelCase__)
      for video in video_inputs:
       self.assertIsInstance(lowerCAmelCase__  ,  lowerCAmelCase__)
       self.assertIsInstance(video[0]  ,  torch.Tensor)

      # Test not batched input
      SCREAMING_SNAKE_CASE				    =		image_processor(video_inputs[0]  ,  return_tensors='pt').pixel_values
      self.assertEqual(
          encoded_videos.shape  ,  (
              1,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['height'],
              self.image_processor_tester.crop_size['width'],
          )  ,  )

      # Test batched
      SCREAMING_SNAKE_CASE				    =		image_processor(lowerCAmelCase__  ,  return_tensors='pt').pixel_values
      self.assertEqual(
          encoded_videos.shape  ,  (
              self.image_processor_tester.batch_size,
              self.image_processor_tester.num_frames,
              self.image_processor_tester.num_channels,
              self.image_processor_tester.crop_size['height'],
              self.image_processor_tester.crop_size['width'],
          )  ,  )












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



     """simple docstring"""



     __snake_case		:				str  					='''hf-internal-testing/tiny-stable-diffusion-pipe'''
     __snake_case		:				Union[str, Any]  					=1
     __snake_case		:				str  					=77
     __snake_case		:				int  					=32
     __snake_case		:				List[str]  					=4
     __snake_case		:				Any  					=64
     __snake_case		:				Optional[int]  					=torch.manual_seed(0	)





     def     __UpperCamelCase						(		self					:	Union[str, Any]  ,  lowerCAmelCase__					:	str=0.99_99)							->	List[Any]:

      """simple docstring"""
      SCREAMING_SNAKE_CASE				    =		UNetaDConditionModel.from_pretrained(self.model_id  ,  subfolder='unet')
      SCREAMING_SNAKE_CASE				    =		unet.to(lowerCAmelCase__)
      SCREAMING_SNAKE_CASE				    =		EMAModel(unet.parameters()  ,  decay=lowerCAmelCase__  ,  model_cls=lowerCAmelCase__  ,  model_config=unet.config)
      return unet, ema_unet





     def     __UpperCamelCase						(		self					:	List[str])							->	Dict:

      """simple docstring"""
      SCREAMING_SNAKE_CASE				    =		torch.randn(
          self.batch_size  ,  self.num_in_channels  ,  self.latent_height  ,  self.latent_width  ,  generator=self.generator).to(lowerCAmelCase__)
      SCREAMING_SNAKE_CASE				    =		torch.randint(0  ,  1_0_0_0  ,  size=(self.batch_size,)  ,  generator=self.generator).to(lowerCAmelCase__)
      SCREAMING_SNAKE_CASE				    =		torch.randn(
          self.batch_size  ,  self.prompt_length  ,  self.text_encoder_hidden_dim  ,  generator=self.generator).to(lowerCAmelCase__)
      return noisy_latents, timesteps, encoder_hidden_states





     def     __UpperCamelCase						(		self					:	int  ,  lowerCAmelCase__					:	Tuple)							->	Dict:

      """simple docstring"""
      SCREAMING_SNAKE_CASE				    =		{}
      for k, param in unet.state_dict().items():
       SCREAMING_SNAKE_CASE				    =		torch.randn_like(lowerCAmelCase__) + (param * torch.randn_like(lowerCAmelCase__))
       updated_state_dict.update({k: updated_param})
      unet.load_state_dict(lowerCAmelCase__)
      return unet





     def     __UpperCamelCase						(		self					:	Optional[int])							->	List[str]:

      """simple docstring"""
      SCREAMING_SNAKE_CASE    ,   SCREAMING_SNAKE_CASE				    =		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     __UpperCamelCase						(		self					:	str)							->	Union[str, Any]:

      """simple docstring"""
      SCREAMING_SNAKE_CASE    ,   SCREAMING_SNAKE_CASE				    =		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())
      SCREAMING_SNAKE_CASE				    =		list(unet.parameters())
      for s_param, param in zip(ema_unet.shadow_params  ,  lowerCAmelCase__):
       assert torch.allclose(lowerCAmelCase__  ,  lowerCAmelCase__)

      # 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  ,  lowerCAmelCase__):
       assert torch.allclose(lowerCAmelCase__  ,  lowerCAmelCase__)





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

      """simple docstring"""
      SCREAMING_SNAKE_CASE    ,   SCREAMING_SNAKE_CASE				    =		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.
      SCREAMING_SNAKE_CASE				    =		self.simulate_backprop(lowerCAmelCase__)

      # 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.
      SCREAMING_SNAKE_CASE				    =		list(unet_pseudo_updated_step_one.parameters())
      for s_param, param in zip(ema_unet.shadow_params  ,  lowerCAmelCase__):
       assert ~torch.allclose(lowerCAmelCase__  ,  lowerCAmelCase__)

      # 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  ,  lowerCAmelCase__):
       assert ~torch.allclose(lowerCAmelCase__  ,  lowerCAmelCase__)





     def     __UpperCamelCase						(		self					:	Optional[Any])							->	Dict:

      """simple docstring"""
      # If we call EMA step after a backpropagation consecutively for two times,
      # the shadow params from those two steps should be different.
      SCREAMING_SNAKE_CASE    ,   SCREAMING_SNAKE_CASE				    =		self.get_models()

      # First backprop + EMA
      SCREAMING_SNAKE_CASE				    =		self.simulate_backprop(lowerCAmelCase__)
      ema_unet.step(unet_step_one.parameters())
      SCREAMING_SNAKE_CASE				    =		ema_unet.shadow_params

      # Second backprop + EMA
      SCREAMING_SNAKE_CASE				    =		self.simulate_backprop(lowerCAmelCase__)
      ema_unet.step(unet_step_two.parameters())
      SCREAMING_SNAKE_CASE				    =		ema_unet.shadow_params

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





     def     __UpperCamelCase						(		self					:	List[str])							->	Optional[Any]:

      """simple docstring"""
      # If there's no decay even if there are backprops, EMA steps
      # won't take any effect i.e., the shadow params would remain the
      # same.
      SCREAMING_SNAKE_CASE    ,   SCREAMING_SNAKE_CASE				    =		self.get_models(decay=0.0)
      SCREAMING_SNAKE_CASE				    =		self.simulate_backprop(lowerCAmelCase__)
      ema_unet.step(unet_step_one.parameters())
      SCREAMING_SNAKE_CASE				    =		ema_unet.shadow_params

      SCREAMING_SNAKE_CASE				    =		self.simulate_backprop(lowerCAmelCase__)
      ema_unet.step(unet_step_two.parameters())
      SCREAMING_SNAKE_CASE				    =		ema_unet.shadow_params

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





     @skip_mps
     def     __UpperCamelCase						(		self					:	Optional[int])							->	Tuple:

      """simple docstring"""
      SCREAMING_SNAKE_CASE    ,   SCREAMING_SNAKE_CASE				    =		self.get_models()
      SCREAMING_SNAKE_CASE    ,   SCREAMING_SNAKE_CASE    ,   SCREAMING_SNAKE_CASE				    =		self.get_dummy_inputs()

      with tempfile.TemporaryDirectory() as tmpdir:
       ema_unet.save_pretrained(lowerCAmelCase__)
       SCREAMING_SNAKE_CASE				    =		UNetaDConditionModel.from_pretrained(lowerCAmelCase__  ,  model_cls=lowerCAmelCase__)
       SCREAMING_SNAKE_CASE				    =		loaded_unet.to(unet.device)

      # Since no EMA step has been performed the outputs should match.
      SCREAMING_SNAKE_CASE				    =		unet(lowerCAmelCase__  ,  lowerCAmelCase__  ,  lowerCAmelCase__).sample
      SCREAMING_SNAKE_CASE				    =		loaded_unet(lowerCAmelCase__  ,  lowerCAmelCase__  ,  lowerCAmelCase__).sample

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




