|
| 1 | +#!/usr/bin/env python |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +# Copyright (C) 2024 Intel Corporation |
| 4 | +# SPDX-License-Identifier: Apache-2.0 |
| 5 | + |
| 6 | + |
| 7 | +import argparse |
| 8 | +import json |
| 9 | +import os |
| 10 | + |
| 11 | +from evals.evaluation.rag_eval import Evaluator |
| 12 | +from evals.evaluation.rag_eval.template import CRUDTemplate |
| 13 | +from evals.metrics.ragas import RagasMetric |
| 14 | +from tqdm import tqdm |
| 15 | + |
| 16 | + |
| 17 | +class CRUD_Evaluator(Evaluator): |
| 18 | + def get_ground_truth_text(self, data: dict): |
| 19 | + if self.task == "summarization": |
| 20 | + ground_truth_text = data["summary"] |
| 21 | + elif self.task == "question_answering": |
| 22 | + ground_truth_text = data["answers"] |
| 23 | + elif self.task == "continuation": |
| 24 | + ground_truth_text = data["continuing"] |
| 25 | + elif self.task == "hallucinated_modified": |
| 26 | + ground_truth_text = data["hallucinatedMod"] |
| 27 | + else: |
| 28 | + raise NotImplementedError( |
| 29 | + f"Unknown task {self.task}, only support " |
| 30 | + "summarization, question_answering, continuation and hallucinated_modified." |
| 31 | + ) |
| 32 | + return ground_truth_text |
| 33 | + |
| 34 | + def get_query(self, data: dict): |
| 35 | + if self.task == "summarization": |
| 36 | + query = data["text"] |
| 37 | + elif self.task == "question_answering": |
| 38 | + query = data["questions"] |
| 39 | + elif self.task == "continuation": |
| 40 | + query = data["beginning"] |
| 41 | + elif self.task == "hallucinated_modified": |
| 42 | + query = data["newsBeginning"] |
| 43 | + else: |
| 44 | + raise NotImplementedError( |
| 45 | + f"Unknown task {self.task}, only support " |
| 46 | + "summarization, question_answering, continuation and hallucinated_modified." |
| 47 | + ) |
| 48 | + return query |
| 49 | + |
| 50 | + def get_document(self, data: dict): |
| 51 | + if self.task == "summarization": |
| 52 | + document = data["text"] |
| 53 | + elif self.task == "question_answering": |
| 54 | + document = data["news1"] |
| 55 | + elif self.task == "continuation": |
| 56 | + document = data["beginning"] |
| 57 | + elif self.task == "hallucinated_modified": |
| 58 | + document = data["newsBeginning"] |
| 59 | + else: |
| 60 | + raise NotImplementedError( |
| 61 | + f"Unknown task {self.task}, only support " |
| 62 | + "summarization, question_answering, continuation and hallucinated_modified." |
| 63 | + ) |
| 64 | + return document |
| 65 | + |
| 66 | + def get_template(self): |
| 67 | + if self.task == "summarization": |
| 68 | + template = CRUDTemplate.get_summarization_template() |
| 69 | + elif self.task == "question_answering": |
| 70 | + template = CRUDTemplate.get_question_answering_template() |
| 71 | + elif self.task == "continuation": |
| 72 | + template = CRUDTemplate.get_continuation_template() |
| 73 | + else: |
| 74 | + raise NotImplementedError( |
| 75 | + f"Unknown task {self.task}, only support " |
| 76 | + "summarization, question_answering, continuation and hallucinated_modified." |
| 77 | + ) |
| 78 | + return template |
| 79 | + |
| 80 | + def post_process(self, result): |
| 81 | + return result.split("<response>")[-1].split("</response>")[0].strip() |
| 82 | + |
| 83 | + def get_ragas_metrics(self, results, arguments): |
| 84 | + from langchain_huggingface import HuggingFaceEndpointEmbeddings |
| 85 | + |
| 86 | + embeddings = HuggingFaceEndpointEmbeddings(model=arguments.tei_embedding_endpoint) |
| 87 | + |
| 88 | + metric = RagasMetric( |
| 89 | + threshold=0.5, |
| 90 | + model=arguments.llm_endpoint, |
| 91 | + embeddings=embeddings, |
| 92 | + metrics=["faithfulness", "answer_relevancy"], |
| 93 | + ) |
| 94 | + |
| 95 | + all_answer_relevancy = 0 |
| 96 | + all_faithfulness = 0 |
| 97 | + ragas_inputs = { |
| 98 | + "question": [], |
| 99 | + "answer": [], |
| 100 | + "ground_truth": [], |
| 101 | + "contexts": [], |
| 102 | + } |
| 103 | + |
| 104 | + valid_results = self.remove_invalid(results["results"]) |
| 105 | + |
| 106 | + for data in tqdm(valid_results): |
| 107 | + data = data["original_data"] |
| 108 | + |
| 109 | + query = self.get_query(data) |
| 110 | + generated_text = data["generated_text"] |
| 111 | + ground_truth = data["ground_truth_text"] |
| 112 | + retrieved_documents = data["retrieved_documents"] |
| 113 | + |
| 114 | + ragas_inputs["question"].append(query) |
| 115 | + ragas_inputs["answer"].append(generated_text) |
| 116 | + ragas_inputs["ground_truth"].append(ground_truth) |
| 117 | + ragas_inputs["contexts"].append(retrieved_documents[:3]) |
| 118 | + |
| 119 | + ragas_metrics = metric.measure(ragas_inputs) |
| 120 | + return ragas_metrics |
| 121 | + |
| 122 | + |
| 123 | +def args_parser(): |
| 124 | + parser = argparse.ArgumentParser() |
| 125 | + |
| 126 | + parser.add_argument( |
| 127 | + "--service_url", type=str, default="http://localhost:8888/v1/chatqna", help="Service URL address." |
| 128 | + ) |
| 129 | + parser.add_argument("--output_dir", type=str, default="./output", help="Directory to save evaluation results.") |
| 130 | + parser.add_argument( |
| 131 | + "--temperature", type=float, default=0.1, help="Controls the randomness of the model's text generation" |
| 132 | + ) |
| 133 | + parser.add_argument( |
| 134 | + "--max_new_tokens", type=int, default=1280, help="Maximum number of new tokens to be generated by the model" |
| 135 | + ) |
| 136 | + parser.add_argument( |
| 137 | + "--chunk_size", type=int, default=256, help="the maximum number of characters that a chunk can contain" |
| 138 | + ) |
| 139 | + parser.add_argument( |
| 140 | + "--chunk_overlap", |
| 141 | + type=int, |
| 142 | + default=100, |
| 143 | + help="the number of characters that should overlap between two adjacent chunks", |
| 144 | + ) |
| 145 | + parser.add_argument("--dataset_path", default="../data/split_merged.json", help="Path to the dataset") |
| 146 | + parser.add_argument("--docs_path", default="../data/80000_docs", help="Path to the retrieval documents") |
| 147 | + |
| 148 | + # Retriever related options |
| 149 | + parser.add_argument("--tasks", default=["question_answering"], nargs="+", help="Task to perform") |
| 150 | + parser.add_argument("--ingest_docs", action="store_true", help="Whether to ingest documents to vector database") |
| 151 | + parser.add_argument( |
| 152 | + "--database_endpoint", type=str, default="http://localhost:6007/v1/dataprep", help="Service URL address." |
| 153 | + ) |
| 154 | + parser.add_argument( |
| 155 | + "--embedding_endpoint", type=str, default="http://localhost:6000/v1/embeddings", help="Service URL address." |
| 156 | + ) |
| 157 | + parser.add_argument( |
| 158 | + "--retrieval_endpoint", type=str, default="http://localhost:7000/v1/retrieval", help="Service URL address." |
| 159 | + ) |
| 160 | + parser.add_argument( |
| 161 | + "--tei_embedding_endpoint", |
| 162 | + type=str, |
| 163 | + default="http://localhost:8090", |
| 164 | + help="Service URL address of tei embedding.", |
| 165 | + ) |
| 166 | + parser.add_argument("--ragas_metrics", action="store_true", help="Whether to compute ragas metrics.") |
| 167 | + parser.add_argument("--llm_endpoint", type=str, default=None, help="Service URL address.") |
| 168 | + parser.add_argument( |
| 169 | + "--show_progress_bar", action="store", default=True, type=bool, help="Whether to show a progress bar" |
| 170 | + ) |
| 171 | + parser.add_argument("--contain_original_data", action="store_true", help="Whether to contain original data") |
| 172 | + |
| 173 | + args = parser.parse_args() |
| 174 | + return args |
| 175 | + |
| 176 | + |
| 177 | +def main(): |
| 178 | + args = args_parser() |
| 179 | + if os.path.isfile(args.dataset_path): |
| 180 | + with open(args.dataset_path) as f: |
| 181 | + all_datasets = json.load(f) |
| 182 | + else: |
| 183 | + raise FileNotFoundError(f"Evaluation dataset file {args.dataset_path} not exist.") |
| 184 | + os.makedirs(args.output_dir, exist_ok=True) |
| 185 | + for task in args.tasks: |
| 186 | + if task == "question_answering": |
| 187 | + dataset = all_datasets["questanswer_1doc"] |
| 188 | + elif task == "summarization": |
| 189 | + dataset = all_datasets["event_summary"] |
| 190 | + else: |
| 191 | + raise NotImplementedError( |
| 192 | + f"Unknown task {task}, only support " |
| 193 | + "summarization, question_answering, continuation and hallucinated_modified." |
| 194 | + ) |
| 195 | + output_save_path = os.path.join(args.output_dir, f"{task}.json") |
| 196 | + evaluator = CRUD_Evaluator(dataset=dataset, output_path=output_save_path, task=task) |
| 197 | + if args.ingest_docs: |
| 198 | + CRUD_Evaluator.ingest_docs(args.docs_path, args.database_endpoint, args.chunk_size, args.chunk_overlap) |
| 199 | + results = evaluator.evaluate( |
| 200 | + args, show_progress_bar=args.show_progress_bar, contain_original_data=args.contain_original_data |
| 201 | + ) |
| 202 | + print(results["overall"]) |
| 203 | + if args.ragas_metrics: |
| 204 | + ragas_metrics = evaluator.get_ragas_metrics(results, args) |
| 205 | + print(ragas_metrics) |
| 206 | + print(f"Evaluation results of task {task} saved to {output_save_path}.") |
| 207 | + |
| 208 | + |
| 209 | +if __name__ == "__main__": |
| 210 | + main() |
0 commit comments