



import argparse
import ast
import logging
import os
import sys

import pandas as pd
import torch
from tqdm import tqdm

from transformers import BartForConditionalGeneration, RagRetriever, RagSequenceForGeneration, RagTokenForGeneration
from transformers import logging as transformers_logging


sys.path.append(os.path.join(os.getcwd()))  # noqa: E402 # isort:skip
from utils_rag import exact_match_score, fa_score  # noqa: E402 # isort:skip


__UpperCAmelCase      = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

transformers_logging.set_verbosity_info()
def 	UpperCamelCase			(     snake_case__ :					Union[str, Any]			)			->  Optional[int]:
   if "token" in model_name_or_path:
      return "rag_token"
   if "sequence" in model_name_or_path:
      return "rag_sequence"
   if "bart" in model_name_or_path:
      return "bart"
   return None
def 	UpperCamelCase			(     snake_case__ :					Optional[Any] ,  snake_case__ :					Optional[Any] ,  snake_case__ :					Union[str, Any]			)			->  int:
   return max(metric_fn(snake_case__ ,  snake_case__			) for gt in ground_truths			)
def 	UpperCamelCase			(     snake_case__ :					List[str] ,  snake_case__ :					Any ,  snake_case__ :					int			)			->  Union[str, Any]:
   UpperCamelCase					:						Dict					=			[line.strip() for line in open(snake_case__ ,  'r'			).readlines()]
   UpperCamelCase					:						Optional[Any]					=			[]

   if args.gold_data_mode == "qa":
      UpperCamelCase					:						Union[str, Any]					=			pd.read_csv(snake_case__ ,  sep='\t' ,  header=snake_case__			)
      for answer_list in data[1]:
         UpperCamelCase					:						int					=			ast.literal_eval(snake_case__			)
         answers.append(snake_case__			)
   else:
      UpperCamelCase					:						Optional[Any]					=			[line.strip() for line in open(snake_case__ ,  'r'			).readlines()]
      UpperCamelCase					:						str					=			[[reference] for reference in references]

   UpperCamelCase					:						Tuple					=			0
   for prediction, ground_truths in zip(snake_case__ ,  snake_case__			):
      total += 1
      em += metric_max_over_ground_truths(snake_case__ ,  snake_case__ ,  snake_case__			)
      fa += metric_max_over_ground_truths(snake_case__ ,  snake_case__ ,  snake_case__			)

   UpperCamelCase					:						Union[str, Any]					=			100.0 * em / total
   UpperCamelCase					:						List[str]					=			100.0 * fa / total

   logger.info(F"""F1: {fa:.2f}"""			)
   logger.info(F"""EM: {em:.2f}"""			)
def 	UpperCamelCase			(     snake_case__ :					int ,  snake_case__ :					Optional[int] ,  snake_case__ :					int			)			->  str:
   UpperCamelCase					:						Tuple					=			args.k
   UpperCamelCase					:						Union[str, Any]					=			[line.strip() for line in open(snake_case__ ,  'r'			).readlines()]
   UpperCamelCase					:						Optional[Any]					=			[line.strip() for line in open(snake_case__ ,  'r'			).readlines()]

   UpperCamelCase					:						Optional[int]					=			0
   for hypo, reference in zip(snake_case__ ,  snake_case__			):
      UpperCamelCase					:						str					=			set(hypo.split('\t'			)[:k]			)
      UpperCamelCase					:						Optional[int]					=			set(reference.split('\t'			)			)
      total += 1
      em += len(hypo_provenance & ref_provenance			) / k

   UpperCamelCase					:						Dict					=			100.0 * em / total
   logger.info(F"""Precision@{k}: {em: .2f}"""			)
