"""simple docstring"""



import random
import unittest

import numpy as np
import torch

from diffusers import (
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    OnnxStableDiffusionUpscalePipeline,
    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       (   snake_case_					,							unittest.TestCase			):
   # TODO: is there an appropriate internal test set?
   __UpperCAmelCase				: Tuple													=						"""ssube/stable-diffusion-x4-upscaler-onnx"""







   def 				lowerCamelCase	(			self		,			UpperCamelCase__=0		)			->	Dict:

       '''simple docstring'''




       snake_case					:   int         =					floats_tensor((1, 3, 128, 128)		,			rng=random.Random(UpperCamelCase__		)		)
       snake_case					:   int         =					torch.manual_seed(UpperCamelCase__		)
       snake_case					:   str         =					{
           "prompt": "A painting of a squirrel eating a burger",
           "image": image,
           "generator": generator,
           "num_inference_steps": 3,
           "guidance_scale": 7.5,
           "output_type": "numpy",
       }
       return inputs







   def 				lowerCamelCase	(			self		)			->	Optional[Any]:

       '''simple docstring'''




       snake_case					:   Optional[int]         =					OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,			provider="CPUExecutionProvider"		)
       pipe.set_progress_bar_config(disable=UpperCamelCase__		)

       snake_case					:   Union[str, Any]         =					self.get_dummy_inputs()
       snake_case					:   Dict         =					pipe(**UpperCamelCase__		).images
       snake_case					:   Optional[int]         =					image[0, -3:, -3:, -1].flatten()

       # started as 128, should now be 512
       assert image.shape == (1, 512, 512, 3)
       snake_case					:   List[str]         =					np.array(
           [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223]		)
       assert np.abs(image_slice - expected_slice		).max() < 1e-1







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

       '''simple docstring'''




       snake_case					:   Tuple         =					OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,			provider="CPUExecutionProvider"		)
       snake_case					:   Union[str, Any]         =					PNDMScheduler.from_config(pipe.scheduler.config		,			skip_prk_steps=UpperCamelCase__		)
       pipe.set_progress_bar_config(disable=UpperCamelCase__		)

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

       assert image.shape == (1, 512, 512, 3)
       snake_case					:   int         =					np.array(
           [0.6898892, 0.59240556, 0.52499527, 0.58866215, 0.52258235, 0.52572715, 0.62414473, 0.6174387, 0.6214964]		)
       assert np.abs(image_slice.flatten() - expected_slice		).max() < 1e-1







   def 				lowerCamelCase	(			self		)			->	str:

       '''simple docstring'''




       snake_case					:   int         =					OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,			provider="CPUExecutionProvider"		)
       snake_case					:   Dict         =					DPMSolverMultistepScheduler.from_config(pipe.scheduler.config		)
       pipe.set_progress_bar_config(disable=UpperCamelCase__		)

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

       assert image.shape == (1, 512, 512, 3)
       snake_case					:   int         =					np.array(
           [0.7659278, 0.76437664, 0.75579107, 0.7691116, 0.77666986, 0.7727672, 0.7758664, 0.7812226, 0.76942515]		)

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







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

       '''simple docstring'''




       snake_case					:   str         =					OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,			provider="CPUExecutionProvider"		)
       snake_case					:   Any         =					EulerDiscreteScheduler.from_config(pipe.scheduler.config		)
       pipe.set_progress_bar_config(disable=UpperCamelCase__		)

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

       assert image.shape == (1, 512, 512, 3)
       snake_case					:   str         =					np.array(
           [0.6974782, 0.68902093, 0.70135885, 0.7583618, 0.7804545, 0.7854912, 0.78667426, 0.78743863, 0.78070223]		)
       assert np.abs(image_slice.flatten() - expected_slice		).max() < 1e-1







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

       '''simple docstring'''




       snake_case					:   Optional[Any]         =					OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,			provider="CPUExecutionProvider"		)
       snake_case					:   Optional[int]         =					EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config		)
       pipe.set_progress_bar_config(disable=UpperCamelCase__		)

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

       assert image.shape == (1, 512, 512, 3)
       snake_case					:   Optional[Any]         =					np.array(
           [0.77424496, 0.773601, 0.7645288, 0.7769598, 0.7772739, 0.7738688, 0.78187233, 0.77879584, 0.767043]		)

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







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







   @property
   def 				lowerCamelCase	(			self		)			->	str:

       '''simple docstring'''




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







   @property
   def 				lowerCamelCase	(			self		)			->	Any:

       '''simple docstring'''




       snake_case					:   Any         =					ort.SessionOptions()
       snake_case					:   Tuple         =					False
       return options







   def 				lowerCamelCase	(			self		)			->	Any:

       '''simple docstring'''




       snake_case					:   Any         =					load_image(
           "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
           "/img2img/sketch-mountains-input.jpg"		)
       snake_case					:   Any         =					init_image.resize((128, 128)		)
       # using the PNDM scheduler by default
       snake_case					:   List[str]         =					OnnxStableDiffusionUpscalePipeline.from_pretrained(
           "ssube/stable-diffusion-x4-upscaler-onnx"		,			provider=self.gpu_provider		,			sess_options=self.gpu_options		,			)
       pipe.set_progress_bar_config(disable=UpperCamelCase__		)

       snake_case					:   List[Any]         =					"A fantasy landscape, trending on artstation"

       snake_case					:   Optional[int]         =					torch.manual_seed(0		)
       snake_case					:   Optional[Any]         =					pipe(
           prompt=UpperCamelCase__		,			image=UpperCamelCase__		,			guidance_scale=7.5		,			num_inference_steps=10		,			generator=UpperCamelCase__		,			output_type="np"		,			)
       snake_case					:   Tuple         =					output.images
       snake_case					:   Optional[Any]         =					images[0, 255:258, 383:386, -1]

       assert images.shape == (1, 512, 512, 3)
       snake_case					:   str         =					np.array([0.4883, 0.4947, 0.4980, 0.4975, 0.4982, 0.4980, 0.5000, 0.5006, 0.4972]		)
       # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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







   def 				lowerCamelCase	(			self		)			->	Union[str, Any]:

       '''simple docstring'''




       snake_case					:   Any         =					load_image(
           "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
           "/img2img/sketch-mountains-input.jpg"		)
       snake_case					:   Tuple         =					init_image.resize((128, 128)		)
       snake_case					:   Union[str, Any]         =					LMSDiscreteScheduler.from_pretrained(
           "ssube/stable-diffusion-x4-upscaler-onnx"		,			subfolder="scheduler"		)
       snake_case					:   List[str]         =					OnnxStableDiffusionUpscalePipeline.from_pretrained(
           "ssube/stable-diffusion-x4-upscaler-onnx"		,			scheduler=UpperCamelCase__		,			provider=self.gpu_provider		,			sess_options=self.gpu_options		,			)
       pipe.set_progress_bar_config(disable=UpperCamelCase__		)

       snake_case					:   Any         =					"A fantasy landscape, trending on artstation"

       snake_case					:   Tuple         =					torch.manual_seed(0		)
       snake_case					:   Optional[Any]         =					pipe(
           prompt=UpperCamelCase__		,			image=UpperCamelCase__		,			guidance_scale=7.5		,			num_inference_steps=20		,			generator=UpperCamelCase__		,			output_type="np"		,			)
       snake_case					:   Union[str, Any]         =					output.images
       snake_case					:   Dict         =					images[0, 255:258, 383:386, -1]

       assert images.shape == (1, 512, 512, 3)
       snake_case					:   Optional[Any]         =					np.array(
           [0.50173753, 0.50223356, 0.502039, 0.50233036, 0.5023725, 0.5022601, 0.5018758, 0.50234085, 0.50241566]		)
       # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues

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









