rich_tagging_pipeline.py 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  1. #!/usr/bin/env python3
  2. """
  3. Tagging pipeline for Dolma JSONL datasets.
  4. For each .jsonl, .jsonl.gz, or .jsonl.ztd file under the dataset/documents folder,
  5. this script issues a model prompt completion
  6. collects the yes/no answers, and writes corresponding Dolma attributes JSONL files under
  7. scratch/attributes/, mirroring the input structure.
  8. """
  9. import argparse
  10. import asyncio
  11. import atexit
  12. import gzip
  13. import json
  14. import logging
  15. import os
  16. import re
  17. import sys
  18. import time
  19. from typing import Optional
  20. from urllib.parse import urlparse
  21. import boto3
  22. import httpx
  23. import zstandard as zstd
  24. from huggingface_hub import snapshot_download
  25. from pydantic import BaseModel, Field, ValidationError
  26. from olmocr.check import (
  27. check_torch_gpu_available,
  28. )
  29. from olmocr.metrics import MetricsKeeper
  30. from olmocr.s3_utils import (
  31. download_directory,
  32. expand_s3_glob,
  33. get_s3_bytes_with_backoff,
  34. parse_s3_path,
  35. )
  36. from olmocr.version import VERSION
  37. from olmocr.work_queue import LocalWorkQueue, S3WorkQueue, WorkQueue
  38. # Initialize logger
  39. logger = logging.getLogger(__name__)
  40. logger.setLevel(logging.DEBUG)
  41. logger.propagate = False
  42. server_logger = logging.getLogger("vllm")
  43. server_logger.propagate = False
  44. file_handler = logging.FileHandler("olmocr-pipeline-debug.log", mode="a")
  45. file_handler.setLevel(logging.DEBUG)
  46. file_handler.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
  47. console_handler = logging.StreamHandler()
  48. console_handler.setLevel(logging.INFO)
  49. console_handler.setFormatter(logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s"))
  50. # Add handlers to the logger
  51. logger.addHandler(file_handler)
  52. logger.addHandler(console_handler)
  53. server_logger.addHandler(file_handler)
  54. # Default port; overridden by --port
  55. SERVER_PORT = 30026
  56. # Global variables for token statistics
  57. metrics = MetricsKeeper(window=60 * 5)
  58. class PIIClassification(BaseModel):
  59. primary_language: str = Field(..., description="Primary language as a two-letter code")
  60. document_type: str = Field(..., description="Basic summary of document type classification")
  61. is_resume_cv: Optional[bool] = Field(None, description="True if the document is a page from a resume or cv")
  62. contains_pii: Optional[bool] = Field(None, description="True if document contains PII")
  63. class RichPIIClassification(BaseModel):
  64. primary_language: str = Field(..., description="Primary language as a two-letter code")
  65. document_type: str = Field(..., description="Basic summary of document type classification")
  66. is_public_document: bool = Field(False, description="True if the document is meant for public dissemination")
  67. contains_pii_government_id: Optional[bool] = Field(None)
  68. contains_pii_financial_info: Optional[bool] = Field(None)
  69. contains_pii_biometric_data: Optional[bool] = Field(None)
  70. contains_pii_login_info: Optional[bool] = Field(None)
  71. contains_identifier_name: Optional[bool] = Field(None, description="True if the document contains a name")
  72. contains_identifier_email: Optional[bool] = Field(None, description="True if the document contains an email address")
  73. contains_identifier_phone_number: Optional[bool] = Field(None, description="True if the document contains phone numbers")
  74. contains_identifier_with_address: Optional[bool] = Field(None)
  75. contains_identifier_with_biographical_info: Optional[bool] = Field(None)
  76. contains_identifier_with_location_info: Optional[bool] = Field(None)
  77. contains_identifier_with_employment_info: Optional[bool] = Field(None)
  78. contains_identifier_with_education_info: Optional[bool] = Field(None)
  79. contains_identifier_with_medical_info: Optional[bool] = Field(None)
  80. def contains_any_pii(self) -> bool:
  81. if self.is_public_document:
  82. return False
  83. if self.contains_pii_government_id or self.contains_pii_financial_info or self.contains_pii_biometric_data or self.contains_pii_login_info:
  84. return True
  85. if self.contains_identifier_name or self.contains_identifier_email or self.contains_identifier_phone_number:
  86. return (
  87. self.contains_identifier_with_address
  88. or self.contains_identifier_with_biographical_info
  89. or self.contains_identifier_with_location_info
  90. or self.contains_identifier_with_employment_info
  91. or self.contains_identifier_with_education_info
  92. or self.contains_identifier_with_medical_info
  93. )
  94. else:
  95. return False
  96. async def _process_single_page(page_text: str) -> RichPIIClassification:
  97. """Helper function to process a single document or page."""
  98. rich_prompt = """You are a document analyzer that identifies Personally Identifiable Information (PII) in documents.
  99. Your task is to analyze the document provided below and determine:
  100. 1. Whether the document is intended for public release or dissemination (e.g., research paper, public report, etc.)
  101. 2. If the document contains any PII
  102. For PII identification, follow these specific guidelines:
  103. PII THAT OCCURS EVEN WITHOUT AN IDENTIFIER:
  104. The following should ALWAYS be marked as PII even if they do not occur alongside an identifier:
  105. - Government IDs (Social Security Numbers, passport numbers, driver's license numbers, tax IDs)
  106. - Financial Information (credit card numbers, bank account/routing numbers)
  107. - Biometric Data (fingerprints, retina scans, facial recognition data, voice signatures)
  108. - Login information (ONLY mark as PII when a username, password, and login location are present together)
  109. IDENTIFIERS FOR PII:
  110. The following are considered identifiers that can make information PII:
  111. - Names (full names, first names, last names, nicknames)
  112. - Email addresses
  113. - Phone numbers
  114. PII THAT MUST CO-OCCUR WITH AN IDENTIFIER:
  115. The following types of information should ONLY be marked as PII if they occur ALONGSIDE an identifier (commonly, a person's name):
  116. - Addresses (street address, postal code, etc.)
  117. - Biographical Information (date of birth, place of birth, gender, sexual orientation, race, ethnicity, citizenship/immigration status, religion)
  118. - Location Information (geolocations, specific coordinates)
  119. - Employment Information (job titles, workplace names, employment history)
  120. - Education Information (school names, degrees, transcripts)
  121. - Medical Information (health records, diagnoses, genetic or neural data)
  122. If the document is a form, then ONLY consider fields which are filled out with specific values as potential PII. An empty form that asks for PII is not to be marked as containing PII.
  123. If this page does not itself contain PII, but references documents (such as curriculum vitae, personal statements) that typically contain PII, then do not mark it as PII.
  124. Only consider actual occurrences of the PII within the document shown.
  125. """
  126. prompt_end = "Answer as a JSON object with the following schema {'primary_language': str, 'document_type': str, 'is_public_document': bool, 'contains_pii_government_id': bool, 'contains_pii_financial_info': bool, 'contains_pii_biometric_data': bool, 'contains_pii_login_info': bool, 'contains_identifier_name': bool, 'contains_identifier_email': bool, 'contains_identifier_phone_number': bool, 'contains_identifier_with_address': bool, 'contains_identifier_with_biographical_info': bool, 'contains_identifier_with_location_info': bool, 'contains_identifier_with_employment_info': bool, 'contains_identifier_with_education_info': bool, 'contains_identifier_with_medical_info': bool}"
  127. query = {
  128. "model": "google/gemma-3-12b-it",
  129. "messages": [
  130. {
  131. "role": "user",
  132. "content": [
  133. {
  134. "type": "text",
  135. "text": (f"{rich_prompt}\n-----DOCUMENT_START-----\n{page_text}\n-----DOCUMENT_END-----\n{prompt_end}"),
  136. }
  137. ],
  138. }
  139. ],
  140. "max_tokens": 300,
  141. "temperature": 0.0,
  142. "response_format": {"type": "json_schema", "json_schema": {"name": "RichPIIClassification", "schema": RichPIIClassification.model_json_schema()}},
  143. }
  144. url = f"http://localhost:{SERVER_PORT}/v1/chat/completions"
  145. # ---------- HTTP call ---------------------------------------------------
  146. try:
  147. status, body = await apost(url, json_data=query)
  148. except Exception as e:
  149. logger.warning(f"Server network error: {e!s}")
  150. metrics.add_metrics(server_errors=1)
  151. return RichPIIClassification(primary_language="en", document_type="unknown", is_public_document=False)
  152. metrics.add_metrics(server_requests=1)
  153. if status != 200:
  154. logger.warning(f"Server HTTP {status}: {body[:250]!r}")
  155. metrics.add_metrics(server_errors=1)
  156. return RichPIIClassification(primary_language="en", document_type="unknown", is_public_document=False)
  157. # ---------- Parse base JSON --------------------------------------------
  158. try:
  159. base = json.loads(body)
  160. except json.JSONDecodeError:
  161. logger.warning(f"Server response is not valid JSON: {body[:250]!r}")
  162. metrics.add_metrics(server_errors=1)
  163. return RichPIIClassification(primary_language="en", document_type="unknown", is_public_document=False)
  164. # Token accounting if available
  165. if "usage" in base:
  166. metrics.add_metrics(
  167. server_input_tokens=base["usage"].get("prompt_tokens", 0),
  168. server_output_tokens=base["usage"].get("completion_tokens", 0),
  169. )
  170. # ---------- Extract the model message ----------------------------------
  171. try:
  172. content = base["choices"][0]["message"].get("content")
  173. except (KeyError, IndexError, AttributeError) as e:
  174. logger.warning(f"Missing fields in Server response: {e!s}")
  175. metrics.add_metrics(server_errors=1)
  176. return RichPIIClassification(primary_language="en", document_type="unknown", is_public_document=False)
  177. if not isinstance(content, str):
  178. logger.warning("Server `content` is not a string; treating as error.")
  179. metrics.add_metrics(server_errors=1)
  180. return RichPIIClassification(primary_language="en", document_type="unknown", is_public_document=False)
  181. try:
  182. pii_classification: RichPIIClassification = RichPIIClassification.model_validate_json(content)
  183. return pii_classification
  184. except ValidationError as e:
  185. logger.warning(f"Unable to parse pii classification object: {e!s}")
  186. metrics.add_metrics(server_errors=1)
  187. return RichPIIClassification(primary_language="en", document_type="unknown", is_public_document=False)
  188. # Manual simple implementation of HTTP Post
  189. # It feels strange perhaps, but httpx and aiohttp are very complex beasts
  190. # Ex. the sessionpool in httpcore has 4 different locks in it, and I've noticed
  191. # that at the scale of 100M+ requests, that they deadlock in different strange ways
  192. async def apost(url, json_data):
  193. parsed_url = urlparse(url)
  194. host = parsed_url.hostname
  195. port = parsed_url.port or 80
  196. path = parsed_url.path or "/"
  197. writer = None
  198. try:
  199. reader, writer = await asyncio.open_connection(host, port)
  200. json_payload = json.dumps(json_data)
  201. request = (
  202. f"POST {path} HTTP/1.1\r\n"
  203. f"Host: {host}\r\n"
  204. f"Content-Type: application/json\r\n"
  205. f"Content-Length: {len(json_payload)}\r\n"
  206. f"Connection: close\r\n\r\n"
  207. f"{json_payload}"
  208. )
  209. writer.write(request.encode())
  210. await writer.drain()
  211. # Read status line
  212. status_line = await reader.readline()
  213. if not status_line:
  214. raise ConnectionError("No response from server")
  215. status_parts = status_line.decode().strip().split(" ", 2)
  216. if len(status_parts) < 2:
  217. raise ValueError(f"Malformed status line: {status_line.decode().strip()}")
  218. status_code = int(status_parts[1])
  219. # Read headers
  220. headers = {}
  221. while True:
  222. line = await reader.readline()
  223. if line in (b"\r\n", b"\n", b""):
  224. break
  225. key, _, value = line.decode().partition(":")
  226. headers[key.strip().lower()] = value.strip()
  227. # Read response body
  228. if "content-length" in headers:
  229. body_length = int(headers["content-length"])
  230. response_body = await reader.readexactly(body_length)
  231. else:
  232. raise ConnectionError("Anything other than fixed content length responses are not implemented yet")
  233. return status_code, response_body
  234. except Exception as e:
  235. # Pass through errors
  236. raise e
  237. finally:
  238. # But just make sure to close the socket on your way out
  239. if writer is not None:
  240. try:
  241. writer.close()
  242. await writer.wait_closed()
  243. except:
  244. pass
  245. async def process_dolma_document(args, dolma_doc, sem):
  246. """
  247. Query model to detect PII, enforcing a JSON schema.
  248. Resilient to:
  249. • Transport / HTTP errors
  250. • Missing or malformed fields in the response
  251. • Non-string or None `content`
  252. • Bad JSON in the model's answer
  253. Always returns: (doc_id, contains_pii: bool, text_length: int)
  254. """
  255. text = dolma_doc.get("text", "") or ""
  256. # Generate attribute key names using model name
  257. model_prefix = args.model.replace("/", "_")
  258. language_key_name = f"{model_prefix}_language"
  259. contains_pii_key_name = f"{model_prefix}_contains_pii"
  260. # Initialize result attributes with all RichPIIClassification attributes
  261. result_attributes = {
  262. contains_pii_key_name: [],
  263. language_key_name: [],
  264. f"{model_prefix}_is_public_document": [],
  265. f"{model_prefix}_contains_pii_government_id": [],
  266. f"{model_prefix}_contains_pii_financial_info": [],
  267. f"{model_prefix}_contains_pii_biometric_data": [],
  268. f"{model_prefix}_contains_pii_login_info": [],
  269. f"{model_prefix}_contains_identifier_name": [],
  270. f"{model_prefix}_contains_identifier_email": [],
  271. f"{model_prefix}_contains_identifier_phone_number": [],
  272. f"{model_prefix}_contains_identifier_with_address": [],
  273. f"{model_prefix}_contains_identifier_with_biographical_info": [],
  274. f"{model_prefix}_contains_identifier_with_location_info": [],
  275. f"{model_prefix}_contains_identifier_with_employment_info": [],
  276. f"{model_prefix}_contains_identifier_with_education_info": [],
  277. f"{model_prefix}_contains_identifier_with_medical_info": [],
  278. }
  279. # If pdf_page_numbers is present, split the text and process each page separately
  280. if "attributes" in dolma_doc and "pdf_page_numbers" in dolma_doc["attributes"]:
  281. page_numbers = dolma_doc["attributes"]["pdf_page_numbers"]
  282. # Filter pages down to actual real content
  283. selected_page_numbers = [tuple(p) for p in page_numbers if p[0] < p[1]]
  284. # Select just the first page
  285. selected_page_numbers = selected_page_numbers[:1]
  286. # Original select first + 2 more code
  287. # first_page_number = selected_page_numbers[0]
  288. # # Sample 3 pages max per document, but always include the first page, it's a good signal for CV classification
  289. # random.shuffle(selected_page_numbers)
  290. # selected_page_numbers = selected_page_numbers[:3]
  291. # if first_page_number not in selected_page_numbers:
  292. # selected_page_numbers[0] = first_page_number
  293. for start_pos, end_pos, page_num in page_numbers:
  294. if (start_pos, end_pos, page_num) in selected_page_numbers:
  295. page_text = text[start_pos:end_pos]
  296. # Process each page with the semaphore to limit concurrent requests
  297. async with sem:
  298. pii_class = await _process_single_page(page_text)
  299. # Add all attributes from RichPIIClassification
  300. result_attributes[contains_pii_key_name].append([start_pos, end_pos, pii_class.contains_any_pii()])
  301. result_attributes[language_key_name].append([start_pos, end_pos, pii_class.primary_language])
  302. result_attributes[f"{model_prefix}_is_public_document"].append([start_pos, end_pos, pii_class.is_public_document])
  303. result_attributes[f"{model_prefix}_contains_pii_government_id"].append([start_pos, end_pos, pii_class.contains_pii_government_id])
  304. result_attributes[f"{model_prefix}_contains_pii_financial_info"].append([start_pos, end_pos, pii_class.contains_pii_financial_info])
  305. result_attributes[f"{model_prefix}_contains_pii_biometric_data"].append([start_pos, end_pos, pii_class.contains_pii_biometric_data])
  306. result_attributes[f"{model_prefix}_contains_pii_login_info"].append([start_pos, end_pos, pii_class.contains_pii_login_info])
  307. result_attributes[f"{model_prefix}_contains_identifier_name"].append([start_pos, end_pos, pii_class.contains_identifier_name])
  308. result_attributes[f"{model_prefix}_contains_identifier_email"].append([start_pos, end_pos, pii_class.contains_identifier_email])
  309. result_attributes[f"{model_prefix}_contains_identifier_phone_number"].append([start_pos, end_pos, pii_class.contains_identifier_phone_number])
  310. result_attributes[f"{model_prefix}_contains_identifier_with_address"].append([start_pos, end_pos, pii_class.contains_identifier_with_address])
  311. result_attributes[f"{model_prefix}_contains_identifier_with_biographical_info"].append(
  312. [start_pos, end_pos, pii_class.contains_identifier_with_biographical_info]
  313. )
  314. result_attributes[f"{model_prefix}_contains_identifier_with_location_info"].append(
  315. [start_pos, end_pos, pii_class.contains_identifier_with_location_info]
  316. )
  317. result_attributes[f"{model_prefix}_contains_identifier_with_employment_info"].append(
  318. [start_pos, end_pos, pii_class.contains_identifier_with_employment_info]
  319. )
  320. result_attributes[f"{model_prefix}_contains_identifier_with_education_info"].append(
  321. [start_pos, end_pos, pii_class.contains_identifier_with_education_info]
  322. )
  323. result_attributes[f"{model_prefix}_contains_identifier_with_medical_info"].append(
  324. [start_pos, end_pos, pii_class.contains_identifier_with_medical_info]
  325. )
  326. else:
  327. # For pages we don't process, set all attributes to None
  328. for attr_key in result_attributes:
  329. result_attributes[attr_key].append([start_pos, end_pos, None])
  330. return result_attributes
  331. else:
  332. raise NotImplementedError("Missing code here, expecting this to be dolma docs made by olmocr....")
  333. async def process_file(args, worker_id: int, file_uri: str):
  334. """
  335. Download a JSONL file, query model per record, and collect attributes.
  336. """
  337. # Fetch raw bytes (S3 or local)
  338. if file_uri.startswith("s3://"):
  339. raw = await asyncio.to_thread(get_s3_bytes_with_backoff, dataset_s3, file_uri)
  340. else:
  341. with open(file_uri, "rb") as f:
  342. raw = f.read()
  343. # Decompress if needed
  344. if file_uri.endswith(".gz"):
  345. file_bytes = gzip.decompress(raw)
  346. elif file_uri.endswith(".ztd") or file_uri.endswith(".zst") or file_uri.endswith(".zstd"):
  347. dctx = zstd.ZstdDecompressor()
  348. file_bytes = dctx.decompress(raw, max_output_size=1_000_000_000)
  349. else:
  350. file_bytes = raw
  351. lines = file_bytes.decode("utf-8").splitlines()
  352. page_tasks = {}
  353. # Send all records in parallel, max N queued at a time
  354. sem = asyncio.Semaphore(args.parallel_requests)
  355. async with asyncio.TaskGroup() as tg:
  356. for line in lines:
  357. dolma_doc = json.loads(line)
  358. task = tg.create_task(process_dolma_document(args, dolma_doc, sem))
  359. page_tasks[dolma_doc["id"]] = (task, dolma_doc)
  360. logger.info(f"Finished taskgroup with {len(page_tasks)} items for {file_uri}")
  361. # Collect results and build attributes
  362. attributes = []
  363. for doc_id, (task, dolma_doc) in page_tasks.items():
  364. doc_attributes = task.result()
  365. attributes.append({"id": doc_id, "attributes": doc_attributes})
  366. return attributes
  367. async def worker(args, work_queue: WorkQueue, semaphore: asyncio.Semaphore, worker_id: int):
  368. """
  369. Pop work-items off the queue, run PII tagging, write the attributes file
  370. next to the dataset (keeping the original compression), mark the item done,
  371. and drop an empty sentinel file in <workspace>/results/.
  372. """
  373. while True:
  374. await semaphore.acquire()
  375. work_item = await work_queue.get_work()
  376. if work_item is None:
  377. logger.info(f"Worker {worker_id} exiting – queue empty")
  378. semaphore.release()
  379. break
  380. file_uri = work_item.work_paths[0]
  381. logger.info(f"Worker {worker_id} processing {file_uri}")
  382. try:
  383. # ------------------------------------------------------------------
  384. # Run the per-file pipeline
  385. # ------------------------------------------------------------------
  386. attributes = await process_file(args, worker_id, file_uri)
  387. # 1. Build the relative path that mirrors documents/…
  388. if file_uri.startswith("s3://"):
  389. _, key = parse_s3_path(file_uri)
  390. _, docs_prefix = parse_s3_path(args.dataset)
  391. rel_path = key[len(os.path.join(docs_prefix, "documents/")) :]
  392. else:
  393. docs_root = os.path.join(args.dataset, "documents")
  394. rel_path = os.path.relpath(file_uri, docs_root)
  395. out_rel = os.path.join("attributes", args.attribute_name, rel_path)
  396. out_jsonl = "\n".join(json.dumps(x) for x in attributes) + "\n"
  397. # 2. Preserve compression type
  398. if rel_path.endswith(".gz"):
  399. payload = gzip.compress(out_jsonl.encode("utf-8"))
  400. elif rel_path.endswith((".zst", ".ztd")):
  401. payload = zstd.ZstdCompressor().compress(out_jsonl.encode("utf-8"))
  402. else:
  403. payload = out_jsonl.encode("utf-8")
  404. # 3. Write to args.dataset (local or S3)
  405. if args.dataset.startswith("s3://"):
  406. bucket, prefix = parse_s3_path(args.dataset)
  407. key = os.path.join(prefix, out_rel)
  408. workspace_s3.put_object(Bucket=bucket, Key=key, Body=payload)
  409. else:
  410. out_path = os.path.join(args.dataset, out_rel)
  411. os.makedirs(os.path.dirname(out_path), exist_ok=True)
  412. with open(out_path, "wb") as fh:
  413. fh.write(payload)
  414. # 4. Mark queue item done
  415. await work_queue.mark_done(work_item)
  416. # 5. Drop empty sentinel file in <workspace>/results/
  417. sentinel_rel = os.path.join("results", f"output_{work_item.hash}.jsonl")
  418. if args.scratch.startswith("s3://"):
  419. bkt, pfx = parse_s3_path(args.scratch)
  420. key = os.path.join(pfx, sentinel_rel)
  421. workspace_s3.put_object(Bucket=bkt, Key=key, Body=b"")
  422. else:
  423. sentinel_path = os.path.join(args.scratch, sentinel_rel)
  424. os.makedirs(os.path.dirname(sentinel_path), exist_ok=True)
  425. open(sentinel_path, "w").close()
  426. except Exception as exc:
  427. logger.exception(f"Worker {worker_id} exception: {exc!s}")
  428. finally:
  429. semaphore.release()
  430. async def server_task(model_name_or_path, args, semaphore):
  431. # Check GPU memory, lower mem devices need a bit less KV cache space because the VLM takes additional memory
  432. # mem_fraction_arg = ["--mem-fraction-static", "0.80"]
  433. cmd = [
  434. "vllm",
  435. "serve",
  436. model_name_or_path,
  437. "--port",
  438. str(SERVER_PORT),
  439. "--uvicorn-log-level",
  440. "warning",
  441. "--disable-log-requests",
  442. "--max-model-len",
  443. "16000",
  444. # "--hf_overrides", "{\"architectures\": [\"Gemma3ForCausalLM\"]}",
  445. "--limit-mm-per-prompt",
  446. "images=0",
  447. ]
  448. proc = await asyncio.create_subprocess_exec(
  449. *cmd,
  450. stdout=asyncio.subprocess.PIPE,
  451. stderr=asyncio.subprocess.PIPE,
  452. )
  453. # Ensure the subprocess is terminated on exit
  454. def _kill_proc():
  455. proc.terminate()
  456. atexit.register(_kill_proc)
  457. # Shared variables between tasks
  458. last_running_req, last_queue_req = 0, 0
  459. server_printed_ready_message = False
  460. last_semaphore_release = time.time()
  461. async def process_line(line):
  462. nonlocal last_running_req, last_queue_req, last_semaphore_release, server_printed_ready_message
  463. server_logger.info(line)
  464. # if the server hasn't initialized yet, log all the lines to the main logger also, so that the user
  465. # can see any warnings/errors more easily
  466. if not server_printed_ready_message:
  467. logger.info(line)
  468. if not server_printed_ready_message and "The server is fired up and ready to roll!" in line:
  469. server_printed_ready_message = True
  470. last_semaphore_release = time.time()
  471. match = re.search(r"Running: (\d+) reqs", line)
  472. if match:
  473. last_running_req = int(match.group(1))
  474. match = re.search(r"Waiting: (\d+) reqs", line)
  475. if match:
  476. last_queue_req = int(match.group(1))
  477. logger.info(f"running req: {last_running_req} queue req: {last_queue_req}")
  478. async def read_stream(stream):
  479. while True:
  480. line = await stream.readline()
  481. if not line:
  482. break
  483. try:
  484. line = line.decode("utf-8").rstrip()
  485. await process_line(line)
  486. except Exception as ex:
  487. logger.warning(f"Got {ex} when reading log line from inference server, skipping")
  488. async def timeout_task():
  489. nonlocal last_running_req, last_queue_req, last_semaphore_release
  490. try:
  491. while True:
  492. await asyncio.sleep(1)
  493. if server_printed_ready_message and last_queue_req == 0 and time.time() - last_semaphore_release > 30 and semaphore.locked():
  494. semaphore.release()
  495. last_semaphore_release = time.time()
  496. logger.info("Semaphore released, allowing a worker to proceed.")
  497. except asyncio.CancelledError:
  498. pass # Clean up if the task is cancelled
  499. # Start tasks to read stdout, stderr, and handle timeout logic
  500. stdout_task = asyncio.create_task(read_stream(proc.stdout))
  501. stderr_task = asyncio.create_task(read_stream(proc.stderr))
  502. timeout_task = asyncio.create_task(timeout_task())
  503. try:
  504. await proc.wait()
  505. except asyncio.CancelledError:
  506. logger.info("Got cancellation request for server")
  507. proc.terminate()
  508. raise
  509. timeout_task.cancel()
  510. await asyncio.gather(stdout_task, stderr_task, timeout_task, return_exceptions=True)
  511. async def server_host(model_name_or_path, args, semaphore):
  512. MAX_RETRIES = 5
  513. retry = 0
  514. while retry < MAX_RETRIES:
  515. await server_task(model_name_or_path, args, semaphore)
  516. logger.warning("Server task ended")
  517. retry += 1
  518. if retry >= MAX_RETRIES:
  519. logger.error(f"Ended up starting the server more than {retry} times, cancelling pipeline")
  520. logger.error("")
  521. logger.error("Please make sure vllm is installed according to the latest instructions for 0.8.4")
  522. sys.exit(1)
  523. async def check_server_ready():
  524. max_attempts = 600
  525. delay_sec = 1
  526. url = f"http://localhost:{SERVER_PORT}/v1/models"
  527. for attempt in range(1, max_attempts + 1):
  528. try:
  529. async with httpx.AsyncClient() as session:
  530. response = await session.get(url)
  531. if response.status_code == 200:
  532. logger.info("server is ready.")
  533. return
  534. else:
  535. logger.info(f"Attempt {attempt}: Unexpected status code {response.status_code}")
  536. except Exception:
  537. logger.warning(f"Attempt {attempt}: Please wait for model server to become ready...")
  538. await asyncio.sleep(delay_sec)
  539. raise Exception("model server did not become ready after waiting.")
  540. async def download_model(model_name_or_path: str):
  541. if model_name_or_path.startswith("s3://") or model_name_or_path.startswith("gs://") or model_name_or_path.startswith("weka://"):
  542. logger.info(f"Downloading model directory from '{model_name_or_path}'")
  543. model_cache_dir = os.path.join(os.path.expanduser("~"), ".cache", "olmocr", "model")
  544. download_directory([model_name_or_path], model_cache_dir)
  545. return model_cache_dir
  546. elif os.path.isabs(model_name_or_path) and os.path.isdir(model_name_or_path):
  547. logger.info(f"Using local model path at '{model_name_or_path}'")
  548. return model_name_or_path
  549. else:
  550. logger.info(f"Downloading model with hugging face '{model_name_or_path}'")
  551. snapshot_download(repo_id=model_name_or_path)
  552. return model_name_or_path
  553. async def metrics_reporter(work_queue):
  554. while True:
  555. # Leading newlines preserve table formatting in logs
  556. logger.info(f"Queue remaining: {work_queue.size}")
  557. logger.info("\n" + str(metrics))
  558. await asyncio.sleep(10)
  559. def submit_beaker_job(args):
  560. from beaker import ( # type: ignore
  561. Beaker,
  562. Constraints,
  563. EnvVar,
  564. ExperimentSpec,
  565. ImageSource,
  566. Priority,
  567. ResultSpec,
  568. SecretNotFound,
  569. TaskContext,
  570. TaskResources,
  571. TaskSpec,
  572. )
  573. b = Beaker.from_env(default_workspace=args.beaker_workspace)
  574. account = b.account.whoami()
  575. owner = account.name
  576. beaker_image = f"jakep/olmocr-tagging-{VERSION}"
  577. task_name = f"olmocr-{os.path.basename(args.dataset.rstrip('/'))}"
  578. # Take out --beaker flag so the workers will just run things
  579. args_list = [arg for arg in sys.argv[1:] if arg != "--beaker"]
  580. # Take out the --pdfs [arg] or --pdfs=[arg], since the queue is populated locally
  581. args_list = [arg for i, arg in enumerate(args_list) if not (arg.startswith("--pdfs") or (i > 0 and args_list[i - 1] == "--pdfs"))]
  582. try:
  583. b.secret.get(f"{owner}-WEKA_ACCESS_KEY_ID", args.beaker_workspace)
  584. b.secret.get(f"{owner}-WEKA_SECRET_ACCESS_KEY", args.beaker_workspace)
  585. b.secret.get(f"{owner}-AWS_CREDENTIALS_FILE", args.beaker_workspace)
  586. except SecretNotFound:
  587. print(
  588. f"Expected beaker secrets for accessing Weka and S3 are not found. Are you okay to write those to your beaker workspace {args.beaker_workspace}? [y/n]"
  589. )
  590. if input().strip().lower() != "y":
  591. print("Exiting...")
  592. sys.exit(1)
  593. b.secret.write(f"{owner}-WEKA_ACCESS_KEY_ID", os.environ.get("WEKA_ACCESS_KEY_ID", ""), args.beaker_workspace)
  594. b.secret.write(f"{owner}-WEKA_SECRET_ACCESS_KEY", os.environ.get("WEKA_SECRET_ACCESS_KEY", ""), args.beaker_workspace)
  595. b.secret.write(
  596. f"{owner}-AWS_CREDENTIALS_FILE",
  597. open(os.path.join(os.path.expanduser("~"), ".aws", "credentials")).read(),
  598. args.beaker_workspace,
  599. )
  600. env_var_secrets = [
  601. EnvVar(name="WEKA_ACCESS_KEY_ID", secret=f"{owner}-WEKA_ACCESS_KEY_ID"),
  602. EnvVar(name="WEKA_SECRET_ACCESS_KEY", secret=f"{owner}-WEKA_SECRET_ACCESS_KEY"),
  603. EnvVar(name="AWS_CREDENTIALS_FILE", secret=f"{owner}-AWS_CREDENTIALS_FILE"),
  604. ]
  605. try:
  606. b.secret.get("OLMOCR_PREVIEW_HF_TOKEN", args.beaker_workspace)
  607. env_var_secrets.append(EnvVar(name="HF_TOKEN", secret="OLMOCR_PREVIEW_HF_TOKEN"))
  608. except SecretNotFound:
  609. pass
  610. try:
  611. b.secret.get("OE_DATA_GCS_SA_KEY", args.beaker_workspace)
  612. env_var_secrets.append(EnvVar(name="GOOGLE_APPLICATION_CREDENTIALS_FILE", secret="OE_DATA_GCS_SA_KEY"))
  613. except SecretNotFound:
  614. print("Input the olmo-gcs SA key if you would like to load weights from gcs (end with a double newline):")
  615. lines = []
  616. prev_empty = False
  617. for line in iter(input, None):
  618. if not line and prev_empty:
  619. break
  620. prev_empty = not line
  621. lines.append(line)
  622. gcs_sa_key = "\n".join(lines[:-1]).strip() # Remove the last empty line
  623. if gcs_sa_key:
  624. b.secret.write("OE_DATA_GCS_SA_KEY", gcs_sa_key, args.beaker_workspace)
  625. env_var_secrets.append(EnvVar(name="GOOGLE_APPLICATION_CREDENTIALS_FILE", secret="OE_DATA_GCS_SA_KEY"))
  626. # Create the experiment spec
  627. experiment_spec = ExperimentSpec(
  628. budget="ai2/oe-data",
  629. description=task_name,
  630. tasks=[
  631. TaskSpec(
  632. name=task_name,
  633. propagate_failure=False,
  634. propagate_preemption=False,
  635. replicas=args.beaker_gpus,
  636. context=TaskContext(
  637. priority=Priority(args.beaker_priority),
  638. preemptible=True,
  639. ),
  640. image=ImageSource(beaker=beaker_image),
  641. command=["python", "scripts/rich_tagging_pipeline.py"] + args_list,
  642. env_vars=[EnvVar(name="BEAKER_JOB_NAME", value=task_name), EnvVar(name="OWNER", value=owner)] + env_var_secrets,
  643. resources=TaskResources(gpu_count=1),
  644. constraints=Constraints(cluster=args.beaker_cluster if isinstance(args.beaker_cluster, list) else [args.beaker_cluster]),
  645. result=ResultSpec(path="/noop-results"),
  646. )
  647. ],
  648. )
  649. experiment_data = b.experiment.create(spec=experiment_spec, workspace=args.beaker_workspace)
  650. print(f"Experiment URL: https://beaker.org/ex/{experiment_data.id}")
  651. async def main():
  652. parser = argparse.ArgumentParser(description="Tagging pipeline for Dolma JSONL dataset")
  653. parser.add_argument("dataset", help="Dolma dataset root (local or s3://) with documents/ folder")
  654. parser.add_argument("scratch", help="Scratch workspace (local dir or s3://)")
  655. parser.add_argument("--workers", type=int, default=4, help="Number of concurrent workers")
  656. parser.add_argument("--parallel_requests", type=int, default=800, help="Max number of parallel requests to send to model")
  657. parser.add_argument("--model", default="google/gemma-3-12b-it", help="Model path or name, hugging face or local path format")
  658. parser.add_argument("--attribute_name", default="model_rich_pii_tagging", help="Path to use for attribute naming")
  659. # Beaker/job running stuff
  660. parser.add_argument("--beaker", action="store_true", help="Submit this job to beaker instead of running locally")
  661. parser.add_argument("--beaker_workspace", help="Beaker workspace to submit to", default="ai2/olmocr")
  662. parser.add_argument(
  663. "--beaker_cluster",
  664. help="Beaker clusters you want to run on",
  665. default=["ai2/jupiter-cirrascale-2", "ai2/ceres-cirrascale", "ai2/neptune-cirrascale", "ai2/saturn-cirrascale", "ai2/augusta-google-1"],
  666. )
  667. parser.add_argument("--beaker_gpus", type=int, default=1, help="Number of gpu replicas to run")
  668. parser.add_argument("--beaker_priority", type=str, default="normal", help="Beaker priority level for the job")
  669. parser.add_argument("--port", type=int, default=30026, help="Port for Model server")
  670. args = parser.parse_args()
  671. global SERVER_PORT, workspace_s3, dataset_s3
  672. SERVER_PORT = args.port
  673. workspace_s3 = boto3.client("s3")
  674. dataset_s3 = boto3.client("s3")
  675. # setup the job to work in beaker environment, load secrets, adjust logging, etc.
  676. if "BEAKER_JOB_ID" in os.environ:
  677. server_logger.addHandler(console_handler)
  678. if "AWS_CREDENTIALS_FILE" in os.environ:
  679. cred_path = os.path.join(os.path.expanduser("~"), ".aws", "credentials")
  680. os.makedirs(os.path.dirname(cred_path), exist_ok=True)
  681. with open(cred_path, "w") as f:
  682. f.write(os.environ.get("AWS_CREDENTIALS_FILE"))
  683. if "GOOGLE_APPLICATION_CREDENTIALS" in os.environ:
  684. cred_path = os.path.join(os.path.expanduser("~"), ".gcs", "credentials")
  685. os.makedirs(os.path.dirname(cred_path), exist_ok=True)
  686. with open(cred_path, "w") as f:
  687. f.write(os.environ.get("GOOGLE_APPLICATION_CREDENTIALS_FILE"))
  688. os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = cred_path
  689. workspace_s3 = boto3.client("s3")
  690. dataset_s3 = boto3.client("s3")
  691. # Wait a little bit so that not all beaker jobs in a task start at the same time and download the model at the same time
  692. replica_count = int(os.environ.get("BEAKER_REPLICA_COUNT", "1"))
  693. interval = 10 if (replica_count - 1) * 10 <= 240 else 240 / max(1, replica_count - 1)
  694. sleep_time = int(int(os.environ.get("BEAKER_REPLICA_RANK", "0")) * interval)
  695. logger.info(f"Beaker job sleeping for {sleep_time} seconds to stagger model downloads")
  696. await asyncio.sleep(sleep_time)
  697. # Initialize work queue
  698. if args.scratch.startswith("s3://"):
  699. work_queue = S3WorkQueue(workspace_s3, args.scratch)
  700. else:
  701. work_queue = LocalWorkQueue(args.scratch)
  702. # Discover input files
  703. files = set()
  704. if args.dataset.startswith("s3://"):
  705. pattern = args.dataset.rstrip("/") + "/documents/*.jsonl*"
  706. matched = expand_s3_glob(dataset_s3, pattern)
  707. files = set(matched.keys())
  708. else:
  709. docs_dir = os.path.join(args.dataset, "documents")
  710. for root, _, fns in os.walk(docs_dir):
  711. for fn in fns:
  712. if fn.endswith((".jsonl", ".jsonl.gz", ".jsonl.ztd")):
  713. files.add(os.path.join(root, fn))
  714. # Populate the work queue if needed
  715. await work_queue.populate_queue(list(files), items_per_group=1)
  716. if args.beaker:
  717. submit_beaker_job(args)
  718. return
  719. # If you get this far, then you are doing inference and need a GPU
  720. check_torch_gpu_available()
  721. logger.info(f"Starting pipeline with PID {os.getpid()}")
  722. # Download the model before you do anything else
  723. model_name_or_path = await download_model(args.model)
  724. # Initialize the work queue
  725. qsize = await work_queue.initialize_queue()
  726. if qsize == 0:
  727. logger.info("No work to do, exiting")
  728. return
  729. # Create a semaphore to control worker access
  730. # We only allow one worker to move forward with requests, until the server has no more requests in its queue
  731. # This lets us get full utilization by having many workers, but also to be outputting dolma docs as soon as possible
  732. # As soon as one worker is no longer saturating the gpu, the next one can start sending requests
  733. semaphore = asyncio.Semaphore(1)
  734. model_server = asyncio.create_task(server_host(model_name_or_path, args, semaphore))
  735. await check_server_ready()
  736. metrics_task = asyncio.create_task(metrics_reporter(work_queue))
  737. # Create worker tasks to process the queue concurrently.
  738. worker_tasks = []
  739. for i in range(args.workers):
  740. task = asyncio.create_task(worker(args, work_queue, semaphore, worker_id=i))
  741. worker_tasks.append(task)
  742. # Wait for all worker tasks to finish
  743. await asyncio.gather(*worker_tasks)
  744. model_server.cancel()
  745. metrics_task.cancel()
  746. logger.info("Work done")
  747. if __name__ == "__main__":
  748. asyncio.run(main())