



'''simple docstring'''


from dataclasses import dataclass
from typing import Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, randn_tensor
from .scheduling_utils import SchedulerMixin

@dataclass
class  SCREAMING_SNAKE_CASE (  _a		):






    """simple docstring"""





    _SCREAMING_SNAKE_CASE	  =  42
    _SCREAMING_SNAKE_CASE	  =  42
    _SCREAMING_SNAKE_CASE	  =  None

class  SCREAMING_SNAKE_CASE (  _a   ,						_a		):






    """simple docstring"""





    _SCREAMING_SNAKE_CASE	  =  2






    @register_to_config
    def __init__(  self      :					Union[str, Any]  ,						UpperCamelCase__      :					float = 0.0_2  ,						UpperCamelCase__      :					float = 1_0_0  ,						UpperCamelCase__      :					float = 1.0_0_7  ,						UpperCamelCase__      :					float = 8_0  ,						UpperCamelCase__      :					float = 0.0_5  ,						UpperCamelCase__      :					float = 5_0  ,						):


       """simple docstring"""







       UpperCamelCase					=  sigma_max

       # setable values
       UpperCamelCase					=  None
       UpperCamelCase					=  None
       UpperCamelCase					=  None  # sigma(t_i)






    def  A       (  self      :					str  ,						UpperCamelCase__      :					torch.FloatTensor  ,						UpperCamelCase__      :					Optional[int] = None ):


       """simple docstring"""







       return sample






    def  A       (  self      :					Union[str, Any]  ,						UpperCamelCase__      :					int  ,						UpperCamelCase__      :					Union[str, torch.device] = None ):


       """simple docstring"""







       UpperCamelCase					=  num_inference_steps
       UpperCamelCase					=  np.arange(0  ,						self.num_inference_steps )[::-1].copy()
       UpperCamelCase					=  torch.from_numpy(UpperCamelCase__ ).to(UpperCamelCase__ )
       UpperCamelCase					=  [
           (
               self.config.sigma_max**2
               * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1))
           )
           for i in self.timesteps
       ]
       UpperCamelCase					=  torch.tensor(UpperCamelCase__  ,						dtype=torch.floataa  ,						device=UpperCamelCase__ )






    def  A       (  self      :					Dict  ,						UpperCamelCase__      :					torch.FloatTensor  ,						UpperCamelCase__      :					float  ,						UpperCamelCase__      :					Optional[torch.Generator] = None ):


       """simple docstring"""







       if self.config.s_min <= sigma <= self.config.s_max:
          UpperCamelCase					=  min(self.config.s_churn / self.num_inference_steps  ,						2**0.5 - 1 )
       else:
          UpperCamelCase					=  0

       # sample eps ~ N(0, S_noise^2 * I)
       UpperCamelCase					=  self.config.s_noise * randn_tensor(sample.shape  ,						generator=UpperCamelCase__ ).to(sample.device )
       UpperCamelCase					=  sigma + gamma * sigma
       UpperCamelCase					=  sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps)

       return sample_hat, sigma_hat






    def  A       (  self      :					str  ,						UpperCamelCase__      :					torch.FloatTensor  ,						UpperCamelCase__      :					float  ,						UpperCamelCase__      :					float  ,						UpperCamelCase__      :					torch.FloatTensor  ,						UpperCamelCase__      :					bool = True  ,						):


       """simple docstring"""







       UpperCamelCase					=  sample_hat + sigma_hat * model_output
       UpperCamelCase					=  (sample_hat - pred_original_sample) / sigma_hat
       UpperCamelCase					=  sample_hat + (sigma_prev - sigma_hat) * derivative

       if not return_dict:
          return (sample_prev, derivative)

       return KarrasVeOutput(
           prev_sample=UpperCamelCase__  ,						derivative=UpperCamelCase__  ,						pred_original_sample=UpperCamelCase__ )






    def  A       (  self      :					List[Any]  ,						UpperCamelCase__      :					torch.FloatTensor  ,						UpperCamelCase__      :					float  ,						UpperCamelCase__      :					float  ,						UpperCamelCase__      :					torch.FloatTensor  ,						UpperCamelCase__      :					torch.FloatTensor  ,						UpperCamelCase__      :					torch.FloatTensor  ,						UpperCamelCase__      :					bool = True  ,						):


       """simple docstring"""







       UpperCamelCase					=  sample_prev + sigma_prev * model_output
       UpperCamelCase					=  (sample_prev - pred_original_sample) / sigma_prev
       UpperCamelCase					=  sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr)

       if not return_dict:
          return (sample_prev, derivative)

       return KarrasVeOutput(
           prev_sample=UpperCamelCase__  ,						derivative=UpperCamelCase__  ,						pred_original_sample=UpperCamelCase__ )






    def  A       (  self      :					Optional[Any]  ,						UpperCamelCase__      :					str  ,						UpperCamelCase__      :					int  ,						UpperCamelCase__      :					str ):


       """simple docstring"""







       raise NotImplementedError()






