






"""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      UpperCamelCase_			(SCREAMING_SNAKE_CASE_							,		SCREAMING_SNAKE_CASE_	):
	__magic_name__       =							1





	@register_to_config
	def __init__( self   :					Union[str, Any]      ,      lowerCAmelCase_   :					int = 1_000      ,      lowerCAmelCase_   :					Optional[Union[np.ndarray, List[float]]] = None		)		->     Optional[int]:
				# set `betas`, `alphas`, `timesteps`
				self.set_timesteps(_a		)

				# standard deviation of the initial noise distribution
				UpperCAmelCase_	:					Union[str, Any]     	=   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.
				UpperCAmelCase_	:					Optional[int]     	=   4

				# running values
				UpperCAmelCase_	:					int     	=   []





	def 	_SCREAMING_SNAKE_CASE ( self   :					List[Any]      ,      lowerCAmelCase_   :					int      ,      lowerCAmelCase_   :					Union[str, torch.device] = None		)		->     str:
				UpperCAmelCase_	:					Any     	=   num_inference_steps
				UpperCAmelCase_	:					Dict     	=   torch.linspace(1      ,      0      ,      num_inference_steps + 1		)[:-1]
				UpperCAmelCase_	:					Tuple     	=   torch.cat([steps, torch.tensor([0.0]		)]		)

				if self.config.trained_betas is not None:
							UpperCAmelCase_	:					Union[str, Any]     	=   torch.tensor(self.config.trained_betas      ,      dtype=torch.floataa		)
				else:
							UpperCAmelCase_	:					List[str]     	=   torch.sin(steps * math.pi / 2		) ** 2

				UpperCAmelCase_	:					str     	=   (1.0 - self.betas**2) ** 0.5

				UpperCAmelCase_	:					Optional[Any]     	=   (torch.atana(self.betas      ,      self.alphas		) / math.pi * 2)[:-1]
				UpperCAmelCase_	:					List[Any]     	=   timesteps.to(_a		)

				UpperCAmelCase_	:					str     	=   []





	def 	_SCREAMING_SNAKE_CASE ( self   :					Optional[Any]      ,      lowerCAmelCase_   :					torch.FloatTensor      ,      lowerCAmelCase_   :					int      ,      lowerCAmelCase_   :					torch.FloatTensor      ,      lowerCAmelCase_   :					bool = True      ,      )		->     Union[SchedulerOutput, Tuple]:
				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"		)

				UpperCAmelCase_	:					List[str]     	=   (self.timesteps == timestep).nonzero().item()
				UpperCAmelCase_	:					Union[str, Any]     	=   timestep_index + 1

				UpperCAmelCase_	:					Any     	=   sample * self.betas[timestep_index] + model_output * self.alphas[timestep_index]
				self.ets.append(_a		)

				if len(self.ets		) == 1:
							UpperCAmelCase_	:					int     	=   self.ets[-1]
				elif len(self.ets		) == 2:
							UpperCAmelCase_	:					Tuple     	=   (3 * self.ets[-1] - self.ets[-2]) / 2
				elif len(self.ets		) == 3:
							UpperCAmelCase_	:					List[str]     	=   (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12
				else:
							UpperCAmelCase_	:					Optional[Any]     	=   (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4])

				UpperCAmelCase_	:					Optional[Any]     	=   self._get_prev_sample(_a      ,      _a      ,      _a      ,      _a		)

				if not return_dict:
							return (prev_sample,)

				return SchedulerOutput(prev_sample=_a		)





	def 	_SCREAMING_SNAKE_CASE ( self   :					int      ,      lowerCAmelCase_   :					torch.FloatTensor      ,      *lowerCAmelCase_   :					Union[str, Any]      ,      **lowerCAmelCase_   :					Tuple		)		->     torch.FloatTensor:
				return sample





	def 	_SCREAMING_SNAKE_CASE ( self   :					Union[str, Any]      ,      lowerCAmelCase_   :					List[str]      ,      lowerCAmelCase_   :					Dict      ,      lowerCAmelCase_   :					List[str]      ,      lowerCAmelCase_   :					Optional[Any]		)		->     int:
				UpperCAmelCase_	:					Optional[int]     	=   self.alphas[timestep_index]
				UpperCAmelCase_	:					Dict     	=   self.betas[timestep_index]

				UpperCAmelCase_	:					Optional[int]     	=   self.alphas[prev_timestep_index]
				UpperCAmelCase_	:					Optional[Any]     	=   self.betas[prev_timestep_index]

				UpperCAmelCase_	:					Dict     	=   (sample - sigma * ets) / max(_a      ,      1e-8		)
				UpperCAmelCase_	:					Dict     	=   next_alpha * pred + ets * next_sigma

				return prev_sample





	def __len__( self   :					Dict		)		->     Tuple:
				return self.config.num_train_timesteps








'''simple docstring'''





from typing import Optional, Tuple

import jax
import jax.numpy as jnp
from flax import linen as nn
from flax.core.frozen_dict import FrozenDict
from transformers import CLIPConfig, FlaxPreTrainedModel
from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule

def 			a_	(				_lowerCAmelCase			,_lowerCAmelCase			,_lowerCAmelCase=1E-12			) -> List[Any]:
  __lowerCamelCase			:			int       			=					jnp.divide(emb_a.T			,jnp.clip(jnp.linalg.norm(_lowerCAmelCase			,axis=1			)			,a_min=_lowerCAmelCase			)			).T
  __lowerCamelCase			:			Tuple       			=					jnp.divide(emb_a.T			,jnp.clip(jnp.linalg.norm(_lowerCAmelCase			,axis=1			)			,a_min=_lowerCAmelCase			)			).T
  return jnp.matmul(_lowerCAmelCase			,norm_emb_a.T			)






class    lowerCamelCase_       (							nn.Module	):
  """simple docstring"""




  a_				   =42
  a_				   =jnp.floataa




  def 		_lowercase	(					self :      Optional[Any]  )   ->   Tuple:
    __lowerCamelCase			:			Optional[int]       			=					FlaxCLIPVisionModule(self.config.vision_config  )
    __lowerCamelCase			:			Any       			=					nn.Dense(self.config.projection_dim     ,      use_bias=_a     ,      dtype=self.dtype  )

    __lowerCamelCase			:			str       			=					self.param('concept_embeds'     ,      jax.nn.initializers.ones     ,      (17, self.config.projection_dim)  )
    __lowerCamelCase			:			str       			=					self.param(
        'special_care_embeds'     ,      jax.nn.initializers.ones     ,      (3, self.config.projection_dim)  )

    __lowerCamelCase			:			Optional[int]       			=					self.param('concept_embeds_weights'     ,      jax.nn.initializers.ones     ,      (17,)  )
    __lowerCamelCase			:			Dict       			=					self.param('special_care_embeds_weights'     ,      jax.nn.initializers.ones     ,      (3,)  )




  def __call__(					self :      Tuple     ,      _a :      Any  )   ->   Optional[int]:
    __lowerCamelCase			:			int       			=					self.vision_model(_a  )[1]
    __lowerCamelCase			:			Optional[int]       			=					self.visual_projection(_a  )

    __lowerCamelCase			:			Optional[Any]       			=					jax_cosine_distance(_a     ,      self.special_care_embeds  )
    __lowerCamelCase			:			Tuple       			=					jax_cosine_distance(_a     ,      self.concept_embeds  )

    # increase this value to create a stronger `nfsw` filter
    # at the cost of increasing the possibility of filtering benign image inputs
    __lowerCamelCase			:			Dict       			=					0.0

    __lowerCamelCase			:			str       			=					special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment
    __lowerCamelCase			:			Optional[int]       			=					jnp.round(_a     ,      3  )
    __lowerCamelCase			:			Dict       			=					jnp.any(special_scores > 0     ,      axis=1     ,      keepdims=_a  )
    # Use a lower threshold if an image has any special care concept
    __lowerCamelCase			:			Dict       			=					is_special_care * 0.01

    __lowerCamelCase			:			Optional[int]       			=					cos_dist - self.concept_embeds_weights[None, :] + special_adjustment
    __lowerCamelCase			:			List[str]       			=					jnp.round(_a     ,      3  )
    __lowerCamelCase			:			List[Any]       			=					jnp.any(concept_scores > 0     ,      axis=1  )

    return has_nsfw_concepts






class    lowerCamelCase_       (							SCREAMING_SNAKE_CASE_	):
  """simple docstring"""




  a_				   =CLIPConfig
  a_				   ="""clip_input"""
  a_				   =FlaxStableDiffusionSafetyCheckerModule




  def __init__(					self :      List[str]     ,      _a :      CLIPConfig     ,      _a :      Optional[Tuple] = None     ,      _a :      int = 0     ,      _a :      jnp.dtype = jnp.floataa     ,      _a :      bool = True     ,      **_a :      List[Any]     ,      )   ->   List[Any]:
    if input_shape is None:
      __lowerCamelCase			:			str       			=					(1, 224, 224, 3)
    __lowerCamelCase			:			List[str]       			=					self.module_class(config=_a     ,      dtype=_a     ,      **_a  )
    super().__init__(_a     ,      _a     ,      input_shape=_a     ,      seed=_a     ,      dtype=_a     ,      _do_init=_do_init  )




  def 		_lowercase	(					self :      int     ,      _a :      jax.random.KeyArray     ,      _a :      Tuple     ,      _a :      FrozenDict = None  )   ->   FrozenDict:
    # init input tensor
    __lowerCamelCase			:			Optional[int]       			=					jax.random.normal(_a     ,      _a  )

    __lowerCamelCase			,__lowerCamelCase			:			Optional[Any]       			=					jax.random.split(_a  )
    __lowerCamelCase			:			int       			=					{'params': params_rng, 'dropout': dropout_rng}

    __lowerCamelCase			:			Tuple       			=					self.module.init(_a     ,      _a  )['params']

    return random_params




  def __call__(					self :      Optional[int]     ,      _a :      int     ,      _a :      dict = None     ,      )   ->   Dict:
    __lowerCamelCase			:			str       			=					jnp.transpose(_a     ,      (0, 2, 3, 1)  )

    return self.module.apply(
        {'params': params or self.params}     ,      jnp.array(_a     ,      dtype=jnp.floataa  )     ,      rngs={}     ,      )






