


"""simple docstring"""






import logging
import os
import threading
import time


try:
							import warnings
except ImportError:
							UpperCAmelCase       :	Tuple  		=						None

try:
							import msvcrt
except ImportError:
							UpperCAmelCase       :	Any  		=						None

try:
							import fcntl
except ImportError:
							UpperCAmelCase       :	List[str]  		=						None


# Backward compatibility
# ------------------------------------------------
try:
							TimeoutError
except NameError:
							UpperCAmelCase       :	Optional[int]  		=						OSError


# Data
# ------------------------------------------------
UpperCAmelCase       :	int  		=						[
    'Timeout',
    'BaseFileLock',
    'WindowsFileLock',
    'UnixFileLock',
    'SoftFileLock',
    'FileLock',
]

UpperCAmelCase       :	List[str]  		=						'3.0.12'


UpperCAmelCase       :	int  		=						None
def 	lowerCamelCase			(	)						->			Optional[Any]:

							'''simple docstring'''



							global _logger
							__UpperCAmelCase  :		List[str] 				=   _logger or logging.getLogger(__name__				)
							return _logger





class 	lowerCamelCase__  (	__UpperCAmelCase							):







					"""simple docstring"""


					def __init__(			self       :					Tuple					,			UpperCamelCase       :					Tuple    ):
												'''simple docstring'''






												__UpperCAmelCase  :		str 				=   lock_file
												return None






					def __str__(			self       :					int    ):
												'''simple docstring'''






												__UpperCAmelCase  :		List[str] 				=   f'''The file lock \'{self.lock_file}\' could not be acquired.'''
												return temp






class 	lowerCamelCase__  :







					"""simple docstring"""


					def __init__(			self       :					Optional[Any]					,			UpperCamelCase       :					int    ):
												'''simple docstring'''






												__UpperCAmelCase  :		str 				=   lock
												return None






					def __enter__(			self       :					Optional[Any]    ):
												'''simple docstring'''






												return self.lock






					def __exit__(			self       :					Tuple					,			UpperCamelCase       :					Any					,			UpperCamelCase       :					List[Any]					,			UpperCamelCase       :					List[Any]    ):
												'''simple docstring'''






												self.lock.release()
												return None






