






import collections
import inspect
import unittest
from typing import Dict, List, Tuple

from transformers import MaskFormerSwinConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, torch_device
from transformers.utils import is_torch_available

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


if is_torch_available():
						import torch
						from torch import nn

						from transformers import MaskFormerSwinBackbone
						from transformers.models.maskformer import MaskFormerSwinModel


class        __UpperCamelCase    :







	def __init__(  self      :							Optional[Any]       ,				_lowerCAmelCase      :							Optional[Any]       ,				_lowerCAmelCase      :							Optional[int]=13       ,				_lowerCAmelCase      :							List[str]=32       ,				_lowerCAmelCase      :							int=2       ,				_lowerCAmelCase      :							Dict=3       ,				_lowerCAmelCase      :							Any=16       ,				_lowerCAmelCase      :							Dict=[1, 2, 1]       ,				_lowerCAmelCase      :							Optional[int]=[2, 2, 4]       ,				_lowerCAmelCase      :							List[str]=2       ,				_lowerCAmelCase      :							Any=2.0       ,				_lowerCAmelCase      :							Optional[Any]=True       ,				_lowerCAmelCase      :							Union[str, Any]=0.0       ,				_lowerCAmelCase      :							Union[str, Any]=0.0       ,				_lowerCAmelCase      :							Any=0.1       ,				_lowerCAmelCase      :							Optional[int]="gelu"       ,				_lowerCAmelCase      :							Optional[int]=False       ,				_lowerCAmelCase      :							Dict=True       ,				_lowerCAmelCase      :							str=0.02       ,				_lowerCAmelCase      :							List[str]=1e-5       ,				_lowerCAmelCase      :							str=True       ,				_lowerCAmelCase      :							List[str]=None       ,				_lowerCAmelCase      :							str=True       ,				_lowerCAmelCase      :							Tuple=10       ,				_lowerCAmelCase      :							str=8       ,				_lowerCAmelCase      :							str=["stage1", "stage2", "stage3"]       ,				_lowerCAmelCase      :							List[str]=[1, 2, 3]       ,				)		-> int:
		"""simple docstring"""







		__lowercase             =  parent
		__lowercase             =  batch_size
		__lowercase             =  image_size
		__lowercase             =  patch_size
		__lowercase             =  num_channels
		__lowercase             =  embed_dim
		__lowercase             =  depths
		__lowercase             =  num_heads
		__lowercase             =  window_size
		__lowercase             =  mlp_ratio
		__lowercase             =  qkv_bias
		__lowercase             =  hidden_dropout_prob
		__lowercase             =  attention_probs_dropout_prob
		__lowercase             =  drop_path_rate
		__lowercase             =  hidden_act
		__lowercase             =  use_absolute_embeddings
		__lowercase             =  patch_norm
		__lowercase             =  layer_norm_eps
		__lowercase             =  initializer_range
		__lowercase             =  is_training
		__lowercase             =  scope
		__lowercase             =  use_labels
		__lowercase             =  type_sequence_label_size
		__lowercase             =  encoder_stride
		__lowercase             =  out_features
		__lowercase             =  out_indices







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







		__lowercase             =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

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

		__lowercase             =  self.get_config()

		return config, pixel_values, labels







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







		return MaskFormerSwinConfig(
		    image_size=self.image_size       ,				patch_size=self.patch_size       ,				num_channels=self.num_channels       ,				embed_dim=self.embed_dim       ,				depths=self.depths       ,				num_heads=self.num_heads       ,				window_size=self.window_size       ,				mlp_ratio=self.mlp_ratio       ,				qkv_bias=self.qkv_bias       ,				hidden_dropout_prob=self.hidden_dropout_prob       ,				attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,				drop_path_rate=self.drop_path_rate       ,				hidden_act=self.hidden_act       ,				use_absolute_embeddings=self.use_absolute_embeddings       ,				path_norm=self.patch_norm       ,				layer_norm_eps=self.layer_norm_eps       ,				initializer_range=self.initializer_range       ,				encoder_stride=self.encoder_stride       ,				out_features=self.out_features       ,				out_indices=self.out_indices       ,				)







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







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

		__lowercase             =  ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths			) - 1))
		__lowercase             =  int(config.embed_dim * 2 ** (len(config.depths			) - 1)			)

		self.parent.assertEqual(result.last_hidden_state.shape       ,				(self.batch_size, expected_seq_len, expected_dim)			)







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







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

		# verify feature maps
		self.parent.assertEqual(len(result.feature_maps			)       ,				len(config.out_features			)			)
		self.parent.assertListEqual(list(result.feature_maps[0].shape			)       ,				[13, 16, 16, 16]			)

		# verify channels
		self.parent.assertEqual(len(model.channels			)       ,				len(config.out_features			)			)
		self.parent.assertListEqual(model.channels       ,				[16, 32, 64]			)

		# verify ValueError
		with self.parent.assertRaises(_lowerCAmelCase			):
			__lowercase             =  ["""stem"""]
			__lowercase             =  MaskFormerSwinBackbone(config=_lowerCAmelCase			)







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







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


