


"""simple docstring"""







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

from ...utils import logging


__lowercase          = logging.get_logger(__name__)


def 	lowercase     (							A_    ,  A_			)-> Optional[int]:
  '''simple docstring'''







  a		:						int 				=     nn.functional.normalize(A_			)
  a		:						Dict 				=     nn.functional.normalize(A_			)
  return torch.mm(A_    ,  normalized_text_embeds.t()			)







class 		_A    (    _a    ):







    """simple docstring"""




    UpperCAmelCase			:				Dict      =			CLIPConfig

    UpperCAmelCase			:				Optional[Any]      =			["""CLIPEncoderLayer"""]






    def __init__(   self							:       List[Any]							,					__UpperCAmelCase							:       CLIPConfig):
      super().__init__(__UpperCAmelCase)

      a		:						int 				=     CLIPVisionModel(config.vision_config)
      a		:						Optional[Any] 				=     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		:						Optional[Any] 				=     nn.Parameter(torch.ones(3							,					config.projection_dim)							,					requires_grad=__UpperCAmelCase)

      a		:						Dict 				=     nn.Parameter(torch.ones(17)							,					requires_grad=__UpperCAmelCase)
      a		:						Tuple 				=     nn.Parameter(torch.ones(3)							,					requires_grad=__UpperCAmelCase)






    @torch.no_grad()
    def       __snake_case				(   self							:       str							,					__UpperCAmelCase							:       Optional[int]							,					__UpperCAmelCase							:       Optional[int]):
      a		:						Dict 				=     self.vision_model(__UpperCAmelCase)[1]  # pooled_output
      a		:						Union[str, Any] 				=     self.visual_projection(__UpperCAmelCase)

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

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

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

        for concept_idx in range(len(cos_dist[0])):
          a		:						Any 				=     cos_dist[i][concept_idx]
          a		:						Dict 				=     self.concept_embeds_weights[concept_idx].item()
          a		:						Optional[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		:						Tuple 				=     [len(res["bad_concepts"]) > 0 for res in result]

      for idx, has_nsfw_concept in enumerate(__UpperCAmelCase):
        if has_nsfw_concept:
          if torch.is_tensor(__UpperCAmelCase) or torch.is_tensor(images[0]):
            a		:						Any 				=     torch.zeros_like(images[idx])  # black image
          else:
            a		:						Any 				=     np.zeros(images[idx].shape)  # black image

      if any(__UpperCAmelCase):
        logger.warning(
            "Potential NSFW content was detected in one or more images. A black image will be returned instead."
            " Try again with a different prompt and/or seed.")

      return images, has_nsfw_concepts






    @torch.no_grad()
    def       __snake_case				(   self							:       Optional[Any]							,					__UpperCAmelCase							:       torch.FloatTensor							,					__UpperCAmelCase							:       torch.FloatTensor):
      a		:						Union[str, Any] 				=     self.vision_model(__UpperCAmelCase)[1]  # pooled_output
      a		:						List[str] 				=     self.visual_projection(__UpperCAmelCase)

      a		:						Optional[Any] 				=     cosine_distance(__UpperCAmelCase							,					self.special_care_embeds)
      a		:						List[Any] 				=     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		:						List[str] 				=     0.0

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

      a		:						Dict 				=     (cos_dist - self.concept_embeds_weights) + special_adjustment
      # concept_scores = concept_scores.round(decimals=3)
      a		:						List[str] 				=     torch.any(concept_scores > 0							,					dim=1)

      a		:						List[Any] 				=     0.0  # black image

      return images, has_nsfw_concepts










"""simple docstring"""







import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional

import transformers
from transformers import (
    AutoConfig,
    AutoModelForQuestionAnswering,
    AutoTokenizer,
    DataCollatorWithPadding,
    HfArgumentParser,
    SquadDataset,
    Trainer,
    TrainingArguments,
)
from transformers import SquadDataTrainingArguments as DataTrainingArguments
from transformers.trainer_utils import is_main_process


__lowercase          = logging.getLogger(__name__)






@dataclass
class 		_A    :







    """simple docstring"""




    UpperCAmelCase			:				str      =			field(
        metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""}    )
    UpperCAmelCase			:				Optional[str]      =			field(
        default=_a       ,metadata={"""help""": """Pretrained config name or path if not the same as model_name"""}    )
    UpperCAmelCase			:				Optional[str]      =			field(
        default=_a       ,metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""}    )
    UpperCAmelCase			:				bool      =			field(default=_a       ,metadata={"""help""": """Set this flag to use fast tokenization."""}    )
    # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script,
    # or just modify its tokenizer_config.json.
    UpperCAmelCase			:				Optional[str]      =			field(
        default=_a       ,metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}       ,)






