



import random
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    UNetaDConditionModel,
    VideoToVideoSDPipeline,
)
from diffusers.utils import floats_tensor, is_xformers_available, skip_mps
from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()



@skip_mps
class        lowerCAmelCase__					(  _lowerCamelCase ,				unittest.TestCase       ):
				A_   :     int								=     VideoToVideoSDPipeline
				A_   :     Optional[Any]								=     TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({'video'}       ) - {'image', 'width', 'height'}
				A_   :     List[str]								=     TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'video'}       ) - {'image'}
				A_   :     Tuple								=     PipelineTesterMixin.required_optional_params - {'latents'}
				A_   :     Dict								=     False

				# No `output_type`.
				A_   :     str								=     frozenset(
				    [
				        'num_inference_steps',
				        'generator',
				        'latents',
				        'return_dict',
				        'callback',
				        'callback_steps',
				    ]       )


				def __UpperCamelCase						(							self      :  Optional[int]       )		->     List[Any]:
											torch.manual_seed(0       )
											A      						=    UNetaDConditionModel(
											    block_out_channels=(32, 64, 64, 64)						, layers_per_block=2						, sample_size=32						, in_channels=4						, out_channels=4						, down_block_types=('CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'CrossAttnDownBlock3D', 'DownBlock3D')						, up_block_types=('UpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D', 'CrossAttnUpBlock3D')						, cross_attention_dim=32						, attention_head_dim=4						, )
											A      						=    DDIMScheduler(
											    beta_start=0.0_0_0_8_5						, beta_end=0.0_1_2						, beta_schedule='scaled_linear'						, clip_sample=__UpperCamelCase						, set_alpha_to_one=__UpperCamelCase						, )
											torch.manual_seed(0       )
											A      						=    AutoencoderKL(
											    block_out_channels=[32, 64]						, in_channels=3						, out_channels=3						, down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']						, up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']						, latent_channels=4						, sample_size=128						, )
											torch.manual_seed(0       )
											A      						=    CLIPTextConfig(
											    bos_token_id=0						, eos_token_id=2						, hidden_size=32						, intermediate_size=37						, layer_norm_eps=1e-05						, num_attention_heads=4						, num_hidden_layers=5						, pad_token_id=1						, vocab_size=1_000						, hidden_act='gelu'						, projection_dim=512						, )
											A      						=    CLIPTextModel(__UpperCamelCase       )
											A      						=    CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip'       )

											A      						=    {
											    'unet': unet,
											    'scheduler': scheduler,
											    'vae': vae,
											    'text_encoder': text_encoder,
											    'tokenizer': tokenizer,
											}
											return components


				def __UpperCamelCase						(							self      :  Optional[Any]						, __UpperCamelCase      :  Any						, __UpperCamelCase      :  str=0       )		->     Optional[int]:
											# 3 frames
											A      						=    floats_tensor((1, 3, 3, 32, 32)						, rng=random.Random(__UpperCamelCase       )       ).to(__UpperCamelCase       )

											if str(__UpperCamelCase       ).startswith('mps'       ):
																		A      						=    torch.manual_seed(__UpperCamelCase       )
											else:
																		A      						=    torch.Generator(device=__UpperCamelCase       ).manual_seed(__UpperCamelCase       )
											A      						=    {
											    'prompt': 'A painting of a squirrel eating a burger',
											    'video': video,
											    'generator': generator,
											    'num_inference_steps': 2,
											    'guidance_scale': 6.0,
											    'output_type': 'pt',
											}
											return inputs


				def __UpperCamelCase						(							self      :  Optional[int]       )		->     str:
											A      						=    'cpu'  # ensure determinism for the device-dependent torch.Generator
											A      						=    self.get_dummy_components()
											A      						=    VideoToVideoSDPipeline(**__UpperCamelCase       )
											A      						=    sd_pipe.to(__UpperCamelCase       )
											sd_pipe.set_progress_bar_config(disable=__UpperCamelCase       )

											A      						=    self.get_dummy_inputs(__UpperCamelCase       )
											A      						=    'np'
											A      						=    sd_pipe(**__UpperCamelCase       ).frames
											A      						=    frames[0][-3:, -3:, -1]

											assert frames[0].shape == (32, 32, 3)
											A      						=    np.array([106, 117, 113, 174, 137, 112, 148, 151, 131]       )

											assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1e-2


				@unittest.skipIf(
				    torch_device != 'cuda' or not is_xformers_available()						, reason='XFormers attention is only available with CUDA and `xformers` installed'						, )
				def __UpperCamelCase						(							self      :  int       )		->     Tuple:
											self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__UpperCamelCase						, expected_max_diff=5e-3       )


				@unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.'       )
				def __UpperCamelCase						(							self      :  Optional[int]       )		->     Any:
											pass


				@unittest.skip(reason='Batching needs to be properly figured out first for this pipeline.'       )
				def __UpperCamelCase						(							self      :  str       )		->     Any:
											pass


				@unittest.skip(reason='`num_images_per_prompt` argument is not supported for this pipeline.'       )
				def __UpperCamelCase						(							self      :  Union[str, Any]       )		->     Optional[Any]:
											pass


				def __UpperCamelCase						(							self      :  Any       )		->     Any:
											return super().test_progress_bar()