@require_torch
class        __UpperCamelCase    (     _lowerCAmelCase   ,			_lowerCAmelCase   ,			unittest.TestCase   ):
	__snake_case	:str   =       (
	    (
	        MaskFormerSwinModel,
	        MaskFormerSwinBackbone,
	    )
	    if is_torch_available()
	    else ()
	)
	__snake_case	:Union[str, Any]   =       {'feature-extraction': MaskFormerSwinModel} if is_torch_available() else {}
	__snake_case	:str   =       False
	__snake_case	:int   =       False
	__snake_case	:Tuple   =       False
	__snake_case	:Tuple   =       False
	__snake_case	:Optional[Any]   =       False







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







		__lowercase             =  MaskFormerSwinModelTester(self			)
		__lowercase             =  ConfigTester(self       ,				config_class=_lowerCAmelCase       ,				embed_dim=37			)







	@require_torch_multi_gpu
	@unittest.skip(
	    reason=(
	        """`MaskFormerSwinModel` outputs `hidden_states_spatial_dimensions` which doesn't work well with"""
	        """ `nn.DataParallel`"""
	    )			)
	def  _a   (  self      :							List[str]			)		-> List[str]:
		"""simple docstring"""







		pass







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







		self.create_and_test_config_common_properties()
		self.config_tester.create_and_test_config_to_json_string()
		self.config_tester.create_and_test_config_to_json_file()
		self.config_tester.create_and_test_config_from_and_save_pretrained()
		self.config_tester.create_and_test_config_with_num_labels()
		self.config_tester.check_config_can_be_init_without_params()
		self.config_tester.check_config_arguments_init()







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







		return







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







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







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







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







	@unittest.skip("""Swin does not use inputs_embeds"""			)
	def  _a   (  self      :							List[str]			)		-> List[str]:
		"""simple docstring"""







		pass







	@unittest.skip("""Swin does not support feedforward chunking"""			)
	def  _a   (  self      :							Tuple			)		-> Any:
		"""simple docstring"""







		pass







	def  _a   (  self      :							Dict			)		-> List[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			)
			self.assertIsInstance(model.get_input_embeddings()       ,				(nn.Module)			)
			__lowercase             =  model.get_output_embeddings()
			self.assertTrue(x is None or isinstance(_lowerCAmelCase       ,				nn.Linear			)			)







	def  _a   (  self      :							Dict			)		-> List[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			)
			__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			)







	@unittest.skip(reason="""MaskFormerSwin is only used as backbone and doesn't support output_attentions"""			)
	def  _a   (  self      :							Tuple			)		-> List[str]:
		"""simple docstring"""







		pass







	@unittest.skip(reason="""MaskFormerSwin is only used as an internal backbone"""			)
	def  _a   (  self      :							Tuple			)		-> List[str]:
		"""simple docstring"""







		pass







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







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

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

		__lowercase             =  outputs.hidden_states

		__lowercase             =  getattr(
		    self.model_tester       ,				"""expected_num_hidden_layers"""       ,				len(self.model_tester.depths			) + 1			)
		self.assertEqual(len(_lowerCAmelCase			)       ,				_lowerCAmelCase			)

		# Swin has a different seq_length
		__lowercase             =  (
		    config.patch_size
		    if isinstance(config.patch_size       ,				collections.abc.Iterable			)
		    else (config.patch_size, config.patch_size)
		)

		__lowercase             =  (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])

		self.assertListEqual(
		    list(hidden_states[0].shape[-2:]			)       ,				[num_patches, self.model_tester.embed_dim]       ,				)







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







		__lowercase       ,						__lowercase             =  self.model_tester.prepare_config_and_inputs_for_common()

		__lowercase             =  (
		    self.model_tester.image_size
		    if isinstance(self.model_tester.image_size       ,				collections.abc.Iterable			)
		    else (self.model_tester.image_size, self.model_tester.image_size)
		)

		for model_class in self.all_model_classes:
			__lowercase             =  True
			self.check_hidden_states_output(_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)

			# check that output_hidden_states also work using config
			del inputs_dict["output_hidden_states"]
			__lowercase             =  True

			self.check_hidden_states_output(_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)







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







		__lowercase       ,						__lowercase             =  self.model_tester.prepare_config_and_inputs_for_common()
		__lowercase             =  3

		__lowercase             =  (
		    self.model_tester.image_size
		    if isinstance(self.model_tester.image_size       ,				collections.abc.Iterable			)
		    else (self.model_tester.image_size, self.model_tester.image_size)
		)
		__lowercase             =  (
		    config.patch_size
		    if isinstance(config.patch_size       ,				collections.abc.Iterable			)
		    else (config.patch_size, config.patch_size)
		)

		__lowercase             =  image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
		__lowercase             =  image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])

		for model_class in self.all_model_classes:
			__lowercase             =  True
			self.check_hidden_states_output(_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				(padded_height, padded_width)			)

			# check that output_hidden_states also work using config
			del inputs_dict["output_hidden_states"]
			__lowercase             =  True
			self.check_hidden_states_output(_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				(padded_height, padded_width)			)







	@unittest.skip(reason="""MaskFormerSwin doesn't have pretrained checkpoints"""			)
	def  _a   (  self      :							Optional[Any]			)		-> Optional[Any]:
		"""simple docstring"""







		pass







	@unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin"""			)
	def  _a   (  self      :							int			)		-> List[str]:
		"""simple docstring"""







		pass







	@unittest.skip(reason="""This will be fixed once MaskFormerSwin is replaced by native Swin"""			)
	def  _a   (  self      :							int			)		-> Tuple:
		"""simple docstring"""







		pass







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







		__lowercase       ,						__lowercase             =  self.model_tester.prepare_config_and_inputs_for_common()

		def set_nan_tensor_to_zero(_lowerCAmelCase      :							Optional[int]			):
			__lowercase             =  0
			return t

		def check_equivalence(_lowerCAmelCase      :							Optional[Any]       ,				_lowerCAmelCase      :							Optional[int]       ,				_lowerCAmelCase      :							int       ,				_lowerCAmelCase      :							int={}			):
			with torch.no_grad():
				__lowercase             =  model(**_lowerCAmelCase       ,				return_dict=_lowerCAmelCase       ,				**_lowerCAmelCase			)
				__lowercase             =  model(**_lowerCAmelCase       ,				return_dict=_lowerCAmelCase       ,				**_lowerCAmelCase			).to_tuple()

				def recursive_check(_lowerCAmelCase      :							List[Any]       ,				_lowerCAmelCase      :							Optional[Any]			):
					if isinstance(_lowerCAmelCase       ,				(List, Tuple)			):
						for tuple_iterable_value, dict_iterable_value in zip(_lowerCAmelCase       ,				_lowerCAmelCase			):
							recursive_check(_lowerCAmelCase       ,				_lowerCAmelCase			)
					elif isinstance(_lowerCAmelCase       ,				_lowerCAmelCase			):
						for tuple_iterable_value, dict_iterable_value in zip(
						    tuple_object.values()       ,				dict_object.values()			):
							recursive_check(_lowerCAmelCase       ,				_lowerCAmelCase			)
					elif tuple_object is None:
						return
					else:
						self.assertTrue(
						    torch.allclose(
						        set_nan_tensor_to_zero(_lowerCAmelCase			)       ,				set_nan_tensor_to_zero(_lowerCAmelCase			)       ,				atol=1e-5			)       ,				msg=(
						        """Tuple and dict output are not equal. Difference:"""
						        F' {torch.max(torch.abs(tuple_object - dict_object			)			)}. Tuple has `nan`:'
						        F' {torch.isnan(_lowerCAmelCase			).any()} and `inf`: {torch.isinf(_lowerCAmelCase			)}. Dict has'
						        F' `nan`: {torch.isnan(_lowerCAmelCase			).any()} and `inf`: {torch.isinf(_lowerCAmelCase			)}.'
						    )       ,				)

				recursive_check(_lowerCAmelCase       ,				_lowerCAmelCase			)

		for model_class in self.all_model_classes:
			__lowercase             =  model_class(_lowerCAmelCase			)
			model.to(_lowerCAmelCase			)
			model.eval()

			__lowercase             =  self._prepare_for_class(_lowerCAmelCase       ,				_lowerCAmelCase			)
			__lowercase             =  self._prepare_for_class(_lowerCAmelCase       ,				_lowerCAmelCase			)
			check_equivalence(_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)

			__lowercase             =  self._prepare_for_class(_lowerCAmelCase       ,				_lowerCAmelCase       ,				return_labels=_lowerCAmelCase			)
			__lowercase             =  self._prepare_for_class(_lowerCAmelCase       ,				_lowerCAmelCase       ,				return_labels=_lowerCAmelCase			)
			check_equivalence(_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)

			__lowercase             =  self._prepare_for_class(_lowerCAmelCase       ,				_lowerCAmelCase			)
			__lowercase             =  self._prepare_for_class(_lowerCAmelCase       ,				_lowerCAmelCase			)
			check_equivalence(_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				{"""output_hidden_states""": True}			)

			__lowercase             =  self._prepare_for_class(_lowerCAmelCase       ,				_lowerCAmelCase       ,				return_labels=_lowerCAmelCase			)
			__lowercase             =  self._prepare_for_class(_lowerCAmelCase       ,				_lowerCAmelCase       ,				return_labels=_lowerCAmelCase			)
			check_equivalence(_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase       ,				{"""output_hidden_states""": True}			)


@require_torch
class        __UpperCamelCase    (     unittest.TestCase   ,			_lowerCAmelCase   ):
	__snake_case	:Union[str, Any]   =       (MaskFormerSwinBackbone,) if is_torch_available() else ()
	__snake_case	:Any   =       MaskFormerSwinConfig







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







		__lowercase             =  MaskFormerSwinModelTester(self			)







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







		__lowercase       ,						__lowercase             =  self.model_tester.prepare_config_and_inputs_for_common()
		__lowercase             =  inputs_dict["""pixel_values"""].shape[0]

		for backbone_class in self.all_model_classes:
			__lowercase             =  backbone_class(_lowerCAmelCase			)
			backbone.to(_lowerCAmelCase			)
			backbone.eval()

			__lowercase             =  backbone(**_lowerCAmelCase			)

			# Test default outputs and verify feature maps
			self.assertIsInstance(outputs.feature_maps       ,				_lowerCAmelCase			)
			self.assertTrue(len(outputs.feature_maps			) == len(backbone.channels			)			)
			for feature_map, n_channels in zip(outputs.feature_maps       ,				backbone.channels			):
				self.assertTrue(feature_map.shape[:2]       ,				(batch_size, n_channels)			)
			self.assertIsNone(outputs.hidden_states			)
			self.assertIsNone(outputs.attentions			)

			# Test output_hidden_states=True
			__lowercase             =  backbone(**_lowerCAmelCase       ,				output_hidden_states=_lowerCAmelCase			)
			self.assertIsNotNone(outputs.hidden_states			)
			self.assertTrue(len(outputs.hidden_states			)       ,				len(backbone.stage_names			)			)
			# We skip the stem layer
			for hidden_states, n_channels in zip(outputs.hidden_states[1:]       ,				backbone.channels			):
				for hidden_state in hidden_states:
					# Hidden states are in the format (batch_size, (height * width), n_channels)
					__lowercase       ,						__lowercase       ,						__lowercase             =  hidden_state.shape
					self.assertTrue((h_batch_size, h_n_channels)       ,				(batch_size, n_channels)			)

            # Test output_attentions=True
			if self.has_attentions:
				__lowercase             =  backbone(**_lowerCAmelCase       ,				output_attentions=_lowerCAmelCase			)
				self.assertIsNotNone(outputs.attentions			)









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

