






import gc
import unittest

import numpy as np
import torch
import torch.nn.functional as F
from transformers import (
    ClapTextConfig,
    ClapTextModelWithProjection,
    RobertaTokenizer,
    SpeechTaHifiGan,
    SpeechTaHifiGanConfig,
)

from diffusers import (
    AudioLDMPipeline,
    AutoencoderKL,
    DDIMScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    UNetaDConditionModel,
)
from diffusers.utils import is_xformers_available, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism

from ..pipeline_params import TEXT_TO_AUDIO_BATCH_PARAMS, TEXT_TO_AUDIO_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()

class 		_snake_case	(	A__ ,     unittest.TestCase       ):
			_lowercase		:     Optional[int]        =				AudioLDMPipeline
			_lowercase		:     Union[str, Any]        =				TEXT_TO_AUDIO_PARAMS
			_lowercase		:     List[str]        =				TEXT_TO_AUDIO_BATCH_PARAMS
			_lowercase		:     Tuple        =				frozenset(
			    [
			        '''num_inference_steps''',
			        '''num_waveforms_per_prompt''',
			        '''generator''',
			        '''latents''',
			        '''output_type''',
			        '''return_dict''',
			        '''callback''',
			        '''callback_steps''',
			    ]       )






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Dict:
						torch.manual_seed(0)
						SCREAMING_SNAKE_CASE							=			UNetaDConditionModel(
						    block_out_channels=(32, 64)		,       layers_per_block=2		,       sample_size=32		,       in_channels=4		,       out_channels=4		,       down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D')		,       up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D')		,       cross_attention_dim=(32, 64)		,       class_embed_type='simple_projection'		,       projection_class_embeddings_input_dim=32		,       class_embeddings_concat=a		,       )
						SCREAMING_SNAKE_CASE							=			DDIMScheduler(
						    beta_start=0.0_00_85		,       beta_end=0.0_12		,       beta_schedule='scaled_linear'		,       clip_sample=a		,       set_alpha_to_one=a		,       )
						torch.manual_seed(0)
						SCREAMING_SNAKE_CASE							=			AutoencoderKL(
						    block_out_channels=[32, 64]		,       in_channels=1		,       out_channels=1		,       down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D']		,       up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D']		,       latent_channels=4		,       )
						torch.manual_seed(0)
						SCREAMING_SNAKE_CASE							=			ClapTextConfig(
						    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=1000		,       projection_dim=32		,       )
						SCREAMING_SNAKE_CASE							=			ClapTextModelWithProjection(a)
						SCREAMING_SNAKE_CASE							=			RobertaTokenizer.from_pretrained('hf-internal-testing/tiny-random-roberta'		,       model_max_length=77)

						SCREAMING_SNAKE_CASE							=			SpeechTaHifiGanConfig(
						    model_in_dim=8		,       sampling_rate=1_6000		,       upsample_initial_channel=16		,       upsample_rates=[2, 2]		,       upsample_kernel_sizes=[4, 4]		,       resblock_kernel_sizes=[3, 7]		,       resblock_dilation_sizes=[[1, 3, 5], [1, 3, 5]]		,       normalize_before=a		,       )

						SCREAMING_SNAKE_CASE							=			SpeechTaHifiGan(a)

						SCREAMING_SNAKE_CASE							=			{
						    'unet': unet,
						    'scheduler': scheduler,
						    'vae': vae,
						    'text_encoder': text_encoder,
						    'tokenizer': tokenizer,
						    'vocoder': vocoder,
						}
						return components






			def  SCREAMING_SNAKE_CASE__     (							self		,       a		,       a=0)   ->							int:
						if str(a).startswith('mps'):
									SCREAMING_SNAKE_CASE							=			torch.manual_seed(a)
						else:
									SCREAMING_SNAKE_CASE							=			torch.Generator(device=a).manual_seed(a)
						SCREAMING_SNAKE_CASE							=			{
						    'prompt': 'A hammer hitting a wooden surface',
						    'generator': generator,
						    'num_inference_steps': 2,
						    'guidance_scale': 6.0,
						}
						return inputs






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Optional[Any]:
						SCREAMING_SNAKE_CASE							=			'cpu'  # ensure determinism for the device-dependent torch.Generator

						SCREAMING_SNAKE_CASE							=			self.get_dummy_components()
						SCREAMING_SNAKE_CASE							=			AudioLDMPipeline(**a)
						SCREAMING_SNAKE_CASE							=			audioldm_pipe.to(a)
						audioldm_pipe.set_progress_bar_config(disable=a)

						SCREAMING_SNAKE_CASE							=			self.get_dummy_inputs(a)
						SCREAMING_SNAKE_CASE							=			audioldm_pipe(**a)
						SCREAMING_SNAKE_CASE							=			output.audios[0]

						assert audio.ndim == 1
						assert len(a) == 256

						SCREAMING_SNAKE_CASE							=			audio[:10]
						SCREAMING_SNAKE_CASE							=			np.array(
						    [-0.00_50, 0.00_50, -0.00_60, 0.00_33, -0.00_26, 0.00_33, -0.00_27, 0.00_33, -0.00_28, 0.00_33])

						assert np.abs(audio_slice - expected_slice).max() < 1E-2






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Tuple:
						SCREAMING_SNAKE_CASE							=			self.get_dummy_components()
						SCREAMING_SNAKE_CASE							=			AudioLDMPipeline(**a)
						SCREAMING_SNAKE_CASE							=			audioldm_pipe.to(a)
						SCREAMING_SNAKE_CASE							=			audioldm_pipe.to(a)
						audioldm_pipe.set_progress_bar_config(disable=a)

						SCREAMING_SNAKE_CASE							=			self.get_dummy_inputs(a)
						SCREAMING_SNAKE_CASE							=			3 * [inputs['prompt']]

						# forward
						SCREAMING_SNAKE_CASE							=			audioldm_pipe(**a)
						SCREAMING_SNAKE_CASE							=			output.audios[0]

						SCREAMING_SNAKE_CASE							=			self.get_dummy_inputs(a)
						SCREAMING_SNAKE_CASE							=			3 * [inputs.pop('prompt')]

						SCREAMING_SNAKE_CASE							=			audioldm_pipe.tokenizer(
						    a		,       padding='max_length'		,       max_length=audioldm_pipe.tokenizer.model_max_length		,       truncation=a		,       return_tensors='pt'		,       )
						SCREAMING_SNAKE_CASE							=			text_inputs['input_ids'].to(a)

						SCREAMING_SNAKE_CASE							=			audioldm_pipe.text_encoder(
						    a		,       )
						SCREAMING_SNAKE_CASE							=			prompt_embeds.text_embeds
						# additional L_2 normalization over each hidden-state
						SCREAMING_SNAKE_CASE							=			F.normalize(a		,       dim=-1)

						SCREAMING_SNAKE_CASE							=			prompt_embeds

						# forward
						SCREAMING_SNAKE_CASE							=			audioldm_pipe(**a)
						SCREAMING_SNAKE_CASE							=			output.audios[0]

						assert np.abs(audio_a - audio_a).max() < 1E-2






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							List[str]:
						SCREAMING_SNAKE_CASE							=			self.get_dummy_components()
						SCREAMING_SNAKE_CASE							=			AudioLDMPipeline(**a)
						SCREAMING_SNAKE_CASE							=			audioldm_pipe.to(a)
						SCREAMING_SNAKE_CASE							=			audioldm_pipe.to(a)
						audioldm_pipe.set_progress_bar_config(disable=a)

						SCREAMING_SNAKE_CASE							=			self.get_dummy_inputs(a)
						SCREAMING_SNAKE_CASE							=			3 * ['this is a negative prompt']
						SCREAMING_SNAKE_CASE							=			negative_prompt
						SCREAMING_SNAKE_CASE							=			3 * [inputs['prompt']]

						# forward
						SCREAMING_SNAKE_CASE							=			audioldm_pipe(**a)
						SCREAMING_SNAKE_CASE							=			output.audios[0]

						SCREAMING_SNAKE_CASE							=			self.get_dummy_inputs(a)
						SCREAMING_SNAKE_CASE							=			3 * [inputs.pop('prompt')]

						SCREAMING_SNAKE_CASE							=			[]
						for p in [prompt, negative_prompt]:
									SCREAMING_SNAKE_CASE							=			audioldm_pipe.tokenizer(
									    a		,       padding='max_length'		,       max_length=audioldm_pipe.tokenizer.model_max_length		,       truncation=a		,       return_tensors='pt'		,       )
									SCREAMING_SNAKE_CASE							=			text_inputs['input_ids'].to(a)

									SCREAMING_SNAKE_CASE							=			audioldm_pipe.text_encoder(
									    a		,       )
									SCREAMING_SNAKE_CASE							=			text_embeds.text_embeds
									# additional L_2 normalization over each hidden-state
									SCREAMING_SNAKE_CASE							=			F.normalize(a		,       dim=-1)

									embeds.append(a)

						SCREAMING_SNAKE_CASE					,    SCREAMING_SNAKE_CASE							=			embeds

						# forward
						SCREAMING_SNAKE_CASE							=			audioldm_pipe(**a)
						SCREAMING_SNAKE_CASE							=			output.audios[0]

						assert np.abs(audio_a - audio_a).max() < 1E-2






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Dict:
						SCREAMING_SNAKE_CASE							=			'cpu'  # ensure determinism for the device-dependent torch.Generator
						SCREAMING_SNAKE_CASE							=			self.get_dummy_components()
						SCREAMING_SNAKE_CASE							=			PNDMScheduler(skip_prk_steps=a)
						SCREAMING_SNAKE_CASE							=			AudioLDMPipeline(**a)
						SCREAMING_SNAKE_CASE							=			audioldm_pipe.to(a)
						audioldm_pipe.set_progress_bar_config(disable=a)

						SCREAMING_SNAKE_CASE							=			self.get_dummy_inputs(a)
						SCREAMING_SNAKE_CASE							=			'egg cracking'
						SCREAMING_SNAKE_CASE							=			audioldm_pipe(**a		,       negative_prompt=a)
						SCREAMING_SNAKE_CASE							=			output.audios[0]

						assert audio.ndim == 1
						assert len(a) == 256

						SCREAMING_SNAKE_CASE							=			audio[:10]
						SCREAMING_SNAKE_CASE							=			np.array(
						    [-0.00_51, 0.00_50, -0.00_60, 0.00_34, -0.00_26, 0.00_33, -0.00_27, 0.00_33, -0.00_28, 0.00_32])

						assert np.abs(audio_slice - expected_slice).max() < 1E-2






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							List[Any]:
						SCREAMING_SNAKE_CASE							=			'cpu'  # ensure determinism for the device-dependent torch.Generator
						SCREAMING_SNAKE_CASE							=			self.get_dummy_components()
						SCREAMING_SNAKE_CASE							=			PNDMScheduler(skip_prk_steps=a)
						SCREAMING_SNAKE_CASE							=			AudioLDMPipeline(**a)
						SCREAMING_SNAKE_CASE							=			audioldm_pipe.to(a)
						audioldm_pipe.set_progress_bar_config(disable=a)

						SCREAMING_SNAKE_CASE							=			'A hammer hitting a wooden surface'

						# test num_waveforms_per_prompt=1 (default)
						SCREAMING_SNAKE_CASE							=			audioldm_pipe(a		,       num_inference_steps=2).audios

						assert audios.shape == (1, 256)

						# test num_waveforms_per_prompt=1 (default) for batch of prompts
						SCREAMING_SNAKE_CASE							=			2
						SCREAMING_SNAKE_CASE							=			audioldm_pipe([prompt] * batch_size		,       num_inference_steps=2).audios

						assert audios.shape == (batch_size, 256)

						# test num_waveforms_per_prompt for single prompt
						SCREAMING_SNAKE_CASE							=			2
						SCREAMING_SNAKE_CASE							=			audioldm_pipe(a		,       num_inference_steps=2		,       num_waveforms_per_prompt=a).audios

						assert audios.shape == (num_waveforms_per_prompt, 256)

						# test num_waveforms_per_prompt for batch of prompts
						SCREAMING_SNAKE_CASE							=			2
						SCREAMING_SNAKE_CASE							=			audioldm_pipe(
						    [prompt] * batch_size		,       num_inference_steps=2		,       num_waveforms_per_prompt=a).audios

						assert audios.shape == (batch_size * num_waveforms_per_prompt, 256)






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							str:
						SCREAMING_SNAKE_CASE							=			'cpu'  # ensure determinism for the device-dependent torch.Generator
						SCREAMING_SNAKE_CASE							=			self.get_dummy_components()
						SCREAMING_SNAKE_CASE							=			AudioLDMPipeline(**a)
						SCREAMING_SNAKE_CASE							=			audioldm_pipe.to(a)
						audioldm_pipe.set_progress_bar_config(disable=a)
						SCREAMING_SNAKE_CASE							=			audioldm_pipe.vocoder.config.sampling_rate

						SCREAMING_SNAKE_CASE							=			self.get_dummy_inputs(a)
						SCREAMING_SNAKE_CASE							=			audioldm_pipe(audio_length_in_s=0.0_16		,       **a)
						SCREAMING_SNAKE_CASE							=			output.audios[0]

						assert audio.ndim == 1
						assert len(a) / vocoder_sampling_rate == 0.0_16

						SCREAMING_SNAKE_CASE							=			audioldm_pipe(audio_length_in_s=0.0_32		,       **a)
						SCREAMING_SNAKE_CASE							=			output.audios[0]

						assert audio.ndim == 1
						assert len(a) / vocoder_sampling_rate == 0.0_32






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Optional[int]:
						SCREAMING_SNAKE_CASE							=			self.get_dummy_components()
						SCREAMING_SNAKE_CASE							=			AudioLDMPipeline(**a)
						SCREAMING_SNAKE_CASE							=			audioldm_pipe.to(a)
						audioldm_pipe.set_progress_bar_config(disable=a)

						SCREAMING_SNAKE_CASE							=			['hey']

						SCREAMING_SNAKE_CASE							=			audioldm_pipe(a		,       num_inference_steps=1)
						SCREAMING_SNAKE_CASE							=			output.audios.shape
						assert audio_shape == (1, 256)

						SCREAMING_SNAKE_CASE							=			audioldm_pipe.vocoder.config
						config.model_in_dim *= 2
						SCREAMING_SNAKE_CASE							=			SpeechTaHifiGan(a).to(a)
						SCREAMING_SNAKE_CASE							=			audioldm_pipe(a		,       num_inference_steps=1)
						SCREAMING_SNAKE_CASE							=			output.audios.shape
						# waveform shape is unchanged, we just have 2x the number of mel channels in the spectrogram
						assert audio_shape == (1, 256)






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Dict:
						self._test_attention_slicing_forward_pass(test_mean_pixel_difference=a)






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Optional[Any]:
						self._test_inference_batch_single_identical(test_mean_pixel_difference=a)







			@unittest.skipIf(
			    torch_device != 'cuda' or not is_xformers_available()		,       reason='XFormers attention is only available with CUDA and `xformers` installed'		,       )
			def  SCREAMING_SNAKE_CASE__     (							self)   ->							int:
						self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=a)



