



"""simple docstring"""






from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPImageProcessor, CLIPVisionModel

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


__snake_case							:     Union[str, Any]   =					logging.get_logger(__name__)  # pylint: disable=invalid-name

__snake_case							:     Tuple   =					'\n    Examples:\n        ```py\n        >>> from PIL import Image\n        >>> import torch\n        >>> from diffusers import DiffusionPipeline\n        >>> from diffusers.utils import export_to_gif, load_image\n\n        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")\n\n        >>> repo = "openai/shap-e-img2img"\n        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)\n        >>> pipe = pipe.to(device)\n\n        >>> guidance_scale = 3.0\n        >>> image_url = "https://hf.co/datasets/diffusers/docs-images/resolve/main/shap-e/corgi.png"\n        >>> image = load_image(image_url).convert("RGB")\n\n        >>> images = pipe(\n        ...     image,\n        ...     guidance_scale=guidance_scale,\n        ...     num_inference_steps=64,\n        ...     frame_size=256,\n        ... ).images\n\n        >>> gif_path = export_to_gif(images[0], "corgi_3d.gif")\n        ```\n'



@dataclass
class     A__     (						__SCREAMING_SNAKE_CASE							):




	'''simple docstring'''





	SCREAMING_SNAKE_CASE					   =			4_2






