"""simple docstring"""
import gc
import random
import unittest

import numpy as np
import torch

from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.utils import floats_tensor, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference


enable_full_determinism()




class    __snake_case       (     __lowerCAmelCase       ,      unittest.TestCase				):
      a__        =		KandinskyVaaPipeline
      a__        =		[
          """image_embeds""",
          """negative_image_embeds""",
      ]
      a__        =		["""image_embeds""", """negative_image_embeds"""]
      a__        =		[
          """generator""",
          """height""",
          """width""",
          """latents""",
          """guidance_scale""",
          """num_inference_steps""",
          """return_dict""",
          """guidance_scale""",
          """num_images_per_prompt""",
          """output_type""",
          """return_dict""",
      ]
      a__        =		False



      @property
      def   lowerCamelCase_   (						self)	->			Any:





        '''simple docstring'''





        return 32



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





        '''simple docstring'''





        return 32



      @property
      def   lowerCamelCase_   (						self)	->			Dict:





        '''simple docstring'''





        return self.time_input_dim



      @property
      def   lowerCamelCase_   (						self)	->			Optional[Any]:





        '''simple docstring'''





        return self.time_input_dim * 4



      @property
      def   lowerCamelCase_   (						self)	->			Optional[Any]:





        '''simple docstring'''





        return 1_00



      @property
      def   lowerCamelCase_   (						self)	->			Optional[Any]:





        '''simple docstring'''





        torch.manual_seed(0)

        a__:     str										=	{
            'in_channels': 4,
            # Out channels is double in channels because predicts mean and variance
            'out_channels': 8,
            'addition_embed_type': 'image',
            'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'),
            'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'),
            'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn',
            'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2),
            'layers_per_block': 1,
            'encoder_hid_dim': self.text_embedder_hidden_size,
            'encoder_hid_dim_type': 'image_proj',
            'cross_attention_dim': self.cross_attention_dim,
            'attention_head_dim': 4,
            'resnet_time_scale_shift': 'scale_shift',
            'class_embed_type': None,
        }

        a__:     Any										=	UNetaDConditionModel(**lowercase)
        return model



      @property
      def   lowerCamelCase_   (						self)	->			Any:





        '''simple docstring'''





        return {
            "block_out_channels": [32, 64],
            "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
            "in_channels": 3,
            "latent_channels": 4,
            "layers_per_block": 1,
            "norm_num_groups": 8,
            "norm_type": "spatial",
            "num_vq_embeddings": 12,
            "out_channels": 3,
            "up_block_types": [
                "AttnUpDecoderBlock2D",
                "UpDecoderBlock2D",
            ],
            "vq_embed_dim": 4,
        }



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





        '''simple docstring'''





        torch.manual_seed(0)
        a__:     Any										=	VQModel(**self.dummy_movq_kwargs)
        return model



      def   lowerCamelCase_   (						self)	->			List[str]:





        '''simple docstring'''





        a__:     Any										=	self.dummy_unet
        a__:     Any										=	self.dummy_movq

        a__:     Dict										=	DDIMScheduler(
            num_train_timesteps=10_00    ,			beta_schedule='linear'    ,			beta_start=0.00085    ,			beta_end=0.012    ,			clip_sample=lowercase    ,			set_alpha_to_one=lowercase    ,			steps_offset=1    ,			prediction_type='epsilon'    ,			thresholding=lowercase    ,			)

        a__:     List[str]										=	{
            'unet': unet,
            'scheduler': scheduler,
            'movq': movq,
        }
        return components



      def   lowerCamelCase_   (						self    ,			lowercase    ,			lowercase=0)	->			int:





        '''simple docstring'''





        a__:     Dict										=	floats_tensor((1, self.text_embedder_hidden_size)    ,			rng=random.Random(lowercase)).to(lowercase)
        a__:     Dict										=	floats_tensor((1, self.text_embedder_hidden_size)    ,			rng=random.Random(seed + 1)).to(
            lowercase)
        if str(lowercase).startswith('mps'):
          a__:     Tuple										=	torch.manual_seed(lowercase)
        else:
          a__:     Union[str, Any]										=	torch.Generator(device=lowercase).manual_seed(lowercase)
        a__:     Optional[Any]										=	{
            'image_embeds': image_embeds,
            'negative_image_embeds': negative_image_embeds,
            'generator': generator,
            'height': 64,
            'width': 64,
            'guidance_scale': 4.0,
            'num_inference_steps': 2,
            'output_type': 'np',
        }
        return inputs



      def   lowerCamelCase_   (						self)	->			Optional[Any]:





        '''simple docstring'''





        a__:     Any										=	'cpu'

        a__:     Dict										=	self.get_dummy_components()

        a__:     Any										=	self.pipeline_class(**lowercase)
        a__:     str										=	pipe.to(lowercase)

        pipe.set_progress_bar_config(disable=lowercase)

        a__:     Any										=	pipe(**self.get_dummy_inputs(lowercase))
        a__:     Optional[Any]										=	output.images

        a__:     Dict										=	pipe(
            **self.get_dummy_inputs(lowercase)    ,			return_dict=lowercase    ,			)[0]

        a__:     int										=	image[0, -3:, -3:, -1]
        a__:     List[Any]										=	image_from_tuple[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)

        a__:     Dict										=	np.array(
            [0.6237976, 1.0, 0.36441332, 1.0, 0.70639634, 0.29877186, 0.85652125, 0.5216843, 0.54454046])

        assert (
            np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
        ), f' expected_slice {expected_slice}, but got {image_slice.flatten()}'

        assert (
            np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2
        ), f' expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}'







