
'''simple docstring'''






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_       :   Any   =       logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)

transformers_logging.set_verbosity_info()







def 		A_       (	_lowerCAmelCase   :    Any							):



      """simple docstring"""




      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 		A_       (	_lowerCAmelCase   :    int				,	_lowerCAmelCase   :    Tuple				,	_lowerCAmelCase   :    Tuple							):



      """simple docstring"""




      return max(metric_fn(_lowerCAmelCase				,	_lowerCAmelCase							) for gt in ground_truths							)







def 		A_       (	_lowerCAmelCase   :    Optional[int]				,	_lowerCAmelCase   :    Optional[Any]				,	_lowerCAmelCase   :    Dict							):



      """simple docstring"""




      _lowerCamelCase				:   Any								=   [line.strip() for line in open(_lowerCAmelCase				,	"r"							).readlines()]
      _lowerCamelCase				:   Union[str, Any]								=   []

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

      _lowerCamelCase				:   Union[str, Any]								=   0
      for prediction, ground_truths in zip(_lowerCAmelCase				,	_lowerCAmelCase							):
            total += 1
            em += metric_max_over_ground_truths(_lowerCAmelCase				,	_lowerCAmelCase				,	_lowerCAmelCase							)
            fa += metric_max_over_ground_truths(_lowerCAmelCase				,	_lowerCAmelCase				,	_lowerCAmelCase							)

      _lowerCamelCase				:   Dict								=   1_0_0.0 * em / total
      _lowerCamelCase				:   Dict								=   1_0_0.0 * fa / total

      logger.info(F'F1: {fa:.2f}'							)
      logger.info(F'EM: {em:.2f}'							)







def 		A_       (	_lowerCAmelCase   :    List[Any]				,	_lowerCAmelCase   :    Tuple				,	_lowerCAmelCase   :    str							):



      """simple docstring"""




      _lowerCamelCase				:   int								=   args.k
      _lowerCamelCase				:   Optional[Any]								=   [line.strip() for line in open(_lowerCAmelCase				,	"r"							).readlines()]
      _lowerCamelCase				:   Union[str, Any]								=   [line.strip() for line in open(_lowerCAmelCase				,	"r"							).readlines()]

      _lowerCamelCase				:   Optional[Any]								=   0
      for hypo, reference in zip(_lowerCAmelCase				,	_lowerCAmelCase							):
            _lowerCamelCase				:   Union[str, Any]								=   set(hypo.split("\t"							)[:k]							)
            _lowerCamelCase				:   List[Any]								=   set(reference.split("\t"							)							)
            total += 1
            em += len(hypo_provenance & ref_provenance							) / k

      _lowerCamelCase				:   List[Any]								=   1_0_0.0 * em / total
      logger.info(F'Precision@{k}: {em: .2f}'							)







