

import logging
import os
import sys
import threading
from logging import (
    CRITICAL,  # NOQA
    DEBUG,  # NOQA
    ERROR,  # NOQA
    FATAL,  # NOQA
    INFO,  # NOQA
    NOTSET,  # NOQA
    WARN,  # NOQA
    WARNING,  # NOQA
)
from typing import Optional

from tqdm import auto as tqdm_lib


_SCREAMING_SNAKE_CASE							 =			threading.Lock()
_SCREAMING_SNAKE_CASE							 =			None

_SCREAMING_SNAKE_CASE							 =			{
    '''debug''': logging.DEBUG,
    '''info''': logging.INFO,
    '''warning''': logging.WARNING,
    '''error''': logging.ERROR,
    '''critical''': logging.CRITICAL,
}

_SCREAMING_SNAKE_CASE							 =			logging.WARNING

_SCREAMING_SNAKE_CASE							 =			True





def  _snake_case		()							->		Union[str, Any]:
  __UpperCAmelCase	:  Optional[int]		=     os.getenv('DIFFUSERS_VERBOSITY'    ,       snake_case_  )
  if env_level_str:
    if env_level_str in log_levels:
      return log_levels[env_level_str]
    else:
      logging.getLogger().warning(
          F"Unknown option DIFFUSERS_VERBOSITY={env_level_str}, "
          F"has to be one of: { ', '.join(log_levels.keys()  ) }"  )
  return _default_log_level





def  _snake_case		()							->		str:
  return __name__.split('.'  )[0]





def  _snake_case		()							->		logging.Logger:
  return logging.getLogger(_get_library_name()  )





def  _snake_case		()							->		None:
  global _default_handler

  with _lock:
    if _default_handler:
      # This library has already configured the library root logger.
      return
    __UpperCAmelCase	:  Optional[int]		=     logging.StreamHandler()  # Set sys.stderr as stream.
    __UpperCAmelCase	:  Any		=     sys.stderr.flush

    # Apply our default configuration to the library root logger.
    __UpperCAmelCase	:  int		=     _get_library_root_logger()
    library_root_logger.addHandler(_default_handler  )
    library_root_logger.setLevel(_get_default_logging_level()  )
    __UpperCAmelCase	:  Dict		=     False





def  _snake_case		()							->		None:
  global _default_handler

  with _lock:
    if not _default_handler:
      return

    __UpperCAmelCase	:  Dict		=     _get_library_root_logger()
    library_root_logger.removeHandler(_default_handler  )
    library_root_logger.setLevel(logging.NOTSET  )
    __UpperCAmelCase	:  Tuple		=     None





def  _snake_case		()							->		Union[str, Any]:
  return log_levels





def  _snake_case		(snake_case_					:     Optional[str] = None  )							->		logging.Logger:

  if name is None:
    __UpperCAmelCase	:  str		=     _get_library_name()

  _configure_library_root_logger()
  return logging.getLogger(snake_case_  )





def  _snake_case		()							->		int:
  _configure_library_root_logger()
  return _get_library_root_logger().getEffectiveLevel()





def  _snake_case		(snake_case_					:     int  )							->		None:
  _configure_library_root_logger()
  _get_library_root_logger().setLevel(snake_case_  )





def  _snake_case		()							->		str:
  return set_verbosity(snake_case_  )





def  _snake_case		()							->		Optional[Any]:
  return set_verbosity(snake_case_  )





def  _snake_case		()							->		Optional[Any]:
  return set_verbosity(snake_case_  )





def  _snake_case		()							->		List[Any]:
  return set_verbosity(snake_case_  )





def  _snake_case		()							->		None:
  _configure_library_root_logger()

  assert _default_handler is not None
  _get_library_root_logger().removeHandler(_default_handler  )





def  _snake_case		()							->		None:
  _configure_library_root_logger()

  assert _default_handler is not None
  _get_library_root_logger().addHandler(_default_handler  )





def  _snake_case		(snake_case_					:     logging.Handler  )							->		None:
  _configure_library_root_logger()

  assert handler is not None
  _get_library_root_logger().addHandler(snake_case_  )





def  _snake_case		(snake_case_					:     logging.Handler  )							->		None:
  _configure_library_root_logger()

  assert handler is not None and handler not in _get_library_root_logger().handlers
  _get_library_root_logger().removeHandler(snake_case_  )





def  _snake_case		()							->		None:
  _configure_library_root_logger()
  __UpperCAmelCase	:  List[Any]		=     False





def  _snake_case		()							->		None:
  _configure_library_root_logger()
  __UpperCAmelCase	:  str		=     True