class 	lowerCamelCase__  :







					"""simple docstring"""


					def __init__(			self       :					Any					,			UpperCamelCase       :					Union[str, Any]					,			UpperCamelCase       :					Any=-1					,			UpperCamelCase       :					Tuple=None    ):
												'''simple docstring'''






												__UpperCAmelCase  :		Union[str, Any] 				=   max_filename_length if max_filename_length is not None else 255
												# Hash the filename if it's too long
												__UpperCAmelCase  :		List[Any] 				=   self.hash_filename_if_too_long(lowerCAmelCase_					,			lowerCAmelCase_    )
												# The path to the lock file.
												__UpperCAmelCase  :		List[str] 				=   lock_file

												# The file descriptor for the *_lock_file* as it is returned by the
												# os.open() function.
												# This file lock is only NOT None, if the object currently holds the
												# lock.
												__UpperCAmelCase  :		Optional[Any] 				=   None

												# The default timeout value.
												__UpperCAmelCase  :		str 				=   timeout

												# We use this lock primarily for the lock counter.
												__UpperCAmelCase  :		str 				=   threading.Lock()

												# The lock counter is used for implementing the nested locking
												# mechanism. Whenever the lock is acquired, the counter is increased and
												# the lock is only released, when this value is 0 again.
												__UpperCAmelCase  :		Optional[Any] 				=   0
												return None






					@property
					def lowerCamelCase__				(			self       :					Dict    ):
												'''simple docstring'''






												return self._lock_file






					@property
					def lowerCamelCase__				(			self       :					str    ):
												'''simple docstring'''






												return self._timeout






					@timeout.setter
					def lowerCamelCase__				(			self       :					List[Any]					,			UpperCamelCase       :					Dict    ):
												'''simple docstring'''






												__UpperCAmelCase  :		Any 				=   float(lowerCAmelCase_    )
												return None






					def lowerCamelCase__				(			self       :					Tuple    ):
												'''simple docstring'''






												raise NotImplementedError()






					def lowerCamelCase__				(			self       :					str    ):
												'''simple docstring'''






												raise NotImplementedError()






					@property
					def lowerCamelCase__				(			self       :					Tuple    ):
												'''simple docstring'''






												return self._lock_file_fd is not None






					def lowerCamelCase__				(			self       :					Optional[int]					,			UpperCamelCase       :					int=None					,			UpperCamelCase       :					Union[str, Any]=0.05    ):
												'''simple docstring'''






												if timeout is None:
																			__UpperCAmelCase  :		Optional[int] 				=   self.timeout

												# Increment the number right at the beginning.
												# We can still undo it, if something fails.
												with self._thread_lock:
																			self._lock_counter += 1

												__UpperCAmelCase  :		List[str] 				=   id(self    )
												__UpperCAmelCase  :		Optional[Any] 				=   self._lock_file
												__UpperCAmelCase  :		Any 				=   time.time()
												try:
																			while True:
																										with self._thread_lock:
																																	if not self.is_locked:
																																								logger().debug(f'''Attempting to acquire lock {lock_id} on {lock_filename}'''    )
																																								self._acquire()

																										if self.is_locked:
																																	logger().debug(f'''Lock {lock_id} acquired on {lock_filename}'''    )
																																	break
																										elif timeout >= 0 and time.time() - start_time > timeout:
																																	logger().debug(f'''Timeout on acquiring lock {lock_id} on {lock_filename}'''    )
																																	raise Timeout(self._lock_file    )
																										else:
																																	logger().debug(
																																	    f'''Lock {lock_id} not acquired on {lock_filename}, waiting {poll_intervall} seconds ...'''    )
																																	time.sleep(lowerCAmelCase_    )
												except:  # noqa
																			# Something did go wrong, so decrement the counter.
																			with self._thread_lock:
																										__UpperCAmelCase  :		Optional[int] 				=   max(0					,			self._lock_counter - 1    )

																			raise
												return _Acquire_ReturnProxy(lock=self    )






					def lowerCamelCase__				(			self       :					Optional[int]					,			UpperCamelCase       :					int=False    ):
												'''simple docstring'''






												with self._thread_lock:
																			if self.is_locked:
																										self._lock_counter -= 1

																										if self._lock_counter == 0 or force:
																																	__UpperCAmelCase  :		str 				=   id(self    )
																																	__UpperCAmelCase  :		Any 				=   self._lock_file

																																	logger().debug(f'''Attempting to release lock {lock_id} on {lock_filename}'''    )
																																	self._release()
																																	__UpperCAmelCase  :		List[Any] 				=   0
																																	logger().debug(f'''Lock {lock_id} released on {lock_filename}'''    )

												return None






					def __enter__(			self       :					List[str]    ):
												'''simple docstring'''






												self.acquire()
												return self






					def __exit__(			self       :					List[str]					,			UpperCamelCase       :					Union[str, Any]					,			UpperCamelCase       :					Dict					,			UpperCamelCase       :					int    ):
												'''simple docstring'''






												self.release()
												return None






					def __del__(			self       :					List[Any]    ):
												'''simple docstring'''






												self.release(force=lowerCAmelCase_    )
												return None






					def lowerCamelCase__				(			self       :					Union[str, Any]					,			UpperCamelCase       :					int					,			UpperCamelCase       :					Union[str, Any]    ):
												'''simple docstring'''






												__UpperCAmelCase  :		int 				=   os.path.basename(lowerCAmelCase_    )
												if len(lowerCAmelCase_    ) > max_length and max_length > 0:
																			__UpperCAmelCase  :		Optional[int] 				=   os.path.dirname(lowerCAmelCase_    )
																			__UpperCAmelCase  :		int 				=   str(hash(lowerCAmelCase_    )    )
																			__UpperCAmelCase  :		Optional[int] 				=   filename[: max_length - len(lowerCAmelCase_    ) - 8] + '...' + hashed_filename + '.lock'
																			return os.path.join(lowerCAmelCase_					,			lowerCAmelCase_    )
												else:
																			return path






