
'''simple docstring'''




import logging
import os
import threading
import time


try:
      import warnings
except ImportError:
      lowercase			:				List[str]    		=			None

try:
      import msvcrt
except ImportError:
      lowercase			:				Optional[int]    		=			None

try:
      import fcntl
except ImportError:
      lowercase			:				Dict    		=			None


# Backward compatibility
# ------------------------------------------------
try:
      TimeoutError
except NameError:
      lowercase			:				Tuple    		=			OSError


# Data
# ------------------------------------------------
lowercase			:				Union[str, Any]    		=			[
    'Timeout',
    'BaseFileLock',
    'WindowsFileLock',
    'UnixFileLock',
    'SoftFileLock',
    'FileLock',
]

lowercase			:				List[str]    		=			'3.0.12'


lowercase			:				Optional[Any]    		=			None







def 		lowerCAmelCase_				(   ):




    '''simple docstring'''



    global _logger
    A       :   Optional[Any]					=						_logger or logging.getLogger(__name__						)
    return _logger





class  A				(							__snake_case						):





     def __init__(							self						,			SCREAMING_SNAKE_CASE	) ->				str:






         """simple docstring"""






         A       :   str					=						lock_file
         return None





     def __str__(							self	) ->				List[Any]:






         """simple docstring"""






         A       :   Dict					=						F'The file lock \'{self.lock_file}\' could not be acquired.'
         return temp





class  A				:





     def __init__(							self						,			SCREAMING_SNAKE_CASE	) ->				Union[str, Any]:






         """simple docstring"""






         A       :   List[Any]					=						lock
         return None





     def __enter__(							self	) ->				Union[str, Any]:






         """simple docstring"""






         return self.lock





     def __exit__(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	) ->				Tuple:






         """simple docstring"""






         self.lock.release()
         return None





class  A				:





     def __init__(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE=-1						,			SCREAMING_SNAKE_CASE=None	) ->				List[str]:






         """simple docstring"""






         A       :   str					=						max_filename_length if max_filename_length is not None else 255
         # Hash the filename if it's too long
         A       :   Optional[Any]					=						self.hash_filename_if_too_long(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)
         # The path to the lock file.
         A       :   Tuple					=						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.
         A       :   Tuple					=						None

         # The default timeout value.
         A       :   List[str]					=						timeout

         # We use this lock primarily for the lock counter.
         A       :   Optional[Any]					=						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.
         A       :   Optional[Any]					=						0
         return None





     @property
     def 				__lowerCAmelCase							(							self	) ->				int:






         """simple docstring"""






         return self._lock_file





     @property
     def 				__lowerCAmelCase							(							self	) ->				int:






         """simple docstring"""






         return self._timeout





     @timeout.setter
     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE	) ->				str:






         """simple docstring"""






         A       :   Optional[Any]					=						float(SCREAMING_SNAKE_CASE	)
         return None





     def 				__lowerCAmelCase							(							self	) ->				int:






         """simple docstring"""






         raise NotImplementedError()





     def 				__lowerCAmelCase							(							self	) ->				Any:






         """simple docstring"""






         raise NotImplementedError()





     @property
     def 				__lowerCAmelCase							(							self	) ->				str:






         """simple docstring"""






         return self._lock_file_fd is not None





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE=None						,			SCREAMING_SNAKE_CASE=0.05	) ->				Optional[Any]:






         """simple docstring"""






         if timeout is None:
             A       :   Optional[Any]					=						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

         A       :   List[str]					=						id(self	)
         A       :   Optional[Any]					=						self._lock_file
         A       :   Optional[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(SCREAMING_SNAKE_CASE	)
         except:  # noqa
             # Something did go wrong, so decrement the counter.
             with self._thread_lock:
                 A       :   List[str]					=						max(0						,			self._lock_counter - 1	)

             raise
         return _Acquire_ReturnProxy(lock=self	)





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE=False	) ->				Optional[Any]:






         """simple docstring"""






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

                 if self._lock_counter == 0 or force:
                     A       :   List[Any]					=						id(self	)
                     A       :   Tuple					=						self._lock_file

                     logger().debug(F'Attempting to release lock {lock_id} on {lock_filename}'	)
                     self._release()
                     A       :   List[str]					=						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						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	) ->				Optional[Any]:






         """simple docstring"""






         self.release()
         return None





     def __del__(							self	) ->				Any:






         """simple docstring"""






         self.release(force=SCREAMING_SNAKE_CASE	)
         return None





     def 				__lowerCAmelCase							(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	) ->				str:






         """simple docstring"""






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





