


import gc
import unittest

import numpy as np
import torch

from diffusers import StableDiffusionKDiffusionPipeline
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()







@slow
@require_torch_gpu
class        snake_case_   (unittest.TestCase      ):
					def  lowerCamelCase__(      self   :Union[str, Any]      )					->    List[Any]:
												# clean up the VRAM after each test
												super().tearDown()
												gc.collect()
												torch.cuda.empty_cache()
					def  lowerCamelCase__(      self   :int      )					->    str:
												a__             =     StableDiffusionKDiffusionPipeline.from_pretrained('CompVis/stable-diffusion-v1-4'      )
												a__             =     sd_pipe.to(__snake_case      )
												sd_pipe.set_progress_bar_config(disable=__snake_case      )

												sd_pipe.set_scheduler('sample_euler'      )

												a__             =     'A painting of a squirrel eating a burger'
												a__             =     torch.manual_seed(0      )
												a__             =     sd_pipe([prompt]			,generator=__snake_case			,guidance_scale=9.0			,num_inference_steps=20			,output_type='np'      )

												a__             =     output.images

												a__             =     image[0, -3:, -3:, -1]

												assert image.shape == (1, 5_12, 5_12, 3)
												a__             =     np.array([0.04_47, 0.04_92, 0.04_68, 0.04_08, 0.03_83, 0.04_08, 0.03_54, 0.03_80, 0.03_39]      )

												assert np.abs(image_slice.flatten() - expected_slice      ).max() < 1E-2
					def  lowerCamelCase__(      self   :int      )					->    List[str]:
												a__             =     StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base'      )
												a__             =     sd_pipe.to(__snake_case      )
												sd_pipe.set_progress_bar_config(disable=__snake_case      )

												sd_pipe.set_scheduler('sample_euler'      )

												a__             =     'A painting of a squirrel eating a burger'
												a__             =     torch.manual_seed(0      )
												a__             =     sd_pipe([prompt]			,generator=__snake_case			,guidance_scale=9.0			,num_inference_steps=20			,output_type='np'      )

												a__             =     output.images

												a__             =     image[0, -3:, -3:, -1]

												assert image.shape == (1, 5_12, 5_12, 3)
												a__             =     np.array([0.12_37, 0.13_20, 0.14_38, 0.13_59, 0.13_90, 0.11_32, 0.12_77, 0.11_75, 0.11_12]      )

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



					def  lowerCamelCase__(      self   :List[Any]      )					->    str:
												a__             =     StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base'      )
												a__             =     sd_pipe.to(__snake_case      )
												sd_pipe.set_progress_bar_config(disable=__snake_case      )

												sd_pipe.set_scheduler('sample_dpmpp_2m'      )

												a__             =     'A painting of a squirrel eating a burger'
												a__             =     torch.manual_seed(0      )
												a__             =     sd_pipe(
												    [prompt]			,generator=__snake_case			,guidance_scale=7.5			,num_inference_steps=15			,output_type='np'			,use_karras_sigmas=__snake_case			,)

												a__             =     output.images

												a__             =     image[0, -3:, -3:, -1]

												assert image.shape == (1, 5_12, 5_12, 3)
												a__             =     np.array(
												    [0.11_38_16_89, 0.12_11_29_21, 0.1_38_94_57, 0.12_54_96_06, 0.1_24_49_64, 0.10_83_15_17, 0.11_56_28_66, 0.10_86_78_16, 0.10_49_90_48]      )

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








import os
import tempfile
import unittest
from pathlib import Path

from transformers import AutoConfig, is_torch_available
from transformers.testing_utils import require_torch, torch_device


if is_torch_available():
						from transformers import PyTorchBenchmark, PyTorchBenchmarkArguments