@slow
@skip_mps
class        lowerCAmelCase__					(  unittest.TestCase       ):


				def __UpperCamelCase						(							self      :  Optional[Any]       )		->     Dict:
											A      						=    VideoToVideoSDPipeline.from_pretrained('cerspense/zeroscope_v2_XL'						, torch_dtype=torch.floataa       )
											pipe.enable_model_cpu_offload()

											# 10 frames
											A      						=    torch.Generator(device='cpu'       ).manual_seed(0       )
											A      						=    torch.randn((1, 10, 3, 1_024, 576)						, generator=__UpperCamelCase       )
											A      						=    video.to('cuda'       )

											A      						=    'Spiderman is surfing'

											A      						=    pipe(__UpperCamelCase						, video=__UpperCamelCase						, generator=__UpperCamelCase						, num_inference_steps=3						, output_type='pt'       ).frames

											A      						=    np.array([-1.0_4_5_8_9_8_4, -1.1_2_7_9_2_9_7, -0.9_6_6_3_0_8_6, -0.9_1_5_0_3_9_0_6, -0.7_5_0_9_7_6_5_6]       )
											assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array       ).sum() < 1e-2



import re
from typing import Callable, List, Optional, Union

import tensorflow as tf


try:
   from tensorflow.keras.optimizers.legacy import Adam
except ImportError:
   from tensorflow.keras.optimizers import Adam


class      __lowerCAmelCase  (			tf.keras.optimizers.schedules.LearningRateSchedule       ):






  """simple docstring"""





  def __init__(  self							:							Union[str, Any]     ,					_lowerCAmelCase							:							float     ,					_lowerCAmelCase							:							Callable     ,					_lowerCAmelCase							:							int     ,					_lowerCAmelCase							:							float = 1.0     ,					_lowerCAmelCase							:							str = None     ,					) ->			str:




     """simple docstring"""
     super().__init__()
     snake_case_            =       initial_learning_rate
     snake_case_            =       warmup_steps
     snake_case_            =       power
     snake_case_            =       decay_schedule_fn
     snake_case_            =       name



  def __call__(  self							:							Any     ,					_lowerCAmelCase							:							int	) ->			Tuple:




     """simple docstring"""
     with tf.name_scope(self.name or "WarmUp"	) as name:
        # Implements polynomial warmup. i.e., if global_step < warmup_steps, the
        # learning rate will be `global_step/num_warmup_steps * init_lr`.
        snake_case_            =       tf.cast(_lowerCAmelCase     ,					tf.floataa	)
        snake_case_            =       tf.cast(self.warmup_steps     ,					tf.floataa	)
        snake_case_            =       global_step_float / warmup_steps_float
        snake_case_            =       self.initial_learning_rate * tf.math.pow(_lowerCAmelCase     ,					self.power	)
        return tf.cond(
            global_step_float < warmup_steps_float     ,					lambda: warmup_learning_rate     ,					lambda: self.decay_schedule_fn(step - self.warmup_steps	)     ,					name=_lowerCAmelCase     ,					)



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




     """simple docstring"""
     return {
         "initial_learning_rate": self.initial_learning_rate,
         "decay_schedule_fn": self.decay_schedule_fn,
         "warmup_steps": self.warmup_steps,
         "power": self.power,
         "name": self.name,
     }