class     A__     (						__SCREAMING_SNAKE_CASE							):




	'''simple docstring'''





	def __init__(  self:	Optional[Any] ,    _SCREAMING_SNAKE_CASE:	PriorTransformer ,    _SCREAMING_SNAKE_CASE:	CLIPVisionModel ,    _SCREAMING_SNAKE_CASE:	CLIPImageProcessor ,    _SCREAMING_SNAKE_CASE:	HeunDiscreteScheduler ,    _SCREAMING_SNAKE_CASE:	ShapERenderer ,    )       -> Optional[int]:

				"""simple docstring"""

				super().__init__()

				self.register_modules(
				    prior=_SCREAMING_SNAKE_CASE ,    image_encoder=_SCREAMING_SNAKE_CASE ,    image_processor=_SCREAMING_SNAKE_CASE ,    scheduler=_SCREAMING_SNAKE_CASE ,    renderer=_SCREAMING_SNAKE_CASE ,    )

	def 							_SCREAMING_SNAKE_CASE     (  self:	Tuple ,    _SCREAMING_SNAKE_CASE:	Dict ,    _SCREAMING_SNAKE_CASE:	Any ,    _SCREAMING_SNAKE_CASE:	List[str] ,    _SCREAMING_SNAKE_CASE:	Dict ,    _SCREAMING_SNAKE_CASE:	int ,    _SCREAMING_SNAKE_CASE:	List[Any])       -> str:

				"""simple docstring"""

				if latents is None:
							__lowerCAmelCase   :						Tuple				= randn_tensor(_SCREAMING_SNAKE_CASE ,    generator=_SCREAMING_SNAKE_CASE ,    device=_SCREAMING_SNAKE_CASE ,    dtype=_SCREAMING_SNAKE_CASE)
				else:
							if latents.shape != shape:
										raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}""")
							__lowerCAmelCase   :						Any				= latents.to(_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase   :						List[Any]				= latents * scheduler.init_noise_sigma
				return latents

	def 							_SCREAMING_SNAKE_CASE     (  self:	Union[str, Any] ,    _SCREAMING_SNAKE_CASE:	List[Any]=0)       -> Optional[int]:

				"""simple docstring"""

				if is_accelerate_available():
							from accelerate import cpu_offload
				else:
							raise ImportError("Please install accelerate via `pip install accelerate`")

				__lowerCAmelCase   :						Optional[Any]				= torch.device(F"""cuda:{gpu_id}""")

				__lowerCAmelCase   :						List[str]				= [self.image_encoder, self.prior]
				for cpu_offloaded_model in models:
							if cpu_offloaded_model is not None:
										cpu_offload(_SCREAMING_SNAKE_CASE ,    _SCREAMING_SNAKE_CASE)

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

				"""simple docstring"""

				if self.device != torch.device("meta") or not hasattr(self.image_encoder ,    "_hf_hook"):
							return self.device
				for module in self.image_encoder.modules():
							if (
							    hasattr(_SCREAMING_SNAKE_CASE ,    "_hf_hook")
							    and hasattr(module._hf_hook ,    "execution_device")
							    and module._hf_hook.execution_device is not None
							):
										return torch.device(module._hf_hook.execution_device)
				return self.device

	def 							_SCREAMING_SNAKE_CASE     (  self:	Optional[Any] ,    _SCREAMING_SNAKE_CASE:	List[str] ,    _SCREAMING_SNAKE_CASE:	Union[str, Any] ,    _SCREAMING_SNAKE_CASE:	Union[str, Any] ,    _SCREAMING_SNAKE_CASE:	str ,    )       -> Union[str, Any]:

				"""simple docstring"""

				if isinstance(_SCREAMING_SNAKE_CASE ,    _SCREAMING_SNAKE_CASE) and isinstance(image[0] ,    torch.Tensor):
							__lowerCAmelCase   :						List[Any]				= torch.cat(_SCREAMING_SNAKE_CASE ,    axis=0) if image[0].ndim == 4 else torch.stack(_SCREAMING_SNAKE_CASE ,    axis=0)

				if not isinstance(_SCREAMING_SNAKE_CASE ,    torch.Tensor):
							__lowerCAmelCase   :						Any				= self.image_processor(_SCREAMING_SNAKE_CASE ,    return_tensors="pt").pixel_values[0].unsqueeze(0)

				__lowerCAmelCase   :						Union[str, Any]				= image.to(dtype=self.image_encoder.dtype ,    device=_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase   :						Tuple				= self.image_encoder(_SCREAMING_SNAKE_CASE)["last_hidden_state"]
				__lowerCAmelCase   :						str				= image_embeds[:, 1:, :].contiguous()  # batch_size, dim, 256

				__lowerCAmelCase   :						List[str]				= image_embeds.repeat_interleave(_SCREAMING_SNAKE_CASE ,    dim=0)

				if do_classifier_free_guidance:
							__lowerCAmelCase   :						str				= torch.zeros_like(_SCREAMING_SNAKE_CASE)

							# For classifier free guidance, we need to do two forward passes.
							# Here we concatenate the unconditional and text embeddings into a single batch
							# to avoid doing two forward passes
							__lowerCAmelCase   :						List[Any]				= torch.cat([negative_image_embeds, image_embeds])

				return image_embeds







	@torch.no_grad()
	@replace_example_docstring(_SCREAMING_SNAKE_CASE)
	def __call__(  self:	Tuple ,    _SCREAMING_SNAKE_CASE:	Union[PIL.Image.Image, List[PIL.Image.Image]] ,    _SCREAMING_SNAKE_CASE:	int = 1 ,    _SCREAMING_SNAKE_CASE:	int = 25 ,    _SCREAMING_SNAKE_CASE:	Optional[Union[torch.Generator, List[torch.Generator]]] = None ,    _SCREAMING_SNAKE_CASE:	Optional[torch.FloatTensor] = None ,    _SCREAMING_SNAKE_CASE:	float = 4.0 ,    _SCREAMING_SNAKE_CASE:	int = 64 ,    _SCREAMING_SNAKE_CASE:	Optional[str] = "pil" ,    _SCREAMING_SNAKE_CASE:	bool = True ,    )       -> Dict:

				"""simple docstring"""

				if isinstance(_SCREAMING_SNAKE_CASE ,    PIL.Image.Image):
							__lowerCAmelCase   :						Tuple				= 1
				elif isinstance(_SCREAMING_SNAKE_CASE ,    torch.Tensor):
							__lowerCAmelCase   :						str				= image.shape[0]
				elif isinstance(_SCREAMING_SNAKE_CASE ,    _SCREAMING_SNAKE_CASE) and isinstance(image[0] ,    (torch.Tensor, PIL.Image.Image)):
							__lowerCAmelCase   :						str				= len(_SCREAMING_SNAKE_CASE)
				else:
							raise ValueError(
							    F"""`image` has to be of type `PIL.Image.Image`, `torch.Tensor`, `List[PIL.Image.Image]` or `List[torch.Tensor]` but is {type(_SCREAMING_SNAKE_CASE)}""")

				__lowerCAmelCase   :						Optional[Any]				= self._execution_device

				__lowerCAmelCase   :						Any				= batch_size * num_images_per_prompt

				__lowerCAmelCase   :						Dict				= guidance_scale > 1.0
				__lowerCAmelCase   :						Optional[Any]				= self._encode_image(_SCREAMING_SNAKE_CASE ,    _SCREAMING_SNAKE_CASE ,    _SCREAMING_SNAKE_CASE ,    _SCREAMING_SNAKE_CASE)

				# prior

				self.scheduler.set_timesteps(_SCREAMING_SNAKE_CASE ,    device=_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase   :						List[Any]				= self.scheduler.timesteps

				__lowerCAmelCase   :						Union[str, Any]				= self.prior.config.num_embeddings
				__lowerCAmelCase   :						Optional[int]				= self.prior.config.embedding_dim

				__lowerCAmelCase   :						List[str]				= self.prepare_latents(
				    (batch_size, num_embeddings * embedding_dim) ,    image_embeds.dtype ,    _SCREAMING_SNAKE_CASE ,    _SCREAMING_SNAKE_CASE ,    _SCREAMING_SNAKE_CASE ,    self.scheduler ,    )

				# YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
				__lowerCAmelCase   :						Any				= latents.reshape(latents.shape[0] ,    _SCREAMING_SNAKE_CASE ,    _SCREAMING_SNAKE_CASE)

				for i, t in enumerate(self.progress_bar(_SCREAMING_SNAKE_CASE)):
							# expand the latents if we are doing classifier free guidance
							__lowerCAmelCase   :						Optional[Any]				= torch.cat([latents] * 2) if do_classifier_free_guidance else latents
							__lowerCAmelCase   :						Union[str, Any]				= self.scheduler.scale_model_input(_SCREAMING_SNAKE_CASE ,    _SCREAMING_SNAKE_CASE)

							__lowerCAmelCase   :						Union[str, Any]				= self.prior(
							    _SCREAMING_SNAKE_CASE ,    timestep=_SCREAMING_SNAKE_CASE ,    proj_embedding=_SCREAMING_SNAKE_CASE ,    ).predicted_image_embedding

							# remove the variance
							__lowerCAmelCase   :						Tuple				= noise_pred.split(
							    scaled_model_input.shape[2] ,    dim=2)  # batch_size, num_embeddings, embedding_dim

							if do_classifier_free_guidance is not None:
										__lowerCAmelCase   :						str				= noise_pred.chunk(2)
										__lowerCAmelCase   :						Any				= noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

							__lowerCAmelCase   :						str				= self.scheduler.step(
							    _SCREAMING_SNAKE_CASE ,    timestep=_SCREAMING_SNAKE_CASE ,    sample=_SCREAMING_SNAKE_CASE ,    ).prev_sample

				if output_type == "latent":
							return ShapEPipelineOutput(images=_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase   :						int				= []
				for i, latent in enumerate(_SCREAMING_SNAKE_CASE):
							print()
							__lowerCAmelCase   :						List[Any]				= self.renderer.decode(
							    latent[None, :] ,    _SCREAMING_SNAKE_CASE ,    size=_SCREAMING_SNAKE_CASE ,    ray_batch_size=4096 ,    n_coarse_samples=64 ,    n_fine_samples=128 ,    )

							images.append(_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase   :						Dict				= torch.stack(_SCREAMING_SNAKE_CASE)

				if output_type not in ["np", "pil"]:
							raise ValueError(F"""Only the output types `pil` and `np` are supported not output_type={output_type}""")

				__lowerCAmelCase   :						Tuple				= images.cpu().numpy()

				if output_type == "pil":
							__lowerCAmelCase   :						str				= [self.numpy_to_pil(_SCREAMING_SNAKE_CASE) for image in images]

				# Offload last model to CPU
				if hasattr(self ,    "final_offload_hook") and self.final_offload_hook is not None:
							self.final_offload_hook.offload()

				if not return_dict:
							return (images,)

				return ShapEPipelineOutput(images=_SCREAMING_SNAKE_CASE)




"""simple docstring"""






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




	'''simple docstring'''





	SCREAMING_SNAKE_CASE					   =			'hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline'

	def 							_SCREAMING_SNAKE_CASE     (  self:	int ,    _SCREAMING_SNAKE_CASE:	Any=0)       -> Union[str, Any]:

				"""simple docstring"""

				__lowerCAmelCase   :						str				= np.random.RandomState(_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase   :						Optional[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 							_SCREAMING_SNAKE_CASE     (  self:	Optional[int])       -> Dict:

				"""simple docstring"""

				__lowerCAmelCase   :						Union[str, Any]				= OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint ,    provider="CPUExecutionProvider")
				pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase   :						Tuple				= self.get_dummy_inputs()
				__lowerCAmelCase   :						Optional[Any]				= pipe(**_SCREAMING_SNAKE_CASE).images
				__lowerCAmelCase   :						Union[str, Any]				= image[0, -3:, -3:, -1]

				assert image.shape == (1, 128, 128, 3)
				__lowerCAmelCase   :						List[str]				= np.array([0.6_5072, 0.5_8492, 0.4_8219, 0.5_5521, 0.5_3180, 0.5_5939, 0.5_0697, 0.3_9800, 0.4_6455])

				assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2

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

				"""simple docstring"""

				__lowerCAmelCase   :						List[Any]				= OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint ,    provider="CPUExecutionProvider")
				__lowerCAmelCase   :						Dict				= PNDMScheduler.from_config(pipe.scheduler.config ,    skip_prk_steps=_SCREAMING_SNAKE_CASE)
				pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase   :						Optional[int]				= self.get_dummy_inputs()
				__lowerCAmelCase   :						str				= pipe(**_SCREAMING_SNAKE_CASE).images
				__lowerCAmelCase   :						int				= image[0, -3:, -3:, -1]

				assert image.shape == (1, 128, 128, 3)
				__lowerCAmelCase   :						str				= np.array([0.6_5863, 0.5_9425, 0.4_9326, 0.5_6313, 0.5_3875, 0.5_6627, 0.5_1065, 0.3_9777, 0.4_6330])

				assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2

	def 							_SCREAMING_SNAKE_CASE     (  self:	str)       -> Any:

				"""simple docstring"""

				__lowerCAmelCase   :						List[str]				= OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint ,    provider="CPUExecutionProvider")
				__lowerCAmelCase   :						Optional[Any]				= LMSDiscreteScheduler.from_config(pipe.scheduler.config)
				pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase   :						str				= self.get_dummy_inputs()
				__lowerCAmelCase   :						Tuple				= pipe(**_SCREAMING_SNAKE_CASE).images
				__lowerCAmelCase   :						Any				= image[0, -3:, -3:, -1]

				assert image.shape == (1, 128, 128, 3)
				__lowerCAmelCase   :						Any				= np.array([0.5_3755, 0.6_0786, 0.4_7402, 0.4_9488, 0.5_1869, 0.4_9819, 0.4_7985, 0.3_8957, 0.4_4279])

				assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2

	def 							_SCREAMING_SNAKE_CASE     (  self:	List[Any])       -> Dict:

				"""simple docstring"""

				__lowerCAmelCase   :						Optional[Any]				= OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint ,    provider="CPUExecutionProvider")
				__lowerCAmelCase   :						Dict				= EulerDiscreteScheduler.from_config(pipe.scheduler.config)
				pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

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

				assert image.shape == (1, 128, 128, 3)
				__lowerCAmelCase   :						Tuple				= np.array([0.5_3755, 0.6_0786, 0.4_7402, 0.4_9488, 0.5_1869, 0.4_9819, 0.4_7985, 0.3_8957, 0.4_4279])

				assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2

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

				"""simple docstring"""

				__lowerCAmelCase   :						Dict				= OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint ,    provider="CPUExecutionProvider")
				__lowerCAmelCase   :						int				= EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
				pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

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

				assert image.shape == (1, 128, 128, 3)
				__lowerCAmelCase   :						List[Any]				= np.array([0.5_3817, 0.6_0812, 0.4_7384, 0.4_9530, 0.5_1894, 0.4_9814, 0.4_7984, 0.3_8958, 0.4_4271])

				assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2

	def 							_SCREAMING_SNAKE_CASE     (  self:	Union[str, Any])       -> Union[str, Any]:

				"""simple docstring"""

				__lowerCAmelCase   :						Optional[int]				= OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint ,    provider="CPUExecutionProvider")
				__lowerCAmelCase   :						Any				= DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
				pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase   :						List[Any]				= self.get_dummy_inputs()
				__lowerCAmelCase   :						List[Any]				= pipe(**_SCREAMING_SNAKE_CASE).images
				__lowerCAmelCase   :						Dict				= image[0, -3:, -3:, -1]

				assert image.shape == (1, 128, 128, 3)
				__lowerCAmelCase   :						Optional[Any]				= np.array([0.5_3895, 0.6_0808, 0.4_7933, 0.4_9608, 0.5_1886, 0.4_9950, 0.4_8053, 0.3_8957, 0.4_4200])

				assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2

	def 							_SCREAMING_SNAKE_CASE     (  self:	Any)       -> str:

				"""simple docstring"""

				__lowerCAmelCase   :						List[str]				= OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint ,    provider="CPUExecutionProvider")
				pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase   :						str				= self.get_dummy_inputs()
				__lowerCAmelCase   :						List[str]				= 3 * [inputs["prompt"]]

				# forward
				__lowerCAmelCase   :						Optional[Any]				= pipe(**_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase   :						List[Any]				= output.images[0, -3:, -3:, -1]

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

				__lowerCAmelCase   :						Union[str, Any]				= pipe.tokenizer(
				    _SCREAMING_SNAKE_CASE ,    padding="max_length" ,    max_length=pipe.tokenizer.model_max_length ,    truncation=_SCREAMING_SNAKE_CASE ,    return_tensors="np" ,    )
				__lowerCAmelCase   :						Dict				= text_inputs["input_ids"]

				__lowerCAmelCase   :						str				= pipe.text_encoder(input_ids=text_inputs.astype(np.intaa))[0]

				__lowerCAmelCase   :						Union[str, Any]				= prompt_embeds

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

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







	def 							_SCREAMING_SNAKE_CASE     (  self:	Any)       -> int:

				"""simple docstring"""

				__lowerCAmelCase   :						Dict				= OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint ,    provider="CPUExecutionProvider")
				pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase   :						Any				= self.get_dummy_inputs()
				__lowerCAmelCase   :						Optional[int]				= 3 * ["this is a negative prompt"]
				__lowerCAmelCase   :						Union[str, Any]				= negative_prompt
				__lowerCAmelCase   :						Union[str, Any]				= 3 * [inputs["prompt"]]

				# forward
				__lowerCAmelCase   :						List[Any]				= pipe(**_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase   :						List[Any]				= output.images[0, -3:, -3:, -1]

				__lowerCAmelCase   :						Any				= self.get_dummy_inputs()
				__lowerCAmelCase   :						List[Any]				= 3 * [inputs.pop("prompt")]

				__lowerCAmelCase   :						Dict				= []
				for p in [prompt, negative_prompt]:
							__lowerCAmelCase   :						Optional[Any]				= pipe.tokenizer(
							    _SCREAMING_SNAKE_CASE ,    padding="max_length" ,    max_length=pipe.tokenizer.model_max_length ,    truncation=_SCREAMING_SNAKE_CASE ,    return_tensors="np" ,    )
							__lowerCAmelCase   :						Any				= text_inputs["input_ids"]

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

				__lowerCAmelCase		,			__lowerCAmelCase   :						List[str]				= embeds

				# forward
				__lowerCAmelCase   :						int				= pipe(**_SCREAMING_SNAKE_CASE)
				__lowerCAmelCase   :						Union[str, Any]				= 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     A__     (						unittest.TestCase							):




	'''simple docstring'''





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

				"""simple docstring"""

				return (
				    "CUDAExecutionProvider",
				    {
				        "gpu_mem_limit": "15000000000",  # 15GB
				        "arena_extend_strategy": "kSameAsRequested",
				    },
				)

	@property
	def 							_SCREAMING_SNAKE_CASE     (  self:	Union[str, Any])       -> Union[str, Any]:

				"""simple docstring"""

				__lowerCAmelCase   :						str				= ort.SessionOptions()
				__lowerCAmelCase   :						List[str]				= False
				return options

	def 							_SCREAMING_SNAKE_CASE     (  self:	Tuple)       -> Union[str, Any]:

				"""simple docstring"""

				__lowerCAmelCase   :						Any				= OnnxStableDiffusionPipeline.from_pretrained(
				    "CompVis/stable-diffusion-v1-4" ,    revision="onnx" ,    safety_checker=_SCREAMING_SNAKE_CASE ,    feature_extractor=_SCREAMING_SNAKE_CASE ,    provider=self.gpu_provider ,    sess_options=self.gpu_options ,    )
				sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

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

				__lowerCAmelCase   :						Any				= image[0, -3:, -3:, -1]

				assert image.shape == (1, 512, 512, 3)
				__lowerCAmelCase   :						Dict				= np.array([0.0452, 0.0390, 0.0087, 0.0350, 0.0617, 0.0364, 0.0544, 0.0523, 0.0720])

				assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3

	def 							_SCREAMING_SNAKE_CASE     (  self:	str)       -> Union[str, Any]:

				"""simple docstring"""

				__lowerCAmelCase   :						Tuple				= DDIMScheduler.from_pretrained(
				    "runwayml/stable-diffusion-v1-5" ,    subfolder="scheduler" ,    revision="onnx")
				__lowerCAmelCase   :						List[str]				= OnnxStableDiffusionPipeline.from_pretrained(
				    "runwayml/stable-diffusion-v1-5" ,    revision="onnx" ,    scheduler=_SCREAMING_SNAKE_CASE ,    safety_checker=_SCREAMING_SNAKE_CASE ,    feature_extractor=_SCREAMING_SNAKE_CASE ,    provider=self.gpu_provider ,    sess_options=self.gpu_options ,    )
				sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase   :						Tuple				= "open neural network exchange"
				__lowerCAmelCase   :						Union[str, Any]				= np.random.RandomState(0)
				__lowerCAmelCase   :						List[str]				= sd_pipe([prompt] ,    guidance_scale=7.5 ,    num_inference_steps=10 ,    generator=_SCREAMING_SNAKE_CASE ,    output_type="np")
				__lowerCAmelCase   :						Tuple				= output.images
				__lowerCAmelCase   :						Union[str, Any]				= image[0, -3:, -3:, -1]

				assert image.shape == (1, 512, 512, 3)
				__lowerCAmelCase   :						Optional[Any]				= np.array([0.2867, 0.1974, 0.1481, 0.7294, 0.7251, 0.6667, 0.4194, 0.5642, 0.6486])

				assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3

	def 							_SCREAMING_SNAKE_CASE     (  self:	Optional[int])       -> str:

				"""simple docstring"""

				__lowerCAmelCase   :						Tuple				= LMSDiscreteScheduler.from_pretrained(
				    "runwayml/stable-diffusion-v1-5" ,    subfolder="scheduler" ,    revision="onnx")
				__lowerCAmelCase   :						Tuple				= OnnxStableDiffusionPipeline.from_pretrained(
				    "runwayml/stable-diffusion-v1-5" ,    revision="onnx" ,    scheduler=_SCREAMING_SNAKE_CASE ,    safety_checker=_SCREAMING_SNAKE_CASE ,    feature_extractor=_SCREAMING_SNAKE_CASE ,    provider=self.gpu_provider ,    sess_options=self.gpu_options ,    )
				sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

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

				assert image.shape == (1, 512, 512, 3)
				__lowerCAmelCase   :						List[Any]				= np.array([0.2306, 0.1959, 0.1593, 0.6549, 0.6394, 0.5408, 0.5065, 0.6010, 0.6161])

				assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3

	def 							_SCREAMING_SNAKE_CASE     (  self:	str)       -> Optional[int]:

				"""simple docstring"""

				__lowerCAmelCase   :						str				= 0

				def test_callback_fn(_SCREAMING_SNAKE_CASE:	int ,    _SCREAMING_SNAKE_CASE:	int ,    _SCREAMING_SNAKE_CASE:	np.ndarray) -> None:
							__lowerCAmelCase   :						Optional[int]				= True
							nonlocal number_of_steps
							number_of_steps += 1
							if step == 0:
										assert latents.shape == (1, 4, 64, 64)
										__lowerCAmelCase   :						Optional[int]				= latents[0, -3:, -3:, -1]
										__lowerCAmelCase   :						List[str]				= np.array(
										    [-0.6772, -0.3835, -1.2456, 0.1905, -1.0974, 0.6967, -1.9353, 0.0178, 1.0167])

										assert np.abs(latents_slice.flatten() - expected_slice).max() < 1e-3
							elif step == 5:
										assert latents.shape == (1, 4, 64, 64)
										__lowerCAmelCase   :						Tuple				= latents[0, -3:, -3:, -1]
										__lowerCAmelCase   :						Any				= np.array(
										    [-0.3351, 0.2241, -0.1837, -0.2325, -0.6577, 0.3393, -0.0241, 0.5899, 1.3875])

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

				__lowerCAmelCase   :						Dict				= False

				__lowerCAmelCase   :						Dict				= OnnxStableDiffusionPipeline.from_pretrained(
				    "runwayml/stable-diffusion-v1-5" ,    revision="onnx" ,    safety_checker=_SCREAMING_SNAKE_CASE ,    feature_extractor=_SCREAMING_SNAKE_CASE ,    provider=self.gpu_provider ,    sess_options=self.gpu_options ,    )
				pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE)

				__lowerCAmelCase   :						Dict				= "Andromeda galaxy in a bottle"

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







	def 							_SCREAMING_SNAKE_CASE     (  self:	str)       -> Tuple:

				"""simple docstring"""

				__lowerCAmelCase   :						Tuple				= OnnxStableDiffusionPipeline.from_pretrained(
				    "runwayml/stable-diffusion-v1-5" ,    revision="onnx" ,    safety_checker=_SCREAMING_SNAKE_CASE ,    feature_extractor=_SCREAMING_SNAKE_CASE ,    provider=self.gpu_provider ,    sess_options=self.gpu_options ,    )
				assert isinstance(_SCREAMING_SNAKE_CASE ,    _SCREAMING_SNAKE_CASE)
				assert pipe.safety_checker is None

				__lowerCAmelCase   :						Optional[Any]				= 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(_SCREAMING_SNAKE_CASE)
							__lowerCAmelCase   :						Tuple				= OnnxStableDiffusionPipeline.from_pretrained(_SCREAMING_SNAKE_CASE)

				# sanity check that the pipeline still works
				assert pipe.safety_checker is None
				__lowerCAmelCase   :						Optional[Any]				= pipe("example prompt" ,    num_inference_steps=2).images[0]
				assert image is not None