def 		A_       (	_lowerCAmelCase   :    Tuple				,	_lowerCAmelCase   :    Any				,	_lowerCAmelCase   :    Any							):



      """simple docstring"""




      def strip_title(_lowerCAmelCase   :    List[Any]							):
            if title.startswith("\""							):
                  _lowerCamelCase				:   Dict								=   title[1:]
            if title.endswith("\""							):
                  _lowerCamelCase				:   List[str]								=   title[:-1]
            return title

      _lowerCamelCase				:   str								=   rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
          _lowerCAmelCase				,	return_tensors="pt"				,	padding=_lowerCAmelCase				,	truncation=_lowerCAmelCase				,	)["input_ids"].to(args.device							)

      _lowerCamelCase				:   Any								=   rag_model.rag.question_encoder(_lowerCAmelCase							)
      _lowerCamelCase				:   str								=   question_enc_outputs[0]

      _lowerCamelCase				:   List[str]								=   rag_model.retriever(
          _lowerCAmelCase				,	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"				,	)
      _lowerCamelCase				:   Tuple								=   rag_model.retriever.index.get_doc_dicts(result.doc_ids							)
      _lowerCamelCase				:   str								=   []
      for docs in all_docs:
            _lowerCamelCase				:   Union[str, Any]								=   [strip_title(_lowerCAmelCase							) for title in docs["title"]]
            provenance_strings.append("\t".join(_lowerCAmelCase							)							)
      return provenance_strings







def 		A_       (	_lowerCAmelCase   :    Union[str, Any]				,	_lowerCAmelCase   :    List[Any]				,	_lowerCAmelCase   :    Optional[int]							):



      """simple docstring"""




      with torch.no_grad():
            _lowerCamelCase				:   Any								=   rag_model.retriever.question_encoder_tokenizer.batch_encode_plus(
                _lowerCAmelCase				,	return_tensors="pt"				,	padding=_lowerCAmelCase				,	truncation=_lowerCAmelCase							)

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

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

            return answers







def 		A_       (	):



      """simple docstring"""




      _lowerCamelCase				:   Any								=   argparse.ArgumentParser()
      parser.add_argument(
          "--model_type"				,	choices=["rag_sequence", "rag_token", "bart"]				,	type=_lowerCAmelCase				,	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=_lowerCAmelCase				,	choices=["exact", "compressed", "legacy"]				,	type=_lowerCAmelCase				,	help="RAG model retriever type"				,	)
      parser.add_argument(
          "--index_path"				,	default=_lowerCAmelCase				,	type=_lowerCAmelCase				,	help="Path to the retrieval index"				,	)
      parser.add_argument("--n_docs"				,	default=5				,	type=_lowerCAmelCase				,	help="Number of retrieved docs"							)
      parser.add_argument(
          "--model_name_or_path"				,	default=_lowerCAmelCase				,	type=_lowerCAmelCase				,	required=_lowerCAmelCase				,	help="Path to pretrained checkpoints or model identifier from huggingface.co/models"				,	)
      parser.add_argument(
          "--eval_mode"				,	choices=["e2e", "retrieval"]				,	default="e2e"				,	type=_lowerCAmelCase				,	help=(
              "Evaluation mode, e2e calculates exact match and F1 of the downstream task, retrieval calculates"
              " precision@k."
          )				,	)
      parser.add_argument("--k"				,	default=1				,	type=_lowerCAmelCase				,	help="k for the precision@k calculation"							)
      parser.add_argument(
          "--evaluation_set"				,	default=_lowerCAmelCase				,	type=_lowerCAmelCase				,	required=_lowerCAmelCase				,	help="Path to a file containing evaluation samples"				,	)
      parser.add_argument(
          "--gold_data_path"				,	default=_lowerCAmelCase				,	type=_lowerCAmelCase				,	required=_lowerCAmelCase				,	help="Path to a tab-separated file with gold samples"				,	)
      parser.add_argument(
          "--gold_data_mode"				,	default="qa"				,	type=_lowerCAmelCase				,	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=_lowerCAmelCase				,	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=_lowerCAmelCase				,	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=_lowerCAmelCase				,	help="Number of beams to be used when generating answers"				,	)
      parser.add_argument("--min_length"				,	default=1				,	type=_lowerCAmelCase				,	help="Min length of the generated answers"							)
      parser.add_argument("--max_length"				,	default=50				,	type=_lowerCAmelCase				,	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."				,	)
      _lowerCamelCase				:   Union[str, Any]								=   parser.parse_args()
      _lowerCamelCase				:   Tuple								=   torch.device("cuda" if torch.cuda.is_available() else "cpu"							)
      return args







def 		A_       (	_lowerCAmelCase   :    Optional[Any]							):



      """simple docstring"""




      _lowerCamelCase				:   Optional[Any]								=   {}
      if args.model_type is None:
            _lowerCamelCase				:   List[Any]								=   infer_model_type(args.model_name_or_path							)
            assert args.model_type is not None
      if args.model_type.startswith("rag"							):
            _lowerCamelCase				:   Any								=   RagTokenForGeneration if args.model_type == "rag_token" else RagSequenceForGeneration
            _lowerCamelCase				:   Dict								=   args.n_docs
            if args.index_name is not None:
                  _lowerCamelCase				:   List[Any]								=   args.index_name
            if args.index_path is not None:
                  _lowerCamelCase				:   Union[str, Any]								=   args.index_path
      else:
            _lowerCamelCase				:   Optional[Any]								=   BartForConditionalGeneration

      _lowerCamelCase				:   Tuple								=   (
          [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"				,	_lowerCAmelCase							)

      _lowerCamelCase				:   str								=   get_scores if args.eval_mode == "e2e" else get_precision_at_k
      _lowerCamelCase				:   str								=   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(_lowerCAmelCase				,	args.predictions_path				,	args.gold_data_path							)
                  continue

            logger.info("***** Running evaluation for {} *****".format(_lowerCAmelCase							)							)
            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"							):
                  _lowerCamelCase				:   List[Any]								=   RagRetriever.from_pretrained(_lowerCAmelCase				,	**_lowerCAmelCase							)
                  _lowerCamelCase				:   Optional[Any]								=   model_class.from_pretrained(_lowerCAmelCase				,	retriever=_lowerCAmelCase				,	**_lowerCAmelCase							)
                  model.retriever.init_retrieval()
            else:
                  _lowerCamelCase				:   str								=   model_class.from_pretrained(_lowerCAmelCase				,	**_lowerCAmelCase							)
            model.to(args.device							)

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

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


if __name__ == "__main__":
 UpperCAmelCase_       :   Any   =       get_args()
 main(args)

'''simple docstring'''






import os
import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Dict, List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features


UpperCAmelCase_       :   Optional[Any]   =       logging.get_logger(__name__)

UpperCAmelCase_       :   Any   =       list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys())
UpperCAmelCase_       :   str   =       tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)

@dataclass
class  UpperCAmelCase__						:
    lowerCAmelCase_				    =		field(
        default=A						,	metadata={'help': 'Model type selected in the list: ' + ', '.join(A )} )
    lowerCAmelCase_				    =		field(
        default=A						,	metadata={'help': 'The input data dir. Should contain the .json files for the SQuAD task.'} )
    lowerCAmelCase_				    =		field(
        default=128						,	metadata={
            'help': (
                'The maximum total input sequence length after tokenization. Sequences longer '
                'than this will be truncated, sequences shorter will be padded.'
            )
        }						,	)
    lowerCAmelCase_				    =		field(
        default=128						,	metadata={'help': 'When splitting up a long document into chunks, how much stride to take between chunks.'}						,	)
    lowerCAmelCase_				    =		field(
        default=64						,	metadata={
            'help': (
                'The maximum number of tokens for the question. Questions longer than this will '
                'be truncated to this length.'
            )
        }						,	)
    lowerCAmelCase_				    =		field(
        default=30						,	metadata={
            'help': (
                'The maximum length of an answer that can be generated. This is needed because the start '
                'and end predictions are not conditioned on one another.'
            )
        }						,	)
    lowerCAmelCase_				    =		field(
        default=A						,	metadata={'help': 'Overwrite the cached training and evaluation sets'} )
    lowerCAmelCase_				    =		field(
        default=A						,	metadata={'help': 'If true, the SQuAD examples contain some that do not have an answer.'} )
    lowerCAmelCase_				    =		field(
        default=0.0						,	metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'} )
    lowerCAmelCase_				    =		field(
        default=20						,	metadata={'help': 'If null_score - best_non_null is greater than the threshold predict null.'} )
    lowerCAmelCase_				    =		field(
        default=0						,	metadata={
            'help': (
                'language id of input for language-specific xlm models (see'
                ' tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)'
            )
        }						,	)
    lowerCAmelCase_				    =		field(default=1						,	metadata={'help': 'multiple threads for converting example to features'} )


class  UpperCAmelCase__						(       A ):
    lowerCAmelCase_				    =		'train'
    lowerCAmelCase_				    =		'dev'


class  UpperCAmelCase__						(       A ):
    lowerCAmelCase_				    =		42
    lowerCAmelCase_				    =		42
    lowerCAmelCase_				    =		42
    lowerCAmelCase_				    =		42



    def __init__(	self      :       Optional[int],__A      :       SquadDataTrainingArguments,__A      :       PreTrainedTokenizer,__A      :       Optional[int] = None,__A      :       Union[str, Split] = Split.train,__A      :       Optional[bool] = False,__A      :       Optional[str] = None,__A      :       Optional[str] = "pt",):
          _lowerCamelCase				:   Tuple								=   args
          _lowerCamelCase				:   List[str]								=   is_language_sensitive
          _lowerCamelCase				:   Dict								=   SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor()
          if isinstance(__A,__A     ):
                try:
                      _lowerCamelCase				:   Union[str, Any]								=   Split[mode]
                except KeyError:
                      raise KeyError("mode is not a valid split name"     )
          _lowerCamelCase				:   str								=   mode
          # Load data features from cache or dataset file
          _lowerCamelCase				:   str								=   "v2" if args.version_2_with_negative else "v1"
          _lowerCamelCase				:   Optional[Any]								=   os.path.join(
              cache_dir if cache_dir is not None else args.data_dir,f'cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}',)

          # Make sure only the first process in distributed training processes the dataset,
          # and the others will use the cache.
          _lowerCamelCase				:   Tuple								=   cached_features_file + ".lock"
          with FileLock(__A     ):
                if os.path.exists(__A     ) and not args.overwrite_cache:
                      _lowerCamelCase				:   int								=   time.time()
                      _lowerCamelCase				:   int								=   torch.load(__A     )

                      # Legacy cache files have only features, while new cache files
                      # will have dataset and examples also.
                      _lowerCamelCase				:   Union[str, Any]								=   self.old_features["features"]
                      _lowerCamelCase				:   List[Any]								=   self.old_features.get("dataset",__A     )
                      _lowerCamelCase				:   List[Any]								=   self.old_features.get("examples",__A     )
                      logger.info(
                          f'Loading features from cached file {cached_features_file} [took %.3f s]',time.time() - start     )

                      if self.dataset is None or self.examples is None:
                            logger.warning(
                                f'Deleting cached file {cached_features_file} will allow dataset and examples to be cached in'
                                " future run"     )
                else:
                      if mode == Split.dev:
                            _lowerCamelCase				:   Dict								=   self.processor.get_dev_examples(args.data_dir     )
                      else:
                            _lowerCamelCase				:   Dict								=   self.processor.get_train_examples(args.data_dir     )

                      _lowerCamelCase						,		_lowerCamelCase				:   Dict								=   squad_convert_examples_to_features(
                          examples=self.examples,tokenizer=__A,max_seq_length=args.max_seq_length,doc_stride=args.doc_stride,max_query_length=args.max_query_length,is_training=mode == Split.train,threads=args.threads,return_dataset=__A,)

                      _lowerCamelCase				:   List[Any]								=   time.time()
                      torch.save(
                          {"features": self.features, "dataset": self.dataset, "examples": self.examples},__A,)
                      # ^ This seems to take a lot of time so I want to investigate why and how we can improve.
                      logger.info(
                          f'Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]'     )



    def __len__(	self      :       Optional[Any]     ):
          return len(self.features     )



    def __getitem__(	self      :       Tuple,__A      :       str     ):
          # Convert to Tensors and build dataset
          _lowerCamelCase				:   List[str]								=   self.features[i]

          _lowerCamelCase				:   List[str]								=   torch.tensor(feature.input_ids,dtype=torch.long     )
          _lowerCamelCase				:   Optional[int]								=   torch.tensor(feature.attention_mask,dtype=torch.long     )
          _lowerCamelCase				:   Union[str, Any]								=   torch.tensor(feature.token_type_ids,dtype=torch.long     )
          _lowerCamelCase				:   str								=   torch.tensor(feature.cls_index,dtype=torch.long     )
          _lowerCamelCase				:   str								=   torch.tensor(feature.p_mask,dtype=torch.float     )
          _lowerCamelCase				:   Tuple								=   torch.tensor(feature.is_impossible,dtype=torch.float     )

          _lowerCamelCase				:   Optional[Any]								=   {
              "input_ids": input_ids,
              "attention_mask": attention_mask,
              "token_type_ids": token_type_ids,
          }

          if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]:
                del inputs["token_type_ids"]

          if self.args.model_type in ["xlnet", "xlm"]:
                inputs.update({"cls_index": cls_index, "p_mask": p_mask}     )
                if self.args.version_2_with_negative:
                      inputs.update({"is_impossible": is_impossible}     )
                if self.is_language_sensitive:
                      inputs.update({"langs": (torch.ones(input_ids.shape,dtype=torch.intaa     ) * self.args.lang_id)}     )

          if self.mode == Split.train:
                _lowerCamelCase				:   List[str]								=   torch.tensor(feature.start_position,dtype=torch.long     )
                _lowerCamelCase				:   Any								=   torch.tensor(feature.end_position,dtype=torch.long     )
                inputs.update({"start_positions": start_positions, "end_positions": end_positions}     )

          return inputs