

'''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 						UpperCamelCase	(			a		,						a		,						a=1e-12			)				->     List[str]:






     '''simple docstring'''
     __magic_name__						       =    jnp.divide(emb_a.T		,						jnp.clip(jnp.linalg.norm(a		,						axis=1			)		,						a_min=a			)			).T
     __magic_name__						       =    jnp.divide(emb_a.T		,						jnp.clip(jnp.linalg.norm(a		,						axis=1			)		,						a_min=a			)			).T
     return jnp.matmul(a		,						norm_emb_a.T			)






class   _SCREAMING_SNAKE_CASE   (   nn.Module     ):
 __SCREAMING_SNAKE_CASE					:CLIPConfig
 __SCREAMING_SNAKE_CASE					:jnp.dtype      	=					jnp.floataa



 def 			snake_case__  (   self		:   Any      ):
      __magic_name__						       =    FlaxCLIPVisionModule(self.config.vision_config      )
      __magic_name__						       =    nn.Dense(self.config.projection_dim			,				use_bias=a__			,				dtype=self.dtype      )

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

      __magic_name__						       =    self.param('''concept_embeds_weights'''			,				jax.nn.initializers.ones			,				(17,)      )
      __magic_name__						       =    self.param('''special_care_embeds_weights'''			,				jax.nn.initializers.ones			,				(3,)      )



 def __call__(   self		:   Any			,				a__		:   List[str]      ):
      __magic_name__						       =    self.vision_model(a__      )[1]
      __magic_name__						       =    self.visual_projection(a__      )

      __magic_name__						       =    jax_cosine_distance(a__			,				self.special_care_embeds      )
      __magic_name__						       =    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
      __magic_name__						       =    0.0

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

      __magic_name__						       =    cos_dist - self.concept_embeds_weights[None, :] + special_adjustment
      __magic_name__						       =    jnp.round(a__			,				3      )
      __magic_name__						       =    jnp.any(concept_scores > 0			,				axis=1      )

      return has_nsfw_concepts






class   _SCREAMING_SNAKE_CASE   (   __a     ):
 __SCREAMING_SNAKE_CASE					:Optional[Any]      	=					CLIPConfig
 __SCREAMING_SNAKE_CASE					:int      	=					"""clip_input"""
 __SCREAMING_SNAKE_CASE					:Tuple      	=					FlaxStableDiffusionSafetyCheckerModule



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



 def 			snake_case__  (   self		:   Any			,				a__		:   jax.random.KeyArray			,				a__		:   Tuple			,				a__		:   FrozenDict = None      ):
      # init input tensor
      __magic_name__						       =    jax.random.normal(a__			,				a__      )

      __magic_name__       ,  __magic_name__						       =    jax.random.split(a__      )
      __magic_name__						       =    {'''params''': params_rng, '''dropout''': dropout_rng}

      __magic_name__						       =    self.module.init(a__			,				a__      )['''params''']

      return random_params



 def __call__(   self		:   Optional[Any]			,				a__		:   Dict			,				a__		:   dict = None			,				):
      __magic_name__						       =    jnp.transpose(a__			,				(0, 2, 3, 1)      )

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









'''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   _SCREAMING_SNAKE_CASE   (   __a		,__a     ):
 __SCREAMING_SNAKE_CASE					:Optional[Any]      	=					1



 @register_to_config
 def __init__(   self		:   Optional[int]			,				a__		:   int = 1000			,				a__		:   Optional[Union[np.ndarray, List[float]]] = None      ):
      # set `betas`, `alphas`, `timesteps`
      self.set_timesteps(a__      )

      # standard deviation of the initial noise distribution
      __magic_name__						       =    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.
      __magic_name__						       =    4

      # running values
      __magic_name__						       =    []



 def 			snake_case__  (   self		:   Dict			,				a__		:   int			,				a__		:   Union[str, torch.device] = None      ):
      __magic_name__						       =    num_inference_steps
      __magic_name__						       =    torch.linspace(1			,				0			,				num_inference_steps + 1      )[:-1]
      __magic_name__						       =    torch.cat([steps, torch.tensor([0.0]      )]      )

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

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

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

      __magic_name__						       =    []



 def 			snake_case__  (   self		:   Union[str, Any]			,				a__		:   torch.FloatTensor			,				a__		:   int			,				a__		:   torch.FloatTensor			,				a__		:   bool = True			,				):
      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'''      )

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

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

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

      __magic_name__						       =    self._get_prev_sample(a__			,				a__			,				a__			,				a__      )

      if not return_dict:
           return (prev_sample,)

      return SchedulerOutput(prev_sample=a__      )



 def 			snake_case__  (   self		:   Any			,				a__		:   torch.FloatTensor			,				*a__		:   Optional[int]			,				**a__		:   Union[str, Any]      ):
      return sample



 def 			snake_case__  (   self		:   str			,				a__		:   Optional[int]			,				a__		:   int			,				a__		:   List[Any]			,				a__		:   List[str]      ):
      __magic_name__						       =    self.alphas[timestep_index]
      __magic_name__						       =    self.betas[timestep_index]

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

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

      return prev_sample



 def __len__(   self		:   int      ):
      return self.config.num_train_timesteps






