

'''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_     (			_lowerCamelCase:     Optional[Any] ,   _lowerCamelCase:     List[str] ,   _lowerCamelCase:     int=1E-12      ):
		__SCREAMING_SNAKE_CASE :	Tuple					 =	jnp.divide(emb_a.T ,   jnp.clip(jnp.linalg.norm(_lowerCamelCase ,   axis=1      ) ,   a_min=_lowerCamelCase      )      ).T
		__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	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 		_UpperCamelCase						(							nn.Module					):


			'''simple docstring'''

			_A   :	CLIPConfig
			_A   :	jnp.dtype    					=	jnp.floataa

			def UpperCamelCase__      (							self  :				Dict		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	str					 =	FlaxCLIPVisionModule(self.config.vision_config		)
					__SCREAMING_SNAKE_CASE :	Union[str, Any]					 =	nn.Dense(self.config.projection_dim							,  use_bias=lowerCAmelCase__							,  dtype=self.dtype		)

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

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



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





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	self.vision_model(lowerCAmelCase__		)[1]
					__SCREAMING_SNAKE_CASE :	List[str]					 =	self.visual_projection(lowerCAmelCase__		)

					__SCREAMING_SNAKE_CASE :	Optional[int]					 =	jax_cosine_distance(lowerCAmelCase__							,  self.special_care_embeds		)
					__SCREAMING_SNAKE_CASE :	Tuple					 =	jax_cosine_distance(lowerCAmelCase__							,  self.concept_embeds		)

					# increase this value to create a stronger `nfsw` filter
					# at the cost of increasing the possibility of filtering benign image inputs
					__SCREAMING_SNAKE_CASE :	List[str]					 =	0.0

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

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

					return has_nsfw_concepts






class 		_UpperCamelCase						(							lowerCamelCase__					):


			'''simple docstring'''

			_A   :	Tuple    					=	CLIPConfig
			_A   :	Any    					=	'''clip_input'''
			_A   :	List[Any]    					=	FlaxStableDiffusionSafetyCheckerModule

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





					"""simple docstring"""






					if input_shape is None:
							__SCREAMING_SNAKE_CASE :	Dict					 =	(1, 2_2_4, 2_2_4, 3)
					__SCREAMING_SNAKE_CASE :	Optional[int]					 =	self.module_class(config=lowerCAmelCase__							,  dtype=lowerCAmelCase__							,  **lowerCAmelCase__		)
					super().__init__(lowerCAmelCase__							,  lowerCAmelCase__							,  input_shape=lowerCAmelCase__							,  seed=lowerCAmelCase__							,  dtype=lowerCAmelCase__							,  _do_init=_do_init		)

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





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	str					 =	jax.random.normal(lowerCAmelCase__							,  lowerCAmelCase__		)

					__SCREAMING_SNAKE_CASE :	Optional[int]					 =	jax.random.split(lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	Dict					 =	{"""params""": params_rng, """dropout""": dropout_rng}

					__SCREAMING_SNAKE_CASE :	List[Any]					 =	self.module.init(lowerCAmelCase__							,  lowerCAmelCase__		)["""params"""]

					return random_params



			def __call__(							self  :				List[str]							,  lowerCAmelCase__  :				Optional[Any]							,  lowerCAmelCase__  :				dict = None							,  ):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	Optional[int]					 =	jnp.transpose(lowerCAmelCase__							,  (0, 2, 3, 1)		)

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




'''simple docstring'''




# coding=utf-8
# Copyright 2020 The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# this script dumps information about the environment

import os
import sys

import transformers


UpperCamelCase__ :			Tuple												=				'''3'''

print('''Python version:''', sys.version)
print('''transformers version:''', transformers.__version__)

try:
						import torch

						print('''Torch version:''', torch.__version__)
						print('''Cuda available:''', torch.cuda.is_available())
						print('''Cuda version:''', torch.version.cuda)
						print('''CuDNN version:''', torch.backends.cudnn.version())
						print('''Number of GPUs available:''', torch.cuda.device_count())
						print('''NCCL version:''', torch.cuda.nccl.version())
except ImportError:
						print('''Torch version:''', None)

try:
						import deepspeed

						print('''DeepSpeed version:''', deepspeed.__version__)
except ImportError:
						print('''DeepSpeed version:''', None)

try:
						import tensorflow as tf

						print('''TensorFlow version:''', tf.__version__)
						print('''TF GPUs available:''', bool(tf.config.list_physical_devices('''GPU''')))
						print('''Number of TF GPUs available:''', len(tf.config.list_physical_devices('''GPU''')))
except ImportError:
						print('''TensorFlow version:''', None)