'''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 				__lowerCamelCase				(   A__    ,						A__    ,						A__=1e-1_2    )       ->	Dict:






   """simple docstring"""
   UpperCamelCase					=  jnp.divide(emb_a.T    ,						jnp.clip(jnp.linalg.norm(A__    ,						axis=1    )    ,						a_min=A__    )    ).T
   UpperCamelCase					=  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		):






    """simple docstring"""





    _SCREAMING_SNAKE_CASE	  =  42
    _SCREAMING_SNAKE_CASE	  =  jnp.floataa






    def  A       (  self      :					List[Any] ):


       """simple docstring"""







       UpperCamelCase					=  FlaxCLIPVisionModule(self.config.vision_config )
       UpperCamelCase					=  nn.Dense(self.config.projection_dim  ,						use_bias=UpperCamelCase__  ,						dtype=self.dtype )

       UpperCamelCase					=  self.param('concept_embeds'  ,						jax.nn.initializers.ones  ,						(1_7, self.config.projection_dim) )
       UpperCamelCase					=  self.param(
           'special_care_embeds'  ,						jax.nn.initializers.ones  ,						(3, self.config.projection_dim) )

       UpperCamelCase					=  self.param('concept_embeds_weights'  ,						jax.nn.initializers.ones  ,						(1_7,) )
       UpperCamelCase					=  self.param('special_care_embeds_weights'  ,						jax.nn.initializers.ones  ,						(3,) )






    def __call__(  self      :					str  ,						UpperCamelCase__      :					List[str] ):


       """simple docstring"""







       UpperCamelCase					=  self.vision_model(UpperCamelCase__ )[1]
       UpperCamelCase					=  self.visual_projection(UpperCamelCase__ )

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

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

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

       return has_nsfw_concepts

class  SCREAMING_SNAKE_CASE (  _a		):






    """simple docstring"""





    _SCREAMING_SNAKE_CASE	  =  CLIPConfig
    _SCREAMING_SNAKE_CASE	  =  """clip_input"""
    _SCREAMING_SNAKE_CASE	  =  FlaxStableDiffusionSafetyCheckerModule






    def __init__(  self      :					Union[str, Any]  ,						UpperCamelCase__      :					CLIPConfig  ,						UpperCamelCase__      :					Optional[Tuple] = None  ,						UpperCamelCase__      :					int = 0  ,						UpperCamelCase__      :					jnp.dtype = jnp.floataa  ,						UpperCamelCase__      :					bool = True  ,						**UpperCamelCase__      :					List[str]  ,						):


       """simple docstring"""







       if input_shape is None:
          UpperCamelCase					=  (1, 2_2_4, 2_2_4, 3)
       UpperCamelCase					=  self.module_class(config=UpperCamelCase__  ,						dtype=UpperCamelCase__  ,						**UpperCamelCase__ )
       super().__init__(UpperCamelCase__  ,						UpperCamelCase__  ,						input_shape=UpperCamelCase__  ,						seed=UpperCamelCase__  ,						dtype=UpperCamelCase__  ,						_do_init=_do_init )






    def  A       (  self      :					int  ,						UpperCamelCase__      :					jax.random.KeyArray  ,						UpperCamelCase__      :					Tuple  ,						UpperCamelCase__      :					FrozenDict = None ):


       """simple docstring"""







       UpperCamelCase					=  jax.random.normal(UpperCamelCase__  ,						UpperCamelCase__ )

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

       UpperCamelCase					=  self.module.init(UpperCamelCase__  ,						UpperCamelCase__ )['params']

       return random_params






    def __call__(  self      :					List[Any]  ,						UpperCamelCase__      :					Dict  ,						UpperCamelCase__      :					dict = None  ,						):


       """simple docstring"""







       UpperCamelCase					=  jnp.transpose(UpperCamelCase__  ,						(0, 2, 3, 1) )

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