class  A				(							__snake_case						):





     def __init__(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE=-1						,			SCREAMING_SNAKE_CASE=None	) ->				Any:






         """simple docstring"""






         from .file_utils import relative_to_absolute_path

         super().__init__(SCREAMING_SNAKE_CASE						,			timeout=SCREAMING_SNAKE_CASE						,			max_filename_length=SCREAMING_SNAKE_CASE	)
         A       :   Optional[Any]					=						'''\\\\?\\''' + relative_to_absolute_path(self.lock_file	)





     def 				__lowerCAmelCase							(							self	) ->				List[str]:






         """simple docstring"""






         A       :   List[str]					=						os.O_RDWR | os.O_CREAT | os.O_TRUNC

         try:
             A       :   Tuple					=						os.open(self._lock_file						,			SCREAMING_SNAKE_CASE	)
         except OSError:
             pass
         else:
             try:
                 msvcrt.locking(SCREAMING_SNAKE_CASE						,			msvcrt.LK_NBLCK						,			1	)
             except OSError:
                 os.close(SCREAMING_SNAKE_CASE	)
             else:
                 A       :   Optional[Any]					=						fd
         return None





     def 				__lowerCAmelCase							(							self	) ->				List[str]:






         """simple docstring"""






         A       :   List[Any]					=						self._lock_file_fd
         A       :   Optional[Any]					=						None
         msvcrt.locking(SCREAMING_SNAKE_CASE						,			msvcrt.LK_UNLCK						,			1	)
         os.close(SCREAMING_SNAKE_CASE	)

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





class  A				(							__snake_case						):





     def __init__(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE=-1						,			SCREAMING_SNAKE_CASE=None	) ->				Tuple:






         """simple docstring"""






         A       :   List[str]					=						os.statvfs(os.path.dirname(SCREAMING_SNAKE_CASE	)	).f_namemax
         super().__init__(SCREAMING_SNAKE_CASE						,			timeout=SCREAMING_SNAKE_CASE						,			max_filename_length=SCREAMING_SNAKE_CASE	)





     def 				__lowerCAmelCase							(							self	) ->				Tuple:






         """simple docstring"""






         A       :   int					=						os.O_RDWR | os.O_CREAT | os.O_TRUNC
         A       :   Tuple					=						os.open(self._lock_file						,			SCREAMING_SNAKE_CASE	)

         try:
             fcntl.flock(SCREAMING_SNAKE_CASE						,			fcntl.LOCK_EX | fcntl.LOCK_NB	)
         except OSError:
             os.close(SCREAMING_SNAKE_CASE	)
         else:
             A       :   Union[str, Any]					=						fd
         return None





     def 				__lowerCAmelCase							(							self	) ->				Tuple:






         """simple docstring"""






         A       :   Optional[int]					=						self._lock_file_fd
         A       :   str					=						None
         fcntl.flock(SCREAMING_SNAKE_CASE						,			fcntl.LOCK_UN	)
         os.close(SCREAMING_SNAKE_CASE	)
         return None





class  A				(							__snake_case						):





     def 				__lowerCAmelCase							(							self	) ->				List[Any]:






         """simple docstring"""






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





     def 				__lowerCAmelCase							(							self	) ->				Tuple:






         """simple docstring"""






         os.close(self._lock_file_fd	)
         A       :   Union[str, Any]					=						None

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





lowercase			:				Union[str, Any]    		=			None

if msvcrt:
      lowercase			:				Optional[int]    		=			WindowsFileLock
elif fcntl:
      lowercase			:				List[str]    		=			UnixFileLock
else:
      lowercase			:				Tuple    		=			SoftFileLock

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






'''simple docstring'''




import flax.linen as nn
import jax.numpy as jnp

from .attention_flax import FlaxTransformeraDModel
from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD





