

class A__    :



 """simple docstring"""







 def __init__(		self :	Optional[Any]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Tuple        =    0
      _lowerCAmelCase   :					str        =    0
      _lowerCAmelCase   :					str        =    {}

 def    __magic_name__       (		self :	str     ,						A_ :	List[str]       ):






      '''simple docstring'''




      if vertex not in self.adjacency:
           _lowerCAmelCase   :					Optional[Any]        =    {}
           self.num_vertices += 1

 def    __magic_name__       (		self :	List[str]     ,						A_ :	Dict     ,						A_ :	Tuple     ,						A_ :	Tuple       ):






      '''simple docstring'''




      self.add_vertex(A_       )
      self.add_vertex(A_       )

      if head == tail:
           return

      _lowerCAmelCase   :					List[str]        =    weight
      _lowerCAmelCase   :					List[Any]        =    weight

 def    __magic_name__       (		self :	Optional[int]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					List[Any]        =    self.get_edges()
      for edge in edges:
           _lowerCAmelCase      ,			_lowerCAmelCase      ,			_lowerCAmelCase   :					List[str]        =    edge
           edges.remove((tail, head, weight)       )
      for i in range(len(A_       )       ):
           _lowerCAmelCase   :					str        =    list(edges[i]       )

      edges.sort(key=lambda A_       : e[2]       )
      for i in range(len(A_       ) - 1       ):
           if edges[i][2] >= edges[i + 1][2]:
                _lowerCAmelCase   :					Tuple        =    edges[i][2] + 1
      for edge in edges:
           _lowerCAmelCase      ,			_lowerCAmelCase      ,			_lowerCAmelCase   :					Optional[int]        =    edge
           _lowerCAmelCase   :					int        =    weight
           _lowerCAmelCase   :					int        =    weight

 def __str__(		self :	Union[str, Any]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					List[str]        =    ""
      for tail in self.adjacency:
           for head in self.adjacency[tail]:
                _lowerCAmelCase   :					Any        =    self.adjacency[head][tail]
                string += F'''{head} -> {tail} == {weight}\n'''
      return string.rstrip("\n"       )

 def    __magic_name__       (		self :	Optional[Any]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Union[str, Any]        =    []
      for tail in self.adjacency:
           for head in self.adjacency[tail]:
                output.append((tail, head, self.adjacency[head][tail])       )
      return output

 def    __magic_name__       (		self :	str       ):






      '''simple docstring'''




      return self.adjacency.keys()

 @staticmethod
 def    __magic_name__       (		A_ :	int=None     ,						A_ :	Optional[Any]=None       ):






      '''simple docstring'''




      _lowerCAmelCase   :					List[str]        =    Graph()
      if vertices is None:
           _lowerCAmelCase   :					Optional[Any]        =    []
      if edges is None:
           _lowerCAmelCase   :					Union[str, Any]        =    []
      for vertex in vertices:
           g.add_vertex(A_       )
      for edge in edges:
           g.add_edge(*A_       )
      return g





 class A__    :



  """simple docstring"""







  def __init__(		self :	Union[str, Any]       ):






       '''simple docstring'''




       _lowerCAmelCase   :					Optional[int]        =    {}
       _lowerCAmelCase   :					Optional[int]        =    {}

  def __len__(		self :	Tuple       ):






       '''simple docstring'''




       return len(self.parent       )

  def    __magic_name__       (		self :	List[str]     ,						A_ :	int       ):






       '''simple docstring'''




       if item in self.parent:
            return self.find(A_       )

       _lowerCAmelCase   :					Any        =    item
       _lowerCAmelCase   :					Tuple        =    0
       return item

  def    __magic_name__       (		self :	Any     ,						A_ :	int       ):






       '''simple docstring'''




       if item not in self.parent:
            return self.make_set(A_       )
       if item != self.parent[item]:
            _lowerCAmelCase   :					List[Any]        =    self.find(self.parent[item]       )
       return self.parent[item]


  def    __magic_name__       (		self :	Tuple     ,						A_ :	List[str]     ,						A_ :	int       ):






       '''simple docstring'''




       _lowerCAmelCase   :					Optional[int]        =    self.find(A_       )
       _lowerCAmelCase   :					List[Any]        =    self.find(A_       )

       if roota == roota:
            return roota

       if self.rank[roota] > self.rank[roota]:
            _lowerCAmelCase   :					int        =    roota
            return roota

       if self.rank[roota] < self.rank[roota]:
            _lowerCAmelCase   :					Union[str, Any]        =    roota
            return roota

       if self.rank[roota] == self.rank[roota]:
            self.rank[roota] += 1
            _lowerCAmelCase   :					List[str]        =    roota
            return roota
       return None

 @staticmethod
 def    __magic_name__       (		A_ :	Union[str, Any]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					int        =    graph.num_vertices

      _lowerCAmelCase   :					List[str]        =    Graph.UnionFind()
      _lowerCAmelCase   :					Any        =    []
      while num_components > 1:
           _lowerCAmelCase   :					Union[str, Any]        =    {}
           for vertex in graph.get_vertices():
                _lowerCAmelCase   :					List[str]        =    -1

           _lowerCAmelCase   :					List[str]        =    graph.get_edges()
           for edge in edges:
                _lowerCAmelCase      ,			_lowerCAmelCase      ,			_lowerCAmelCase   :					Union[str, Any]        =    edge
                edges.remove((tail, head, weight)       )
           for edge in edges:
                _lowerCAmelCase      ,			_lowerCAmelCase      ,			_lowerCAmelCase   :					Dict        =    edge
                _lowerCAmelCase   :					List[str]        =    union_find.find(A_       )
                _lowerCAmelCase   :					Tuple        =    union_find.find(A_       )
                if seta != seta:
                     if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight:
                          _lowerCAmelCase   :					List[str]        =    [head, tail, weight]

                     if cheap_edge[seta] == -1 or cheap_edge[seta][2] > weight:
                          _lowerCAmelCase   :					Dict        =    [head, tail, weight]
           for vertex in cheap_edge:
                if cheap_edge[vertex] != -1:
                     _lowerCAmelCase      ,			_lowerCAmelCase      ,			_lowerCAmelCase   :					Any        =    cheap_edge[vertex]
                     if union_find.find(A_       ) != union_find.find(A_       ):
                          union_find.union(A_     ,						A_       )
                          mst_edges.append(cheap_edge[vertex]       )
                          _lowerCAmelCase   :					Dict        =    num_components - 1
      _lowerCAmelCase   :					str        =    Graph.build(edges=A_       )
      return mst









import gc
import random
import unittest

import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer

from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableDiffusionUpscalePipeline, UNetaDConditionModel
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()





class A__    ( unittest.TestCase ):



 """simple docstring"""







 def    __magic_name__       (		self :	Any       ):






      '''simple docstring'''




      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()

 @property
 def    __magic_name__       (		self :	List[Any]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Optional[int]        =    1
      _lowerCAmelCase   :					List[str]        =    3
      _lowerCAmelCase   :					int        =    (3_2, 3_2)

      _lowerCAmelCase   :					Dict        =    floats_tensor((batch_size, num_channels) + sizes     ,						rng=random.Random(0       )       ).to(A_       )
      return image

 @property
 def    __magic_name__       (		self :	List[str]       ):






      '''simple docstring'''




      torch.manual_seed(0       )
      _lowerCAmelCase   :					Dict        =    UNetaDConditionModel(
          block_out_channels=(3_2, 3_2, 6_4)     ,						layers_per_block=2     ,						sample_size=3_2     ,						in_channels=7     ,						out_channels=4     ,						down_block_types=("DownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D")     ,						up_block_types=("CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "UpBlock2D")     ,						cross_attention_dim=3_2     ,						attention_head_dim=8     ,						use_linear_projection=A_     ,						only_cross_attention=(True, True, False)     ,						num_class_embeds=1_0_0     ,						)
      return model

 @property
 def    __magic_name__       (		self :	Union[str, Any]       ):






      '''simple docstring'''




      torch.manual_seed(0       )
      _lowerCAmelCase   :					Union[str, Any]        =    AutoencoderKL(
          block_out_channels=[3_2, 3_2, 6_4]     ,						in_channels=3     ,						out_channels=3     ,						down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D"]     ,						up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"]     ,						latent_channels=4     ,						)
      return model

 @property
 def    __magic_name__       (		self :	Tuple       ):






      '''simple docstring'''




      torch.manual_seed(0       )
      _lowerCAmelCase   :					Optional[Any]        =    CLIPTextConfig(
          bos_token_id=0     ,						eos_token_id=2     ,						hidden_size=3_2     ,						intermediate_size=3_7     ,						layer_norm_eps=1E-05     ,						num_attention_heads=4     ,						num_hidden_layers=5     ,						pad_token_id=1     ,						vocab_size=1_0_0_0     ,						hidden_act="gelu"     ,						projection_dim=5_1_2     ,						)
      return CLIPTextModel(A_       )

 def    __magic_name__       (		self :	str       ):






      '''simple docstring'''




      _lowerCAmelCase   :					List[str]        =    "cpu"  # ensure determinism for the device-dependent torch.Generator
      _lowerCAmelCase   :					Tuple        =    self.dummy_cond_unet_upscale
      _lowerCAmelCase   :					Optional[int]        =    DDPMScheduler()
      _lowerCAmelCase   :					Optional[Any]        =    DDIMScheduler(prediction_type="v_prediction"       )
      _lowerCAmelCase   :					str        =    self.dummy_vae
      _lowerCAmelCase   :					Any        =    self.dummy_text_encoder
      _lowerCAmelCase   :					Dict        =    CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"       )

      _lowerCAmelCase   :					List[Any]        =    self.dummy_image.cpu().permute(0     ,						2     ,						3     ,						1       )[0]
      _lowerCAmelCase   :					List[Any]        =    Image.fromarray(np.uinta(A_       )       ).convert("RGB"       ).resize((6_4, 6_4)       )

      # make sure here that pndm scheduler skips prk
      _lowerCAmelCase   :					List[Any]        =    StableDiffusionUpscalePipeline(
          unet=A_     ,						low_res_scheduler=A_     ,						scheduler=A_     ,						vae=A_     ,						text_encoder=A_     ,						tokenizer=A_     ,						max_noise_level=3_5_0     ,						)
      _lowerCAmelCase   :					Optional[int]        =    sd_pipe.to(A_       )
      sd_pipe.set_progress_bar_config(disable=A_       )

      _lowerCAmelCase   :					List[str]        =    "A painting of a squirrel eating a burger"
      _lowerCAmelCase   :					Tuple        =    torch.Generator(device=A_       ).manual_seed(0       )
      _lowerCAmelCase   :					Optional[int]        =    sd_pipe(
          [prompt]     ,						image=A_     ,						generator=A_     ,						guidance_scale=6.0     ,						noise_level=2_0     ,						num_inference_steps=2     ,						output_type="np"     ,						)

      _lowerCAmelCase   :					Tuple        =    output.images

      _lowerCAmelCase   :					Optional[int]        =    torch.Generator(device=A_       ).manual_seed(0       )
      _lowerCAmelCase   :					Union[str, Any]        =    sd_pipe(
          [prompt]     ,						image=A_     ,						generator=A_     ,						guidance_scale=6.0     ,						noise_level=2_0     ,						num_inference_steps=2     ,						output_type="np"     ,						return_dict=A_     ,						)[0]

      _lowerCAmelCase   :					List[Any]        =    image[0, -3:, -3:, -1]
      _lowerCAmelCase   :					List[str]        =    image_from_tuple[0, -3:, -3:, -1]

      _lowerCAmelCase   :					Optional[int]        =    low_res_image.size[0] * 4
      assert image.shape == (1, expected_height_width, expected_height_width, 3)
      _lowerCAmelCase   :					str        =    np.array([0.3113, 0.3910, 0.4272, 0.4859, 0.5061, 0.4652, 0.5362, 0.5715, 0.5661]       )

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

 def    __magic_name__       (		self :	int       ):






      '''simple docstring'''




      _lowerCAmelCase   :					List[str]        =    "cpu"  # ensure determinism for the device-dependent torch.Generator
      _lowerCAmelCase   :					List[str]        =    self.dummy_cond_unet_upscale
      _lowerCAmelCase   :					str        =    DDPMScheduler()
      _lowerCAmelCase   :					Union[str, Any]        =    DDIMScheduler(prediction_type="v_prediction"       )
      _lowerCAmelCase   :					Tuple        =    self.dummy_vae
      _lowerCAmelCase   :					Union[str, Any]        =    self.dummy_text_encoder
      _lowerCAmelCase   :					List[Any]        =    CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"       )

      _lowerCAmelCase   :					Dict        =    self.dummy_image.cpu().permute(0     ,						2     ,						3     ,						1       )[0]
      _lowerCAmelCase   :					Tuple        =    Image.fromarray(np.uinta(A_       )       ).convert("RGB"       ).resize((6_4, 6_4)       )

      # make sure here that pndm scheduler skips prk
      _lowerCAmelCase   :					Optional[Any]        =    StableDiffusionUpscalePipeline(
          unet=A_     ,						low_res_scheduler=A_     ,						scheduler=A_     ,						vae=A_     ,						text_encoder=A_     ,						tokenizer=A_     ,						max_noise_level=3_5_0     ,						)
      _lowerCAmelCase   :					Dict        =    sd_pipe.to(A_       )
      sd_pipe.set_progress_bar_config(disable=A_       )

      _lowerCAmelCase   :					Union[str, Any]        =    "A painting of a squirrel eating a burger"
      _lowerCAmelCase   :					Tuple        =    sd_pipe(
          2 * [prompt]     ,						image=2 * [low_res_image]     ,						guidance_scale=6.0     ,						noise_level=2_0     ,						num_inference_steps=2     ,						output_type="np"     ,						)
      _lowerCAmelCase   :					List[str]        =    output.images
      assert image.shape[0] == 2

      _lowerCAmelCase   :					str        =    torch.Generator(device=A_       ).manual_seed(0       )
      _lowerCAmelCase   :					List[Any]        =    sd_pipe(
          [prompt]     ,						image=A_     ,						generator=A_     ,						num_images_per_prompt=2     ,						guidance_scale=6.0     ,						noise_level=2_0     ,						num_inference_steps=2     ,						output_type="np"     ,						)
      _lowerCAmelCase   :					int        =    output.images
      assert image.shape[0] == 2


 @unittest.skipIf(torch_device != "cuda"     ,						"This test requires a GPU"       )
 def    __magic_name__       (		self :	Tuple       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Any        =    self.dummy_cond_unet_upscale
      _lowerCAmelCase   :					List[str]        =    DDPMScheduler()
      _lowerCAmelCase   :					Optional[int]        =    DDIMScheduler(prediction_type="v_prediction"       )
      _lowerCAmelCase   :					Optional[Any]        =    self.dummy_vae
      _lowerCAmelCase   :					List[str]        =    self.dummy_text_encoder
      _lowerCAmelCase   :					Union[str, Any]        =    CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip"       )

      _lowerCAmelCase   :					Any        =    self.dummy_image.cpu().permute(0     ,						2     ,						3     ,						1       )[0]
      _lowerCAmelCase   :					Any        =    Image.fromarray(np.uinta(A_       )       ).convert("RGB"       ).resize((6_4, 6_4)       )

      # put models in fp16, except vae as it overflows in fp16
      _lowerCAmelCase   :					Tuple        =    unet.half()
      _lowerCAmelCase   :					Optional[Any]        =    text_encoder.half()

      # make sure here that pndm scheduler skips prk
      _lowerCAmelCase   :					List[str]        =    StableDiffusionUpscalePipeline(
          unet=A_     ,						low_res_scheduler=A_     ,						scheduler=A_     ,						vae=A_     ,						text_encoder=A_     ,						tokenizer=A_     ,						max_noise_level=3_5_0     ,						)
      _lowerCAmelCase   :					Optional[Any]        =    sd_pipe.to(A_       )
      sd_pipe.set_progress_bar_config(disable=A_       )

      _lowerCAmelCase   :					str        =    "A painting of a squirrel eating a burger"
      _lowerCAmelCase   :					Any        =    torch.manual_seed(0       )
      _lowerCAmelCase   :					Optional[Any]        =    sd_pipe(
          [prompt]     ,						image=A_     ,						generator=A_     ,						num_inference_steps=2     ,						output_type="np"     ,						).images

      _lowerCAmelCase   :					List[str]        =    low_res_image.size[0] * 4
      assert image.shape == (1, expected_height_width, expected_height_width, 3)





@slow
@require_torch_gpu
class A__    ( unittest.TestCase ):



 """simple docstring"""







 def    __magic_name__       (		self :	Any       ):






      '''simple docstring'''




      super().tearDown()
      gc.collect()
      torch.cuda.empty_cache()

 def    __magic_name__       (		self :	List[str]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					List[Any]        =    load_image(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
          "/sd2-upscale/low_res_cat.png"       )
      _lowerCAmelCase   :					Dict        =    load_numpy(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale"
          "/upsampled_cat.npy"       )

      _lowerCAmelCase   :					Union[str, Any]        =    "stabilityai/stable-diffusion-x4-upscaler"
      _lowerCAmelCase   :					Optional[int]        =    StableDiffusionUpscalePipeline.from_pretrained(A_       )
      pipe.to(A_       )
      pipe.set_progress_bar_config(disable=A_       )
      pipe.enable_attention_slicing()

      _lowerCAmelCase   :					str        =    "a cat sitting on a park bench"

      _lowerCAmelCase   :					str        =    torch.manual_seed(0       )
      _lowerCAmelCase   :					Optional[int]        =    pipe(
          prompt=A_     ,						image=A_     ,						generator=A_     ,						output_type="np"     ,						)
      _lowerCAmelCase   :					int        =    output.images[0]

      assert image.shape == (5_1_2, 5_1_2, 3)
      assert np.abs(expected_image - image       ).max() < 1E-3

 def    __magic_name__       (		self :	Tuple       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Optional[int]        =    load_image(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
          "/sd2-upscale/low_res_cat.png"       )
      _lowerCAmelCase   :					Dict        =    load_numpy(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd2-upscale"
          "/upsampled_cat_fp16.npy"       )

      _lowerCAmelCase   :					Union[str, Any]        =    "stabilityai/stable-diffusion-x4-upscaler"
      _lowerCAmelCase   :					Any        =    StableDiffusionUpscalePipeline.from_pretrained(
          A_     ,						torch_dtype=torch.floataa     ,						)
      pipe.to(A_       )
      pipe.set_progress_bar_config(disable=A_       )
      pipe.enable_attention_slicing()

      _lowerCAmelCase   :					Optional[Any]        =    "a cat sitting on a park bench"

      _lowerCAmelCase   :					Any        =    torch.manual_seed(0       )
      _lowerCAmelCase   :					int        =    pipe(
          prompt=A_     ,						image=A_     ,						generator=A_     ,						output_type="np"     ,						)
      _lowerCAmelCase   :					Union[str, Any]        =    output.images[0]

      assert image.shape == (5_1_2, 5_1_2, 3)
      assert np.abs(expected_image - image       ).max() < 5E-1


 def    __magic_name__       (		self :	List[Any]       ):






      '''simple docstring'''




      torch.cuda.empty_cache()
      torch.cuda.reset_max_memory_allocated()
      torch.cuda.reset_peak_memory_stats()

      _lowerCAmelCase   :					int        =    load_image(
          "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
          "/sd2-upscale/low_res_cat.png"       )

      _lowerCAmelCase   :					Tuple        =    "stabilityai/stable-diffusion-x4-upscaler"
      _lowerCAmelCase   :					Any        =    StableDiffusionUpscalePipeline.from_pretrained(
          A_     ,						torch_dtype=torch.floataa     ,						)
      pipe.to(A_       )
      pipe.set_progress_bar_config(disable=A_       )
      pipe.enable_attention_slicing(1       )
      pipe.enable_sequential_cpu_offload()

      _lowerCAmelCase   :					List[Any]        =    "a cat sitting on a park bench"

      _lowerCAmelCase   :					Union[str, Any]        =    torch.manual_seed(0       )
      _lowerCAmelCase   :					List[Any]        =    pipe(
          prompt=A_     ,						image=A_     ,						generator=A_     ,						num_inference_steps=5     ,						output_type="np"     ,						)

      _lowerCAmelCase   :					Optional[Any]        =    torch.cuda.max_memory_allocated()
      # make sure that less than 2.9 GB is allocated
      assert mem_bytes < 2.9 * 1_0**9






