raft_eval.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # This software may be used and distributed according to the terms of the Llama 3 Community License Agreement.
  3. import logging
  4. import evaluate
  5. import argparse
  6. from config import load_config
  7. import json
  8. from langchain_openai import ChatOpenAI
  9. from langchain_community.embeddings import HuggingFaceEmbeddings
  10. from langchain_community.vectorstores import FAISS
  11. from langchain.text_splitter import RecursiveCharacterTextSplitter
  12. from langchain_community.vectorstores.utils import DistanceStrategy
  13. from datetime import datetime
  14. from langchain_community.document_loaders import DirectoryLoader
  15. import re
  16. import string
  17. import pandas as pd
  18. from langchain.retrievers.document_compressors import FlashrankRerank
  19. def generate_answers_model_only(model_name,question_list,api_url="http://localhost:8000/v1",key="EMPTY"):
  20. # Use langchain to load the documents from data directory
  21. # Load the RAFT model
  22. llm = ChatOpenAI(
  23. openai_api_key=key,
  24. openai_api_base=api_url,
  25. model_name=model_name,
  26. temperature=0.0,
  27. max_tokens=1000
  28. )
  29. all_tasks = [api_config['eval_prompt_template'].format(question=question) for question in question_list]
  30. generated_answers = llm.batch(all_tasks)
  31. generated_answers = [ item.content for item in generated_answers]
  32. if len(generated_answers) == 0:
  33. logging.error("No model answers generated. Please check the input context or model configuration in ",model_name)
  34. return []
  35. return clean_text_list(generated_answers)
  36. def format_docs_raft(docs):
  37. context = ""
  38. for doc in docs:
  39. context += "\n<DOCUMENT>" + str(doc.page_content) + "</DOCUMENT>\n"
  40. return context
  41. def build_retriever(api_config,embedding_model_name,retrieved_docs_num=5):
  42. # Use langchain to load the documents from data directory
  43. loader = DirectoryLoader(api_config['data_dir'])
  44. docs = loader.load()
  45. # Split the document into chunks with a specified chunk size
  46. text_splitter = RecursiveCharacterTextSplitter(chunk_size=api_config["chunk_size"],chunk_overlap=int(api_config["chunk_size"] / 10),separators= ["----------","\n\n", "\n", " ", ""],strip_whitespace=True)
  47. docs_processed = text_splitter.split_documents(docs)
  48. # Remove duplicates
  49. unique_texts = {}
  50. docs_processed_unique = []
  51. for doc in docs_processed:
  52. if doc.page_content not in unique_texts:
  53. unique_texts[doc.page_content] = True
  54. docs_processed_unique.append(doc)
  55. logging.info(f"Total number of docs_processed used by vectorstore: {len(docs_processed_unique)}")
  56. # Store the document into a vector store with a specific embedding model
  57. embedding_model = HuggingFaceEmbeddings(
  58. model_name=embedding_model_name,
  59. model_kwargs={"device": "cuda"},
  60. encode_kwargs={"normalize_embeddings": True}, # Set `True` for cosine similarity
  61. )
  62. vectorstore = FAISS.from_documents(docs_processed_unique, embedding_model, distance_strategy=DistanceStrategy.COSINE)
  63. retriever = vectorstore.as_retriever(
  64. search_kwargs={"k": retrieved_docs_num},
  65. )
  66. return retriever
  67. def generate_answers_with_RAG(model_name, question_list,api_config,retriever,api_url_overwrite=None):
  68. api_url = api_config['model_endpoint_url']
  69. if api_url_overwrite:
  70. api_url = api_url_overwrite
  71. key = api_config['api_key']
  72. rerank_topk = api_config["rerank_topk"]
  73. # Load the RAFT model
  74. llm = ChatOpenAI(
  75. openai_api_key=key,
  76. openai_api_base=api_url,
  77. model_name=model_name,
  78. temperature=0.0,
  79. max_tokens=1000
  80. )
  81. all_tasks = []
  82. for q in question_list:
  83. # retrive the top K documents
  84. retrieved_docs = retriever.invoke(q)
  85. if rerank_topk:
  86. ranker = FlashrankRerank(top_n=rerank_topk)
  87. documents = ranker.compress_documents(retrieved_docs,q)
  88. # format the documents into a string
  89. documents = format_docs_raft(retrieved_docs)
  90. # create a prompt
  91. text = api_config["RAG_prompt_template"].format(context=documents,question=q)
  92. all_tasks.append(text)
  93. generated_answers = llm.batch(all_tasks)
  94. generated_answers = [ item.content for item in generated_answers]
  95. if len(generated_answers) == 0:
  96. logging.error("No RAG answers generated. Please check the input context or model configuration in ",model_name)
  97. return []
  98. return clean_text_list(generated_answers)
  99. def compute_rouge_score(generated : list, reference: list):
  100. rouge_score = evaluate.load('rouge')
  101. return rouge_score.compute(
  102. predictions=generated,
  103. references=reference,
  104. use_stemmer=True,
  105. use_aggregator=True
  106. )
  107. def clean_text_list(text_list):
  108. result = []
  109. for text in text_list:
  110. # for raft model, the answer will started with <ANSWER>
  111. index = text.rfind("<ANSWER>")
  112. if index!= -1:
  113. text = text[index:]
  114. text = text.replace("</ANSWER>:","")
  115. text = text.replace("begin_quote","")
  116. text = text.replace("end_quote","")
  117. text = text.replace("##","")
  118. text = text.strip()
  119. result.append(text)
  120. return result
  121. def normalize_answer(s):
  122. def remove_articles(text):
  123. return re.sub(r'\b(a|an|the)\b', ' ', text)
  124. def white_space_fix(text):
  125. return ' '.join(text.split())
  126. def remove_punc(text):
  127. exclude = set(string.punctuation)
  128. return ''.join(ch for ch in text if ch not in exclude)
  129. def lower(text):
  130. return text.lower()
  131. return white_space_fix(remove_articles(remove_punc(lower(s))))
  132. def exact_match_score(prediction, ground_truth):
  133. """Computes EM score for a single prediction and ground truth answer."""
  134. num_match = 0
  135. assert len(prediction) == len(ground_truth), "Answer length does not match prediction length."
  136. assert(len(ground_truth) > 0)
  137. for idx, (pred,gold) in enumerate(zip(prediction, ground_truth)):
  138. if (normalize_answer(pred) == normalize_answer(gold)):
  139. num_match += 1
  140. return num_match/len(ground_truth)
  141. def compute_bert_score(generated : list, reference: list):
  142. bertscore = evaluate.load("bertscore")
  143. score = bertscore.compute(
  144. predictions=generated,
  145. references=reference,
  146. lang="en"
  147. )
  148. f1 = score["f1"]
  149. precision = score["precision"]
  150. recall = score["recall"]
  151. return sum(precision)/len(precision), sum(recall)/len(recall), sum(f1)/len(f1)
  152. def compute_judge_score(questions: list, generated : list, reference: list, api_config,api_url="http://localhost:8001/v1",key="EMPTY"):
  153. correct_num = 0
  154. model_name = "meta-llama/Meta-Llama-3-70B-Instruct"
  155. llm = ChatOpenAI(
  156. openai_api_key=key,
  157. openai_api_base=api_url,
  158. model_name=model_name,
  159. max_tokens=1000,
  160. temperature=0.0)
  161. all_tasks = []
  162. for question,prediction,gold in zip(questions, generated,reference):
  163. message = api_config['judge_prompt_template'].format(question=question,prediction=prediction,gold=gold)
  164. all_tasks.append(message)
  165. judge_responses = llm.batch(all_tasks)
  166. judge_responses = ["YES" in item.content for item in judge_responses]
  167. correct_num = sum(judge_responses)
  168. return correct_num/len(questions),judge_responses
  169. def score_single(api_config,generated,reference,questions, run_exact_match=True,run_rouge=True, run_bert=False, run_llm_as_judge=True):
  170. # set metric to default -1, means no metric is computed
  171. metric = {
  172. "Rouge_score": -1,
  173. "BERTScore_Precision": -1,
  174. "BERTScore_Recall": -1,
  175. "BERTScore_F1": -1,
  176. "LLM_judge_score": -1,
  177. "Exact_match": -1
  178. }
  179. if run_rouge:
  180. rouge_score = compute_rouge_score(generated,reference)
  181. metric["Rouge_score"] = rouge_score
  182. print("Rouge_score:",rouge_score)
  183. if run_bert:
  184. P, R, F1 = compute_bert_score(generated,reference)
  185. print(f"BERTScore Precision: {P:.4f}, Recall: {R:.4f}, F1: {F1:.4f}")
  186. metric["BERTScore_Precision"] = P
  187. metric["BERTScore_Recall"] = R
  188. metric["BERTScore_F1"] = F1
  189. if api_config["judge_endpoint_url"] and run_llm_as_judge:
  190. api_url = api_config["judge_endpoint_url"]
  191. LLM_judge_score,judge_responses = compute_judge_score(questions, generated, reference, api_config,api_url=api_url)
  192. metric["LLM_judge_score"] = LLM_judge_score
  193. metric["LLM_judge_responses"] = judge_responses
  194. print(f"LLM_judge_score: {LLM_judge_score}")
  195. if run_exact_match:
  196. exact_match = exact_match_score(generated,reference)
  197. print(f"Exact_match_percentage: {exact_match:.4f}")
  198. metric["Exact_match"] = exact_match
  199. return metric
  200. def main(api_config):
  201. # Since the eval set is small, we can run the eval without async functions
  202. try:
  203. api_url = api_config["model_endpoint_url"]
  204. logging.info("Starting to generate answer given the eval set.")
  205. questions,groud_truth = [],[]
  206. if api_config["eval_file"].endswith(".parquet"):
  207. eval_file = pd.read_parquet(api_config["eval_file"],filters=[('source', '=', 'pt_discuss_forum')])
  208. for index, item in eval_file.iterrows():
  209. questions.append(item["question"]+"\nDetails:\n"+item["context"])
  210. groud_truth.append(item["answer"])
  211. else:
  212. with open(api_config["eval_file"]) as fp:
  213. eval_file = json.load(fp)
  214. for index, item in enumerate(eval_file):
  215. questions.append(item["question"])
  216. groud_truth.append(item["answer"])
  217. generated_answers = {}
  218. # build retriver
  219. retriever = build_retriever(api_config,"sentence-transformers/multi-qa-mpnet-base-cos-v1",api_config["rag_topk"])
  220. # Generate answers for 8B models
  221. model_name = api_config["model_name"]
  222. generated_answers[model_name] = generate_answers_model_only(model_name,questions,api_url)
  223. generated_answers[model_name+"_RAG"] = generate_answers_with_RAG(model_name, questions,api_config,retriever)
  224. print("Finished generating answers for ", model_name)
  225. large_model_name = "meta-llama/Meta-Llama-3-70B-Instruct"
  226. large_api_url = api_config["judge_endpoint_url"]
  227. #generated_answers["70B_Base"] = generate_answers_model_only(large_model_name,questions,large_api_url)
  228. #generated_answers["70B_RAG"] = generate_answers_with_RAG(large_model_name, questions,api_config,retriever,large_api_url)
  229. print("Finished generating answers for ", large_model_name)
  230. logging.info(f"Successfully generated {len(generated_answers[model_name+'_RAG'])} answers for all models.")
  231. # for generate answer from each model, compute the score metric
  232. all_metrics = []
  233. output_file = api_config["output_log"]+str(datetime.now().strftime("%Y%m%d_%H%M%S"))
  234. for model_name,model_answer in generated_answers.items():
  235. if len(model_answer) != len(groud_truth):
  236. print(f"The length of {model_name} answer is not equal to the length of ground truth.")
  237. continue
  238. metric = score_single(api_config,model_answer,groud_truth,questions)
  239. print(f"The eval result for {model_name} is: {metric}")
  240. with open(output_file,"a") as fp:
  241. fp.write(f"Eval_result for {model_name} \n")
  242. fp.write(f"Rouge_score: {metric['Rouge_score']} \n")
  243. fp.write(f"BERTScore Precision: {metric['BERTScore_Precision']:.4f}, Recall: {metric['BERTScore_Recall']:.4f}, F1: {metric['BERTScore_F1']:.4f} \n")
  244. fp.write(f"Exact_match_percentage: {metric['Exact_match']} \n")
  245. judge_responses = ["None"] * len(questions)
  246. if api_config["judge_endpoint_url"]:
  247. fp.write(f"LLM_judge_score: {metric['LLM_judge_score']} \n")
  248. judge_responses = metric["LLM_judge_responses"]
  249. all_metrics.append((model_name,metric['LLM_judge_score'],metric["LLM_judge_responses"]))
  250. fp.write(f"QA details: \n")
  251. for item in zip(questions,model_answer,groud_truth,judge_responses):
  252. fp.write(f"question: {item[0]} \n")
  253. fp.write(f"generated_answers: {item[1]} \n")
  254. fp.write(f"groud_truth: {item[2]} \n")
  255. fp.write(f"LLM_judge_response: {item[3]} \n")
  256. fp.write("\n")
  257. fp.write("\n------------------------------------\n")
  258. # Now we want to take a closer look at the questions that are not answered the same by all the models.
  259. judge_zip = list(zip(*[item[-1] for item in all_metrics]))
  260. model_names = [item[0] for item in all_metrics]
  261. with open(output_file,"a") as fp:
  262. for item in all_metrics:
  263. fp.write(f"Model_Name: {item[0]}, LLM_SCORE: {item[1]} \n")
  264. for idx,item in enumerate(judge_zip):
  265. # if all the responses are "YES", then we skip this question
  266. if sum(item) == len(item):
  267. continue
  268. else:
  269. fp.write(f"Comparing interested question: {questions[idx]} \n")
  270. fp.write(f"groud_truth: {groud_truth[idx]} \n")
  271. for i in range(len(model_names)):
  272. fp.write(f"{item[i]} {model_names[i]}_answers: {generated_answers[model_names[i]][idx]} \n")
  273. fp.write("------------------------\n")
  274. fp.write(json.dumps(all_metrics))
  275. print("Finished evaluating the model.")
  276. logging.info(f"Eval successfully, the eval result is saved to {api_config['output_log']}.")
  277. # Saving the eval result to a log file
  278. except Exception as e:
  279. logging.error(f"An unexpected error occurred during the process: {e}",exc_info=True)
  280. def parse_arguments():
  281. # Define command line arguments for the script
  282. parser = argparse.ArgumentParser(
  283. description="Generate question/answer pairs from documentation."
  284. )
  285. parser.add_argument(
  286. "-m", "--model_name",
  287. default=None,
  288. help="Provide the model_name to use for evaluation. If not specified, the model_path in eval_config.yaml will be used."
  289. )
  290. parser.add_argument(
  291. "-c", "--config_path",
  292. default="raft_eval_config.yaml",
  293. help="Set the configuration file path that has system prompt along with language, evalset path."
  294. )
  295. parser.add_argument(
  296. "-d", "--data_dir",
  297. default=None,
  298. help="Provide the data folder path to build RAG for evaluation. If not specified, the data_dir in eval_config.yaml will be used."
  299. )
  300. parser.add_argument(
  301. "-u", "--model_endpoint_url",
  302. default="http://localhost:8000/v1",
  303. type=str,
  304. help="The raft model endpoint url for eval."
  305. )
  306. parser.add_argument(
  307. "-j", "--judge_endpoint_url",
  308. default=None,
  309. type=str,
  310. help="The large model endpoint url for judge as LLM."
  311. )
  312. parser.add_argument(
  313. "-o", "--output_log",
  314. default="./eval_result",
  315. help="save the eval result to a log file. Default is eval_result[timestamp].log"
  316. )
  317. parser.add_argument(
  318. "-k", "--api_key",
  319. default="EMPTY",
  320. type=str,
  321. help="LLM API key for generating question/answer pairs."
  322. )
  323. parser.add_argument(
  324. "-r", "--rag_topk",
  325. default=5,
  326. type=int,
  327. help="set the number of top k documents the RAG needs to retrive."
  328. )
  329. parser.add_argument(
  330. "--rerank_topk",
  331. default=0,
  332. type=int,
  333. help="set the number of top k documents the reranker needs to retrive."
  334. )
  335. parser.add_argument("--chunk_size", type=int, default=1000, help="The character size of each chunk used in RAG")
  336. return parser.parse_args()
  337. if __name__ == "__main__":
  338. logging.info("Initializing the process and loading configuration...")
  339. args = parse_arguments()
  340. api_config = load_config(args.config_path)
  341. api_config["model_endpoint_url"] = args.model_endpoint_url
  342. if args.data_dir:
  343. api_config["data_dir"] = args.data_dir
  344. if args.model_name:
  345. api_config["model_name"] = args.model_name
  346. api_config["judge_endpoint_url"] = args.judge_endpoint_url
  347. api_config["output_log"] = args.output_log
  348. api_config["api_key"] = args.api_key
  349. api_config["chunk_size"] = args.chunk_size
  350. api_config["rag_topk"] = args.rag_topk
  351. api_config["rerank_topk"] = args.rerank_topk
  352. if api_config["rag_topk"] < api_config["rerank_topk"]:
  353. logging.error("The rerank_topk should be smaller than rag_topk.")
  354. if api_config["judge_endpoint_url"]:
  355. logging.info(f"The judge model url is: '{args.judge_endpoint_url}'.")
  356. main(api_config)