@slow
class 		_snake_case	(	unittest.TestCase       ):






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






			def  SCREAMING_SNAKE_CASE__     (							self		,       a		,       a="cpu"		,       a=torch.floataa		,       a=0)   ->							Dict:
						SCREAMING_SNAKE_CASE							=			torch.Generator(device=a).manual_seed(a)
						SCREAMING_SNAKE_CASE							=			np.random.RandomState(a).standard_normal((1, 8, 128, 16))
						SCREAMING_SNAKE_CASE							=			torch.from_numpy(a).to(device=a		,       dtype=a)
						SCREAMING_SNAKE_CASE							=			{
						    'prompt': 'A hammer hitting a wooden surface',
						    'latents': latents,
						    'generator': generator,
						    'num_inference_steps': 3,
						    'guidance_scale': 2.5,
						}
						return inputs






			def  SCREAMING_SNAKE_CASE__     (							self)   ->							Any:
						SCREAMING_SNAKE_CASE							=			AudioLDMPipeline.from_pretrained('cvssp/audioldm')
						SCREAMING_SNAKE_CASE							=			audioldm_pipe.to(a)
						audioldm_pipe.set_progress_bar_config(disable=a)

						SCREAMING_SNAKE_CASE							=			self.get_inputs(a)
						SCREAMING_SNAKE_CASE							=			25
						SCREAMING_SNAKE_CASE							=			audioldm_pipe(**a).audios[0]

						assert audio.ndim == 1
						assert len(a) == 8_1920

						SCREAMING_SNAKE_CASE							=			audio[7_7230:7_7240]
						SCREAMING_SNAKE_CASE							=			np.array(
						    [-0.48_84, -0.46_07, 0.00_23, 0.50_07, 0.58_96, 0.51_51, 0.38_13, -0.02_08, -0.36_87, -0.43_15])
						SCREAMING_SNAKE_CASE							=			np.abs(expected_slice - audio_slice).max()
						assert max_diff < 1E-2







			def  SCREAMING_SNAKE_CASE__     (							self)   ->							List[str]:
						SCREAMING_SNAKE_CASE							=			AudioLDMPipeline.from_pretrained('cvssp/audioldm')
						SCREAMING_SNAKE_CASE							=			LMSDiscreteScheduler.from_config(audioldm_pipe.scheduler.config)
						SCREAMING_SNAKE_CASE							=			audioldm_pipe.to(a)
						audioldm_pipe.set_progress_bar_config(disable=a)

						SCREAMING_SNAKE_CASE							=			self.get_inputs(a)
						SCREAMING_SNAKE_CASE							=			audioldm_pipe(**a).audios[0]

						assert audio.ndim == 1
						assert len(a) == 8_1920

						SCREAMING_SNAKE_CASE							=			audio[2_7780:2_7790]
						SCREAMING_SNAKE_CASE							=			np.array([-0.21_31, -0.08_73, -0.01_24, -0.01_89, 0.05_69, 0.13_73, 0.18_83, 0.28_86, 0.32_97, 0.22_12])
						SCREAMING_SNAKE_CASE							=			np.abs(expected_slice - audio_slice).max()
						assert max_diff < 3E-2








