




"""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__      (							lowerCamelCase__       ,						unittest.TestCase	):
						snake_case__							   =			"""ssube/stable-diffusion-x4-upscaler-onnx"""





						def    __UpperCamelCase  (				self   :						Optional[int]  ,a__   :						str=0)    ->							List[Any]:




											"""simple docstring"""







											_lowerCAmelCase:Any						=	floats_tensor((1, 3, 128, 128)  ,rng=random.Random(snake_case__))
											_lowerCAmelCase:int						=	torch.manual_seed(snake_case__)
											_lowerCAmelCase: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   :						Dict)    ->							Any:




											"""simple docstring"""







											_lowerCAmelCase:Optional[int]						=	OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint  ,provider='''CPUExecutionProvider''')
											pipe.set_progress_bar_config(disable=snake_case__)

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

											# started as 128, should now be 512
											assert image.shape == (1, 512, 512, 3)
											_lowerCAmelCase:Optional[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    __UpperCamelCase  (				self   :						Union[str, Any])    ->							Dict:




											"""simple docstring"""







											_lowerCAmelCase:Optional[int]						=	OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint  ,provider='''CPUExecutionProvider''')
											_lowerCAmelCase:Union[str, Any]						=	PNDMScheduler.from_config(pipe.scheduler.config  ,skip_prk_steps=snake_case__)
											pipe.set_progress_bar_config(disable=snake_case__)

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

											assert image.shape == (1, 512, 512, 3)
											_lowerCAmelCase: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    __UpperCamelCase  (				self   :						Union[str, Any])    ->							Optional[int]:




											"""simple docstring"""







											_lowerCAmelCase:Any						=	OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint  ,provider='''CPUExecutionProvider''')
											_lowerCAmelCase:Union[str, Any]						=	DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
											pipe.set_progress_bar_config(disable=snake_case__)

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

											assert image.shape == (1, 512, 512, 3)
											_lowerCAmelCase:Optional[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    __UpperCamelCase  (				self   :						str)    ->							Optional[int]:




											"""simple docstring"""







											_lowerCAmelCase:str						=	OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint  ,provider='''CPUExecutionProvider''')
											_lowerCAmelCase:List[str]						=	EulerDiscreteScheduler.from_config(pipe.scheduler.config)
											pipe.set_progress_bar_config(disable=snake_case__)

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

											assert image.shape == (1, 512, 512, 3)
											_lowerCAmelCase:Optional[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.flatten() - expected_slice).max() < 1E-1







						def    __UpperCamelCase  (				self   :						int)    ->							Optional[Any]:




											"""simple docstring"""







											_lowerCAmelCase:Tuple						=	OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint  ,provider='''CPUExecutionProvider''')
											_lowerCAmelCase:str						=	EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config)
											pipe.set_progress_bar_config(disable=snake_case__)

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

											assert image.shape == (1, 512, 512, 3)
											_lowerCAmelCase: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 	a__      (							unittest.TestCase	):





						@property
						def    __UpperCamelCase  (				self   :						Optional[Any])    ->							Tuple:




											"""simple docstring"""







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





						@property
						def    __UpperCamelCase  (				self   :						Optional[Any])    ->							Dict:




											"""simple docstring"""







											_lowerCAmelCase:Union[str, Any]						=	ort.SessionOptions()
											_lowerCAmelCase:Optional[Any]						=	False
											return options





						def    __UpperCamelCase  (				self   :						Dict)    ->							Tuple:




											"""simple docstring"""







											_lowerCAmelCase:Dict						=	load_image(
											    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
											    '''/img2img/sketch-mountains-input.jpg''')
											_lowerCAmelCase:Tuple						=	init_image.resize((128, 128))
											# using the PNDM scheduler by default
											_lowerCAmelCase: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__)

											_lowerCAmelCase:int						=	"""A fantasy landscape, trending on artstation"""

											_lowerCAmelCase:str						=	torch.manual_seed(0)
											_lowerCAmelCase:str						=	pipe(
											    prompt=snake_case__  ,image=snake_case__  ,guidance_scale=7.5  ,num_inference_steps=10  ,generator=snake_case__  ,output_type='''np'''  ,)
											_lowerCAmelCase:List[Any]						=	output.images
											_lowerCAmelCase:Dict						=	images[0, 255:258, 383:386, -1]

											assert images.shape == (1, 512, 512, 3)
											_lowerCAmelCase:Union[str, Any]						=	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])    ->							str:




											"""simple docstring"""







											_lowerCAmelCase:str						=	load_image(
											    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
											    '''/img2img/sketch-mountains-input.jpg''')
											_lowerCAmelCase:Optional[int]						=	init_image.resize((128, 128))
											_lowerCAmelCase:List[str]						=	LMSDiscreteScheduler.from_pretrained(
											    '''ssube/stable-diffusion-x4-upscaler-onnx'''  ,subfolder='''scheduler''')
											_lowerCAmelCase:Union[str, 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__)

											_lowerCAmelCase:Union[str, Any]						=	"""A fantasy landscape, trending on artstation"""

											_lowerCAmelCase:str						=	torch.manual_seed(0)
											_lowerCAmelCase:str						=	pipe(
											    prompt=snake_case__  ,image=snake_case__  ,guidance_scale=7.5  ,num_inference_steps=20  ,generator=snake_case__  ,output_type='''np'''  ,)
											_lowerCAmelCase:Optional[Any]						=	output.images
											_lowerCAmelCase:Any						=	images[0, 255:258, 383:386, -1]

											assert images.shape == (1, 512, 512, 3)
											_lowerCAmelCase: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













def  __magic_name__  (				lowercase				)				-> list[list]:

							"""simple docstring"""



							lowercase_	:   int  				=     current_set.copy()
							for row_index, row in enumerate(lowercase				):
														lowercase_	:   Tuple  				=     row[0]
														for column_index, column in enumerate(lowercase				):
																					if magnitude == 0:
																												lowercase_	:   Optional[int]  				=     column
																												continue
																					lowercase_	:   List[str]  				=     column / magnitude
    # Subtract to cancel term
							lowercase_	:   List[str]  				=     current_set[0]
							lowercase_	:   Optional[int]  				=     [first_row]
							lowercase_	:   Optional[Any]  				=     current_set[1::]
							for row in current_set:
														lowercase_	:   Union[str, Any]  				=     []
														# If first term is 0, it is already in form we want, so we preserve it
														if row[0] == 0:
																					final_set.append(lowercase				)
																					continue
														for column_index in range(len(lowercase				)				):
																					temp_row.append(first_row[column_index] - row[column_index]				)
														final_set.append(lowercase				)
							# Create next recursion iteration set
							if len(final_set[0]				) != 3:
														lowercase_	:   Tuple  				=     final_set[0]
														lowercase_	:   Dict  				=     []
														lowercase_	:   Any  				=     []
														for row in final_set[1::]:
																					current_first_column.append(row[0]				)
																					next_iteration.append(row[1::]				)
														lowercase_	:   Optional[Any]  				=     simplify(lowercase				)
														for i in range(len(lowercase				)				):
																					resultant[i].insert(0				,       current_first_column[i]				)
														resultant.insert(0				,       lowercase				)
														lowercase_	:   Tuple  				=     resultant
							return final_set





def  __magic_name__  (				lowercase				)				-> list:

							"""simple docstring"""



							if len(lowercase				) == 0:
														raise IndexError("""solve_simultaneous() requires n lists of length n+1"""				)
							lowercase_	:   Tuple  				=     len(lowercase				) + 1
							if any(len(lowercase				) != _length for item in equations				):
														raise IndexError("""solve_simultaneous() requires n lists of length n+1"""				)
							for row in equations:
														if any(not isinstance(lowercase				,       (int, float)				) for column in row				):
																					raise ValueError("""solve_simultaneous() requires lists of integers"""				)
							if len(lowercase				) == 1:
														return [equations[0][-1] / equations[0][0]]
							lowercase_	:   List[str]  				=     equations.copy()
							if any(0 in row for row in data_set				):
														lowercase_	:   int  				=     data_set.copy()
														lowercase_	:   Dict  				=     []
														for row_index, row in enumerate(lowercase				):
																					if 0 not in row:
																												lowercase_	:   Dict  				=     data_set.pop(lowercase				)
																												break
														if not full_row:
																					raise ValueError("""solve_simultaneous() requires at least 1 full equation"""				)
														data_set.insert(0				,       lowercase				)
							lowercase_	:   Tuple  				=     data_set.copy()
							lowercase_	:   List[Any]  				=     simplify(lowercase				)
							lowercase_	:   Dict  				=     simplified[::-1]
							lowercase_	:   list  				=     []
							for row in simplified:
														lowercase_	:   Union[str, Any]  				=     row[-1]
														if not solutions:
																					if row[-2] == 0:
																												solutions.append(0				)
																												continue
																					solutions.append(current_solution / row[-2]				)
																					continue
														lowercase_	:   Any  				=     row.copy()[: len(lowercase				) - 1 :]
														while temp_row[0] == 0:
																					temp_row.pop(0				)
														if len(lowercase				) == 0:
																					solutions.append(0				)
																					continue
														lowercase_	:   Any  				=     temp_row[1::]
														lowercase_	:   Union[str, Any]  				=     temp_row[::-1]
														for column_index, column in enumerate(lowercase				):
																					current_solution -= column * solutions[column_index]
														solutions.append(lowercase				)
							lowercase_	:   Any  				=     []
							for item in solutions:
														final.append(float(round(lowercase				,       5				)				)				)
							return final[::-1]


if __name__ == "__main__":
							import doctest

							doctest.testmod()
							UpperCAmelCase_							=				[
							    [2, 1, 1, 1, 1, 4],
							    [1, 2, 1, 1, 1, 5],
							    [1, 1, 2, 1, 1, 6],
							    [1, 1, 1, 2, 1, 7],
							    [1, 1, 1, 1, 2, 8],
							]
							print(solve_simultaneous(eq))
							print(solve_simultaneous([[4, 2]]))