def 	UpperCamelCase			(     snake_case__ :					int ,  snake_case__ :					Dict ,  snake_case__ :					Dict			)			->  str:
   def strip_title(snake_case__ :					str			):
      if title.startswith('"'			):
         UpperCamelCase					:						Dict					=			title[1:]
      if title.endswith('"'			):
         UpperCamelCase					:						Optional[Any]					=			title[:-1]
      return title

   UpperCamelCase					:						List[str]					=			rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
       snake_case__ ,  return_tensors='pt' ,  padding=snake_case__ ,  truncation=snake_case__ ,  )['input_ids'].to(args.device			)

   UpperCamelCase					:						Optional[int]					=			rag_model.rag.question_encoder(snake_case__			)
   UpperCamelCase					:						Tuple					=			question_enc_outputs[0]

   UpperCamelCase					:						Optional[int]					=			rag_model.retriever(
       snake_case__ ,  question_enc_pool_output.cpu().detach().to(torch.floataa			).numpy() ,  prefix=rag_model.rag.generator.config.prefix ,  n_docs=rag_model.config.n_docs ,  return_tensors='pt' ,  )
   UpperCamelCase					:						List[str]					=			rag_model.retriever.index.get_doc_dicts(result.doc_ids			)
   UpperCamelCase					:						Any					=			[]
   for docs in all_docs:
      UpperCamelCase					:						Dict					=			[strip_title(snake_case__			) for title in docs['title']]
      provenance_strings.append('\t'.join(snake_case__			)			)
   return provenance_strings
def 	UpperCamelCase			(     snake_case__ :					int ,  snake_case__ :					int ,  snake_case__ :					List[Any]			)			->  Dict:
   with torch.no_grad():
      UpperCamelCase					:						Any					=			rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
          snake_case__ ,  return_tensors='pt' ,  padding=snake_case__ ,  truncation=snake_case__			)

      UpperCamelCase					:						List[str]					=			inputs_dict.input_ids.to(args.device			)
      UpperCamelCase					:						Optional[int]					=			inputs_dict.attention_mask.to(args.device			)
      UpperCamelCase					:						List[str]					=			rag_model.generate(  # rag_model overwrites generate
          snake_case__ ,  attention_mask=snake_case__ ,  num_beams=args.num_beams ,  min_length=args.min_length ,  max_length=args.max_length ,  early_stopping=snake_case__ ,  num_return_sequences=1 ,  bad_words_ids=[[0, 0]] ,  )
      UpperCamelCase					:						Dict					=			rag_model.retriever.generator_tokenizer.batch_decode(snake_case__ ,  skip_special_tokens=snake_case__			)

      if args.print_predictions:
         for q, a in zip(snake_case__ ,  snake_case__			):
            logger.info('Q: {} - A: {}'.format(snake_case__ ,  snake_case__			)			)

      return answers
def 	UpperCamelCase			(     )			->  str:
   UpperCamelCase					:						Any					=			argparse.ArgumentParser()
   parser.add_argument(
       '--model_type' ,  choices=['rag_sequence', 'rag_token', 'bart'] ,  type=snake_case__ ,  help=(
           'RAG model type: rag_sequence, rag_token or bart, if none specified, the type is inferred from the'
           ' model_name_or_path'
       ) ,  )
   parser.add_argument(
       '--index_name' ,  default=snake_case__ ,  choices=['exact', 'compressed', 'legacy'] ,  type=snake_case__ ,  help='RAG model retriever type' ,  )
   parser.add_argument(
       '--index_path' ,  default=snake_case__ ,  type=snake_case__ ,  help='Path to the retrieval index' ,  )
   parser.add_argument('--n_docs' ,  default=5 ,  type=snake_case__ ,  help='Number of retrieved docs'			)
   parser.add_argument(
       '--model_name_or_path' ,  default=snake_case__ ,  type=snake_case__ ,  required=snake_case__ ,  help='Path to pretrained checkpoints or model identifier from huggingface.co/models' ,  )
   parser.add_argument(
       '--eval_mode' ,  choices=['e2e', 'retrieval'] ,  default='e2e' ,  type=snake_case__ ,  help=(
           'Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates'
           ' precision@k.'
       ) ,  )
   parser.add_argument('--k' ,  default=1 ,  type=snake_case__ ,  help='k for the precision@k calculation'			)
   parser.add_argument(
       '--evaluation_set' ,  default=snake_case__ ,  type=snake_case__ ,  required=snake_case__ ,  help='Path to a file containing evaluation samples' ,  )
   parser.add_argument(
       '--gold_data_path' ,  default=snake_case__ ,  type=snake_case__ ,  required=snake_case__ ,  help='Path to a tab-separated file with gold samples' ,  )
   parser.add_argument(
       '--gold_data_mode' ,  default='qa' ,  type=snake_case__ ,  choices=['qa', 'ans'] ,  help=(
           'Format of the gold data file'
           'qa - a single line in the following format: question [tab] answer_list'
           'ans - a single line of the gold file contains the expected answer string'
       ) ,  )
   parser.add_argument(
       '--predictions_path' ,  type=snake_case__ ,  default='predictions.txt' ,  help='Name of the predictions file, to be stored in the checkpoints directory' ,  )
   parser.add_argument(
       '--eval_all_checkpoints' ,  action='store_true' ,  help='Evaluate all checkpoints starting with the same prefix as model_name ending and ending with step number' ,  )
   parser.add_argument(
       '--eval_batch_size' ,  default=8 ,  type=snake_case__ ,  help='Batch size per GPU/CPU for evaluation.' ,  )
   parser.add_argument(
       '--recalculate' ,  help='Recalculate predictions even if the prediction file exists' ,  action='store_true' ,  )
   parser.add_argument(
       '--num_beams' ,  default=4 ,  type=snake_case__ ,  help='Number of beams to be used when generating answers' ,  )
   parser.add_argument('--min_length' ,  default=1 ,  type=snake_case__ ,  help='Min length of the generated answers'			)
   parser.add_argument('--max_length' ,  default=50 ,  type=snake_case__ ,  help='Max length of the generated answers'			)

   parser.add_argument(
       '--print_predictions' ,  action='store_true' ,  help='If True, prints predictions while evaluating.' ,  )
   parser.add_argument(
       '--print_docs' ,  action='store_true' ,  help='If True, prints docs retried while generating.' ,  )
   UpperCamelCase					:						Optional[Any]					=			parser.parse_args()
   UpperCamelCase					:						Optional[int]					=			torch.device('cuda' if torch.cuda.is_available() else 'cpu'			)
   return args
