


import csv
from collections import defaultdict
from dataclasses import dataclass, field
from typing import List, Optional

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import ScalarFormatter

from transformers import HfArgumentParser







def 	_snake_case		(    SCREAMING_SNAKE_CASE=None		,							SCREAMING_SNAKE_CASE=None				)       ->      List[Any]:

     """simple docstring"""







     return field(default_factory=lambda: default		,							metadata=SCREAMING_SNAKE_CASE				)





@dataclass
class A__    :



 """simple docstring"""







 _lowercase     :					str      =						field(
     metadata={'''help''': '''The csv file to plot.'''}  ,		)
 _lowercase     :					bool      =						field(
     default=A  ,		metadata={'''help''': '''Whether to plot along batch size or sequence length. Defaults to sequence length.'''}  ,		)
 _lowercase     :					bool      =						field(
     default=A  ,		metadata={'''help''': '''Whether the csv file has time results or memory results. Defaults to memory results.'''}  ,		)
 _lowercase     :					bool      =						field(
     default=A  ,		metadata={'''help''': '''Disable logarithmic scale when plotting'''}  ,		)
 _lowercase     :					bool      =						field(
     default=A  ,		metadata={
         '''help''': '''Whether the csv file has training results or inference results. Defaults to inference results.'''
     }  ,		)
 _lowercase     :					Optional[str]      =						field(
     default=A  ,		metadata={'''help''': '''Filename under which the plot will be saved. If unused no plot is saved.'''}  ,		)
 _lowercase     :					Optional[List[str]]      =						list_field(
     default=A  ,		metadata={'''help''': '''List of model names that are used instead of the ones in the csv file.'''} )







def 	_snake_case		(    SCREAMING_SNAKE_CASE				)       ->      List[Any]:

     """simple docstring"""







     try:
          int(SCREAMING_SNAKE_CASE				)
          return True
     except ValueError:
          return False







def 	_snake_case		(    SCREAMING_SNAKE_CASE				)       ->      Union[str, Any]:

     """simple docstring"""







     try:
          float(SCREAMING_SNAKE_CASE				)
          return True
     except ValueError:
          return False





class A__    :



 """simple docstring"""







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






      '''simple docstring'''




      _lowerCAmelCase   :					Tuple        =    args
      _lowerCAmelCase   :					Tuple        =    defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}}       )

      with open(self.args.csv_file     ,						newline=""       ) as csv_file:
           _lowerCAmelCase   :					Tuple        =    csv.DictReader(A_       )
           for row in reader:
                _lowerCAmelCase   :					List[Any]        =    row["model"]
                self.result_dict[model_name]["bsz"].append(int(row["batch_size"]       )       )
                self.result_dict[model_name]["seq_len"].append(int(row["sequence_length"]       )       )
                if can_convert_to_int(row["result"]       ):
                     # value is not None
                     _lowerCAmelCase   :					Optional[int]        =    int(row["result"]       )
                elif can_convert_to_float(row["result"]       ):
                     # value is not None
                     _lowerCAmelCase   :					Optional[int]        =    float(row["result"]       )


 def    __magic_name__       (		self :	List[str]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					str        =    plt.subplots()
      _lowerCAmelCase   :					Tuple        =    "Time usage" if self.args.is_time else "Memory usage"
      _lowerCAmelCase   :					Union[str, Any]        =    title_str + " for training" if self.args.is_train else title_str + " for inference"

      if not self.args.no_log_scale:
           # set logarithm scales
           ax.set_xscale("log"       )
           ax.set_yscale("log"       )

      for axis in [ax.xaxis, ax.yaxis]:
           axis.set_major_formatter(ScalarFormatter()       )

      for model_name_idx, model_name in enumerate(self.result_dict.keys()       ):
           _lowerCAmelCase   :					List[str]        =    sorted(set(self.result_dict[model_name]["bsz"]       )       )
           _lowerCAmelCase   :					Tuple        =    sorted(set(self.result_dict[model_name]["seq_len"]       )       )
           _lowerCAmelCase   :					Union[str, Any]        =    self.result_dict[model_name]["result"]

           (_lowerCAmelCase)   :					Dict        =    (
               (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes)
           )

           _lowerCAmelCase   :					List[Any]        =    (
               model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx]
           )

           for inner_loop_value in inner_loop_array:
                if self.args.plot_along_batch:
                     _lowerCAmelCase   :					Tuple        =    np.asarray(
                         [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results]     ,						dtype=A_     ,						)
                else:
                     _lowerCAmelCase   :					Optional[Any]        =    np.asarray(
                         [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results]     ,						dtype=np.floataa     ,						)

                (_lowerCAmelCase)   :					List[str]        =    (
                    ("batch_size", "len") if self.args.plot_along_batch else ("in #tokens", "bsz")
                )

                _lowerCAmelCase   :					List[Any]        =    np.asarray(A_     ,						A_       )[: len(A_       )]
                plt.scatter(
                    A_     ,						A_     ,						label=F'''{label_model_name} - {inner_loop_label}: {inner_loop_value}'''       )
                plt.plot(A_     ,						A_     ,						"--"       )

           title_str += F''' {label_model_name} vs.'''

      _lowerCAmelCase   :					Dict        =    title_str[:-4]
      _lowerCAmelCase   :					Union[str, Any]        =    "Time in s" if self.args.is_time else "Memory in MB"

      # plot
      plt.title(A_       )
      plt.xlabel(A_       )
      plt.ylabel(A_       )
      plt.legend()

      if self.args.figure_png_file is not None:
           plt.savefig(self.args.figure_png_file       )
      else:
           plt.show()







def 	_snake_case		(    )       ->      int:

     """simple docstring"""







     _lowerCAmelCase   :					Dict        =    HfArgumentParser(SCREAMING_SNAKE_CASE				)
     _lowerCAmelCase   :					Optional[Any]        =    parser.parse_args_into_dataclasses()[0]
     _lowerCAmelCase   :					str        =    Plot(args=SCREAMING_SNAKE_CASE				)
     plot.plot()


if __name__ == "__main__":
  main()









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






