


'''simple docstring'''



import gc
import tempfile
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionPipeline
from diffusers.utils.testing_utils import load_image, nightly, require_torch_gpu, torch_device


__lowercase     :						Optional[Any]	=     False





class 							__UpperCamelCase    (		unittest.TestCase ):
	pass





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




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





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




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						__a      :	Tuple    =  VersatileDiffusionPipeline.from_pretrained('shi-labs/versatile-diffusion'						,    torch_dtype=torch.floataa							)
						pipe.to(__a							)
						pipe.set_progress_bar_config(disable=__a							)

						__a      :	List[str]    =  load_image(
						    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'							)

						__a      :	Optional[int]    =  torch.manual_seed(0							)
						__a      :	Tuple    =  pipe.dual_guided(
						    prompt='first prompt'						,    image=__a						,    text_to_image_strength=0.75						,    generator=__a						,    guidance_scale=7.5						,    num_inference_steps=2						,    output_type='numpy'						,    ).images

						with tempfile.TemporaryDirectory() as tmpdirname:
											pipe.save_pretrained(__a							)
											__a      :	Union[str, Any]    =  VersatileDiffusionPipeline.from_pretrained(__a						,    torch_dtype=torch.floataa							)
						pipe.to(__a							)
						pipe.set_progress_bar_config(disable=__a							)

						__a      :	Tuple    =  generator.manual_seed(0							)
						__a      :	Dict    =  pipe.dual_guided(
						    prompt='first prompt'						,    image=__a						,    text_to_image_strength=0.75						,    generator=__a						,    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'''





						__a      :	List[Any]    =  VersatileDiffusionPipeline.from_pretrained('shi-labs/versatile-diffusion'						,    torch_dtype=torch.floataa							)
						pipe.to(__a							)
						pipe.set_progress_bar_config(disable=__a							)

						__a      :	str    =  'cyberpunk 2077'
						__a      :	str    =  load_image(
						    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg'							)
						__a      :	Tuple    =  torch.manual_seed(0							)
						__a      :	int    =  pipe.dual_guided(
						    prompt=__a						,    image=__a						,    text_to_image_strength=0.75						,    generator=__a						,    guidance_scale=7.5						,    num_inference_steps=50						,    output_type='numpy'						,    ).images

						__a      :	List[Any]    =  image[0, 253:256, 253:256, -1]

						assert image.shape == (1, 512, 512, 3)
						__a      :	List[Any]    =  np.array([0.1448, 0.1619, 0.1741, 0.1086, 0.1147, 0.1128, 0.1199, 0.1165, 0.1001]							)

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

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

						__a      :	int    =  image[0, 253:256, 253:256, -1]

						assert image.shape == (1, 512, 512, 3)
						__a      :	Tuple    =  np.array([0.3367, 0.3169, 0.2656, 0.3870, 0.4790, 0.3796, 0.4009, 0.4878, 0.4778]							)

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

						__a      :	str    =  pipe.image_variation(__a						,    generator=__a						,    output_type='numpy'							).images

						__a      :	Optional[Any]    =  image[0, 253:256, 253:256, -1]

						assert image.shape == (1, 512, 512, 3)
						__a      :	int    =  np.array([0.3076, 0.3123, 0.3284, 0.3782, 0.3770, 0.3894, 0.4297, 0.4331, 0.4456]							)

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




'''simple docstring'''



import os
import socket
from contextlib import contextmanager

import torch

from ..commands.config.default import write_basic_config  # noqa: F401
from ..state import PartialState
from .dataclasses import DistributedType
from .imports import is_deepspeed_available, is_tpu_available
from .transformer_engine import convert_model
from .versions import is_torch_version


if is_deepspeed_available():
	from deepspeed import DeepSpeedEngine

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






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE				:       Optional[Any]       ):
					if is_torch_version('<'						,				'2.0.0'       ) or not hasattr(_SCREAMING_SNAKE_CASE						,				'_dynamo'       ):
										return False
					return isinstance(_SCREAMING_SNAKE_CASE						,				torch._dynamo.eval_frame.OptimizedModule       )






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE				:       Optional[Any]						,				_SCREAMING_SNAKE_CASE				:       bool = True       ):
					__a      :	int    =  (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel)

					__a      :	Any    =  is_compiled_module(_SCREAMING_SNAKE_CASE       )
					if is_compiled:
										__a      :	List[Any]    =  model
										__a      :	Union[str, Any]    =  model._orig_mod

					if is_deepspeed_available():
										options += (DeepSpeedEngine,)

					while isinstance(_SCREAMING_SNAKE_CASE						,				_SCREAMING_SNAKE_CASE       ):
										__a      :	Union[str, Any]    =  model.module

					if not keep_fpaa_wrapper:
										__a      :	Optional[Any]    =  getattr(_SCREAMING_SNAKE_CASE						,				'forward'       )
										__a      :	str    =  model.__dict__.pop('_original_forward'						,				_SCREAMING_SNAKE_CASE       )
										if original_forward is not None:
															while hasattr(_SCREAMING_SNAKE_CASE						,				'__wrapped__'       ):
																				__a      :	Any    =  forward.__wrapped__
																				if forward == original_forward:
																									break
															__a      :	str    =  forward
										if getattr(_SCREAMING_SNAKE_CASE						,				'_converted_to_transformer_engine'						,				_SCREAMING_SNAKE_CASE       ):
															convert_model(_SCREAMING_SNAKE_CASE						,				to_transformer_engine=_SCREAMING_SNAKE_CASE       )

					if is_compiled:
										__a      :	List[str]    =  model
										__a      :	Optional[int]    =  compiled_model

					return model






def   lowerCamelCase							():
					PartialState().wait_for_everyone()






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE				:       int						,				_SCREAMING_SNAKE_CASE				:       Tuple       ):
					if PartialState().distributed_type == DistributedType.TPU:
										xm.save(_SCREAMING_SNAKE_CASE						,				_SCREAMING_SNAKE_CASE       )
					elif PartialState().local_process_index == 0:
										torch.save(_SCREAMING_SNAKE_CASE						,				_SCREAMING_SNAKE_CASE       )






@contextmanager
def   lowerCamelCase							(**_SCREAMING_SNAKE_CASE				:       Tuple       ):
					for key, value in kwargs.items():
										__a      :	Optional[int]    =  str(_SCREAMING_SNAKE_CASE       )

					yield

					for key in kwargs:
										if key.upper() in os.environ:
															del os.environ[key.upper()]






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE				:       Dict       ):
					if not hasattr(_SCREAMING_SNAKE_CASE						,				'__qualname__'       ) and not hasattr(_SCREAMING_SNAKE_CASE						,				'__name__'       ):
										__a      :	List[Any]    =  getattr(_SCREAMING_SNAKE_CASE						,				'__class__'						,				_SCREAMING_SNAKE_CASE       )
					if hasattr(_SCREAMING_SNAKE_CASE						,				'__qualname__'       ):
										return obj.__qualname__
					if hasattr(_SCREAMING_SNAKE_CASE						,				'__name__'       ):
										return obj.__name__
					return str(_SCREAMING_SNAKE_CASE       )






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE				:       int						,				_SCREAMING_SNAKE_CASE				:       List[str]       ):
					for key, value in source.items():
										if isinstance(_SCREAMING_SNAKE_CASE						,				_SCREAMING_SNAKE_CASE       ):
															__a      :	int    =  destination.setdefault(_SCREAMING_SNAKE_CASE						,				{}       )
															merge_dicts(_SCREAMING_SNAKE_CASE						,				_SCREAMING_SNAKE_CASE       )
										else:
															__a      :	Tuple    =  value

					return destination






def   lowerCamelCase							(_SCREAMING_SNAKE_CASE				:       int = None       ):
					if port is None:
										__a      :	List[str]    =  29_500
					with socket.socket(socket.AF_INET						,				socket.SOCK_STREAM       ) as s:
										return s.connect_ex(('localhost', port)       ) == 0



