


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     A__   (       snake_case__			,   unittest.TestCase      ):







    """simple docstring"""

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

    # No `output_type`.
    __magic_name__         =						frozenset(
        [
            'num_inference_steps',
            'generator',
            'latents',
            'return_dict',
            'callback',
            'callback_steps',
        ]      )
    def 						a_     (			self       ):
         torch.manual_seed(0       )
         snake_case											=							UNetaDConditionModel(
             block_out_channels=(3_2, 6_4, 6_4, 6_4)     ,   layers_per_block=2     ,   sample_size=3_2     ,   in_channels=4     ,   out_channels=4     ,   down_block_types=('''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''CrossAttnDownBlock3D''', '''DownBlock3D''')     ,   up_block_types=('''UpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''', '''CrossAttnUpBlock3D''')     ,   cross_attention_dim=3_2     ,   attention_head_dim=4     ,   )
         snake_case											=							DDIMScheduler(
             beta_start=0.0_0085     ,   beta_end=0.012     ,   beta_schedule='''scaled_linear'''     ,   clip_sample=__snake_case     ,   set_alpha_to_one=__snake_case     ,   )
         torch.manual_seed(0       )
         snake_case											=							AutoencoderKL(
             block_out_channels=[3_2, 6_4]     ,   in_channels=3     ,   out_channels=3     ,   down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']     ,   up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']     ,   latent_channels=4     ,   sample_size=1_2_8     ,   )
         torch.manual_seed(0       )
         snake_case											=							CLIPTextConfig(
             bos_token_id=0     ,   eos_token_id=2     ,   hidden_size=3_2     ,   intermediate_size=3_7     ,   layer_norm_eps=1E-05     ,   num_attention_heads=4     ,   num_hidden_layers=5     ,   pad_token_id=1     ,   vocab_size=1_0_0_0     ,   hidden_act='''gelu'''     ,   projection_dim=5_1_2     ,   )
         snake_case											=							CLIPTextModel(__snake_case       )
         snake_case											=							CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip'''       )

         snake_case											=							{
             '''unet''': unet,
             '''scheduler''': scheduler,
             '''vae''': vae,
             '''text_encoder''': text_encoder,
             '''tokenizer''': tokenizer,
         }
         return components
    def 						a_     (			self     ,   __snake_case     ,   __snake_case=0       ):
         # 3 frames
         snake_case											=							floats_tensor((1, 3, 3, 3_2, 3_2)     ,   rng=random.Random(__snake_case       )       ).to(__snake_case       )

         if str(__snake_case       ).startswith('''mps'''       ):
              snake_case											=							torch.manual_seed(__snake_case       )
         else:
              snake_case											=							torch.Generator(device=__snake_case       ).manual_seed(__snake_case       )
         snake_case											=							{
             '''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       ):
         snake_case											=							'''cpu'''  # ensure determinism for the device-dependent torch.Generator
         snake_case											=							self.get_dummy_components()
         snake_case											=							VideoToVideoSDPipeline(**__snake_case       )
         snake_case											=							sd_pipe.to(__snake_case       )
         sd_pipe.set_progress_bar_config(disable=__snake_case       )

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

         assert frames[0].shape == (3_2, 3_2, 3)
         snake_case											=							np.array([1_0_6, 1_1_7, 1_1_3, 1_7_4, 1_3_7, 1_1_2, 1_4_8, 1_5_1, 1_3_1]       )

         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       ):
         self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__snake_case     ,   expected_max_diff=5E-3       )
    @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.'''       )
    def 						a_     (			self       ):
         pass
    @unittest.skip(reason='''Batching needs to be properly figured out first for this pipeline.'''       )
    def 						a_     (			self       ):
         pass
    @unittest.skip(reason='''`num_images_per_prompt` argument is not supported for this pipeline.'''       )
    def 						a_     (			self       ):
         pass




    def 						a_     (			self       ):
         return super().test_progress_bar()






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







    """simple docstring"""

    def 						a_     (			self       ):
         snake_case											=							VideoToVideoSDPipeline.from_pretrained('''cerspense/zeroscope_v2_XL'''     ,   torch_dtype=torch.floataa       )
         pipe.enable_model_cpu_offload()

         # 10 frames
         snake_case											=							torch.Generator(device='''cpu'''       ).manual_seed(0       )
         snake_case											=							torch.randn((1, 1_0, 3, 1_0_2_4, 5_7_6)     ,   generator=__snake_case       )
         snake_case											=							video.to('''cuda'''       )

         snake_case											=							'''Spiderman is surfing'''

         snake_case											=							pipe(__snake_case     ,   video=__snake_case     ,   generator=__snake_case     ,   num_inference_steps=3     ,   output_type='''pt'''       ).frames

         snake_case											=							np.array([-1.045_8984, -1.127_9297, -0.966_3086, -0.9150_3906, -0.7509_7656]       )
         assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array       ).sum() < 1E-2








import inspect
import unittest

import numpy as np

from transformers import ViTConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
 import jax

 from transformers.models.vit.modeling_flax_vit import FlaxViTForImageClassification, FlaxViTModel

class     A__   (       unittest.TestCase      ):







    """simple docstring"""

    def __init__(			self     ,   __snake_case     ,   __snake_case=1_3     ,   __snake_case=3_0     ,   __snake_case=2     ,   __snake_case=3     ,   __snake_case=True     ,   __snake_case=True     ,   __snake_case=3_2     ,   __snake_case=5     ,   __snake_case=4     ,   __snake_case=3_7     ,   __snake_case="gelu"     ,   __snake_case=0.1     ,   __snake_case=0.1     ,   __snake_case=1_0     ,   __snake_case=0.02     ,   ):
         snake_case											=							parent
         snake_case											=							batch_size
         snake_case											=							image_size
         snake_case											=							patch_size
         snake_case											=							num_channels
         snake_case											=							is_training
         snake_case											=							use_labels
         snake_case											=							hidden_size
         snake_case											=							num_hidden_layers
         snake_case											=							num_attention_heads
         snake_case											=							intermediate_size
         snake_case											=							hidden_act
         snake_case											=							hidden_dropout_prob
         snake_case											=							attention_probs_dropout_prob
         snake_case											=							type_sequence_label_size
         snake_case											=							initializer_range

         # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
         snake_case											=							(image_size // patch_size) ** 2
         snake_case											=							num_patches + 1
    def 						a_     (			self       ):
         snake_case											=							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

         snake_case											=							ViTConfig(
             image_size=self.image_size     ,   patch_size=self.patch_size     ,   num_channels=self.num_channels     ,   hidden_size=self.hidden_size     ,   num_hidden_layers=self.num_hidden_layers     ,   num_attention_heads=self.num_attention_heads     ,   intermediate_size=self.intermediate_size     ,   hidden_act=self.hidden_act     ,   hidden_dropout_prob=self.hidden_dropout_prob     ,   attention_probs_dropout_prob=self.attention_probs_dropout_prob     ,   is_decoder=__snake_case     ,   initializer_range=self.initializer_range     ,   )

         return config, pixel_values
    def 						a_     (			self     ,   __snake_case     ,   __snake_case       ):
         snake_case											=							FlaxViTModel(config=__snake_case       )
         snake_case											=							model(__snake_case       )
         # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
         snake_case											=							(self.image_size, self.image_size)
         snake_case											=							(self.patch_size, self.patch_size)
         snake_case											=							(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
         self.parent.assertEqual(result.last_hidden_state.shape     ,   (self.batch_size, num_patches + 1, self.hidden_size)       )
    def 						a_     (			self     ,   __snake_case     ,   __snake_case       ):
         snake_case											=							self.type_sequence_label_size
         snake_case											=							FlaxViTForImageClassification(config=__snake_case       )
         snake_case											=							model(__snake_case       )
         self.parent.assertEqual(result.logits.shape     ,   (self.batch_size, self.type_sequence_label_size)       )

         # test greyscale images
         snake_case											=							1
         snake_case											=							FlaxViTForImageClassification(__snake_case       )

         snake_case											=							floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
         snake_case											=							model(__snake_case       )




    def 						a_     (			self       ):
         snake_case											=							self.prepare_config_and_inputs()
         (
             (
             snake_case
         )					,    (
             snake_case
         )					,    
         )											=							config_and_inputs
         snake_case											=							{'''pixel_values''': pixel_values}
         return config, inputs_dict






@require_flax
class     A__   (       snake_case__			,   unittest.TestCase      ):







    """simple docstring"""

    __magic_name__         =						(FlaxViTModel, FlaxViTForImageClassification) if is_flax_available() else ()
    def 						a_     (			self       ):
         snake_case											=							FlaxViTModelTester(self       )
         snake_case											=							ConfigTester(self     ,   config_class=__snake_case     ,   has_text_modality=__snake_case     ,   hidden_size=3_7       )
    def 						a_     (			self       ):
         self.config_tester.run_common_tests()
    def 						a_     (			self       ):
         snake_case											=							self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__snake_case       )
    def 						a_     (			self       ):
         snake_case											=							self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*__snake_case       )
    def 						a_     (			self       ):
         snake_case					,    snake_case											=							self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              snake_case											=							model_class(__snake_case       )
              snake_case											=							inspect.signature(model.__call__       )
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              snake_case											=							[*signature.parameters.keys()]

              snake_case											=							['''pixel_values''']
              self.assertListEqual(arg_names[:1]     ,   __snake_case       )
    def 						a_     (			self       ):
         snake_case					,    snake_case											=							self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
              with self.subTest(model_class.__name__       ):
                   snake_case											=							self._prepare_for_class(__snake_case     ,   __snake_case       )
                   snake_case											=							model_class(__snake_case       )

                   @jax.jit
                   def model_jitted(__snake_case     ,   **__snake_case       ):
                        return model(pixel_values=__snake_case     ,   **__snake_case       )

                   with self.subTest('''JIT Enabled'''       ):
                        snake_case											=							model_jitted(**__snake_case       ).to_tuple()

                   with self.subTest('''JIT Disabled'''       ):
                        with jax.disable_jit():
                             snake_case											=							model_jitted(**__snake_case       ).to_tuple()

                   self.assertEqual(len(__snake_case       )     ,   len(__snake_case       )       )
                   for jitted_output, output in zip(__snake_case     ,   __snake_case       ):
                        self.assertEqual(jitted_output.shape     ,   output.shape       )




    @slow
    def 						a_     (			self       ):
         for model_class_name in self.all_model_classes:
              snake_case											=							model_class_name.from_pretrained('''google/vit-base-patch16-224'''       )
              snake_case											=							model(np.ones((1, 3, 2_2_4, 2_2_4)       )       )
              self.assertIsNotNone(__snake_case       )




