





"""simple docstring"""





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 							snake_case							(			lowercase__      ,  unittest.TestCase ):

      '''simple docstring'''



      _A         =       VideoToVideoSDPipeline
      _A         =       TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({'video'} ) - {'image', 'width', 'height'}
      _A         =       TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'video'} ) - {'image'}
      _A         =       PipelineTesterMixin.required_optional_params - {'latents'}
      _A         =       False

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

      def       A_					(							self       :      int ):


        '''simple docstring'''




        torch.manual_seed(0 )
        __UpperCAmelCase    :						str       =						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						,				)
        __UpperCAmelCase    :						Optional[Any]       =						DDIMScheduler(
            beta_start=0.0_0_0_8_5						,				beta_end=0.0_1_2						,				beta_schedule='''scaled_linear'''						,				clip_sample=__lowerCamelCase						,				set_alpha_to_one=__lowerCamelCase						,				)
        torch.manual_seed(0 )
        __UpperCAmelCase    :						Union[str, Any]       =						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 )
        __UpperCAmelCase    :						Union[str, Any]       =						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						,				)
        __UpperCAmelCase    :						Optional[int]       =						CLIPTextModel(__lowerCamelCase )
        __UpperCAmelCase    :						int       =						CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' )

        __UpperCAmelCase    :						Optional[Any]       =						{
            "unet": unet,
            "scheduler": scheduler,
            "vae": vae,
            "text_encoder": text_encoder,
            "tokenizer": tokenizer,
        }
        return components

      def       A_					(							self       :      str						,				__lowercase       :      Optional[int]						,				__lowercase       :      Tuple=0 ):


        '''simple docstring'''




        __UpperCAmelCase    :						Optional[Any]       =						floats_tensor((1, 3, 3, 32, 32)						,				rng=random.Random(__lowerCamelCase ) ).to(__lowerCamelCase )

        if str(__lowerCamelCase ).startswith('''mps''' ):
          __UpperCAmelCase    :						str       =						torch.manual_seed(__lowerCamelCase )
        else:
          __UpperCAmelCase    :						Optional[Any]       =						torch.Generator(device=__lowerCamelCase ).manual_seed(__lowerCamelCase )
        __UpperCAmelCase    :						List[str]       =						{
            "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       A_					(							self       :      Any ):


        '''simple docstring'''




        __UpperCAmelCase    :						Any       =						"cpu"  # ensure determinism for the device-dependent torch.Generator
        __UpperCAmelCase    :						Any       =						self.get_dummy_components()
        __UpperCAmelCase    :						List[Any]       =						VideoToVideoSDPipeline(**__lowerCamelCase )
        __UpperCAmelCase    :						Union[str, Any]       =						sd_pipe.to(__lowerCamelCase )
        sd_pipe.set_progress_bar_config(disable=__lowerCamelCase )

        __UpperCAmelCase    :						int       =						self.get_dummy_inputs(__lowerCamelCase )
        __UpperCAmelCase    :						int       =						"np"
        __UpperCAmelCase    :						Tuple       =						sd_pipe(**__lowerCamelCase ).frames
        __UpperCAmelCase    :						Union[str, Any]       =						frames[0][-3:, -3:, -1]

        assert frames[0].shape == (32, 32, 3)
        __UpperCAmelCase    :						int       =						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       A_					(							self       :      Dict ):


        '''simple docstring'''




        self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__lowerCamelCase						,				expected_max_diff=5e-3 )

      @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''' )
      def       A_					(							self       :      Tuple ):


        '''simple docstring'''




        pass

      @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.''' )
      def       A_					(							self       :      Tuple ):


        '''simple docstring'''




        pass

      @unittest.skip(reason='''`num_images_per_prompt` argument is not supported for this pipeline.''' )
      def       A_					(							self       :      Dict ):


        '''simple docstring'''




        pass







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


        '''simple docstring'''




        return super().test_progress_bar()




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

      '''simple docstring'''



      def       A_					(							self       :      Optional[int] ):


        '''simple docstring'''




        __UpperCAmelCase    :						Any       =						VideoToVideoSDPipeline.from_pretrained('''cerspense/zeroscope_v2_XL'''						,				torch_dtype=torch.floataa )
        pipe.enable_model_cpu_offload()

        # 10 frames
        __UpperCAmelCase    :						Optional[int]       =						torch.Generator(device='''cpu''' ).manual_seed(0 )
        __UpperCAmelCase    :						Optional[int]       =						torch.randn((1, 10, 3, 1_024, 576)						,				generator=__lowerCamelCase )
        __UpperCAmelCase    :						Dict       =						video.to('''cuda''' )

        __UpperCAmelCase    :						Union[str, Any]       =						"Spiderman is surfing"

        __UpperCAmelCase    :						Optional[Any]       =						pipe(__lowerCamelCase						,				video=__lowerCamelCase						,				generator=__lowerCamelCase						,				num_inference_steps=3						,				output_type='''pt''' ).frames

        __UpperCAmelCase    :						Dict       =						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 unittest

