


import random
import unittest

import numpy as np

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionImgaImgPipeline,
    PNDMScheduler,
)
from diffusers.utils import floats_tensor
from diffusers.utils.testing_utils import (
    is_onnx_available,
    load_image,
    nightly,
    require_onnxruntime,
    require_torch_gpu,
)

from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin


if is_onnx_available():
				import onnxruntime as ort




class        lowerCamelCase      (     _UpperCamelCase       ,	unittest.TestCase   ):
	_lowerCAmelCase    :		Union[str, Any]        =	'''hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline'''


	def    A(						self							,    lowercase__=0):
							__UpperCAmelCase :       List[Any]  						=  floats_tensor((1, 3, 1_2_8, 1_2_8)							,    rng=random.Random(lowercase__))
							__UpperCAmelCase :       Tuple  						=  np.random.RandomState(lowercase__)
							__UpperCAmelCase :       Optional[Any]  						=  {
							    '''prompt''': '''A painting of a squirrel eating a burger''',
							    '''image''': image,
							    '''generator''': generator,
							    '''num_inference_steps''': 3,
							    '''strength''': 0.7_5,
							    '''guidance_scale''': 7.5,
							    '''output_type''': '''numpy''',
							}
							return inputs


	def    A(						self):
							__UpperCAmelCase :       Optional[Any]  						=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint							,    provider='''CPUExecutionProvider''')
							pipe.set_progress_bar_config(disable=lowercase__)

							__UpperCAmelCase :       List[Any]  						=  self.get_dummy_inputs()
							__UpperCAmelCase :       List[Any]  						=  pipe(**lowercase__).images
							__UpperCAmelCase :       str  						=  image[0, -3:, -3:, -1].flatten()

							assert image.shape == (1, 1_2_8, 1_2_8, 3)
							__UpperCAmelCase :       List[Any]  						=  np.array([0.6_9_6_4_3, 0.5_8_4_8_4, 0.5_0_3_1_4, 0.5_8_7_6_0, 0.5_5_3_6_8, 0.5_9_6_4_3, 0.5_1_5_2_9, 0.4_1_2_1_7, 0.4_9_0_8_7])
							assert np.abs(image_slice - expected_slice).max() < 1e-1


	def    A(						self):
							__UpperCAmelCase :       List[str]  						=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint							,    provider='''CPUExecutionProvider''')
							__UpperCAmelCase :       Dict  						=  PNDMScheduler.from_config(pipe.scheduler.config							,    skip_prk_steps=lowercase__)
							pipe.set_progress_bar_config(disable=lowercase__)

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

							assert image.shape == (1, 1_2_8, 1_2_8, 3)
							__UpperCAmelCase :       str  						=  np.array([0.6_1_7_3_7, 0.5_4_6_4_2, 0.5_3_1_8_3, 0.5_4_4_6_5, 0.5_2_7_4_2, 0.6_0_5_2_5, 0.4_9_9_6_9, 0.4_0_6_5_5, 0.4_8_1_5_4])

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


	def    A(						self):
							__UpperCAmelCase :       Optional[int]  						=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint							,    provider='''CPUExecutionProvider''')
							__UpperCAmelCase :       Tuple  						=  LMSDiscreteScheduler.from_config(pipe.scheduler.config)
							pipe.set_progress_bar_config(disable=lowercase__)

							# warmup pass to apply optimizations
							__UpperCAmelCase :       Union[str, Any]  						=  pipe(**self.get_dummy_inputs())

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

							assert image.shape == (1, 1_2_8, 1_2_8, 3)
							__UpperCAmelCase :       Optional[Any]  						=  np.array([0.5_2_7_6_1, 0.5_9_9_7_7, 0.4_9_0_3_3, 0.4_9_6_1_9, 0.5_4_2_8_2, 0.5_0_3_1_1, 0.4_7_6_0_0, 0.4_0_9_1_8, 0.4_5_2_0_3])

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


	def    A(						self):
							__UpperCAmelCase :       str  						=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint							,    provider='''CPUExecutionProvider''')
							__UpperCAmelCase :       Tuple  						=  EulerDiscreteScheduler.from_config(pipe.scheduler.config)
							pipe.set_progress_bar_config(disable=lowercase__)

							__UpperCAmelCase :       Optional[int]  						=  self.get_dummy_inputs()
							__UpperCAmelCase :       Tuple  						=  pipe(**lowercase__).images
							__UpperCAmelCase :       Optional[int]  						=  image[0, -3:, -3:, -1]

							assert image.shape == (1, 1_2_8, 1_2_8, 3)
							__UpperCAmelCase :       Tuple  						=  np.array([0.5_2_9_1_1, 0.6_0_0_0_4, 0.4_9_2_2_9, 0.4_9_8_0_5, 0.5_4_5_0_2, 0.5_0_6_8_0, 0.4_7_7_7_7, 0.4_1_0_2_8, 0.4_5_3_0_4])

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


	def    A(						self):
							__UpperCAmelCase :       Optional[Any]  						=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint							,    provider='''CPUExecutionProvider''')
							__UpperCAmelCase :       Union[str, Any]  						=  EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
							pipe.set_progress_bar_config(disable=lowercase__)

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

							assert image.shape == (1, 1_2_8, 1_2_8, 3)
							__UpperCAmelCase :       Any  						=  np.array([0.5_2_9_1_1, 0.6_0_0_0_4, 0.4_9_2_2_9, 0.4_9_8_0_5, 0.5_4_5_0_2, 0.5_0_6_8_0, 0.4_7_7_7_7, 0.4_1_0_2_8, 0.4_5_3_0_4])

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


	def    A(						self):
							__UpperCAmelCase :       Union[str, Any]  						=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(self.hub_checkpoint							,    provider='''CPUExecutionProvider''')
							__UpperCAmelCase :       List[Any]  						=  DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
							pipe.set_progress_bar_config(disable=lowercase__)

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

							assert image.shape == (1, 1_2_8, 1_2_8, 3)
							__UpperCAmelCase :       str  						=  np.array([0.6_5_3_3_1, 0.5_8_2_7_7, 0.4_8_2_0_4, 0.5_6_0_5_9, 0.5_3_6_6_5, 0.5_6_2_3_5, 0.5_0_9_6_9, 0.4_0_0_0_9, 0.4_6_5_5_2])

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