class 	lowerCamelCase__  (	__UpperCAmelCase							):







					"""simple docstring"""


					def __init__(			self       :					List[Any]					,			UpperCamelCase       :					Union[str, Any]					,			UpperCamelCase       :					int=-1					,			UpperCamelCase       :					Any=None    ):
												'''simple docstring'''






												from .file_utils import relative_to_absolute_path

												super().__init__(lowerCAmelCase_					,			timeout=lowerCAmelCase_					,			max_filename_length=lowerCAmelCase_    )
												__UpperCAmelCase  :		Tuple 				=   '\\\\?\\' + relative_to_absolute_path(self.lock_file    )






					def lowerCamelCase__				(			self       :					List[str]    ):
												'''simple docstring'''






												__UpperCAmelCase  :		Union[str, Any] 				=   os.O_RDWR | os.O_CREAT | os.O_TRUNC

												try:
																			__UpperCAmelCase  :		Dict 				=   os.open(self._lock_file					,			lowerCAmelCase_    )
												except OSError:
																			pass
												else:
																			try:
																										msvcrt.locking(lowerCAmelCase_					,			msvcrt.LK_NBLCK					,			1    )
																			except OSError:
																										os.close(lowerCAmelCase_    )
																			else:
																										__UpperCAmelCase  :		int 				=   fd
												return None






					def lowerCamelCase__				(			self       :					List[str]    ):
												'''simple docstring'''






												__UpperCAmelCase  :		List[Any] 				=   self._lock_file_fd
												__UpperCAmelCase  :		List[str] 				=   None
												msvcrt.locking(lowerCAmelCase_					,			msvcrt.LK_UNLCK					,			1    )
												os.close(lowerCAmelCase_    )

												try:
																			os.remove(self._lock_file    )
												# Probably another instance of the application
												# that acquired the file lock.
												except OSError:
																			pass
												return None






class 	lowerCamelCase__  (	__UpperCAmelCase							):







					"""simple docstring"""


					def __init__(			self       :					int					,			UpperCamelCase       :					Union[str, Any]					,			UpperCamelCase       :					int=-1					,			UpperCamelCase       :					Tuple=None    ):
												'''simple docstring'''






												__UpperCAmelCase  :		int 				=   os.statvfs(os.path.dirname(lowerCAmelCase_    )    ).f_namemax
												super().__init__(lowerCAmelCase_					,			timeout=lowerCAmelCase_					,			max_filename_length=lowerCAmelCase_    )






					def lowerCamelCase__				(			self       :					Tuple    ):
												'''simple docstring'''






												__UpperCAmelCase  :		Union[str, Any] 				=   os.O_RDWR | os.O_CREAT | os.O_TRUNC
												__UpperCAmelCase  :		Optional[int] 				=   os.open(self._lock_file					,			lowerCAmelCase_    )

												try:
																			fcntl.flock(lowerCAmelCase_					,			fcntl.LOCK_EX | fcntl.LOCK_NB    )
												except OSError:
																			os.close(lowerCAmelCase_    )
												else:
																			__UpperCAmelCase  :		Any 				=   fd
												return None






					def lowerCamelCase__				(			self       :					str    ):
												'''simple docstring'''






												__UpperCAmelCase  :		str 				=   self._lock_file_fd
												__UpperCAmelCase  :		Any 				=   None
												fcntl.flock(lowerCAmelCase_					,			fcntl.LOCK_UN    )
												os.close(lowerCAmelCase_    )
												return None






class 	lowerCamelCase__  (	__UpperCAmelCase							):







					"""simple docstring"""


					def lowerCamelCase__				(			self       :					Union[str, Any]    ):
												'''simple docstring'''






												__UpperCAmelCase  :		List[Any] 				=   os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_TRUNC
												try:
																			__UpperCAmelCase  :		List[Any] 				=   os.open(self._lock_file					,			lowerCAmelCase_    )
												except OSError:
																			pass
												else:
																			__UpperCAmelCase  :		Tuple 				=   fd
												return None






					def lowerCamelCase__				(			self       :					List[Any]    ):
												'''simple docstring'''






												os.close(self._lock_file_fd    )
												__UpperCAmelCase  :		int 				=   None

												try:
																			os.remove(self._lock_file    )
												# The file is already deleted and that's what we want.
												except OSError:
																			pass
												return None






UpperCAmelCase       :	Union[str, Any]  		=						None

if msvcrt:
							UpperCAmelCase       :	Optional[Any]  		=						WindowsFileLock
elif fcntl:
							UpperCAmelCase       :	Dict  		=						UnixFileLock
else:
							UpperCAmelCase       :	Union[str, Any]  		=						SoftFileLock

							if warnings is not None:
														warnings.warn('only soft file lock is available')








"""simple docstring"""
import gc
import unittest

from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline
from diffusers.utils import is_flax_available, slow
from diffusers.utils.testing_utils import require_flax


if is_flax_available():
			import jax
			import jax.numpy as jnp
			from flax.jax_utils import replicate
			from flax.training.common_utils import shard