def       _lowerCAmelCase    (				lowerCAmelCase_				:float		,    lowerCAmelCase_				:int		,    lowerCAmelCase_				:int		,    lowerCAmelCase_				:float = 0.0		,    lowerCAmelCase_				:float = 0.9		,    lowerCAmelCase_				:float = 0.9_9_9		,    lowerCAmelCase_				:float = 1e-8		,    lowerCAmelCase_				:Optional[float] = None		,    lowerCAmelCase_				:Optional[float] = None		,    lowerCAmelCase_				:float = 0.0		,    lowerCAmelCase_				:float = 1.0		,    lowerCAmelCase_				:Optional[List[str]] = None		,    )->Optional[Any]:
   '''simple docstring'''






   snake_case_            =       tf.keras.optimizers.schedules.PolynomialDecay(
       initial_learning_rate=lowerCAmelCase_		,    decay_steps=num_train_steps - num_warmup_steps		,    end_learning_rate=init_lr * min_lr_ratio		,    power=lowerCAmelCase_		,    )
   if num_warmup_steps:
      snake_case_            =       WarmUp(
          initial_learning_rate=lowerCAmelCase_		,    decay_schedule_fn=lowerCAmelCase_		,    warmup_steps=lowerCAmelCase_		,    )
   if weight_decay_rate > 0.0:
      snake_case_            =       AdamWeightDecay(
          learning_rate=lowerCAmelCase_		,    weight_decay_rate=lowerCAmelCase_		,    beta_a=lowerCAmelCase_		,    beta_a=lowerCAmelCase_		,    epsilon=lowerCAmelCase_		,    clipnorm=lowerCAmelCase_		,    global_clipnorm=lowerCAmelCase_		,    exclude_from_weight_decay=["LayerNorm", "layer_norm", "bias"]		,    include_in_weight_decay=lowerCAmelCase_		,    )
   else:
      snake_case_            =       tf.keras.optimizers.Adam(
          learning_rate=lowerCAmelCase_		,    beta_a=lowerCAmelCase_		,    beta_a=lowerCAmelCase_		,    epsilon=lowerCAmelCase_		,    clipnorm=lowerCAmelCase_		,    global_clipnorm=lowerCAmelCase_		,    )
   # We return the optimizer and the LR scheduler in order to better track the
   # evolution of the LR independently of the optimizer.
   return optimizer, lr_schedule


