



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

'''simple docstring'''





import gc
import inspect
import unittest

import torch
from parameterized import parameterized

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

from .test_modeling_common import ModelTesterMixin


enable_full_determinism()






class 							UpperCAmelCase_							(    A					,				unittest.TestCase				):

 '''simple docstring'''
 lowercase_					:    Tuple				=							PriorTransformer
 lowercase_					:    Dict				=							"hidden_states"







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



   '''simple docstring'''




   UpperCAmelCase__      :					List[Any]				       =							4
   UpperCAmelCase__      :					List[Any]				       =							8
   UpperCAmelCase__      :					Union[str, Any]				       =							7

   UpperCAmelCase__      :					Tuple				       =							floats_tensor((batch_size, embedding_dim) ).to(snake_case__ )

   UpperCAmelCase__      :					List[Any]				       =							floats_tensor((batch_size, embedding_dim) ).to(snake_case__ )
   UpperCAmelCase__      :					Union[str, Any]				       =							floats_tensor((batch_size, num_embeddings, embedding_dim) ).to(snake_case__ )

   return {
       "hidden_states": hidden_states,
       "timestep": 2,
       "proj_embedding": proj_embedding,
       "encoder_hidden_states": encoder_hidden_states,
   }







 def 							UpperCamelCase  (					self		:  int			,				snake_case__		:  List[str]=0 ):



   '''simple docstring'''




   torch.manual_seed(snake_case__ )
   UpperCAmelCase__      :					str				       =							4
   UpperCAmelCase__      :					int				       =							8
   UpperCAmelCase__      :					Optional[int]				       =							7

   UpperCAmelCase__      :					Any				       =							torch.randn((batch_size, embedding_dim) ).to(snake_case__ )

   UpperCAmelCase__      :					Union[str, Any]				       =							torch.randn((batch_size, embedding_dim) ).to(snake_case__ )
   UpperCAmelCase__      :					List[str]				       =							torch.randn((batch_size, num_embeddings, embedding_dim) ).to(snake_case__ )

   return {
       "hidden_states": hidden_states,
       "timestep": 2,
       "proj_embedding": proj_embedding,
       "encoder_hidden_states": encoder_hidden_states,
   }







 @property
 def 							UpperCamelCase  (					self		:  Tuple ):



   '''simple docstring'''




   return (4, 8)







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



   '''simple docstring'''




   return (4, 8)







 def 							UpperCamelCase  (					self		:  int ):



   '''simple docstring'''




   UpperCAmelCase__      :					Optional[Any]				       =							{
       "num_attention_heads": 2,
       "attention_head_dim": 4,
       "num_layers": 2,
       "embedding_dim": 8,
       "num_embeddings": 7,
       "additional_embeddings": 4,
   }
   UpperCAmelCase__      :					Optional[Any]				       =							self.dummy_input
   return init_dict, inputs_dict







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



   '''simple docstring'''




   UpperCAmelCase__       ,			UpperCAmelCase__      :					List[str]				       =							PriorTransformer.from_pretrained(
       "hf-internal-testing/prior-dummy"			,				output_loading_info=snake_case__ )
   self.assertIsNotNone(snake_case__ )
   self.assertEqual(len(loading_info["missing_keys"] )			,				0 )

   model.to(snake_case__ )
   UpperCAmelCase__      :					List[Any]				       =							model(**self.dummy_input )[0]

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







 def 							UpperCamelCase  (					self		:  Any ):



   '''simple docstring'''




   UpperCAmelCase__       ,			UpperCAmelCase__      :					int				       =							self.prepare_init_args_and_inputs_for_common()

   UpperCAmelCase__      :					Tuple				       =							self.model_class(**snake_case__ )
   UpperCAmelCase__      :					Optional[int]				       =							inspect.signature(model.forward )
   # signature.parameters is an OrderedDict => so arg_names order is deterministic
   UpperCAmelCase__      :					int				       =							[*signature.parameters.keys()]

   UpperCAmelCase__      :					Optional[Any]				       =							["hidden_states", "timestep"]
   self.assertListEqual(arg_names[:2]			,				snake_case__ )







 def 							UpperCamelCase  (					self		:  Tuple ):



   '''simple docstring'''




   UpperCAmelCase__      :					List[Any]				       =							PriorTransformer.from_pretrained("hf-internal-testing/prior-dummy" )
   UpperCAmelCase__      :					List[Any]				       =							model.to(snake_case__ )

   if hasattr(snake_case__			,				"set_default_attn_processor" ):
     model.set_default_attn_processor()

   UpperCAmelCase__      :					int				       =							self.get_dummy_seed_input()

   with torch.no_grad():
     UpperCAmelCase__      :					Tuple				       =							model(**snake_case__ )[0]

   UpperCAmelCase__      :					Any				       =							output[0, :5].flatten().cpu()
   print(snake_case__ )

   # Since the VAE Gaussian prior's generator is seeded on the appropriate device,
   # the expected output slices are not the same for CPU and GPU.
   UpperCAmelCase__      :					Optional[int]				       =							torch.tensor([-1.3436, -0.2870, 0.7538, 0.4368, -0.0239] )
   self.assertTrue(torch_all_close(snake_case__			,				snake_case__			,				rtol=1e-2 ) )






