





import torch
import torch.nn as nn
from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel

from ...utils import logging


UpperCamelCase__											= logging.get_logger(__name__)





def     _UpperCamelCase     (a__   :Dict   ,			a__   :Optional[Any]       ):






							"""simple docstring"""





							UpperCamelCase__				     =			nn.functional.normalize(a__       )
							UpperCamelCase__				     =			nn.functional.normalize(a__       )
							return torch.mm(a__   ,			normalized_text_embeds.t()       )

class        __SCREAMING_SNAKE_CASE					(     _a       ):
							snake_case     :      Optional[Any]						     =       CLIPConfig

							snake_case     :      Tuple						     =       ["""CLIPEncoderLayer"""]






							def __init__(						self  , __lowerCAmelCase  ):
														super().__init__(__lowerCAmelCase  )

														UpperCamelCase__				     =			CLIPVisionModel(config.vision_config  )
														UpperCamelCase__				     =			nn.Linear(config.vision_config.hidden_size  , config.projection_dim  , bias=__lowerCAmelCase  )

														UpperCamelCase__				     =			nn.Parameter(torch.ones(17  , config.projection_dim  )  , requires_grad=__lowerCAmelCase  )
														UpperCamelCase__				     =			nn.Parameter(torch.ones(3  , config.projection_dim  )  , requires_grad=__lowerCAmelCase  )

														UpperCamelCase__				     =			nn.Parameter(torch.ones(17  )  , requires_grad=__lowerCAmelCase  )
														UpperCamelCase__				     =			nn.Parameter(torch.ones(3  )  , requires_grad=__lowerCAmelCase  )






							@torch.no_grad()
							def 				_lowerCamelCase		(						self  , __lowerCAmelCase  , __lowerCAmelCase  ):
														UpperCamelCase__				     =			self.vision_model(__lowerCAmelCase  )[1]  # pooled_output
														UpperCamelCase__				     =			self.visual_projection(__lowerCAmelCase  )

														# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
														UpperCamelCase__				     =			cosine_distance(__lowerCAmelCase  , self.special_care_embeds  ).cpu().float().numpy()
														UpperCamelCase__				     =			cosine_distance(__lowerCAmelCase  , self.concept_embeds  ).cpu().float().numpy()

														UpperCamelCase__				     =			[]
														UpperCamelCase__				     =			image_embeds.shape[0]
														for i in range(__lowerCAmelCase  ):
																					UpperCamelCase__				     =			{"""special_scores""": {}, """special_care""": [], """concept_scores""": {}, """bad_concepts""": []}

																					# increase this value to create a stronger `nfsw` filter
																					# at the cost of increasing the possibility of filtering benign images
																					UpperCamelCase__				     =			0.0

																					for concept_idx in range(len(special_cos_dist[0]  )  ):
																												UpperCamelCase__				     =			special_cos_dist[i][concept_idx]
																												UpperCamelCase__				     =			self.special_care_embeds_weights[concept_idx].item()
																												UpperCamelCase__				     =			round(concept_cos - concept_threshold + adjustment  , 3  )
																												if result_img["special_scores"][concept_idx] > 0:
																																			result_img["special_care"].append({concept_idx, result_img["""special_scores"""][concept_idx]}  )
																																			UpperCamelCase__				     =			0.01

																					for concept_idx in range(len(cos_dist[0]  )  ):
																												UpperCamelCase__				     =			cos_dist[i][concept_idx]
																												UpperCamelCase__				     =			self.concept_embeds_weights[concept_idx].item()
																												UpperCamelCase__				     =			round(concept_cos - concept_threshold + adjustment  , 3  )
																												if result_img["concept_scores"][concept_idx] > 0:
																																			result_img["bad_concepts"].append(__lowerCAmelCase  )

																					result.append(__lowerCAmelCase  )

														UpperCamelCase__				     =			[len(res["""bad_concepts"""]  ) > 0 for res in result]

														return images, has_nsfw_concepts







							@torch.no_grad()
							def 				_lowerCamelCase		(						self  , __lowerCAmelCase  , __lowerCAmelCase  ):
														UpperCamelCase__				     =			self.vision_model(__lowerCAmelCase  )[1]  # pooled_output
														UpperCamelCase__				     =			self.visual_projection(__lowerCAmelCase  )

														UpperCamelCase__				     =			cosine_distance(__lowerCAmelCase  , self.special_care_embeds  )
														UpperCamelCase__				     =			cosine_distance(__lowerCAmelCase  , self.concept_embeds  )

														# increase this value to create a stronger `nsfw` filter
														# at the cost of increasing the possibility of filtering benign images
														UpperCamelCase__				     =			0.0

														UpperCamelCase__				     =			special_cos_dist - self.special_care_embeds_weights + adjustment
														# special_scores = special_scores.round(decimals=3)
														UpperCamelCase__				     =			torch.any(special_scores > 0  , dim=1  )
														UpperCamelCase__				     =			special_care * 0.01
														UpperCamelCase__				     =			special_adjustment.unsqueeze(1  ).expand(-1  , cos_dist.shape[1]  )

														UpperCamelCase__				     =			(cos_dist - self.concept_embeds_weights) + special_adjustment
														# concept_scores = concept_scores.round(decimals=3)
														UpperCamelCase__				     =			torch.any(concept_scores > 0  , dim=1  )

														return images, has_nsfw_concepts











