


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__     ( _lowercase				,		unittest.TestCase  ):



  """simple docstring"""



  _lowercase									=		'ssube/stable-diffusion-x4-upscaler-onnx'

  def    _UpperCamelCase( self			:  str				,				lowerCamelCase__			:  Any=0       ):
        a__	:  int     =   floats_tensor((1, 3, 128, 128)				,				rng=random.Random(_snake_case       )       )
        a__	:  Union[str, Any]     =   torch.manual_seed(_snake_case       )
        a__	:  int     =   {
            "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    _UpperCamelCase( self			:  int       ):
        a__	:  int     =   OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint				,				provider="CPUExecutionProvider"       )
        pipe.set_progress_bar_config(disable=_snake_case       )

        a__	:  Dict     =   self.get_dummy_inputs()
        a__	:  List[Any]     =   pipe(**_snake_case       ).images
        a__	:  Any     =   image[0, -3:, -3:, -1].flatten()

        # started as 128, should now be 512
        assert image.shape == (1, 512, 512, 3)
        a__	:  List[Any]     =   np.array(
            [0.697_4782, 0.6890_2093, 0.7013_5885, 0.758_3618, 0.780_4545, 0.785_4912, 0.7866_7426, 0.7874_3863, 0.7807_0223]       )
        assert np.abs(image_slice - expected_slice       ).max() < 1E-1

  def    _UpperCamelCase( self			:  Optional[int]       ):
        a__	:  Optional[Any]     =   OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint				,				provider="CPUExecutionProvider"       )
        a__	:  int     =   PNDMScheduler.from_config(pipe.scheduler.config				,				skip_prk_steps=_snake_case       )
        pipe.set_progress_bar_config(disable=_snake_case       )

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

        assert image.shape == (1, 512, 512, 3)
        a__	:  str     =   np.array(
            [0.689_8892, 0.5924_0556, 0.5249_9527, 0.5886_6215, 0.5225_8235, 0.5257_2715, 0.6241_4473, 0.617_4387, 0.621_4964]       )
        assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1E-1

  def    _UpperCamelCase( self			:  int       ):
        a__	:  Optional[Any]     =   OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint				,				provider="CPUExecutionProvider"       )
        a__	:  Optional[Any]     =   DPMSolverMultistepScheduler.from_config(pipe.scheduler.config       )
        pipe.set_progress_bar_config(disable=_snake_case       )

        a__	:  List[Any]     =   self.get_dummy_inputs()
        a__	:  Tuple     =   pipe(**_snake_case       ).images
        a__	:  str     =   image[0, -3:, -3:, -1]

        assert image.shape == (1, 512, 512, 3)
        a__	:  int     =   np.array(
            [0.765_9278, 0.7643_7664, 0.7557_9107, 0.769_1116, 0.7766_6986, 0.772_7672, 0.775_8664, 0.781_2226, 0.7694_2515]       )

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

  def    _UpperCamelCase( self			:  Tuple       ):
        a__	:  Optional[int]     =   OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint				,				provider="CPUExecutionProvider"       )
        a__	:  Optional[int]     =   EulerDiscreteScheduler.from_config(pipe.scheduler.config       )
        pipe.set_progress_bar_config(disable=_snake_case       )

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

        assert image.shape == (1, 512, 512, 3)
        a__	:  int     =   np.array(
            [0.697_4782, 0.6890_2093, 0.7013_5885, 0.758_3618, 0.780_4545, 0.785_4912, 0.7866_7426, 0.7874_3863, 0.7807_0223]       )
        assert np.abs(image_slice.flatten() - expected_slice       ).max() < 1E-1

  def    _UpperCamelCase( self			:  Tuple       ):
        a__	:  int     =   OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint				,				provider="CPUExecutionProvider"       )
        a__	:  List[str]     =   EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config       )
        pipe.set_progress_bar_config(disable=_snake_case       )

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

        assert image.shape == (1, 512, 512, 3)
        a__	:  Optional[Any]     =   np.array(
            [0.7742_4496, 0.77_3601, 0.764_5288, 0.776_9598, 0.777_2739, 0.773_8688, 0.7818_7233, 0.7787_9584, 0.76_7043]       )

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




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



  """simple docstring"""



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

  @property
  def    _UpperCamelCase( self			:  Union[str, Any]       ):
        a__	:  Any     =   ort.SessionOptions()
        a__	:  int     =   False
        return options

  def    _UpperCamelCase( self			:  int       ):
        a__	:  int     =   load_image(
            "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
            "/img2img/sketch-mountains-input.jpg"       )
        a__	:  Union[str, Any]     =   init_image.resize((128, 128)       )
        # using the PNDM scheduler by default
        a__	:  Any     =   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       )

        a__	:  str     =   "A fantasy landscape, trending on artstation"

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

        assert images.shape == (1, 512, 512, 3)
        a__	:  Dict     =   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    _UpperCamelCase( self			:  Optional[int]       ):
        a__	:  Union[str, Any]     =   load_image(
            "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
            "/img2img/sketch-mountains-input.jpg"       )
        a__	:  int     =   init_image.resize((128, 128)       )
        a__	:  Any     =   LMSDiscreteScheduler.from_pretrained(
            "ssube/stable-diffusion-x4-upscaler-onnx"				,				subfolder="scheduler"       )
        a__	:  Dict     =   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       )

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

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

        assert images.shape == (1, 512, 512, 3)
        a__	:  List[Any]     =   np.array(
            [0.5017_3753, 0.5022_3356, 0.50_2039, 0.5023_3036, 0.502_3725, 0.502_2601, 0.501_8758, 0.5023_4085, 0.5024_1566]       )
        # 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"""