def 	UpperCamelCase			(     snake_case__ :					List[str]			)			->  Dict:
   UpperCamelCase					:						Union[str, Any]					=			{}
   if args.model_type is None:
      UpperCamelCase					:						Dict					=			infer_model_type(args.model_name_or_path			)
      assert args.model_type is not None
   if args.model_type.startswith('rag'			):
      UpperCamelCase					:						int					=			RagTokenForGeneration if args.model_type == 'rag_token' else RagSequenceForGeneration
      UpperCamelCase					:						Union[str, Any]					=			args.n_docs
      if args.index_name is not None:
         UpperCamelCase					:						int					=			args.index_name
      if args.index_path is not None:
         UpperCamelCase					:						Any					=			args.index_path
   else:
      UpperCamelCase					:						Tuple					=			BartForConditionalGeneration

   UpperCamelCase					:						int					=			(
       [f.path for f in os.scandir(args.model_name_or_path			) if f.is_dir()]
       if args.eval_all_checkpoints
       else [args.model_name_or_path]
   )

   logger.info('Evaluate the following checkpoints: %s' ,  snake_case__			)

   UpperCamelCase					:						Optional[int]					=			get_scores if args.eval_mode == 'e2e' else get_precision_at_k
   UpperCamelCase					:						int					=			evaluate_batch_eae if args.eval_mode == 'e2e' else evaluate_batch_retrieval

   for checkpoint in checkpoints:
      if os.path.exists(args.predictions_path			) and (not args.recalculate):
         logger.info('Calculating metrics based on an existing predictions file: {}'.format(args.predictions_path			)			)
         score_fn(snake_case__ ,  args.predictions_path ,  args.gold_data_path			)
         continue

      logger.info('***** Running evaluation for {} *****'.format(snake_case__			)			)
      logger.info('  Batch size = %d' ,  args.eval_batch_size			)
      logger.info('  Predictions will be stored under {}'.format(args.predictions_path			)			)

      if args.model_type.startswith('rag'			):
         UpperCamelCase					:						Optional[Any]					=			RagRetriever.from_pretrained(snake_case__ ,  **snake_case__			)
         UpperCamelCase					:						Optional[int]					=			model_class.from_pretrained(snake_case__ ,  retriever=snake_case__ ,  **snake_case__			)
         model.retriever.init_retrieval()
      else:
         UpperCamelCase					:						Union[str, Any]					=			model_class.from_pretrained(snake_case__ ,  **snake_case__			)
      model.to(args.device			)

      with open(args.evaluation_set ,  'r'			) as eval_file, open(args.predictions_path ,  'w'			) as preds_file:
         UpperCamelCase					:						Optional[Any]					=			[]
         for line in tqdm(snake_case__			):
            questions.append(line.strip()			)
            if len(snake_case__			) == args.eval_batch_size:
               UpperCamelCase					:						Union[str, Any]					=			evaluate_batch_fn(snake_case__ ,  snake_case__ ,  snake_case__			)
               preds_file.write('\n'.join(snake_case__			) + '\n'			)
               preds_file.flush()
               UpperCamelCase					:						List[str]					=			[]
         if len(snake_case__			) > 0:
            UpperCamelCase					:						Tuple					=			evaluate_batch_fn(snake_case__ ,  snake_case__ ,  snake_case__			)
            preds_file.write('\n'.join(snake_case__			)			)
            preds_file.flush()

         score_fn(snake_case__ ,  args.predictions_path ,  args.gold_data_path			)


