


"""simple docstring"""



import tempfile
import unittest

import numpy as np

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

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
 import onnxruntime as ort
class 					__magic_name__		(			__UpperCAmelCase			,						unittest.TestCase     ):
       __A			:      List[Any]        =   "hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline"






       def  __snake_case						(   self  :    Dict  ,     snake_case__  :    List[str]=0				):

              '''simple docstring'''






              lowercase		:str       							=				np.random.RandomState(__UpperCamelCase				)
              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  __snake_case						(   self  :    Optional[Any]				):

              '''simple docstring'''






              lowercase		:Any       							=				OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint  ,     provider='''CPUExecutionProvider'''				)
              pipe.set_progress_bar_config(disable=__UpperCamelCase				)

              lowercase		:List[str]       							=				self.get_dummy_inputs()
              lowercase		:int       							=				pipe(**__UpperCamelCase				).images
              lowercase		:str       							=				image[0, -3:, -3:, -1]

              assert image.shape == (1, 1_2_8, 1_2_8, 3)
              lowercase		:Union[str, Any]       							=				np.array([0.6_50_72, 0.5_84_92, 0.4_82_19, 0.5_55_21, 0.5_31_80, 0.5_59_39, 0.5_06_97, 0.3_98_00, 0.4_64_55]				)

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






       def  __snake_case						(   self  :    str				):

              '''simple docstring'''






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

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

              assert image.shape == (1, 1_2_8, 1_2_8, 3)
              lowercase		:Optional[int]       							=				np.array([0.6_58_63, 0.5_94_25, 0.4_93_26, 0.5_63_13, 0.5_38_75, 0.5_66_27, 0.5_10_65, 0.3_97_77, 0.4_63_30]				)

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






       def  __snake_case						(   self  :    str				):

              '''simple docstring'''






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

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

              assert image.shape == (1, 1_2_8, 1_2_8, 3)
              lowercase		:Any       							=				np.array([0.5_37_55, 0.6_07_86, 0.4_74_02, 0.4_94_88, 0.5_18_69, 0.4_98_19, 0.4_79_85, 0.3_89_57, 0.4_42_79]				)

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






       def  __snake_case						(   self  :    Optional[Any]				):

              '''simple docstring'''






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

              lowercase		:Union[str, Any]       							=				self.get_dummy_inputs()
              lowercase		:int       							=				pipe(**__UpperCamelCase				).images
              lowercase		:Tuple       							=				image[0, -3:, -3:, -1]

              assert image.shape == (1, 1_2_8, 1_2_8, 3)
              lowercase		:int       							=				np.array([0.5_37_55, 0.6_07_86, 0.4_74_02, 0.4_94_88, 0.5_18_69, 0.4_98_19, 0.4_79_85, 0.3_89_57, 0.4_42_79]				)

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






       def  __snake_case						(   self  :    Optional[int]				):

              '''simple docstring'''






              lowercase		:List[str]       							=				OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint  ,     provider='''CPUExecutionProvider'''				)
              lowercase		:Dict       							=				EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config				)
              pipe.set_progress_bar_config(disable=__UpperCamelCase				)

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

              assert image.shape == (1, 1_2_8, 1_2_8, 3)
              lowercase		:Optional[int]       							=				np.array([0.5_38_17, 0.6_08_12, 0.4_73_84, 0.4_95_30, 0.5_18_94, 0.4_98_14, 0.4_79_84, 0.3_89_58, 0.4_42_71]				)

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






       def  __snake_case						(   self  :    Tuple				):

              '''simple docstring'''






              lowercase		:Any       							=				OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint  ,     provider='''CPUExecutionProvider'''				)
              lowercase		:str       							=				DPMSolverMultistepScheduler.from_config(pipe.scheduler.config				)
              pipe.set_progress_bar_config(disable=__UpperCamelCase				)

              lowercase		:Any       							=				self.get_dummy_inputs()
              lowercase		:Optional[int]       							=				pipe(**__UpperCamelCase				).images
              lowercase		:Optional[Any]       							=				image[0, -3:, -3:, -1]

              assert image.shape == (1, 1_2_8, 1_2_8, 3)
              lowercase		:Union[str, Any]       							=				np.array([0.5_38_95, 0.6_08_08, 0.4_79_33, 0.4_96_08, 0.5_18_86, 0.4_99_50, 0.4_80_53, 0.3_89_57, 0.4_42_00]				)

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






       def  __snake_case						(   self  :    int				):

              '''simple docstring'''






              lowercase		:List[str]       							=				OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint  ,     provider='''CPUExecutionProvider'''				)
              pipe.set_progress_bar_config(disable=__UpperCamelCase				)

              lowercase		:Optional[Any]       							=				self.get_dummy_inputs()
              lowercase		:Dict       							=				3 * [inputs['''prompt''']]

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

              lowercase		:Any       							=				self.get_dummy_inputs()
              lowercase		:Tuple       							=				3 * [inputs.pop('''prompt'''				)]

              lowercase		:Any       							=				pipe.tokenizer(
                  __UpperCamelCase  ,     padding='''max_length'''  ,     max_length=pipe.tokenizer.model_max_length  ,     truncation=__UpperCamelCase  ,     return_tensors='''np'''  ,     )
              lowercase		:Optional[Any]       							=				text_inputs['''input_ids''']

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

              lowercase		:Union[str, Any]       							=				prompt_embeds

              # forward
              lowercase		:Tuple       							=				pipe(**__UpperCamelCase				)
              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  __snake_case						(   self  :    List[Any]				):

              '''simple docstring'''






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

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

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

              lowercase		:int       							=				self.get_dummy_inputs()
              lowercase		:Tuple       							=				3 * [inputs.pop('''prompt'''				)]

              lowercase		:List[Any]       							=				[]
              for p in [prompt, negative_prompt]:
                     lowercase		:List[Any]       							=				pipe.tokenizer(
                         __UpperCamelCase  ,     padding='''max_length'''  ,     max_length=pipe.tokenizer.model_max_length  ,     truncation=__UpperCamelCase  ,     return_tensors='''np'''  ,     )
                     lowercase		:str       							=				text_inputs['''input_ids''']

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

              lowercase							,  lowercase		:int       							=				embeds

              # forward
              lowercase		:Optional[Any]       							=				pipe(**__UpperCamelCase				)
              lowercase		:Dict       							=				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 					__magic_name__		(			unittest.TestCase     ):






       @property
       def  __snake_case						(   self  :    Tuple				):

              '''simple docstring'''






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






       @property
       def  __snake_case						(   self  :    Dict				):

              '''simple docstring'''






              lowercase		:str       							=				ort.SessionOptions()
              lowercase		:Any       							=				False
              return options






       def  __snake_case						(   self  :    Dict				):

              '''simple docstring'''






              lowercase		:Dict       							=				OnnxStableDiffusionPipeline.from_pretrained(
                  '''CompVis/stable-diffusion-v1-4'''  ,     revision='''onnx'''  ,     safety_checker=__UpperCamelCase  ,     feature_extractor=__UpperCamelCase  ,     provider=self.gpu_provider  ,     sess_options=self.gpu_options  ,     )
              sd_pipe.set_progress_bar_config(disable=__UpperCamelCase				)

              lowercase		:List[Any]       							=				'''A painting of a squirrel eating a burger'''
              np.random.seed(0				)
              lowercase		:Any       							=				sd_pipe([prompt]  ,     guidance_scale=6.0  ,     num_inference_steps=1_0  ,     output_type='''np'''				)
              lowercase		:List[Any]       							=				output.images

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

              assert image.shape == (1, 5_1_2, 5_1_2, 3)
              lowercase		:int       							=				np.array([0.04_52, 0.03_90, 0.00_87, 0.03_50, 0.06_17, 0.03_64, 0.05_44, 0.05_23, 0.07_20]				)

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






       def  __snake_case						(   self  :    Union[str, Any]				):

              '''simple docstring'''






              lowercase		:List[Any]       							=				DDIMScheduler.from_pretrained(
                  '''runwayml/stable-diffusion-v1-5'''  ,     subfolder='''scheduler'''  ,     revision='''onnx'''				)
              lowercase		:Any       							=				OnnxStableDiffusionPipeline.from_pretrained(
                  '''runwayml/stable-diffusion-v1-5'''  ,     revision='''onnx'''  ,     scheduler=__UpperCamelCase  ,     safety_checker=__UpperCamelCase  ,     feature_extractor=__UpperCamelCase  ,     provider=self.gpu_provider  ,     sess_options=self.gpu_options  ,     )
              sd_pipe.set_progress_bar_config(disable=__UpperCamelCase				)

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

              assert image.shape == (1, 5_1_2, 5_1_2, 3)
              lowercase		:int       							=				np.array([0.28_67, 0.19_74, 0.14_81, 0.72_94, 0.72_51, 0.66_67, 0.41_94, 0.56_42, 0.64_86]				)

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






       def  __snake_case						(   self  :    List[str]				):

              '''simple docstring'''






              lowercase		:Optional[int]       							=				LMSDiscreteScheduler.from_pretrained(
                  '''runwayml/stable-diffusion-v1-5'''  ,     subfolder='''scheduler'''  ,     revision='''onnx'''				)
              lowercase		:List[Any]       							=				OnnxStableDiffusionPipeline.from_pretrained(
                  '''runwayml/stable-diffusion-v1-5'''  ,     revision='''onnx'''  ,     scheduler=__UpperCamelCase  ,     safety_checker=__UpperCamelCase  ,     feature_extractor=__UpperCamelCase  ,     provider=self.gpu_provider  ,     sess_options=self.gpu_options  ,     )
              sd_pipe.set_progress_bar_config(disable=__UpperCamelCase				)

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

              assert image.shape == (1, 5_1_2, 5_1_2, 3)
              lowercase		:List[str]       							=				np.array([0.23_06, 0.19_59, 0.15_93, 0.65_49, 0.63_94, 0.54_08, 0.50_65, 0.60_10, 0.61_61]				)

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






       def  __snake_case						(   self  :    Dict				):

              '''simple docstring'''






              lowercase		:Any       							=				0

              def test_callback_fn(snake_case__  :    int  ,     snake_case__  :    int  ,     snake_case__  :    np.ndarray				) -> None:
                     lowercase		:List[str]       							=				True
                     nonlocal number_of_steps
                     number_of_steps += 1
                     if step == 0:
                            assert latents.shape == (1, 4, 6_4, 6_4)
                            lowercase		:Tuple       							=				latents[0, -3:, -3:, -1]
                            lowercase		:int       							=				np.array(
                                [-0.67_72, -0.38_35, -1.24_56, 0.19_05, -1.09_74, 0.69_67, -1.93_53, 0.01_78, 1.01_67]				)

                            assert np.abs(latents_slice.flatten() - expected_slice				).max() < 1e-3
                     elif step == 5:
                            assert latents.shape == (1, 4, 6_4, 6_4)
                            lowercase		:Optional[Any]       							=				latents[0, -3:, -3:, -1]
                            lowercase		:Dict       							=				np.array(
                                [-0.33_51, 0.22_41, -0.18_37, -0.23_25, -0.65_77, 0.33_93, -0.02_41, 0.58_99, 1.38_75]				)

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

              lowercase		:Union[str, Any]       							=				False

              lowercase		:Union[str, Any]       							=				OnnxStableDiffusionPipeline.from_pretrained(
                  '''runwayml/stable-diffusion-v1-5'''  ,     revision='''onnx'''  ,     safety_checker=__UpperCamelCase  ,     feature_extractor=__UpperCamelCase  ,     provider=self.gpu_provider  ,     sess_options=self.gpu_options  ,     )
              pipe.set_progress_bar_config(disable=__UpperCamelCase				)

              lowercase		:Optional[Any]       							=				'''Andromeda galaxy in a bottle'''

              lowercase		:List[Any]       							=				np.random.RandomState(0				)
              pipe(
                  prompt=__UpperCamelCase  ,     num_inference_steps=5  ,     guidance_scale=7.5  ,     generator=__UpperCamelCase  ,     callback=__UpperCamelCase  ,     callback_steps=1  ,     )
              assert test_callback_fn.has_been_called
              assert number_of_steps == 6







       def  __snake_case						(   self  :    int				):

              '''simple docstring'''






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

              lowercase		: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(__UpperCamelCase				)
                     lowercase		:Any       							=				OnnxStableDiffusionPipeline.from_pretrained(__UpperCamelCase				)

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