class  A				(							nn.Module						):
     __magic_name__						=		42
     __magic_name__						=		42
     __magic_name__						=		0.0
     __magic_name__						=		1
     __magic_name__						=		1
     __magic_name__						=		True
     __magic_name__						=		False
     __magic_name__						=		False
     __magic_name__						=		False
     __magic_name__						=		jnp.floataa





     def 				__lowerCAmelCase							(							self	) ->				Tuple:






         """simple docstring"""






         A       :   Union[str, Any]					=						[]
         A       :   Union[str, Any]					=						[]

         for i in range(self.num_layers	):
             A       :   Any					=						self.in_channels if i == 0 else self.out_channels

             A       :   Optional[Any]					=						FlaxResnetBlockaD(
                 in_channels=SCREAMING_SNAKE_CASE						,			out_channels=self.out_channels						,			dropout_prob=self.dropout						,			dtype=self.dtype						,			)
             resnets.append(SCREAMING_SNAKE_CASE	)

             A       :   Optional[int]					=						FlaxTransformeraDModel(
                 in_channels=self.out_channels						,			n_heads=self.num_attention_heads						,			d_head=self.out_channels // self.num_attention_heads						,			depth=1						,			use_linear_projection=self.use_linear_projection						,			only_cross_attention=self.only_cross_attention						,			use_memory_efficient_attention=self.use_memory_efficient_attention						,			dtype=self.dtype						,			)
             attentions.append(SCREAMING_SNAKE_CASE	)

         A       :   Union[str, Any]					=						resnets
         A       :   Union[str, Any]					=						attentions

         if self.add_downsample:
             A       :   int					=						FlaxDownsampleaD(self.out_channels						,			dtype=self.dtype	)





     def __call__(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE=True	) ->				Union[str, Any]:






         """simple docstring"""






         A       :   Optional[Any]					=						()

         for resnet, attn in zip(self.resnets						,			self.attentions	):
             A       :   int					=						resnet(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			deterministic=SCREAMING_SNAKE_CASE	)
             A       :   Dict					=						attn(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			deterministic=SCREAMING_SNAKE_CASE	)
             output_states += (hidden_states,)

         if self.add_downsample:
             A       :   Optional[Any]					=						self.downsamplers_a(SCREAMING_SNAKE_CASE	)
             output_states += (hidden_states,)

         return hidden_states, output_states





class  A				(							nn.Module						):
     __magic_name__						=		42
     __magic_name__						=		42
     __magic_name__						=		0.0
     __magic_name__						=		1
     __magic_name__						=		True
     __magic_name__						=		jnp.floataa





     def 				__lowerCAmelCase							(							self	) ->				Optional[Any]:






         """simple docstring"""






         A       :   Optional[Any]					=						[]

         for i in range(self.num_layers	):
             A       :   Optional[Any]					=						self.in_channels if i == 0 else self.out_channels

             A       :   List[str]					=						FlaxResnetBlockaD(
                 in_channels=SCREAMING_SNAKE_CASE						,			out_channels=self.out_channels						,			dropout_prob=self.dropout						,			dtype=self.dtype						,			)
             resnets.append(SCREAMING_SNAKE_CASE	)
         A       :   Dict					=						resnets

         if self.add_downsample:
             A       :   Dict					=						FlaxDownsampleaD(self.out_channels						,			dtype=self.dtype	)





     def __call__(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE=True	) ->				Optional[Any]:






         """simple docstring"""






         A       :   str					=						()

         for resnet in self.resnets:
             A       :   Optional[int]					=						resnet(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			deterministic=SCREAMING_SNAKE_CASE	)
             output_states += (hidden_states,)

         if self.add_downsample:
             A       :   Optional[int]					=						self.downsamplers_a(SCREAMING_SNAKE_CASE	)
             output_states += (hidden_states,)

         return hidden_states, output_states





class  A				(							nn.Module						):
     __magic_name__						=		42
     __magic_name__						=		42
     __magic_name__						=		42
     __magic_name__						=		0.0
     __magic_name__						=		1
     __magic_name__						=		1
     __magic_name__						=		True
     __magic_name__						=		False
     __magic_name__						=		False
     __magic_name__						=		False
     __magic_name__						=		jnp.floataa





     def 				__lowerCAmelCase							(							self	) ->				Tuple:






         """simple docstring"""






         A       :   Optional[Any]					=						[]
         A       :   Optional[int]					=						[]

         for i in range(self.num_layers	):
             A       :   str					=						self.in_channels if (i == self.num_layers - 1) else self.out_channels
             A       :   Dict					=						self.prev_output_channel if i == 0 else self.out_channels

             A       :   List[str]					=						FlaxResnetBlockaD(
                 in_channels=resnet_in_channels + res_skip_channels						,			out_channels=self.out_channels						,			dropout_prob=self.dropout						,			dtype=self.dtype						,			)
             resnets.append(SCREAMING_SNAKE_CASE	)

             A       :   int					=						FlaxTransformeraDModel(
                 in_channels=self.out_channels						,			n_heads=self.num_attention_heads						,			d_head=self.out_channels // self.num_attention_heads						,			depth=1						,			use_linear_projection=self.use_linear_projection						,			only_cross_attention=self.only_cross_attention						,			use_memory_efficient_attention=self.use_memory_efficient_attention						,			dtype=self.dtype						,			)
             attentions.append(SCREAMING_SNAKE_CASE	)

         A       :   Dict					=						resnets
         A       :   Optional[Any]					=						attentions

         if self.add_upsample:
             A       :   Optional[int]					=						FlaxUpsampleaD(self.out_channels						,			dtype=self.dtype	)





     def __call__(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE=True	) ->				Optional[int]:






         """simple docstring"""






         for resnet, attn in zip(self.resnets						,			self.attentions	):
             # pop res hidden states
             A       :   List[str]					=						res_hidden_states_tuple[-1]
             A       :   int					=						res_hidden_states_tuple[:-1]
             A       :   List[str]					=						jnp.concatenate((hidden_states, res_hidden_states)						,			axis=-1	)

             A       :   Union[str, Any]					=						resnet(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			deterministic=SCREAMING_SNAKE_CASE	)
             A       :   Tuple					=						attn(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			deterministic=SCREAMING_SNAKE_CASE	)

         if self.add_upsample:
             A       :   Dict					=						self.upsamplers_a(SCREAMING_SNAKE_CASE	)

         return hidden_states





class  A				(							nn.Module						):
     __magic_name__						=		42
     __magic_name__						=		42
     __magic_name__						=		42
     __magic_name__						=		0.0
     __magic_name__						=		1
     __magic_name__						=		True
     __magic_name__						=		jnp.floataa





     def 				__lowerCAmelCase							(							self	) ->				Dict:






         """simple docstring"""






         A       :   int					=						[]

         for i in range(self.num_layers	):
             A       :   List[Any]					=						self.in_channels if (i == self.num_layers - 1) else self.out_channels
             A       :   List[str]					=						self.prev_output_channel if i == 0 else self.out_channels

             A       :   str					=						FlaxResnetBlockaD(
                 in_channels=resnet_in_channels + res_skip_channels						,			out_channels=self.out_channels						,			dropout_prob=self.dropout						,			dtype=self.dtype						,			)
             resnets.append(SCREAMING_SNAKE_CASE	)

         A       :   List[Any]					=						resnets

         if self.add_upsample:
             A       :   Optional[Any]					=						FlaxUpsampleaD(self.out_channels						,			dtype=self.dtype	)





     def __call__(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE=True	) ->				Tuple:






         """simple docstring"""






         for resnet in self.resnets:
             # pop res hidden states
             A       :   Optional[int]					=						res_hidden_states_tuple[-1]
             A       :   Optional[Any]					=						res_hidden_states_tuple[:-1]
             A       :   List[Any]					=						jnp.concatenate((hidden_states, res_hidden_states)						,			axis=-1	)

             A       :   Optional[Any]					=						resnet(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			deterministic=SCREAMING_SNAKE_CASE	)

         if self.add_upsample:
             A       :   List[str]					=						self.upsamplers_a(SCREAMING_SNAKE_CASE	)

         return hidden_states





class  A				(							nn.Module						):
     __magic_name__						=		42
     __magic_name__						=		0.0
     __magic_name__						=		1
     __magic_name__						=		1
     __magic_name__						=		False
     __magic_name__						=		False
     __magic_name__						=		jnp.floataa





     def 				__lowerCAmelCase							(							self	) ->				Optional[int]:






         """simple docstring"""






         A       :   str					=						[
             FlaxResnetBlockaD(
                 in_channels=self.in_channels						,			out_channels=self.in_channels						,			dropout_prob=self.dropout						,			dtype=self.dtype						,			)
         ]

         A       :   List[Any]					=						[]

         for _ in range(self.num_layers	):
             A       :   int					=						FlaxTransformeraDModel(
                 in_channels=self.in_channels						,			n_heads=self.num_attention_heads						,			d_head=self.in_channels // self.num_attention_heads						,			depth=1						,			use_linear_projection=self.use_linear_projection						,			use_memory_efficient_attention=self.use_memory_efficient_attention						,			dtype=self.dtype						,			)
             attentions.append(SCREAMING_SNAKE_CASE	)

             A       :   Union[str, Any]					=						FlaxResnetBlockaD(
                 in_channels=self.in_channels						,			out_channels=self.in_channels						,			dropout_prob=self.dropout						,			dtype=self.dtype						,			)
             resnets.append(SCREAMING_SNAKE_CASE	)

         A       :   List[str]					=						resnets
         A       :   List[str]					=						attentions





     def __call__(							self						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE=True	) ->				Dict:






         """simple docstring"""






         A       :   Optional[Any]					=						self.resnets[0](SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE	)
         for attn, resnet in zip(self.attentions						,			self.resnets[1:]	):
             A       :   Optional[int]					=						attn(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			deterministic=SCREAMING_SNAKE_CASE	)
             A       :   Union[str, Any]					=						resnet(SCREAMING_SNAKE_CASE						,			SCREAMING_SNAKE_CASE						,			deterministic=SCREAMING_SNAKE_CASE	)

         return hidden_states




