




"""simple docstring"""

import inspect
import unittest

from transformers import BitConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_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 BitBackbone, BitForImageClassification, BitImageProcessor, BitModel
       from transformers.models.bit.modeling_bit import BIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from PIL import Image





class 							lowercase_			:



 '''simple docstring'''

 def __init__(					self			:			Tuple       ,				_UpperCAmelCase			:			int       ,				_UpperCAmelCase			:			List[Any]=3       ,				_UpperCAmelCase			:			List[Any]=32       ,				_UpperCAmelCase			:			Optional[Any]=3       ,				_UpperCAmelCase			:			int=10       ,				_UpperCAmelCase			:			int=[8, 16, 32, 64]       ,				_UpperCAmelCase			:			Optional[Any]=[1, 1, 2, 1]       ,				_UpperCAmelCase			:			Optional[Any]=True       ,				_UpperCAmelCase			:			Union[str, Any]=True       ,				_UpperCAmelCase			:			Union[str, Any]="relu"       ,				_UpperCAmelCase			:			Optional[int]=3       ,				_UpperCAmelCase			:			Tuple=None       ,				_UpperCAmelCase			:			Dict=["stage2", "stage3", "stage4"]       ,				_UpperCAmelCase			:			Union[str, Any]=[2, 3, 4]       ,				_UpperCAmelCase			:			Optional[int]=1       ,				):
       _A     =  parent
       _A     =  batch_size
       _A     =  image_size
       _A     =  num_channels
       _A     =  embeddings_size
       _A     =  hidden_sizes
       _A     =  depths
       _A     =  is_training
       _A     =  use_labels
       _A     =  hidden_act
       _A     =  num_labels
       _A     =  scope
       _A     =  len(_UpperCAmelCase						)
       _A     =  out_features
       _A     =  out_indices
       _A     =  num_groups

 def      lowerCAmelCase_				(					self			:			str						):
       _A     =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

       _A     =  None
       if self.use_labels:
             _A     =  ids_tensor([self.batch_size]       ,				self.num_labels						)

       _A     =  self.get_config()

       return config, pixel_values, labels

 def      lowerCAmelCase_				(					self			:			int						):
       return BitConfig(
           num_channels=self.num_channels       ,				embeddings_size=self.embeddings_size       ,				hidden_sizes=self.hidden_sizes       ,				depths=self.depths       ,				hidden_act=self.hidden_act       ,				num_labels=self.num_labels       ,				out_features=self.out_features       ,				out_indices=self.out_indices       ,				num_groups=self.num_groups       ,				)

 def      lowerCAmelCase_				(					self			:			List[Any]       ,				_UpperCAmelCase			:			Optional[Any]       ,				_UpperCAmelCase			:			Tuple       ,				_UpperCAmelCase			:			List[str]						):
       _A     =  BitModel(config=_UpperCAmelCase						)
       model.to(_UpperCAmelCase						)
       model.eval()
       _A     =  model(_UpperCAmelCase						)
       self.parent.assertEqual(
           result.last_hidden_state.shape       ,				(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)       ,				)

 def      lowerCAmelCase_				(					self			:			Tuple       ,				_UpperCAmelCase			:			Optional[Any]       ,				_UpperCAmelCase			:			int       ,				_UpperCAmelCase			:			Tuple						):
       _A     =  self.num_labels
       _A     =  BitForImageClassification(_UpperCAmelCase						)
       model.to(_UpperCAmelCase						)
       model.eval()
       _A     =  model(_UpperCAmelCase       ,				labels=_UpperCAmelCase						)
       self.parent.assertEqual(result.logits.shape       ,				(self.batch_size, self.num_labels)						)

 def      lowerCAmelCase_				(					self			:			List[str]       ,				_UpperCAmelCase			:			Union[str, Any]       ,				_UpperCAmelCase			:			Optional[int]       ,				_UpperCAmelCase			:			int						):
       _A     =  BitBackbone(config=_UpperCAmelCase						)
       model.to(_UpperCAmelCase						)
       model.eval()
       _A     =  model(_UpperCAmelCase						)

       # verify feature maps
       self.parent.assertEqual(len(result.feature_maps						)       ,				len(config.out_features						)						)
       self.parent.assertListEqual(list(result.feature_maps[0].shape						)       ,				[self.batch_size, self.hidden_sizes[1], 4, 4]						)

       # verify channels
       self.parent.assertEqual(len(model.channels						)       ,				len(config.out_features						)						)
       self.parent.assertListEqual(model.channels       ,				config.hidden_sizes[1:]						)

       # verify backbone works with out_features=None
       _A     =  None
       _A     =  BitBackbone(config=_UpperCAmelCase						)
       model.to(_UpperCAmelCase						)
       model.eval()
       _A     =  model(_UpperCAmelCase						)

       # verify feature maps
       self.parent.assertEqual(len(result.feature_maps						)       ,				1						)
       self.parent.assertListEqual(list(result.feature_maps[0].shape						)       ,				[self.batch_size, self.hidden_sizes[-1], 1, 1]						)

       # verify channels
       self.parent.assertEqual(len(model.channels						)       ,				1						)
       self.parent.assertListEqual(model.channels       ,				[config.hidden_sizes[-1]]						)



 def      lowerCAmelCase_				(					self			:			Union[str, Any]						):
       _A     =  self.prepare_config_and_inputs()
       _A  ,       _A  ,       _A     =  config_and_inputs
       _A     =  {'pixel_values': pixel_values}
       return config, inputs_dict