"""simple docstring"""



from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_tf_available,
    is_tokenizers_available,
    is_torch_available,
    is_vision_available,
)


UpperCAmelCase      		=			{
    '''configuration_layoutlmv3''': [
        '''LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP''',
        '''LayoutLMv3Config''',
        '''LayoutLMv3OnnxConfig''',
    ],
    '''processing_layoutlmv3''': ['''LayoutLMv3Processor'''],
    '''tokenization_layoutlmv3''': ['''LayoutLMv3Tokenizer'''],
}

try:
 if not is_tokenizers_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 UpperCAmelCase      		=			['''LayoutLMv3TokenizerFast''']

try:
 if not is_torch_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 UpperCAmelCase      		=			[
     '''LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST''',
     '''LayoutLMv3ForQuestionAnswering''',
     '''LayoutLMv3ForSequenceClassification''',
     '''LayoutLMv3ForTokenClassification''',
     '''LayoutLMv3Model''',
     '''LayoutLMv3PreTrainedModel''',
 ]

try:
 if not is_tf_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 UpperCAmelCase      		=			[
     '''TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST''',
     '''TFLayoutLMv3ForQuestionAnswering''',
     '''TFLayoutLMv3ForSequenceClassification''',
     '''TFLayoutLMv3ForTokenClassification''',
     '''TFLayoutLMv3Model''',
     '''TFLayoutLMv3PreTrainedModel''',
 ]

