raft_eval.py 15 KB

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