def  _snake_case		()							->		None:
  __UpperCAmelCase	:  Any		=     _get_library_root_logger().handlers

  for handler in handlers:
    __UpperCAmelCase	:  Optional[int]		=     logging.Formatter('[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s'  )
    handler.setFormatter(snake_case_  )





def  _snake_case		()							->		None:
  __UpperCAmelCase	:  Dict		=     _get_library_root_logger().handlers

  for handler in handlers:
    handler.setFormatter(snake_case_  )





def  _snake_case		(self					:     Tuple    ,       *snake_case_					:     str    ,       **snake_case_					:     Tuple  )							->		str:
  __UpperCAmelCase	:  str		=     os.getenv('DIFFUSERS_NO_ADVISORY_WARNINGS'    ,       snake_case_  )
  if no_advisory_warnings:
    return
  self.warning(*snake_case_    ,       **snake_case_  )


_SCREAMING_SNAKE_CASE							 =			warning_advice


class      lowerCamelCase_ :




 def __init__(			self  ,  *_UpperCAmelCase  ,  **_UpperCAmelCase							):  # pylint: disable=unused-argument
   __UpperCAmelCase	:  Optional[Any]		=     args[0] if args else None




 def __iter__(			self							):
   return iter(self._iterator							)




 def __getattr__(			self  ,  _UpperCAmelCase							):

   def empty_fn(*_UpperCAmelCase  ,  **_UpperCAmelCase							):  # pylint: disable=unused-argument
     return

   return empty_fn




 def __enter__(			self							):
   return self




 def __exit__(			self  ,  _UpperCAmelCase  ,  _UpperCAmelCase  ,  _UpperCAmelCase							):
   return



class      lowerCamelCase_ :




 def __call__(			self  ,  *_UpperCAmelCase  ,  **_UpperCAmelCase							):
   if _tqdm_active:
     return tqdm_lib.tqdm(*_UpperCAmelCase  ,  **_UpperCAmelCase							)
   else:
     return EmptyTqdm(*_UpperCAmelCase  ,  **_UpperCAmelCase							)




 def     a       (			self  ,  *_UpperCAmelCase  ,  **_UpperCAmelCase							):
   __UpperCAmelCase	:  Tuple		=     None
   if _tqdm_active:
     return tqdm_lib.tqdm.set_lock(*_UpperCAmelCase  ,  **_UpperCAmelCase							)




 def     a       (			self							):
   if _tqdm_active:
     return tqdm_lib.tqdm.get_lock()



_SCREAMING_SNAKE_CASE							 =			_tqdm_cls()





def  _snake_case		()							->		bool:
  global _tqdm_active
  return bool(_tqdm_active  )





def  _snake_case		()							->		Any:
  global _tqdm_active
  __UpperCAmelCase	:  int		=     True







def  _snake_case		()							->		str:
  global _tqdm_active
  __UpperCAmelCase	:  Dict		=     False







import math
from collections import OrderedDict

import torch
from packaging import version
from torch import Tensor, nn

from .utils import logging


