


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

import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
    DDPMScheduler,
    PriorTransformer,
    StableUnCLIPPipeline,
    UNetaDConditionModel,
)
from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer
from diffusers.utils.testing_utils import enable_full_determinism, load_numpy, require_torch_gpu, slow, torch_device

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import (
    PipelineKarrasSchedulerTesterMixin,
    PipelineLatentTesterMixin,
    PipelineTesterMixin,
    assert_mean_pixel_difference,
)


enable_full_determinism()




class 	lowercase__				(					__snake_case ,__snake_case ,__snake_case ,unittest.TestCase				):
   __UpperCAmelCase							       =					StableUnCLIPPipeline
   __UpperCAmelCase							       =					TEXT_TO_IMAGE_PARAMS
   __UpperCAmelCase							       =					TEXT_TO_IMAGE_BATCH_PARAMS
   __UpperCAmelCase							       =					TEXT_TO_IMAGE_IMAGE_PARAMS
   __UpperCAmelCase							       =					TEXT_TO_IMAGE_IMAGE_PARAMS

   # TODO(will) Expected attn_bias.stride(1) == 0 to be true, but got false
   __UpperCAmelCase							       =					False





   def 		UpperCamelCase_  (							self)  ->  Union[str, Any]:
      _lowerCamelCase	:					List[str]   =		32
      _lowerCamelCase	:					Dict   =		embedder_hidden_size

      # prior components

      torch.manual_seed(0)
      _lowerCamelCase	:					Any   =		CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""")

      torch.manual_seed(0)
      _lowerCamelCase	:					Tuple   =		CLIPTextModelWithProjection(
          CLIPTextConfig(
              bos_token_id=0      ,   eos_token_id=2      ,   hidden_size=__UpperCamelCase      ,   projection_dim=__UpperCamelCase      ,   intermediate_size=37      ,   layer_norm_eps=1e-0_5      ,   num_attention_heads=4      ,   num_hidden_layers=5      ,   pad_token_id=1      ,   vocab_size=1000      ,   ))

      torch.manual_seed(0)
      _lowerCamelCase	:					Union[str, Any]   =		PriorTransformer(
          num_attention_heads=2      ,   attention_head_dim=12      ,   embedding_dim=__UpperCamelCase      ,   num_layers=1      ,   )

      torch.manual_seed(0)
      _lowerCamelCase	:					int   =		DDPMScheduler(
          variance_type="""fixed_small_log"""      ,   prediction_type="""sample"""      ,   num_train_timesteps=1000      ,   clip_sample=__UpperCamelCase      ,   clip_sample_range=5.0      ,   beta_schedule="""squaredcos_cap_v2"""      ,   )

      # regular denoising components

      torch.manual_seed(0)
      _lowerCamelCase	:					Union[str, Any]   =		StableUnCLIPImageNormalizer(embedding_dim=__UpperCamelCase)
      _lowerCamelCase	:					List[Any]   =		DDPMScheduler(beta_schedule="""squaredcos_cap_v2""")

      torch.manual_seed(0)
      _lowerCamelCase	:					Any   =		CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""")

      torch.manual_seed(0)
      _lowerCamelCase	:					int   =		CLIPTextModel(
          CLIPTextConfig(
              bos_token_id=0      ,   eos_token_id=2      ,   hidden_size=__UpperCamelCase      ,   projection_dim=32      ,   intermediate_size=37      ,   layer_norm_eps=1e-0_5      ,   num_attention_heads=4      ,   num_hidden_layers=5      ,   pad_token_id=1      ,   vocab_size=1000      ,   ))

      torch.manual_seed(0)
      _lowerCamelCase	:					List[Any]   =		UNetaDConditionModel(
          sample_size=32      ,   in_channels=4      ,   out_channels=4      ,   down_block_types=("""CrossAttnDownBlock2D""", """DownBlock2D""")      ,   up_block_types=("""UpBlock2D""", """CrossAttnUpBlock2D""")      ,   block_out_channels=(32, 64)      ,   attention_head_dim=(2, 4)      ,   class_embed_type="""projection"""      ,   projection_class_embeddings_input_dim=embedder_projection_dim * 2      ,   cross_attention_dim=__UpperCamelCase      ,   layers_per_block=1      ,   upcast_attention=__UpperCamelCase      ,   use_linear_projection=__UpperCamelCase      ,   )

      torch.manual_seed(0)
      _lowerCamelCase	:					List[Any]   =		DDIMScheduler(
          beta_schedule="""scaled_linear"""      ,   beta_start=0.0_00_85      ,   beta_end=0.0_12      ,   prediction_type="""v_prediction"""      ,   set_alpha_to_one=__UpperCamelCase      ,   steps_offset=1      ,   )

      torch.manual_seed(0)
      _lowerCamelCase	:					int   =		AutoencoderKL()

      _lowerCamelCase	:					Tuple   =		{
          # prior components
          """prior_tokenizer""": prior_tokenizer,
          """prior_text_encoder""": prior_text_encoder,
          """prior""": prior,
          """prior_scheduler""": prior_scheduler,
          # image noising components
          """image_normalizer""": image_normalizer,
          """image_noising_scheduler""": image_noising_scheduler,
          # regular denoising components
          """tokenizer""": tokenizer,
          """text_encoder""": text_encoder,
          """unet""": unet,
          """scheduler""": scheduler,
          """vae""": vae,
      }

      return components





   def 		UpperCamelCase_  (							self      ,   SCREAMING_SNAKE_CASE      ,   SCREAMING_SNAKE_CASE=0)  ->  Optional[Any]:


      if str(__UpperCamelCase).startswith("""mps"""):
         _lowerCamelCase	:					List[str]   =		torch.manual_seed(__UpperCamelCase)
      else:
         _lowerCamelCase	:					Optional[Any]   =		torch.Generator(device=__UpperCamelCase).manual_seed(__UpperCamelCase)
      _lowerCamelCase	:					str   =		{
          """prompt""": """A painting of a squirrel eating a burger""",
          """generator""": generator,
          """num_inference_steps""": 2,
          """prior_num_inference_steps""": 2,
          """output_type""": """numpy""",
      }
      return inputs





   def 		UpperCamelCase_  (							self)  ->  Optional[Any]:
      _lowerCamelCase	:					Optional[int]   =		torch_device == """cpu"""

      self._test_attention_slicing_forward_pass(test_max_difference=__UpperCamelCase)





   def 		UpperCamelCase_  (							self)  ->  List[Any]:
      _lowerCamelCase	:					str   =		torch_device in ["""cpu""", """mps"""]

      self._test_inference_batch_single_identical(test_max_difference=__UpperCamelCase)







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





   def 		UpperCamelCase_  (							self)  ->  List[str]:
      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()





   def 		UpperCamelCase_  (							self)  ->  Tuple:
      _lowerCamelCase	:					Any   =		load_numpy(
          """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_anime_turtle_fp16.npy""")

      _lowerCamelCase	:					Any   =		StableUnCLIPPipeline.from_pretrained("""fusing/stable-unclip-2-1-l"""      ,   torch_dtype=torch.floataa)
      pipe.to(__UpperCamelCase)
      pipe.set_progress_bar_config(disable=__UpperCamelCase)
      # stable unclip will oom when integration tests are run on a V100,
      # so turn on memory savings
      pipe.enable_attention_slicing()
      pipe.enable_sequential_cpu_offload()

      _lowerCamelCase	:					Union[str, Any]   =		torch.Generator(device="""cpu""").manual_seed(0)
      _lowerCamelCase	:					Optional[Any]   =		pipe("""anime turle"""      ,   generator=__UpperCamelCase      ,   output_type="""np""")

      _lowerCamelCase	:					int   =		output.images[0]

      assert image.shape == (768, 768, 3)

      assert_mean_pixel_difference(__UpperCamelCase      ,   __UpperCamelCase)





   def 		UpperCamelCase_  (							self)  ->  Optional[Any]:
      torch.cuda.empty_cache()
      torch.cuda.reset_max_memory_allocated()
      torch.cuda.reset_peak_memory_stats()

      _lowerCamelCase	:					Dict   =		StableUnCLIPPipeline.from_pretrained("""fusing/stable-unclip-2-1-l"""      ,   torch_dtype=torch.floataa)
      _lowerCamelCase	:					Tuple   =		pipe.to(__UpperCamelCase)
      pipe.set_progress_bar_config(disable=__UpperCamelCase)
      pipe.enable_attention_slicing()
      pipe.enable_sequential_cpu_offload()

      _lowerCamelCase	:					Dict   =		pipe(
          """anime turtle"""      ,   prior_num_inference_steps=2      ,   num_inference_steps=2      ,   output_type="""np"""      ,   )

      _lowerCamelCase	:					str   =		torch.cuda.max_memory_allocated()
      # make sure that less than 7 GB is allocated
      assert mem_bytes < 7 * 10**9




