andersoncliffb commited on
Commit
296ed1a
·
verified ·
1 Parent(s): f434b4c

Create glm-ocr-wandb.py

Browse files
Files changed (1) hide show
  1. glm-ocr-wandb.py +750 -0
glm-ocr-wandb.py ADDED
@@ -0,0 +1,750 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "datasets>=3.1.0",
5
+ # "huggingface-hub",
6
+ # "pillow",
7
+ # "vllm",
8
+ # "toolz",
9
+ # "torch",
10
+ # "weave",
11
+ # ]
12
+ #
13
+ # [[tool.uv.index]]
14
+ # url = "https://wheels.vllm.ai/nightly/cu129"
15
+ #
16
+ # [tool.uv]
17
+ # prerelease = "allow"
18
+ # override-dependencies = ["transformers>=5.1.0"]
19
+ # ///
20
+
21
+ """
22
+ Convert document images to markdown using GLM-OCR with vLLM, traced with W&B Weave.
23
+
24
+ Based on uv-scripts/ocr glm-ocr.py (commit 9a22cbb) by Daniel van Strien.
25
+ Adds Weave tracing: one root trace per run (main), a child call per batch
26
+ (ocr_batch), and a child call per page (ocr_page) with an image thumbnail
27
+ and the OCR output.
28
+
29
+ Weave setup:
30
+ WANDB_API_KEY CoreWeave Forge / W&B API key (pass as a secret)
31
+ WEAVE_PROJECT "entity/project" to log to (default: "glm-ocr")
32
+ WANDB_BASE_URL only if your W&B instance is not the default host
33
+
34
+ GLM-OCR is a compact 0.9B parameter OCR model achieving 94.62% on OmniDocBench V1.5.
35
+ Uses CogViT visual encoder with GLM-0.5B language decoder and Multi-Token Prediction
36
+ (MTP) loss for fast, accurate document parsing.
37
+
38
+ NOTE: Requires vLLM nightly wheels from cu129 variant (GLM-OCR added in v0.16.0,
39
+ PR #33005) and transformers>=5.1.0 (GLM-OCR support landed in stable release).
40
+ Uses https://wheels.vllm.ai/nightly/cu129 which has x86_64 wheels.
41
+ First run may take a few minutes to download and install dependencies.
42
+
43
+ Model: zai-org/GLM-OCR
44
+ """
45
+
46
+ import argparse
47
+ import base64
48
+ import io
49
+ import json
50
+ import logging
51
+ import os
52
+ import sys
53
+ import time
54
+ from datetime import datetime
55
+ from typing import Any, Dict, List, Optional, Union
56
+
57
+ import torch
58
+ import weave
59
+ from datasets import load_dataset
60
+ from huggingface_hub import DatasetCard, login
61
+ from PIL import Image
62
+ from toolz import partition_all
63
+
64
+ # Disable vLLM's FlashInfer sampler: it JIT-compiles a CUDA kernel needing nvcc, which the
65
+ # default uv-script image lacks (engine init then crashes). Greedy OCR doesn't use it; this
66
+ # lets the plain default-image command work. On the vllm/vllm-openai image it's a harmless no-op.
67
+ os.environ.setdefault("VLLM_USE_FLASHINFER_SAMPLER", "0")
68
+ # Same story for DeepGEMM (nightly vLLM): its init calls _find_cuda_home, which asserts on the
69
+ # nvcc-less base image (a non-fatal warning that clutters the log and hides the real traceback).
70
+ # Greedy OCR doesn't need the DeepGEMM JIT path, so disable it explicitly.
71
+ os.environ.setdefault("VLLM_USE_DEEP_GEMM", "0")
72
+
73
+ from vllm import LLM, SamplingParams
74
+
75
+ logging.basicConfig(level=logging.INFO)
76
+ logger = logging.getLogger(__name__)
77
+
78
+ MODEL = "zai-org/GLM-OCR"
79
+ THUMBNAIL_SIZE = (1024, 1024)
80
+
81
+ # Task prompts as specified by the model
82
+ TASK_PROMPTS = {
83
+ "ocr": "Text Recognition:",
84
+ "formula": "Formula Recognition:",
85
+ "table": "Table Recognition:",
86
+ }
87
+
88
+
89
+ def check_cuda_availability():
90
+ """Check if CUDA is available and exit if not."""
91
+ if not torch.cuda.is_available():
92
+ logger.error("CUDA is not available. This script requires a GPU.")
93
+ logger.error("Please run on a machine with a CUDA-capable GPU.")
94
+ sys.exit(1)
95
+ else:
96
+ logger.info(f"CUDA is available. GPU: {torch.cuda.get_device_name(0)}")
97
+
98
+
99
+ def ensure_output_columns_free(dataset, columns, overwrite=False):
100
+ """Fail fast if an output column would collide with an existing input column.
101
+
102
+ Adding a column that already exists silently overwrites it (e.g. a ground-truth
103
+ `text`/`markdown` column) or crashes on push with a duplicate-column error only
104
+ *after* inference has run. Catch it up front. With overwrite=True, drop the clashing
105
+ column(s) here instead (logged) so the later add_column is clean.
106
+ """
107
+ clash = [c for c in columns if c in dataset.column_names]
108
+ if not clash:
109
+ return dataset
110
+ if overwrite:
111
+ logger.warning(f"--overwrite: replacing existing column(s) {clash}")
112
+ return dataset.remove_columns(clash)
113
+ logger.error(
114
+ f"Output column(s) {clash} already exist in the input dataset "
115
+ f"(columns: {dataset.column_names})."
116
+ )
117
+ logger.error("Choose a different --output-column, or pass --overwrite to replace them.")
118
+ sys.exit(1)
119
+
120
+
121
+ def downscale_to_max_pixels(img: Image.Image, max_pixels: Optional[int]) -> Image.Image:
122
+ """Shrink an image so width*height <= max_pixels, preserving aspect ratio.
123
+
124
+ GLM-OCR does no internal resizing and its card gives no resolution guidance. Capping
125
+ input pixels bounds both image tokens and vision-encoder memory, a safety valve for very
126
+ large (multi-MP) scans that can pressure GPU memory at high batch sizes. No-op when
127
+ max_pixels is None or the image is already small enough (never upscales)."""
128
+ if not max_pixels:
129
+ return img
130
+ w, h = img.size
131
+ if w * h <= max_pixels:
132
+ return img
133
+ scale = (max_pixels / (w * h)) ** 0.5
134
+ new_size = (max(1, int(w * scale)), max(1, int(h * scale)))
135
+ return img.resize(new_size, Image.Resampling.LANCZOS)
136
+
137
+
138
+ def to_pil(image: Union[Image.Image, Dict[str, Any], str]) -> Image.Image:
139
+ """Convert a dataset image value to a PIL Image."""
140
+ if isinstance(image, Image.Image):
141
+ return image
142
+ if isinstance(image, dict) and "bytes" in image:
143
+ return Image.open(io.BytesIO(image["bytes"]))
144
+ if isinstance(image, str):
145
+ return Image.open(image)
146
+ raise ValueError(f"Unsupported image type: {type(image)}")
147
+
148
+
149
+ def make_ocr_message(
150
+ image: Union[Image.Image, Dict[str, Any], str],
151
+ task: str = "ocr",
152
+ max_pixels: Optional[int] = None,
153
+ ) -> List[Dict]:
154
+ """
155
+ Create chat message for OCR processing.
156
+
157
+ GLM-OCR uses a chat format with an image and a task prompt prefix.
158
+ Supported tasks: ocr, formula, table.
159
+ """
160
+ pil_img = to_pil(image).convert("RGB")
161
+
162
+ # Optionally cap resolution to protect the vision encoder from OOM on huge scans
163
+ pil_img = downscale_to_max_pixels(pil_img, max_pixels)
164
+
165
+ # Convert to base64 data URI
166
+ buf = io.BytesIO()
167
+ pil_img.save(buf, format="PNG")
168
+ data_uri = f"data:image/png;base64,{base64.b64encode(buf.getvalue()).decode()}"
169
+
170
+ prompt_text = TASK_PROMPTS.get(task, TASK_PROMPTS["ocr"])
171
+
172
+ return [
173
+ {
174
+ "role": "user",
175
+ "content": [
176
+ {"type": "image_url", "image_url": {"url": data_uri}},
177
+ {"type": "text", "text": prompt_text},
178
+ ],
179
+ }
180
+ ]
181
+
182
+
183
+ # ---------------------------------------------------------------------------
184
+ # Weave-traced operations
185
+ # ---------------------------------------------------------------------------
186
+
187
+
188
+ @weave.op
189
+ def ocr_page(index: int, image: Image.Image, text: str) -> str:
190
+ """Record one page (thumbnail + OCR output) as a child call of its batch."""
191
+ return text
192
+
193
+
194
+ @weave.op(
195
+ postprocess_inputs=lambda d: {
196
+ "batch_num": d["batch_num"],
197
+ "indices": d["indices"],
198
+ "n_images": len(d["images"]),
199
+ "task": d["task"],
200
+ "max_pixels": d["max_pixels"],
201
+ }
202
+ )
203
+ def ocr_batch(
204
+ llm,
205
+ images: list,
206
+ indices: list,
207
+ batch_num: int,
208
+ sampling_params,
209
+ task: str,
210
+ max_pixels: Optional[int],
211
+ ) -> List[str]:
212
+ """Run one vLLM batch; full-resolution images and engine objects are not logged."""
213
+ messages = [make_ocr_message(img, task=task, max_pixels=max_pixels) for img in images]
214
+ outputs = llm.chat(messages, sampling_params)
215
+ texts = [o.outputs[0].text.strip() for o in outputs]
216
+
217
+ for idx, img, text in zip(indices, images, texts):
218
+ thumb = to_pil(img).convert("RGB")
219
+ thumb.thumbnail(THUMBNAIL_SIZE)
220
+ ocr_page(idx, thumb, text)
221
+
222
+ return texts
223
+
224
+
225
+ def create_dataset_card(
226
+ source_dataset: str,
227
+ model: str,
228
+ num_samples: int,
229
+ processing_time: str,
230
+ batch_size: int,
231
+ max_model_len: int,
232
+ max_tokens: int,
233
+ gpu_memory_utilization: float,
234
+ temperature: float,
235
+ top_p: float,
236
+ task: str,
237
+ image_column: str = "image",
238
+ split: str = "train",
239
+ ) -> str:
240
+ """Create a dataset card documenting the OCR process."""
241
+ model_name = model.split("/")[-1]
242
+ task_desc = {
243
+ "ocr": "text recognition",
244
+ "formula": "formula recognition",
245
+ "table": "table recognition",
246
+ }
247
+
248
+ # Canonical provenance stamp: Jobs claim gated on JOB_ID, set by HF Jobs in-container.
249
+ on_jobs = os.environ.get("JOB_ID") is not None
250
+ hw = os.environ.get("ACCELERATOR") or ""
251
+ origin = (
252
+ "Produced on [Hugging Face Jobs](https://huggingface.co/docs/huggingface_hub/guides/jobs)"
253
+ + (f" (`{hw}`)" if hw else "")
254
+ ) if on_jobs else "Generated"
255
+ jobs_tag = "\n- hf-jobs" if on_jobs else ""
256
+
257
+ return f"""---
258
+ tags:
259
+ - ocr
260
+ - document-processing
261
+ - glm-ocr
262
+ - markdown
263
+ - uv-script
264
+ - generated{jobs_tag}
265
+ ---
266
+
267
+ # Document OCR using {model_name}
268
+
269
+ This dataset contains OCR results from images in [{source_dataset}](https://huggingface.co/datasets/{source_dataset}) using GLM-OCR, a compact 0.9B OCR model achieving SOTA performance.
270
+
271
+ ## Processing Details
272
+
273
+ - **Source Dataset**: [{source_dataset}](https://huggingface.co/datasets/{source_dataset})
274
+ - **Model**: [{model}](https://huggingface.co/{model})
275
+ - **Task**: {task_desc.get(task, task)}
276
+ - **Number of Samples**: {num_samples:,}
277
+ - **Processing Time**: {processing_time}
278
+ - **Processing Date**: {datetime.now().strftime("%Y-%m-%d %H:%M UTC")}
279
+
280
+ ### Configuration
281
+
282
+ - **Image Column**: `{image_column}`
283
+ - **Output Column**: `markdown`
284
+ - **Dataset Split**: `{split}`
285
+ - **Batch Size**: {batch_size}
286
+ - **Max Model Length**: {max_model_len:,} tokens
287
+ - **Max Output Tokens**: {max_tokens:,}
288
+ - **Temperature**: {temperature}
289
+ - **Top P**: {top_p}
290
+ - **GPU Memory Utilization**: {gpu_memory_utilization:.1%}
291
+
292
+ ## Model Information
293
+
294
+ GLM-OCR is a compact, high-performance OCR model:
295
+ - 0.9B parameters
296
+ - 94.62% on OmniDocBench V1.5
297
+ - CogViT visual encoder + GLM-0.5B language decoder
298
+ - Multi-Token Prediction (MTP) loss for efficiency
299
+ - Multilingual: zh, en, fr, es, ru, de, ja, ko
300
+ - MIT licensed
301
+
302
+ ## Dataset Structure
303
+
304
+ The dataset contains all original columns plus:
305
+ - `markdown`: The extracted text in markdown format
306
+ - `inference_info`: JSON list tracking all OCR models applied to this dataset
307
+
308
+ ## Reproduction
309
+
310
+ {origin} with a Weave-traced variant of the [`glm-ocr.py`](https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py) recipe from [uv-scripts](https://huggingface.co/uv-scripts). To run the original:
311
+
312
+ ```bash
313
+ hf jobs uv run https://huggingface.co/datasets/uv-scripts/ocr/raw/main/glm-ocr.py \\
314
+ {source_dataset} \\
315
+ <output-dataset> \\
316
+ --image-column {image_column} \\
317
+ --batch-size {batch_size} \\
318
+ --task {task}
319
+ ```
320
+ """
321
+
322
+
323
+ @weave.op(postprocess_inputs=lambda d: {k: v for k, v in d.items() if k != "hf_token"})
324
+ def main(
325
+ input_dataset: str,
326
+ output_dataset: str,
327
+ image_column: str = "image",
328
+ batch_size: int = 16,
329
+ max_model_len: int = 8192,
330
+ max_pixels: Optional[int] = None,
331
+ max_tokens: int = 8192,
332
+ temperature: float = 0.01,
333
+ top_p: float = 0.00001,
334
+ repetition_penalty: float = 1.1,
335
+ gpu_memory_utilization: float = 0.8,
336
+ task: str = "ocr",
337
+ hf_token: str = None,
338
+ split: str = "train",
339
+ max_samples: int = None,
340
+ private: bool = False,
341
+ shuffle: bool = False,
342
+ seed: int = 42,
343
+ output_column: str = "markdown",
344
+ overwrite: bool = False,
345
+ verbose: bool = False,
346
+ config: str = None,
347
+ create_pr: bool = False,
348
+ ):
349
+ """Process images from HF dataset through GLM-OCR model."""
350
+ check_cuda_availability()
351
+
352
+ start_time = datetime.now()
353
+
354
+ HF_TOKEN = hf_token or os.environ.get("HF_TOKEN")
355
+ if HF_TOKEN:
356
+ login(token=HF_TOKEN)
357
+
358
+ # Validate task
359
+ if task not in TASK_PROMPTS:
360
+ logger.error(f"Unknown task '{task}'. Supported: {list(TASK_PROMPTS.keys())}")
361
+ sys.exit(1)
362
+
363
+ logger.info(f"Using model: {MODEL}")
364
+ logger.info(f"Task: {task} (prompt: '{TASK_PROMPTS[task]}')")
365
+
366
+ # Load dataset
367
+ logger.info(f"Loading dataset: {input_dataset}")
368
+ dataset = load_dataset(input_dataset, split=split)
369
+
370
+ if image_column not in dataset.column_names:
371
+ raise ValueError(
372
+ f"Column '{image_column}' not found. Available: {dataset.column_names}"
373
+ )
374
+
375
+ # Fail fast if the output column would collide with an existing input column
376
+ dataset = ensure_output_columns_free(dataset, [output_column], overwrite=overwrite)
377
+
378
+ if shuffle:
379
+ logger.info(f"Shuffling dataset with seed {seed}")
380
+ dataset = dataset.shuffle(seed=seed)
381
+
382
+ if max_samples:
383
+ dataset = dataset.select(range(min(max_samples, len(dataset))))
384
+ logger.info(f"Limited to {len(dataset)} samples")
385
+
386
+ # Initialize vLLM
387
+ logger.info("Initializing vLLM with GLM-OCR")
388
+ logger.info("This may take a few minutes on first run...")
389
+ llm = LLM(
390
+ model=MODEL,
391
+ trust_remote_code=True,
392
+ max_model_len=max_model_len,
393
+ gpu_memory_utilization=gpu_memory_utilization,
394
+ limit_mm_per_prompt={"image": 1},
395
+ )
396
+
397
+ # Sampling defaults from GLM-OCR SDK (github.com/zai-org/GLM-OCR)
398
+ # glmocr/config.py PageLoaderConfig: temperature=0.01, top_p=0.00001,
399
+ # top_k=1, repetition_penalty=1.1, max_tokens=16384
400
+ # generation_config.json on HF also sets do_sample=false (greedy)
401
+ # Note: SDK uses max_tokens=16384 but vLLM caps at max_model_len (8192)
402
+ sampling_params = SamplingParams(
403
+ temperature=temperature,
404
+ top_p=top_p,
405
+ max_tokens=max_tokens,
406
+ repetition_penalty=repetition_penalty,
407
+ )
408
+
409
+ logger.info(f"Processing {len(dataset)} images in batches of {batch_size}")
410
+ logger.info(f"Output will be written to column: {output_column}")
411
+
412
+ all_outputs = []
413
+ total_batches = (len(dataset) + batch_size - 1) // batch_size
414
+ processed = 0
415
+
416
+ for batch_num, batch_indices in enumerate(
417
+ partition_all(batch_size, range(len(dataset))), 1
418
+ ):
419
+ batch_indices = list(batch_indices)
420
+ batch_images = [dataset[i][image_column] for i in batch_indices]
421
+
422
+ logger.info(
423
+ f"Batch {batch_num}/{total_batches} "
424
+ f"({processed}/{len(dataset)} images done)"
425
+ )
426
+
427
+ try:
428
+ texts = ocr_batch(
429
+ llm,
430
+ batch_images,
431
+ batch_indices,
432
+ batch_num,
433
+ sampling_params,
434
+ task,
435
+ max_pixels,
436
+ )
437
+ all_outputs.extend(texts)
438
+ processed += len(batch_images)
439
+
440
+ except Exception as e:
441
+ # The exception is already recorded on the ocr_batch call in Weave
442
+ logger.error(f"Error processing batch: {e}")
443
+ all_outputs.extend(["[OCR ERROR]"] * len(batch_images))
444
+ processed += len(batch_images)
445
+
446
+ processing_duration = datetime.now() - start_time
447
+ processing_time_str = f"{processing_duration.total_seconds() / 60:.1f} min"
448
+
449
+ logger.info(f"Adding '{output_column}' column to dataset")
450
+ dataset = dataset.add_column(output_column, all_outputs)
451
+
452
+ # Inference info tracking
453
+ inference_entry = {
454
+ "model_id": MODEL,
455
+ "model_name": "GLM-OCR",
456
+ "column_name": output_column,
457
+ "timestamp": datetime.now().isoformat(),
458
+ "task": task,
459
+ "temperature": temperature,
460
+ "top_p": top_p,
461
+ "repetition_penalty": repetition_penalty,
462
+ "max_tokens": max_tokens,
463
+ }
464
+
465
+ if "inference_info" in dataset.column_names:
466
+ logger.info("Updating existing inference_info column")
467
+
468
+ def update_inference_info(example):
469
+ try:
470
+ existing_info = (
471
+ json.loads(example["inference_info"])
472
+ if example["inference_info"]
473
+ else []
474
+ )
475
+ except (json.JSONDecodeError, TypeError):
476
+ existing_info = []
477
+ existing_info.append(inference_entry)
478
+ return {"inference_info": json.dumps(existing_info)}
479
+
480
+ dataset = dataset.map(update_inference_info)
481
+ else:
482
+ logger.info("Creating new inference_info column")
483
+ inference_list = [json.dumps([inference_entry])] * len(dataset)
484
+ dataset = dataset.add_column("inference_info", inference_list)
485
+
486
+ # Push to hub with retry and XET fallback
487
+ logger.info(f"Pushing to {output_dataset}")
488
+ max_retries = 3
489
+ for attempt in range(1, max_retries + 1):
490
+ try:
491
+ if attempt > 1:
492
+ logger.warning("Disabling XET (fallback to HTTP upload)")
493
+ os.environ["HF_HUB_DISABLE_XET"] = "1"
494
+ dataset.push_to_hub(
495
+ output_dataset,
496
+ private=private,
497
+ token=HF_TOKEN,
498
+ max_shard_size="500MB",
499
+ **({"config_name": config} if config else {}),
500
+ create_pr=create_pr,
501
+ commit_message=f"Add {MODEL} OCR results ({len(dataset)} samples)"
502
+ + (f" [{config}]" if config else ""),
503
+ )
504
+ break
505
+ except Exception as e:
506
+ logger.error(f"Upload attempt {attempt}/{max_retries} failed: {e}")
507
+ if attempt < max_retries:
508
+ delay = 30 * (2 ** (attempt - 1))
509
+ logger.info(f"Retrying in {delay}s...")
510
+ time.sleep(delay)
511
+ else:
512
+ logger.error("All upload attempts failed. OCR results are lost.")
513
+ sys.exit(1)
514
+
515
+ # Create and push dataset card
516
+ logger.info("Creating dataset card")
517
+ card_content = create_dataset_card(
518
+ source_dataset=input_dataset,
519
+ model=MODEL,
520
+ num_samples=len(dataset),
521
+ processing_time=processing_time_str,
522
+ batch_size=batch_size,
523
+ max_model_len=max_model_len,
524
+ max_tokens=max_tokens,
525
+ gpu_memory_utilization=gpu_memory_utilization,
526
+ temperature=temperature,
527
+ top_p=top_p,
528
+ task=task,
529
+ image_column=image_column,
530
+ split=split,
531
+ )
532
+
533
+ card = DatasetCard(card_content)
534
+ card.push_to_hub(output_dataset, token=HF_TOKEN)
535
+
536
+ logger.info("Done! GLM-OCR processing complete.")
537
+ logger.info(
538
+ f"Dataset available at: https://huggingface.co/datasets/{output_dataset}"
539
+ )
540
+ logger.info(f"Processing time: {processing_time_str}")
541
+ logger.info(
542
+ f"Processing speed: {len(dataset) / processing_duration.total_seconds():.2f} images/sec"
543
+ )
544
+
545
+ if verbose:
546
+ import importlib.metadata
547
+
548
+ logger.info("--- Resolved package versions ---")
549
+ for pkg in ["vllm", "transformers", "torch", "datasets", "pyarrow", "pillow", "weave"]:
550
+ try:
551
+ logger.info(f" {pkg}=={importlib.metadata.version(pkg)}")
552
+ except importlib.metadata.PackageNotFoundError:
553
+ logger.info(f" {pkg}: not installed")
554
+ logger.info("--- End versions ---")
555
+
556
+ return {
557
+ "output_dataset": output_dataset,
558
+ "num_samples": len(dataset),
559
+ "num_errors": sum(1 for t in all_outputs if t == "[OCR ERROR]"),
560
+ "processing_seconds": processing_duration.total_seconds(),
561
+ }
562
+
563
+
564
+ if __name__ == "__main__":
565
+ if len(sys.argv) == 1:
566
+ print("=" * 70)
567
+ print("GLM-OCR Document Processing (Weave-traced)")
568
+ print("=" * 70)
569
+ print("\n0.9B OCR model - 94.62% on OmniDocBench V1.5")
570
+ print("\nTask modes:")
571
+ print(" ocr - Text recognition (default)")
572
+ print(" formula - LaTeX formula recognition")
573
+ print(" table - Table extraction")
574
+ print("\nRunning on HF Jobs:")
575
+ print(" hf jobs uv run --flavor l4x1 \\")
576
+ print(" -s HF_TOKEN -s WANDB_API_KEY \\")
577
+ print(" -e WEAVE_PROJECT=entity/project \\")
578
+ print(" glm-ocr-weave.py input-dataset output-dataset --batch-size 16")
579
+ print("\nFor full help: uv run glm-ocr-weave.py --help")
580
+ sys.exit(0)
581
+
582
+ parser = argparse.ArgumentParser(
583
+ description="Document OCR using GLM-OCR (0.9B, 94.62% OmniDocBench V1.5), traced with W&B Weave",
584
+ formatter_class=argparse.RawDescriptionHelpFormatter,
585
+ epilog="""
586
+ Task modes:
587
+ ocr Text recognition to markdown (default)
588
+ formula LaTeX formula recognition
589
+ table Table extraction
590
+
591
+ Environment:
592
+ WANDB_API_KEY W&B / CoreWeave Forge API key
593
+ WEAVE_PROJECT Weave project as entity/project (default: glm-ocr)
594
+
595
+ Examples:
596
+ uv run glm-ocr-weave.py my-docs analyzed-docs
597
+ uv run glm-ocr-weave.py docs results --task formula
598
+ uv run glm-ocr-weave.py large-dataset test --max-samples 50 --shuffle
599
+ """,
600
+ )
601
+
602
+ parser.add_argument("input_dataset", help="Input dataset ID from Hugging Face Hub")
603
+ parser.add_argument("output_dataset", help="Output dataset ID for Hugging Face Hub")
604
+ parser.add_argument(
605
+ "--image-column",
606
+ default="image",
607
+ help="Column containing images (default: image)",
608
+ )
609
+ parser.add_argument(
610
+ "--batch-size",
611
+ type=int,
612
+ default=16,
613
+ help="Batch size for processing (default: 16)",
614
+ )
615
+ parser.add_argument(
616
+ "--max-model-len",
617
+ type=int,
618
+ default=8192,
619
+ help="Maximum model context length (default: 8192)",
620
+ )
621
+ parser.add_argument(
622
+ "--max-pixels",
623
+ type=int,
624
+ default=None,
625
+ help=(
626
+ "Optional cap on input image pixels (width*height); larger scans are "
627
+ "downscaled (aspect preserved) before OCR. Default: no cap."
628
+ ),
629
+ )
630
+ parser.add_argument(
631
+ "--max-tokens",
632
+ type=int,
633
+ default=8192,
634
+ help="Maximum tokens to generate (default: 8192, capped by max-model-len)",
635
+ )
636
+ parser.add_argument(
637
+ "--temperature",
638
+ type=float,
639
+ default=0.01,
640
+ help="Sampling temperature (default: 0.01, near-greedy for OCR accuracy)",
641
+ )
642
+ parser.add_argument(
643
+ "--top-p",
644
+ type=float,
645
+ default=0.00001,
646
+ help="Top-p sampling parameter (default: 0.00001, near-greedy)",
647
+ )
648
+ parser.add_argument(
649
+ "--repetition-penalty",
650
+ type=float,
651
+ default=1.1,
652
+ help="Repetition penalty to prevent loops (default: 1.1)",
653
+ )
654
+ parser.add_argument(
655
+ "--gpu-memory-utilization",
656
+ type=float,
657
+ default=0.8,
658
+ help="GPU memory utilization (default: 0.8)",
659
+ )
660
+ parser.add_argument(
661
+ "--task",
662
+ choices=["ocr", "formula", "table"],
663
+ default="ocr",
664
+ help="OCR task mode (default: ocr)",
665
+ )
666
+ parser.add_argument("--hf-token", help="Hugging Face API token")
667
+ parser.add_argument(
668
+ "--split", default="train", help="Dataset split to use (default: train)"
669
+ )
670
+ parser.add_argument(
671
+ "--max-samples",
672
+ type=int,
673
+ help="Maximum number of samples to process (for testing)",
674
+ )
675
+ parser.add_argument(
676
+ "--private", action="store_true", help="Make output dataset private"
677
+ )
678
+ parser.add_argument(
679
+ "--config",
680
+ help="Config/subset name when pushing to Hub (for benchmarking multiple models in one repo)",
681
+ )
682
+ parser.add_argument(
683
+ "--create-pr",
684
+ action="store_true",
685
+ help="Create a pull request instead of pushing directly (for parallel benchmarking)",
686
+ )
687
+ parser.add_argument(
688
+ "--shuffle", action="store_true", help="Shuffle dataset before processing"
689
+ )
690
+ parser.add_argument(
691
+ "--seed",
692
+ type=int,
693
+ default=42,
694
+ help="Random seed for shuffling (default: 42)",
695
+ )
696
+ parser.add_argument(
697
+ "--output-column",
698
+ default="markdown",
699
+ help="Column name for output text (default: markdown)",
700
+ )
701
+ parser.add_argument(
702
+ "--overwrite",
703
+ action="store_true",
704
+ help="Replace the output column if it already exists in the input dataset "
705
+ "(default: error out to avoid clobbering an existing column).",
706
+ )
707
+ parser.add_argument(
708
+ "--verbose",
709
+ action="store_true",
710
+ help="Log resolved package versions after processing (useful for pinning deps)",
711
+ )
712
+
713
+ args = parser.parse_args()
714
+
715
+ weave.init(os.environ.get("WEAVE_PROJECT", "glm-ocr"))
716
+
717
+ with weave.attributes(
718
+ {
719
+ "hf_job_id": os.environ.get("JOB_ID"),
720
+ "accelerator": os.environ.get("ACCELERATOR"),
721
+ "script": "glm-ocr-weave.py",
722
+ }
723
+ ):
724
+ main(
725
+ input_dataset=args.input_dataset,
726
+ output_dataset=args.output_dataset,
727
+ image_column=args.image_column,
728
+ batch_size=args.batch_size,
729
+ max_model_len=args.max_model_len,
730
+ max_pixels=args.max_pixels,
731
+ max_tokens=args.max_tokens,
732
+ temperature=args.temperature,
733
+ top_p=args.top_p,
734
+ repetition_penalty=args.repetition_penalty,
735
+ gpu_memory_utilization=args.gpu_memory_utilization,
736
+ task=args.task,
737
+ hf_token=args.hf_token,
738
+ split=args.split,
739
+ max_samples=args.max_samples,
740
+ private=args.private,
741
+ shuffle=args.shuffle,
742
+ seed=args.seed,
743
+ output_column=args.output_column,
744
+ overwrite=args.overwrite,
745
+ verbose=args.verbose,
746
+ config=args.config,
747
+ create_pr=args.create_pr,
748
+ )
749
+
750
+ weave.finish()