


'''simple docstring'''



import os
import sys
import unittest


__lowercase     :						Any	=     os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, 'utils'))

import check_dummies  # noqa: E402
from check_dummies import create_dummy_files, create_dummy_object, find_backend, read_init  # noqa: E402


# Align TRANSFORMERS_PATH in check_dummies with the current path
__lowercase     :						Optional[Any]	=     os.path.join(git_repo_path, 'src', 'diffusers')





class 							__UpperCamelCase    (		unittest.TestCase ):




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						__a      :	Union[str, Any]    =  find_backend('    if not is_torch_available():'							)
						self.assertEqual(__a						,    'torch'							)

						# backend_with_underscore = find_backend("    if not is_tensorflow_text_available():")
						# self.assertEqual(backend_with_underscore, "tensorflow_text")

						__a      :	str    =  find_backend('    if not (is_torch_available() and is_transformers_available()):'							)
						self.assertEqual(__a						,    'torch_and_transformers'							)

						# double_backend_with_underscore = find_backend(
						#    "    if not (is_sentencepiece_available() and is_tensorflow_text_available()):"
						# )
						# self.assertEqual(double_backend_with_underscore, "sentencepiece_and_tensorflow_text")

						__a      :	Optional[int]    =  find_backend(
						    '    if not (is_torch_available() and is_transformers_available() and is_onnx_available()):'							)
						self.assertEqual(__a						,    'torch_and_transformers_and_onnx'							)




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						__a      :	List[str]    =  read_init()
						# We don't assert on the exact list of keys to allow for smooth grow of backend-specific objects
						self.assertIn('torch'						,    __a							)
						self.assertIn('torch_and_transformers'						,    __a							)
						self.assertIn('flax_and_transformers'						,    __a							)
						self.assertIn('torch_and_transformers_and_onnx'						,    __a							)

						# Likewise, we can't assert on the exact content of a key
						self.assertIn('UNet2DModel'						,    objects['torch']							)
						self.assertIn('FlaxUNet2DConditionModel'						,    objects['flax']							)
						self.assertIn('StableDiffusionPipeline'						,    objects['torch_and_transformers']							)
						self.assertIn('FlaxStableDiffusionPipeline'						,    objects['flax_and_transformers']							)
						self.assertIn('LMSDiscreteScheduler'						,    objects['torch_and_scipy']							)
						self.assertIn('OnnxStableDiffusionPipeline'						,    objects['torch_and_transformers_and_onnx']							)




	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						__a      :	Any    =  create_dummy_object('CONSTANT'						,    '\'torch\''							)
						self.assertEqual(__a						,    '\nCONSTANT = None\n'							)

						__a      :	Any    =  create_dummy_object('function'						,    '\'torch\''							)
						self.assertEqual(
						    __a						,    '\ndef function(*args, **kwargs):\n    requires_backends(function, \'torch\')\n'							)

						__a      :	List[Any]    =  '\nclass FakeClass(metaclass=DummyObject):\n    _backends = \'torch\'\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, \'torch\')\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, \'torch\')\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, \'torch\')\n'
						__a      :	Union[str, Any]    =  create_dummy_object('FakeClass'						,    '\'torch\''							)
						self.assertEqual(__a						,    __a							)





	def 				__UpperCAmelCase							(       self							):

						'''simple docstring'''





						__a      :	Tuple    =  '# This file is autogenerated by the command `make fix-copies`, do not edit.\nfrom ..utils import DummyObject, requires_backends\n\n\nCONSTANT = None\n\n\ndef function(*args, **kwargs):\n    requires_backends(function, ["torch"])\n\n\nclass FakeClass(metaclass=DummyObject):\n    _backends = ["torch"]\n\n    def __init__(self, *args, **kwargs):\n        requires_backends(self, ["torch"])\n\n    @classmethod\n    def from_config(cls, *args, **kwargs):\n        requires_backends(cls, ["torch"])\n\n    @classmethod\n    def from_pretrained(cls, *args, **kwargs):\n        requires_backends(cls, ["torch"])\n'
						__a      :	Optional[int]    =  create_dummy_files({'torch': ['CONSTANT', 'function', 'FakeClass']}							)
						self.assertEqual(dummy_files['torch']						,    __a							)







'''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