import unittest

from transformers import AutoConfig, AutoTokenizer, BertConfig, TensorType, is_flax_available
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, slow


if is_flax_available():
					import jax

					from transformers.models.auto.modeling_flax_auto import FlaxAutoModel
					from transformers.models.bert.modeling_flax_bert import FlaxBertModel
					from transformers.models.roberta.modeling_flax_roberta import FlaxRobertaModel

@require_flax
class        __SCREAMING_SNAKE_CASE					(     unittest.TestCase       ):






							@slow
							def 				_lowerCamelCase		(						self  ):
														for model_name in ["bert-base-cased", "bert-large-uncased"]:
																					with self.subTest(__lowerCAmelCase  ):
																												UpperCamelCase__				     =			AutoConfig.from_pretrained(__lowerCAmelCase  )
																												self.assertIsNotNone(__lowerCAmelCase  )
																												self.assertIsInstance(__lowerCAmelCase  , __lowerCAmelCase  )

																												UpperCamelCase__				     =			FlaxAutoModel.from_pretrained(__lowerCAmelCase  )
																												self.assertIsNotNone(__lowerCAmelCase  )
																												self.assertIsInstance(__lowerCAmelCase  , __lowerCAmelCase  )






							@slow
							def 				_lowerCamelCase		(						self  ):
														for model_name in ["roberta-base", "roberta-large"]:
																					with self.subTest(__lowerCAmelCase  ):
																												UpperCamelCase__				     =			AutoConfig.from_pretrained(__lowerCAmelCase  )
																												self.assertIsNotNone(__lowerCAmelCase  )
																												self.assertIsInstance(__lowerCAmelCase  , __lowerCAmelCase  )

																												UpperCamelCase__				     =			FlaxAutoModel.from_pretrained(__lowerCAmelCase  )
																												self.assertIsNotNone(__lowerCAmelCase  )
																												self.assertIsInstance(__lowerCAmelCase  , __lowerCAmelCase  )






							@slow
							def 				_lowerCamelCase		(						self  ):
														for model_name in ["bert-base-cased", "bert-large-uncased"]:
																					UpperCamelCase__				     =			AutoTokenizer.from_pretrained(__lowerCAmelCase  )
																					UpperCamelCase__				     =			FlaxBertModel.from_pretrained(__lowerCAmelCase  )
																					UpperCamelCase__				     =			tokenizer("""Do you support jax jitted function?"""  , return_tensors=TensorType.JAX  )

																					@jax.jit
																					def eval(**__lowerCAmelCase  ):
																												return model(**__lowerCAmelCase  )

																					eval(**__lowerCAmelCase  ).block_until_ready()






							@slow
							def 				_lowerCamelCase		(						self  ):
														for model_name in ["roberta-base", "roberta-large"]:
																					UpperCamelCase__				     =			AutoTokenizer.from_pretrained(__lowerCAmelCase  )
																					UpperCamelCase__				     =			FlaxRobertaModel.from_pretrained(__lowerCAmelCase  )
																					UpperCamelCase__				     =			tokenizer("""Do you support jax jitted function?"""  , return_tensors=TensorType.JAX  )

																					@jax.jit
																					def eval(**__lowerCAmelCase  ):
																												return model(**__lowerCAmelCase  )

																					eval(**__lowerCAmelCase  ).block_until_ready()






							def 				_lowerCamelCase		(						self  ):
														with self.assertRaisesRegex(
														    __lowerCAmelCase  , """bert-base is not a local folder and is not a valid model identifier"""  ):
																					UpperCamelCase__				     =			FlaxAutoModel.from_pretrained("""bert-base"""  )






							def 				_lowerCamelCase		(						self  ):
														with self.assertRaisesRegex(
														    __lowerCAmelCase  , r"""aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)"""  ):
																					UpperCamelCase__				     =			FlaxAutoModel.from_pretrained(__lowerCAmelCase  , revision="""aaaaaa"""  )






							def 				_lowerCamelCase		(						self  ):
														with self.assertRaisesRegex(
														    __lowerCAmelCase  , """hf-internal-testing/config-no-model does not appear to have a file named flax_model.msgpack"""  , ):
																					UpperCamelCase__				     =			FlaxAutoModel.from_pretrained("""hf-internal-testing/config-no-model"""  )







							def 				_lowerCamelCase		(						self  ):
														with self.assertRaisesRegex(__lowerCAmelCase  , """Use `from_pt=True` to load this model"""  ):
																					UpperCamelCase__				     =			FlaxAutoModel.from_pretrained("""hf-internal-testing/tiny-bert-pt-only"""  )