@slow
class 							UpperCAmelCase_							(    unittest.TestCase				):

 '''simple docstring'''







 def 							UpperCamelCase  (					self		:  Union[str, Any]			,				snake_case__		:  Optional[int]=1			,				snake_case__		:  Any=7_68			,				snake_case__		:  List[Any]=77			,				snake_case__		:  Tuple=0 ):



   '''simple docstring'''




   torch.manual_seed(snake_case__ )
   UpperCAmelCase__      :					Optional[int]				       =							batch_size
   UpperCAmelCase__      :					Any				       =							embedding_dim
   UpperCAmelCase__      :					Any				       =							num_embeddings

   UpperCAmelCase__      :					str				       =							torch.randn((batch_size, embedding_dim) ).to(snake_case__ )

   UpperCAmelCase__      :					Optional[Any]				       =							torch.randn((batch_size, embedding_dim) ).to(snake_case__ )
   UpperCAmelCase__      :					Any				       =							torch.randn((batch_size, num_embeddings, embedding_dim) ).to(snake_case__ )

   return {
       "hidden_states": hidden_states,
       "timestep": 2,
       "proj_embedding": proj_embedding,
       "encoder_hidden_states": encoder_hidden_states,
   }







 def 							UpperCamelCase  (					self		:  str ):



   '''simple docstring'''




   super().tearDown()
   gc.collect()
   torch.cuda.empty_cache()







 @parameterized.expand(
     [
         # fmt: off
         [13, [-0.5861,  0.1283, -0.0931,  0.0882,  0.4476,  0.1329, -0.0498,  0.0640]],
         [37, [-0.4913,  0.0110, -0.0483,  0.0541,  0.4954, -0.0170,  0.0354,  0.1651]],
         # fmt: on
     ] )
 def 							UpperCamelCase  (					self		:  Optional[Any]			,				snake_case__		:  List[str]			,				snake_case__		:  Optional[int] ):



   '''simple docstring'''




   UpperCAmelCase__      :					int				       =							PriorTransformer.from_pretrained("kandinsky-community/kandinsky-2-1-prior"			,				subfolder="prior" )
   model.to(snake_case__ )
   UpperCAmelCase__      :					List[Any]				       =							self.get_dummy_seed_input(seed=snake_case__ )

   with torch.no_grad():
     UpperCAmelCase__      :					Any				       =							model(**snake_case__ )[0]

   assert list(sample.shape ) == [1, 7_68]

   UpperCAmelCase__      :					List[str]				       =							sample[0, :8].flatten().cpu()
   print(snake_case__ )
   UpperCAmelCase__      :					Tuple				       =							torch.tensor(snake_case__ )

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