import shutil
import tempfile
import unittest
from unittest.mock import patch

from transformers import (
    DefaultFlowCallback,
    IntervalStrategy,
    PrinterCallback,
    ProgressCallback,
    Trainer,
    TrainerCallback,
    TrainingArguments,
    is_torch_available,
)
from transformers.testing_utils import require_torch


if is_torch_available():
		from transformers.trainer import DEFAULT_CALLBACKS

		from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel



class __lowerCAmelCase					(       _lowercase   ):




			"""simple docstring"""







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







								"""simple docstring"""
								A_								=    []




			def   lowerCamelCase__  (					self    :       Tuple							, _snake_case    :       List[str]							, _snake_case    :       Optional[int]							, _snake_case    :       Optional[int]							, **_snake_case    :       str						)   ->			int:







								"""simple docstring"""
								self.events.append("on_init_end"						)




			def   lowerCamelCase__  (					self    :       Dict							, _snake_case    :       Union[str, Any]							, _snake_case    :       List[Any]							, _snake_case    :       Tuple							, **_snake_case    :       Tuple						)   ->			List[str]:







								"""simple docstring"""
								self.events.append("on_train_begin"						)




			def   lowerCamelCase__  (					self    :       List[Any]							, _snake_case    :       Any							, _snake_case    :       Optional[Any]							, _snake_case    :       Tuple							, **_snake_case    :       Optional[int]						)   ->			str:







								"""simple docstring"""
								self.events.append("on_train_end"						)




			def   lowerCamelCase__  (					self    :       Dict							, _snake_case    :       str							, _snake_case    :       List[Any]							, _snake_case    :       str							, **_snake_case    :       Optional[int]						)   ->			Dict:







								"""simple docstring"""
								self.events.append("on_epoch_begin"						)




			def   lowerCamelCase__  (					self    :       Optional[int]							, _snake_case    :       Optional[int]							, _snake_case    :       Any							, _snake_case    :       Optional[Any]							, **_snake_case    :       Optional[Any]						)   ->			str:







								"""simple docstring"""
								self.events.append("on_epoch_end"						)




			def   lowerCamelCase__  (					self    :       List[Any]							, _snake_case    :       List[str]							, _snake_case    :       str							, _snake_case    :       Optional[Any]							, **_snake_case    :       Optional[int]						)   ->			List[str]:







								"""simple docstring"""
								self.events.append("on_step_begin"						)




			def   lowerCamelCase__  (					self    :       Optional[Any]							, _snake_case    :       Union[str, Any]							, _snake_case    :       Optional[Any]							, _snake_case    :       Any							, **_snake_case    :       Union[str, Any]						)   ->			List[str]:







								"""simple docstring"""
								self.events.append("on_step_end"						)




			def   lowerCamelCase__  (					self    :       Tuple							, _snake_case    :       Dict							, _snake_case    :       Dict							, _snake_case    :       Union[str, Any]							, **_snake_case    :       List[str]						)   ->			Optional[int]:







								"""simple docstring"""
								self.events.append("on_evaluate"						)




			def   lowerCamelCase__  (					self    :       Optional[int]							, _snake_case    :       Optional[Any]							, _snake_case    :       int							, _snake_case    :       int							, **_snake_case    :       List[Any]						)   ->			List[str]:







								"""simple docstring"""
								self.events.append("on_predict"						)




			def   lowerCamelCase__  (					self    :       List[str]							, _snake_case    :       Union[str, Any]							, _snake_case    :       List[str]							, _snake_case    :       Optional[Any]							, **_snake_case    :       List[Any]						)   ->			Union[str, Any]:







								"""simple docstring"""
								self.events.append("on_save"						)




			def   lowerCamelCase__  (					self    :       Dict							, _snake_case    :       Dict							, _snake_case    :       List[Any]							, _snake_case    :       Optional[int]							, **_snake_case    :       Dict						)   ->			str:







								"""simple docstring"""
								self.events.append("on_log"						)






			def   lowerCamelCase__  (					self    :       Tuple							, _snake_case    :       Optional[Any]							, _snake_case    :       str							, _snake_case    :       int							, **_snake_case    :       List[Any]						)   ->			int:







								"""simple docstring"""
								self.events.append("on_prediction_step"						)