@require_torch
class 							lowercase_			(	__lowerCAmelCase     ,      __lowerCAmelCase     ,      unittest.TestCase				):



 '''simple docstring'''
 UpperCAmelCase       :	str     =      (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else ()
 UpperCAmelCase       :	Tuple     =      (
     {'''feature-extraction''': BitModel, '''image-classification''': BitForImageClassification}
     if is_torch_available()
     else {}
 )

 UpperCAmelCase       :	Optional[int]     =      False
 UpperCAmelCase       :	Any     =      False
 UpperCAmelCase       :	List[str]     =      False
 UpperCAmelCase       :	List[Any]     =      False
 UpperCAmelCase       :	str     =      False

 def      lowerCAmelCase_				(					self			:			int						):
       _A     =  BitModelTester(self						)
       _A     =  ConfigTester(self       ,				config_class=_UpperCAmelCase       ,				has_text_modality=_UpperCAmelCase						)

 def      lowerCAmelCase_				(					self			:			Optional[Any]						):
       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      lowerCAmelCase_				(					self			:			Any						):
       return

 @unittest.skip(reason='Bit does not output attentions'						)
 def      lowerCAmelCase_				(					self			:			List[str]						):
       pass

 @unittest.skip(reason='Bit does not use inputs_embeds'						)
 def      lowerCAmelCase_				(					self			:			List[Any]						):
       pass

 @unittest.skip(reason='Bit does not support input and output embeddings'						)
 def      lowerCAmelCase_				(					self			:			str						):
       pass

 def      lowerCAmelCase_				(					self			:			Optional[int]						):
       _A  ,       _A     =  self.model_tester.prepare_config_and_inputs_for_common()

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

             _A     =  ['pixel_values']
             self.assertListEqual(arg_names[:1]       ,				_UpperCAmelCase						)

 def      lowerCAmelCase_				(					self			:			Optional[int]						):
       _A     =  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_UpperCAmelCase						)

 def      lowerCAmelCase_				(					self			:			List[Any]						):
       _A     =  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_backbone(*_UpperCAmelCase						)

 def      lowerCAmelCase_				(					self			:			str						):
       _A  ,       _A     =  self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
             _A     =  model_class(config=_UpperCAmelCase						)
             for name, module in model.named_modules():
                   if isinstance(_UpperCAmelCase       ,				(nn.BatchNormad, nn.GroupNorm)						):
                         self.assertTrue(
                             torch.all(module.weight == 1						)       ,				msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''       ,				)
                         self.assertTrue(
                             torch.all(module.bias == 0						)       ,				msg=F'''Parameter {name} of model {model_class} seems not properly initialized'''       ,				)

 def      lowerCAmelCase_				(					self			:			List[str]						):
       def check_hidden_states_output(_UpperCAmelCase			:			Any       ,				_UpperCAmelCase			:			Tuple       ,				_UpperCAmelCase			:			Any						):
             _A     =  model_class(_UpperCAmelCase						)
             model.to(_UpperCAmelCase						)
             model.eval()

             with torch.no_grad():
                   _A     =  model(**self._prepare_for_class(_UpperCAmelCase       ,				_UpperCAmelCase						)						)

             _A     =  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

             _A     =  self.model_tester.num_stages
             self.assertEqual(len(_UpperCAmelCase						)       ,				expected_num_stages + 1						)

             # Bit's feature maps are of shape (batch_size, num_channels, height, width)
             self.assertListEqual(
                 list(hidden_states[0].shape[-2:]						)       ,				[self.model_tester.image_size // 4, self.model_tester.image_size // 4]       ,				)

       _A  ,       _A     =  self.model_tester.prepare_config_and_inputs_for_common()
       _A     =  ['preactivation', 'bottleneck']
       for model_class in self.all_model_classes:
             for layer_type in layers_type:
                   _A     =  layer_type
                   _A     =  True
                   check_hidden_states_output(_UpperCAmelCase       ,				_UpperCAmelCase       ,				_UpperCAmelCase						)

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

                   check_hidden_states_output(_UpperCAmelCase       ,				_UpperCAmelCase       ,				_UpperCAmelCase						)

 @unittest.skip(reason='Bit does not use feedforward chunking'						)
 def      lowerCAmelCase_				(					self			:			int						):
       pass

 def      lowerCAmelCase_				(					self			:			List[str]						):
       _A     =  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase						)



 @slow
 def      lowerCAmelCase_				(					self			:			List[str]						):
       for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             _A     =  BitModel.from_pretrained(_UpperCAmelCase						)
             self.assertIsNotNone(_UpperCAmelCase						)






def 		_snake_case	(   )       ->   str:






      '''simple docstring'''


      _A     =  Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
      return image





@require_torch
@require_vision
class 							lowercase_			(	unittest.TestCase				):



 '''simple docstring'''

 @cached_property
 def      lowerCAmelCase_				(					self			:			List[str]						):
       return (
           BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]						) if is_vision_available() else None
       )



 @slow
 def      lowerCAmelCase_				(					self			:			Tuple						):
       _A     =  BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0]						).to(_UpperCAmelCase						)

       _A     =  self.default_image_processor
       _A     =  prepare_img()
       _A     =  image_processor(images=_UpperCAmelCase       ,				return_tensors='pt'						).to(_UpperCAmelCase						)

       # forward pass
       with torch.no_grad():
             _A     =  model(**_UpperCAmelCase						)

       # verify the logits
       _A     =  torch.Size((1, 1_000)						)
       self.assertEqual(outputs.logits.shape       ,				_UpperCAmelCase						)

       _A     =  torch.tensor([[-0.6526, -0.5263, -1.4398]]						).to(_UpperCAmelCase						)

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