if __name__ == "__main__":
 __UpperCAmelCase      = get_args()
 main(args)








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

from ...utils import logging


__UpperCAmelCase      = logging.get_logger(__name__)
def 	UpperCamelCase			(     snake_case__ :					List[str] ,  snake_case__ :					str			)			->  Dict:
   UpperCamelCase					:						int					=			nn.functional.normalize(snake_case__			)
   UpperCamelCase					:						Union[str, Any]					=			nn.functional.normalize(snake_case__			)
   return torch.mm(snake_case__ ,  normalized_text_embeds.t()			)



class        lowerCAmelCase_	(						a__							):
       UpperCAmelCase__       :      int       =						CLIPConfig

       UpperCAmelCase__       :      Union[str, Any]       =						["CLIPEncoderLayer"]
       def __init__(    self,    SCREAMING_SNAKE_CASE_ )  ->	List[str]:
          super().__init__(SCREAMING_SNAKE_CASE_ )

          UpperCamelCase					:						int					=			CLIPVisionModel(config.vision_config )
          UpperCamelCase					:						int					=			nn.Linear(config.vision_config.hidden_size,    config.projection_dim,    bias=SCREAMING_SNAKE_CASE_ )

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

          UpperCamelCase					:						Dict					=			nn.Parameter(torch.ones(17 ),    requires_grad=SCREAMING_SNAKE_CASE_ )
          UpperCamelCase					:						Optional[Any]					=			nn.Parameter(torch.ones(3 ),    requires_grad=SCREAMING_SNAKE_CASE_ )
       @torch.no_grad()
       def       snake_case_ (    self,    SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_ )  ->	Union[str, Any]:
          UpperCamelCase					:						Optional[int]					=			self.vision_model(SCREAMING_SNAKE_CASE_ )[1]  # pooled_output
          UpperCamelCase					:						int					=			self.visual_projection(SCREAMING_SNAKE_CASE_ )

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

          UpperCamelCase					:						str					=			[]
          UpperCamelCase					:						int					=			image_embeds.shape[0]
          for i in range(SCREAMING_SNAKE_CASE_ ):
             UpperCamelCase					:						Optional[int]					=			{'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
             UpperCamelCase					:						Optional[Any]					=			0.0

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

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

             result.append(SCREAMING_SNAKE_CASE_ )

          UpperCamelCase					:						int					=			[len(res['bad_concepts'] ) > 0 for res in result]

          for idx, has_nsfw_concept in enumerate(SCREAMING_SNAKE_CASE_ ):
             if has_nsfw_concept:
                if torch.is_tensor(SCREAMING_SNAKE_CASE_ ) or torch.is_tensor(images[0] ):
                   UpperCamelCase					:						List[str]					=			torch.zeros_like(images[idx] )  # black image
                else:
                   UpperCamelCase					:						int					=			np.zeros(images[idx].shape )  # black image

          if any(SCREAMING_SNAKE_CASE_ ):
             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,    SCREAMING_SNAKE_CASE_,    SCREAMING_SNAKE_CASE_ )  ->	Optional[int]:
          UpperCamelCase					:						Union[str, Any]					=			self.vision_model(SCREAMING_SNAKE_CASE_ )[1]  # pooled_output
          UpperCamelCase					:						str					=			self.visual_projection(SCREAMING_SNAKE_CASE_ )

          UpperCamelCase					:						str					=			cosine_distance(SCREAMING_SNAKE_CASE_,    self.special_care_embeds )
          UpperCamelCase					:						Any					=			cosine_distance(SCREAMING_SNAKE_CASE_,    self.concept_embeds )

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

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

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

          UpperCamelCase					:						Any					=			0.0  # black image

          return images, has_nsfw_concepts



