






import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
						import torch

						from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel

						if is_vision_available():
												from transformers import MaskFormerImageProcessor

if is_vision_available():
						from PIL import Image


class        __UpperCamelCase    :







	def __init__(  self      :							List[Any]       ,				_lowerCAmelCase      :							Dict       ,				_lowerCAmelCase      :							List[str]=2       ,				_lowerCAmelCase      :							List[Any]=True       ,				_lowerCAmelCase      :							Union[str, Any]=False       ,				_lowerCAmelCase      :							int=10       ,				_lowerCAmelCase      :							Tuple=3       ,				_lowerCAmelCase      :							Any=32 * 4       ,				_lowerCAmelCase      :							str=32 * 6       ,				_lowerCAmelCase      :							str=4       ,				_lowerCAmelCase      :							Union[str, Any]=32       ,				)		-> Any:
		"""simple docstring"""







		__lowercase             =  parent
		__lowercase             =  batch_size
		__lowercase             =  is_training
		__lowercase             =  use_auxiliary_loss
		__lowercase             =  num_queries
		__lowercase             =  num_channels
		__lowercase             =  min_size
		__lowercase             =  max_size
		__lowercase             =  num_labels
		__lowercase             =  mask_feature_size







	def  _a   (  self      :							int			)		-> Tuple:
		"""simple docstring"""







		__lowercase             =  floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]			).to(
		    _lowerCAmelCase			)

		__lowercase             =  torch.ones([self.batch_size, self.min_size, self.max_size]       ,				device=_lowerCAmelCase			)

		__lowercase             =  (
		    torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size]       ,				device=_lowerCAmelCase			) > 0.5
		).float()
		__lowercase             =  (torch.rand((self.batch_size, self.num_labels)       ,				device=_lowerCAmelCase			) > 0.5).long()

		__lowercase             =  self.get_config()
		return config, pixel_values, pixel_mask, mask_labels, class_labels







	def  _a   (  self      :							Tuple			)		-> Tuple:
		"""simple docstring"""







		return MaskFormerConfig.from_backbone_and_decoder_configs(
		    backbone_config=SwinConfig(
		        depths=[1, 1, 1, 1]       ,				)       ,				decoder_config=DetrConfig(
		        decoder_ffn_dim=128       ,				num_queries=self.num_queries       ,				decoder_attention_heads=2       ,				d_model=self.mask_feature_size       ,				)       ,				mask_feature_size=self.mask_feature_size       ,				fpn_feature_size=self.mask_feature_size       ,				num_channels=self.num_channels       ,				num_labels=self.num_labels       ,				)







	def  _a   (  self      :							Tuple			)		-> int:
		"""simple docstring"""







		__lowercase       ,						__lowercase       ,						__lowercase       ,						__lowercase       ,						__lowercase             =  self.prepare_config_and_inputs()
		__lowercase             =  {"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask}
		return config, inputs_dict







	def  _a   (  self      :							List[Any]       ,				_lowerCAmelCase      :							int       ,				_lowerCAmelCase      :							Dict			)		-> int:
		"""simple docstring"""







		__lowercase             =  output.encoder_hidden_states
		__lowercase             =  output.pixel_decoder_hidden_states
		__lowercase             =  output.transformer_decoder_hidden_states

		self.parent.assertTrue(len(_lowerCAmelCase			)       ,				len(config.backbone_config.depths			)			)
		self.parent.assertTrue(len(_lowerCAmelCase			)       ,				len(config.backbone_config.depths			)			)
		self.parent.assertTrue(len(_lowerCAmelCase			)       ,				config.decoder_config.decoder_layers			)







	def  _a   (  self      :							Optional[Any]       ,				_lowerCAmelCase      :							Optional[Any]       ,				_lowerCAmelCase      :							Dict       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							List[Any]=False			)		-> Tuple:
		"""simple docstring"""







		with torch.no_grad():
			__lowercase             =  MaskFormerModel(config=_lowerCAmelCase			)
			model.to(_lowerCAmelCase			)
			model.eval()

			__lowercase             =  model(pixel_values=_lowerCAmelCase       ,				pixel_mask=_lowerCAmelCase			)
			__lowercase             =  model(_lowerCAmelCase       ,				output_hidden_states=_lowerCAmelCase			)
		# the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
		# encoder and pixel decoder
		self.parent.assertEqual(
		    output.transformer_decoder_last_hidden_state.shape       ,				(self.batch_size, self.num_queries, self.mask_feature_size)       ,				)
		# let's ensure the other two hidden state exists
		self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None			)
		self.parent.assertTrue(output.encoder_last_hidden_state is not None			)

		if output_hidden_states:
			self.check_output_hidden_state(_lowerCAmelCase       ,				_lowerCAmelCase			)







	def  _a   (  self      :							Optional[Any]       ,				_lowerCAmelCase      :							int       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							int       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							int			)		-> int:
		"""simple docstring"""







		__lowercase             =  MaskFormerForInstanceSegmentation(config=_lowerCAmelCase			)
		model.to(_lowerCAmelCase			)
		model.eval()

		def comm_check_on_output(_lowerCAmelCase      :							List[Any]			):
			# let's still check that all the required stuff is there
			self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None			)
			self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None			)
			self.parent.assertTrue(result.encoder_last_hidden_state is not None			)
			# okay, now we need to check the logits shape
			# due to the encoder compression, masks have a //4 spatial size
			self.parent.assertEqual(
			    result.masks_queries_logits.shape       ,				(self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4)       ,				)
			# + 1 for null class
			self.parent.assertEqual(
			    result.class_queries_logits.shape       ,				(self.batch_size, self.num_queries, self.num_labels + 1)			)

		with torch.no_grad():
			__lowercase             =  model(pixel_values=_lowerCAmelCase       ,				pixel_mask=_lowerCAmelCase			)
			__lowercase             =  model(_lowerCAmelCase			)

			comm_check_on_output(_lowerCAmelCase			)

			__lowercase             =  model(
			    pixel_values=_lowerCAmelCase       ,				pixel_mask=_lowerCAmelCase       ,				mask_labels=_lowerCAmelCase       ,				class_labels=_lowerCAmelCase			)

		comm_check_on_output(_lowerCAmelCase			)

		self.parent.assertTrue(result.loss is not None			)
		self.parent.assertEqual(result.loss.shape       ,				torch.Size([1]			)			)