@slow
@require_torch_gpu
class    __snake_case       (     unittest.TestCase				):



      def   lowerCamelCase_   (						self)	->			List[str]:





        '''simple docstring'''





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



      def   lowerCamelCase_   (						self)	->			str:





        '''simple docstring'''





        a__:     Optional[Any]										=	load_numpy(
            'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
            '/kandinskyv22/kandinskyv22_text2img_cat_fp16.npy')

        a__:     List[str]										=	KandinskyVaaPriorPipeline.from_pretrained(
            'kandinsky-community/kandinsky-2-2-prior'    ,			torch_dtype=torch.floataa)
        pipe_prior.to(lowercase)

        a__:     Tuple										=	KandinskyVaaPipeline.from_pretrained(
            'kandinsky-community/kandinsky-2-2-decoder'    ,			torch_dtype=torch.floataa)
        a__:     Dict										=	pipeline.to(lowercase)
        pipeline.set_progress_bar_config(disable=lowercase)

        a__:     List[Any]										=	'red cat, 4k photo'

        a__:     Dict										=	torch.Generator(device='cuda').manual_seed(0)
        a__							,    a__:     Optional[Any]										=	pipe_prior(
            lowercase    ,			generator=lowercase    ,			num_inference_steps=5    ,			negative_prompt=''    ,			).to_tuple()

        a__:     Any										=	torch.Generator(device='cuda').manual_seed(0)
        a__:     str										=	pipeline(
            image_embeds=lowercase    ,			negative_image_embeds=lowercase    ,			generator=lowercase    ,			num_inference_steps=1_00    ,			output_type='np'    ,			)

        a__:     Optional[Any]										=	output.images[0]

        assert image.shape == (5_12, 5_12, 3)

        assert_mean_pixel_difference(lowercase    ,			lowercase)



"""simple docstring"""
from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowercase__					       =	logging.get_logger(__name__)

lowercase__					       =	{
    'MIT/ast-finetuned-audioset-10-10-0.4593': (
        'https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json'
    ),
}




class    __snake_case       (     __lowerCAmelCase				):
      a__        =		"""audio-spectrogram-transformer"""



      def __init__(						self    ,			lowercase=7_68    ,			lowercase=12    ,			lowercase=12    ,			lowercase=30_72    ,			lowercase="gelu"    ,			lowercase=0.0    ,			lowercase=0.0    ,			lowercase=0.02    ,			lowercase=1e-12    ,			lowercase=16    ,			lowercase=True    ,			lowercase=10    ,			lowercase=10    ,			lowercase=10_24    ,			lowercase=1_28    ,			**lowercase    ,			)	->			str:





        '''simple docstring'''





        super().__init__(**lowercase)

        a__:     Any										=	hidden_size
        a__:     int										=	num_hidden_layers
        a__:     Union[str, Any]										=	num_attention_heads
        a__:     Any										=	intermediate_size
        a__:     Union[str, Any]										=	hidden_act
        a__:     int										=	hidden_dropout_prob
        a__:     str										=	attention_probs_dropout_prob
        a__:     str										=	initializer_range
        a__:     Tuple										=	layer_norm_eps
        a__:     Any										=	patch_size
        a__:     int										=	qkv_bias
        a__:     Optional[Any]										=	frequency_stride
        a__:     int										=	time_stride
        a__:     List[str]										=	max_length
        a__:     Tuple										=	num_mel_bins


