





"""simple docstring"""





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

from ...utils import logging


SCREAMING_SNAKE_CASE__					=   logging.get_logger(__name__)


def 			UpperCAmelCase__							(  SCREAMING_SNAKE_CASE     :						Union[str, Any]							,						SCREAMING_SNAKE_CASE     :						List[Any]			):







      '''simple docstring'''




      lowerCAmelCase  						=       nn.functional.normalize(SCREAMING_SNAKE_CASE			)
      lowerCAmelCase  						=       nn.functional.normalize(SCREAMING_SNAKE_CASE			)
      return torch.mm(SCREAMING_SNAKE_CASE							,						normalized_text_embeds.t()			)






class 		lowercase					(					_UpperCAmelCase					):
      _SCREAMING_SNAKE_CASE					=      CLIPConfig

      _SCREAMING_SNAKE_CASE					=      ['CLIPEncoderLayer']





      def __init__(       self      ,						lowercase )		->     Optional[int]:
            super().__init__(lowercase )

            lowerCAmelCase  						=       CLIPVisionModel(config.vision_config )
            lowerCAmelCase  						=       nn.Linear(config.vision_config.hidden_size      ,						config.projection_dim      ,						bias=lowercase )

            lowerCAmelCase  						=       nn.Parameter(torch.ones(17      ,						config.projection_dim )      ,						requires_grad=lowercase )
            lowerCAmelCase  						=       nn.Parameter(torch.ones(3      ,						config.projection_dim )      ,						requires_grad=lowercase )

            lowerCAmelCase  						=       nn.Parameter(torch.ones(17 )      ,						requires_grad=lowercase )
            lowerCAmelCase  						=       nn.Parameter(torch.ones(3 )      ,						requires_grad=lowercase )





      @torch.no_grad()
      def     _snake_case			(       self      ,						lowercase      ,						lowercase )		->     Optional[Any]:
            lowerCAmelCase  						=       self.vision_model(lowercase )[1]  # pooled_output
            lowerCAmelCase  						=       self.visual_projection(lowercase )

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

            lowerCAmelCase  						=       []
            lowerCAmelCase  						=       image_embeds.shape[0]
            for i in range(lowercase ):
                  lowerCAmelCase  						=       {"""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
                  lowerCAmelCase  						=       0.0

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

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

                  result.append(lowercase )

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

            return images, has_nsfw_concepts





      @torch.no_grad()
      def     _snake_case			(       self      ,						lowercase      ,						lowercase )		->     Union[str, Any]:
            lowerCAmelCase  						=       self.vision_model(lowercase )[1]  # pooled_output
            lowerCAmelCase  						=       self.visual_projection(lowercase )

            lowerCAmelCase  						=       cosine_distance(lowercase      ,						self.special_care_embeds )
            lowerCAmelCase  						=       cosine_distance(lowercase      ,						self.concept_embeds )

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

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

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

            return images, has_nsfw_concepts













"""simple docstring"""





from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


if TYPE_CHECKING:
       from ... import FeatureExtractionMixin, TensorType

SCREAMING_SNAKE_CASE__					=   logging.get_logger(__name__)

SCREAMING_SNAKE_CASE__					=   {
    "openai/imagegpt-small": "",
    "openai/imagegpt-medium": "",
    "openai/imagegpt-large": "",
}

class 		lowercase					(					_UpperCAmelCase					):
      _SCREAMING_SNAKE_CASE					=      'imagegpt'
      _SCREAMING_SNAKE_CASE					=      ['past_key_values']
      _SCREAMING_SNAKE_CASE					=      {
          'hidden_size': 'n_embd',
          'max_position_embeddings': 'n_positions',
          'num_attention_heads': 'n_head',
          'num_hidden_layers': 'n_layer',
      }





      def __init__(       self      ,						lowercase=512 + 1      ,						lowercase=32 * 32      ,						lowercase=512      ,						lowercase=24      ,						lowercase=8      ,						lowercase=None      ,						lowercase="quick_gelu"      ,						lowercase=0.1      ,						lowercase=0.1      ,						lowercase=0.1      ,						lowercase=1e-5      ,						lowercase=0.02      ,						lowercase=True      ,						lowercase=True      ,						lowercase=False      ,						lowercase=False      ,						lowercase=False      ,						**lowercase      ,						)		->     Any:
            lowerCAmelCase  						=       vocab_size
            lowerCAmelCase  						=       n_positions
            lowerCAmelCase  						=       n_embd
            lowerCAmelCase  						=       n_layer
            lowerCAmelCase  						=       n_head
            lowerCAmelCase  						=       n_inner
            lowerCAmelCase  						=       activation_function
            lowerCAmelCase  						=       resid_pdrop
            lowerCAmelCase  						=       embd_pdrop
            lowerCAmelCase  						=       attn_pdrop
            lowerCAmelCase  						=       layer_norm_epsilon
            lowerCAmelCase  						=       initializer_range
            lowerCAmelCase  						=       scale_attn_weights
            lowerCAmelCase  						=       use_cache
            lowerCAmelCase  						=       scale_attn_by_inverse_layer_idx
            lowerCAmelCase  						=       reorder_and_upcast_attn
            lowerCAmelCase  						=       tie_word_embeddings

            super().__init__(tie_word_embeddings=lowercase      ,						**lowercase )







class 		lowercase					(					_UpperCAmelCase					):





      @property
      def     _snake_case			(       self )		->     Mapping[str, Mapping[int, str]]:
            return OrderedDict(
                [
                    ("""input_ids""", {0: """batch""", 1: """sequence"""}),
                ] )





      def     _snake_case			(       self      ,						lowercase      ,						lowercase = 1      ,						lowercase = -1      ,						lowercase = False      ,						lowercase = None      ,						lowercase = 3      ,						lowercase = 32      ,						lowercase = 32      ,						)		->     Mapping[str, Any]:
            lowerCAmelCase  						=       self._generate_dummy_images(lowercase      ,						lowercase      ,						lowercase      ,						lowercase )
            lowerCAmelCase  						=       dict(preprocessor(images=lowercase      ,						return_tensors=lowercase ) )

            return inputs






