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 		_lowercase						(					snake_case_						,      unittest.TestCase       ):
 # TODO: is there an appropriate internal test set?
 lowercase				     =   'ssube/stable-diffusion-x4-upscaler-onnx'

 def 						SCREAMING_SNAKE_CASE__   ( self	:							Tuple   ,      snake_case	:							List[Any]=0			)   ->						Any:

  """simple docstring"""





  UpperCamelCase_					:						Dict =					floats_tensor((1, 3, 1_2_8, 1_2_8)   ,      rng=random.Random(snake_case			)			)
  UpperCamelCase_					:						List[Any] =					torch.manual_seed(snake_case			)
  UpperCamelCase_					:						List[Any] =					{
      '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 						SCREAMING_SNAKE_CASE__   ( self	:							Optional[Any]			)   ->						Tuple:

  """simple docstring"""





  UpperCamelCase_					:						Optional[Any] =					OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint   ,      provider='CPUExecutionProvider'			)
  pipe.set_progress_bar_config(disable=snake_case			)

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

  # started as 128, should now be 512
  assert image.shape == (1, 5_1_2, 5_1_2, 3)
  UpperCamelCase_					:						Any =					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 						SCREAMING_SNAKE_CASE__   ( self	:							Dict			)   ->						Tuple:

  """simple docstring"""





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

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

  assert image.shape == (1, 5_1_2, 5_1_2, 3)
  UpperCamelCase_					:						List[str] =					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 						SCREAMING_SNAKE_CASE__   ( self	:							Optional[int]			)   ->						Union[str, Any]:

  """simple docstring"""





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

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

  assert image.shape == (1, 5_1_2, 5_1_2, 3)
  UpperCamelCase_					:						Any =					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 						SCREAMING_SNAKE_CASE__   ( self	:							Tuple			)   ->						Tuple:

  """simple docstring"""





  UpperCamelCase_					:						int =					OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint   ,      provider='CPUExecutionProvider'			)
  UpperCamelCase_					:						int =					EulerDiscreteScheduler.from_config(pipe.scheduler.config			)
  pipe.set_progress_bar_config(disable=snake_case			)

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

  assert image.shape == (1, 5_1_2, 5_1_2, 3)
  UpperCamelCase_					:						int =					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 						SCREAMING_SNAKE_CASE__   ( self	:							List[Any]			)   ->						List[Any]:

  """simple docstring"""





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

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

  assert image.shape == (1, 5_1_2, 5_1_2, 3)
  UpperCamelCase_					:						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 		_lowercase						(					unittest.TestCase       ):

 @property
 def 						SCREAMING_SNAKE_CASE__   ( self	:							Union[str, Any]			)   ->						Any:

  """simple docstring"""





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

 @property
 def 						SCREAMING_SNAKE_CASE__   ( self	:							int			)   ->						Tuple:

  """simple docstring"""





  UpperCamelCase_					:						Any =					ort.SessionOptions()
  UpperCamelCase_					:						Optional[Any] =					False
  return options

 def 						SCREAMING_SNAKE_CASE__   ( self	:							List[str]			)   ->						int:

  """simple docstring"""





  UpperCamelCase_					:						Any =					load_image(
      'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
      '/img2img/sketch-mountains-input.jpg'			)
  UpperCamelCase_					:						List[str] =					init_image.resize((1_2_8, 1_2_8)			)
  # using the PNDM scheduler by default
  UpperCamelCase_					:						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=snake_case			)

  UpperCamelCase_					:						int =					'A fantasy landscape, trending on artstation'

  UpperCamelCase_					:						Optional[Any] =					torch.manual_seed(0			)
  UpperCamelCase_					:						Union[str, Any] =					pipe(
      prompt=snake_case   ,      image=snake_case   ,      guidance_scale=7.5   ,      num_inference_steps=1_0   ,      generator=snake_case   ,      output_type='np'   ,      )
  UpperCamelCase_					:						str =					output.images
  UpperCamelCase_					:						Optional[Any] =					images[0, 2_5_5:2_5_8, 3_8_3:3_8_6, -1]

  assert images.shape == (1, 5_1_2, 5_1_2, 3)
  UpperCamelCase_					:						Tuple =					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 						SCREAMING_SNAKE_CASE__   ( self	:							Any			)   ->						Any:

  """simple docstring"""





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

  UpperCamelCase_					:						int =					'A fantasy landscape, trending on artstation'

  UpperCamelCase_					:						Any =					torch.manual_seed(0			)
  UpperCamelCase_					:						Optional[int] =					pipe(
      prompt=snake_case   ,      image=snake_case   ,      guidance_scale=7.5   ,      num_inference_steps=2_0   ,      generator=snake_case   ,      output_type='np'   ,      )
  UpperCamelCase_					:						Tuple =					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, 5_1_2, 3)
  UpperCamelCase_					:						List[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




import os
import tempfile
import unittest
from pathlib import Path

from transformers import AutoConfig, is_tf_available
from transformers.testing_utils import require_tf


if is_tf_available():
   import tensorflow as tf

   from transformers import TensorFlowBenchmark, TensorFlowBenchmarkArguments





@require_tf
class 		_lowercase						(					unittest.TestCase       ):

 def 						SCREAMING_SNAKE_CASE__   ( self	:							int   ,      snake_case	:							Union[str, Any]			)   ->						Optional[int]:

  """simple docstring"""





  for model_result in results.values():
   for batch_size, sequence_length in zip(model_result['bs']   ,      model_result['ss']			):
    UpperCamelCase_					:						Optional[Any] =					model_result['result'][batch_size][sequence_length]
    self.assertIsNotNone(snake_case			)

 def 						SCREAMING_SNAKE_CASE__   ( self	:							int			)   ->						Tuple:

  """simple docstring"""





  UpperCamelCase_					:						Optional[Any] =					'sshleifer/tiny-gpt2'
  UpperCamelCase_					:						Dict =					TensorFlowBenchmarkArguments(
      models=[MODEL_ID]   ,      training=snake_case   ,      inference=snake_case   ,      sequence_lengths=[8]   ,      batch_sizes=[1]   ,      eager_mode=snake_case   ,      multi_process=snake_case   ,      )
  UpperCamelCase_					:						Tuple =					TensorFlowBenchmark(snake_case			)
  UpperCamelCase_					:						List[str] =					benchmark.run()
  self.check_results_dict_not_empty(results.time_inference_result			)
  self.check_results_dict_not_empty(results.memory_inference_result			)

 def 						SCREAMING_SNAKE_CASE__   ( self	:							str			)   ->						Optional[Any]:

  """simple docstring"""





  UpperCamelCase_					:						Dict =					'sgugger/tiny-distilbert-classification'
  UpperCamelCase_					:						int =					TensorFlowBenchmarkArguments(
      models=[MODEL_ID]   ,      training=snake_case   ,      inference=snake_case   ,      sequence_lengths=[8]   ,      batch_sizes=[1]   ,      multi_process=snake_case   ,      only_pretrain_model=snake_case   ,      )
  UpperCamelCase_					:						int =					TensorFlowBenchmark(snake_case			)
  UpperCamelCase_					:						Tuple =					benchmark.run()
  self.check_results_dict_not_empty(results.time_inference_result			)
  self.check_results_dict_not_empty(results.memory_inference_result			)

 def 						SCREAMING_SNAKE_CASE__   ( self	:							Tuple			)   ->						List[str]:

  """simple docstring"""





  UpperCamelCase_					:						str =					'sshleifer/tiny-gpt2'
  UpperCamelCase_					:						Any =					TensorFlowBenchmarkArguments(
      models=[MODEL_ID]   ,      training=snake_case   ,      inference=snake_case   ,      sequence_lengths=[8]   ,      batch_sizes=[1]   ,      multi_process=snake_case   ,      )
  UpperCamelCase_					:						List[str] =					TensorFlowBenchmark(snake_case			)
  UpperCamelCase_					:						Optional[int] =					benchmark.run()
  self.check_results_dict_not_empty(results.time_inference_result			)
  self.check_results_dict_not_empty(results.memory_inference_result			)

 def 						SCREAMING_SNAKE_CASE__   ( self	:							Tuple			)   ->						Dict:

  """simple docstring"""





  UpperCamelCase_					:						List[str] =					'sshleifer/tiny-gpt2'
  UpperCamelCase_					:						str =					AutoConfig.from_pretrained(snake_case			)
  UpperCamelCase_					:						List[str] =					TensorFlowBenchmarkArguments(
      models=[MODEL_ID]   ,      training=snake_case   ,      inference=snake_case   ,      sequence_lengths=[8]   ,      batch_sizes=[1]   ,      eager_mode=snake_case   ,      multi_process=snake_case   ,      )
  UpperCamelCase_					:						int =					TensorFlowBenchmark(snake_case   ,      [config]			)
  UpperCamelCase_					:						Optional[Any] =					benchmark.run()
  self.check_results_dict_not_empty(results.time_inference_result			)
  self.check_results_dict_not_empty(results.memory_inference_result			)

 def 						SCREAMING_SNAKE_CASE__   ( self	:							Optional[Any]			)   ->						List[str]:

  """simple docstring"""





  UpperCamelCase_					:						List[str] =					'sshleifer/tiny-gpt2'
  UpperCamelCase_					:						int =					AutoConfig.from_pretrained(snake_case			)
  UpperCamelCase_					:						Any =					TensorFlowBenchmarkArguments(
      models=[MODEL_ID]   ,      training=snake_case   ,      inference=snake_case   ,      sequence_lengths=[8]   ,      batch_sizes=[1]   ,      multi_process=snake_case   ,      )
  UpperCamelCase_					:						Tuple =					TensorFlowBenchmark(snake_case   ,      [config]			)
  UpperCamelCase_					:						Tuple =					benchmark.run()
  self.check_results_dict_not_empty(results.time_inference_result			)
  self.check_results_dict_not_empty(results.memory_inference_result			)

 def 						SCREAMING_SNAKE_CASE__   ( self	:							Tuple			)   ->						int:

  """simple docstring"""





  UpperCamelCase_					:						Optional[int] =					'sshleifer/tiny-gpt2'
  UpperCamelCase_					:						Tuple =					TensorFlowBenchmarkArguments(
      models=[MODEL_ID]   ,      training=snake_case   ,      inference=snake_case   ,      sequence_lengths=[8]   ,      batch_sizes=[1]   ,      multi_process=snake_case   ,      )
  UpperCamelCase_					:						Optional[int] =					TensorFlowBenchmark(snake_case			)
  UpperCamelCase_					:						str =					benchmark.run()
  self.check_results_dict_not_empty(results.time_train_result			)
  self.check_results_dict_not_empty(results.memory_train_result			)

 def 						SCREAMING_SNAKE_CASE__   ( self	:							Any			)   ->						int:

  """simple docstring"""





  UpperCamelCase_					:						Tuple =					'sshleifer/tiny-gpt2'
  UpperCamelCase_					:						List[str] =					AutoConfig.from_pretrained(snake_case			)
  UpperCamelCase_					:						int =					TensorFlowBenchmarkArguments(
      models=[MODEL_ID]   ,      training=snake_case   ,      inference=snake_case   ,      sequence_lengths=[8]   ,      batch_sizes=[1]   ,      multi_process=snake_case   ,      )
  UpperCamelCase_					:						List[Any] =					TensorFlowBenchmark(snake_case   ,      [config]			)
  UpperCamelCase_					:						int =					benchmark.run()
  self.check_results_dict_not_empty(results.time_train_result			)
  self.check_results_dict_not_empty(results.memory_train_result			)

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

  """simple docstring"""





  UpperCamelCase_					:						Tuple =					'patrickvonplaten/t5-tiny-random'
  UpperCamelCase_					:						List[str] =					AutoConfig.from_pretrained(snake_case			)
  UpperCamelCase_					:						List[str] =					TensorFlowBenchmarkArguments(
      models=[MODEL_ID]   ,      training=snake_case   ,      inference=snake_case   ,      sequence_lengths=[8]   ,      batch_sizes=[1]   ,      multi_process=snake_case   ,      )
  UpperCamelCase_					:						int =					TensorFlowBenchmark(snake_case   ,      configs=[config]			)
  UpperCamelCase_					:						Optional[Any] =					benchmark.run()
  self.check_results_dict_not_empty(results.time_inference_result			)
  self.check_results_dict_not_empty(results.memory_inference_result			)

 @unittest.skipIf(is_tf_available() and len(tf.config.list_physical_devices('GPU'			)			) == 0   ,      'Cannot do xla on CPU.'			)
 def 						SCREAMING_SNAKE_CASE__   ( self	:							Optional[int]			)   ->						Dict:

  """simple docstring"""





  UpperCamelCase_					:						int =					'sshleifer/tiny-gpt2'
  UpperCamelCase_					:						Union[str, Any] =					TensorFlowBenchmarkArguments(
      models=[MODEL_ID]   ,      training=snake_case   ,      inference=snake_case   ,      sequence_lengths=[8]   ,      batch_sizes=[1]   ,      use_xla=snake_case   ,      multi_process=snake_case   ,      )
  UpperCamelCase_					:						Union[str, Any] =					TensorFlowBenchmark(snake_case			)
  UpperCamelCase_					:						List[str] =					benchmark.run()
  self.check_results_dict_not_empty(results.time_inference_result			)
  self.check_results_dict_not_empty(results.memory_inference_result			)

 def 						SCREAMING_SNAKE_CASE__   ( self	:							List[str]			)   ->						Optional[int]:

  """simple docstring"""





  UpperCamelCase_					:						List[Any] =					'sshleifer/tiny-gpt2'
  with tempfile.TemporaryDirectory() as tmp_dir:
   UpperCamelCase_					:						List[Any] =					TensorFlowBenchmarkArguments(
       models=[MODEL_ID]   ,      inference=snake_case   ,      save_to_csv=snake_case   ,      sequence_lengths=[8]   ,      batch_sizes=[1]   ,      inference_time_csv_file=os.path.join(snake_case   ,      'inf_time.csv'			)   ,      inference_memory_csv_file=os.path.join(snake_case   ,      'inf_mem.csv'			)   ,      env_info_csv_file=os.path.join(snake_case   ,      'env.csv'			)   ,      multi_process=snake_case   ,      )
   UpperCamelCase_					:						List[str] =					TensorFlowBenchmark(snake_case			)
   benchmark.run()
   self.assertTrue(Path(os.path.join(snake_case   ,      'inf_time.csv'			)			).exists()			)
   self.assertTrue(Path(os.path.join(snake_case   ,      'inf_mem.csv'			)			).exists()			)
   self.assertTrue(Path(os.path.join(snake_case   ,      'env.csv'			)			).exists()			)


 def 						SCREAMING_SNAKE_CASE__   ( self	:							List[str]			)   ->						str:

  """simple docstring"""





  UpperCamelCase_					:						Optional[Any] =					'sshleifer/tiny-gpt2'

  def _check_summary_is_not_empty(snake_case	:							Union[str, Any]			):
   self.assertTrue(hasattr(snake_case   ,      'sequential'			)			)
   self.assertTrue(hasattr(snake_case   ,      'cumulative'			)			)
   self.assertTrue(hasattr(snake_case   ,      'current'			)			)
   self.assertTrue(hasattr(snake_case   ,      'total'			)			)

  with tempfile.TemporaryDirectory() as tmp_dir:
   UpperCamelCase_					:						str =					TensorFlowBenchmarkArguments(
       models=[MODEL_ID]   ,      inference=snake_case   ,      sequence_lengths=[8]   ,      batch_sizes=[1]   ,      log_filename=os.path.join(snake_case   ,      'log.txt'			)   ,      log_print=snake_case   ,      trace_memory_line_by_line=snake_case   ,      eager_mode=snake_case   ,      multi_process=snake_case   ,      )
   UpperCamelCase_					:						Tuple =					TensorFlowBenchmark(snake_case			)
   UpperCamelCase_					:						Union[str, Any] =					benchmark.run()
   _check_summary_is_not_empty(result.inference_summary			)
   self.assertTrue(Path(os.path.join(snake_case   ,      'log.txt'			)			).exists()			)



