
# DISCLAIMER: This file is strongly influenced by https://github.com/yang-song/score_sde_pytorch

import math
from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, randn_tensor
from .scheduling_utils import SchedulerMixin, SchedulerOutput






@dataclass
class        SCREAMING_SNAKE_CASE__    (							SCREAMING_SNAKE_CASE_    ):

							"""simple docstring"""






							_snake_case     		=  42
							_snake_case     		=  42






class        SCREAMING_SNAKE_CASE__    (							SCREAMING_SNAKE_CASE_   ,		SCREAMING_SNAKE_CASE_    ):

							"""simple docstring"""






							_snake_case     		=  1



							@register_to_config
							def __init__(  self     ,	SCREAMING_SNAKE_CASE_ = 2000     ,	SCREAMING_SNAKE_CASE_ = 0.1_5     ,	SCREAMING_SNAKE_CASE_ = 0.0_1     ,	SCREAMING_SNAKE_CASE_ = 1_3_4_8.0     ,	SCREAMING_SNAKE_CASE_ = 1E-5     ,	SCREAMING_SNAKE_CASE_ = 1     ,	)->   Union[str, Any]:





													'''simple docstring'''






													__UpperCamelCase       =			sigma_max

													# setable values
													__UpperCamelCase       =			None

													self.set_sigmas(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			)



							def     A__		(  self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_ = None			)->   torch.FloatTensor:





													'''simple docstring'''






													return sample



							def     A__		(  self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_ = None     ,	SCREAMING_SNAKE_CASE_ = None			)->   str:





													'''simple docstring'''






													__UpperCamelCase       =			sampling_eps if sampling_eps is not None else self.config.sampling_eps

													__UpperCamelCase       =			torch.linspace(1     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	device=SCREAMING_SNAKE_CASE_			)



							def     A__		(  self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_ = None     ,	SCREAMING_SNAKE_CASE_ = None     ,	SCREAMING_SNAKE_CASE_ = None			)->   int:





													'''simple docstring'''






													__UpperCamelCase       =			sigma_min if sigma_min is not None else self.config.sigma_min
													__UpperCamelCase       =			sigma_max if sigma_max is not None else self.config.sigma_max
													__UpperCamelCase       =			sampling_eps if sampling_eps is not None else self.config.sampling_eps
													if self.timesteps is None:
																			self.set_timesteps(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			)

													__UpperCamelCase       =			sigma_min * (sigma_max / sigma_min) ** (self.timesteps / sampling_eps)
													__UpperCamelCase       =			torch.exp(torch.linspace(math.log(SCREAMING_SNAKE_CASE_			)     ,	math.log(SCREAMING_SNAKE_CASE_			)     ,	SCREAMING_SNAKE_CASE_			)			)
													__UpperCamelCase       =			torch.tensor([sigma_min * (sigma_max / sigma_min) ** t for t in self.timesteps]			)



							def     A__		(  self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			)->   Tuple:





													'''simple docstring'''






													return torch.where(
													    timesteps == 0     ,	torch.zeros_like(t.to(timesteps.device			)			)     ,	self.discrete_sigmas[timesteps - 1].to(timesteps.device			)     ,	)



							def     A__		(  self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_ = None     ,	SCREAMING_SNAKE_CASE_ = True     ,	)->   Union[SdeVeOutput, Tuple]:





													'''simple docstring'''






													if self.timesteps is None:
																			raise ValueError(
																			    '''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler'''			)

													__UpperCamelCase       =			timestep * torch.ones(
													    sample.shape[0]     ,	device=sample.device			)  # torch.repeat_interleave(timestep, sample.shape[0])
													__UpperCamelCase       =			(timestep * (len(self.timesteps			) - 1)).long()

													# mps requires indices to be in the same device, so we use cpu as is the default with cuda
													__UpperCamelCase       =			timesteps.to(self.discrete_sigmas.device			)

													__UpperCamelCase       =			self.discrete_sigmas[timesteps].to(sample.device			)
													__UpperCamelCase       =			self.get_adjacent_sigma(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			).to(sample.device			)
													__UpperCamelCase       =			torch.zeros_like(SCREAMING_SNAKE_CASE_			)
													__UpperCamelCase       =			(sigma**2 - adjacent_sigma**2) ** 0.5

													# equation 6 in the paper: the model_output modeled by the network is grad_x log pt(x)
													# also equation 47 shows the analog from SDE models to ancestral sampling methods
													__UpperCamelCase       =			diffusion.flatten()
													while len(diffusion.shape			) < len(sample.shape			):
																			__UpperCamelCase       =			diffusion.unsqueeze(-1			)
													__UpperCamelCase       =			drift - diffusion**2 * model_output

													#  equation 6: sample noise for the diffusion term of
													__UpperCamelCase       =			randn_tensor(
													    sample.shape     ,	layout=sample.layout     ,	generator=SCREAMING_SNAKE_CASE_     ,	device=sample.device     ,	dtype=sample.dtype			)
													__UpperCamelCase       =			sample - drift  # subtract because `dt` is a small negative timestep
													# TODO is the variable diffusion the correct scaling term for the noise?
													__UpperCamelCase       =			prev_sample_mean + diffusion * noise  # add impact of diffusion field g

													if not return_dict:
																			return (prev_sample, prev_sample_mean)

													return SdeVeOutput(prev_sample=SCREAMING_SNAKE_CASE_     ,	prev_sample_mean=SCREAMING_SNAKE_CASE_			)



							def     A__		(  self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_ = None     ,	SCREAMING_SNAKE_CASE_ = True     ,	)->   Union[SchedulerOutput, Tuple]:





													'''simple docstring'''






													if self.timesteps is None:
																			raise ValueError(
																			    '''`self.timesteps` is not set, you need to run \'set_timesteps\' after creating the scheduler'''			)

													# For small batch sizes, the paper "suggest replacing norm(z) with sqrt(d), where d is the dim. of z"
													# sample noise for correction
													__UpperCamelCase       =			randn_tensor(sample.shape     ,	layout=sample.layout     ,	generator=SCREAMING_SNAKE_CASE_			).to(sample.device			)

													# compute step size from the model_output, the noise, and the snr
													__UpperCamelCase       =			torch.norm(model_output.reshape(model_output.shape[0]     ,	-1			)     ,	dim=-1			).mean()
													__UpperCamelCase       =			torch.norm(noise.reshape(noise.shape[0]     ,	-1			)     ,	dim=-1			).mean()
													__UpperCamelCase       =			(self.config.snr * noise_norm / grad_norm) ** 2 * 2
													__UpperCamelCase       =			step_size * torch.ones(sample.shape[0]			).to(sample.device			)
													# self.repeat_scalar(step_size, sample.shape[0])

													# compute corrected sample: model_output term and noise term
													__UpperCamelCase       =			step_size.flatten()
													while len(step_size.shape			) < len(sample.shape			):
																			__UpperCamelCase       =			step_size.unsqueeze(-1			)
													__UpperCamelCase       =			sample + step_size * model_output
													__UpperCamelCase       =			prev_sample_mean + ((step_size * 2) ** 0.5) * noise

													if not return_dict:
																			return (prev_sample,)

													return SchedulerOutput(prev_sample=SCREAMING_SNAKE_CASE_			)



							def     A__		(  self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	)->   torch.FloatTensor:





													'''simple docstring'''






													__UpperCamelCase       =			timesteps.to(original_samples.device			)
													__UpperCamelCase       =			self.discrete_sigmas.to(original_samples.device			)[timesteps]
													__UpperCamelCase       =			(
													    noise * sigmas[:, None, None, None]
													    if noise is not None
													    else torch.randn_like(SCREAMING_SNAKE_CASE_			) * sigmas[:, None, None, None]
													)
													__UpperCamelCase       =			noise + original_samples
													return noisy_samples



							def __len__(  self			)->   List[Any]:





													'''simple docstring'''






													return self.config.num_train_timesteps






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     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_=13     ,	SCREAMING_SNAKE_CASE_=2     ,	SCREAMING_SNAKE_CASE_=24     ,	SCREAMING_SNAKE_CASE_=16     ,	SCREAMING_SNAKE_CASE_=True     ,	SCREAMING_SNAKE_CASE_=True     ,	SCREAMING_SNAKE_CASE_=32     ,	SCREAMING_SNAKE_CASE_=5     ,	SCREAMING_SNAKE_CASE_=4     ,	SCREAMING_SNAKE_CASE_=37     ,	SCREAMING_SNAKE_CASE_="gelu"     ,	SCREAMING_SNAKE_CASE_=0.1     ,	SCREAMING_SNAKE_CASE_=0.1     ,	SCREAMING_SNAKE_CASE_=10     ,	SCREAMING_SNAKE_CASE_=0.0_2     ,	SCREAMING_SNAKE_CASE_=None     ,	SCREAMING_SNAKE_CASE_=2     ,	SCREAMING_SNAKE_CASE_=2     ,	)->   Optional[int]:





													'''simple docstring'''






													__UpperCamelCase       =			parent
													__UpperCamelCase       =			batch_size
													__UpperCamelCase       =			patch_size
													__UpperCamelCase       =			max_length
													__UpperCamelCase       =			num_mel_bins
													__UpperCamelCase       =			is_training
													__UpperCamelCase       =			use_labels
													__UpperCamelCase       =			hidden_size
													__UpperCamelCase       =			num_hidden_layers
													__UpperCamelCase       =			num_attention_heads
													__UpperCamelCase       =			intermediate_size
													__UpperCamelCase       =			hidden_act
													__UpperCamelCase       =			hidden_dropout_prob
													__UpperCamelCase       =			attention_probs_dropout_prob
													__UpperCamelCase       =			type_sequence_label_size
													__UpperCamelCase       =			initializer_range
													__UpperCamelCase       =			scope
													__UpperCamelCase       =			frequency_stride
													__UpperCamelCase       =			time_stride

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



							def     A__		(  self			)->   Dict:





													'''simple docstring'''






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

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

													__UpperCamelCase       =			self.get_config()

													return config, input_values, labels



							def     A__		(  self			)->   Optional[int]:





													'''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=SCREAMING_SNAKE_CASE_     ,	initializer_range=self.initializer_range     ,	frequency_stride=self.frequency_stride     ,	time_stride=self.time_stride     ,	)



							def     A__		(  self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			)->   Optional[Any]:





													'''simple docstring'''






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



							def     A__		(  self			)->   Tuple:





													'''simple docstring'''






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






@require_torch
class        SCREAMING_SNAKE_CASE__    (							SCREAMING_SNAKE_CASE_   ,		SCREAMING_SNAKE_CASE_   ,		unittest.TestCase    ):

							"""simple docstring"""






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



							def     A__		(  self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_			)->   int:





													'''simple docstring'''






													if pipeline_test_casse_name == "AudioClassificationPipelineTests":
																			return True

													return False



							def     A__		(  self			)->   Tuple:





													'''simple docstring'''






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



							def     A__		(  self			)->   Tuple:





													'''simple docstring'''






													self.config_tester.run_common_tests()



							@unittest.skip(reason='''AST does not use inputs_embeds'''			)
							def     A__		(  self			)->   Union[str, Any]:





													'''simple docstring'''






													pass



							def     A__		(  self			)->   List[Any]:





													'''simple docstring'''






													__UpperCamelCase  ,							__UpperCamelCase       =			self.model_tester.prepare_config_and_inputs_for_common()

													for model_class in self.all_model_classes:
																			__UpperCamelCase       =			model_class(SCREAMING_SNAKE_CASE_			)
																			self.assertIsInstance(model.get_input_embeddings()     ,	(nn.Module)			)
																			__UpperCamelCase       =			model.get_output_embeddings()
																			self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_     ,	nn.Linear			)			)



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





													'''simple docstring'''






													__UpperCamelCase  ,							__UpperCamelCase       =			self.model_tester.prepare_config_and_inputs_for_common()

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

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



							def     A__		(  self			)->   List[Any]:





													'''simple docstring'''






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



							@slow
							def     A__		(  self			)->   Optional[Any]:





													'''simple docstring'''






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





def 	A_ (							)      ->    int:



						'''simple docstring'''

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

						__UpperCamelCase  ,							__UpperCamelCase       =			torchaudio.load(snake_case )

						return audio, sampling_rate






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

							"""simple docstring"""






							@cached_property
							def     A__		(  self			)->   List[str]:





													'''simple docstring'''






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



							@slow
							def     A__		(  self			)->   Dict:





													'''simple docstring'''






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

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

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

													# verify the logits
													__UpperCamelCase       =			torch.Size((1, 527)			)
													self.assertEqual(outputs.logits.shape     ,	SCREAMING_SNAKE_CASE_			)

													__UpperCamelCase       =			torch.tensor([-0.8_7_6_0, -7.0_0_4_2, -8.6_6_0_2]			).to(SCREAMING_SNAKE_CASE_			)

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