class      __lowerCAmelCase  (			a       ):






  """simple docstring"""





  def __init__(  self							:							Dict     ,					_lowerCAmelCase							:							Union[float, tf.keras.optimizers.schedules.LearningRateSchedule] = 0.001     ,					_lowerCAmelCase							:							float = 0.9     ,					_lowerCAmelCase							:							float = 0.999     ,					_lowerCAmelCase							:							float = 1e-7     ,					_lowerCAmelCase							:							bool = False     ,					_lowerCAmelCase							:							float = 0.0     ,					_lowerCAmelCase							:							Optional[List[str]] = None     ,					_lowerCAmelCase							:							Optional[List[str]] = None     ,					_lowerCAmelCase							:							str = "AdamWeightDecay"     ,					**_lowerCAmelCase							:							Union[str, Any]     ,					) ->			Optional[int]:




     """simple docstring"""
     super().__init__(_lowerCAmelCase     ,					_lowerCAmelCase     ,					_lowerCAmelCase     ,					_lowerCAmelCase     ,					_lowerCAmelCase     ,					_lowerCAmelCase     ,					**_lowerCAmelCase	)
     snake_case_            =       weight_decay_rate
     snake_case_            =       include_in_weight_decay
     snake_case_            =       exclude_from_weight_decay



  @classmethod
  def        lowerCAmelCase__	(  cls							:							Dict     ,					_lowerCAmelCase							:							Optional[Any]	) ->			Tuple:




     """simple docstring"""
     snake_case_            =       {"WarmUp": WarmUp}
     return super(_lowerCAmelCase     ,					cls	).from_config(_lowerCAmelCase     ,					custom_objects=_lowerCAmelCase	)



  def        lowerCAmelCase__	(  self							:							List[Any]     ,					_lowerCAmelCase							:							Union[str, Any]     ,					_lowerCAmelCase							:							int     ,					_lowerCAmelCase							:							Optional[int]	) ->			List[str]:




     """simple docstring"""
     super(_lowerCAmelCase     ,					self	)._prepare_local(_lowerCAmelCase     ,					_lowerCAmelCase     ,					_lowerCAmelCase	)
     snake_case_            =       tf.constant(
         self.weight_decay_rate     ,					name="adam_weight_decay_rate"	)



  def        lowerCAmelCase__	(  self							:							Optional[Any]     ,					_lowerCAmelCase							:							List[Any]     ,					_lowerCAmelCase							:							Optional[Any]     ,					_lowerCAmelCase							:							List[Any]	) ->			int:




     """simple docstring"""
     snake_case_            =       self._do_use_weight_decay(var.name	)
     if do_decay:
        return var.assign_sub(
            learning_rate * var * apply_state[(var.device, var.dtype.base_dtype)]["weight_decay_rate"]     ,					use_locking=self._use_locking     ,					)
     return tf.no_op()



  def        lowerCAmelCase__	(  self							:							List[str]     ,					_lowerCAmelCase							:							str     ,					_lowerCAmelCase							:							Optional[int]=None     ,					**_lowerCAmelCase							:							Dict	) ->			Union[str, Any]:




     """simple docstring"""
     snake_case_     ,     snake_case_            =       list(zip(*_lowerCAmelCase	)	)
     return super(_lowerCAmelCase     ,					self	).apply_gradients(zip(_lowerCAmelCase     ,					_lowerCAmelCase	)     ,					name=_lowerCAmelCase     ,					**_lowerCAmelCase	)



  def        lowerCAmelCase__	(  self							:							List[str]     ,					_lowerCAmelCase							:							Union[str, Any]     ,					_lowerCAmelCase							:							Optional[Any]     ,					_lowerCAmelCase							:							Optional[int]	) ->			int:




     """simple docstring"""
     if apply_state is None:
        return self._decayed_lr_t[var_dtype], {}

     snake_case_            =       apply_state or {}
     snake_case_            =       apply_state.get((var_device, var_dtype)	)
     if coefficients is None:
        snake_case_            =       self._fallback_apply_state(_lowerCAmelCase     ,					_lowerCAmelCase	)
        snake_case_            =       coefficients

     return coefficients["lr_t"], {"apply_state": apply_state}



  def        lowerCAmelCase__	(  self							:							int     ,					_lowerCAmelCase							:							List[Any]     ,					_lowerCAmelCase							:							Optional[int]     ,					_lowerCAmelCase							:							Tuple=None	) ->			List[str]:




     """simple docstring"""
     snake_case_     ,     snake_case_            =       self._get_lr(var.device     ,					var.dtype.base_dtype     ,					_lowerCAmelCase	)
     snake_case_            =       self._decay_weights_op(_lowerCAmelCase     ,					_lowerCAmelCase     ,					_lowerCAmelCase	)
     with tf.control_dependencies([decay]	):
        return super(_lowerCAmelCase     ,					self	)._resource_apply_dense(_lowerCAmelCase     ,					_lowerCAmelCase     ,					**_lowerCAmelCase	)



  def        lowerCAmelCase__	(  self							:							List[Any]     ,					_lowerCAmelCase							:							Any     ,					_lowerCAmelCase							:							str     ,					_lowerCAmelCase							:							Any     ,					_lowerCAmelCase							:							Tuple=None	) ->			List[str]:




     """simple docstring"""
     snake_case_     ,     snake_case_            =       self._get_lr(var.device     ,					var.dtype.base_dtype     ,					_lowerCAmelCase	)
     snake_case_            =       self._decay_weights_op(_lowerCAmelCase     ,					_lowerCAmelCase     ,					_lowerCAmelCase	)
     with tf.control_dependencies([decay]	):
        return super(_lowerCAmelCase     ,					self	)._resource_apply_sparse(_lowerCAmelCase     ,					_lowerCAmelCase     ,					_lowerCAmelCase     ,					**_lowerCAmelCase	)



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




     """simple docstring"""
     snake_case_            =       super().get_config()
     config.update({"weight_decay_rate": self.weight_decay_rate}	)
     return config



  def        lowerCAmelCase__	(  self							:							Union[str, Any]     ,					_lowerCAmelCase							:							List[str]	) ->			Tuple:




     """simple docstring"""
     if self.weight_decay_rate == 0:
        return False

     if self._include_in_weight_decay:
        for r in self._include_in_weight_decay:
           if re.search(_lowerCAmelCase     ,					_lowerCAmelCase	) is not None:
              return True

     if self._exclude_from_weight_decay:
        for r in self._exclude_from_weight_decay:
           if re.search(_lowerCAmelCase     ,					_lowerCAmelCase	) is not None:
              return False
     return True