from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline
from diffusers.utils import is_flax_available, slow
from diffusers.utils.testing_utils import require_flax


if is_flax_available():
  import jax
  import jax.numpy as jnp
  from flax.jax_utils import replicate
  from flax.training.common_utils import shard




@slow
@require_flax
class 							snake_case							(			unittest.TestCase ):

      '''simple docstring'''



      def       A_					(							self       :      str ):


        '''simple docstring'''




        super().tearDown()
        gc.collect()

      def       A_					(							self       :      List[Any] ):


        '''simple docstring'''




        __UpperCAmelCase       ,     __UpperCAmelCase    :						List[Any]       =						FlaxStableDiffusionPipeline.from_pretrained(
            '''stabilityai/stable-diffusion-2'''						,				revision='''bf16'''						,				dtype=jnp.bfloataa						,				)

        __UpperCAmelCase    :						Dict       =						'''A painting of a squirrel eating a burger'''
        __UpperCAmelCase    :						Any       =						jax.device_count()
        __UpperCAmelCase    :						Optional[int]       =						num_samples * [prompt]
        __UpperCAmelCase    :						Tuple       =						sd_pipe.prepare_inputs(__lowercase )

        __UpperCAmelCase    :						List[Any]       =						replicate(__lowercase )
        __UpperCAmelCase    :						Optional[Any]       =						shard(__lowercase )

        __UpperCAmelCase    :						str       =						jax.random.PRNGKey(0 )
        __UpperCAmelCase    :						Dict       =						jax.random.split(__lowercase						,				jax.device_count() )

        __UpperCAmelCase    :						Tuple       =						sd_pipe(__lowercase						,				__lowercase						,				__lowercase						,				num_inference_steps=25						,				jit=__lowercase )[0]
        assert images.shape == (jax.device_count(), 1, 768, 768, 3)

        __UpperCAmelCase    :						Any       =						images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] )
        __UpperCAmelCase    :						Union[str, Any]       =						images[0, 253:256, 253:256, -1]

        __UpperCAmelCase    :						str       =						jnp.asarray(jax.device_get(image_slice.flatten() ) )
        __UpperCAmelCase    :						List[Any]       =						jnp.array([0.4_2_3_8, 0.4_4_1_4, 0.4_3_9_5, 0.4_4_5_3, 0.4_6_2_9, 0.4_5_9_0, 0.4_5_3_1, 0.4_5_5_0_8, 0.4_5_1_2] )
        print(f'''output_slice: {output_slice}''' )
        assert jnp.abs(output_slice - expected_slice ).max() < 1e-2







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


        '''simple docstring'''




        __UpperCAmelCase    :						Optional[int]       =						'''stabilityai/stable-diffusion-2'''
        __UpperCAmelCase       ,     __UpperCAmelCase    :						Any       =						FlaxDPMSolverMultistepScheduler.from_pretrained(__lowercase						,				subfolder='''scheduler''' )
        __UpperCAmelCase       ,     __UpperCAmelCase    :						Optional[int]       =						FlaxStableDiffusionPipeline.from_pretrained(
            __lowercase						,				scheduler=__lowercase						,				revision='''bf16'''						,				dtype=jnp.bfloataa						,				)
        __UpperCAmelCase    :						Dict       =						scheduler_params

        __UpperCAmelCase    :						int       =						'''A painting of a squirrel eating a burger'''
        __UpperCAmelCase    :						List[Any]       =						jax.device_count()
        __UpperCAmelCase    :						Optional[int]       =						num_samples * [prompt]
        __UpperCAmelCase    :						Tuple       =						sd_pipe.prepare_inputs(__lowercase )

        __UpperCAmelCase    :						Optional[int]       =						replicate(__lowercase )
        __UpperCAmelCase    :						List[Any]       =						shard(__lowercase )

        __UpperCAmelCase    :						Union[str, Any]       =						jax.random.PRNGKey(0 )
        __UpperCAmelCase    :						List[Any]       =						jax.random.split(__lowercase						,				jax.device_count() )

        __UpperCAmelCase    :						List[Any]       =						sd_pipe(__lowercase						,				__lowercase						,				__lowercase						,				num_inference_steps=25						,				jit=__lowercase )[0]
        assert images.shape == (jax.device_count(), 1, 768, 768, 3)

        __UpperCAmelCase    :						Tuple       =						images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] )
        __UpperCAmelCase    :						Any       =						images[0, 253:256, 253:256, -1]

        __UpperCAmelCase    :						List[str]       =						jnp.asarray(jax.device_get(image_slice.flatten() ) )
        __UpperCAmelCase    :						Any       =						jnp.array([0.4_3_3_6, 0.4_2_9_6_9, 0.4_4_5_3, 0.4_1_9_9, 0.4_2_9_7, 0.4_5_3_1, 0.4_4_3_4, 0.4_4_3_4, 0.4_2_9_7] )
        print(f'''output_slice: {output_slice}''' )
        assert jnp.abs(output_slice - expected_slice ).max() < 1e-2