@nightly
@require_onnxruntime
@require_torch_gpu
class        lowerCamelCase      (     unittest.TestCase   ):


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


	@property
	def    A(						self):
							__UpperCAmelCase :       Optional[Any]  						=  ort.SessionOptions()
							__UpperCAmelCase :       int  						=  False
							return options


	def    A(						self):
							__UpperCAmelCase :       int  						=  load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
							    '''/img2img/sketch-mountains-input.jpg''')
							__UpperCAmelCase :       Optional[Any]  						=  init_image.resize((7_6_8, 5_1_2))
							# using the PNDM scheduler by default
							__UpperCAmelCase :       List[str]  						=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(
							    '''CompVis/stable-diffusion-v1-4'''							,    revision='''onnx'''							,    safety_checker=lowercase__							,    feature_extractor=lowercase__							,    provider=self.gpu_provider							,    sess_options=self.gpu_options							,    )
							pipe.set_progress_bar_config(disable=lowercase__)

							__UpperCAmelCase :       Dict  						=  '''A fantasy landscape, trending on artstation'''

							__UpperCAmelCase :       List[Any]  						=  np.random.RandomState(0)
							__UpperCAmelCase :       List[Any]  						=  pipe(
							    prompt=lowercase__							,    image=lowercase__							,    strength=0.7_5							,    guidance_scale=7.5							,    num_inference_steps=1_0							,    generator=lowercase__							,    output_type='''np'''							,    )
							__UpperCAmelCase :       List[str]  						=  output.images
							__UpperCAmelCase :       List[str]  						=  images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]

							assert images.shape == (1, 5_1_2, 7_6_8, 3)
							__UpperCAmelCase :       Optional[Any]  						=  np.array([0.4_9_0_9, 0.5_0_5_9, 0.5_3_7_2, 0.4_6_2_3, 0.4_8_7_6, 0.5_0_4_9, 0.4_8_2_0, 0.4_9_5_6, 0.5_0_1_9])
							# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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


	def    A(						self):
							__UpperCAmelCase :       List[str]  						=  load_image(
							    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
							    '''/img2img/sketch-mountains-input.jpg''')
							__UpperCAmelCase :       Tuple  						=  init_image.resize((7_6_8, 5_1_2))
							__UpperCAmelCase :       Any  						=  LMSDiscreteScheduler.from_pretrained(
							    '''runwayml/stable-diffusion-v1-5'''							,    subfolder='''scheduler'''							,    revision='''onnx''')
							__UpperCAmelCase :       Any  						=  OnnxStableDiffusionImgaImgPipeline.from_pretrained(
							    '''runwayml/stable-diffusion-v1-5'''							,    revision='''onnx'''							,    scheduler=lowercase__							,    safety_checker=lowercase__							,    feature_extractor=lowercase__							,    provider=self.gpu_provider							,    sess_options=self.gpu_options							,    )
							pipe.set_progress_bar_config(disable=lowercase__)

							__UpperCAmelCase :       List[Any]  						=  '''A fantasy landscape, trending on artstation'''

							__UpperCAmelCase :       Optional[int]  						=  np.random.RandomState(0)
							__UpperCAmelCase :       str  						=  pipe(
							    prompt=lowercase__							,    image=lowercase__							,    strength=0.7_5							,    guidance_scale=7.5							,    num_inference_steps=2_0							,    generator=lowercase__							,    output_type='''np'''							,    )
							__UpperCAmelCase :       List[Any]  						=  output.images
							__UpperCAmelCase :       Tuple  						=  images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]

							assert images.shape == (1, 5_1_2, 7_6_8, 3)
							__UpperCAmelCase :       Tuple  						=  np.array([0.8_0_4_3, 0.9_2_6, 0.9_5_8_1, 0.8_1_1_9, 0.8_9_5_4, 0.9_1_3, 0.7_2_0_9, 0.7_4_6_3, 0.7_4_3_1])
							# TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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





