



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







				def     lowercase_ (   self				:						List[str]		,    __snake_case				:						Dict=0			):
						a		:      Union[str, Any]       =  floats_tensor((1, 3, 1_28, 1_28)		,    rng=random.Random(__lowerCamelCase			)			)
						a		:      str       =  torch.manual_seed(__lowerCamelCase			)
						a		:      str       =  {
						    "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     lowercase_ (   self				:						Optional[Any]			):
						a		:      int       =  OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,    provider='CPUExecutionProvider'			)
						pipe.set_progress_bar_config(disable=__lowerCamelCase			)

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

						# started as 128, should now be 512
						assert image.shape == (1, 5_12, 5_12, 3)
						a		:      str       =  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     lowercase_ (   self				:						Tuple			):
						a		:      Tuple       =  OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,    provider='CPUExecutionProvider'			)
						a		:      Dict       =  PNDMScheduler.from_config(pipe.scheduler.config		,    skip_prk_steps=__lowerCamelCase			)
						pipe.set_progress_bar_config(disable=__lowerCamelCase			)

						a		:      int       =  self.get_dummy_inputs()
						a		:      Tuple       =  pipe(**__lowerCamelCase			).images
						a		:      List[Any]       =  image[0, -3:, -3:, -1]

						assert image.shape == (1, 5_12, 5_12, 3)
						a		:      Dict       =  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     lowercase_ (   self				:						int			):
						a		:      Any       =  OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,    provider='CPUExecutionProvider'			)
						a		:      Any       =  DPMSolverMultistepScheduler.from_config(pipe.scheduler.config			)
						pipe.set_progress_bar_config(disable=__lowerCamelCase			)

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

						assert image.shape == (1, 5_12, 5_12, 3)
						a		:      List[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     lowercase_ (   self				:						List[Any]			):
						a		:      int       =  OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,    provider='CPUExecutionProvider'			)
						a		:      Optional[Any]       =  EulerDiscreteScheduler.from_config(pipe.scheduler.config			)
						pipe.set_progress_bar_config(disable=__lowerCamelCase			)

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

						assert image.shape == (1, 5_12, 5_12, 3)
						a		:      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     lowercase_ (   self				:						int			):
						a		:      int       =  OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint		,    provider='CPUExecutionProvider'			)
						a		:      Optional[int]       =  EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config			)
						pipe.set_progress_bar_config(disable=__lowerCamelCase			)

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

						assert image.shape == (1, 5_12, 5_12, 3)
						a		:      Optional[int]       =  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     lowercase_ (   self				:						Optional[Any]			):
						return (
						    "CUDAExecutionProvider",
						    {
						        "gpu_mem_limit": "15000000000",  # 15GB
						        "arena_extend_strategy": "kSameAsRequested",
						    },
						)







				@property
				def     lowercase_ (   self				:						Optional[int]			):
						a		:      Any       =  ort.SessionOptions()
						a		:      List[Any]       =  False
						return options







				def     lowercase_ (   self				:						str			):
						a		:      Optional[int]       =  load_image(
						    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'
						    '/img2img/sketch-mountains-input.jpg'			)
						a		:      List[str]       =  init_image.resize((1_28, 1_28)			)
						# using the PNDM scheduler by default
						a		:      List[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=__lowerCamelCase			)

						a		:      List[str]       =  "A fantasy landscape, trending on artstation"

						a		:      Any       =  torch.manual_seed(0			)
						a		:      Union[str, Any]       =  pipe(
						    prompt=__lowerCamelCase		,    image=__lowerCamelCase		,    guidance_scale=7.5		,    num_inference_steps=10		,    generator=__lowerCamelCase		,    output_type='np'		,    )
						a		:      List[Any]       =  output.images
						a		:      Optional[int]       =  images[0, 2_55:2_58, 3_83:3_86, -1]

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

						a		:      Optional[int]       =  "A fantasy landscape, trending on artstation"

						a		:      Union[str, Any]       =  torch.manual_seed(0			)
						a		:      List[str]       =  pipe(
						    prompt=__lowerCamelCase		,    image=__lowerCamelCase		,    guidance_scale=7.5		,    num_inference_steps=20		,    generator=__lowerCamelCase		,    output_type='np'		,    )
						a		:      Optional[Any]       =  output.images
						a		:      Optional[int]       =  images[0, 2_55:2_58, 3_83:3_86, -1]

						assert images.shape == (1, 5_12, 5_12, 3)
						a		:      str       =  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




'''simple docstring'''






from __future__ import annotations

from sys import maxsize
from typing import Generic, TypeVar

lowerCAmelCase:      List[str]		 =		TypeVar('T')
def    lowerCamelCase__ (		_A       ):
  return (position - 1) // 2
def    lowerCamelCase__ (		_A       ):
  return (2 * position) + 1
def    lowerCamelCase__ (		_A       ):
  return (2 * position) + 2