@require_torch
class 							lowercase_			(	__lowerCAmelCase     ,      unittest.TestCase				):



 '''simple docstring'''
 UpperCAmelCase       :	Tuple     =      (BitBackbone,) if is_torch_available() else ()
 UpperCAmelCase       :	List[Any]     =      BitConfig

 UpperCAmelCase       :	Optional[int]     =      False

 def      lowerCAmelCase_				(					self			:			List[Any]						):
       _A     =  BitModelTester(self						)





import tempfile
import unittest

import numpy as np

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

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
 import onnxruntime as ort






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




           """simple docstring"""

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




           """simple docstring"""

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

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

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

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




           """simple docstring"""

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

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

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

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




           """simple docstring"""

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

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

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

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




           """simple docstring"""

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

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

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

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




           """simple docstring"""

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

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

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

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




           """simple docstring"""

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

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

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

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




           """simple docstring"""

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

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

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

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

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

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

           _lowercase			:				List[Any] 						=						prompt_embeds

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

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




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




           """simple docstring"""

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

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

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

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

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

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

           _lowercase						,							_lowercase			:				str 						=						embeds

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

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






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




           """simple docstring"""

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




           """simple docstring"""

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




           """simple docstring"""

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

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

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

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

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




           """simple docstring"""

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

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

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

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




           """simple docstring"""

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

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

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

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




           """simple docstring"""

           _lowercase			:				List[Any] 						=						0

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

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

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

           _lowercase			:				Any 						=						False

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

           _lowercase			:				Any 						=						'Andromeda galaxy in a bottle'

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




       def      UpperCamelCase	(   self)			->  Tuple:




           """simple docstring"""

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

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

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

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


