


'''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				):




 '''simple docstring'''
 # TODO: is there an appropriate internal test set?
 __lowercase				:		Any    							=						'''ssube/stable-diffusion-x4-upscaler-onnx'''


 def  snake_case__   (      self      ,      __lowercase=0						):

  """simple docstring"""







  __A  :		List[Any]       =			floats_tensor((1, 3, 128, 128)      ,      rng=random.Random(__lowercase						)						)
  __A  :		str       =			torch.manual_seed(__lowercase						)
  __A  :		Union[str, 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  snake_case__   (      self						):

  """simple docstring"""







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

  __A  :		Dict       =			self.get_dummy_inputs()
  __A  :		Optional[int]       =			pipe(**__lowercase						).images
  __A  :		List[str]       =			image[0, -3:, -3:, -1].flatten()

  # started as 128, should now be 512
  assert image.shape == (1, 512, 512, 3)
  __A  :		Dict       =			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  snake_case__   (      self						):

  """simple docstring"""







  __A  :		Any       =			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint      ,      provider='CPUExecutionProvider'						)
  __A  :		List[str]       =			PNDMScheduler.from_config(pipe.scheduler.config      ,      skip_prk_steps=__lowercase						)
  pipe.set_progress_bar_config(disable=__lowercase						)

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

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

  """simple docstring"""







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

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

  assert image.shape == (1, 512, 512, 3)
  __A  :		Any       =			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  snake_case__   (      self						):

  """simple docstring"""







  __A  :		int       =			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint      ,      provider='CPUExecutionProvider'						)
  __A  :		List[Any]       =			EulerDiscreteScheduler.from_config(pipe.scheduler.config						)
  pipe.set_progress_bar_config(disable=__lowercase						)

  __A  :		Dict       =			self.get_dummy_inputs()
  __A  :		List[str]       =			pipe(**__lowercase						).images
  __A  :		Union[str, Any]       =			image[0, -3:, -3:, -1]

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

  """simple docstring"""







  __A  :		Optional[Any]       =			OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint      ,      provider='CPUExecutionProvider'						)
  __A  :		Optional[Any]       =			EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config						)
  pipe.set_progress_bar_config(disable=__lowercase						)

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

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




 '''simple docstring'''


 @property
 def  snake_case__   (      self						):

  """simple docstring"""







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


 @property
 def  snake_case__   (      self						):

  """simple docstring"""







  __A  :		str       =			ort.SessionOptions()
  __A  :		str       =			False
  return options


 def  snake_case__   (      self						):

  """simple docstring"""







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

  __A  :		List[str]       =			'A fantasy landscape, trending on artstation'

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

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

  """simple docstring"""







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

  __A  :		str       =			'A fantasy landscape, trending on artstation'

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

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










'''simple docstring'''
from __future__ import annotations

import math
import random
from collections.abc import Collection
from typing import overload

class 						_lowerCamelCase					:




 '''simple docstring'''


 def __init__(      self      ,      __lowercase = None						):

  """simple docstring"""







  if components is None:
   __A  :		Optional[int]       =			[]
  __A  :		Dict       =			list(__lowercase						)


 def __len__(      self						):

  """simple docstring"""







  return len(self.__components						)


 def __str__(      self						):

  """simple docstring"""







  return "(" + ",".join(map(__lowercase      ,      self.__components						)						) + ")"


 def __add__(      self      ,      __lowercase						):

  """simple docstring"""







  __A  :		Union[str, Any]       =			len(self						)
  if size == len(__lowercase						):
   __A  :		Dict       =			[self.__components[i] + other.component(__lowercase						) for i in range(__lowercase						)]
   return Vector(__lowercase						)
  else:
   raise Exception('must have the same size'						)


 def __sub__(      self      ,      __lowercase						):

  """simple docstring"""







  __A  :		int       =			len(self						)
  if size == len(__lowercase						):
   __A  :		str       =			[self.__components[i] - other.component(__lowercase						) for i in range(__lowercase						)]
   return Vector(__lowercase						)
  else:  # error case
   raise Exception('must have the same size'						)


 @overload
 def __mul__(      self      ,      __lowercase						):

  """simple docstring"""







  ...


 @overload
 def __mul__(      self      ,      __lowercase						):

  """simple docstring"""







  ...


 def __mul__(      self      ,      __lowercase						):

  """simple docstring"""







  if isinstance(__lowercase      ,      (float, int)						):
   __A  :		Dict       =			[c * other for c in self.__components]
   return Vector(__lowercase						)
  elif isinstance(__lowercase      ,      __lowercase						) and len(self						) == len(__lowercase						):
   __A  :		Optional[Any]       =			len(self						)
   __A  :		Optional[int]       =			[self.__components[i] * other.component(__lowercase						) for i in range(__lowercase						)]
   return sum(__lowercase						)
  else:  # error case
   raise Exception('invalid operand!'						)


 def  snake_case__   (      self						):

  """simple docstring"""







  return Vector(self.__components						)


 def  snake_case__   (      self      ,      __lowercase						):

  """simple docstring"""







  if isinstance(__lowercase      ,      __lowercase						) and -len(self.__components						) <= i < len(self.__components						):
   return self.__components[i]
  else:
   raise Exception('index out of range'						)


 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase						):

  """simple docstring"""







  assert -len(self.__components						) <= pos < len(self.__components						)
  __A  :		str       =			value


 def  snake_case__   (      self						):

  """simple docstring"""







  if len(self.__components						) == 0:
   raise Exception('Vector is empty'						)
  __A  :		List[Any]       =			[c**2 for c in self.__components]
  return math.sqrt(sum(__lowercase						)						)







 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase = False						):

  """simple docstring"""







  __A  :		List[Any]       =			self * other
  __A  :		Any       =			self.euclidean_length() * other.euclidean_length()
  if deg:
   return math.degrees(math.acos(num / den						)						)
  else:
   return math.acos(num / den						)


def 			_lowercase       (				UpperCamelCase__       :					int			):
 assert isinstance(UpperCamelCase__,				UpperCamelCase__			)
 return Vector([0] * dimension			)


def 			_lowercase       (				UpperCamelCase__       :					int,				UpperCamelCase__       :					int			):
 assert isinstance(UpperCamelCase__,				UpperCamelCase__			) and (isinstance(UpperCamelCase__,				UpperCamelCase__			))
 __A  :		List[str]       =			[0] * dimension
 __A  :		Tuple       =			1
 return Vector(UpperCamelCase__			)


def 			_lowercase       (				UpperCamelCase__       :					float,				UpperCamelCase__       :					Vector,				UpperCamelCase__       :					Vector			):
 assert (
     isinstance(UpperCamelCase__,				UpperCamelCase__			)
     and isinstance(UpperCamelCase__,				UpperCamelCase__			)
     and (isinstance(UpperCamelCase__,				(int, float)			))
 )
 return x * scalar + y


def 			_lowercase       (				UpperCamelCase__       :					int,				UpperCamelCase__       :					int,				UpperCamelCase__       :					int			):
 random.seed(UpperCamelCase__			)
 __A  :		Any       =			[random.randint(UpperCamelCase__,				UpperCamelCase__			) for _ in range(UpperCamelCase__			)]
 return Vector(UpperCamelCase__			)

class 						_lowerCamelCase					:




 '''simple docstring'''


 def __init__(      self      ,      __lowercase      ,      __lowercase      ,      __lowercase						):

  """simple docstring"""







  __A  :		str       =			matrix
  __A  :		str       =			w
  __A  :		Dict       =			h


 def __str__(      self						):

  """simple docstring"""







  __A  :		Tuple       =			''
  for i in range(self.__height						):
   ans += "|"
   for j in range(self.__width						):
    if j < self.__width - 1:
     ans += str(self.__matrix[i][j]						) + ","
    else:
     ans += str(self.__matrix[i][j]						) + "|\n"
  return ans


 def __add__(      self      ,      __lowercase						):

  """simple docstring"""







  if self.__width == other.width() and self.__height == other.height():
   __A  :		Union[str, Any]       =			[]
   for i in range(self.__height						):
    __A  :		List[Any]       =			[
        self.__matrix[i][j] + other.component(__lowercase      ,      __lowercase						)
        for j in range(self.__width						)
    ]
    matrix.append(__lowercase						)
   return Matrix(__lowercase      ,      self.__width      ,      self.__height						)
  else:
   raise Exception('matrix must have the same dimension!'						)


 def __sub__(      self      ,      __lowercase						):

  """simple docstring"""







  if self.__width == other.width() and self.__height == other.height():
   __A  :		Dict       =			[]
   for i in range(self.__height						):
    __A  :		str       =			[
        self.__matrix[i][j] - other.component(__lowercase      ,      __lowercase						)
        for j in range(self.__width						)
    ]
    matrix.append(__lowercase						)
   return Matrix(__lowercase      ,      self.__width      ,      self.__height						)
  else:
   raise Exception('matrices must have the same dimension!'						)


 @overload
 def __mul__(      self      ,      __lowercase						):

  """simple docstring"""







  ...


 @overload
 def __mul__(      self      ,      __lowercase						):

  """simple docstring"""







  ...


 def __mul__(      self      ,      __lowercase						):

  """simple docstring"""







  if isinstance(__lowercase      ,      __lowercase						):  # matrix-vector
   if len(__lowercase						) == self.__width:
    __A  :		Tuple       =			zero_vector(self.__height						)
    for i in range(self.__height						):
     __A  :		Any       =			[
         self.__matrix[i][j] * other.component(__lowercase						)
         for j in range(self.__width						)
     ]
     ans.change_component(__lowercase      ,      sum(__lowercase						)						)
    return ans
   else:
    raise Exception(
        'vector must have the same size as the '
        'number of columns of the matrix!'						)
  elif isinstance(__lowercase      ,      (int, float)						):  # matrix-scalar
   __A  :		Optional[Any]       =			[
       [self.__matrix[i][j] * other for j in range(self.__width						)]
       for i in range(self.__height						)
   ]
   return Matrix(__lowercase      ,      self.__width      ,      self.__height						)
  return None


 def  snake_case__   (      self						):

  """simple docstring"""







  return self.__height


 def  snake_case__   (      self						):

  """simple docstring"""







  return self.__width


 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase						):

  """simple docstring"""







  if 0 <= x < self.__height and 0 <= y < self.__width:
   return self.__matrix[x][y]
  else:
   raise Exception('change_component: indices out of bounds'						)


 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase      ,      __lowercase						):

  """simple docstring"""







  if 0 <= x < self.__height and 0 <= y < self.__width:
   __A  :		Dict       =			value
  else:
   raise Exception('change_component: indices out of bounds'						)


 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase						):

  """simple docstring"""







  if self.__height != self.__width:
   raise Exception('Matrix is not square'						)
  __A  :		Union[str, Any]       =			self.__matrix[:x] + self.__matrix[x + 1 :]
  for i in range(len(__lowercase						)						):
   __A  :		Dict       =			minor[i][:y] + minor[i][y + 1 :]
  return Matrix(__lowercase      ,      self.__width - 1      ,      self.__height - 1						).determinant()


 def  snake_case__   (      self      ,      __lowercase      ,      __lowercase						):

  """simple docstring"""







  if self.__height != self.__width:
   raise Exception('Matrix is not square'						)
  if 0 <= x < self.__height and 0 <= y < self.__width:
   return (-1) ** (x + y) * self.minor(__lowercase      ,      __lowercase						)
  else:
   raise Exception('Indices out of bounds'						)







 def  snake_case__   (      self						):

  """simple docstring"""







  if self.__height != self.__width:
   raise Exception('Matrix is not square'						)
  if self.__height < 1:
   raise Exception('Matrix has no element'						)
  elif self.__height == 1:
   return self.__matrix[0][0]
  elif self.__height == 2:
   return (
       self.__matrix[0][0] * self.__matrix[1][1]
       - self.__matrix[0][1] * self.__matrix[1][0]
   )
  else:
   __A  :		List[str]       =			[
       self.__matrix[0][y] * self.cofactor(0      ,      __lowercase						) for y in range(self.__width						)
   ]
   return sum(__lowercase						)


def 			_lowercase       (				UpperCamelCase__       :					int			):
 __A  :		list[list[float]]       =			[[0] * n for _ in range(UpperCamelCase__			)]
 return Matrix(UpperCamelCase__,				UpperCamelCase__,				UpperCamelCase__			)


def 			_lowercase       (				UpperCamelCase__       :					int,				UpperCamelCase__       :					int,				UpperCamelCase__       :					int,				UpperCamelCase__       :					int			):
 random.seed(UpperCamelCase__			)
 __A  :		list[list[float]]       =			[
     [random.randint(UpperCamelCase__,				UpperCamelCase__			) for _ in range(UpperCamelCase__			)] for _ in range(UpperCamelCase__			)
 ]
 return Matrix(UpperCamelCase__,				UpperCamelCase__,				UpperCamelCase__			)