@slow
@require_flax
class _lowerCAmelCase						(    unittest.TestCase       ):







						def 			A      (    self							)		->							Any:
										# clean up the VRAM after each test
										super().tearDown()
										gc.collect()







						def 			A      (    self							)		->							int:
										_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    FlaxStableDiffusionPipeline.from_pretrained(
										    'stabilityai/stable-diffusion-2'   ,				revision='bf16'   ,				dtype=jnp.bfloataa   ,				)

										_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    'A painting of a squirrel eating a burger'
										_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    jax.device_count()
										_SCREAMING_SNAKE_CASE   :		List[Any]       		=    num_samples * [prompt]
										_SCREAMING_SNAKE_CASE   :		Any       		=    sd_pipe.prepare_inputs(lowerCAmelCase_							)

										_SCREAMING_SNAKE_CASE   :		List[Any]       		=    replicate(lowerCAmelCase_							)
										_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    shard(lowerCAmelCase_							)

										_SCREAMING_SNAKE_CASE   :		Any       		=    jax.random.PRNGKey(0							)
										_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    jax.random.split(lowerCAmelCase_   ,				jax.device_count()							)

										_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    sd_pipe(lowerCAmelCase_   ,				lowerCAmelCase_   ,				lowerCAmelCase_   ,				num_inference_steps=2_5   ,				jit=lowerCAmelCase_							)[0]
										assert images.shape == (jax.device_count(), 1, 7_6_8, 7_6_8, 3)

										_SCREAMING_SNAKE_CASE   :		int       		=    images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:]							)
										_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]

										_SCREAMING_SNAKE_CASE   :		Tuple       		=    jnp.asarray(jax.device_get(image_slice.flatten()							)							)
										_SCREAMING_SNAKE_CASE   :		List[Any]       		=    jnp.array([0.4_238, 0.4_414, 0.4_395, 0.4_453, 0.4_629, 0.4_590, 0.4_531, 0.45_508, 0.4_512]							)
										print(F"""output_slice: {output_slice}"""							)
										assert jnp.abs(output_slice - expected_slice							).max() < 1e-2







						def 			A      (    self							)		->							Optional[int]:
										_SCREAMING_SNAKE_CASE   :		str       		=    'stabilityai/stable-diffusion-2'
										_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE   :		int       		=    FlaxDPMSolverMultistepScheduler.from_pretrained(lowerCAmelCase_   ,				subfolder='scheduler'							)
										_SCREAMING_SNAKE_CASE		,						_SCREAMING_SNAKE_CASE   :		List[str]       		=    FlaxStableDiffusionPipeline.from_pretrained(
										    lowerCAmelCase_   ,				scheduler=lowerCAmelCase_   ,				revision='bf16'   ,				dtype=jnp.bfloataa   ,				)
										_SCREAMING_SNAKE_CASE   :		Any       		=    scheduler_params

										_SCREAMING_SNAKE_CASE   :		int       		=    'A painting of a squirrel eating a burger'
										_SCREAMING_SNAKE_CASE   :		Tuple       		=    jax.device_count()
										_SCREAMING_SNAKE_CASE   :		Union[str, Any]       		=    num_samples * [prompt]
										_SCREAMING_SNAKE_CASE   :		Any       		=    sd_pipe.prepare_inputs(lowerCAmelCase_							)

										_SCREAMING_SNAKE_CASE   :		Dict       		=    replicate(lowerCAmelCase_							)
										_SCREAMING_SNAKE_CASE   :		Any       		=    shard(lowerCAmelCase_							)

										_SCREAMING_SNAKE_CASE   :		Any       		=    jax.random.PRNGKey(0							)
										_SCREAMING_SNAKE_CASE   :		Optional[Any]       		=    jax.random.split(lowerCAmelCase_   ,				jax.device_count()							)

										_SCREAMING_SNAKE_CASE   :		int       		=    sd_pipe(lowerCAmelCase_   ,				lowerCAmelCase_   ,				lowerCAmelCase_   ,				num_inference_steps=2_5   ,				jit=lowerCAmelCase_							)[0]
										assert images.shape == (jax.device_count(), 1, 7_6_8, 7_6_8, 3)

										_SCREAMING_SNAKE_CASE   :		str       		=    images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:]							)
										_SCREAMING_SNAKE_CASE   :		str       		=    images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]

										_SCREAMING_SNAKE_CASE   :		int       		=    jnp.asarray(jax.device_get(image_slice.flatten()							)							)
										_SCREAMING_SNAKE_CASE   :		Optional[int]       		=    jnp.array([0.4_336, 0.42_969, 0.4_453, 0.4_199, 0.4_297, 0.4_531, 0.4_434, 0.4_434, 0.4_297]							)
										print(F"""output_slice: {output_slice}"""							)
										assert jnp.abs(output_slice - expected_slice							).max() < 1e-2

