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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# /// script
|
| 3 |
+
# requires-python = ">=3.11"
|
| 4 |
+
# dependencies = [
|
| 5 |
+
# "datasets>=4.0.0",
|
| 6 |
+
# "huggingface-hub",
|
| 7 |
+
# "pillow",
|
| 8 |
+
# "vllm>=0.9.1",
|
| 9 |
+
# "torch",
|
| 10 |
+
# "rich",
|
| 11 |
+
# "tqdm",
|
| 12 |
+
# ]
|
| 13 |
+
# ///
|
| 14 |
+
"""
|
| 15 |
+
Offline vLLM judge for OCR benchmark evaluation.
|
| 16 |
+
|
| 17 |
+
Runs pairwise OCR quality comparisons using a local VLM judge via vLLM's
|
| 18 |
+
offline LLM() pattern. Supports jury mode (multiple models vote sequentially
|
| 19 |
+
on the same GPU) with majority voting.
|
| 20 |
+
|
| 21 |
+
Advantages over API-based judging (ocr-jury-bench.py):
|
| 22 |
+
- Zero network failures — everything runs locally
|
| 23 |
+
- vLLM structured output guarantees valid JSON (no parse retries)
|
| 24 |
+
- Batch processing is faster than sequential API calls
|
| 25 |
+
- Any vLLM-supported VLM can be used as judge
|
| 26 |
+
|
| 27 |
+
Usage:
|
| 28 |
+
# Single judge
|
| 29 |
+
uv run ocr-vllm-judge.py davanstrien/ocr-bench-nls-50 --from-prs \\
|
| 30 |
+
--judge-model Qwen/Qwen2.5-VL-7B-Instruct --max-samples 3
|
| 31 |
+
|
| 32 |
+
# Jury of 2 models (sequential on same GPU)
|
| 33 |
+
uv run ocr-vllm-judge.py davanstrien/ocr-bench-nls-50 --from-prs \\
|
| 34 |
+
--judge-model Qwen/Qwen3-VL-8B-Instruct \\
|
| 35 |
+
--judge-model Qwen/Qwen2.5-VL-7B-Instruct \\
|
| 36 |
+
--max-samples 50
|
| 37 |
+
|
| 38 |
+
# Via HF Job
|
| 39 |
+
hf jobs uv run --flavor l4x1 -s HF_TOKEN \\
|
| 40 |
+
ocr-vllm-judge.py davanstrien/ocr-bench-nls-50 --from-prs \\
|
| 41 |
+
--judge-model Qwen/Qwen3-VL-8B-Instruct --max-samples 50
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
import argparse
|
| 45 |
+
import base64
|
| 46 |
+
import gc
|
| 47 |
+
import io
|
| 48 |
+
import json
|
| 49 |
+
import logging
|
| 50 |
+
import random
|
| 51 |
+
import sys
|
| 52 |
+
from collections import Counter
|
| 53 |
+
from itertools import combinations
|
| 54 |
+
from typing import NamedTuple
|
| 55 |
+
|
| 56 |
+
import torch
|
| 57 |
+
from datasets import Dataset, load_dataset
|
| 58 |
+
from huggingface_hub import HfApi
|
| 59 |
+
from PIL import Image
|
| 60 |
+
from rich.console import Console
|
| 61 |
+
from rich.table import Table
|
| 62 |
+
|
| 63 |
+
logging.basicConfig(
|
| 64 |
+
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
|
| 65 |
+
)
|
| 66 |
+
logger = logging.getLogger(__name__)
|
| 67 |
+
console = Console()
|
| 68 |
+
|
| 69 |
+
# --- ELO ---
|
| 70 |
+
INITIAL_ELO = 1500
|
| 71 |
+
K = 32
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def update_elo(elo_a: float, elo_b: float, winner: str) -> tuple[float, float]:
|
| 75 |
+
expected_a = 1 / (1 + 10 ** ((elo_b - elo_a) / 400))
|
| 76 |
+
if winner == "A":
|
| 77 |
+
score_a = 1.0
|
| 78 |
+
elif winner == "B":
|
| 79 |
+
score_a = 0.0
|
| 80 |
+
else: # tie
|
| 81 |
+
score_a = 0.5
|
| 82 |
+
elo_a += K * (score_a - expected_a)
|
| 83 |
+
elo_b += K * ((1 - score_a) - (1 - expected_a))
|
| 84 |
+
return elo_a, elo_b
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# --- Image helpers ---
|
| 88 |
+
def image_to_base64(image: Image.Image) -> str:
|
| 89 |
+
if image.mode != "RGB":
|
| 90 |
+
image = image.convert("RGB")
|
| 91 |
+
max_dim = 1024
|
| 92 |
+
if max(image.size) > max_dim:
|
| 93 |
+
ratio = max_dim / max(image.size)
|
| 94 |
+
new_size = (int(image.width * ratio), int(image.height * ratio))
|
| 95 |
+
image = image.resize(new_size, Image.Resampling.LANCZOS)
|
| 96 |
+
buf = io.BytesIO()
|
| 97 |
+
image.save(buf, format="PNG")
|
| 98 |
+
return base64.b64encode(buf.getvalue()).decode()
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
# --- Judge prompt ---
|
| 102 |
+
PAIRWISE_PROMPT = """You are an expert OCR quality evaluator. You are given a document image and TWO OCR outputs (A and B) extracted from that same image.
|
| 103 |
+
|
| 104 |
+
Compare them and decide which extraction is better overall. Consider:
|
| 105 |
+
- Accuracy: correct characters, no hallucinations
|
| 106 |
+
- Completeness: all text captured
|
| 107 |
+
- Formatting: clean structure (ignore bounding box tags like <|ref|> <|det|> if present)
|
| 108 |
+
- Reading order: natural flow
|
| 109 |
+
|
| 110 |
+
Output A:
|
| 111 |
+
---
|
| 112 |
+
{ocr_text_a}
|
| 113 |
+
---
|
| 114 |
+
|
| 115 |
+
Output B:
|
| 116 |
+
---
|
| 117 |
+
{ocr_text_b}
|
| 118 |
+
---
|
| 119 |
+
|
| 120 |
+
Respond with JSON only (no markdown fences, no extra text):
|
| 121 |
+
{{"winner": "A", "reason": "brief explanation"}}
|
| 122 |
+
Use "A", "B", or "tie" for the winner field."""
|
| 123 |
+
|
| 124 |
+
# JSON schema for structured output
|
| 125 |
+
JUDGE_SCHEMA = {
|
| 126 |
+
"type": "object",
|
| 127 |
+
"properties": {
|
| 128 |
+
"winner": {"type": "string", "enum": ["A", "B", "tie"]},
|
| 129 |
+
"reason": {"type": "string"},
|
| 130 |
+
},
|
| 131 |
+
"required": ["winner", "reason"],
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
class Comparison(NamedTuple):
|
| 136 |
+
"""A single pairwise comparison to evaluate."""
|
| 137 |
+
|
| 138 |
+
sample_idx: int
|
| 139 |
+
model_a: str
|
| 140 |
+
model_b: str
|
| 141 |
+
col_a: str
|
| 142 |
+
col_b: str
|
| 143 |
+
swapped: bool # True if A/B labels were swapped for position-bias mitigation
|
| 144 |
+
messages: list # Chat messages for vLLM
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# --- Data loading (adapted from ocr-jury-bench.py) ---
|
| 148 |
+
def discover_ocr_columns(dataset) -> dict[str, str]:
|
| 149 |
+
columns = {}
|
| 150 |
+
try:
|
| 151 |
+
info_raw = dataset[0].get("inference_info")
|
| 152 |
+
if not info_raw:
|
| 153 |
+
return columns
|
| 154 |
+
info = json.loads(info_raw)
|
| 155 |
+
if not isinstance(info, list):
|
| 156 |
+
info = [info]
|
| 157 |
+
for entry in info:
|
| 158 |
+
col = entry.get("column_name", "")
|
| 159 |
+
model = entry.get("model_id", entry.get("model_name", "unknown"))
|
| 160 |
+
if col and col in dataset.column_names:
|
| 161 |
+
columns[col] = model
|
| 162 |
+
except (json.JSONDecodeError, TypeError, KeyError) as e:
|
| 163 |
+
logger.warning(f"Could not parse inference_info: {e}")
|
| 164 |
+
|
| 165 |
+
if not columns:
|
| 166 |
+
for col in dataset.column_names:
|
| 167 |
+
if "markdown" in col.lower() or "ocr" in col.lower() or "text" == col:
|
| 168 |
+
columns[col] = col
|
| 169 |
+
|
| 170 |
+
model_counts = {}
|
| 171 |
+
for model in columns.values():
|
| 172 |
+
model_counts[model] = model_counts.get(model, 0) + 1
|
| 173 |
+
|
| 174 |
+
disambiguated = {}
|
| 175 |
+
for col, model in columns.items():
|
| 176 |
+
if model_counts[model] > 1:
|
| 177 |
+
short_model = model.split("/")[-1] if "/" in model else model
|
| 178 |
+
disambiguated[col] = f"{short_model} ({col})"
|
| 179 |
+
else:
|
| 180 |
+
disambiguated[col] = model
|
| 181 |
+
|
| 182 |
+
return disambiguated
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def load_benchmark_dataset(args):
|
| 186 |
+
"""Load dataset from configs/PRs/flat mode. Returns (dataset, ocr_columns)."""
|
| 187 |
+
api = HfApi()
|
| 188 |
+
pr_revisions = {}
|
| 189 |
+
|
| 190 |
+
if args.from_prs or args.merge_prs:
|
| 191 |
+
console.print(f"\n[bold]Checking PRs on:[/bold] {args.dataset}")
|
| 192 |
+
discussions = api.get_repo_discussions(
|
| 193 |
+
args.dataset,
|
| 194 |
+
repo_type="dataset",
|
| 195 |
+
discussion_type="pull_request",
|
| 196 |
+
discussion_status="open",
|
| 197 |
+
)
|
| 198 |
+
prs = list(discussions)
|
| 199 |
+
|
| 200 |
+
if not prs:
|
| 201 |
+
console.print("[yellow]No open PRs found.[/yellow]")
|
| 202 |
+
else:
|
| 203 |
+
for pr in prs:
|
| 204 |
+
title = pr.title
|
| 205 |
+
config_name = None
|
| 206 |
+
if "[" in title and title.endswith("]"):
|
| 207 |
+
config_name = title.rsplit("[", 1)[1].rstrip("]")
|
| 208 |
+
|
| 209 |
+
if config_name:
|
| 210 |
+
console.print(
|
| 211 |
+
f" PR #{pr.num}: {title} -> config [cyan]{config_name}[/cyan]"
|
| 212 |
+
)
|
| 213 |
+
pr_revisions[config_name] = f"refs/pr/{pr.num}"
|
| 214 |
+
|
| 215 |
+
if args.merge_prs:
|
| 216 |
+
console.print(f" Merging PR #{pr.num}...")
|
| 217 |
+
api.merge_pull_request(
|
| 218 |
+
args.dataset,
|
| 219 |
+
pr.num,
|
| 220 |
+
repo_type="dataset",
|
| 221 |
+
comment="Auto-merged by ocr-vllm-judge.py",
|
| 222 |
+
)
|
| 223 |
+
pr_revisions[config_name] = "main"
|
| 224 |
+
else:
|
| 225 |
+
console.print(
|
| 226 |
+
f" PR #{pr.num}: {title} (skipped — no config name in title)"
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
if args.from_prs and not args.configs:
|
| 230 |
+
args.configs = list(pr_revisions.keys())
|
| 231 |
+
if not args.configs:
|
| 232 |
+
console.print("[red]No config PRs found. Nothing to evaluate.[/red]")
|
| 233 |
+
sys.exit(1)
|
| 234 |
+
console.print(f"\n Auto-discovered configs: {', '.join(args.configs)}")
|
| 235 |
+
|
| 236 |
+
if args.configs:
|
| 237 |
+
console.print(
|
| 238 |
+
f"\n[bold]Loading dataset (config-per-model):[/bold] {args.dataset}"
|
| 239 |
+
)
|
| 240 |
+
console.print(f" Configs: {', '.join(args.configs)}")
|
| 241 |
+
|
| 242 |
+
config_datasets = {}
|
| 243 |
+
ocr_columns = {}
|
| 244 |
+
|
| 245 |
+
for config_name in args.configs:
|
| 246 |
+
revision = pr_revisions.get(config_name)
|
| 247 |
+
rev_label = f" (from {revision})" if revision and revision != "main" else ""
|
| 248 |
+
console.print(f" Loading config: {config_name}{rev_label}")
|
| 249 |
+
cds = load_dataset(
|
| 250 |
+
args.dataset,
|
| 251 |
+
name=config_name,
|
| 252 |
+
split=args.split,
|
| 253 |
+
revision=revision,
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
info_raw = cds[0].get("inference_info")
|
| 257 |
+
if info_raw:
|
| 258 |
+
info = json.loads(info_raw)
|
| 259 |
+
entry = info[0] if isinstance(info, list) else info
|
| 260 |
+
model_id = entry.get("model_id", config_name)
|
| 261 |
+
else:
|
| 262 |
+
model_id = config_name
|
| 263 |
+
ocr_columns[config_name] = model_id
|
| 264 |
+
config_datasets[config_name] = cds
|
| 265 |
+
|
| 266 |
+
base = config_datasets[args.configs[0]]
|
| 267 |
+
rows = []
|
| 268 |
+
for i in range(len(base)):
|
| 269 |
+
row = {"image": base[i]["image"]}
|
| 270 |
+
for cn in args.configs:
|
| 271 |
+
row[cn] = config_datasets[cn][i].get("markdown", "") or ""
|
| 272 |
+
rows.append(row)
|
| 273 |
+
ds = Dataset.from_list(rows)
|
| 274 |
+
console.print(f" Unified rows: {len(ds)}")
|
| 275 |
+
else:
|
| 276 |
+
console.print(f"[bold]Loading dataset:[/bold] {args.dataset}")
|
| 277 |
+
ds = load_dataset(args.dataset, split=args.split)
|
| 278 |
+
console.print(f" Columns: {ds.column_names}")
|
| 279 |
+
console.print(f" Rows: {len(ds)}")
|
| 280 |
+
|
| 281 |
+
if args.columns:
|
| 282 |
+
ocr_columns = {col: col for col in args.columns}
|
| 283 |
+
else:
|
| 284 |
+
ocr_columns = discover_ocr_columns(ds)
|
| 285 |
+
|
| 286 |
+
if len(ocr_columns) < 2:
|
| 287 |
+
console.print(
|
| 288 |
+
"[red]Need at least 2 OCR columns for pairwise comparison. "
|
| 289 |
+
"Use --columns or --configs to specify them.[/red]"
|
| 290 |
+
)
|
| 291 |
+
sys.exit(1)
|
| 292 |
+
|
| 293 |
+
return ds, ocr_columns
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
# --- vLLM structured output compatibility ---
|
| 297 |
+
def make_sampling_params(schema: dict, max_tokens: int = 512):
|
| 298 |
+
"""Create SamplingParams with structured output, handling vLLM version differences."""
|
| 299 |
+
from vllm import SamplingParams
|
| 300 |
+
|
| 301 |
+
# Try StructuredOutputsParams first (vLLM >= 0.12)
|
| 302 |
+
try:
|
| 303 |
+
from vllm.sampling_params import StructuredOutputsParams
|
| 304 |
+
|
| 305 |
+
return SamplingParams(
|
| 306 |
+
temperature=0.0,
|
| 307 |
+
max_tokens=max_tokens,
|
| 308 |
+
structured_outputs=StructuredOutputsParams(json=schema),
|
| 309 |
+
)
|
| 310 |
+
except (ImportError, TypeError):
|
| 311 |
+
pass
|
| 312 |
+
|
| 313 |
+
# Try GuidedDecodingParams (older vLLM)
|
| 314 |
+
try:
|
| 315 |
+
from vllm.sampling_params import GuidedDecodingParams
|
| 316 |
+
|
| 317 |
+
return SamplingParams(
|
| 318 |
+
temperature=0.0,
|
| 319 |
+
max_tokens=max_tokens,
|
| 320 |
+
guided_decoding=GuidedDecodingParams(json=schema),
|
| 321 |
+
)
|
| 322 |
+
except (ImportError, TypeError):
|
| 323 |
+
pass
|
| 324 |
+
|
| 325 |
+
# Fallback: no structured output, rely on prompt-based JSON
|
| 326 |
+
logger.warning(
|
| 327 |
+
"Structured output not available in this vLLM version. "
|
| 328 |
+
"Falling back to prompt-based JSON parsing."
|
| 329 |
+
)
|
| 330 |
+
return SamplingParams(
|
| 331 |
+
temperature=0.0,
|
| 332 |
+
max_tokens=max_tokens,
|
| 333 |
+
)
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def parse_judge_output(text: str) -> dict:
|
| 337 |
+
"""Parse judge output, handling both structured and free-form JSON."""
|
| 338 |
+
text = text.strip()
|
| 339 |
+
# Strip markdown fences if present
|
| 340 |
+
if text.startswith("```"):
|
| 341 |
+
text = text.split("\n", 1)[1].rsplit("```", 1)[0].strip()
|
| 342 |
+
try:
|
| 343 |
+
result = json.loads(text)
|
| 344 |
+
winner = result.get("winner", "tie").upper().strip()
|
| 345 |
+
if winner not in ("A", "B", "TIE"):
|
| 346 |
+
winner = "tie"
|
| 347 |
+
return {"winner": winner, "reason": result.get("reason", "")}
|
| 348 |
+
except json.JSONDecodeError:
|
| 349 |
+
logger.warning(f"Failed to parse judge output: {text[:200]}")
|
| 350 |
+
return {}
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
# --- Build comparisons ---
|
| 354 |
+
def build_comparisons(
|
| 355 |
+
dataset,
|
| 356 |
+
ocr_columns: dict[str, str],
|
| 357 |
+
max_samples: int | None,
|
| 358 |
+
seed: int,
|
| 359 |
+
) -> list[Comparison]:
|
| 360 |
+
"""Build all pairwise comparison prompts upfront (CPU only)."""
|
| 361 |
+
model_names = list(ocr_columns.values())
|
| 362 |
+
col_names = list(ocr_columns.keys())
|
| 363 |
+
pairs = list(combinations(range(len(col_names)), 2))
|
| 364 |
+
|
| 365 |
+
indices = list(range(len(dataset)))
|
| 366 |
+
if max_samples and max_samples < len(indices):
|
| 367 |
+
random.seed(seed)
|
| 368 |
+
indices = random.sample(indices, max_samples)
|
| 369 |
+
|
| 370 |
+
rng = random.Random(seed)
|
| 371 |
+
comparisons = []
|
| 372 |
+
|
| 373 |
+
for idx in indices:
|
| 374 |
+
row = dataset[idx]
|
| 375 |
+
image = row["image"]
|
| 376 |
+
b64 = image_to_base64(image)
|
| 377 |
+
|
| 378 |
+
for i, j in pairs:
|
| 379 |
+
col_a, col_b = col_names[i], col_names[j]
|
| 380 |
+
model_a, model_b = model_names[i], model_names[j]
|
| 381 |
+
text_a = row[col_a] or ""
|
| 382 |
+
text_b = row[col_b] or ""
|
| 383 |
+
|
| 384 |
+
if not text_a.strip() or not text_b.strip():
|
| 385 |
+
continue
|
| 386 |
+
|
| 387 |
+
# Randomize order to reduce position bias
|
| 388 |
+
swapped = rng.random() < 0.5
|
| 389 |
+
if swapped:
|
| 390 |
+
prompt = PAIRWISE_PROMPT.format(
|
| 391 |
+
ocr_text_a=text_b[:2500], ocr_text_b=text_a[:2500]
|
| 392 |
+
)
|
| 393 |
+
else:
|
| 394 |
+
prompt = PAIRWISE_PROMPT.format(
|
| 395 |
+
ocr_text_a=text_a[:2500], ocr_text_b=text_b[:2500]
|
| 396 |
+
)
|
| 397 |
+
|
| 398 |
+
messages = [
|
| 399 |
+
{
|
| 400 |
+
"role": "user",
|
| 401 |
+
"content": [
|
| 402 |
+
{
|
| 403 |
+
"type": "image_url",
|
| 404 |
+
"image_url": {"url": f"data:image/png;base64,{b64}"},
|
| 405 |
+
},
|
| 406 |
+
{"type": "text", "text": prompt},
|
| 407 |
+
],
|
| 408 |
+
}
|
| 409 |
+
]
|
| 410 |
+
|
| 411 |
+
comparisons.append(
|
| 412 |
+
Comparison(
|
| 413 |
+
sample_idx=idx,
|
| 414 |
+
model_a=model_a,
|
| 415 |
+
model_b=model_b,
|
| 416 |
+
col_a=col_a,
|
| 417 |
+
col_b=col_b,
|
| 418 |
+
swapped=swapped,
|
| 419 |
+
messages=messages,
|
| 420 |
+
)
|
| 421 |
+
)
|
| 422 |
+
|
| 423 |
+
return comparisons
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
# --- GPU cleanup ---
|
| 427 |
+
def cleanup_vllm():
|
| 428 |
+
"""Free GPU memory between judge models."""
|
| 429 |
+
try:
|
| 430 |
+
from vllm.distributed import (
|
| 431 |
+
destroy_distributed_environment,
|
| 432 |
+
destroy_model_parallel,
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
destroy_model_parallel()
|
| 436 |
+
destroy_distributed_environment()
|
| 437 |
+
except ImportError:
|
| 438 |
+
pass
|
| 439 |
+
gc.collect()
|
| 440 |
+
if torch.cuda.is_available():
|
| 441 |
+
torch.cuda.empty_cache()
|
| 442 |
+
torch.cuda.synchronize()
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
# --- Run judge ---
|
| 446 |
+
def run_judge(
|
| 447 |
+
model_id: str,
|
| 448 |
+
comparisons: list[Comparison],
|
| 449 |
+
max_model_len: int,
|
| 450 |
+
gpu_memory_utilization: float,
|
| 451 |
+
) -> list[dict]:
|
| 452 |
+
"""Run a single judge model on all comparisons via vLLM batch inference."""
|
| 453 |
+
from vllm import LLM
|
| 454 |
+
|
| 455 |
+
short_name = model_id.split("/")[-1] if "/" in model_id else model_id
|
| 456 |
+
console.print(f"\n[bold]Loading judge:[/bold] {model_id}")
|
| 457 |
+
|
| 458 |
+
llm = LLM(
|
| 459 |
+
model=model_id,
|
| 460 |
+
trust_remote_code=True,
|
| 461 |
+
max_model_len=max_model_len,
|
| 462 |
+
gpu_memory_utilization=gpu_memory_utilization,
|
| 463 |
+
limit_mm_per_prompt={"image": 1},
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
sampling_params = make_sampling_params(JUDGE_SCHEMA, max_tokens=512)
|
| 467 |
+
|
| 468 |
+
console.print(f" Running {len(comparisons)} comparisons...")
|
| 469 |
+
all_messages = [comp.messages for comp in comparisons]
|
| 470 |
+
|
| 471 |
+
results = []
|
| 472 |
+
try:
|
| 473 |
+
outputs = llm.chat(all_messages, sampling_params)
|
| 474 |
+
for output in outputs:
|
| 475 |
+
text = output.outputs[0].text
|
| 476 |
+
results.append(parse_judge_output(text))
|
| 477 |
+
console.print(
|
| 478 |
+
f" [green]{short_name}: {sum(1 for r in results if r)}/{len(results)} valid responses[/green]"
|
| 479 |
+
)
|
| 480 |
+
except Exception as e:
|
| 481 |
+
logger.error(f"vLLM batch inference failed for {short_name}: {e}")
|
| 482 |
+
results = [{}] * len(comparisons)
|
| 483 |
+
finally:
|
| 484 |
+
del llm
|
| 485 |
+
cleanup_vllm()
|
| 486 |
+
|
| 487 |
+
return results
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
# --- Aggregate and score ---
|
| 491 |
+
def aggregate_jury_votes(
|
| 492 |
+
all_judge_results: list[list[dict]],
|
| 493 |
+
comparisons: list[Comparison],
|
| 494 |
+
judge_names: list[str],
|
| 495 |
+
) -> list[dict]:
|
| 496 |
+
"""Aggregate votes from multiple judges using majority voting."""
|
| 497 |
+
n_comparisons = len(comparisons)
|
| 498 |
+
final_results = []
|
| 499 |
+
|
| 500 |
+
for i in range(n_comparisons):
|
| 501 |
+
votes = []
|
| 502 |
+
reasons = []
|
| 503 |
+
for j, judge_results in enumerate(all_judge_results):
|
| 504 |
+
result = judge_results[i]
|
| 505 |
+
if result:
|
| 506 |
+
winner = result.get("winner", "tie").upper().strip()
|
| 507 |
+
votes.append(winner)
|
| 508 |
+
reasons.append(f"[{judge_names[j]}] {result.get('reason', '')[:60]}")
|
| 509 |
+
|
| 510 |
+
if not votes:
|
| 511 |
+
final_results.append({})
|
| 512 |
+
continue
|
| 513 |
+
|
| 514 |
+
counts = Counter(votes)
|
| 515 |
+
winner, count = counts.most_common(1)[0]
|
| 516 |
+
agreement = f"{count}/{len(votes)}"
|
| 517 |
+
|
| 518 |
+
final_results.append(
|
| 519 |
+
{
|
| 520 |
+
"winner": winner,
|
| 521 |
+
"reason": f"Jury ({agreement}): " + " | ".join(reasons),
|
| 522 |
+
"votes": dict(counts),
|
| 523 |
+
"agreement": agreement,
|
| 524 |
+
}
|
| 525 |
+
)
|
| 526 |
+
|
| 527 |
+
return final_results
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
def compute_elo(
|
| 531 |
+
comparisons: list[Comparison],
|
| 532 |
+
results: list[dict],
|
| 533 |
+
model_names: list[str],
|
| 534 |
+
) -> tuple[dict, dict, dict, dict, list]:
|
| 535 |
+
"""Compute ELO ratings from comparison results."""
|
| 536 |
+
elo = {model: INITIAL_ELO for model in model_names}
|
| 537 |
+
wins = {model: 0 for model in model_names}
|
| 538 |
+
losses = {model: 0 for model in model_names}
|
| 539 |
+
ties = {model: 0 for model in model_names}
|
| 540 |
+
comparison_log = []
|
| 541 |
+
|
| 542 |
+
for comp, result in zip(comparisons, results):
|
| 543 |
+
if not result:
|
| 544 |
+
continue
|
| 545 |
+
|
| 546 |
+
winner_raw = result.get("winner", "tie").upper().strip()
|
| 547 |
+
|
| 548 |
+
# Unswap if positions were randomized
|
| 549 |
+
if comp.swapped:
|
| 550 |
+
if winner_raw == "A":
|
| 551 |
+
winner_raw = "B"
|
| 552 |
+
elif winner_raw == "B":
|
| 553 |
+
winner_raw = "A"
|
| 554 |
+
|
| 555 |
+
model_a, model_b = comp.model_a, comp.model_b
|
| 556 |
+
|
| 557 |
+
if winner_raw == "A":
|
| 558 |
+
elo[model_a], elo[model_b] = update_elo(elo[model_a], elo[model_b], "A")
|
| 559 |
+
wins[model_a] += 1
|
| 560 |
+
losses[model_b] += 1
|
| 561 |
+
elif winner_raw == "B":
|
| 562 |
+
elo[model_a], elo[model_b] = update_elo(elo[model_a], elo[model_b], "B")
|
| 563 |
+
losses[model_a] += 1
|
| 564 |
+
wins[model_b] += 1
|
| 565 |
+
else:
|
| 566 |
+
elo[model_a], elo[model_b] = update_elo(elo[model_a], elo[model_b], "tie")
|
| 567 |
+
ties[model_a] += 1
|
| 568 |
+
ties[model_b] += 1
|
| 569 |
+
|
| 570 |
+
comparison_log.append(
|
| 571 |
+
{
|
| 572 |
+
"sample_idx": comp.sample_idx,
|
| 573 |
+
"model_a": model_a,
|
| 574 |
+
"model_b": model_b,
|
| 575 |
+
"winner": winner_raw,
|
| 576 |
+
"reason": result.get("reason", ""),
|
| 577 |
+
"agreement": result.get("agreement", "1/1"),
|
| 578 |
+
}
|
| 579 |
+
)
|
| 580 |
+
|
| 581 |
+
return elo, wins, losses, ties, comparison_log
|
| 582 |
+
|
| 583 |
+
|
| 584 |
+
def print_elo_leaderboard(elo, wins, losses, ties):
|
| 585 |
+
table = Table(title="OCR ELO Leaderboard (vLLM Judge)", show_lines=True)
|
| 586 |
+
table.add_column("Rank", style="bold", justify="center")
|
| 587 |
+
table.add_column("Model", style="cyan")
|
| 588 |
+
table.add_column("ELO", style="bold green", justify="right")
|
| 589 |
+
table.add_column("W", justify="right")
|
| 590 |
+
table.add_column("L", justify="right")
|
| 591 |
+
table.add_column("T", justify="right")
|
| 592 |
+
table.add_column("Win%", justify="right")
|
| 593 |
+
|
| 594 |
+
ranked = sorted(elo.items(), key=lambda x: x[1], reverse=True)
|
| 595 |
+
for rank, (model, rating) in enumerate(ranked, 1):
|
| 596 |
+
total = wins[model] + losses[model] + ties[model]
|
| 597 |
+
win_pct = f"{wins[model] / total * 100:.0f}%" if total > 0 else "N/A"
|
| 598 |
+
table.add_row(
|
| 599 |
+
str(rank),
|
| 600 |
+
model.split("/")[-1] if "/" in model else model,
|
| 601 |
+
f"{rating:.0f}",
|
| 602 |
+
str(wins[model]),
|
| 603 |
+
str(losses[model]),
|
| 604 |
+
str(ties[model]),
|
| 605 |
+
win_pct,
|
| 606 |
+
)
|
| 607 |
+
|
| 608 |
+
console.print()
|
| 609 |
+
console.print(table)
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
def main():
|
| 613 |
+
parser = argparse.ArgumentParser(
|
| 614 |
+
description="Offline vLLM judge for OCR benchmark evaluation",
|
| 615 |
+
formatter_class=argparse.RawDescriptionHelpFormatter,
|
| 616 |
+
epilog="""
|
| 617 |
+
Examples:
|
| 618 |
+
# Single judge, 3 samples
|
| 619 |
+
uv run ocr-vllm-judge.py my-bench --from-prs \\
|
| 620 |
+
--judge-model Qwen/Qwen2.5-VL-7B-Instruct --max-samples 3
|
| 621 |
+
|
| 622 |
+
# Jury of 2 models
|
| 623 |
+
uv run ocr-vllm-judge.py my-bench --from-prs \\
|
| 624 |
+
--judge-model Qwen/Qwen3-VL-8B-Instruct \\
|
| 625 |
+
--judge-model Qwen/Qwen2.5-VL-7B-Instruct \\
|
| 626 |
+
--max-samples 50
|
| 627 |
+
|
| 628 |
+
# Via HF Job
|
| 629 |
+
hf jobs uv run --flavor l4x1 -s HF_TOKEN \\
|
| 630 |
+
ocr-vllm-judge.py my-bench --from-prs \\
|
| 631 |
+
--judge-model Qwen/Qwen3-VL-8B-Instruct
|
| 632 |
+
""",
|
| 633 |
+
)
|
| 634 |
+
parser.add_argument(
|
| 635 |
+
"dataset", help="HF dataset with OCR outputs from multiple models"
|
| 636 |
+
)
|
| 637 |
+
parser.add_argument(
|
| 638 |
+
"--judge-model",
|
| 639 |
+
action="append",
|
| 640 |
+
dest="judge_models",
|
| 641 |
+
default=None,
|
| 642 |
+
help="Judge model ID (repeatable for jury mode)",
|
| 643 |
+
)
|
| 644 |
+
parser.add_argument(
|
| 645 |
+
"--max-samples",
|
| 646 |
+
type=int,
|
| 647 |
+
default=None,
|
| 648 |
+
help="Max samples to evaluate (default: all)",
|
| 649 |
+
)
|
| 650 |
+
parser.add_argument(
|
| 651 |
+
"--seed", type=int, default=42, help="Random seed (default: 42)"
|
| 652 |
+
)
|
| 653 |
+
parser.add_argument(
|
| 654 |
+
"--split", default="train", help="Dataset split (default: train)"
|
| 655 |
+
)
|
| 656 |
+
parser.add_argument(
|
| 657 |
+
"--columns", nargs="+", default=None, help="Specific OCR columns to compare"
|
| 658 |
+
)
|
| 659 |
+
parser.add_argument(
|
| 660 |
+
"--configs",
|
| 661 |
+
nargs="+",
|
| 662 |
+
default=None,
|
| 663 |
+
help="Load these configs from the dataset repo",
|
| 664 |
+
)
|
| 665 |
+
parser.add_argument(
|
| 666 |
+
"--from-prs", action="store_true", help="Auto-discover configs from open PRs"
|
| 667 |
+
)
|
| 668 |
+
parser.add_argument(
|
| 669 |
+
"--merge-prs", action="store_true", help="Merge open PRs before loading"
|
| 670 |
+
)
|
| 671 |
+
parser.add_argument(
|
| 672 |
+
"--max-model-len",
|
| 673 |
+
type=int,
|
| 674 |
+
default=4096,
|
| 675 |
+
help="vLLM context length (default: 4096)",
|
| 676 |
+
)
|
| 677 |
+
parser.add_argument(
|
| 678 |
+
"--gpu-memory-utilization",
|
| 679 |
+
type=float,
|
| 680 |
+
default=0.85,
|
| 681 |
+
help="vLLM GPU memory fraction (default: 0.85)",
|
| 682 |
+
)
|
| 683 |
+
args = parser.parse_args()
|
| 684 |
+
|
| 685 |
+
# --- CUDA check ---
|
| 686 |
+
if not torch.cuda.is_available():
|
| 687 |
+
logger.error("CUDA is not available. This script requires a GPU.")
|
| 688 |
+
sys.exit(1)
|
| 689 |
+
logger.info(f"CUDA available. GPU: {torch.cuda.get_device_name(0)}")
|
| 690 |
+
|
| 691 |
+
# --- Judge models ---
|
| 692 |
+
judge_models = args.judge_models or ["Qwen/Qwen2.5-VL-7B-Instruct"]
|
| 693 |
+
|
| 694 |
+
console.print(
|
| 695 |
+
f"\n[bold]Judge panel ({len(judge_models)} model{'s' if len(judge_models) > 1 else ''}):[/bold]"
|
| 696 |
+
)
|
| 697 |
+
for m in judge_models:
|
| 698 |
+
console.print(f" - {m}")
|
| 699 |
+
|
| 700 |
+
# --- Load data ---
|
| 701 |
+
ds, ocr_columns = load_benchmark_dataset(args)
|
| 702 |
+
|
| 703 |
+
console.print("\n[bold]OCR columns found:[/bold]")
|
| 704 |
+
for col, model in ocr_columns.items():
|
| 705 |
+
console.print(f" {col} -> {model}")
|
| 706 |
+
|
| 707 |
+
model_names = list(ocr_columns.values())
|
| 708 |
+
|
| 709 |
+
# --- Build comparisons (CPU, no GPU needed) ---
|
| 710 |
+
console.print("\n[bold]Building comparison prompts...[/bold]")
|
| 711 |
+
comparisons = build_comparisons(ds, ocr_columns, args.max_samples, args.seed)
|
| 712 |
+
|
| 713 |
+
pairs = list(combinations(range(len(model_names)), 2))
|
| 714 |
+
console.print(
|
| 715 |
+
f" Models: {len(model_names)}, Pairs per sample: {len(pairs)}, "
|
| 716 |
+
f"Total comparisons: {len(comparisons)}"
|
| 717 |
+
)
|
| 718 |
+
|
| 719 |
+
if not comparisons:
|
| 720 |
+
console.print("[red]No valid comparisons to evaluate.[/red]")
|
| 721 |
+
sys.exit(1)
|
| 722 |
+
|
| 723 |
+
# --- Run judges ---
|
| 724 |
+
all_judge_results = []
|
| 725 |
+
judge_short_names = []
|
| 726 |
+
|
| 727 |
+
for model_id in judge_models:
|
| 728 |
+
short_name = model_id.split("/")[-1] if "/" in model_id else model_id
|
| 729 |
+
judge_short_names.append(short_name)
|
| 730 |
+
|
| 731 |
+
results = run_judge(
|
| 732 |
+
model_id,
|
| 733 |
+
comparisons,
|
| 734 |
+
max_model_len=args.max_model_len,
|
| 735 |
+
gpu_memory_utilization=args.gpu_memory_utilization,
|
| 736 |
+
)
|
| 737 |
+
all_judge_results.append(results)
|
| 738 |
+
|
| 739 |
+
# --- Aggregate votes ---
|
| 740 |
+
if len(judge_models) > 1:
|
| 741 |
+
console.print(
|
| 742 |
+
f"\n[bold]Aggregating jury votes ({len(judge_models)} judges)...[/bold]"
|
| 743 |
+
)
|
| 744 |
+
final_results = aggregate_jury_votes(
|
| 745 |
+
all_judge_results, comparisons, judge_short_names
|
| 746 |
+
)
|
| 747 |
+
else:
|
| 748 |
+
final_results = all_judge_results[0]
|
| 749 |
+
|
| 750 |
+
# --- Compute ELO ---
|
| 751 |
+
elo, wins, losses, ties, comparison_log = compute_elo(
|
| 752 |
+
comparisons, final_results, model_names
|
| 753 |
+
)
|
| 754 |
+
print_elo_leaderboard(elo, wins, losses, ties)
|
| 755 |
+
|
| 756 |
+
# --- Sample comparisons ---
|
| 757 |
+
console.print("\n[bold]Sample comparisons:[/bold]")
|
| 758 |
+
for entry in comparison_log[:5]:
|
| 759 |
+
winner_model = (
|
| 760 |
+
entry["model_a"]
|
| 761 |
+
if entry["winner"] == "A"
|
| 762 |
+
else (entry["model_b"] if entry["winner"] == "B" else "tie")
|
| 763 |
+
)
|
| 764 |
+
agreement = entry.get("agreement", "1/1")
|
| 765 |
+
console.print(
|
| 766 |
+
f" Sample {entry['sample_idx']}: {entry['winner']} wins "
|
| 767 |
+
f"({winner_model.split('/')[-1]}) [{agreement}] — {entry['reason'][:80]}"
|
| 768 |
+
)
|
| 769 |
+
|
| 770 |
+
console.print("\n[bold green]Evaluation complete![/bold green]")
|
| 771 |
+
console.print(
|
| 772 |
+
f" Judge{'s' if len(judge_models) > 1 else ''}: {', '.join(judge_short_names)}"
|
| 773 |
+
)
|
| 774 |
+
console.print(f" Comparisons evaluated: {len(comparison_log)}/{len(comparisons)}")
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
if __name__ == "__main__":
|
| 778 |
+
main()
|