from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


lowerCAmelCase							=						logging.get_logger(__name__)

lowerCAmelCase							=						{
    """bert-base-uncased""": """https://huggingface.co/bert-base-uncased/resolve/main/config.json""",
    """bert-large-uncased""": """https://huggingface.co/bert-large-uncased/resolve/main/config.json""",
    """bert-base-cased""": """https://huggingface.co/bert-base-cased/resolve/main/config.json""",
    """bert-large-cased""": """https://huggingface.co/bert-large-cased/resolve/main/config.json""",
    """bert-base-multilingual-uncased""": """https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json""",
    """bert-base-multilingual-cased""": """https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json""",
    """bert-base-chinese""": """https://huggingface.co/bert-base-chinese/resolve/main/config.json""",
    """bert-base-german-cased""": """https://huggingface.co/bert-base-german-cased/resolve/main/config.json""",
    """bert-large-uncased-whole-word-masking""": (
        """https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json"""
    ),
    """bert-large-cased-whole-word-masking""": (
        """https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json"""
    ),
    """bert-large-uncased-whole-word-masking-finetuned-squad""": (
        """https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json"""
    ),
    """bert-large-cased-whole-word-masking-finetuned-squad""": (
        """https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json"""
    ),
    """bert-base-cased-finetuned-mrpc""": """https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json""",
    """bert-base-german-dbmdz-cased""": """https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json""",
    """bert-base-german-dbmdz-uncased""": """https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json""",
    """cl-tohoku/bert-base-japanese""": """https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json""",
    """cl-tohoku/bert-base-japanese-whole-word-masking""": (
        """https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json"""
    ),
    """cl-tohoku/bert-base-japanese-char""": (
        """https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json"""
    ),
    """cl-tohoku/bert-base-japanese-char-whole-word-masking""": (
        """https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json"""
    ),
    """TurkuNLP/bert-base-finnish-cased-v1""": (
        """https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json"""
    ),
    """TurkuNLP/bert-base-finnish-uncased-v1""": (
        """https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json"""
    ),
    """wietsedv/bert-base-dutch-cased""": """https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json""",
    # See all BERT models at https://huggingface.co/models?filter=bert
}




class        lowerCamelCase      (     _UpperCamelCase   ):
	_lowerCAmelCase    :		int        =	'''bert'''


	def __init__(						self							,    lowercase__=3_0_5_2_2							,    lowercase__=7_6_8							,    lowercase__=1_2							,    lowercase__=1_2							,    lowercase__=3_0_7_2							,    lowercase__="gelu"							,    lowercase__=0.1							,    lowercase__=0.1							,    lowercase__=5_1_2							,    lowercase__=2							,    lowercase__=0.0_2							,    lowercase__=1e-12							,    lowercase__=0							,    lowercase__="absolute"							,    lowercase__=True							,    lowercase__=None							,    **lowercase__							,    ):
							super().__init__(pad_token_id=lowercase__							,    **lowercase__)

							__UpperCAmelCase :       Tuple  						=  vocab_size
							__UpperCAmelCase :       Any  						=  hidden_size
							__UpperCAmelCase :       str  						=  num_hidden_layers
							__UpperCAmelCase :       Dict  						=  num_attention_heads
							__UpperCAmelCase :       Tuple  						=  hidden_act
							__UpperCAmelCase :       int  						=  intermediate_size
							__UpperCAmelCase :       List[Any]  						=  hidden_dropout_prob
							__UpperCAmelCase :       Union[str, Any]  						=  attention_probs_dropout_prob
							__UpperCAmelCase :       List[Any]  						=  max_position_embeddings
							__UpperCAmelCase :       Union[str, Any]  						=  type_vocab_size
							__UpperCAmelCase :       List[Any]  						=  initializer_range
							__UpperCAmelCase :       List[Any]  						=  layer_norm_eps
							__UpperCAmelCase :       List[str]  						=  position_embedding_type
							__UpperCAmelCase :       Optional[Any]  						=  use_cache
							__UpperCAmelCase :       List[Any]  						=  classifier_dropout






class        lowerCamelCase      (     _UpperCamelCase   ):


	@property
	def    A(						self):
							if self.task == "multiple-choice":
													__UpperCAmelCase :       Optional[int]  						=  {0: '''batch''', 1: '''choice''', 2: '''sequence'''}
							else:
													__UpperCAmelCase :       Optional[Any]  						=  {0: '''batch''', 1: '''sequence'''}
							return OrderedDict(
							    [
							        ('''input_ids''', dynamic_axis),
							        ('''attention_mask''', dynamic_axis),
							        ('''token_type_ids''', dynamic_axis),
							    ])

