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

      def 				A__       (						self		,       __lowerCAmelCase=0						):







            """simple docstring"""



            lowercase														=	floats_tensor((1, 3, 128, 128)		,       rng=random.Random(__lowerCAmelCase						)						)
            lowercase														=	torch.manual_seed(__lowerCAmelCase						)
            lowercase														=	{
                '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 				A__       (						self						):







            """simple docstring"""



            lowercase														=	OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,       provider="""CPUExecutionProvider"""						)
            pipe.set_progress_bar_config(disable=__lowerCAmelCase						)

            lowercase														=	self.get_dummy_inputs()
            lowercase														=	pipe(**__lowerCAmelCase						).images
            lowercase														=	image[0, -3:, -3:, -1].flatten()

            # started as 128, should now be 512
            assert image.shape == (1, 512, 512, 3)
            lowercase														=	np.array(
                [0.6_9_7_4_7_8_2, 0.6_8_9_0_2_0_9_3, 0.7_0_1_3_5_8_8_5, 0.7_5_8_3_6_1_8, 0.7_8_0_4_5_4_5, 0.7_8_5_4_9_1_2, 0.7_8_6_6_7_4_2_6, 0.7_8_7_4_3_8_6_3, 0.7_8_0_7_0_2_2_3]						)
            assert np.abs(image_slice - expected_slice						).max() < 1E-1

      def 				A__       (						self						):







            """simple docstring"""



            lowercase														=	OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,       provider="""CPUExecutionProvider"""						)
            lowercase														=	PNDMScheduler.from_config(pipe.scheduler.config		,       skip_prk_steps=__lowerCAmelCase						)
            pipe.set_progress_bar_config(disable=__lowerCAmelCase						)

            lowercase														=	self.get_dummy_inputs()
            lowercase														=	pipe(**__lowerCAmelCase						).images
            lowercase														=	image[0, -3:, -3:, -1]

            assert image.shape == (1, 512, 512, 3)
            lowercase														=	np.array(
                [0.6_8_9_8_8_9_2, 0.5_9_2_4_0_5_5_6, 0.5_2_4_9_9_5_2_7, 0.5_8_8_6_6_2_1_5, 0.5_2_2_5_8_2_3_5, 0.5_2_5_7_2_7_1_5, 0.6_2_4_1_4_4_7_3, 0.6_1_7_4_3_8_7, 0.6_2_1_4_9_6_4]						)
            assert np.abs(image_slice.flatten() - expected_slice						).max() < 1E-1

      def 				A__       (						self						):







            """simple docstring"""



            lowercase														=	OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,       provider="""CPUExecutionProvider"""						)
            lowercase														=	DPMSolverMultistepScheduler.from_config(pipe.scheduler.config						)
            pipe.set_progress_bar_config(disable=__lowerCAmelCase						)

            lowercase														=	self.get_dummy_inputs()
            lowercase														=	pipe(**__lowerCAmelCase						).images
            lowercase														=	image[0, -3:, -3:, -1]

            assert image.shape == (1, 512, 512, 3)
            lowercase														=	np.array(
                [0.7_6_5_9_2_7_8, 0.7_6_4_3_7_6_6_4, 0.7_5_5_7_9_1_0_7, 0.7_6_9_1_1_1_6, 0.7_7_6_6_6_9_8_6, 0.7_7_2_7_6_7_2, 0.7_7_5_8_6_6_4, 0.7_8_1_2_2_2_6, 0.7_6_9_4_2_5_1_5]						)

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

      def 				A__       (						self						):







            """simple docstring"""



            lowercase														=	OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,       provider="""CPUExecutionProvider"""						)
            lowercase														=	EulerDiscreteScheduler.from_config(pipe.scheduler.config						)
            pipe.set_progress_bar_config(disable=__lowerCAmelCase						)

            lowercase														=	self.get_dummy_inputs()
            lowercase														=	pipe(**__lowerCAmelCase						).images
            lowercase														=	image[0, -3:, -3:, -1]

            assert image.shape == (1, 512, 512, 3)
            lowercase														=	np.array(
                [0.6_9_7_4_7_8_2, 0.6_8_9_0_2_0_9_3, 0.7_0_1_3_5_8_8_5, 0.7_5_8_3_6_1_8, 0.7_8_0_4_5_4_5, 0.7_8_5_4_9_1_2, 0.7_8_6_6_7_4_2_6, 0.7_8_7_4_3_8_6_3, 0.7_8_0_7_0_2_2_3]						)
            assert np.abs(image_slice.flatten() - expected_slice						).max() < 1E-1







      def 				A__       (						self						):







            """simple docstring"""



            lowercase														=	OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,       provider="""CPUExecutionProvider"""						)
            lowercase														=	EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config						)
            pipe.set_progress_bar_config(disable=__lowerCAmelCase						)

            lowercase														=	self.get_dummy_inputs()
            lowercase														=	pipe(**__lowerCAmelCase						).images
            lowercase														=	image[0, -3:, -3:, -1]

            assert image.shape == (1, 512, 512, 3)
            lowercase														=	np.array(
                [0.7_7_4_2_4_4_9_6, 0.7_7_3_6_0_1, 0.7_6_4_5_2_8_8, 0.7_7_6_9_5_9_8, 0.7_7_7_2_7_3_9, 0.7_7_3_8_6_8_8, 0.7_8_1_8_7_2_3_3, 0.7_7_8_7_9_5_8_4, 0.7_6_7_0_4_3]						)

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






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

      @property
      def 				A__       (						self						):







            """simple docstring"""



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

      @property
      def 				A__       (						self						):







            """simple docstring"""



            lowercase														=	ort.SessionOptions()
            lowercase														=	False
            return options

      def 				A__       (						self						):







            """simple docstring"""



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

            lowercase														=	'A fantasy landscape, trending on artstation'

            lowercase														=	torch.manual_seed(0						)
            lowercase														=	pipe(
                prompt=__lowerCAmelCase		,       image=__lowerCAmelCase		,       guidance_scale=7.5		,       num_inference_steps=10		,       generator=__lowerCAmelCase		,       output_type="""np"""		,       )
            lowercase														=	output.images
            lowercase														=	images[0, 255:258, 383:386, -1]

            assert images.shape == (1, 512, 512, 3)
            lowercase														=	np.array([0.4_8_8_3, 0.4_9_4_7, 0.4_9_8_0, 0.4_9_7_5, 0.4_9_8_2, 0.4_9_8_0, 0.5_0_0_0, 0.5_0_0_6, 0.4_9_7_2]						)
            # 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						):







            """simple docstring"""



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

            lowercase														=	'A fantasy landscape, trending on artstation'

            lowercase														=	torch.manual_seed(0						)
            lowercase														=	pipe(
                prompt=__lowerCAmelCase		,       image=__lowerCAmelCase		,       guidance_scale=7.5		,       num_inference_steps=20		,       generator=__lowerCAmelCase		,       output_type="""np"""		,       )
            lowercase														=	output.images
            lowercase														=	images[0, 255:258, 383:386, -1]

            assert images.shape == (1, 512, 512, 3)
            lowercase														=	np.array(
                [0.5_0_1_7_3_7_5_3, 0.5_0_2_2_3_3_5_6, 0.5_0_2_0_3_9, 0.5_0_2_3_3_0_3_6, 0.5_0_2_3_7_2_5, 0.5_0_2_2_6_0_1, 0.5_0_1_8_7_5_8, 0.5_0_2_3_4_0_8_5, 0.5_0_2_4_1_5_6_6]						)
            # 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()			)