def 	lowercase     (							)-> Dict:
  '''simple docstring'''







  a		:						Tuple 				=     HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)			)

  if len(sys.argv			) == 2 and sys.argv[1].endswith(".json"			):
    # If we pass only one argument to the script and it's the path to a json file,
    # let's parse it to get our arguments.
    a				,						a				,						a		:						Any 				=     parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]			)			)
  else:
    a				,						a				,						a		:						List[str] 				=     parser.parse_args_into_dataclasses()

  if (
      os.path.exists(training_args.output_dir			)
      and os.listdir(training_args.output_dir			)
      and training_args.do_train
      and not training_args.overwrite_output_dir
  ):
    raise ValueError(
        F'''Output directory ({training_args.output_dir}) already exists and is not empty. Use'''
        " --overwrite_output_dir to overcome."			)

  # Setup logging
  logging.basicConfig(
      format="%(asctime)s - %(levelname)s - %(name)s - %(message)s"    ,  datefmt="%m/%d/%Y %H:%M:%S"    ,  level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN    ,  )
  logger.warning(
      "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s"    ,  training_args.local_rank    ,  training_args.device    ,  training_args.n_gpu    ,  bool(training_args.local_rank != -1			)    ,  training_args.fpaa    ,  )
  # Set the verbosity to info of the Transformers logger (on main process only):
  if is_main_process(training_args.local_rank			):
    transformers.utils.logging.set_verbosity_info()
    transformers.utils.logging.enable_default_handler()
    transformers.utils.logging.enable_explicit_format()
  logger.info("Training/evaluation parameters %s"    ,  A_			)

  # Prepare Question-Answering task
  # Load pretrained model and tokenizer
  #
  # Distributed training:
  # The .from_pretrained methods guarantee that only one local process can concurrently
  # download model & vocab.

  a		:						str 				=     AutoConfig.from_pretrained(
      model_args.config_name if model_args.config_name else model_args.model_name_or_path    ,  cache_dir=model_args.cache_dir    ,  )
  a		:						str 				=     AutoTokenizer.from_pretrained(
      model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path    ,  cache_dir=model_args.cache_dir    ,  use_fast=A_    ,  )
  a		:						List[Any] 				=     AutoModelForQuestionAnswering.from_pretrained(
      model_args.model_name_or_path    ,  from_tf=bool(".ckpt" in model_args.model_name_or_path			)    ,  config=A_    ,  cache_dir=model_args.cache_dir    ,  )

  # Get datasets
  a		:						int 				=     hasattr(model.config    ,  "lang2id"			)
  a		:						Any 				=     (
      SquadDataset(
          A_    ,  tokenizer=A_    ,  is_language_sensitive=A_    ,  cache_dir=model_args.cache_dir			)
      if training_args.do_train
      else None
  )
  a		:						Tuple 				=     (
      SquadDataset(
          A_    ,  tokenizer=A_    ,  mode="dev"    ,  is_language_sensitive=A_    ,  cache_dir=model_args.cache_dir    ,  )
      if training_args.do_eval
      else None
  )

  # Data collator
  a		:						str 				=     DataCollatorWithPadding(A_    ,  pad_to_multiple_of=8			) if training_args.fpaa else None

  # Initialize our Trainer
  a		:						Tuple 				=     Trainer(
      model=A_    ,  args=A_    ,  train_dataset=A_    ,  eval_dataset=A_    ,  data_collator=A_    ,  )

  # Training
  if training_args.do_train:
    trainer.train(
        model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path			) else None			)
    trainer.save_model()
    # For convenience, we also re-save the tokenizer to the same directory,
    # so that you can share your model easily on huggingface.co/models =)
    if trainer.is_world_master():
      tokenizer.save_pretrained(training_args.output_dir			)


def 	lowercase     (							A_			)-> int:
  '''simple docstring'''







  main()


if __name__ == "__main__":
 main()