class 							a__(      Generic[T]			):







    def __init__(   self				:						Optional[Any]			):
      a		:      list[tuple[T, int]]       =  []
      a		:      dict[T, int]       =  {}
      a		:      int       =  0







    def __len__(   self				:						Union[str, Any]			):
      return self.elements







    def __repr__(   self				:						Any			):
      return str(self.heap			)







    def     lowercase_ (   self				:						Optional[int]			):
      # Check if the priority queue is empty
      return self.elements == 0







    def     lowercase_ (   self				:						Union[str, Any]		,    __snake_case				:						T		,    __snake_case				:						int			):
      # Add an element with given priority to the queue
      self.heap.append((elem, weight)			)
      a		:      int       =  self.elements
      self.elements += 1
      self._bubble_up(__snake_case			)







    def     lowercase_ (   self				:						Union[str, Any]			):
      # Remove and return the element with lowest weight (highest priority)
      if self.elements > 1:
        self._swap_nodes(0		,    self.elements - 1			)
      a     ,			a		:      str       =  self.heap.pop()
      del self.position_map[elem]
      self.elements -= 1
      if self.elements > 0:
        a     ,			a		:      List[Any]       =  self.heap[0]
        self._bubble_down(__snake_case			)
      return elem







    def     lowercase_ (   self				:						List[str]		,    __snake_case				:						T		,    __snake_case				:						int			):
      # Update the weight of the given key
      a		:      Any       =  self.position_map[elem]
      a		:      Union[str, Any]       =  (elem, weight)
      if position > 0:
        a		:      Optional[Any]       =  get_parent_position(__snake_case			)
        a     ,			a		:      Union[str, Any]       =  self.heap[parent_position]
        if parent_weight > weight:
          self._bubble_up(__snake_case			)
        else:
          self._bubble_down(__snake_case			)
      else:
        self._bubble_down(__snake_case			)







    def     lowercase_ (   self				:						int		,    __snake_case				:						T			):
      # Place a node at the proper position (upward movement) [to be used internally
      # only]
      a		:      Union[str, Any]       =  self.position_map[elem]
      if curr_pos == 0:
        return None
      a		:      Union[str, Any]       =  get_parent_position(__snake_case			)
      a     ,			a		:      Tuple       =  self.heap[curr_pos]
      a     ,			a		:      List[Any]       =  self.heap[parent_position]
      if parent_weight > weight:
        self._swap_nodes(__snake_case		,    __snake_case			)
        return self._bubble_up(__snake_case			)
      return None







    def     lowercase_ (   self				:						Tuple		,    __snake_case				:						T			):
      # Place a node at the proper position (downward movement) [to be used
      # internally only]
      a		:      str       =  self.position_map[elem]
      a     ,			a		:      List[Any]       =  self.heap[curr_pos]
      a		:      int       =  get_child_left_position(__snake_case			)
      a		:      Dict       =  get_child_right_position(__snake_case			)
      if child_left_position < self.elements and child_right_position < self.elements:
        a     ,			a		:      int       =  self.heap[child_left_position]
        a     ,			a		:      Optional[Any]       =  self.heap[child_right_position]
        if child_right_weight < child_left_weight and child_right_weight < weight:
          self._swap_nodes(__snake_case		,    __snake_case			)
          return self._bubble_down(__snake_case			)
      if child_left_position < self.elements:
        a     ,			a		:      Dict       =  self.heap[child_left_position]
        if child_left_weight < weight:
          self._swap_nodes(__snake_case		,    __snake_case			)
          return self._bubble_down(__snake_case			)
      else:
        return None
      if child_right_position < self.elements:
        a     ,			a		:      List[Any]       =  self.heap[child_right_position]
        if child_right_weight < weight:
          self._swap_nodes(__snake_case		,    __snake_case			)
          return self._bubble_down(__snake_case			)
      return None







    def     lowercase_ (   self				:						List[Any]		,    __snake_case				:						int		,    __snake_case				:						int			):
      # Swap the nodes at the given positions
      a		:      Optional[int]       =  self.heap[nodea_pos][0]
      a		:      int       =  self.heap[nodea_pos][0]
      a     ,			a		:      List[str]       =  (
          self.heap[nodea_pos],
          self.heap[nodea_pos],
      )
      a		:      Tuple       =  nodea_pos
      a		:      Any       =  nodea_pos

class 							a__(      Generic[T]			):







    def __init__(   self				:						Optional[int]			):
      a		:      dict[T, dict[T, int]]       =  {}
      a		:      int       =  0







    def __repr__(   self				:						List[str]			):
      return str(self.connections			)







    def __len__(   self				:						str			):
      return self.nodes







    def     lowercase_ (   self				:						int		,    __snake_case				:						T			):
      # Add a node in the graph if it is not in the graph
      if node not in self.connections:
        a		:      Optional[int]       =  {}
        self.nodes += 1







    def     lowercase_ (   self				:						Dict		,    __snake_case				:						T		,    __snake_case				:						T		,    __snake_case				:						int			):
      # Add an edge between 2 nodes in the graph
      self.add_node(__snake_case			)
      self.add_node(__snake_case			)
      a		:      Any       =  weight
      a		:      Dict       =  weight
def    lowerCamelCase__ (		_A				,    ):
  a		:      dict[T, int]       =  {node: maxsize for node in graph.connections}
  a		:      dict[T, T | None]       =  {node: None for node in graph.connections}

  a		:      MinPriorityQueue[T]       =  MinPriorityQueue()
  for node, weight in dist.items():
    priority_queue.push(_A				,    _A       )

  if priority_queue.is_empty():
    return dist, parent

  # initialization
  a		:      int       =  priority_queue.extract_min()
  a		:      Dict       =  0
  for neighbour in graph.connections[node]:
    if dist[neighbour] > dist[node] + graph.connections[node][neighbour]:
      a		:      Tuple       =  dist[node] + graph.connections[node][neighbour]
      priority_queue.update_key(_A				,    dist[neighbour]       )
      a		:      Dict       =  node

    # running prim's algorithm
  while not priority_queue.is_empty():
    a		:      List[str]       =  priority_queue.extract_min()
    for neighbour in graph.connections[node]:
      if dist[neighbour] > dist[node] + graph.connections[node][neighbour]:
        a		:      int       =  dist[node] + graph.connections[node][neighbour]
        priority_queue.update_key(_A				,    dist[neighbour]       )
        a		:      Optional[int]       =  node
  return dist, parent