@require_torch
class        __UpperCamelCase    (     _lowerCAmelCase   ,			_lowerCAmelCase   ,			unittest.TestCase   ):
	__snake_case	:str   =       (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
	__snake_case	:Tuple   =       (
	    {'feature-extraction': MaskFormerModel, 'image-segmentation': MaskFormerForInstanceSegmentation}
	    if is_torch_available()
	    else {}
	)

	__snake_case	:Tuple   =       False
	__snake_case	:List[str]   =       False
	__snake_case	:List[str]   =       False
	__snake_case	:List[str]   =       False







	def  _a   (  self      :							Dict			)		-> Dict:
		"""simple docstring"""







		__lowercase             =  MaskFormerModelTester(self			)
		__lowercase             =  ConfigTester(self       ,				config_class=_lowerCAmelCase       ,				has_text_modality=_lowerCAmelCase			)







	def  _a   (  self      :							Tuple			)		-> Optional[Any]:
		"""simple docstring"""







		self.config_tester.run_common_tests()







	def  _a   (  self      :							str			)		-> Optional[Any]:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.model_tester.prepare_config_and_inputs_for_common()
		self.model_tester.create_and_check_maskformer_model(_lowerCAmelCase       ,				**_lowerCAmelCase       ,				output_hidden_states=_lowerCAmelCase			)







	def  _a   (  self      :							List[Any]			)		-> Union[str, Any]:
		"""simple docstring"""







		__lowercase             =  self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*_lowerCAmelCase			)







	@unittest.skip(reason="""MaskFormer does not use inputs_embeds"""			)
	def  _a   (  self      :							List[str]			)		-> Union[str, Any]:
		"""simple docstring"""







		pass







	@unittest.skip(reason="""MaskFormer does not have a get_input_embeddings method"""			)
	def  _a   (  self      :							List[str]			)		-> Dict:
		"""simple docstring"""







		pass







	@unittest.skip(reason="""MaskFormer is not a generative model"""			)
	def  _a   (  self      :							Optional[int]			)		-> Optional[int]:
		"""simple docstring"""







		pass







	@unittest.skip(reason="""MaskFormer does not use token embeddings"""			)
	def  _a   (  self      :							Union[str, Any]			)		-> List[str]:
		"""simple docstring"""







		pass







	@require_torch_multi_gpu
	@unittest.skip(
	    reason="""MaskFormer has some layers using `add_module` which doesn't work well with `nn.DataParallel`"""			)
	def  _a   (  self      :							Any			)		-> List[Any]:
		"""simple docstring"""







		pass







	@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""			)
	def  _a   (  self      :							Optional[Any]			)		-> Any:
		"""simple docstring"""







		pass







	def  _a   (  self      :							int			)		-> str:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.model_tester.prepare_config_and_inputs_for_common()

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

			__lowercase             =  ["""pixel_values"""]
			self.assertListEqual(arg_names[:1]       ,				_lowerCAmelCase			)







	@slow
	def  _a   (  self      :							Any			)		-> Any:
		"""simple docstring"""







		for model_name in ["facebook/maskformer-swin-small-coco"]:
			__lowercase             =  MaskFormerModel.from_pretrained(_lowerCAmelCase			)
			self.assertIsNotNone(_lowerCAmelCase			)







	def  _a   (  self      :							List[str]			)		-> Union[str, Any]:
		"""simple docstring"""







		__lowercase             =  (self.model_tester.min_size,) * 2
		__lowercase             =  {
		    """pixel_values""": torch.randn((2, 3, *size)       ,				device=_lowerCAmelCase			),
		    """mask_labels""": torch.randn((2, 10, *size)       ,				device=_lowerCAmelCase			),
		    """class_labels""": torch.zeros(2       ,				10       ,				device=_lowerCAmelCase			).long(),
		}

		__lowercase             =  MaskFormerForInstanceSegmentation(MaskFormerConfig()			).to(_lowerCAmelCase			)
		__lowercase             =  model(**_lowerCAmelCase			)
		self.assertTrue(outputs.loss is not None			)







	def  _a   (  self      :							Optional[Any]			)		-> str:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.model_tester.prepare_config_and_inputs_for_common()
		self.model_tester.create_and_check_maskformer_model(_lowerCAmelCase       ,				**_lowerCAmelCase       ,				output_hidden_states=_lowerCAmelCase			)







	def  _a   (  self      :							Union[str, Any]			)		-> Any:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.model_tester.prepare_config_and_inputs_for_common()

		for model_class in self.all_model_classes:
			__lowercase             =  model_class(_lowerCAmelCase			).to(_lowerCAmelCase			)
			__lowercase             =  model(**_lowerCAmelCase       ,				output_attentions=_lowerCAmelCase			)
			self.assertTrue(outputs.attentions is not None			)







	def  _a   (  self      :							Dict			)		-> Dict:
		"""simple docstring"""







		if not self.model_tester.is_training:
			return
		# only MaskFormerForInstanceSegmentation has the loss
		__lowercase             =  self.all_model_classes[1]
		__lowercase       ,						__lowercase       ,						__lowercase       ,						__lowercase       ,						__lowercase             =  self.model_tester.prepare_config_and_inputs()

		__lowercase             =  model_class(_lowerCAmelCase			)
		model.to(_lowerCAmelCase			)
		model.train()

		__lowercase             =  model(_lowerCAmelCase       ,				mask_labels=_lowerCAmelCase       ,				class_labels=_lowerCAmelCase			).loss
		loss.backward()







	def  _a   (  self      :							Union[str, Any]			)		-> Union[str, Any]:
		"""simple docstring"""







		__lowercase             =  self.all_model_classes[1]
		__lowercase       ,						__lowercase       ,						__lowercase       ,						__lowercase       ,						__lowercase             =  self.model_tester.prepare_config_and_inputs()
		__lowercase             =  True
		__lowercase             =  True

		__lowercase             =  model_class(_lowerCAmelCase			)
		model.to(_lowerCAmelCase			)
		model.train()

		__lowercase             =  model(_lowerCAmelCase       ,				mask_labels=_lowerCAmelCase       ,				class_labels=_lowerCAmelCase			)

		__lowercase             =  outputs.encoder_hidden_states[0]
		encoder_hidden_states.retain_grad()

		__lowercase             =  outputs.pixel_decoder_hidden_states[0]
		pixel_decoder_hidden_states.retain_grad()
		# we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
		__lowercase             =  outputs.transformer_decoder_hidden_states[0]
		transformer_decoder_hidden_states.retain_grad()

		__lowercase             =  outputs.attentions[0]
		attentions.retain_grad()

		outputs.loss.backward(retain_graph=_lowerCAmelCase			)

		self.assertIsNotNone(encoder_hidden_states.grad			)
		self.assertIsNotNone(pixel_decoder_hidden_states.grad			)
		self.assertIsNotNone(transformer_decoder_hidden_states.grad			)
		self.assertIsNotNone(attentions.grad			)

