





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

from ...utils import logging


lowerCAmelCase							:       List[str]					 =	logging.get_logger(__name__)






def 		lowerCAmelCase  (	UpperCamelCase__   :   int       ,			UpperCamelCase__   :   Dict					)      ->    Any:

						"""simple docstring"""





						__SCREAMING_SNAKE_CASE:				Optional[Any]           =   nn.functional.normalize(UpperCamelCase__					)
						__SCREAMING_SNAKE_CASE:				int           =   nn.functional.normalize(UpperCamelCase__					)
						return torch.mm(UpperCamelCase__       ,			normalized_text_embeds.t()					)





class 				a			(      __lowercase			):
				SCREAMING_SNAKE_CASE__     :   int		      =     CLIPConfig

				SCREAMING_SNAKE_CASE__     :   Optional[Any]		      =     ['''CLIPEncoderLayer''']






				def __init__(  self			, _lowerCAmelCase					):

										"""simple docstring"""




										super().__init__(_lowerCAmelCase					)

										__SCREAMING_SNAKE_CASE:				List[Any]           =   CLIPVisionModel(config.vision_config					)
										__SCREAMING_SNAKE_CASE:				int           =   nn.Linear(config.vision_config.hidden_size			, config.projection_dim			, bias=_lowerCAmelCase					)

										__SCREAMING_SNAKE_CASE:				Union[str, Any]           =   nn.Parameter(torch.ones(17			, config.projection_dim					)			, requires_grad=_lowerCAmelCase					)
										__SCREAMING_SNAKE_CASE:				List[Any]           =   nn.Parameter(torch.ones(3			, config.projection_dim					)			, requires_grad=_lowerCAmelCase					)

										__SCREAMING_SNAKE_CASE:				str           =   nn.Parameter(torch.ones(17					)			, requires_grad=_lowerCAmelCase					)
										__SCREAMING_SNAKE_CASE:				Union[str, Any]           =   nn.Parameter(torch.ones(3					)			, requires_grad=_lowerCAmelCase					)






				@torch.no_grad()
				def 			snake_case_    (  self			, _lowerCAmelCase			, _lowerCAmelCase					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				Optional[Any]           =   self.vision_model(_lowerCAmelCase					)[1]  # pooled_output
										__SCREAMING_SNAKE_CASE:				Union[str, Any]           =   self.visual_projection(_lowerCAmelCase					)

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

										__SCREAMING_SNAKE_CASE:				List[str]           =   []
										__SCREAMING_SNAKE_CASE:				Tuple           =   image_embeds.shape[0]
										for i in range(_lowerCAmelCase					):
																__SCREAMING_SNAKE_CASE:				List[str]           =   {'''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
																__SCREAMING_SNAKE_CASE:				Tuple           =   0.0

																for concept_idx in range(len(special_cos_dist[0]					)					):
																						__SCREAMING_SNAKE_CASE:				List[str]           =   special_cos_dist[i][concept_idx]
																						__SCREAMING_SNAKE_CASE:				int           =   self.special_care_embeds_weights[concept_idx].item()
																						__SCREAMING_SNAKE_CASE:				Optional[int]           =   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]}					)
																												__SCREAMING_SNAKE_CASE:				List[str]           =   0.01

																for concept_idx in range(len(cos_dist[0]					)					):
																						__SCREAMING_SNAKE_CASE:				Tuple           =   cos_dist[i][concept_idx]
																						__SCREAMING_SNAKE_CASE:				int           =   self.concept_embeds_weights[concept_idx].item()
																						__SCREAMING_SNAKE_CASE:				Union[str, Any]           =   round(concept_cos - concept_threshold + adjustment			, 3					)
																						if result_img["concept_scores"][concept_idx] > 0:
																												result_img["bad_concepts"].append(_lowerCAmelCase					)

																result.append(_lowerCAmelCase					)

										__SCREAMING_SNAKE_CASE:				List[str]           =   [len(res['''bad_concepts''']					) > 0 for res in result]

										return images, has_nsfw_concepts






				@torch.no_grad()
				def 			snake_case_    (  self			, _lowerCAmelCase			, _lowerCAmelCase					):

										"""simple docstring"""




										__SCREAMING_SNAKE_CASE:				str           =   self.vision_model(_lowerCAmelCase					)[1]  # pooled_output
										__SCREAMING_SNAKE_CASE:				Optional[Any]           =   self.visual_projection(_lowerCAmelCase					)

										__SCREAMING_SNAKE_CASE:				Dict           =   cosine_distance(_lowerCAmelCase			, self.special_care_embeds					)
										__SCREAMING_SNAKE_CASE:				Dict           =   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
										__SCREAMING_SNAKE_CASE:				Optional[int]           =   0.0

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

										__SCREAMING_SNAKE_CASE:				Union[str, Any]           =   (cos_dist - self.concept_embeds_weights) + special_adjustment
										# concept_scores = concept_scores.round(decimals=3)
										__SCREAMING_SNAKE_CASE:				Optional[int]           =   torch.any(concept_scores > 0			, dim=1					)

										return images, has_nsfw_concepts










from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_torch_available,
)


lowerCAmelCase							:       List[str]					 =	{
    """configuration_gpt_bigcode""": ["""GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP""", """GPTBigCodeConfig"""],
}

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							lowerCAmelCase							:       str					 =	[
							    """GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST""",
							    """GPTBigCodeForSequenceClassification""",
							    """GPTBigCodeForTokenClassification""",
							    """GPTBigCodeForCausalLM""",
							    """GPTBigCodeModel""",
							    """GPTBigCodePreTrainedModel""",
							]

if TYPE_CHECKING:
							from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .modeling_gpt_bigcode import (
														    GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST,
														    GPTBigCodeForCausalLM,
														    GPTBigCodeForSequenceClassification,
														    GPTBigCodeForTokenClassification,
														    GPTBigCodeModel,
														    GPTBigCodePreTrainedModel,
														)


else:
							import sys

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



