raft_utils.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
  3. import os
  4. from transformers import AutoTokenizer
  5. import logging
  6. import json
  7. from langchain_community.embeddings import HuggingFaceEmbeddings
  8. from langchain_experimental.text_splitter import SemanticChunker
  9. from math import ceil
  10. import datasets
  11. from datasets import Dataset, load_dataset
  12. import random
  13. from langchain_community.document_loaders import SitemapLoader,DirectoryLoader
  14. from bs4 import BeautifulSoup
  15. from langchain_openai import ChatOpenAI
  16. from langchain_core.messages import HumanMessage, SystemMessage
  17. from langchain_community.llms import VLLMOpenAI
  18. from langchain_core.prompts import ChatPromptTemplate
  19. # Initialize logging
  20. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  21. def strip_str(s: str) -> str:
  22. """
  23. Helper function for helping format strings returned by GPT-4.
  24. """
  25. l, r = 0, len(s)-1
  26. beg_found = False
  27. for i in range(len(s)):
  28. if s[i].isalpha():
  29. if not beg_found:
  30. l = i
  31. beg_found = True
  32. else:
  33. r = i
  34. r += 2
  35. return s[l:min(r, len(s))]
  36. def clean_documents(raw_text):
  37. unwanted= ["Technology",
  38. "Getting Started",
  39. "Trust & Safety",
  40. "Community",
  41. "Resources",
  42. "Skip to main content",
  43. "How-to guides"]
  44. all_lines = []
  45. for line in raw_text.split("\n"):
  46. line = line.strip()
  47. if line in unwanted or len(line.split()) == 0:
  48. continue
  49. else:
  50. all_lines.append(line)
  51. result = " ".join(all_lines)
  52. return result
  53. def clean_text(content: BeautifulSoup) -> str:
  54. # Find all 'nav' and 'header' elements in the BeautifulSoup object
  55. nav_elements = content.find_all("nav")
  56. header_elements = content.find_all("header")
  57. mydivs = content.find_all("div", {"role": "list"})
  58. # Remove each 'nav' and 'header' element from the BeautifulSoup object
  59. for element in nav_elements + header_elements+mydivs:
  60. element.decompose()
  61. raw_text = content.get_text("\n")
  62. return clean_documents(raw_text)
  63. # Read
  64. def read_file_content(xml_path: str, data_folder: str) -> str:
  65. if xml_path and data_folder:
  66. logging.info(f"Error: both xml_path and data_folder are provided, will only read from xml for now")
  67. if not xml_path and not data_folder:
  68. logging.info(f"Error: both xml_path and data_folder are not provided")
  69. return ""
  70. if xml_path:
  71. if not os.path.exists(xml_path):
  72. logging.info(f"Error: {xml_path} does not exist")
  73. return ""
  74. # Use langchain to load the documents from webpage links in the xml file
  75. sitemap_loader = SitemapLoader(web_path=xml_path,is_local=True,parsing_function=clean_text)
  76. sitemap_loader.requests_kwargs = {"verify": False}
  77. docs = sitemap_loader.load()
  78. return "\n".join([doc.page_content for doc in docs])
  79. elif len(data_folder) != 0:
  80. if not os.path.exists(data_folder):
  81. logging.info(f"Error: {data_folder} does not exist")
  82. return ""
  83. # Use langchain to load the documents from data folder
  84. loader = DirectoryLoader(data_folder)
  85. docs = loader.load()
  86. text = "\n".join([clean_documents(doc.page_content) for doc in docs])
  87. return text
  88. def get_chunks(
  89. text: str,
  90. chunk_size: int = 512,
  91. embedding_model: str = None
  92. ) -> list[str]:
  93. """
  94. Takes in a `file_path` and `doctype`, retrieves the document, breaks it down into chunks of size
  95. `chunk_size`, and returns the chunks.
  96. """
  97. chunks = []
  98. if len(text) == 0:
  99. raise TypeError("Can not get chunks from empty text")
  100. else:
  101. num_chunks = ceil(len(text) / chunk_size)
  102. logging.info(f"Splitting text into {num_chunks} chunks")
  103. text_splitter = SemanticChunker(embedding_model, number_of_chunks=num_chunks)
  104. chunks = text_splitter.create_documents([text])
  105. chunks = [chunk.page_content for chunk in chunks]
  106. return chunks
  107. # read all the files in the data folder, then split them into chunks
  108. # generate questions for each chunk and return zip of chunk and related questions list
  109. def generate_questions(api_config):
  110. # get documents from the data folder or xml file
  111. api_url = api_config["endpoint_url"]
  112. key = api_config["api_key"]
  113. document_text = read_file_content(api_config["xml_path"],api_config["data_dir"])
  114. if len(document_text) == 0:
  115. logging.info(f"Error reading files, document_text is {len(document_text)}")
  116. embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2",model_kwargs={'device': 'cuda'})
  117. document_batches = get_chunks(document_text,api_config["chunk_size"],embedding_model)
  118. batches_count = len(document_batches)
  119. total_questions = api_config["questions_per_chunk"] * batches_count
  120. # use OpenAI API protocol to hanlde the chat request, including local VLLM openai compatible server
  121. llm = VLLMOpenAI(
  122. openai_api_key=key,
  123. openai_api_base=api_url,
  124. model_name=api_config["model"],
  125. temperature=0.0,
  126. max_tokens=250
  127. )
  128. prompt = api_config['question_prompt_template'].format(num_questions=str(api_config['questions_per_chunk']))
  129. system_prompt = SystemMessage(content=prompt)
  130. generated_answers = []
  131. all_tasks = [[system_prompt, HumanMessage(content=batch)] for batch in document_batches]
  132. generated_answers = llm.batch(all_tasks)
  133. if len(generated_answers) == 0:
  134. logging.error("No model answers generated. Please check the input context or model configuration in ",model_name)
  135. return []
  136. final_result = []
  137. for result in generated_answers:
  138. queries = result.split('\n')
  139. queries = [strip_str(q) for q in queries]
  140. queries = [q for q in queries if any(c.isalpha() for c in q)]
  141. if len(queries) > int(api_config['questions_per_chunk']):
  142. # As the model may have unrelated question at the begining of the result
  143. # if queries is more than questions_per_chunk, then we need to truncate it and only keep last questions_per_chunk lines
  144. queries = queries[-int(api_config['questions_per_chunk']):]
  145. final_result.append(queries)
  146. return list(zip(document_batches,final_result))
  147. # Generate COT answer for each question given the chunk context
  148. def generate_COT(chunk_questions_zip,api_config) -> dict:
  149. all_tasks = []
  150. chunk_questions = []
  151. for document_content,questions in chunk_questions_zip:
  152. for question in questions:
  153. prompt = api_config['COT_prompt_template'].format(question=question,context=str(document_content))
  154. all_tasks.append(prompt)
  155. chunk_questions.append((document_content,question))
  156. # use OpenAI API protocol to hanlde the chat request, including local VLLM openai compatible server
  157. llm = VLLMOpenAI(
  158. openai_api_key=api_config["api_key"],
  159. openai_api_base=api_config["endpoint_url"],
  160. model_name=api_config["model"],
  161. temperature=0.0,
  162. max_tokens=350
  163. )
  164. generated_answers = llm.batch(all_tasks)
  165. COT_results = []
  166. # return a list of (chunk, question, generated_answer)
  167. for (chunk, question),generated_answer in zip(chunk_questions,generated_answers):
  168. COT_results.append((chunk,question,generated_answer))
  169. return COT_results
  170. def add_chunk_to_dataset(
  171. chunk_questions_zip: list,
  172. api_config: dict,
  173. ds,
  174. num_distract: int = 3,
  175. p: float = 0.8,
  176. ) -> None:
  177. """
  178. Given a chunk and related questions lists, create {Q, A, D} triplets and add them to the dataset.
  179. """
  180. COT_tasks = []
  181. chunks = [chunk for chunk, _ in chunk_questions_zip]
  182. COT_results = generate_COT(chunk_questions_zip,api_config)
  183. for chunk, q , cot in COT_results:
  184. # The COT answer will be used as the label in the fine-tuning stage
  185. datapt = {
  186. "id": None,
  187. "type": "general",
  188. "question": q,
  189. "context": None,
  190. "oracle_context": None,
  191. "cot_answer": cot
  192. }
  193. i = chunks.index(chunk)
  194. datapt["id"] = f"seed_task_{0 if not ds else ds.num_rows}"
  195. # add num_distract distractor docs
  196. docs = [chunk]
  197. indices = list(range(0, len(chunks)))
  198. indices.remove(i)
  199. for j in random.sample(indices, num_distract):
  200. docs.append(chunks[j])
  201. # decides whether to add oracle document
  202. oracle = random.uniform(0, 1) < p
  203. if not oracle:
  204. docs[0] = chunks[random.sample(indices, 1)[0]]
  205. random.shuffle(docs)
  206. d = {
  207. "title": [],
  208. "sentences": []
  209. }
  210. d["title"].append(["placeholder_title"]*(num_distract+1))
  211. d["sentences"].append(docs)
  212. datapt["context"] = d
  213. datapt["oracle_context"] = chunk
  214. # construct model instruction
  215. context = ""
  216. for doc in docs:
  217. context += "<DOCUMENT>" + str(doc) + "</DOCUMENT>\n"
  218. context += q
  219. # This instruction will be used in the fine-tuning stage
  220. datapt["instruction"] = context
  221. # add to dataset
  222. if not ds:
  223. # init ds
  224. datapt["id"] = [datapt["id"]]
  225. datapt["type"] = [datapt["type"]]
  226. datapt["question"] = [datapt["question"]]
  227. datapt["context"] = [datapt["context"]]
  228. datapt["oracle_context"] = [datapt["oracle_context"]]
  229. datapt["cot_answer"] = [datapt["cot_answer"]]
  230. datapt["instruction"] = [datapt["instruction"]]
  231. ds = Dataset.from_dict(datapt)
  232. else:
  233. ds = ds.add_item(datapt)
  234. return ds