





'''simple docstring'''




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

from ...utils import logging


lowercase__    :      str						=    logging.get_logger(__name__)






def        _lowerCAmelCase			(  __snake_case  : Any ,							__snake_case  : Union[str, Any]			)     ->     Optional[Any]:
     __A						: Optional[int]      =       nn.functional.normalize(__snake_case			)
     __A						: int      =       nn.functional.normalize(__snake_case			)
     return torch.mm(__snake_case ,							normalized_text_embeds.t()			)







class  SCREAMING_SNAKE_CASE    (a__							):
     lowerCAmelCase					=       CLIPConfig

     lowerCAmelCase					=       ['''CLIPEncoderLayer''']


     def __init__(						self						,	_UpperCAmelCase):

          '''simple docstring'''






          super().__init__(_UpperCAmelCase)

          __A						: List[str]      =       CLIPVisionModel(config.vision_config)
          __A						: Tuple      =       nn.Linear(config.vision_config.hidden_size						,	config.projection_dim						,	bias=_UpperCAmelCase)

          __A						: List[Any]      =       nn.Parameter(torch.ones(17						,	config.projection_dim)						,	requires_grad=_UpperCAmelCase)
          __A						: Any      =       nn.Parameter(torch.ones(3						,	config.projection_dim)						,	requires_grad=_UpperCAmelCase)

          __A						: Optional[int]      =       nn.Parameter(torch.ones(17)						,	requires_grad=_UpperCAmelCase)
          __A						: Optional[Any]      =       nn.Parameter(torch.ones(3)						,	requires_grad=_UpperCAmelCase)


     @torch.no_grad()
     def 							SCREAMING_SNAKE_CASE  (						self						,	_UpperCAmelCase						,	_UpperCAmelCase):

          '''simple docstring'''






          __A						: Optional[Any]      =       self.vision_model(_UpperCAmelCase)[1]  # pooled_output
          __A						: Dict      =       self.visual_projection(_UpperCAmelCase)

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

          __A						: Optional[int]      =       []
          __A						: Tuple      =       image_embeds.shape[0]
          for i in range(_UpperCAmelCase):
               __A						: 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
               __A						: Tuple      =       0.0

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

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

               result.append(_UpperCAmelCase)

          __A						: Dict      =       [len(res['bad_concepts']) > 0 for res in result]

          return images, has_nsfw_concepts


     @torch.no_grad()
     def 							SCREAMING_SNAKE_CASE  (						self						,	_UpperCAmelCase						,	_UpperCAmelCase):

          '''simple docstring'''






          __A						: Any      =       self.vision_model(_UpperCAmelCase)[1]  # pooled_output
          __A						: str      =       self.visual_projection(_UpperCAmelCase)

          __A						: Union[str, Any]      =       cosine_distance(_UpperCAmelCase						,	self.special_care_embeds)
          __A						: List[str]      =       cosine_distance(_UpperCAmelCase						,	self.concept_embeds)

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

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

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

          return images, has_nsfw_concepts






'''simple docstring'''




from collections import OrderedDict
from typing import Mapping

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


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

lowercase__    :      Dict						=    {
    '''roberta-base''': '''https://huggingface.co/roberta-base/resolve/main/config.json''',
    '''roberta-large''': '''https://huggingface.co/roberta-large/resolve/main/config.json''',
    '''roberta-large-mnli''': '''https://huggingface.co/roberta-large-mnli/resolve/main/config.json''',
    '''distilroberta-base''': '''https://huggingface.co/distilroberta-base/resolve/main/config.json''',
    '''roberta-base-openai-detector''': '''https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json''',
    '''roberta-large-openai-detector''': '''https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json''',
}


class  SCREAMING_SNAKE_CASE    (a__							):
     lowerCAmelCase					=       '''roberta'''


     def __init__(						self						,	_UpperCAmelCase=5_0265						,	_UpperCAmelCase=768						,	_UpperCAmelCase=12						,	_UpperCAmelCase=12						,	_UpperCAmelCase=3072						,	_UpperCAmelCase="gelu"						,	_UpperCAmelCase=0.1						,	_UpperCAmelCase=0.1						,	_UpperCAmelCase=512						,	_UpperCAmelCase=2						,	_UpperCAmelCase=0.02						,	_UpperCAmelCase=1e-1_2						,	_UpperCAmelCase=1						,	_UpperCAmelCase=0						,	_UpperCAmelCase=2						,	_UpperCAmelCase="absolute"						,	_UpperCAmelCase=True						,	_UpperCAmelCase=None						,	**_UpperCAmelCase						,	):

          '''simple docstring'''






          super().__init__(pad_token_id=_UpperCAmelCase						,	bos_token_id=_UpperCAmelCase						,	eos_token_id=_UpperCAmelCase						,	**_UpperCAmelCase)

          __A						: Optional[int]      =       vocab_size
          __A						: int      =       hidden_size
          __A						: Union[str, Any]      =       num_hidden_layers
          __A						: List[str]      =       num_attention_heads
          __A						: Optional[int]      =       hidden_act
          __A						: str      =       intermediate_size
          __A						: Union[str, Any]      =       hidden_dropout_prob
          __A						: Dict      =       attention_probs_dropout_prob
          __A						: int      =       max_position_embeddings
          __A						: str      =       type_vocab_size
          __A						: Any      =       initializer_range
          __A						: int      =       layer_norm_eps
          __A						: Optional[int]      =       position_embedding_type
          __A						: int      =       use_cache
          __A						: Union[str, Any]      =       classifier_dropout




class  SCREAMING_SNAKE_CASE    (a__							):


     @property
     def 							SCREAMING_SNAKE_CASE  (						self):

          '''simple docstring'''






          if self.task == "multiple-choice":
               __A						: str      =       {0: 'batch', 1: 'choice', 2: 'sequence'}
          else:
               __A						: List[str]      =       {0: 'batch', 1: 'sequence'}
          return OrderedDict(
              [
                  ('input_ids', dynamic_axis),
                  ('attention_mask', dynamic_axis),
              ])