import tempfile
import unittest

import numpy as np

from diffusers import (
    DDIMScheduler,
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionPipeline,
    PNDMScheduler,
)
from diffusers.utils.testing_utils import is_onnx_available, nightly, require_onnxruntime, require_torch_gpu

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
 import onnxruntime as ort






class _lowerCamelCase(		_a,					unittest.TestCase  ):
       lowercase_					:      Optional[int]       					=     """hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline"""
       def      UpperCamelCase	(   self, lowerCamelCase=0)			->  str:




           """simple docstring"""

           _lowercase			:				Optional[int] 						=						np.random.RandomState(lowerCamelCase)
           _lowercase			:				Union[str, Any] 						=						{
               'prompt': 'A painting of a squirrel eating a burger',
               'generator': generator,
               'num_inference_steps': 2,
               'guidance_scale': 7.5,
               'output_type': 'numpy',
           }
           return inputs
       def      UpperCamelCase	(   self)			->  List[str]:




           """simple docstring"""

           _lowercase			:				int 						=						OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint, provider='CPUExecutionProvider')
           pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase			:				List[str] 						=						self.get_dummy_inputs()
           _lowercase			:				Tuple 						=						pipe(**lowerCamelCase).images
           _lowercase			:				Optional[Any] 						=						image[0, -3:, -3:, -1]

           assert image.shape == (1, 1_28, 1_28, 3)
           _lowercase			:				List[Any] 						=						np.array([0.6_5_0_7_2, 0.5_8_4_9_2, 0.4_8_2_1_9, 0.5_5_5_2_1, 0.5_3_1_8_0, 0.5_5_9_3_9, 0.5_0_6_9_7, 0.3_9_8_0_0, 0.4_6_4_5_5])

           assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
       def      UpperCamelCase	(   self)			->  List[Any]:




           """simple docstring"""

           _lowercase			:				str 						=						OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint, provider='CPUExecutionProvider')
           _lowercase			:				List[Any] 						=						PNDMScheduler.from_config(pipe.scheduler.config, skip_prk_steps=lowerCamelCase)
           pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase			:				Dict 						=						self.get_dummy_inputs()
           _lowercase			:				Optional[int] 						=						pipe(**lowerCamelCase).images
           _lowercase			:				Dict 						=						image[0, -3:, -3:, -1]

           assert image.shape == (1, 1_28, 1_28, 3)
           _lowercase			:				List[Any] 						=						np.array([0.6_5_8_6_3, 0.5_9_4_2_5, 0.4_9_3_2_6, 0.5_6_3_1_3, 0.5_3_8_7_5, 0.5_6_6_2_7, 0.5_1_0_6_5, 0.3_9_7_7_7, 0.4_6_3_3_0])

           assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
       def      UpperCamelCase	(   self)			->  str:




           """simple docstring"""

           _lowercase			:				Optional[int] 						=						OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint, provider='CPUExecutionProvider')
           _lowercase			:				Optional[int] 						=						LMSDiscreteScheduler.from_config(pipe.scheduler.config)
           pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase			:				Dict 						=						self.get_dummy_inputs()
           _lowercase			:				Union[str, Any] 						=						pipe(**lowerCamelCase).images
           _lowercase			:				str 						=						image[0, -3:, -3:, -1]

           assert image.shape == (1, 1_28, 1_28, 3)
           _lowercase			:				Union[str, Any] 						=						np.array([0.5_3_7_5_5, 0.6_0_7_8_6, 0.4_7_4_0_2, 0.4_9_4_8_8, 0.5_1_8_6_9, 0.4_9_8_1_9, 0.4_7_9_8_5, 0.3_8_9_5_7, 0.4_4_2_7_9])

           assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
       def      UpperCamelCase	(   self)			->  Optional[int]:




           """simple docstring"""

           _lowercase			:				Union[str, Any] 						=						OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint, provider='CPUExecutionProvider')
           _lowercase			:				Any 						=						EulerDiscreteScheduler.from_config(pipe.scheduler.config)
           pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase			:				List[Any] 						=						self.get_dummy_inputs()
           _lowercase			:				Any 						=						pipe(**lowerCamelCase).images
           _lowercase			:				Tuple 						=						image[0, -3:, -3:, -1]

           assert image.shape == (1, 1_28, 1_28, 3)
           _lowercase			:				Union[str, Any] 						=						np.array([0.5_3_7_5_5, 0.6_0_7_8_6, 0.4_7_4_0_2, 0.4_9_4_8_8, 0.5_1_8_6_9, 0.4_9_8_1_9, 0.4_7_9_8_5, 0.3_8_9_5_7, 0.4_4_2_7_9])

           assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
       def      UpperCamelCase	(   self)			->  Dict:




           """simple docstring"""

           _lowercase			:				List[str] 						=						OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint, provider='CPUExecutionProvider')
           _lowercase			:				Optional[int] 						=						EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
           pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase			:				List[Any] 						=						self.get_dummy_inputs()
           _lowercase			:				Optional[int] 						=						pipe(**lowerCamelCase).images
           _lowercase			:				str 						=						image[0, -3:, -3:, -1]

           assert image.shape == (1, 1_28, 1_28, 3)
           _lowercase			:				List[str] 						=						np.array([0.5_3_8_1_7, 0.6_0_8_1_2, 0.4_7_3_8_4, 0.4_9_5_3_0, 0.5_1_8_9_4, 0.4_9_8_1_4, 0.4_7_9_8_4, 0.3_8_9_5_8, 0.4_4_2_7_1])

           assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
       def      UpperCamelCase	(   self)			->  List[Any]:




           """simple docstring"""

           _lowercase			:				List[Any] 						=						OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint, provider='CPUExecutionProvider')
           _lowercase			:				Any 						=						DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
           pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase			:				Union[str, Any] 						=						self.get_dummy_inputs()
           _lowercase			:				Any 						=						pipe(**lowerCamelCase).images
           _lowercase			:				List[str] 						=						image[0, -3:, -3:, -1]

           assert image.shape == (1, 1_28, 1_28, 3)
           _lowercase			:				Any 						=						np.array([0.5_3_8_9_5, 0.6_0_8_0_8, 0.4_7_9_3_3, 0.4_9_6_0_8, 0.5_1_8_8_6, 0.4_9_9_5_0, 0.4_8_0_5_3, 0.3_8_9_5_7, 0.4_4_2_0_0])

           assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-2
       def      UpperCamelCase	(   self)			->  int:




           """simple docstring"""

           _lowercase			:				Dict 						=						OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint, provider='CPUExecutionProvider')
           pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase			:				str 						=						self.get_dummy_inputs()
           _lowercase			:				Any 						=						3 * [inputs['prompt']]

           # forward
           _lowercase			:				int 						=						pipe(**lowerCamelCase)
           _lowercase			:				Optional[int] 						=						output.images[0, -3:, -3:, -1]

           _lowercase			:				int 						=						self.get_dummy_inputs()
           _lowercase			:				Union[str, Any] 						=						3 * [inputs.pop('prompt')]

           _lowercase			:				Union[str, Any] 						=						pipe.tokenizer(
               lowerCamelCase, padding='max_length', max_length=pipe.tokenizer.model_max_length, truncation=lowerCamelCase, return_tensors='np', )
           _lowercase			:				Tuple 						=						text_inputs['input_ids']

           _lowercase			:				Any 						=						pipe.text_encoder(input_ids=text_inputs.astype(np.intaa))[0]

           _lowercase			:				List[Any] 						=						prompt_embeds

           # forward
           _lowercase			:				Union[str, Any] 						=						pipe(**lowerCamelCase)
           _lowercase			:				Union[str, Any] 						=						output.images[0, -3:, -3:, -1]

           assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()).max() < 1E-4




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




           """simple docstring"""

           _lowercase			:				Optional[Any] 						=						OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint, provider='CPUExecutionProvider')
           pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase			:				Optional[Any] 						=						self.get_dummy_inputs()
           _lowercase			:				Any 						=						3 * ['this is a negative prompt']
           _lowercase			:				str 						=						negative_prompt
           _lowercase			:				Optional[int] 						=						3 * [inputs['prompt']]

           # forward
           _lowercase			:				int 						=						pipe(**lowerCamelCase)
           _lowercase			:				str 						=						output.images[0, -3:, -3:, -1]

           _lowercase			:				Union[str, Any] 						=						self.get_dummy_inputs()
           _lowercase			:				str 						=						3 * [inputs.pop('prompt')]

           _lowercase			:				Optional[int] 						=						[]
           for p in [prompt, negative_prompt]:
               _lowercase			:				Tuple 						=						pipe.tokenizer(
                   lowerCamelCase, padding='max_length', max_length=pipe.tokenizer.model_max_length, truncation=lowerCamelCase, return_tensors='np', )
               _lowercase			:				Dict 						=						text_inputs['input_ids']

               embeds.append(pipe.text_encoder(input_ids=text_inputs.astype(np.intaa))[0])

           _lowercase						,							_lowercase			:				str 						=						embeds

           # forward
           _lowercase			:				Dict 						=						pipe(**lowerCamelCase)
           _lowercase			:				Tuple 						=						output.images[0, -3:, -3:, -1]

           assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()).max() < 1E-4