import inspect
import unittest

from huggingface_hub import hf_hub_download

from transformers import ASTConfig
from transformers.testing_utils import require_torch, require_torchaudio, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_torchaudio_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
		import torch
		from torch import nn

		from transformers import ASTForAudioClassification, ASTModel
		from transformers.models.audio_spectrogram_transformer.modeling_audio_spectrogram_transformer import (
		    AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST,
		)


if is_torchaudio_available():
		import torchaudio

		from transformers import ASTFeatureExtractor


class SCREAMING_SNAKE_CASE	:






			"""simple docstring"""




			def __init__(     self			,					__UpperCamelCase			,					__UpperCamelCase=13			,					__UpperCamelCase=2			,					__UpperCamelCase=24			,					__UpperCamelCase=16			,					__UpperCamelCase=True			,					__UpperCamelCase=True			,					__UpperCamelCase=32			,					__UpperCamelCase=5			,					__UpperCamelCase=4			,					__UpperCamelCase=37			,					__UpperCamelCase="gelu"			,					__UpperCamelCase=0.1			,					__UpperCamelCase=0.1			,					__UpperCamelCase=10			,					__UpperCamelCase=0.02			,					__UpperCamelCase=None			,					__UpperCamelCase=2			,					__UpperCamelCase=2			,					):

				"""simple docstring"""


				snake_case_   		=			parent
				snake_case_   		=			batch_size
				snake_case_   		=			patch_size
				snake_case_   		=			max_length
				snake_case_   		=			num_mel_bins
				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
				snake_case_   		=			scope
				snake_case_   		=			frequency_stride
				snake_case_   		=			time_stride

				# in AST, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
				snake_case_   		=			(self.num_mel_bins - self.patch_size) // self.frequency_stride + 1
				snake_case_   		=			(self.max_length - self.patch_size) // self.time_stride + 1
				snake_case_   		=			frequency_out_dimension * time_out_dimension
				snake_case_   		=			num_patches + 2


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_   		=			floats_tensor([self.batch_size, self.max_length, self.num_mel_bins]				)

				snake_case_   		=			None
				if self.use_labels:
					snake_case_   		=			ids_tensor([self.batch_size]			,					self.type_sequence_label_size				)

				snake_case_   		=			self.get_config()

				return config, input_values, labels


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				return ASTConfig(
				    patch_size=self.patch_size			,					max_length=self.max_length			,					num_mel_bins=self.num_mel_bins			,					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=__UpperCamelCase			,					initializer_range=self.initializer_range			,					frequency_stride=self.frequency_stride			,					time_stride=self.time_stride			,					)


			def       __lowerCAmelCase			(     self			,					__UpperCamelCase			,					__UpperCamelCase			,					__UpperCamelCase				):

				"""simple docstring"""


				snake_case_   		=			ASTModel(config=__UpperCamelCase				)
				model.to(__UpperCamelCase				)
				model.eval()
				snake_case_   		=			model(__UpperCamelCase				)
				self.parent.assertEqual(result.last_hidden_state.shape			,					(self.batch_size, self.seq_length, self.hidden_size)				)







			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_   		=			self.prepare_config_and_inputs()
				(
				    (
				    snake_case_
				)		,							(
				    snake_case_
				)		,							(
				    snake_case_
				)		,							
				)   		=			config_and_inputs
				snake_case_   		=			{'input_values': input_values}
				return config, inputs_dict