try:
 if not is_vision_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 UpperCAmelCase      		=			['''LayoutLMv3FeatureExtractor''']
 UpperCAmelCase      		=			['''LayoutLMv3ImageProcessor''']


if TYPE_CHECKING:
 from .configuration_layoutlmva import (
     LAYOUTLMV3_PRETRAINED_CONFIG_ARCHIVE_MAP,
     LayoutLMvaConfig,
     LayoutLMvaOnnxConfig,
 )
 from .processing_layoutlmva import LayoutLMvaProcessor
 from .tokenization_layoutlmva import LayoutLMvaTokenizer

 try:
  if not is_tokenizers_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .tokenization_layoutlmva_fast import LayoutLMvaTokenizerFast

 try:
  if not is_torch_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_layoutlmva import (
      LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
      LayoutLMvaForQuestionAnswering,
      LayoutLMvaForSequenceClassification,
      LayoutLMvaForTokenClassification,
      LayoutLMvaModel,
      LayoutLMvaPreTrainedModel,
  )

 try:
  if not is_tf_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .modeling_tf_layoutlmva import (
      TF_LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST,
      TFLayoutLMvaForQuestionAnswering,
      TFLayoutLMvaForSequenceClassification,
      TFLayoutLMvaForTokenClassification,
      TFLayoutLMvaModel,
      TFLayoutLMvaPreTrainedModel,
  )

 try:
  if not is_vision_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .feature_extraction_layoutlmva import LayoutLMvaFeatureExtractor
  from .image_processing_layoutlmva import LayoutLMvaImageProcessor

else:
 import sys

 UpperCAmelCase      		=			_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)

