



"""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 						__snake_case						(				SCREAMING_SNAKE_CASE__     :						List[Any]						,  SCREAMING_SNAKE_CASE__     :						Dict						,  SCREAMING_SNAKE_CASE__     :						List[str]=1E-12    )  ->       List[str]:





     '''simple docstring'''

     _UpperCAmelCase      :     Optional[int]        =   jnp.divide(emb_a.T						,  jnp.clip(jnp.linalg.norm(SCREAMING_SNAKE_CASE__						,  axis=1    )						,  a_min=SCREAMING_SNAKE_CASE__    )    ).T
     _UpperCAmelCase      :     Optional[Any]        =   jnp.divide(emb_a.T						,  jnp.clip(jnp.linalg.norm(SCREAMING_SNAKE_CASE__						,  axis=1    )						,  a_min=SCREAMING_SNAKE_CASE__    )    ).T
     return jnp.matmul(SCREAMING_SNAKE_CASE__						,  norm_emb_a.T    )






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



      def 						snake_case_ (					self					:     Dict						):
           _UpperCAmelCase      :     Any        =   FlaxCLIPVisionModule(self.config.vision_config						)
           _UpperCAmelCase      :     str        =   nn.Dense(self.config.projection_dim					,     use_bias=A					,     dtype=self.dtype						)

           _UpperCAmelCase      :     Optional[int]        =   self.param("concept_embeds"					,     jax.nn.initializers.ones					,     (1_7, self.config.projection_dim)						)
           _UpperCAmelCase      :     Tuple        =   self.param(
               "special_care_embeds"					,     jax.nn.initializers.ones					,     (3, self.config.projection_dim)						)

           _UpperCAmelCase      :     List[Any]        =   self.param("concept_embeds_weights"					,     jax.nn.initializers.ones					,     (1_7,)						)
           _UpperCAmelCase      :     Optional[int]        =   self.param("special_care_embeds_weights"					,     jax.nn.initializers.ones					,     (3,)						)



      def __call__(					self					:     Any					,     A					:     Tuple						):
           _UpperCAmelCase      :     Optional[int]        =   self.vision_model(A						)[1]
           _UpperCAmelCase      :     int        =   self.visual_projection(A						)

           _UpperCAmelCase      :     int        =   jax_cosine_distance(A					,     self.special_care_embeds						)
           _UpperCAmelCase      :     int        =   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
           _UpperCAmelCase      :     Tuple        =   0.0

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

           _UpperCAmelCase      :     Union[str, Any]        =   cos_dist - self.concept_embeds_weights[None, :] + special_adjustment
           _UpperCAmelCase      :     Union[str, Any]        =   jnp.round(A					,     3						)
           _UpperCAmelCase      :     Union[str, Any]        =   jnp.any(concept_scores > 0					,     axis=1						)

           return has_nsfw_concepts







class      UpperCAmelCase_  (    _UpperCamelCase						):
      __SCREAMING_SNAKE_CASE						:       int								=			CLIPConfig
      __SCREAMING_SNAKE_CASE						:       Any								=			'clip_input'
      __SCREAMING_SNAKE_CASE						:       Union[str, Any]								=			FlaxStableDiffusionSafetyCheckerModule



      def __init__(					self					:     Any					,     A					:     CLIPConfig					,     A					:     Optional[Tuple] = None					,     A					:     int = 0					,     A					:     jnp.dtype = jnp.floataa					,     A					:     bool = True					,     **A					:     List[Any]					,     ):
           if input_shape is None:
                _UpperCAmelCase      :     List[str]        =   (1, 2_2_4, 2_2_4, 3)
           _UpperCAmelCase      :     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 						snake_case_ (					self					:     Union[str, Any]					,     A					:     jax.random.KeyArray					,     A					:     Tuple					,     A					:     FrozenDict = None						):
           # init input tensor
           _UpperCAmelCase      :     Optional[Any]        =   jax.random.normal(A					,     A						)

           _UpperCAmelCase    ,	_UpperCAmelCase      :     Optional[int]        =   jax.random.split(A						)
           _UpperCAmelCase      :     Any        =   {"params": params_rng, "dropout": dropout_rng}

           _UpperCAmelCase      :     Union[str, Any]        =   self.module.init(A					,     A						)["params"]

           return random_params



      def __call__(					self					:     Tuple					,     A					:     Union[str, Any]					,     A					:     dict = None					,     ):
           _UpperCAmelCase      :     Dict        =   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"""




from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available


_lowerCAmelCase    : Union[str, Any]							=							{}

try:
 if not is_sentencepiece_available():
  raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
 pass
else:
 _lowerCAmelCase    : Optional[Any]							=							["GPTSw3Tokenizer"]


if TYPE_CHECKING:
 try:
  if not is_sentencepiece_available():
   raise OptionalDependencyNotAvailable()
 except OptionalDependencyNotAvailable:
  pass
 else:
  from .tokenization_gpt_swa import GPTSwaTokenizer

else:
 import sys

 _lowerCAmelCase    : List[Any]							=							_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