__UpperCamelCase      :      Optional[Any]     						=						1e-4





def 				snake_case  (     ):




	'''simple docstring'''







	__lowercase             =  Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""					)
	return image




@require_vision
@slow
class        __UpperCamelCase    (     unittest.TestCase   ):







	@cached_property
	def  _a   (  self      :							Dict			)		-> int:
		"""simple docstring"""







		return (
		    MaskFormerImageProcessor.from_pretrained("""facebook/maskformer-swin-small-coco"""			)
		    if is_vision_available()
		    else None
		)







	def  _a   (  self      :							str			)		-> str:
		"""simple docstring"""







		__lowercase             =  MaskFormerModel.from_pretrained("""facebook/maskformer-swin-small-coco"""			).to(_lowerCAmelCase			)
		__lowercase             =  self.default_image_processor
		__lowercase             =  prepare_img()
		__lowercase             =  image_processor(_lowerCAmelCase       ,				return_tensors="""pt"""			).to(_lowerCAmelCase			)
		__lowercase             =  inputs["""pixel_values"""].shape
		# check size is divisible by 32
		self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0			)
		# check size
		self.assertEqual(_lowerCAmelCase       ,				(1, 3, 800, 1088)			)

		with torch.no_grad():
			__lowercase             =  model(**_lowerCAmelCase			)

		__lowercase             =  torch.tensor(
		    [[-0.0_482, 0.9_228, 0.4_951], [-0.2_547, 0.8_017, 0.8_527], [-0.0_069, 0.3_385, -0.0_089]]			).to(_lowerCAmelCase			)
		self.assertTrue(
		    torch.allclose(
		        outputs.encoder_last_hidden_state[0, 0, :3, :3]       ,				_lowerCAmelCase       ,				atol=_lowerCAmelCase			)			)

		__lowercase             =  torch.tensor(
		    [[-0.8_422, -0.8_434, -0.9_718], [-1.0_144, -0.5_565, -0.4_195], [-1.0_038, -0.4_484, -0.1_961]]			).to(_lowerCAmelCase			)
		self.assertTrue(
		    torch.allclose(
		        outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3]       ,				_lowerCAmelCase       ,				atol=_lowerCAmelCase			)			)

		__lowercase             =  torch.tensor(
		    [[0.2_852, -0.0_159, 0.9_735], [0.6_254, 0.1_858, 0.8_529], [-0.0_680, -0.4_116, 1.8_413]]			).to(_lowerCAmelCase			)
		self.assertTrue(
		    torch.allclose(
		        outputs.transformer_decoder_last_hidden_state[0, :3, :3]       ,				_lowerCAmelCase       ,				atol=_lowerCAmelCase			)			)







	def  _a   (  self      :							int			)		-> List[str]:
		"""simple docstring"""







		__lowercase             =  (
		    MaskFormerForInstanceSegmentation.from_pretrained("""facebook/maskformer-swin-small-coco"""			)
		    .to(_lowerCAmelCase			)
		    .eval()
		)
		__lowercase             =  self.default_image_processor
		__lowercase             =  prepare_img()
		__lowercase             =  image_processor(_lowerCAmelCase       ,				return_tensors="""pt"""			).to(_lowerCAmelCase			)
		__lowercase             =  inputs["""pixel_values"""].shape
		# check size is divisible by 32
		self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0			)
		# check size
		self.assertEqual(_lowerCAmelCase       ,				(1, 3, 800, 1088)			)

		with torch.no_grad():
			__lowercase             =  model(**_lowerCAmelCase			)
		# masks_queries_logits
		__lowercase             =  outputs.masks_queries_logits
		self.assertEqual(
		    masks_queries_logits.shape       ,				(1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)       ,				)
		__lowercase             =  [
		    [-1.3_737_124, -1.7_724_937, -1.9_364_233],
		    [-1.5_977_281, -1.9_867_939, -2.1_523_695],
		    [-1.5_795_398, -1.9_269_832, -2.093_942],
		]
		__lowercase             =  torch.tensor(_lowerCAmelCase			).to(_lowerCAmelCase			)
		self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]       ,				_lowerCAmelCase       ,				atol=_lowerCAmelCase			)			)
		# class_queries_logits
		__lowercase             =  outputs.class_queries_logits
		self.assertEqual(
		    class_queries_logits.shape       ,				(1, model.config.decoder_config.num_queries, model.config.num_labels + 1)			)
		__lowercase             =  torch.tensor(
		    [
		        [1.6512e00, -5.2572e00, -3.3519e00],
		        [3.6169e-02, -5.9025e00, -2.9313e00],
		        [1.0766e-04, -7.7630e00, -5.1263e00],
		    ]			).to(_lowerCAmelCase			)
		self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]       ,				_lowerCAmelCase       ,				atol=_lowerCAmelCase			)			)







	def  _a   (  self      :							Union[str, Any]			)		-> Optional[int]:
		"""simple docstring"""







		__lowercase             =  (
		    MaskFormerForInstanceSegmentation.from_pretrained("""facebook/maskformer-resnet101-coco-stuff"""			)
		    .to(_lowerCAmelCase			)
		    .eval()
		)
		__lowercase             =  self.default_image_processor
		__lowercase             =  prepare_img()
		__lowercase             =  image_processor(_lowerCAmelCase       ,				return_tensors="""pt"""			).to(_lowerCAmelCase			)
		__lowercase             =  inputs["""pixel_values"""].shape
		# check size is divisible by 32
		self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0			)
		# check size
		self.assertEqual(_lowerCAmelCase       ,				(1, 3, 800, 1088)			)

		with torch.no_grad():
			__lowercase             =  model(**_lowerCAmelCase			)
		# masks_queries_logits
		__lowercase             =  outputs.masks_queries_logits
		self.assertEqual(
		    masks_queries_logits.shape       ,				(1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)       ,				)
		__lowercase             =  [[-0.9_046, -2.6_366, -4.6_062], [-3.4_179, -5.7_890, -8.8_057], [-4.9_179, -7.6_560, -10.7_711]]
		__lowercase             =  torch.tensor(_lowerCAmelCase			).to(_lowerCAmelCase			)
		self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3]       ,				_lowerCAmelCase       ,				atol=_lowerCAmelCase			)			)
		# class_queries_logits
		__lowercase             =  outputs.class_queries_logits
		self.assertEqual(
		    class_queries_logits.shape       ,				(1, model.config.decoder_config.num_queries, model.config.num_labels + 1)			)
		__lowercase             =  torch.tensor(
		    [[4.7_188, -3.2_585, -2.8_857], [6.6_871, -2.9_181, -1.2_487], [7.2_449, -2.2_764, -2.1_874]]			).to(_lowerCAmelCase			)
		self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3]       ,				_lowerCAmelCase       ,				atol=_lowerCAmelCase			)			)







	def  _a   (  self      :							List[Any]			)		-> Optional[Any]:
		"""simple docstring"""







		__lowercase             =  (
		    MaskFormerForInstanceSegmentation.from_pretrained("""facebook/maskformer-swin-small-coco"""			)
		    .to(_lowerCAmelCase			)
		    .eval()
		)
		__lowercase             =  self.default_image_processor

		__lowercase             =  image_processor(
		    [np.zeros((3, 800, 1333)			), np.zeros((3, 800, 1333)			)]       ,				segmentation_maps=[np.zeros((384, 384)			).astype(np.floataa			), np.zeros((384, 384)			).astype(np.floataa			)]       ,				return_tensors="""pt"""       ,				)

		__lowercase             =  inputs["""pixel_values"""].to(_lowerCAmelCase			)
		__lowercase             =  [el.to(_lowerCAmelCase			) for el in inputs["""mask_labels"""]]
		__lowercase             =  [el.to(_lowerCAmelCase			) for el in inputs["""class_labels"""]]

		with torch.no_grad():
			__lowercase             =  model(**_lowerCAmelCase			)

		self.assertTrue(outputs.loss is not None			)









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        __UpperCamelCase    (     _lowerCAmelCase   ,			unittest.TestCase   ):
	__snake_case	:Union[str, Any]   =       'hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline'







	def  _a   (  self      :							Any       ,				_lowerCAmelCase      :							str=0			)		-> str:
		"""simple docstring"""







		__lowercase             =  np.random.RandomState(_lowerCAmelCase			)
		__lowercase             =  {
		    """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  _a   (  self      :							int			)		-> List[Any]:
		"""simple docstring"""







		__lowercase             =  OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint       ,				provider="""CPUExecutionProvider"""			)
		pipe.set_progress_bar_config(disable=_lowerCAmelCase			)

		__lowercase             =  self.get_dummy_inputs()
		__lowercase             =  pipe(**_lowerCAmelCase			).images
		__lowercase             =  image[0, -3:, -3:, -1]

		assert image.shape == (1, 128, 128, 3)
		__lowercase             =  np.array([0.65_072, 0.58_492, 0.48_219, 0.55_521, 0.53_180, 0.55_939, 0.50_697, 0.39_800, 0.46_455]			)

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







	def  _a   (  self      :							Union[str, Any]			)		-> str:
		"""simple docstring"""







		__lowercase             =  OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint       ,				provider="""CPUExecutionProvider"""			)
		__lowercase             =  PNDMScheduler.from_config(pipe.scheduler.config       ,				skip_prk_steps=_lowerCAmelCase			)
		pipe.set_progress_bar_config(disable=_lowerCAmelCase			)

		__lowercase             =  self.get_dummy_inputs()
		__lowercase             =  pipe(**_lowerCAmelCase			).images
		__lowercase             =  image[0, -3:, -3:, -1]

		assert image.shape == (1, 128, 128, 3)
		__lowercase             =  np.array([0.65_863, 0.59_425, 0.49_326, 0.56_313, 0.53_875, 0.56_627, 0.51_065, 0.39_777, 0.46_330]			)

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







	def  _a   (  self      :							Optional[int]			)		-> Optional[int]:
		"""simple docstring"""







		__lowercase             =  OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint       ,				provider="""CPUExecutionProvider"""			)
		__lowercase             =  LMSDiscreteScheduler.from_config(pipe.scheduler.config			)
		pipe.set_progress_bar_config(disable=_lowerCAmelCase			)

		__lowercase             =  self.get_dummy_inputs()
		__lowercase             =  pipe(**_lowerCAmelCase			).images
		__lowercase             =  image[0, -3:, -3:, -1]

		assert image.shape == (1, 128, 128, 3)
		__lowercase             =  np.array([0.53_755, 0.60_786, 0.47_402, 0.49_488, 0.51_869, 0.49_819, 0.47_985, 0.38_957, 0.44_279]			)

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







	def  _a   (  self      :							Tuple			)		-> int:
		"""simple docstring"""







		__lowercase             =  OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint       ,				provider="""CPUExecutionProvider"""			)
		__lowercase             =  EulerDiscreteScheduler.from_config(pipe.scheduler.config			)
		pipe.set_progress_bar_config(disable=_lowerCAmelCase			)

		__lowercase             =  self.get_dummy_inputs()
		__lowercase             =  pipe(**_lowerCAmelCase			).images
		__lowercase             =  image[0, -3:, -3:, -1]

		assert image.shape == (1, 128, 128, 3)
		__lowercase             =  np.array([0.53_755, 0.60_786, 0.47_402, 0.49_488, 0.51_869, 0.49_819, 0.47_985, 0.38_957, 0.44_279]			)

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







	def  _a   (  self      :							Tuple			)		-> Union[str, Any]:
		"""simple docstring"""







		__lowercase             =  OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint       ,				provider="""CPUExecutionProvider"""			)
		__lowercase             =  EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config			)
		pipe.set_progress_bar_config(disable=_lowerCAmelCase			)

		__lowercase             =  self.get_dummy_inputs()
		__lowercase             =  pipe(**_lowerCAmelCase			).images
		__lowercase             =  image[0, -3:, -3:, -1]

		assert image.shape == (1, 128, 128, 3)
		__lowercase             =  np.array([0.53_817, 0.60_812, 0.47_384, 0.49_530, 0.51_894, 0.49_814, 0.47_984, 0.38_958, 0.44_271]			)

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







	def  _a   (  self      :							Union[str, Any]			)		-> List[str]:
		"""simple docstring"""







		__lowercase             =  OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint       ,				provider="""CPUExecutionProvider"""			)
		__lowercase             =  DPMSolverMultistepScheduler.from_config(pipe.scheduler.config			)
		pipe.set_progress_bar_config(disable=_lowerCAmelCase			)

		__lowercase             =  self.get_dummy_inputs()
		__lowercase             =  pipe(**_lowerCAmelCase			).images
		__lowercase             =  image[0, -3:, -3:, -1]

		assert image.shape == (1, 128, 128, 3)
		__lowercase             =  np.array([0.53_895, 0.60_808, 0.47_933, 0.49_608, 0.51_886, 0.49_950, 0.48_053, 0.38_957, 0.44_200]			)

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







	def  _a   (  self      :							List[str]			)		-> List[str]:
		"""simple docstring"""







		__lowercase             =  OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint       ,				provider="""CPUExecutionProvider"""			)
		pipe.set_progress_bar_config(disable=_lowerCAmelCase			)

		__lowercase             =  self.get_dummy_inputs()
		__lowercase             =  3 * [inputs["""prompt"""]]

		# forward
		__lowercase             =  pipe(**_lowerCAmelCase			)
		__lowercase             =  output.images[0, -3:, -3:, -1]

		__lowercase             =  self.get_dummy_inputs()
		__lowercase             =  3 * [inputs.pop("""prompt"""			)]

		__lowercase             =  pipe.tokenizer(
		    _lowerCAmelCase       ,				padding="""max_length"""       ,				max_length=pipe.tokenizer.model_max_length       ,				truncation=_lowerCAmelCase       ,				return_tensors="""np"""       ,				)
		__lowercase             =  text_inputs["""input_ids"""]

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

		__lowercase             =  prompt_embeds

		# forward
		__lowercase             =  pipe(**_lowerCAmelCase			)
		__lowercase             =  output.images[0, -3:, -3:, -1]

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







	def  _a   (  self      :							int			)		-> str:
		"""simple docstring"""







		__lowercase             =  OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint       ,				provider="""CPUExecutionProvider"""			)
		pipe.set_progress_bar_config(disable=_lowerCAmelCase			)

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

		# forward
		__lowercase             =  pipe(**_lowerCAmelCase			)
		__lowercase             =  output.images[0, -3:, -3:, -1]

		__lowercase             =  self.get_dummy_inputs()
		__lowercase             =  3 * [inputs.pop("""prompt"""			)]

		__lowercase             =  []
		for p in [prompt, negative_prompt]:
			__lowercase             =  pipe.tokenizer(
			    _lowerCAmelCase       ,				padding="""max_length"""       ,				max_length=pipe.tokenizer.model_max_length       ,				truncation=_lowerCAmelCase       ,				return_tensors="""np"""       ,				)
			__lowercase             =  text_inputs["""input_ids"""]

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

		__lowercase       ,						__lowercase             =  embeds

		# forward
		__lowercase             =  pipe(**_lowerCAmelCase			)
		__lowercase             =  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        __UpperCamelCase    (     unittest.TestCase   ):







	@property
	def  _a   (  self      :							Dict			)		-> str:
		"""simple docstring"""







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







	@property
	def  _a   (  self      :							Optional[Any]			)		-> Optional[Any]:
		"""simple docstring"""







		__lowercase             =  ort.SessionOptions()
		__lowercase             =  False
		return options







	def  _a   (  self      :							List[Any]			)		-> Union[str, Any]:
		"""simple docstring"""







		__lowercase             =  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             =  """A painting of a squirrel eating a burger"""
		np.random.seed(0			)
		__lowercase             =  sd_pipe([prompt]       ,				guidance_scale=6.0       ,				num_inference_steps=10       ,				output_type="""np"""			)
		__lowercase             =  output.images

		__lowercase             =  image[0, -3:, -3:, -1]

		assert image.shape == (1, 512, 512, 3)
		__lowercase             =  np.array([0.0_452, 0.0_390, 0.0_087, 0.0_350, 0.0_617, 0.0_364, 0.0_544, 0.0_523, 0.0_720]			)

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







	def  _a   (  self      :							Tuple			)		-> Any:
		"""simple docstring"""







		__lowercase             =  DDIMScheduler.from_pretrained(
		    """runwayml/stable-diffusion-v1-5"""       ,				subfolder="""scheduler"""       ,				revision="""onnx"""			)
		__lowercase             =  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             =  """open neural network exchange"""
		__lowercase             =  np.random.RandomState(0			)
		__lowercase             =  sd_pipe([prompt]       ,				guidance_scale=7.5       ,				num_inference_steps=10       ,				generator=_lowerCAmelCase       ,				output_type="""np"""			)
		__lowercase             =  output.images
		__lowercase             =  image[0, -3:, -3:, -1]

		assert image.shape == (1, 512, 512, 3)
		__lowercase             =  np.array([0.2_867, 0.1_974, 0.1_481, 0.7_294, 0.7_251, 0.6_667, 0.4_194, 0.5_642, 0.6_486]			)

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







	def  _a   (  self      :							Dict			)		-> Dict:
		"""simple docstring"""







		__lowercase             =  LMSDiscreteScheduler.from_pretrained(
		    """runwayml/stable-diffusion-v1-5"""       ,				subfolder="""scheduler"""       ,				revision="""onnx"""			)
		__lowercase             =  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             =  """open neural network exchange"""
		__lowercase             =  np.random.RandomState(0			)
		__lowercase             =  sd_pipe([prompt]       ,				guidance_scale=7.5       ,				num_inference_steps=10       ,				generator=_lowerCAmelCase       ,				output_type="""np"""			)
		__lowercase             =  output.images
		__lowercase             =  image[0, -3:, -3:, -1]

		assert image.shape == (1, 512, 512, 3)
		__lowercase             =  np.array([0.2_306, 0.1_959, 0.1_593, 0.6_549, 0.6_394, 0.5_408, 0.5_065, 0.6_010, 0.6_161]			)

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







	def  _a   (  self      :							str			)		-> List[str]:
		"""simple docstring"""







		__lowercase             =  0

		def test_callback_fn(_lowerCAmelCase      :							int       ,				_lowerCAmelCase      :							int       ,				_lowerCAmelCase      :							np.ndarray			) -> None:
			__lowercase             =  True
			nonlocal number_of_steps
			number_of_steps += 1
			if step == 0:
				assert latents.shape == (1, 4, 64, 64)
				__lowercase             =  latents[0, -3:, -3:, -1]
				__lowercase             =  np.array(
				    [-0.6_772, -0.3_835, -1.2_456, 0.1_905, -1.0_974, 0.6_967, -1.9_353, 0.0_178, 1.0_167]			)

				assert np.abs(latents_slice.flatten() - expected_slice			).max() < 1e-3
			elif step == 5:
				assert latents.shape == (1, 4, 64, 64)
				__lowercase             =  latents[0, -3:, -3:, -1]
				__lowercase             =  np.array(
				    [-0.3_351, 0.2_241, -0.1_837, -0.2_325, -0.6_577, 0.3_393, -0.0_241, 0.5_899, 1.3_875]			)

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

		__lowercase             =  False

		__lowercase             =  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             =  """Andromeda galaxy in a bottle"""

		__lowercase             =  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  _a   (  self      :							Union[str, Any]			)		-> Tuple:
		"""simple docstring"""







		__lowercase             =  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             =  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             =  OnnxStableDiffusionPipeline.from_pretrained(_lowerCAmelCase			)

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