@require_torch
class __lowerCAmelCase					(       unittest.TestCase   ):




			"""simple docstring"""







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







								"""simple docstring"""
								A_								=    tempfile.mkdtemp()




			def   lowerCamelCase__  (					self    :       str						)   ->			Tuple:







								"""simple docstring"""
								shutil.rmtree(self.output_dir						)




			def   lowerCamelCase__  (					self    :       List[str]							, _snake_case    :       Any=0							, _snake_case    :       Optional[int]=0							, _snake_case    :       int=64							, _snake_case    :       Optional[int]=64							, _snake_case    :       List[Any]=None							, _snake_case    :       List[Any]=False							, **_snake_case    :       Optional[int]						)   ->			List[Any]:







								"""simple docstring"""
								# disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure
								# its set to False since the tests later on depend on its value.
								A_								=    RegressionDataset(length=_snake_case						)
								A_								=    RegressionDataset(length=_snake_case						)
								A_								=    RegressionModelConfig(a=_snake_case							, b=_snake_case						)
								A_								=    RegressionPreTrainedModel(_snake_case						)

								A_								=    TrainingArguments(self.output_dir							, disable_tqdm=_snake_case							, report_to=[]							, **_snake_case						)
								return Trainer(
								    _snake_case							, _snake_case							, train_dataset=_snake_case							, eval_dataset=_snake_case							, callbacks=_snake_case							, )




			def   lowerCamelCase__  (					self    :       List[Any]							, _snake_case    :       Optional[Any]							, _snake_case    :       List[Any]						)   ->			Union[str, Any]:







								"""simple docstring"""
								self.assertEqual(len(_snake_case						)							, len(_snake_case						)						)

								# Order doesn't matter
								A_								=    sorted(_snake_case							, key=lambda _snake_case						: cb.__name__ if isinstance(_snake_case							, _snake_case						) else cb.__class__.__name__						)
								A_								=    sorted(_snake_case							, key=lambda _snake_case						: cb.__name__ if isinstance(_snake_case							, _snake_case						) else cb.__class__.__name__						)

								for cba, cba in zip(_snake_case							, _snake_case						):
													if isinstance(_snake_case							, _snake_case						) and isinstance(_snake_case							, _snake_case						):
																		self.assertEqual(_snake_case							, _snake_case						)
													elif isinstance(_snake_case							, _snake_case						) and not isinstance(_snake_case							, _snake_case						):
																		self.assertEqual(_snake_case							, cba.__class__						)
													elif not isinstance(_snake_case							, _snake_case						) and isinstance(_snake_case							, _snake_case						):
																		self.assertEqual(cba.__class__							, _snake_case						)
													else:
																		self.assertEqual(_snake_case							, _snake_case						)




			def   lowerCamelCase__  (					self    :       List[Any]							, _snake_case    :       Union[str, Any]						)   ->			Optional[Any]:







								"""simple docstring"""
								A_								=    ["on_init_end", "on_train_begin"]
								A_								=    0
								A_								=    len(trainer.get_eval_dataloader()						)
								A_								=    ["on_prediction_step"] * len(trainer.get_eval_dataloader()						) + ["on_log", "on_evaluate"]
								for _ in range(trainer.state.num_train_epochs						):
													expected_events.append("on_epoch_begin"						)
													for _ in range(_snake_case						):
																		step += 1
																		expected_events += ["on_step_begin", "on_step_end"]
																		if step % trainer.args.logging_steps == 0:
																							expected_events.append("on_log"						)
																		if trainer.args.evaluation_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0:
																							expected_events += evaluation_events.copy()
																		if step % trainer.args.save_steps == 0:
																							expected_events.append("on_save"						)
													expected_events.append("on_epoch_end"						)
													if trainer.args.evaluation_strategy == IntervalStrategy.EPOCH:
																		expected_events += evaluation_events.copy()
								expected_events += ["on_log", "on_train_end"]
								return expected_events




			def   lowerCamelCase__  (					self    :       List[Any]						)   ->			int:







								"""simple docstring"""
								A_								=    self.get_trainer()
								A_								=    DEFAULT_CALLBACKS.copy() + [ProgressCallback]
								self.check_callbacks_equality(trainer.callback_handler.callbacks							, _snake_case						)

								# Callbacks passed at init are added to the default callbacks
								A_								=    self.get_trainer(callbacks=[MyTestTrainerCallback]						)
								expected_callbacks.append(_snake_case						)
								self.check_callbacks_equality(trainer.callback_handler.callbacks							, _snake_case						)

								# TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback
								A_								=    self.get_trainer(disable_tqdm=_snake_case						)
								A_								=    DEFAULT_CALLBACKS.copy() + [PrinterCallback]
								self.check_callbacks_equality(trainer.callback_handler.callbacks							, _snake_case						)




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







								"""simple docstring"""
								A_								=    DEFAULT_CALLBACKS.copy() + [ProgressCallback]
								A_								=    self.get_trainer()

								# We can add, pop, or remove by class name
								trainer.remove_callback(_snake_case						)
								expected_callbacks.remove(_snake_case						)
								self.check_callbacks_equality(trainer.callback_handler.callbacks							, _snake_case						)

								A_								=    self.get_trainer()
								A_								=    trainer.pop_callback(_snake_case						)
								self.assertEqual(cb.__class__							, _snake_case						)
								self.check_callbacks_equality(trainer.callback_handler.callbacks							, _snake_case						)

								trainer.add_callback(_snake_case						)
								expected_callbacks.insert(0							, _snake_case						)
								self.check_callbacks_equality(trainer.callback_handler.callbacks							, _snake_case						)

								# We can also add, pop, or remove by instance
								A_								=    self.get_trainer()
								A_								=    trainer.callback_handler.callbacks[0]
								trainer.remove_callback(_snake_case						)
								expected_callbacks.remove(_snake_case						)
								self.check_callbacks_equality(trainer.callback_handler.callbacks							, _snake_case						)

								A_								=    self.get_trainer()
								A_								=    trainer.callback_handler.callbacks[0]
								A_								=    trainer.pop_callback(_snake_case						)
								self.assertEqual(_snake_case							, _snake_case						)
								self.check_callbacks_equality(trainer.callback_handler.callbacks							, _snake_case						)

								trainer.add_callback(_snake_case						)
								expected_callbacks.insert(0							, _snake_case						)
								self.check_callbacks_equality(trainer.callback_handler.callbacks							, _snake_case						)






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







								"""simple docstring"""
								import warnings

								# XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested
								warnings.simplefilter(action="ignore"							, category=_snake_case						)

								A_								=    self.get_trainer(callbacks=[MyTestTrainerCallback]						)
								trainer.train()
								A_								=    trainer.callback_handler.callbacks[-2].events
								self.assertEqual(_snake_case							, self.get_expected_events(_snake_case						)						)

								# Independent log/save/eval
								A_								=    self.get_trainer(callbacks=[MyTestTrainerCallback]							, logging_steps=5						)
								trainer.train()
								A_								=    trainer.callback_handler.callbacks[-2].events
								self.assertEqual(_snake_case							, self.get_expected_events(_snake_case						)						)

								A_								=    self.get_trainer(callbacks=[MyTestTrainerCallback]							, save_steps=5						)
								trainer.train()
								A_								=    trainer.callback_handler.callbacks[-2].events
								self.assertEqual(_snake_case							, self.get_expected_events(_snake_case						)						)

								A_								=    self.get_trainer(callbacks=[MyTestTrainerCallback]							, eval_steps=5							, evaluation_strategy="steps"						)
								trainer.train()
								A_								=    trainer.callback_handler.callbacks[-2].events
								self.assertEqual(_snake_case							, self.get_expected_events(_snake_case						)						)

								A_								=    self.get_trainer(callbacks=[MyTestTrainerCallback]							, evaluation_strategy="epoch"						)
								trainer.train()
								A_								=    trainer.callback_handler.callbacks[-2].events
								self.assertEqual(_snake_case							, self.get_expected_events(_snake_case						)						)

								# A bit of everything
								A_								=    self.get_trainer(
								    callbacks=[MyTestTrainerCallback]							, logging_steps=3							, save_steps=10							, eval_steps=5							, evaluation_strategy="steps"							, )
								trainer.train()
								A_								=    trainer.callback_handler.callbacks[-2].events
								self.assertEqual(_snake_case							, self.get_expected_events(_snake_case						)						)

								# warning should be emitted for duplicated callbacks
								with patch("transformers.trainer_callback.logger.warning"						) as warn_mock:
													A_								=    self.get_trainer(
													    callbacks=[MyTestTrainerCallback, MyTestTrainerCallback]							, )
													assert str(_snake_case						) in warn_mock.call_args[0][0]