@require_torch
class SCREAMING_SNAKE_CASE	(		__snake_case				,    __snake_case				,    unittest.TestCase				):






			"""simple docstring"""




			__A    	=	(
			    (
			        ASTModel,
			        ASTForAudioClassification,
			    )
			    if is_torch_available()
			    else ()
			)
			__A    	=	(
			    {"""audio-classification""": ASTForAudioClassification, """feature-extraction""": ASTModel}
			    if is_torch_available()
			    else {}
			)
			__A    	=	False
			__A    	=	False
			__A    	=	False
			__A    	=	False


			def       __lowerCAmelCase			(     self			,					__UpperCamelCase			,					__UpperCamelCase			,					__UpperCamelCase			,					__UpperCamelCase			,					__UpperCamelCase				):

				"""simple docstring"""


				if pipeline_test_casse_name == "AudioClassificationPipelineTests":
					return True

				return False


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_   		=			ASTModelTester(self				)
				snake_case_   		=			ConfigTester(self			,					config_class=__UpperCamelCase			,					has_text_modality=__UpperCamelCase			,					hidden_size=37				)


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				self.config_tester.run_common_tests()


			@unittest.skip(reason='AST does not use inputs_embeds'				)
			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				pass


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				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(__UpperCamelCase				)
					self.assertIsInstance(model.get_input_embeddings()			,					(nn.Module)				)
					snake_case_   		=			model.get_output_embeddings()
					self.assertTrue(x is None or isinstance(__UpperCamelCase			,					nn.Linear				)				)


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				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(__UpperCamelCase				)
					snake_case_   		=			inspect.signature(model.forward				)
					# signature.parameters is an OrderedDict => so arg_names order is deterministic
					snake_case_   		=			[*signature.parameters.keys()]

					snake_case_   		=			['input_values']
					self.assertListEqual(arg_names[:1]			,					__UpperCamelCase				)


			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_   		=			self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*__UpperCamelCase				)







			@slow
			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				for model_name in AUDIO_SPECTROGRAM_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
					snake_case_   		=			ASTModel.from_pretrained(__UpperCamelCase				)
					self.assertIsNotNone(__UpperCamelCase				)







