tagging_pipeline.py 31 KB

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