raft.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. from concurrent.futures import ThreadPoolExecutor, as_completed
  2. import time
  3. from mdc import MDC
  4. from tqdm import tqdm
  5. from logconf import log_setup
  6. import logging
  7. from typing import Literal, Any, get_args
  8. import argparse
  9. from openai import OpenAI, BadRequestError
  10. import datasets
  11. from datasets import Dataset, concatenate_datasets
  12. import pyarrow as pa
  13. from transformers import AutoTokenizer
  14. import json
  15. import PyPDF2
  16. import random
  17. from langchain_experimental.text_splitter import SemanticChunker
  18. from langchain_openai.embeddings import OpenAIEmbeddings
  19. from client_utils import build_openai_client, build_langchain_embeddings, UsageStats, ChatCompleter
  20. from math import ceil
  21. from format import DatasetConverter, datasetFormats, outputDatasetTypes
  22. from pathlib import Path
  23. from dotenv import load_dotenv
  24. from checkpointing import Checkpointing, checkpointed
  25. import uuid
  26. import shutil
  27. from threading import Thread, Event
  28. log_setup()
  29. load_dotenv() # take environment variables from .env.
  30. logger = logging.getLogger("raft")
  31. DocType = Literal["api", "pdf", "json", "txt"]
  32. docTypes = list(get_args(DocType))
  33. SystemPromptKey = Literal["gpt", "llama"]
  34. systemPromptKeys = list(get_args(SystemPromptKey))
  35. def get_args() -> argparse.Namespace:
  36. """
  37. Parses and returns the arguments specified by the user's command
  38. """
  39. parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
  40. parser.add_argument("--datapath", type=Path, default="", help="If a file, the path at which the document is located. If a folder, the path at which to load all documents")
  41. parser.add_argument("--output", type=str, default="./", help="The path at which to save the dataset")
  42. parser.add_argument("--output-format", type=str, default="hf", help="The format of the output dataset.", choices=datasetFormats)
  43. parser.add_argument("--output-type", type=str, default="jsonl", help="Type to export the dataset to. Defaults to jsonl.", choices=outputDatasetTypes)
  44. parser.add_argument("--output-chat-system-prompt", type=str, help="The system prompt to use when the output format is chat")
  45. parser.add_argument("--output-completion-prompt-column", type=str, default="prompt", help="The prompt column name to use for the completion format")
  46. parser.add_argument("--output-completion-completion-column", type=str, default="completion", help="The completion column name to use for the completion format")
  47. parser.add_argument("--distractors", type=int, default=3, help="The number of distractor documents to include per data point / triplet")
  48. parser.add_argument("--p", type=float, default=1.0, help="The percentage that the oracle document is included in the context")
  49. parser.add_argument("--questions", type=int, default=5, help="The number of data points / triplets to generate per chunk")
  50. parser.add_argument("--chunk_size", type=int, default=512, help="The size of each chunk in number of tokens")
  51. parser.add_argument("--doctype", type=str, default="pdf", help="The type of the document, must be one of the accepted doctypes", choices=docTypes)
  52. parser.add_argument("--openai_key", type=str, default=None, help="Your OpenAI key used to make queries to GPT-3.5 or GPT-4")
  53. parser.add_argument("--embedding_model", type=str, default="text-embedding-ada-002", help="The embedding model to use to encode documents chunks (text-embedding-ada-002, ...)")
  54. parser.add_argument("--completion_model", type=str, default="gpt-4", help="The model to use to generate questions and answers (gpt-3.5, gpt-4, ...)")
  55. parser.add_argument("--system-prompt-key", default="gpt", help="The system prompt to use to generate the dataset", choices=systemPromptKeys)
  56. parser.add_argument("--workers", type=int, default=2, help="The number of worker threads to use to generate the dataset")
  57. parser.add_argument("--auto-clean-checkpoints", type=bool, default=False, help="Whether to auto clean the checkpoints after the dataset is generated")
  58. parser.add_argument("--qa-threshold", type=int, default=None, help="The number of Q/A samples to generate after which to stop the generation process. Defaults to None, which means generating Q/A samples for all documents")
  59. args = parser.parse_args()
  60. return args
  61. def get_chunks(
  62. data_path: Path,
  63. doctype: DocType = "pdf",
  64. chunk_size: int = 512,
  65. openai_key: str | None = None,
  66. model: str = None
  67. ) -> list[str]:
  68. """
  69. Takes in a `data_path` and `doctype`, retrieves the document, breaks it down into chunks of size
  70. `chunk_size`, and returns the chunks.
  71. """
  72. chunks = []
  73. logger.info(f"Retrieving chunks from {data_path} of type {doctype} using the {model} model.")
  74. if doctype == "api":
  75. with open(data_path) as f:
  76. api_docs_json = json.load(f)
  77. chunks = list(api_docs_json)
  78. chunks = [str(api_doc_json) for api_doc_json in api_docs_json]
  79. for field in ["user_name", "api_name", "api_call", "api_version", "api_arguments", "functionality"]:
  80. if field not in chunks[0]:
  81. raise TypeError(f"API documentation is not in the format specified by the Gorilla API Store: Missing field `{field}`")
  82. else:
  83. embeddings = build_langchain_embeddings(openai_api_key=openai_key, model=model)
  84. chunks = []
  85. file_paths = [data_path]
  86. if data_path.is_dir():
  87. file_paths = list(data_path.rglob('**/*.' + doctype))
  88. futures = []
  89. with tqdm(total=len(file_paths), desc="Chunking", unit="file") as pbar:
  90. with ThreadPoolExecutor(max_workers=2) as executor:
  91. for file_path in file_paths:
  92. futures.append(executor.submit(get_doc_chunks, embeddings, file_path, doctype, chunk_size))
  93. for future in as_completed(futures):
  94. doc_chunks = future.result()
  95. chunks.extend(doc_chunks)
  96. pbar.set_postfix({'chunks': len(chunks)})
  97. pbar.update(1)
  98. return chunks
  99. def get_doc_chunks(
  100. embeddings: OpenAIEmbeddings,
  101. file_path: Path,
  102. doctype: DocType = "pdf",
  103. chunk_size: int = 512,
  104. ) -> list[str]:
  105. if doctype == "json":
  106. with open(file_path, 'r') as f:
  107. data = json.load(f)
  108. text = data["text"]
  109. elif doctype == "pdf":
  110. text = ""
  111. with open(file_path, 'rb') as file:
  112. reader = PyPDF2.PdfReader(file)
  113. num_pages = len(reader.pages)
  114. for page_num in range(num_pages):
  115. page = reader.pages[page_num]
  116. text += page.extract_text()
  117. elif doctype == "txt":
  118. with open(file_path, 'r') as file:
  119. data = file.read()
  120. text = str(data)
  121. else:
  122. raise TypeError("Document is not one of the accepted types: api, pdf, json, txt")
  123. num_chunks = ceil(len(text) / chunk_size)
  124. logger.debug(f"Splitting text into {num_chunks} chunks.")
  125. text_splitter = SemanticChunker(embeddings, number_of_chunks=num_chunks)
  126. chunks = text_splitter.create_documents([text])
  127. chunks = [chunk.page_content for chunk in chunks]
  128. return chunks
  129. def generate_chunk_instructions(chat_completer: ChatCompleter, chunk: Any, x=5, model: str = None) -> list[str]:
  130. """
  131. Generates `x` questions / use cases for `api_call`. Used when the input document is of type `api`.
  132. """
  133. response = chat_completer(
  134. model=model,
  135. messages=[
  136. {"role": "system", "content": "You are a synthetic instruction-api pair generator. Given an API endpoint in the form of a JSON object, generate %s example queries of instructions a user could ask and would be answered by invoking the API call. For example, if the given API call is the `service.users().getProfile(userId='me').execute()` call from the Gmail API, an example query could be 'How can I fetch my Gmail account's email address?'" % (x)},
  137. {"role": "system", "content": "The API endpoint is a JSON object with required params: user_name, api_name, api_call, api_version, api_arguments, functionality, and optional params: env_requirements, example_code, meta_data, Questions"},
  138. {"role": "system", "content": "For instance, if the api call contains: {'user_name': 'felixzhu555', 'api_name': 'Google Maps - Address Validation', 'api_call': 'Client.addressvalidation(addressLines, regionCode=region_code, locality=locality, enableUspsCass=boolean)', 'api_version': '4.10.0', 'api_arguments': {}, 'functionality': 'Validate an address and its components, standardize the address for mailing, and determine the best known geocode for it.', 'env_requirements': ['googlemaps'], 'example_code': 'client = googlemaps.Client(key='YOUR_API_KEY')\nresponse = client.addressvalidation('1600 Amphitheatre Pk', regionCode='US', locality='Mountain View', enableUspsCass=True)', 'meta_data': {'description': 'The googlemaps python client is an abstraction for the Google Maps API that requires python 3.5+. Each Google Maps web service request requires an API key or client ID. API keys are generated in the 'Credentials' page of the 'APIs & Services' tab of Google Cloud console. This key should be kept secret on your server.'}, 'questions': []}, an example instruction would be 'Validate the following address: University Avenue and, Oxford St, Berkeley, CA 94720.'"},
  139. {"role": "system", "content": "Don't mention 'API' or use any hints or the name of the API. In one-third of the queries, make sure to include a specific example, like 'Validate this address: 123 Harrison St, Oakland CA'. Include ONLY the queries in your response."},
  140. {"role": "user", "content": str(chunk)}
  141. ]
  142. )
  143. content = response.choices[0].message.content
  144. queries = content.split('\n')
  145. queries = [strip_str(q) for q in queries]
  146. queries = [q for q in queries if any(c.isalpha() for c in q)]
  147. return queries
  148. build_qa_messages = {
  149. "gpt": lambda chunk, x : [
  150. {"role": "system", "content": """You are a synthetic question-answer pair generator. Given a chunk of context about
  151. some topic(s), generate %s example questions a user could ask and would be answered using information from the chunk.
  152. For example, if the given context was a Wikipedia paragraph about the United States, an example question could be
  153. 'How many states are in the United States?'""" % (x)},
  154. {"role": "system", "content": "The questions should be able to be answered in a few words or less. Include only the questions in your response."},
  155. {"role": "user", "content": str(chunk)}
  156. ],
  157. "llama": lambda chunk, x : [
  158. {"role": "system", "content":
  159. """You are a synthetic question generator.
  160. Instructions:
  161. - Given a chunk of context about some topic(s), generate %s example questions a user could ask
  162. - Questions should be answerable using only information from the chunk.
  163. - Generate one question per line
  164. - Generate only questions
  165. - Questions should be succinct
  166. Here are some samples:
  167. Context: A Wikipedia paragraph about the United States,
  168. Question: How many states are in the United States?
  169. Context: A Wikipedia paragraph about vampire bats,
  170. Question: What are the different species of vampire bats?
  171. """ % (x)},
  172. {"role": "system", "content": "The questions should be able to be answered in a few words or less. Include only the questions in your response."},
  173. {"role": "user", "content": str(chunk)}
  174. ]
  175. }
  176. def generate_instructions_gen(chat_completer: ChatCompleter, chunk: Any, x: int = 5, model: str = None, prompt_key : str = "gpt") -> list[str]:
  177. """
  178. Generates `x` questions / use cases for `chunk`. Used when the input document is of general types
  179. `pdf`, `json`, or `txt`.
  180. """
  181. try:
  182. response = chat_completer(
  183. model=model,
  184. messages=build_qa_messages[prompt_key](chunk, x),
  185. max_tokens=min(25 * x, 512), # 25 tokens per question
  186. )
  187. except BadRequestError as e:
  188. if e.code == "content_filter":
  189. logger.warning(f"Got content filter error, skipping chunk: {e.message}")
  190. return []
  191. raise e
  192. content = response.choices[0].message.content
  193. queries = content.split('\n') if content else []
  194. #queries = [strip_str(q) for q in queries]
  195. queries = [q for q in queries if any(c.isalpha() for c in q)]
  196. return queries
  197. def strip_str(s: str) -> str:
  198. """
  199. Helper function for helping format strings returned by GPT-4.
  200. """
  201. l, r = 0, len(s)-1
  202. beg_found = False
  203. for i in range(len(s)):
  204. if s[i].isalpha():
  205. if not beg_found:
  206. l = i
  207. beg_found = True
  208. else:
  209. r = i
  210. r += 2
  211. return s[l:min(r, len(s))]
  212. def encode_question(question: str, api: Any) -> list[str]:
  213. """
  214. Encode multiple prompt instructions into a single string for the `api` case.
  215. """
  216. prompts = []
  217. prompt = question + "\nWrite a python program to call API in " + str(api) + ".\n\nThe answer should follow the format: <<<domain>>> $DOMAIN \n, <<<api_call>>>: $API_CALL \n, <<<api_provider>>>: $API_PROVIDER \n, <<<explanation>>>: $EXPLANATION \n, <<<code>>>: $CODE}. Here are the requirements:\n \n2. The $DOMAIN should be the domain of the API ('N/A' if unknown). The $API_CALL should have only 1 line of code that calls api.\n3. The $API_PROVIDER should be the programming framework used.\n4. $EXPLANATION should be a numbered, step-by-step explanation.\n5. The $CODE is the python code.\n6. Do not repeat the format in your answer."
  218. prompts.append({"role": "system", "content": "You are a helpful API writer who can write APIs based on requirements."})
  219. prompts.append({"role": "user", "content": prompt})
  220. return prompts
  221. prompt_templates = {
  222. "gpt": """
  223. Question: {question}\nContext: {context}\n
  224. Answer this question using the information given in the context above. Here is things to pay attention to:
  225. - First provide step-by-step reasoning on how to answer the question.
  226. - In the reasoning, if you need to copy paste some sentences from the context, include them in ##begin_quote## and ##end_quote##. This would mean that things outside of ##begin_quote## and ##end_quote## are not directly copy paste from the context.
  227. - End your response with final answer in the form <ANSWER>: $answer, the answer should be succinct.
  228. You MUST begin your final answer with the tag "<ANSWER>:".
  229. """,
  230. "llama": """
  231. Question: {question}
  232. Context: {context}
  233. Answer this question using the information given in the context above.
  234. Instructions:
  235. - Provide step-by-step reasoning on how to answer the question.
  236. - Explain which parts of the context are meaningful and why.
  237. - Copy paste the relevant sentences from the context in ##begin_quote## and ##end_quote##.
  238. - Provide a summary of how you reached your answer.
  239. - End your response with the final answer in the form <ANSWER>: $answer, the answer should be succinct.
  240. - You MUST begin your final answer with the tag "<ANSWER>:".
  241. Here are some samples:
  242. Example question: What movement did the arrest of Jack Weinberg in Sproul Plaza give rise to?
  243. Example answer: To answer the question, we need to identify the movement that was sparked by the arrest of Jack Weinberg in Sproul Plaza.
  244. The context provided gives us the necessary information to determine this.
  245. First, we look for the part of the context that directly mentions Jack Weinberg's arrest.
  246. We find it in the sentence: ##begin_quote##The arrest in Sproul Plaza of Jack Weinberg, a recent Berkeley alumnus and chair of Campus CORE,
  247. prompted a series of student-led acts of formal remonstrance and civil disobedience that ultimately gave rise to the Free Speech Movement##end_quote##.
  248. From this sentence, we understand that the arrest of Jack Weinberg led to student-led acts which then gave rise to a specific movement.
  249. The name of the movement is explicitly mentioned in the same sentence as the "Free Speech Movement."
  250. Therefore, based on the context provided, we can conclude that the arrest of Jack Weinberg in Sproul Plaza gave rise to the Free Speech Movement.
  251. <ANSWER>: Free Speech Movement
  252. """
  253. }
  254. def encode_question_gen(question: str, chunk: Any, prompt_key : str = "gpt") -> list[str]:
  255. """
  256. Encode multiple prompt instructions into a single string for the general case (`pdf`, `json`, or `txt`).
  257. """
  258. prompts = []
  259. prompt = prompt_templates[prompt_key].format(question=question, context=str(chunk))
  260. prompts.append({"role": "system", "content": "You are a helpful question answerer who can provide an answer given a question and relevant context."})
  261. prompts.append({"role": "user", "content": prompt})
  262. return prompts
  263. def generate_label(chat_completer: ChatCompleter, question: str, context: Any, doctype: DocType = "pdf", model: str = None, prompt_key : str = "gpt") -> str | None:
  264. """
  265. Generates the label / answer to `question` using `context` and GPT-4.
  266. """
  267. question = encode_question(question, context) if doctype == "api" else encode_question_gen(question, context, prompt_key)
  268. response = chat_completer(
  269. model=model,
  270. messages=question,
  271. n=1,
  272. temperature=0,
  273. max_tokens=512,
  274. )
  275. response = response.choices[0].message.content
  276. return response
  277. def generate_question_cot_answer(
  278. chat_completer: ChatCompleter,
  279. chunks: list[str],
  280. chunk: str,
  281. chunk_id,
  282. question,
  283. doctype: DocType = "api",
  284. num_distract: int = 3,
  285. p: float = 0.8,
  286. model: str = None,
  287. prompt_key: str = "gpt",
  288. ):
  289. datapt = {
  290. "id": None,
  291. "type": None,
  292. "question": None,
  293. "context": None,
  294. "oracle_context": None,
  295. "cot_answer": None
  296. }
  297. datapt["id"] = str(uuid.uuid4())
  298. datapt["type"] = "api call" if doctype == "api" else "general"
  299. datapt["question"] = question
  300. # add num_distract distractor docs
  301. docs = [chunk]
  302. indices = list(range(0, len(chunks)))
  303. indices.remove(chunk_id)
  304. for j in random.sample(indices, num_distract):
  305. docs.append(chunks[j])
  306. # decides whether to add oracle document
  307. oracle = random.uniform(0, 1) < p
  308. if not oracle:
  309. docs[0] = chunks[random.sample(indices, 1)[0]]
  310. random.shuffle(docs)
  311. d = {
  312. "title": [],
  313. "sentences": []
  314. }
  315. d["title"].append(["placeholder_title"]*(num_distract+1))
  316. d["sentences"].append(docs)
  317. datapt["context"] = d
  318. datapt["oracle_context"] = chunk
  319. # add answer to q
  320. datapt["cot_answer"] = generate_label(chat_completer, question, chunk, doctype, model=model, prompt_key=prompt_key)
  321. # construct model instruction
  322. context = ""
  323. for doc in docs:
  324. context += "<DOCUMENT>" + str(doc) + "</DOCUMENT>\n"
  325. context += question
  326. datapt["instruction"] = context
  327. return datapt
  328. def build_or_load_chunks(
  329. datapath: Path,
  330. doctype: str,
  331. CHUNK_SIZE: int,
  332. OPENAPI_API_KEY: str,
  333. embedding_model: str,
  334. checkpoints_dir: Path,
  335. ):
  336. """
  337. Builds chunks and checkpoints them if asked
  338. """
  339. chunks_ds: Dataset = None
  340. chunks = None
  341. checkpoints_chunks_path = checkpoints_dir / "chunks"
  342. logger.info(f"Using checkpoint chunks {checkpoints_chunks_path}")
  343. if checkpoints_chunks_path.exists():
  344. chunks_ds = Dataset.load_from_disk(checkpoints_chunks_path)
  345. chunks = chunks_ds['chunk']
  346. if not chunks:
  347. chunks = get_chunks(datapath, doctype, CHUNK_SIZE, OPENAPI_API_KEY, model=embedding_model)
  348. if not chunks_ds:
  349. chunks_table = pa.table({ "chunk": chunks })
  350. chunks_ds = Dataset(chunks_table)
  351. chunks_ds.save_to_disk(checkpoints_chunks_path)
  352. return chunks
  353. def main():
  354. main_start = time.time()
  355. # run code
  356. args = get_args()
  357. # Validate arguments
  358. if args.output_chat_system_prompt and args.output_format != "chat":
  359. raise Exception("Parameter --output-chat-system-prompt can only be used with --output-format chat")
  360. OPENAPI_API_KEY = args.openai_key
  361. client = build_openai_client(
  362. api_key=OPENAPI_API_KEY,
  363. )
  364. chat_completer = ChatCompleter(client)
  365. CHUNK_SIZE = args.chunk_size
  366. NUM_DISTRACT_DOCS = args.distractors
  367. output_path = Path(args.output).absolute()
  368. checkpoints_dir = Path(str(output_path) + "-checkpoints").absolute()
  369. auto_clean_checkpoints = args.auto_clean_checkpoints
  370. if auto_clean_checkpoints:
  371. logger.info(f"Checkpoints will be automatically deleted after dataset generation. Remove --auto-clean-checkpoints to deactivate.")
  372. datapath: Path = args.datapath
  373. datasets.disable_progress_bars()
  374. # Chunks
  375. chunks = build_or_load_chunks(datapath, args.doctype, CHUNK_SIZE, OPENAPI_API_KEY, args.embedding_model, checkpoints_dir)
  376. cot_answers_ds = None
  377. num_chunks = len(chunks)
  378. num_questions = args.questions
  379. max_workers = args.workers
  380. doctype = args.doctype
  381. completion_model = args.completion_model
  382. system_prompt_key = args.system_prompt_key
  383. logger.info(f"Using system prompt key {system_prompt_key}")
  384. logger.info(f"Using {max_workers} worker threads")
  385. cot_answers_ds = stage_generate(chat_completer, checkpoints_dir, chunks, num_questions, max_workers, doctype, completion_model, system_prompt_key, num_distract=NUM_DISTRACT_DOCS, p=args.p, qa_threshold=args.qa_threshold)
  386. # Save as .arrow format
  387. datasets.enable_progress_bars()
  388. cot_answers_ds.save_to_disk(str(output_path))
  389. # Save as .jsonl format
  390. formatter = DatasetConverter()
  391. # Extract format specific params
  392. format_params = {}
  393. if args.output_chat_system_prompt:
  394. format_params['system_prompt'] = args.output_chat_system_prompt
  395. if args.output_format == "completion":
  396. format_params['prompt_column'] = args.output_completion_prompt_column
  397. format_params['completion_column'] = args.output_completion_completion_column
  398. formatter.convert(ds=cot_answers_ds, format=args.output_format, output_path=str(output_path), output_type=args.output_type, params=format_params)
  399. # Warning, this deletes all intermediary checkpoint files
  400. if auto_clean_checkpoints:
  401. shutil.rmtree(checkpoints_dir)
  402. logger.info(f"Generated {len(cot_answers_ds)} question/answer/CoT/documents samples")
  403. logger.info(f"Dataset saved to {output_path}")
  404. logger.info(f"Done in {time.time() - main_start:.2f}s")
  405. class StoppingException(Exception):
  406. """
  407. Raised by worker threads when the process is stopping early
  408. """
  409. pass
  410. def stage_generate(chat_completer: ChatCompleter, checkpoints_dir, chunks, num_questions, max_workers, doctype, completion_model, system_prompt_key, num_distract, p, qa_threshold):
  411. """
  412. Given a chunk, create {Q, A, D} triplets and add them to the dataset.
  413. """
  414. questions_checkpointing = Checkpointing(checkpoints_dir / "questions")
  415. answers_checkpointing = Checkpointing(checkpoints_dir / "answers")
  416. num_chunks = len(chunks)
  417. # Tracking when the process is stopping, so we can stop the generation process early
  418. # Initial value is False
  419. is_stopping = Event()
  420. @checkpointed(questions_checkpointing)
  421. def generate_chunk_instructions_ds(chunk: str, chunk_id: int, doctype: str, *args, **kwargs):
  422. """
  423. Generates a dataset of instructions for a given chunk.
  424. """
  425. questions = generate_chunk_instructions(chunk=chunk, *args, **kwargs) if doctype == "api" else generate_instructions_gen(chunk=chunk, *args, **kwargs)
  426. chunk_question_pairs = [{"chunk": chunk, "chunk_id": chunk_id, "question": question} for question in questions]
  427. questions_ds = Dataset.from_list(chunk_question_pairs)
  428. return questions_ds
  429. @checkpointed(answers_checkpointing)
  430. def generate_question_cot_answers(questions_ds, chunk_id: int, chunk: str, *args, **kwargs):
  431. def process_example(chunk, question):
  432. try:
  433. cot_answer = generate_question_cot_answer(chunk=chunk, chunk_id=chunk_id, chunks=chunks, question=question, *args, **kwargs)
  434. except BadRequestError as e:
  435. if e.code == "content_filter":
  436. logger.warning(f"Got content filter error, skipping question '{question}': {e.message}")
  437. return None
  438. raise e
  439. return cot_answer
  440. results = [process_example(chunk, question) for chunk, question in zip(questions_ds['chunk'], questions_ds['question'])] if len(questions_ds) > 0 else []
  441. results = [r for r in results if r is not None]
  442. table = pa.Table.from_pylist(results)
  443. ds = Dataset(table)
  444. return ds
  445. def process_chunk(i):
  446. if is_stopping.is_set():
  447. raise StoppingException()
  448. chunk = chunks[i]
  449. questions_ds = generate_chunk_instructions_ds(chunk=chunk, chunk_id=i, chat_completer=chat_completer, x=num_questions, model=completion_model, doctype=doctype, prompt_key=system_prompt_key)
  450. answers_ds = generate_question_cot_answers(questions_ds=questions_ds, chunk=chunk, chunk_id=i, chat_completer=chat_completer, model=completion_model, doctype=doctype, prompt_key=system_prompt_key, num_distract=num_distract, p=p)
  451. return answers_ds
  452. futures = []
  453. answers_ds_list = []
  454. usage_stats = UsageStats()
  455. # we use the checkpointing to keep track of the chunks that have already been processed
  456. # the answers are generated after the questions so the process might have been stopped in between a batch of answers and matching questions
  457. # so we need to use the answers checkpointing to keep track of which chunks we need to process
  458. # if the questions for a given chunk have already been checkpointed, they will just be loaded from the checkpoint
  459. # we set the tqdm's initial position to avoid having cached data skew the stats
  460. missing_chunks = answers_checkpointing.missing_checkpoints(num_chunks)
  461. gen_questions_count = 0
  462. if answers_checkpointing.has_checkpoints():
  463. ds = answers_checkpointing.collect_checkpoints()
  464. gen_questions_count = len(ds)
  465. done_chunks = num_chunks - len(missing_chunks)
  466. if done_chunks > 0 or gen_questions_count > 0:
  467. logger.info(f"Resuming generation from chunk {done_chunks}/{num_chunks} and {gen_questions_count} questions")
  468. # If we have a QA threshold, it makes more sense to keep track of the number of questions generated
  469. # Otherwise, track chunks
  470. track_questions = qa_threshold is not None
  471. if qa_threshold:
  472. logger.info(f"Will stop early as soon as the QA threshold is met: {qa_threshold}")
  473. if track_questions:
  474. tqdm_args = {"total": qa_threshold, "unit": "qa", "initial": gen_questions_count}
  475. else:
  476. tqdm_args = {"total": num_chunks, "unit": "chunk", "initial": done_chunks}
  477. tps = 0
  478. with tqdm(desc="Generating", **tqdm_args) as pbar:
  479. with ThreadPoolExecutor(max_workers=max_workers) as executor:
  480. for i in missing_chunks:
  481. futures.append(executor.submit(process_chunk, i))
  482. for future in as_completed(futures):
  483. if qa_threshold and gen_questions_count >= qa_threshold:
  484. logger.info(f"Met threshold {gen_questions_count} >= {qa_threshold} questions, stopping generation")
  485. is_stopping.set()
  486. break
  487. answers_ds = future.result()
  488. answers_ds_list.append(answers_ds)
  489. increment = min(len(answers_ds), qa_threshold - gen_questions_count) if track_questions else 1
  490. gen_questions_count += len(answers_ds)
  491. done_chunks += 1
  492. stats = chat_completer.get_stats_and_reset()
  493. if stats:
  494. tps = stats.total_tokens / stats.duration
  495. usage_stats += stats
  496. postfix = {'last tok/s': tps, 'avg tok/s': usage_stats.total_tokens / usage_stats.duration if usage_stats.duration > 0 else 0}
  497. if track_questions:
  498. postfix['chunks'] = done_chunks
  499. else:
  500. postfix['qa'] = gen_questions_count
  501. pbar.set_postfix(postfix)
  502. pbar.update(increment)
  503. ds = answers_checkpointing.collect_checkpoints()
  504. ds = ds.select(range(qa_threshold)) if qa_threshold else ds
  505. logger.info(f"Consumed {usage_stats.prompt_tokens} prompt tokens, {usage_stats.completion_tokens} completion tokens, {usage_stats.total_tokens} total tokens")
  506. return ds
  507. if __name__ == "__main__":
  508. with MDC(progress="0%"):
  509. main()