def a():





	'''simple docstring'''
	snake_case_   		=			hf_hub_download(
	    repo_id='nielsr/audio-spectogram-transformer-checkpoint'      ,			filename='sample_audio.flac'      ,			repo_type='dataset'						)

	snake_case_		,							snake_case_   		=			torchaudio.load(lowercase__						)

	return audio, sampling_rate






@require_torch
@require_torchaudio
class SCREAMING_SNAKE_CASE	(		unittest.TestCase				):






			"""simple docstring"""




			@cached_property
			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				return (
				    ASTFeatureExtractor.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593'				)
				    if is_torchaudio_available()
				    else None
				)







			@slow
			def       __lowerCAmelCase			(     self				):

				"""simple docstring"""


				snake_case_   		=			self.default_feature_extractor
				snake_case_   		=			ASTForAudioClassification.from_pretrained('MIT/ast-finetuned-audioset-10-10-0.4593'				).to(__UpperCamelCase				)

				snake_case_   		=			self.default_feature_extractor
				snake_case_		,							snake_case_   		=			prepare_audio()
				snake_case_   		=			audio.squeeze().numpy()
				snake_case_   		=			feature_extractor(__UpperCamelCase			,					sampling_rate=__UpperCamelCase			,					return_tensors='pt'				).to(__UpperCamelCase				)

				# forward pass
				with torch.no_grad():
					snake_case_   		=			model(**__UpperCamelCase				)

				# verify the logits
				snake_case_   		=			torch.Size((1, 5_27)				)
				self.assertEqual(outputs.logits.shape			,					__UpperCamelCase				)

				snake_case_   		=			torch.tensor([-0.8760, -7.0042, -8.6602]				).to(__UpperCamelCase				)

				self.assertTrue(torch.allclose(outputs.logits[0, :3]			,					__UpperCamelCase			,					atol=1E-4				)				)