@nightly
@require_onnxruntime
@require_torch_gpu
class _lowerCamelCase(		unittest.TestCase  ):
       @property
       def      UpperCamelCase	(   self)			->  Union[str, Any]:




           """simple docstring"""

           return (
               "CUDAExecutionProvider",
               {
                   "gpu_mem_limit": "15000000000",  # 15GB
                   "arena_extend_strategy": "kSameAsRequested",
               },
           )
       @property
       def      UpperCamelCase	(   self)			->  str:




           """simple docstring"""

           _lowercase			:				int 						=						ort.SessionOptions()
           _lowercase			:				str 						=						False
           return options
       def      UpperCamelCase	(   self)			->  Optional[Any]:




           """simple docstring"""

           _lowercase			:				Optional[int] 						=						OnnxStableDiffusionPipeline.from_pretrained(
               'CompVis/stable-diffusion-v1-4', revision='onnx', safety_checker=lowerCamelCase, feature_extractor=lowerCamelCase, provider=self.gpu_provider, sess_options=self.gpu_options, )
           sd_pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase			:				List[Any] 						=						'A painting of a squirrel eating a burger'
           np.random.seed(0)
           _lowercase			:				Union[str, Any] 						=						sd_pipe([prompt], guidance_scale=6.0, num_inference_steps=10, output_type='np')
           _lowercase			:				Optional[Any] 						=						output.images

           _lowercase			:				Optional[int] 						=						image[0, -3:, -3:, -1]

           assert image.shape == (1, 5_12, 5_12, 3)
           _lowercase			:				Union[str, Any] 						=						np.array([0.0_4_5_2, 0.0_3_9_0, 0.0_0_8_7, 0.0_3_5_0, 0.0_6_1_7, 0.0_3_6_4, 0.0_5_4_4, 0.0_5_2_3, 0.0_7_2_0])

           assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-3
       def      UpperCamelCase	(   self)			->  Optional[int]:




           """simple docstring"""

           _lowercase			:				str 						=						DDIMScheduler.from_pretrained(
               'runwayml/stable-diffusion-v1-5', subfolder='scheduler', revision='onnx')
           _lowercase			:				str 						=						OnnxStableDiffusionPipeline.from_pretrained(
               'runwayml/stable-diffusion-v1-5', revision='onnx', scheduler=lowerCamelCase, safety_checker=lowerCamelCase, feature_extractor=lowerCamelCase, provider=self.gpu_provider, sess_options=self.gpu_options, )
           sd_pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase			:				List[Any] 						=						'open neural network exchange'
           _lowercase			:				List[Any] 						=						np.random.RandomState(0)
           _lowercase			:				Optional[Any] 						=						sd_pipe([prompt], guidance_scale=7.5, num_inference_steps=10, generator=lowerCamelCase, output_type='np')
           _lowercase			:				Optional[Any] 						=						output.images
           _lowercase			:				List[Any] 						=						image[0, -3:, -3:, -1]

           assert image.shape == (1, 5_12, 5_12, 3)
           _lowercase			:				Optional[int] 						=						np.array([0.2_8_6_7, 0.1_9_7_4, 0.1_4_8_1, 0.7_2_9_4, 0.7_2_5_1, 0.6_6_6_7, 0.4_1_9_4, 0.5_6_4_2, 0.6_4_8_6])

           assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-3
       def      UpperCamelCase	(   self)			->  List[str]:




           """simple docstring"""

           _lowercase			:				Dict 						=						LMSDiscreteScheduler.from_pretrained(
               'runwayml/stable-diffusion-v1-5', subfolder='scheduler', revision='onnx')
           _lowercase			:				Dict 						=						OnnxStableDiffusionPipeline.from_pretrained(
               'runwayml/stable-diffusion-v1-5', revision='onnx', scheduler=lowerCamelCase, safety_checker=lowerCamelCase, feature_extractor=lowerCamelCase, provider=self.gpu_provider, sess_options=self.gpu_options, )
           sd_pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase			:				Tuple 						=						'open neural network exchange'
           _lowercase			:				str 						=						np.random.RandomState(0)
           _lowercase			:				Dict 						=						sd_pipe([prompt], guidance_scale=7.5, num_inference_steps=10, generator=lowerCamelCase, output_type='np')
           _lowercase			:				Optional[Any] 						=						output.images
           _lowercase			:				int 						=						image[0, -3:, -3:, -1]

           assert image.shape == (1, 5_12, 5_12, 3)
           _lowercase			:				Optional[Any] 						=						np.array([0.2_3_0_6, 0.1_9_5_9, 0.1_5_9_3, 0.6_5_4_9, 0.6_3_9_4, 0.5_4_0_8, 0.5_0_6_5, 0.6_0_1_0, 0.6_1_6_1])

           assert np.abs(image_slice.flatten() - expected_slice).max() < 1E-3
       def      UpperCamelCase	(   self)			->  int:




           """simple docstring"""

           _lowercase			:				List[Any] 						=						0

           def test_callback_fn(lowerCamelCase, lowerCamelCase, lowerCamelCase) -> None:
               _lowercase			:				List[str] 						=						True
               nonlocal number_of_steps
               number_of_steps += 1
               if step == 0:
                   assert latents.shape == (1, 4, 64, 64)
                   _lowercase			:				Any 						=						latents[0, -3:, -3:, -1]
                   _lowercase			:				Tuple 						=						np.array(
                       [-0.6_7_7_2, -0.3_8_3_5, -1.2_4_5_6, 0.1_9_0_5, -1.0_9_7_4, 0.6_9_6_7, -1.9_3_5_3, 0.0_1_7_8, 1.0_1_6_7])

                   assert np.abs(latents_slice.flatten() - expected_slice).max() < 1E-3
               elif step == 5:
                   assert latents.shape == (1, 4, 64, 64)
                   _lowercase			:				List[Any] 						=						latents[0, -3:, -3:, -1]
                   _lowercase			:				str 						=						np.array(
                       [-0.3_3_5_1, 0.2_2_4_1, -0.1_8_3_7, -0.2_3_2_5, -0.6_5_7_7, 0.3_3_9_3, -0.0_2_4_1, 0.5_8_9_9, 1.3_8_7_5])

                   assert np.abs(latents_slice.flatten() - expected_slice).max() < 1E-3

           _lowercase			:				Any 						=						False

           _lowercase			:				int 						=						OnnxStableDiffusionPipeline.from_pretrained(
               'runwayml/stable-diffusion-v1-5', revision='onnx', safety_checker=lowerCamelCase, feature_extractor=lowerCamelCase, provider=self.gpu_provider, sess_options=self.gpu_options, )
           pipe.set_progress_bar_config(disable=lowerCamelCase)

           _lowercase			:				Any 						=						'Andromeda galaxy in a bottle'

           _lowercase			:				str 						=						np.random.RandomState(0)
           pipe(
               prompt=lowerCamelCase, num_inference_steps=5, guidance_scale=7.5, generator=lowerCamelCase, callback=lowerCamelCase, callback_steps=1, )
           assert test_callback_fn.has_been_called
           assert number_of_steps == 6




       def      UpperCamelCase	(   self)			->  Tuple:




           """simple docstring"""

           _lowercase			:				List[str] 						=						OnnxStableDiffusionPipeline.from_pretrained(
               'runwayml/stable-diffusion-v1-5', revision='onnx', safety_checker=lowerCamelCase, feature_extractor=lowerCamelCase, provider=self.gpu_provider, sess_options=self.gpu_options, )
           assert isinstance(lowerCamelCase, lowerCamelCase)
           assert pipe.safety_checker is None

           _lowercase			:				Optional[int] 						=						pipe('example prompt', num_inference_steps=2).images[0]
           assert image is not None

           # check that there's no error when saving a pipeline with one of the models being None
           with tempfile.TemporaryDirectory() as tmpdirname:
               pipe.save_pretrained(lowerCamelCase)
               _lowercase			:				Any 						=						OnnxStableDiffusionPipeline.from_pretrained(lowerCamelCase)

           # sanity check that the pipeline still works
           assert pipe.safety_checker is None
           _lowercase			:				List[str] 						=						pipe('example prompt', num_inference_steps=2).images[0]
           assert image is not None