"""simple docstring"""



from typing import TYPE_CHECKING

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


__snake_case         =					{
    """configuration_distilbert""": [
        """DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """DistilBertConfig""",
        """DistilBertOnnxConfig""",
    ],
    """tokenization_distilbert""": ["""DistilBertTokenizer"""],
}

try:
  if not is_tokenizers_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  __snake_case         =					["""DistilBertTokenizerFast"""]

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  __snake_case         =					[
      """DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
      """DistilBertForMaskedLM""",
      """DistilBertForMultipleChoice""",
      """DistilBertForQuestionAnswering""",
      """DistilBertForSequenceClassification""",
      """DistilBertForTokenClassification""",
      """DistilBertModel""",
      """DistilBertPreTrainedModel""",
  ]

try:
  if not is_tf_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  __snake_case         =					[
      """TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST""",
      """TFDistilBertForMaskedLM""",
      """TFDistilBertForMultipleChoice""",
      """TFDistilBertForQuestionAnswering""",
      """TFDistilBertForSequenceClassification""",
      """TFDistilBertForTokenClassification""",
      """TFDistilBertMainLayer""",
      """TFDistilBertModel""",
      """TFDistilBertPreTrainedModel""",
  ]

try:
  if not is_flax_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  __snake_case         =					[
      """FlaxDistilBertForMaskedLM""",
      """FlaxDistilBertForMultipleChoice""",
      """FlaxDistilBertForQuestionAnswering""",
      """FlaxDistilBertForSequenceClassification""",
      """FlaxDistilBertForTokenClassification""",
      """FlaxDistilBertModel""",
      """FlaxDistilBertPreTrainedModel""",
  ]


if TYPE_CHECKING:
  from .configuration_distilbert import (
      DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
      DistilBertConfig,
      DistilBertOnnxConfig,
  )
  from .tokenization_distilbert import DistilBertTokenizer

  try:
    if not is_tokenizers_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .tokenization_distilbert_fast import DistilBertTokenizerFast

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_distilbert import (
        DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
        DistilBertForMaskedLM,
        DistilBertForMultipleChoice,
        DistilBertForQuestionAnswering,
        DistilBertForSequenceClassification,
        DistilBertForTokenClassification,
        DistilBertModel,
        DistilBertPreTrainedModel,
    )

  try:
    if not is_tf_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_tf_distilbert import (
        TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
        TFDistilBertForMaskedLM,
        TFDistilBertForMultipleChoice,
        TFDistilBertForQuestionAnswering,
        TFDistilBertForSequenceClassification,
        TFDistilBertForTokenClassification,
        TFDistilBertMainLayer,
        TFDistilBertModel,
        TFDistilBertPreTrainedModel,
    )

  try:
    if not is_flax_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_flax_distilbert import (
        FlaxDistilBertForMaskedLM,
        FlaxDistilBertForMultipleChoice,
        FlaxDistilBertForQuestionAnswering,
        FlaxDistilBertForSequenceClassification,
        FlaxDistilBertForTokenClassification,
        FlaxDistilBertModel,
        FlaxDistilBertPreTrainedModel,
    )

else:
  import sys

  __snake_case         =					_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)