class      __lowerCAmelCase  (			a       ):






  """simple docstring"""





  def __init__(  self							:							str	) ->			Dict:




     """simple docstring"""
     snake_case_            =       []
     snake_case_            =       None



  @property
  def        lowerCAmelCase__	(  self							:							Dict	) ->			List[Any]:




     """simple docstring"""
     if self._accum_steps is None:
        snake_case_            =       tf.Variable(
            tf.constant(0     ,					dtype=tf.intaa	)     ,					trainable=_lowerCAmelCase     ,					synchronization=tf.VariableSynchronization.ON_READ     ,					aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA     ,					)

     return self._accum_steps.value()



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




     """simple docstring"""
     if not self._gradients:
        raise ValueError("The accumulator should be called first to initialize the gradients"	)
     return [gradient.value() if gradient is not None else gradient for gradient in self._gradients]



  def __call__(  self							:							List[Any]     ,					_lowerCAmelCase							:							Union[str, Any]	) ->			Optional[Any]:




     """simple docstring"""
     if not self._gradients:
        snake_case_            =       self.step  # Create the step variable.
        self._gradients.extend(
            [
                tf.Variable(
                    tf.zeros_like(_lowerCAmelCase	)     ,					trainable=_lowerCAmelCase     ,					synchronization=tf.VariableSynchronization.ON_READ     ,					aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA     ,					)
                if gradient is not None
                else gradient
                for gradient in gradients
            ]	)
     if len(_lowerCAmelCase	) != len(self._gradients	):
        raise ValueError(F'''Expected {len(self._gradients	)} gradients, but got {len(_lowerCAmelCase	)}'''	)

     for accum_gradient, gradient in zip(self._gradients     ,					_lowerCAmelCase	):
        if accum_gradient is not None and gradient is not None:
           accum_gradient.assign_add(_lowerCAmelCase	)

     self._accum_steps.assign_add(1	)



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




     """simple docstring"""
     if not self._gradients:
        return
     self._accum_steps.assign(0	)
     for gradient in self._gradients:
        if gradient is not None:
           gradient.assign(tf.zeros_like(_lowerCAmelCase	)	)




