




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

from ...utils import logging


lowerCamelCase	:	Union[str, Any]				=   logging.get_logger(__name__)




def 						SCREAMING_SNAKE_CASE__ (   lowercase						,lowercase					)  ->       Any:
   snake_case				:    Dict           =	nn.functional.normalize(lowercase					)
   snake_case				:    str           =	nn.functional.normalize(lowercase					)
   return torch.mm(lowercase						,normalized_text_embeds.t()					)




class 						__lowercase		(UpperCamelCase__							):




      """simple docstring"""





      _snake_case												=						CLIPConfig

      _snake_case												=						["""CLIPEncoderLayer"""]

      def __init__(				self    ,				A     )		->    Optional[Any]:
         super().__init__(A     )

         snake_case				:    List[Any]           =	CLIPVisionModel(config.vision_config     )
         snake_case				:    List[str]           =	nn.Linear(config.vision_config.hidden_size    ,				config.projection_dim    ,				bias=A     )

         snake_case				:    Optional[int]           =	nn.Parameter(torch.ones(1_7    ,				config.projection_dim     )    ,				requires_grad=A     )
         snake_case				:    Optional[int]           =	nn.Parameter(torch.ones(3    ,				config.projection_dim     )    ,				requires_grad=A     )

         snake_case				:    List[Any]           =	nn.Parameter(torch.ones(1_7     )    ,				requires_grad=A     )
         snake_case				:    Optional[int]           =	nn.Parameter(torch.ones(3     )    ,				requires_grad=A     )

      @torch.no_grad()
      def      UpperCAmelCase				(				self    ,				A    ,				A     )		->    Optional[Any]:
         snake_case				:    List[str]           =	self.vision_model(A     )[1]  # pooled_output
         snake_case				:    Union[str, Any]           =	self.visual_projection(A     )

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

         snake_case				:    Optional[Any]           =	[]
         snake_case				:    int           =	image_embeds.shape[0]
         for i in range(A     ):
            snake_case				:    List[Any]           =	{"""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
            snake_case				:    Tuple           =	0.0

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

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

            result.append(A     )

         snake_case				:    Union[str, Any]           =	[len(res["""bad_concepts"""]     ) > 0 for res in result]

         return images, has_nsfw_concepts

      @torch.no_grad()
      def      UpperCAmelCase				(				self    ,				A    ,				A     )		->    Union[str, Any]:
         snake_case				:    str           =	self.vision_model(A     )[1]  # pooled_output
         snake_case				:    Any           =	self.visual_projection(A     )

         snake_case				:    Optional[Any]           =	cosine_distance(A    ,				self.special_care_embeds     )
         snake_case				:    Tuple           =	cosine_distance(A    ,				self.concept_embeds     )

         # increase this value to create a stronger `nsfw` filter
         # at the cost of increasing the possibility of filtering benign images
         snake_case				:    Union[str, Any]           =	0.0

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

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

         return images, has_nsfw_concepts











def 						SCREAMING_SNAKE_CASE__ (   lowercase						,lowercase					)  ->       int:
   return int((input_a, input_a).count(1					) != 0					)




def 						SCREAMING_SNAKE_CASE__ (   )  ->       None:
   assert or_gate(0						,0					) == 0
   assert or_gate(0						,1					) == 1
   assert or_gate(1						,0					) == 1
   assert or_gate(1						,1					) == 1


if __name__ == "__main__":
       print(or_gate(0, 1))
       print(or_gate(1, 0))
       print(or_gate(0, 0))
       print(or_gate(1, 1))