UpperCAmelCase__						:	Any	     = logging.get_logger(__name__)






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def __init__(   self	:				List[str]	):

      """simple docstring"""
      super().__init__()
      if version.parse(torch.__version__	) < version.parse('''1.12.0'''	):
         raise ImportError(
             F"""You are using torch=={torch.__version__}, but torch>=1.12.0 is required to use """
             '''PytorchGELUTanh. Please upgrade torch.'''	)


   def 					__magic_name__							(   self	:				Any     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return nn.functional.gelu(lowerCAmelCase_     ,     approximate='''tanh'''	)






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def 					__magic_name__							(   self	:				Tuple     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi	) * (input + 0.044715 * torch.pow(lowerCAmelCase_     ,     3.0	))	))






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def __init__(   self	:				Tuple     ,     lowerCAmelCase_	:				bool = False	):

      """simple docstring"""
      super().__init__()
      if use_gelu_python:
         _A:    Union[str, Any]						     =			self._gelu_python
      else:
         _A:    Union[str, Any]						     =			nn.functional.gelu


   def 					__magic_name__							(   self	:				Union[str, Any]     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return input * 0.5 * (1.0 + torch.erf(input / math.sqrt(2.0	)	))


   def 					__magic_name__							(   self	:				Any     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return self.act(lowerCAmelCase_	)






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def 					__magic_name__							(   self	:				Optional[int]     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return 0.5 * input * (1.0 + torch.tanh(input * 0.7978845608 * (1.0 + 0.044715 * input * input)	))






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def 					__magic_name__							(   self	:				Optional[int]     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return input * torch.sigmoid(1.702 * input	)






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def __init__(   self	:				str     ,     lowerCAmelCase_	:				float     ,     lowerCAmelCase_	:				float	):

      """simple docstring"""
      if min > max:
         raise ValueError(F"""min should be < max (got min: {min}, max: {max})"""	)

      super().__init__()
      _A:    Tuple						     =			min
      _A:    str						     =			max


   def 					__magic_name__							(   self	:				int     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return torch.clip(gelu(lowerCAmelCase_	)     ,     self.min     ,     self.max	)






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def __init__(   self	:				Optional[Any]	):

      """simple docstring"""
      super().__init__()
      _A:    Any						     =			math.sqrt(2 / math.pi	)


   def 					__magic_name__							(   self	:				Union[str, Any]     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return 0.5 * input * (1 + torch.tanh(self.precomputed_constant * (input + 0.044715 * torch.pow(lowerCAmelCase_     ,     3	))	))






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def 					__magic_name__							(   self	:				str     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return nn.functional.silu(lowerCAmelCase_	)






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


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

      """simple docstring"""
      super().__init__()
      if version.parse(torch.__version__	) < version.parse('''1.9.0'''	):
         _A:    Optional[Any]						     =			self._mish_python
      else:
         _A:    int						     =			nn.functional.mish


   def 					__magic_name__							(   self	:				Optional[int]     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return input * torch.tanh(nn.functional.softplus(lowerCAmelCase_	)	)


   def 					__magic_name__							(   self	:				Any     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return self.act(lowerCAmelCase_	)






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def 					__magic_name__							(   self	:				Tuple     ,     lowerCAmelCase_	:				Tensor	):

      """simple docstring"""
      return input






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def 					__magic_name__							(   self	:				Dict     ,     lowerCAmelCase_	:				List[str]     ,     lowerCAmelCase_	:				Tuple=0.707107     ,     lowerCAmelCase_	:				Union[str, Any]=0.282095	):

      """simple docstring"""
      _A:    Any						     =			(input - mu).div(sigma * math.sqrt(2.0	)	)
      return 0.5 * (1.0 + torch.erf(lowerCAmelCase_	))






class UpperCAmelCase  (		nn.Module  ):





   '''simple docstring'''


   def 					__magic_name__							(   self	:				Union[str, Any]     ,     lowerCAmelCase_	:				List[Any]	):

      """simple docstring"""
      _A:    Optional[int]						     =			nn.functional.relu(lowerCAmelCase_	)
      _A:    Any						     =			torch.square(lowerCAmelCase_	)
      return squared






class UpperCAmelCase  (		SCREAMING_SNAKE_CASE__  ):





   '''simple docstring'''


   def __getitem__(   self	:				List[Any]     ,     lowerCAmelCase_	:				Tuple	):

      """simple docstring"""
      _A:    Any						     =			super().__getitem__(lowerCAmelCase_	)
      _A     ,    _A:    List[str]						     =			content if isinstance(lowerCAmelCase_     ,     lowerCAmelCase_	) else (content, {})
      return cls(**lowerCAmelCase_	)

UpperCAmelCase__						:	List[str]	     = {
    'gelu': GELUActivation,
    'gelu_10': (ClippedGELUActivation, {'min': -10, 'max': 10}),
    'gelu_fast': FastGELUActivation,
    'gelu_new': NewGELUActivation,
    'gelu_python': (GELUActivation, {'use_gelu_python': True}),
    'gelu_pytorch_tanh': PytorchGELUTanh,
    'gelu_accurate': AccurateGELUActivation,
    'laplace': LaplaceActivation,
    'linear': LinearActivation,
    'mish': MishActivation,
    'quick_gelu': QuickGELUActivation,
    'relu': nn.ReLU,
    'relu2': ReLUSquaredActivation,
    'relu6': nn.ReLUa,
    'sigmoid': nn.Sigmoid,
    'silu': SiLUActivation,
    'swish': SiLUActivation,
    'tanh': nn.Tanh,
}
UpperCAmelCase__						:	List[str]	     = ClassInstantier(ACTaCLS)






def     lowerCamelCase__				(   a ) ->  List[str]:
   if activation_string in ACTaFN:
      return ACTaFN[activation_string]
   else:
      raise KeyError(f"""function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys() )}""" )


# For backwards compatibility with: from activations import gelu_python
UpperCAmelCase__						:	Any	     = get_activation('gelu_python')
UpperCAmelCase__						:	Dict	     = get_activation('gelu_new')
UpperCAmelCase__						:	List[Any]	     = get_activation('gelu')
UpperCAmelCase__						:	Dict	     = get_activation('gelu_fast')
UpperCAmelCase__						:	str	     = get_activation('quick_gelu')
UpperCAmelCase__						:	Union[str, Any]	     = get_activation('silu')
UpperCAmelCase__						:	List[Any]	     = get_activation('mish')





UpperCAmelCase__						:	int	     = get_activation('linear')