@require_torch
class        snake_case_   (unittest.TestCase      ):
					def  lowerCamelCase__(      self   :Any			,__snake_case   :List[Any]      )					->    Union[str, Any]:
												for model_result in results.values():
																			for batch_size, sequence_length in zip(model_result['bs']			,model_result['ss']      ):
																										a__             =     model_result['result'][batch_size][sequence_length]
																										self.assertIsNotNone(__snake_case      )
					def  lowerCamelCase__(      self   :List[str]      )					->    Union[str, Any]:
												a__             =     'sshleifer/tiny-gpt2'
												a__             =     PyTorchBenchmarkArguments(
												    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,multi_process=__snake_case			,)
												a__             =     PyTorchBenchmark(__snake_case      )
												a__             =     benchmark.run()
												self.check_results_dict_not_empty(results.time_inference_result      )
												self.check_results_dict_not_empty(results.memory_inference_result      )
					def  lowerCamelCase__(      self   :List[Any]      )					->    Union[str, Any]:
												a__             =     'sgugger/tiny-distilbert-classification'
												a__             =     PyTorchBenchmarkArguments(
												    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,multi_process=__snake_case			,only_pretrain_model=__snake_case			,)
												a__             =     PyTorchBenchmark(__snake_case      )
												a__             =     benchmark.run()
												self.check_results_dict_not_empty(results.time_inference_result      )
												self.check_results_dict_not_empty(results.memory_inference_result      )
					def  lowerCamelCase__(      self   :Optional[Any]      )					->    Optional[Any]:
												a__             =     'sshleifer/tiny-gpt2'
												a__             =     PyTorchBenchmarkArguments(
												    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,torchscript=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,multi_process=__snake_case			,)
												a__             =     PyTorchBenchmark(__snake_case      )
												a__             =     benchmark.run()
												self.check_results_dict_not_empty(results.time_inference_result      )
												self.check_results_dict_not_empty(results.memory_inference_result      )
					@unittest.skipIf(torch_device == 'cpu'			,'Cant do half precision'      )
					def  lowerCamelCase__(      self   :int      )					->    str:
												a__             =     'sshleifer/tiny-gpt2'
												a__             =     PyTorchBenchmarkArguments(
												    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,fpaa=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,multi_process=__snake_case			,)
												a__             =     PyTorchBenchmark(__snake_case      )
												a__             =     benchmark.run()
												self.check_results_dict_not_empty(results.time_inference_result      )
												self.check_results_dict_not_empty(results.memory_inference_result      )
					def  lowerCamelCase__(      self   :Optional[int]      )					->    Union[str, Any]:
												a__             =     'sshleifer/tiny-gpt2'
												a__             =     AutoConfig.from_pretrained(__snake_case      )
												# set architectures equal to `None`
												a__             =     None
												a__             =     PyTorchBenchmarkArguments(
												    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,multi_process=__snake_case			,)
												a__             =     PyTorchBenchmark(__snake_case			,configs=[config]      )
												a__             =     benchmark.run()
												self.check_results_dict_not_empty(results.time_inference_result      )
												self.check_results_dict_not_empty(results.memory_inference_result      )
					def  lowerCamelCase__(      self   :Dict      )					->    int:
												a__             =     'sshleifer/tiny-gpt2'
												a__             =     PyTorchBenchmarkArguments(
												    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,multi_process=__snake_case			,)
												a__             =     PyTorchBenchmark(__snake_case      )
												a__             =     benchmark.run()
												self.check_results_dict_not_empty(results.time_train_result      )
												self.check_results_dict_not_empty(results.memory_train_result      )
					@unittest.skipIf(torch_device == 'cpu'			,'Can\'t do half precision'      )
					def  lowerCamelCase__(      self   :int      )					->    List[str]:
												a__             =     'sshleifer/tiny-gpt2'
												a__             =     PyTorchBenchmarkArguments(
												    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,fpaa=__snake_case			,multi_process=__snake_case			,)
												a__             =     PyTorchBenchmark(__snake_case      )
												a__             =     benchmark.run()
												self.check_results_dict_not_empty(results.time_train_result      )
												self.check_results_dict_not_empty(results.memory_train_result      )
					def  lowerCamelCase__(      self   :str      )					->    Union[str, Any]:
												a__             =     'sshleifer/tiny-gpt2'
												a__             =     AutoConfig.from_pretrained(__snake_case      )
												a__             =     PyTorchBenchmarkArguments(
												    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,multi_process=__snake_case			,)
												a__             =     PyTorchBenchmark(__snake_case			,configs=[config]      )
												a__             =     benchmark.run()
												self.check_results_dict_not_empty(results.time_inference_result      )
												self.check_results_dict_not_empty(results.memory_inference_result      )
					def  lowerCamelCase__(      self   :List[Any]      )					->    Any:
												a__             =     'sshleifer/tinier_bart'
												a__             =     AutoConfig.from_pretrained(__snake_case      )
												a__             =     PyTorchBenchmarkArguments(
												    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,multi_process=__snake_case			,)
												a__             =     PyTorchBenchmark(__snake_case			,configs=[config]      )
												a__             =     benchmark.run()
												self.check_results_dict_not_empty(results.time_inference_result      )
												self.check_results_dict_not_empty(results.memory_inference_result      )
					def  lowerCamelCase__(      self   :Tuple      )					->    Dict:
												a__             =     'sshleifer/tiny-gpt2'
												a__             =     AutoConfig.from_pretrained(__snake_case      )
												a__             =     PyTorchBenchmarkArguments(
												    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,multi_process=__snake_case			,)
												a__             =     PyTorchBenchmark(__snake_case			,configs=[config]      )
												a__             =     benchmark.run()
												self.check_results_dict_not_empty(results.time_train_result      )
												self.check_results_dict_not_empty(results.memory_train_result      )
					def  lowerCamelCase__(      self   :Union[str, Any]      )					->    Optional[int]:
												a__             =     'sshleifer/tinier_bart'
												a__             =     AutoConfig.from_pretrained(__snake_case      )
												a__             =     PyTorchBenchmarkArguments(
												    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,multi_process=__snake_case			,)
												a__             =     PyTorchBenchmark(__snake_case			,configs=[config]      )
												a__             =     benchmark.run()
												self.check_results_dict_not_empty(results.time_train_result      )
												self.check_results_dict_not_empty(results.memory_train_result      )
					def  lowerCamelCase__(      self   :Optional[int]      )					->    List[Any]:
												a__             =     'sshleifer/tiny-gpt2'
												with tempfile.TemporaryDirectory() as tmp_dir:
																			a__             =     PyTorchBenchmarkArguments(
																			    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,save_to_csv=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,inference_time_csv_file=os.path.join(__snake_case			,'inf_time.csv'      )			,train_memory_csv_file=os.path.join(__snake_case			,'train_mem.csv'      )			,inference_memory_csv_file=os.path.join(__snake_case			,'inf_mem.csv'      )			,train_time_csv_file=os.path.join(__snake_case			,'train_time.csv'      )			,env_info_csv_file=os.path.join(__snake_case			,'env.csv'      )			,multi_process=__snake_case			,)
																			a__             =     PyTorchBenchmark(__snake_case      )
																			benchmark.run()
																			self.assertTrue(Path(os.path.join(__snake_case			,'inf_time.csv'      )      ).exists()      )
																			self.assertTrue(Path(os.path.join(__snake_case			,'train_time.csv'      )      ).exists()      )
																			self.assertTrue(Path(os.path.join(__snake_case			,'inf_mem.csv'      )      ).exists()      )
																			self.assertTrue(Path(os.path.join(__snake_case			,'train_mem.csv'      )      ).exists()      )
																			self.assertTrue(Path(os.path.join(__snake_case			,'env.csv'      )      ).exists()      )



					def  lowerCamelCase__(      self   :Optional[int]      )					->    List[str]:
												a__             =     'sshleifer/tiny-gpt2'

												def _check_summary_is_not_empty(__snake_case   :List[str]      ):
																			self.assertTrue(hasattr(__snake_case			,'sequential'      )      )
																			self.assertTrue(hasattr(__snake_case			,'cumulative'      )      )
																			self.assertTrue(hasattr(__snake_case			,'current'      )      )
																			self.assertTrue(hasattr(__snake_case			,'total'      )      )

												with tempfile.TemporaryDirectory() as tmp_dir:
																			a__             =     PyTorchBenchmarkArguments(
																			    models=[MODEL_ID]			,training=__snake_case			,inference=__snake_case			,sequence_lengths=[8]			,batch_sizes=[1]			,log_filename=os.path.join(__snake_case			,'log.txt'      )			,log_print=__snake_case			,trace_memory_line_by_line=__snake_case			,multi_process=__snake_case			,)
																			a__             =     PyTorchBenchmark(__snake_case      )
																			a__             =     benchmark.run()
																			_check_summary_is_not_empty(result.inference_summary      )
																			_check_summary_is_not_empty(result.train_summary      )
																			self.assertTrue(Path(os.path.join(__snake_case			,'log.txt'      )      ).exists()      )




