


"""simple docstring"""







from dataclasses import dataclass, field
from typing import Tuple

from ..utils import cached_property, is_torch_available, is_torch_tpu_available, logging, requires_backends
from .benchmark_args_utils import BenchmarkArguments


if is_torch_available():
			import torch

if is_torch_tpu_available(check_device=False):
			import torch_xla.core.xla_model as xm


a			:    Any				 =		logging.get_logger(__name__)


@dataclass
class    __UpperCAmelCase(       A__							):




						"""simple docstring"""




						__lowerCamelCase    	= [
						    "no_inference",
						    "no_cuda",
						    "no_tpu",
						    "no_speed",
						    "no_memory",
						    "no_env_print",
						    "no_multi_process",
						]




						def __init__(       self	,  **snake_case__      ):
												'''simple docstring'''
												for deprecated_arg in self.deprecated_args:
																		if deprecated_arg in kwargs:
																								lowercase__    :				int=	deprecated_arg[3:]
																								setattr(self	,  __A	,  not kwargs.pop(__A      )      )
																								logger.warning(
																								    F'''{deprecated_arg} is depreciated. Please use --no_{positive_arg} or'''
																								    F''' {positive_arg}={kwargs[positive_arg]}'''      )

												lowercase__    :				Optional[int]=	kwargs.pop("torchscript"	,  self.torchscript      )
												lowercase__    :				List[str]=	kwargs.pop("torch_xla_tpu_print_metrics"	,  self.torch_xla_tpu_print_metrics      )
												lowercase__    :				Tuple=	kwargs.pop("fp16_opt_level"	,  self.fpaa_opt_level      )
												super().__init__(**__A      )

						__lowerCamelCase    	= field(default=A__  ,  metadata={"help": "Trace the models using torchscript"}							)
						__lowerCamelCase    	= field(default=A__  ,  metadata={"help": "Print Xla/PyTorch tpu metrics"}							)
						__lowerCamelCase    	= field(
						    default="O1"  ,  metadata={
						        "help": (
						            "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']. "
						            "See details at https://nvidia.github.io/apex/amp.html"
						        )
						    }  ,  )




						@cached_property
						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												requires_backends(self	,  ["torch"]      )
												logger.info("PyTorch: setting up devices"      )
												if not self.cuda:
																		lowercase__    :				str=	torch.device("cpu"      )
																		lowercase__    :				Tuple=	0
												elif is_torch_tpu_available():
																		lowercase__    :				int=	xm.xla_device()
																		lowercase__    :				Optional[Any]=	0
												else:
																		lowercase__    :				Tuple=	torch.device("cuda" if torch.cuda.is_available() else "cpu"      )
																		lowercase__    :				List[str]=	torch.cuda.device_count()
												return device, n_gpu




						@property
						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												return is_torch_tpu_available() and self.tpu




						@property
						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												requires_backends(self	,  ["torch"]      )
												# TODO(PVP): currently only single GPU is supported
												return torch.cuda.current_device()




						@property
						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												requires_backends(self	,  ["torch"]      )
												return self._setup_devices[0]




						@property
						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												requires_backends(self	,  ["torch"]      )
												return self._setup_devices[1]




						@property
						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												return self.n_gpu > 0














"""simple docstring"""







import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionTextToImagePipeline
from diffusers.utils.testing_utils import nightly, require_torch_gpu, torch_device


a			:    Union[str, Any]				 =		False


class    __UpperCAmelCase(       unittest.TestCase							):




						"""simple docstring"""




						pass


@nightly
@require_torch_gpu
class    __UpperCAmelCase(       unittest.TestCase							):




						"""simple docstring"""




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												# clean up the VRAM after each test
												super().tearDown()
												gc.collect()
												torch.cuda.empty_cache()




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				Dict=	VersatileDiffusionTextToImagePipeline.from_pretrained("shi-labs/versatile-diffusion"      )
												# remove text_unet
												pipe.remove_unused_weights()
												pipe.to(snake_case__      )
												pipe.set_progress_bar_config(disable=snake_case__      )

												lowercase__    :				Any=	"A painting of a squirrel eating a burger "
												lowercase__    :				Optional[Any]=	torch.manual_seed(0      )
												lowercase__    :				List[str]=	pipe(
												    prompt=snake_case__	,  generator=snake_case__	,  guidance_scale=7.5	,  num_inference_steps=2	,  output_type="numpy"      ).images

												with tempfile.TemporaryDirectory() as tmpdirname:
																		pipe.save_pretrained(snake_case__      )
																		lowercase__    :				Optional[Any]=	VersatileDiffusionTextToImagePipeline.from_pretrained(snake_case__      )
												pipe.to(snake_case__      )
												pipe.set_progress_bar_config(disable=snake_case__      )

												lowercase__    :				Any=	generator.manual_seed(0      )
												lowercase__    :				Tuple=	pipe(
												    prompt=snake_case__	,  generator=snake_case__	,  guidance_scale=7.5	,  num_inference_steps=2	,  output_type="numpy"      ).images

												assert np.abs(image - new_image      ).sum() < 1e-5, "Models don't have the same forward pass"




						def 		UpperCAmelCase_	(       self      ):
												'''simple docstring'''
												lowercase__    :				Tuple=	VersatileDiffusionTextToImagePipeline.from_pretrained(
												    "shi-labs/versatile-diffusion"	,  torch_dtype=torch.floataa      )
												pipe.to(snake_case__      )
												pipe.set_progress_bar_config(disable=snake_case__      )

												lowercase__    :				List[str]=	"A painting of a squirrel eating a burger "
												lowercase__    :				Union[str, Any]=	torch.manual_seed(0      )
												lowercase__    :				Optional[Any]=	pipe(
												    prompt=snake_case__	,  generator=snake_case__	,  guidance_scale=7.5	,  num_inference_steps=50	,  output_type="numpy"      ).images

												lowercase__    :				List[str]=	image[0, 253:256, 253:256, -1]

												assert image.shape == (1, 512, 512, 3)
												lowercase__    :				Optional[int]=	np.array([0.33_67, 0.31_69, 0.26_56, 0.38_70, 0.47_90, 0.37_96, 0.40_09, 0.48_78, 0.47_78]      )

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






