


"""simple docstring"""







import functools
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

import huggingface_hub.utils as hf_hub_utils
from tqdm import auto as tqdm_lib


lowerCAmelCase__      				=   threading.Lock()
lowerCAmelCase__      				=   None

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

lowerCAmelCase__      				=   logging.WARNING

lowerCAmelCase__      				=   True
def 					a__			(				):


  '''simple docstring'''







  lowerCAmelCase     :     Dict								=							os.getenv("TRANSFORMERS_VERBOSITY"				,      SCREAMING_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 TRANSFORMERS_VERBOSITY={env_level_str}, """
          f"""has to be one of: { ", ".join(log_levels.keys()				) }"""				)
  return _default_log_level
def 					a__			(				):


  '''simple docstring'''







  return __name__.split("."				)[0]
def 					a__			(				):


  '''simple docstring'''







  return logging.getLogger(_get_library_name()				)
def 					a__			(				):


  '''simple docstring'''







  global _default_handler

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

    # Apply our default configuration to the library root logger.
    lowerCAmelCase     :     Optional[Any]								=							_get_library_root_logger()
    library_root_logger.addHandler(_default_handler				)
    library_root_logger.setLevel(_get_default_logging_level()				)
    lowerCAmelCase     :     List[Any]								=							False
def 					a__			(				):


  '''simple docstring'''







  global _default_handler

  with _lock:
    if not _default_handler:
      return

    lowerCAmelCase     :     Tuple								=							_get_library_root_logger()
    library_root_logger.removeHandler(_default_handler				)
    library_root_logger.setLevel(logging.NOTSET				)
    lowerCAmelCase     :     Optional[Any]								=							None
def 					a__			(				):


  '''simple docstring'''







  return log_levels
def 					a__			(				SCREAMING_SNAKE_CASE    :    Optional[str] = None				):


  '''simple docstring'''







  if name is None:
    lowerCAmelCase     :     List[str]								=							_get_library_name()

  _configure_library_root_logger()
  return logging.getLogger(SCREAMING_SNAKE_CASE				)
def 					a__			(				):


  '''simple docstring'''







  _configure_library_root_logger()
  return _get_library_root_logger().getEffectiveLevel()
def 					a__			(				SCREAMING_SNAKE_CASE    :    int				):


  '''simple docstring'''







  _configure_library_root_logger()
  _get_library_root_logger().setLevel(SCREAMING_SNAKE_CASE				)
def 					a__			(				):


  '''simple docstring'''







  return set_verbosity(SCREAMING_SNAKE_CASE				)
def 					a__			(				):


  '''simple docstring'''







  return set_verbosity(SCREAMING_SNAKE_CASE				)
def 					a__			(				):


  '''simple docstring'''







  return set_verbosity(SCREAMING_SNAKE_CASE				)
def 					a__			(				):


  '''simple docstring'''







  return set_verbosity(SCREAMING_SNAKE_CASE				)
def 					a__			(				):


  '''simple docstring'''







  _configure_library_root_logger()

  assert _default_handler is not None
  _get_library_root_logger().removeHandler(_default_handler				)
def 					a__			(				):


  '''simple docstring'''







  _configure_library_root_logger()

  assert _default_handler is not None
  _get_library_root_logger().addHandler(_default_handler				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    logging.Handler				):


  '''simple docstring'''







  _configure_library_root_logger()

  assert handler is not None
  _get_library_root_logger().addHandler(SCREAMING_SNAKE_CASE				)
def 					a__			(				SCREAMING_SNAKE_CASE    :    logging.Handler				):


  '''simple docstring'''







  _configure_library_root_logger()

  assert handler is not None and handler not in _get_library_root_logger().handlers
  _get_library_root_logger().removeHandler(SCREAMING_SNAKE_CASE				)
def 					a__			(				):


  '''simple docstring'''







  _configure_library_root_logger()
  lowerCAmelCase     :     Optional[Any]								=							False
def 					a__			(				):


  '''simple docstring'''







  _configure_library_root_logger()
  lowerCAmelCase     :     List[Any]								=							True
def 					a__			(				):


  '''simple docstring'''







  lowerCAmelCase     :     Tuple								=							_get_library_root_logger().handlers

  for handler in handlers:
    lowerCAmelCase     :     Optional[Any]								=							logging.Formatter("[%(levelname)s|%(filename)s:%(lineno)s] %(asctime)s >> %(message)s"				)
    handler.setFormatter(SCREAMING_SNAKE_CASE				)
def 					a__			(				):


  '''simple docstring'''







  lowerCAmelCase     :     Dict								=							_get_library_root_logger().handlers

  for handler in handlers:
    handler.setFormatter(SCREAMING_SNAKE_CASE				)
def 					a__			(				self    :    int				,      *SCREAMING_SNAKE_CASE    :    str				,      **SCREAMING_SNAKE_CASE    :    str				):


  '''simple docstring'''







  lowerCAmelCase     :     Union[str, Any]								=							os.getenv("TRANSFORMERS_NO_ADVISORY_WARNINGS"				,      SCREAMING_SNAKE_CASE				)
  if no_advisory_warnings:
    return
  self.warning(*SCREAMING_SNAKE_CASE				,      **SCREAMING_SNAKE_CASE				)


lowerCAmelCase__      				=   warning_advice
@functools.lru_cache(SCREAMING_SNAKE_CASE				)
def 					a__			(				self    :    str				,      *SCREAMING_SNAKE_CASE    :    Dict				,      **SCREAMING_SNAKE_CASE    :    Optional[int]				):


  '''simple docstring'''







  self.warning(*SCREAMING_SNAKE_CASE				,      **SCREAMING_SNAKE_CASE				)


lowerCAmelCase__      				=   warning_once


class       SCREAMING_SNAKE_CASE__				:
       """simple docstring"""


       def __init__(						self		,     *snake_case__		,     **snake_case__						):  # pylint: disable=unused-argument






         """simple docstring"""





         lowerCAmelCase     :     Dict								=							args[0] if args else None

       def __iter__(						self						):






         """simple docstring"""





         return iter(self._iterator						)

       def __getattr__(						self		,     snake_case__						):






         """simple docstring"""





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

         return empty_fn

       def __enter__(						self						):






         """simple docstring"""





         return self







       def __exit__(						self		,     snake_case__		,     snake_case__		,     snake_case__						):






         """simple docstring"""





         return


class       SCREAMING_SNAKE_CASE__				:
       """simple docstring"""


       def __call__(						self		,     *snake_case__		,     **snake_case__						):






         """simple docstring"""





         if _tqdm_active:
           return tqdm_lib.tqdm(*snake_case__		,     **snake_case__						)
         else:
           return EmptyTqdm(*snake_case__		,     **snake_case__						)

       def        lowercase__							(						self		,     *snake_case__		,     **snake_case__						):






         """simple docstring"""





         lowerCAmelCase     :     Optional[int]								=							None
         if _tqdm_active:
           return tqdm_lib.tqdm.set_lock(*snake_case__		,     **snake_case__						)







       def        lowercase__							(						self						):






         """simple docstring"""





         if _tqdm_active:
           return tqdm_lib.tqdm.get_lock()

lowerCAmelCase__      				=   _tqdm_cls()
def 					a__			(				):


  '''simple docstring'''







  global _tqdm_active
  return bool(_tqdm_active				)
def 					a__			(				):


  '''simple docstring'''







  global _tqdm_active
  lowerCAmelCase     :     Optional[Any]								=							True
  hf_hub_utils.enable_progress_bars()





def 					a__			(				):


  '''simple docstring'''







  global _tqdm_active
  lowerCAmelCase     :     Tuple								=							False
  hf_hub_utils.disable_progress_bars()






"""simple docstring"""






import math
from typing import List, Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils import SchedulerMixin, SchedulerOutput





class  _A						(       lowerCAmelCase  ,    lowerCAmelCase	):
      snake_case__			:   Tuple							  =	1

      @register_to_config
      def __init__(						self		,       __lowerCAmelCase = 1000		,       __lowerCAmelCase = None						):







            """simple docstring"""



            self.set_timesteps(__lowerCAmelCase						)

            # standard deviation of the initial noise distribution
            lowercase														=	1.0

            # For now we only support F-PNDM, i.e. the runge-kutta method
            # For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf
            # mainly at formula (9), (12), (13) and the Algorithm 2.
            lowercase														=	4

            # running values
            lowercase														=	[]

      def 				A__       (						self		,       __lowerCAmelCase		,       __lowerCAmelCase = None						):







            """simple docstring"""



            lowercase														=	num_inference_steps
            lowercase														=	torch.linspace(1		,       0		,       num_inference_steps + 1						)[:-1]
            lowercase														=	torch.cat([steps, torch.tensor([0.0]						)]						)

            if self.config.trained_betas is not None:
                  lowercase														=	torch.tensor(self.config.trained_betas		,       dtype=torch.floataa						)
            else:
                  lowercase														=	torch.sin(steps * math.pi / 2						) ** 2

            lowercase														=	(1.0 - self.betas**2) ** 0.5

            lowercase														=	(torch.atana(self.betas		,       self.alphas						) / math.pi * 2)[:-1]
            lowercase														=	timesteps.to(__lowerCAmelCase						)

            lowercase														=	[]

      def 				A__       (						self		,       __lowerCAmelCase		,       __lowerCAmelCase		,       __lowerCAmelCase		,       __lowerCAmelCase = True		,       ):







            """simple docstring"""



            if self.num_inference_steps is None:
                  raise ValueError(
                      """Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"""						)

            lowercase														=	(self.timesteps == timestep).nonzero().item()
            lowercase														=	timestep_index + 1

            lowercase														=	sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index]
            self.ets.append(__lowerCAmelCase						)

            if len(self.ets						) == 1:
                  lowercase														=	self.ets[-1]
            elif len(self.ets						) == 2:
                  lowercase														=	(3 * self.ets[-1] - self.ets[-2]) / 2
            elif len(self.ets						) == 3:
                  lowercase														=	(23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12
            else:
                  lowercase														=	(1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4])

            lowercase														=	self._get_prev_sample(__lowerCAmelCase		,       __lowerCAmelCase		,       __lowerCAmelCase		,       __lowerCAmelCase						)

            if not return_dict:
                  return (prev_sample,)

            return SchedulerOutput(prev_sample=__lowerCAmelCase						)

      def 				A__       (						self		,       __lowerCAmelCase		,       *__lowerCAmelCase		,       **__lowerCAmelCase						):







            """simple docstring"""



            return sample

      def 				A__       (						self		,       __lowerCAmelCase		,       __lowerCAmelCase		,       __lowerCAmelCase		,       __lowerCAmelCase						):







            """simple docstring"""



            lowercase														=	self.alphas[timestep_index]
            lowercase														=	self.betas[timestep_index]

            lowercase														=	self.alphas[prev_timestep_index]
            lowercase														=	self.betas[prev_timestep_index]

            lowercase														=	(sample - sigma * ets) / max(__lowerCAmelCase		,       1E-8						)
            lowercase														=	next_alpha * pred + ets * next_sigma

            return prev_sample







      def __len__(						self						):







            """simple docstring"""



            return self.config.num_train_timesteps



