Paulo-DharmaAI commited on
Commit
43b3a45
·
verified ·
1 Parent(s): 851d544

add evaluation notebook and frozen requirements

Browse files
Files changed (1) hide show
  1. evaluation.ipynb +1252 -0
evaluation.ipynb ADDED
@@ -0,0 +1,1252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Dharma-OCR — Model Evaluation\n",
8
+ "\n",
9
+ "This notebook provides a complete, self-contained pipeline for evaluating the **Dharma-OCR** model family.\n",
10
+ "It is organized in two main sections:\n",
11
+ "\n",
12
+ "| Section | Description |\n",
13
+ "|---|---|\n",
14
+ "| **1 — Model Inference** | Loads the evaluation dataset, serves the model via vLLM, and runs batched inference |\n",
15
+ "| **2 — Benchmark & Metrics** | Computes quality metrics and generates a comparative summary table |\n",
16
+ "\n",
17
+ "---\n",
18
+ "\n",
19
+ "> **Hardware requirements:** A CUDA-capable GPU is required to run vLLM locally. \n",
20
+ "> **Python requirements:** Python 3.10+ is required. \n",
21
+ "\n",
22
+ "### Dependencies\n",
23
+ "\n",
24
+ "Install the required packages before running:\n",
25
+ "\n",
26
+ "```bash\n",
27
+ "pip install -r requirements.txt\n",
28
+ "```"
29
+ ]
30
+ },
31
+ {
32
+ "cell_type": "markdown",
33
+ "metadata": {},
34
+ "source": [
35
+ "---\n",
36
+ "## ⚙️ Parameters\n",
37
+ "\n",
38
+ "Configure **all** settings here before running the notebook. \n",
39
+ "No other cell needs to be edited."
40
+ ]
41
+ },
42
+ {
43
+ "cell_type": "code",
44
+ "execution_count": null,
45
+ "id": "278fcaff",
46
+ "metadata": {},
47
+ "outputs": [],
48
+ "source": [
49
+ "# ============================================================\n",
50
+ "# MODEL\n",
51
+ "# ============================================================\n",
52
+ "\n",
53
+ "# Hugging Face model ID for the base OCR model\n",
54
+ "MODEL_NAME = \"Dharma-AI/Dharma-OCR-LITE\"\n",
55
+ "\n",
56
+ "# (Optional) Local path to a LoRA adapter directory.\n",
57
+ "# Set to None to evaluate the base model without any adapter.\n",
58
+ "LORA_ADAPTER_PATH = None # e.g. \"adapters/my_lora\"\n",
59
+ "\n",
60
+ "# Name registered for the LoRA module in vLLM (only used when LORA_ADAPTER_PATH is set)\n",
61
+ "LORA_NAME = \"ocr-lora\"\n",
62
+ "\n",
63
+ "# GPU / server configuration\n",
64
+ "GPU_MEMORY_UTILIZATION = 0.90\n",
65
+ "TENSOR_PARALLEL_SIZE = 1\n",
66
+ "MAX_MODEL_LEN = 65536\n",
67
+ "MAX_NUM_BATCHED_TOKENS = 32000\n",
68
+ "MAX_LORA_RANK = 128\n",
69
+ "\n",
70
+ "# ============================================================\n",
71
+ "# INFERENCE\n",
72
+ "# ============================================================\n",
73
+ "\n",
74
+ "# Number of concurrent inference requests in flight at any time.\n",
75
+ "# Default value based on the value used in the original Dharma-OCR paper.\n",
76
+ "# WARNING: Default for a L40S system, adjust with caution.\n",
77
+ "# Increase for higher throughput on large datasets; decrease to reduce GPU memory pressure.\n",
78
+ "BATCH_SIZE = 30\n",
79
+ "\n",
80
+ "# Maximum number of tokens the model may generate per response\n",
81
+ "MAX_TOKENS = 8192\n",
82
+ "\n",
83
+ "# Sampling temperature: 0 = greedy / deterministic (recommended for OCR evaluation)\n",
84
+ "TEMPERATURE = 0\n",
85
+ "\n",
86
+ "# System prompt sent to the model before each document image\n",
87
+ "SYSTEM_PROMPT = (\n",
88
+ " \"You are an expert OCR system. Extract all text from the provided document image \"\n",
89
+ " \"exactly as it appears, preserving the original layout and structure. \"\n",
90
+ " \"Return only the extracted text with no additional commentary.\"\n",
91
+ ")\n",
92
+ "\n",
93
+ "# ============================================================\n",
94
+ "# SERVER\n",
95
+ "# ============================================================\n",
96
+ "\n",
97
+ "# Set to False if you already have a running OpenAI-compatible endpoint\n",
98
+ "# (e.g. a remote vLLM server). The notebook will then skip the server startup cell.\n",
99
+ "START_LOCAL_SERVER = True\n",
100
+ "\n",
101
+ "VLLM_HOST = \"localhost\"\n",
102
+ "VLLM_PORT = 8000\n",
103
+ "VLLM_STARTUP_TIMEOUT_SECONDS = 600 # Maximum seconds to wait for the server to become ready\n",
104
+ "\n",
105
+ "# ============================================================\n",
106
+ "# DATASET\n",
107
+ "# ============================================================\n",
108
+ "\n",
109
+ "# Dataset source — either a local file path or a Hugging Face dataset ID.\n",
110
+ "DATASET_PATH = \"Dharma-AI/DharmaOCR-Benchmark\"\n",
111
+ "\n",
112
+ "# Split to load when using a Hugging Face dataset (ignored for local files)\n",
113
+ "DATASET_SPLIT = \"test\"\n",
114
+ "\n",
115
+ "# Column containing base64-encoded document images (JPEG / PNG / WebP).\n",
116
+ "IMAGE_COLUMN = \"image_base64\"\n",
117
+ "\n",
118
+ "# Column containing the ground truth transcriptions.\n",
119
+ "GROUND_TRUTH_COLUMN = \"assistant\"\n",
120
+ "\n",
121
+ "# Whether to normalise both columns to plain text before metric computation.\n",
122
+ "#\n",
123
+ "# False — both columns are used as-is (default).\n",
124
+ "# True — JSON values in either column are extracted and joined with newlines\n",
125
+ "# before comparison. Columns that are already plain text are unchanged.\n",
126
+ "# Use to normalize comparisons. \n",
127
+ "PLAIN_TEXT = True\n",
128
+ "\n",
129
+ "# Column containing the model predictions.\n",
130
+ "# This is the \"model_answer\" column in the inference output Parquet file.\n",
131
+ "PREDICTION_COLUMN = \"model_answer\"\n",
132
+ "\n",
133
+ "# ============================================================\n",
134
+ "# OUTPUT\n",
135
+ "# ============================================================\n",
136
+ "\n",
137
+ "# Directory where benchmark result files are saved (relative to this notebook)\n",
138
+ "BENCHMARK_RESULTS_DIR = \"benchmark_results\"\n",
139
+ "\n",
140
+ "# Filename for the inference output Parquet file.\n",
141
+ "# DATASET_PATH may contain '/' (e.g. a HuggingFace org/repo slug), so we\n",
142
+ "# replace it with '_' to produce a flat filename rather than a subdirectory path.\n",
143
+ "INFERENCE_OUTPUT_FILE = DATASET_PATH.replace(\"/\", \"_\") + \".parquet\""
144
+ ]
145
+ },
146
+ {
147
+ "cell_type": "markdown",
148
+ "id": "d8266d86",
149
+ "metadata": {},
150
+ "source": [
151
+ "---\n",
152
+ "## Section 1 — Model Inference\n",
153
+ "\n",
154
+ "This section runs the configured model on the evaluation dataset and saves the raw predictions for benchmarking.\n",
155
+ "\n",
156
+ "**Steps:**\n",
157
+ "1. Import dependencies\n",
158
+ "2. Load the evaluation dataset\n",
159
+ "3. *(Optional)* Start the vLLM server locally\n",
160
+ "4. Run batch inference\n",
161
+ "5. Save results to disk"
162
+ ]
163
+ },
164
+ {
165
+ "cell_type": "markdown",
166
+ "id": "d031d9db",
167
+ "metadata": {},
168
+ "source": [
169
+ "### 1.1 Imports & Setup"
170
+ ]
171
+ },
172
+ {
173
+ "cell_type": "code",
174
+ "execution_count": null,
175
+ "id": "cf42a7a5",
176
+ "metadata": {},
177
+ "outputs": [],
178
+ "source": [
179
+ "import asyncio\n",
180
+ "import base64\n",
181
+ "import json\n",
182
+ "import logging\n",
183
+ "import os\n",
184
+ "import subprocess\n",
185
+ "import time\n",
186
+ "from pathlib import Path\n",
187
+ "from typing import Optional\n",
188
+ "\n",
189
+ "import httpx\n",
190
+ "import pandas as pd\n",
191
+ "from openai import AsyncOpenAI\n",
192
+ "from tqdm.asyncio import tqdm as async_tqdm\n",
193
+ "\n",
194
+ "# Benchmark metrics (used in Section 2 — imported here to fail fast)\n",
195
+ "import nltk\n",
196
+ "from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction\n",
197
+ "import Levenshtein as _lev_lib\n",
198
+ "\n",
199
+ "# Jupyter display utilities\n",
200
+ "from IPython.display import display, HTML\n",
201
+ "\n",
202
+ "# Suppress verbose HTTP client logs\n",
203
+ "logging.getLogger(\"httpx\").setLevel(logging.WARNING)\n",
204
+ "logging.getLogger(\"openai\").setLevel(logging.WARNING)\n",
205
+ "\n",
206
+ "# Download NLTK tokenizer data required for BLEU scoring\n",
207
+ "try:\n",
208
+ " nltk.data.find(\"tokenizers/punkt\")\n",
209
+ "except LookupError:\n",
210
+ " nltk.download(\"punkt\", quiet=True)\n",
211
+ "\n",
212
+ "print(\"All dependencies loaded successfully.\")"
213
+ ]
214
+ },
215
+ {
216
+ "cell_type": "markdown",
217
+ "id": "4f468fd3",
218
+ "metadata": {},
219
+ "source": [
220
+ "### 1.2 Load Evaluation Dataset"
221
+ ]
222
+ },
223
+ {
224
+ "cell_type": "code",
225
+ "execution_count": null,
226
+ "id": "ceb6a2a5",
227
+ "metadata": {},
228
+ "outputs": [],
229
+ "source": [
230
+ "def _load_dataset(dataset_path: str, split: str = \"test\") -> \"pd.DataFrame\":\n",
231
+ " \"\"\"\n",
232
+ " Load the evaluation dataset from a local Parquet file or a Hugging Face dataset ID.\n",
233
+ "\n",
234
+ " Detection logic:\n",
235
+ " - If ``dataset_path`` points to an existing file on disk -> read as Parquet\n",
236
+ " - Otherwise -> load via the HF `datasets` library\n",
237
+ " \"\"\"\n",
238
+ " local_path = Path(dataset_path)\n",
239
+ "\n",
240
+ " if local_path.exists():\n",
241
+ " print(f\"Source detected: local file ({local_path.resolve()})\")\n",
242
+ " return pd.read_parquet(local_path)\n",
243
+ "\n",
244
+ " # Not a local file — treat as a Hugging Face dataset ID\n",
245
+ " print(f\"Source detected: Hugging Face dataset (id='{dataset_path}', split='{split}')\")\n",
246
+ " try:\n",
247
+ " from datasets import load_dataset as hf_load_dataset\n",
248
+ " except ImportError:\n",
249
+ " raise ImportError(\n",
250
+ " \"The 'datasets' package is required to load Hugging Face datasets.\\n\"\n",
251
+ " \"Install it with: pip install datasets\"\n",
252
+ " )\n",
253
+ " hf_ds = hf_load_dataset(dataset_path, split=split)\n",
254
+ " return hf_ds.to_pandas()\n",
255
+ "\n",
256
+ "\n",
257
+ "df = _load_dataset(DATASET_PATH, split=DATASET_SPLIT)\n",
258
+ "\n",
259
+ "assert IMAGE_COLUMN in df.columns, (\n",
260
+ " f\"Column '{IMAGE_COLUMN}' not found. Available columns: {list(df.columns)}\"\n",
261
+ ")\n",
262
+ "assert GROUND_TRUTH_COLUMN in df.columns, (\n",
263
+ " f\"Column '{GROUND_TRUTH_COLUMN}' not found. Available columns: {list(df.columns)}\"\n",
264
+ ")\n",
265
+ "\n",
266
+ "print(f\"Dataset loaded: {len(df):,} rows, {len(df.columns)} columns\")\n",
267
+ "display(df[[GROUND_TRUTH_COLUMN, IMAGE_COLUMN]].head(2))\n"
268
+ ]
269
+ },
270
+ {
271
+ "cell_type": "markdown",
272
+ "id": "cb619fc7",
273
+ "metadata": {},
274
+ "source": [
275
+ "### 1.3 Start vLLM Server\n",
276
+ "\n",
277
+ "> **Skip this cell** (set `START_LOCAL_SERVER = False` in the Parameters section) if you are connecting to a remote or pre-started OpenAI-compatible endpoint. \n",
278
+ "> Make sure `VLLM_HOST` and `VLLM_PORT` point to your server.\n",
279
+ "\n",
280
+ "This cell launches vLLM as a local subprocess and waits until it is ready to accept requests.\n",
281
+ "A LoRA adapter is automatically configured if `LORA_ADAPTER_PATH` is set."
282
+ ]
283
+ },
284
+ {
285
+ "cell_type": "code",
286
+ "execution_count": null,
287
+ "id": "c9f23a92",
288
+ "metadata": {},
289
+ "outputs": [],
290
+ "source": [
291
+ "def _build_vllm_command(\n",
292
+ " model_name: str,\n",
293
+ " host: str,\n",
294
+ " port: int,\n",
295
+ " gpu_memory_utilization: float,\n",
296
+ " tensor_parallel_size: int,\n",
297
+ " max_model_len: int,\n",
298
+ " max_num_batched_tokens: int,\n",
299
+ " lora_adapter_path: Optional[str] = None,\n",
300
+ " lora_name: str = \"lora-1\",\n",
301
+ " max_lora_rank: int = 128,\n",
302
+ ") -> list:\n",
303
+ " \"\"\"Build the `vllm serve` command as an argument list.\"\"\"\n",
304
+ " cmd = [\n",
305
+ " \"vllm\", \"serve\", model_name,\n",
306
+ " f\"--host={host}\",\n",
307
+ " f\"--port={port}\",\n",
308
+ " f\"--gpu-memory-utilization={gpu_memory_utilization}\",\n",
309
+ " f\"--tensor-parallel-size={tensor_parallel_size}\",\n",
310
+ " f\"--max-model-len={max_model_len}\",\n",
311
+ " f\"--max-num-batched-tokens={max_num_batched_tokens}\",\n",
312
+ " \"--trust-remote-code\",\n",
313
+ " \"--dtype=auto\",\n",
314
+ " \"--load-format=auto\",\n",
315
+ " \"--kv-cache-dtype=auto\",\n",
316
+ " ]\n",
317
+ " if lora_adapter_path:\n",
318
+ " lora_module = json.dumps({\n",
319
+ " \"name\": lora_name,\n",
320
+ " \"path\": lora_adapter_path,\n",
321
+ " \"base_model_name\": model_name,\n",
322
+ " })\n",
323
+ " cmd += [\n",
324
+ " \"--enable-lora\",\n",
325
+ " f\"--max-lora-rank={max_lora_rank}\",\n",
326
+ " \"--lora-modules\", lora_module,\n",
327
+ " ]\n",
328
+ " return cmd\n",
329
+ "\n",
330
+ "\n",
331
+ "def _wait_for_server(host: str, port: int, timeout: int = 300) -> bool:\n",
332
+ " \"\"\"Poll the server health endpoint until it responds or the timeout is reached.\"\"\"\n",
333
+ " url = f\"http://{host}:{port}/health\"\n",
334
+ " deadline = time.time() + timeout\n",
335
+ " print(f\"Waiting for vLLM server at {url} (timeout: {timeout}s)\", end=\"\", flush=True)\n",
336
+ " while time.time() < deadline:\n",
337
+ " try:\n",
338
+ " resp = httpx.get(url, timeout=5)\n",
339
+ " if resp.status_code == 200:\n",
340
+ " print(\" ready!\")\n",
341
+ " return True\n",
342
+ " except Exception:\n",
343
+ " pass\n",
344
+ " time.sleep(5)\n",
345
+ " print(\".\", end=\"\", flush=True)\n",
346
+ " print(\" timed out.\")\n",
347
+ " return False\n",
348
+ "\n",
349
+ "\n",
350
+ "vllm_process = None\n",
351
+ "\n",
352
+ "if START_LOCAL_SERVER:\n",
353
+ " vllm_cmd = _build_vllm_command(\n",
354
+ " model_name=MODEL_NAME,\n",
355
+ " host=VLLM_HOST,\n",
356
+ " port=VLLM_PORT,\n",
357
+ " gpu_memory_utilization=GPU_MEMORY_UTILIZATION,\n",
358
+ " tensor_parallel_size=TENSOR_PARALLEL_SIZE,\n",
359
+ " max_model_len=MAX_MODEL_LEN,\n",
360
+ " max_num_batched_tokens=MAX_NUM_BATCHED_TOKENS,\n",
361
+ " lora_adapter_path=LORA_ADAPTER_PATH,\n",
362
+ " lora_name=LORA_NAME,\n",
363
+ " max_lora_rank=MAX_LORA_RANK,\n",
364
+ " )\n",
365
+ "\n",
366
+ " print(\"Starting vLLM server with command:\")\n",
367
+ " print(\" \".join(vllm_cmd))\n",
368
+ " print()\n",
369
+ "\n",
370
+ " vllm_process = subprocess.Popen(\n",
371
+ " vllm_cmd,\n",
372
+ " stdout=open(\"vllm.log\", \"w\"),\n",
373
+ " stderr=subprocess.STDOUT,\n",
374
+ " text=True,\n",
375
+ " )\n",
376
+ "\n",
377
+ " ready = _wait_for_server(VLLM_HOST, VLLM_PORT, timeout=VLLM_STARTUP_TIMEOUT_SECONDS)\n",
378
+ " if ready:\n",
379
+ " print(f\"vLLM server is live at http://{VLLM_HOST}:{VLLM_PORT}\")\n",
380
+ " else:\n",
381
+ " print(\"Server did not become ready within the timeout. Check vllm_process.stdout for details.\")\n",
382
+ "else:\n",
383
+ " print(f\"Using existing server at http://{VLLM_HOST}:{VLLM_PORT}\")"
384
+ ]
385
+ },
386
+ {
387
+ "cell_type": "markdown",
388
+ "id": "da46db47",
389
+ "metadata": {},
390
+ "source": [
391
+ "### 1.4 Run Batch Inference\n",
392
+ "\n",
393
+ "All requests are dispatched concurrently using an async event loop with a semaphore that\n",
394
+ "caps the number of in-flight requests to `BATCH_SIZE` at any given time.\n",
395
+ "A new request is submitted as soon as any in-flight one completes, keeping the server\n",
396
+ "fully utilised throughout the run.\n",
397
+ "\n",
398
+ "Three columns are added to the dataset:\n",
399
+ "\n",
400
+ "| Column | Description |\n",
401
+ "|---|---|\n",
402
+ "| `model_answer` | Raw text returned by the model |\n",
403
+ "| `time_to_preprocess` | Message-building time — mirrors library phase 1 |\n",
404
+ "| `time_to_inference` | API round-trip only — mirrors library phase 2 |\n",
405
+ "| `time_to_postprocess` | Response-processing time — mirrors library phase 3 |\n",
406
+ "| `time_to_inference_total` | End-to-end latency per request (sum of all three phases) |\n",
407
+ "| `textual_degeneration` | `True` if the model hit the token limit (`finish_reason == \"length\"`) **and** the last 15 characters repeat at least 4 times in the output |"
408
+ ]
409
+ },
410
+ {
411
+ "cell_type": "code",
412
+ "execution_count": null,
413
+ "id": "33ba4e7e",
414
+ "metadata": {},
415
+ "outputs": [],
416
+ "source": [
417
+ "# ── Inference helpers ─────────────────────────────────────────────────────────\n",
418
+ "\n",
419
+ "def _encode_image(image_data) -> str:\n",
420
+ " \"\"\"Return a clean base64 string from raw bytes or an existing base64 string.\"\"\"\n",
421
+ " if isinstance(image_data, bytes):\n",
422
+ " return base64.b64encode(image_data).decode()\n",
423
+ " return str(image_data).strip().replace(\"\\n\", \"\").replace(\"\\r\", \"\")\n",
424
+ "\n",
425
+ "\n",
426
+ "def _detect_image_format(b64: str) -> str:\n",
427
+ " \"\"\"Infer the image MIME sub-type from the leading base64 bytes.\"\"\"\n",
428
+ " if b64.startswith(\"/9j/\"):\n",
429
+ " return \"jpeg\"\n",
430
+ " if b64.startswith(\"iVBORw\"):\n",
431
+ " return \"png\"\n",
432
+ " if b64.startswith(\"UklGR\"):\n",
433
+ " return \"webp\"\n",
434
+ " return \"jpeg\"\n",
435
+ "\n",
436
+ "\n",
437
+ "def _build_messages(image_data, system_prompt: str) -> list:\n",
438
+ " \"\"\"Build an OpenAI-compatible chat message list for a single document image.\"\"\"\n",
439
+ " b64 = _encode_image(image_data)\n",
440
+ " fmt = _detect_image_format(b64)\n",
441
+ " return [\n",
442
+ " {\"role\": \"system\", \"content\": system_prompt},\n",
443
+ " {\n",
444
+ " \"role\": \"user\",\n",
445
+ " \"content\": [\n",
446
+ " {\n",
447
+ " \"type\": \"image_url\",\n",
448
+ " \"image_url\": {\"url\": f\"data:image/{fmt};base64,{b64}\"},\n",
449
+ " }\n",
450
+ " ],\n",
451
+ " },\n",
452
+ " ]\n",
453
+ "\n",
454
+ "\n",
455
+ "async def _infer_single_async(\n",
456
+ " client: AsyncOpenAI,\n",
457
+ " image_data,\n",
458
+ " system_prompt: str,\n",
459
+ " model: str,\n",
460
+ " max_tokens: int,\n",
461
+ " temperature: float,\n",
462
+ " semaphore: asyncio.Semaphore,\n",
463
+ " results: list,\n",
464
+ " index: int,\n",
465
+ " pbar,\n",
466
+ " *,\n",
467
+ " max_attempts: int = 4,\n",
468
+ " base_delay_seconds: float = 0.5,\n",
469
+ ") -> None:\n",
470
+ " \"\"\"\n",
471
+ " Execute a single chat-completion request and store the result in ``results[index]``.\n",
472
+ "\n",
473
+ " Timing follows the same three-phase structure as the dharma-ai library\n",
474
+ " (basic_pipeline.BasicPipeline):\n",
475
+ "\n",
476
+ " time_to_preprocess — message building (base64 encode + format detection)\n",
477
+ " time_to_inference — API round-trip only (chat.completions.create)\n",
478
+ " time_to_postprocess — response processing (degeneration check, token count)\n",
479
+ " time_to_inference_total — sum of all three phases (end-to-end latency)\n",
480
+ "\n",
481
+ " Concurrency is controlled by ``semaphore``; the timer starts only after a slot\n",
482
+ " is acquired, so semaphore queue wait is excluded from all timing columns.\n",
483
+ " The timeout is enforced at the HTTP transport layer (``httpx.Timeout`` on the\n",
484
+ " client) so timed-out connections are properly reset on the server side.\n",
485
+ " On failure the request is retried up to ``max_attempts`` times with exponential\n",
486
+ " backoff. If all attempts fail the result is recorded as an error string.\n",
487
+ " \"\"\"\n",
488
+ " async with semaphore:\n",
489
+ " last_error: Exception | None = None\n",
490
+ "\n",
491
+ " for attempt in range(max(1, max_attempts)):\n",
492
+ " try:\n",
493
+ " # ── Preprocess ────────────────────────────────────────────────\n",
494
+ " t_preprocess_start = time.time()\n",
495
+ " messages = _build_messages(image_data, system_prompt)\n",
496
+ " t_inference_start = time.time()\n",
497
+ "\n",
498
+ " # ── Inference ─────────────────────────────────────────────────\n",
499
+ " response = await client.chat.completions.create(\n",
500
+ " model=model,\n",
501
+ " messages=messages,\n",
502
+ " max_tokens=max_tokens,\n",
503
+ " temperature=temperature,\n",
504
+ " extra_headers={\"X-Request-Id\": str(index)},\n",
505
+ " )\n",
506
+ " t_postprocess_start = time.time()\n",
507
+ "\n",
508
+ " # ── Postprocess ───────────────────────────────────────────────\n",
509
+ " choice = response.choices[0]\n",
510
+ " content = choice.message.content or \"\"\n",
511
+ " textual_degeneration = (\n",
512
+ " len(content) >= 15\n",
513
+ " and choice.finish_reason == \"length\"\n",
514
+ " and content.count(content[-15:]) >= 4\n",
515
+ " )\n",
516
+ " num_output_tokens = (response.usage.completion_tokens\n",
517
+ " if response.usage is not None else 0)\n",
518
+ " t_end = time.time()\n",
519
+ "\n",
520
+ " time_to_preprocess = t_inference_start - t_preprocess_start\n",
521
+ " time_to_inference = t_postprocess_start - t_inference_start\n",
522
+ " time_to_postprocess = t_end - t_postprocess_start\n",
523
+ " total_elapsed = t_end - t_preprocess_start\n",
524
+ "\n",
525
+ " inference_tokens_per_second = (num_output_tokens / total_elapsed\n",
526
+ " if total_elapsed > 0 else 0.0)\n",
527
+ "\n",
528
+ " results[index] = {\n",
529
+ " \"model_answer\": content,\n",
530
+ " \"time_to_preprocess\": time_to_preprocess,\n",
531
+ " \"time_to_inference\": time_to_inference,\n",
532
+ " \"time_to_postprocess\": time_to_postprocess,\n",
533
+ " \"time_to_inference_total\": total_elapsed,\n",
534
+ " \"textual_degeneration\": textual_degeneration,\n",
535
+ " \"num_output_tokens\": num_output_tokens,\n",
536
+ " \"inference_tokens_per_second\": inference_tokens_per_second,\n",
537
+ " }\n",
538
+ " pbar.update(1)\n",
539
+ " return\n",
540
+ "\n",
541
+ " except Exception as exc:\n",
542
+ " last_error = exc\n",
543
+ " if attempt < max(1, max_attempts) - 1:\n",
544
+ " await asyncio.sleep(base_delay_seconds * (2 ** attempt))\n",
545
+ "\n",
546
+ " results[index] = {\n",
547
+ " \"model_answer\": f\"ERROR: {last_error}\",\n",
548
+ " \"time_to_preprocess\": 0.0,\n",
549
+ " \"time_to_inference\": 0.0,\n",
550
+ " \"time_to_postprocess\": 0.0,\n",
551
+ " \"time_to_inference_total\": 0.0,\n",
552
+ " \"textual_degeneration\": False,\n",
553
+ " \"num_output_tokens\": 0,\n",
554
+ " \"inference_tokens_per_second\": 0.0,\n",
555
+ " }\n",
556
+ " pbar.update(1)\n",
557
+ "\n",
558
+ "\n",
559
+ "async def _run_inference_async(\n",
560
+ " df: pd.DataFrame,\n",
561
+ " image_column: str,\n",
562
+ " system_prompt: str,\n",
563
+ " model: str,\n",
564
+ " host: str,\n",
565
+ " port: int,\n",
566
+ " batch_size: int = 30,\n",
567
+ " max_tokens: int = 4096,\n",
568
+ " temperature: float = 0,\n",
569
+ " timeout_seconds: float = 600.0,\n",
570
+ " max_attempts: int = 4,\n",
571
+ ") -> tuple: # noqa: C901\n",
572
+ " \"\"\"\n",
573
+ " Run inference on a DataFrame of document images using async concurrency.\n",
574
+ "\n",
575
+ " All requests are created upfront as coroutines and driven by ``asyncio.gather``.\n",
576
+ " An ``asyncio.Semaphore`` caps the number of requests in flight at any time to\n",
577
+ " ``batch_size``, so as soon as one request finishes the next one starts without\n",
578
+ " any gap. Each individual request supports per-attempt timeouts and automatic\n",
579
+ " retry with exponential backoff (see ``_infer_single_async``).\n",
580
+ "\n",
581
+ " The timeout is enforced via ``httpx.Timeout`` on the HTTP transport layer, not\n",
582
+ " via ``asyncio.wait_for``. This distinction matters: an httpx-level timeout\n",
583
+ " properly resets the TCP connection (sending RST to the server), whereas\n",
584
+ " cancelling an asyncio coroutine leaves the socket open. Open sockets with\n",
585
+ " unread data accumulate in the server's send buffer and eventually deadlock its\n",
586
+ " event loop.\n",
587
+ "\n",
588
+ " Parameters\n",
589
+ " ----------\n",
590
+ " df : pd.DataFrame\n",
591
+ " Must contain at least the column specified by ``image_column``.\n",
592
+ " image_column : str\n",
593
+ " Name of the column containing base64-encoded document images.\n",
594
+ " system_prompt : str\n",
595
+ " System prompt sent to the model with every request.\n",
596
+ " model : str\n",
597
+ " Model identifier as registered in the server (base model name or LoRA adapter name).\n",
598
+ " host, port : str, int\n",
599
+ " Address of the OpenAI-compatible inference server.\n",
600
+ " batch_size : int\n",
601
+ " Maximum number of concurrent in-flight requests (default: 30).\n",
602
+ " max_tokens : int\n",
603
+ " Maximum tokens to generate per response.\n",
604
+ " temperature : float\n",
605
+ " Sampling temperature. 0 = greedy / deterministic.\n",
606
+ " timeout_seconds : float\n",
607
+ " Per-request timeout enforced at the HTTP transport level (default: 600).\n",
608
+ " When exceeded, httpx resets the TCP connection so the server can\n",
609
+ " immediately reclaim its resources. 600 s is intentionally generous:\n",
610
+ " large document images (multi-MB base64 payloads) can take tens of seconds\n",
611
+ " to queue and process; a shorter timeout causes premature FIN-WAIT-1 storms\n",
612
+ " that deadlock vLLM's event loop.\n",
613
+ " max_attempts : int\n",
614
+ " Total number of attempts per request, including the first try (default: 4).\n",
615
+ "\n",
616
+ " Returns\n",
617
+ " -------\n",
618
+ " out_df : pd.DataFrame\n",
619
+ " Input DataFrame with the following columns added:\n",
620
+ "\n",
621
+ " * ``model_answer`` — generated text\n",
622
+ " * ``time_to_preprocess`` — message-building time (mirrors library phase 1)\n",
623
+ " * ``time_to_inference`` — API round-trip only (mirrors library phase 2)\n",
624
+ " * ``time_to_postprocess`` — response-processing time (mirrors library phase 3)\n",
625
+ " * ``time_to_inference_total`` — end-to-end latency per request (sum of all three phases)\n",
626
+ " * ``textual_degeneration`` — True if finish_reason == \"length\" and last 15 chars repeat ≥ 4 times\n",
627
+ " * ``num_output_tokens`` — completion tokens reported by the server\n",
628
+ " * ``inference_tokens_per_second``— num_output_tokens / time_to_inference_total (per-request throughput)\n",
629
+ " * ``time_per_page`` — total_elapsed / N (constant per run; matches paper's Time/Page metric)\n",
630
+ " total_elapsed : float\n",
631
+ " Total wall-clock time in seconds for the full inference run.\n",
632
+ " \"\"\"\n",
633
+ " http_client = httpx.AsyncClient(\n",
634
+ " timeout=httpx.Timeout(\n",
635
+ " connect=60.0,\n",
636
+ " read=timeout_seconds,\n",
637
+ " write=timeout_seconds,\n",
638
+ " pool=timeout_seconds,\n",
639
+ " ),\n",
640
+ " limits=httpx.Limits(\n",
641
+ " max_connections=200,\n",
642
+ " max_keepalive_connections=100,\n",
643
+ " ),\n",
644
+ " )\n",
645
+ " client = AsyncOpenAI(\n",
646
+ " base_url=f\"http://{host}:{port}/v1\",\n",
647
+ " api_key=\"not-required\",\n",
648
+ " http_client=http_client,\n",
649
+ " max_retries=0,\n",
650
+ " )\n",
651
+ "\n",
652
+ " n = len(df)\n",
653
+ " results: list = [None] * n\n",
654
+ " semaphore = asyncio.Semaphore(batch_size)\n",
655
+ " total_start = time.time()\n",
656
+ "\n",
657
+ " with async_tqdm(total=n, desc=\"Inference\", unit=\"sample\") as pbar:\n",
658
+ " tasks = [\n",
659
+ " _infer_single_async(\n",
660
+ " client=client,\n",
661
+ " image_data=row[image_column],\n",
662
+ " system_prompt=system_prompt,\n",
663
+ " model=model,\n",
664
+ " max_tokens=max_tokens,\n",
665
+ " temperature=temperature,\n",
666
+ " semaphore=semaphore,\n",
667
+ " results=results,\n",
668
+ " index=i,\n",
669
+ " pbar=pbar,\n",
670
+ " max_attempts=max_attempts,\n",
671
+ " )\n",
672
+ " for i, (_, row) in enumerate(df.iterrows())\n",
673
+ " ]\n",
674
+ " await asyncio.gather(*tasks)\n",
675
+ "\n",
676
+ " await http_client.aclose()\n",
677
+ "\n",
678
+ " total_elapsed = time.time() - total_start\n",
679
+ "\n",
680
+ " out_df = df.copy()\n",
681
+ " out_df[\"model_answer\"] = [r[\"model_answer\"] for r in results]\n",
682
+ " out_df[\"time_to_preprocess\"] = [r[\"time_to_preprocess\"] for r in results]\n",
683
+ " out_df[\"time_to_inference\"] = [r[\"time_to_inference\"] for r in results]\n",
684
+ " out_df[\"time_to_postprocess\"] = [r[\"time_to_postprocess\"] for r in results]\n",
685
+ " out_df[\"time_to_inference_total\"] = [r[\"time_to_inference_total\"] for r in results]\n",
686
+ " out_df[\"textual_degeneration\"] = [r[\"textual_degeneration\"] for r in results]\n",
687
+ " out_df[\"num_output_tokens\"] = [r[\"num_output_tokens\"] for r in results]\n",
688
+ " out_df[\"inference_tokens_per_second\"] = [r[\"inference_tokens_per_second\"] for r in results]\n",
689
+ " out_df[\"time_per_page\"] = total_elapsed / n\n",
690
+ "\n",
691
+ " n_deg = int(out_df[\"textual_degeneration\"].sum())\n",
692
+ " mean_latency = out_df[\"time_to_inference_total\"].mean()\n",
693
+ " mean_tps = out_df[\"inference_tokens_per_second\"].mean()\n",
694
+ " time_per_page = total_elapsed / n\n",
695
+ "\n",
696
+ " print(f\"\\nInference complete\")\n",
697
+ " print(f\" Samples : {n:,}\")\n",
698
+ " print(f\" Total wall time : {total_elapsed:.1f}s\")\n",
699
+ " print(f\" Time per page : {time_per_page:.3f}s\")\n",
700
+ " print(f\" Throughput : {mean_tps:.1f} tokens/s\")\n",
701
+ " print(f\" Mean latency : {mean_latency:.3f}s / sample\")\n",
702
+ " print(f\" Textual degeneration: {n_deg} ({n_deg / n * 100:.1f}%)\")\n",
703
+ "\n",
704
+ " return out_df, total_elapsed\n",
705
+ "\n",
706
+ "\n",
707
+ "def run_inference(\n",
708
+ " df: pd.DataFrame,\n",
709
+ " image_column: str,\n",
710
+ " system_prompt: str,\n",
711
+ " model: str,\n",
712
+ " host: str,\n",
713
+ " port: int,\n",
714
+ " batch_size: int = 30,\n",
715
+ " max_tokens: int = 4096,\n",
716
+ " temperature: float = 0,\n",
717
+ " timeout_seconds: float = 600.0,\n",
718
+ " max_attempts: int = 4,\n",
719
+ ") -> tuple:\n",
720
+ " \"\"\"\n",
721
+ " Synchronous wrapper around ``_run_inference_async`` for use outside Jupyter.\n",
722
+ "\n",
723
+ " When called from a Jupyter notebook, prefer ``await _run_inference_async(...)``\n",
724
+ " directly, since Jupyter already runs an event loop and supports top-level await.\n",
725
+ " This wrapper is provided for scripted or non-interactive contexts where no event\n",
726
+ " loop is active.\n",
727
+ " \"\"\"\n",
728
+ " try:\n",
729
+ " loop = asyncio.get_event_loop()\n",
730
+ " if loop.is_running():\n",
731
+ " import nest_asyncio\n",
732
+ " nest_asyncio.apply()\n",
733
+ " return loop.run_until_complete(\n",
734
+ " _run_inference_async(\n",
735
+ " df=df, image_column=image_column, system_prompt=system_prompt,\n",
736
+ " model=model, host=host, port=port, batch_size=batch_size,\n",
737
+ " max_tokens=max_tokens, temperature=temperature,\n",
738
+ " timeout_seconds=timeout_seconds, max_attempts=max_attempts,\n",
739
+ " )\n",
740
+ " )\n",
741
+ " except RuntimeError:\n",
742
+ " return asyncio.run(\n",
743
+ " _run_inference_async(\n",
744
+ " df=df, image_column=image_column, system_prompt=system_prompt,\n",
745
+ " model=model, host=host, port=port, batch_size=batch_size,\n",
746
+ " max_tokens=max_tokens, temperature=temperature,\n",
747
+ " timeout_seconds=timeout_seconds, max_attempts=max_attempts,\n",
748
+ " )\n",
749
+ " )"
750
+ ]
751
+ },
752
+ {
753
+ "cell_type": "code",
754
+ "execution_count": null,
755
+ "id": "7ab48bdf",
756
+ "metadata": {},
757
+ "outputs": [],
758
+ "source": [
759
+ "_inference_model = LORA_NAME if LORA_ADAPTER_PATH else MODEL_NAME\n",
760
+ "\n",
761
+ "inference_df, _total_inference_time = await _run_inference_async(\n",
762
+ " df=df,\n",
763
+ " image_column=IMAGE_COLUMN,\n",
764
+ " system_prompt=SYSTEM_PROMPT,\n",
765
+ " model=_inference_model,\n",
766
+ " host=VLLM_HOST,\n",
767
+ " port=VLLM_PORT,\n",
768
+ " batch_size=BATCH_SIZE,\n",
769
+ " max_tokens=MAX_TOKENS,\n",
770
+ " temperature=TEMPERATURE,\n",
771
+ ")\n",
772
+ "\n",
773
+ "display(\n",
774
+ " inference_df[\n",
775
+ " [GROUND_TRUTH_COLUMN, \"model_answer\", \"time_to_inference_total\", \"textual_degeneration\"]\n",
776
+ " ].head(3)\n",
777
+ ")"
778
+ ]
779
+ },
780
+ {
781
+ "cell_type": "markdown",
782
+ "id": "b10b976d",
783
+ "metadata": {},
784
+ "source": [
785
+ "### 1.5 Save Inference Results"
786
+ ]
787
+ },
788
+ {
789
+ "cell_type": "code",
790
+ "execution_count": null,
791
+ "id": "e6ecdbef",
792
+ "metadata": {},
793
+ "outputs": [],
794
+ "source": [
795
+ "output_path = Path(INFERENCE_OUTPUT_FILE)\n",
796
+ "inference_df.to_parquet(output_path, index=False)\n",
797
+ "\n",
798
+ "print(f\"Inference results saved to: {output_path.resolve()}\")\n",
799
+ "print(f\"Shape: {inference_df.shape}\")"
800
+ ]
801
+ },
802
+ {
803
+ "cell_type": "markdown",
804
+ "id": "4e3d3aac",
805
+ "metadata": {},
806
+ "source": [
807
+ "---\n",
808
+ "## Section 2 — Benchmark & Metrics Collection\n",
809
+ "\n",
810
+ "This section evaluates model prediction quality against the ground truth text using two standard metrics:\n",
811
+ "\n",
812
+ "| Metric | Description |\n",
813
+ "|---|---|\n",
814
+ "| **Levenshtein ratio** | Character-level edit-distance similarity — `1 − distance / max_length` (0–1, higher is better) |\n",
815
+ "| **BLEU score** | N-gram precision with NLTK `method1` smoothing (0–1, higher is better) |\n",
816
+ "\n",
817
+ "Results are saved as Parquet files in `BENCHMARK_RESULTS_DIR`. \n",
818
+ "`Benchmark.view()` reads all files in that folder and produces a comparative summary table."
819
+ ]
820
+ },
821
+ {
822
+ "cell_type": "markdown",
823
+ "id": "c98dab8f",
824
+ "metadata": {},
825
+ "source": [
826
+ "### 2.1 Benchmark Class"
827
+ ]
828
+ },
829
+ {
830
+ "cell_type": "code",
831
+ "execution_count": null,
832
+ "id": "6fbc9735",
833
+ "metadata": {},
834
+ "outputs": [],
835
+ "source": [
836
+ "class Benchmark:\n",
837
+ " \"\"\"\n",
838
+ " Evaluates OCR model predictions against ground truth using Levenshtein and BLEU metrics.\n",
839
+ "\n",
840
+ " Unlike a conventional benchmark class, no DataFrame is stored internally.\n",
841
+ " DataFrames are passed directly to :meth:`bench`, keeping the object stateless\n",
842
+ " and reusable across multiple evaluation runs.\n",
843
+ "\n",
844
+ " Parameters\n",
845
+ " ----------\n",
846
+ " columns : list[str]\n",
847
+ " Two-element list ``[ground_truth_column, prediction_column]``.\n",
848
+ " model_name : str\n",
849
+ " Human-readable identifier for the model being evaluated.\n",
850
+ " Used as the default output filename stem.\n",
851
+ "\n",
852
+ " Examples\n",
853
+ " --------\n",
854
+ " >>> bm = Benchmark([\"text\", \"model_answer\"], \"Dharma-OCR-LITE\")\n",
855
+ " >>> result_df = bm.bench(inference_df, output_dir=BENCHMARK_RESULTS_DIR)\n",
856
+ " >>> Benchmark.view(BENCHMARK_RESULTS_DIR)\n",
857
+ " \"\"\"\n",
858
+ "\n",
859
+ " def __init__(\n",
860
+ " self,\n",
861
+ " columns: list,\n",
862
+ " model_name: str,\n",
863
+ " ):\n",
864
+ " if not isinstance(columns, (list, tuple)) or len(columns) != 2:\n",
865
+ " raise ValueError(\"'columns' must be a list with exactly two column names.\")\n",
866
+ " if not isinstance(model_name, str) or not model_name:\n",
867
+ " raise ValueError(\"'model_name' must be a non-empty string.\")\n",
868
+ " self.columns = list(columns)\n",
869
+ " self.model_name = model_name\n",
870
+ "\n",
871
+ " def __repr__(self) -> str:\n",
872
+ " return (\n",
873
+ " f\"Benchmark(columns={self.columns!r}, model_name={self.model_name!r})\"\n",
874
+ " )\n",
875
+ "\n",
876
+ " # ── Private helpers ───────────────────────────────────────────────────────\n",
877
+ "\n",
878
+ " def _get_text_columns(self, df: pd.DataFrame, plain_text: bool = False):\n",
879
+ " \"\"\"Return (c1, c2) — ground truth and prediction as string Series.\"\"\"\n",
880
+ " col_gt, col_pred = self.columns\n",
881
+ " for col in (col_gt, col_pred):\n",
882
+ " if col not in df.columns:\n",
883
+ " raise ValueError(\n",
884
+ " f\"Column '{col}' not found in DataFrame. \"\n",
885
+ " f\"Available columns: {list(df.columns)}\"\n",
886
+ " )\n",
887
+ "\n",
888
+ " if plain_text:\n",
889
+ " # Both columns are normalised to plain text.\n",
890
+ " # If a value is already plain text (not valid JSON), it is returned as-is.\n",
891
+ " def _json_to_plain(x):\n",
892
+ " try:\n",
893
+ " parsed = eval(str(x).replace(\"null\", \"'null'\"))\n",
894
+ " if isinstance(parsed, dict):\n",
895
+ " return \"\\n\".join(\n",
896
+ " str(v) for v in parsed.values()\n",
897
+ " if v is not None and str(v).strip()\n",
898
+ " )\n",
899
+ " return str(x)\n",
900
+ " except Exception:\n",
901
+ " return str(x)\n",
902
+ " c1 = df[col_gt].apply(_json_to_plain)\n",
903
+ " c2 = df[col_pred].apply(_json_to_plain)\n",
904
+ " else:\n",
905
+ " c1 = df[col_gt].astype(str)\n",
906
+ " c2 = df[col_pred].astype(str)\n",
907
+ "\n",
908
+ " return c1, c2\n",
909
+ "\n",
910
+ " def _compute_metrics(self, df: pd.DataFrame, plain_text: bool = False) -> pd.DataFrame:\n",
911
+ " \"\"\"\n",
912
+ " Compute per-sample Levenshtein ratio and BLEU score.\n",
913
+ "\n",
914
+ " Returns a copy of ``df`` with two additional columns:\n",
915
+ " ``levenshtein_ratio`` and ``bleu``.\n",
916
+ " \"\"\"\n",
917
+ " result = df.copy()\n",
918
+ " c1, c2 = self._get_text_columns(result, plain_text=plain_text)\n",
919
+ "\n",
920
+ " result[\"levenshtein_ratio\"] = [\n",
921
+ " (\n",
922
+ " 1.0 - _lev_lib.distance(a, b) / max(len(a), len(b))\n",
923
+ " if max(len(a), len(b)) > 0\n",
924
+ " else 0.0\n",
925
+ " )\n",
926
+ " for a, b in zip(c1, c2)\n",
927
+ " ]\n",
928
+ "\n",
929
+ " smoother = SmoothingFunction().method1\n",
930
+ " result[\"bleu\"] = [\n",
931
+ " sentence_bleu([a.split()], b.split(), smoothing_function=smoother)\n",
932
+ " for a, b in zip(c1, c2)\n",
933
+ " ]\n",
934
+ "\n",
935
+ " return result\n",
936
+ "\n",
937
+ " # ── Public API ────────────────────────────────────────────────────────────\n",
938
+ "\n",
939
+ " def bench(\n",
940
+ " self,\n",
941
+ " df: pd.DataFrame,\n",
942
+ " result_name: Optional[str] = None,\n",
943
+ " output_dir: str = \"benchmark_results\",\n",
944
+ " total_wall_time: Optional[float] = None,\n",
945
+ " plain_text: bool = False,\n",
946
+ " ) -> pd.DataFrame:\n",
947
+ " \"\"\"\n",
948
+ " Compute text similarity metrics on the given DataFrame and save the results.\n",
949
+ "\n",
950
+ " Parameters\n",
951
+ " ----------\n",
952
+ " df : pd.DataFrame\n",
953
+ " Must contain the two columns listed in ``self.columns``.\n",
954
+ " May also contain ``time_to_inference`` and ``textual_degeneration``\n",
955
+ " columns produced by the inference step — these are preserved in the output\n",
956
+ " and used by :meth:`view` to compute timing and degeneration statistics.\n",
957
+ " result_name : str, optional\n",
958
+ " Stem of the output Parquet filename (without ``.parquet`` extension).\n",
959
+ " Defaults to ``self.model_name``.\n",
960
+ " output_dir : str\n",
961
+ " Directory where the result file is saved.\n",
962
+ " Created automatically if it does not exist.\n",
963
+ " Pass ``BENCHMARK_RESULTS_DIR`` to keep results visible to :meth:`view`.\n",
964
+ " total_wall_time : float, optional\n",
965
+ " Accepted for backward compatibility; no longer used internally.\n",
966
+ " Throughput is derived from ``inference_tokens_per_second`` when available.\n",
967
+ " plain_text : bool, optional\n",
968
+ " If ``False`` (default), the ground truth column is used directly as-is.\n",
969
+ " If ``True``, the column contains JSON strings; all values are extracted\n",
970
+ " and joined with ``\\n`` into plain text before comparison.\n",
971
+ "\n",
972
+ " Returns\n",
973
+ " -------\n",
974
+ " pd.DataFrame\n",
975
+ " Input DataFrame with ``levenshtein_ratio`` and ``bleu`` columns added.\n",
976
+ " \"\"\"\n",
977
+ " if not isinstance(df, pd.DataFrame):\n",
978
+ " raise TypeError(\"'df' must be a pandas DataFrame.\")\n",
979
+ "\n",
980
+ " result_df = self._compute_metrics(df, plain_text=plain_text)\n",
981
+ "\n",
982
+ " stem = (result_name or self.model_name).replace(\" \", \"_\")\n",
983
+ " out_dir = Path(output_dir)\n",
984
+ " out_dir.mkdir(parents=True, exist_ok=True)\n",
985
+ " out_path = out_dir / f\"{stem}.parquet\"\n",
986
+ " result_df.to_parquet(out_path, index=False)\n",
987
+ "\n",
988
+ " lev_mean = result_df[\"levenshtein_ratio\"].mean()\n",
989
+ " bleu_mean = result_df[\"bleu\"].mean()\n",
990
+ " score = (lev_mean + bleu_mean) / 2\n",
991
+ "\n",
992
+ " print(f\"Benchmark saved: {out_path.resolve()}\")\n",
993
+ " print(f\" Samples : {len(result_df):,}\")\n",
994
+ " print(f\" Levenshtein ratio : {lev_mean:.4f}\")\n",
995
+ " print(f\" BLEU : {bleu_mean:.4f}\")\n",
996
+ " print(f\" Benchmark score : {score:.4f}\")\n",
997
+ " if \"inference_tokens_per_second\" in result_df.columns:\n",
998
+ " tps = result_df[\"inference_tokens_per_second\"].mean()\n",
999
+ " print(f\" Throughput : {tps:.1f} tokens/s\")\n",
1000
+ "\n",
1001
+ " return result_df\n",
1002
+ "\n",
1003
+ " @staticmethod\n",
1004
+ " def view(folder_path: str) -> pd.DataFrame:\n",
1005
+ " \"\"\"\n",
1006
+ " Build an aggregated summary table from all benchmark Parquet files in a folder.\n",
1007
+ "\n",
1008
+ " Recursively searches for ``.parquet`` files under ``folder_path`` and computes\n",
1009
+ " aggregate statistics for each one. Displays the result as an HTML table in\n",
1010
+ " Jupyter and also returns it as a DataFrame.\n",
1011
+ "\n",
1012
+ " Parameters\n",
1013
+ " ----------\n",
1014
+ " folder_path : str\n",
1015
+ " Root directory to search for benchmark result files\n",
1016
+ " (typically ``BENCHMARK_RESULTS_DIR``).\n",
1017
+ "\n",
1018
+ " Returns\n",
1019
+ " -------\n",
1020
+ " pd.DataFrame\n",
1021
+ " One row per benchmark file with the following columns:\n",
1022
+ "\n",
1023
+ " ========================= =====================================================\n",
1024
+ " Column Description\n",
1025
+ " ========================= =====================================================\n",
1026
+ " ``benchmark_score`` ``(levenshtein_ratio_mean + bleu_mean) / 2``\n",
1027
+ " ``textual_degeneration (%)`` Percentage of samples flagged as textually degenerate\n",
1028
+ " ``mean_time_per_inference (s)`` Total wall time divided by number of samples (total_elapsed / N) — matches paper's Time/Page\n",
1029
+ " ``throughput (tokens/s)`` Mean tokens per second (inference_tokens_per_second mean)\n",
1030
+ " ``latency (s)`` Mean end-to-end per-request time (time_to_inference_total mean: preprocess + inference + postprocess)\n",
1031
+ "\n",
1032
+ " ``levenshtein_ratio_mean`` and ``bleu`` are saved in the result Parquet\n",
1033
+ " files but intentionally omitted from this summary view.\n",
1034
+ " ========================= =====================================================\n",
1035
+ "\n",
1036
+ " Columns that cannot be computed from the saved file are left blank.\n",
1037
+ " \"\"\"\n",
1038
+ " root = Path(folder_path)\n",
1039
+ " if not root.exists():\n",
1040
+ " raise FileNotFoundError(f\"Folder not found: {root.resolve()}\")\n",
1041
+ "\n",
1042
+ " parquet_files = sorted(root.rglob(\"*.parquet\"))\n",
1043
+ " if not parquet_files:\n",
1044
+ " print(f\"No .parquet files found under: {root.resolve()}\")\n",
1045
+ " return pd.DataFrame()\n",
1046
+ "\n",
1047
+ " rows = []\n",
1048
+ " for fpath in parquet_files:\n",
1049
+ " try:\n",
1050
+ " data = pd.read_parquet(fpath)\n",
1051
+ " except Exception as exc:\n",
1052
+ " print(f\"Could not read {fpath.name}: {exc}\")\n",
1053
+ " continue\n",
1054
+ "\n",
1055
+ " def _safe_mean(col: str):\n",
1056
+ " return float(data[col].mean()) if col in data.columns else None\n",
1057
+ "\n",
1058
+ " lev_mean = _safe_mean(\"levenshtein_ratio\")\n",
1059
+ " bleu_mean = _safe_mean(\"bleu\")\n",
1060
+ " score = (\n",
1061
+ " (lev_mean + bleu_mean) / 2\n",
1062
+ " if lev_mean is not None and bleu_mean is not None\n",
1063
+ " else None\n",
1064
+ " )\n",
1065
+ "\n",
1066
+ " tps = _safe_mean(\"inference_tokens_per_second\")\n",
1067
+ "\n",
1068
+ " # latency = mean end-to-end per-request time (preprocess + inference + postprocess)\n",
1069
+ " latency = _safe_mean(\"time_to_inference_total\")\n",
1070
+ "\n",
1071
+ " # mean_time_per_inference = total_elapsed / N, stored as a constant column.\n",
1072
+ " # Falls back to latency when running against older Parquet files that\n",
1073
+ " # predate the time_per_page column.\n",
1074
+ " mean_time = _safe_mean(\"time_per_page\") or latency\n",
1075
+ "\n",
1076
+ " deg_frac = _safe_mean(\"textual_degeneration\")\n",
1077
+ " inf_gen_pct = deg_frac * 100 if deg_frac is not None else None\n",
1078
+ "\n",
1079
+ " def _fmt(v, decimals=4):\n",
1080
+ " return round(v, decimals) if v is not None else \"\"\n",
1081
+ "\n",
1082
+ " rows.append({\n",
1083
+ " \"model\": fpath.stem,\n",
1084
+ " \"benchmark_score\": _fmt(score),\n",
1085
+ " \"textual_degeneration (%)\": _fmt(inf_gen_pct, 2),\n",
1086
+ " \"mean_time_per_inference (s)\": _fmt(mean_time, 3),\n",
1087
+ " \"throughput (tokens/s)\": _fmt(tps, 2),\n",
1088
+ " \"latency (s)\": _fmt(latency, 3),\n",
1089
+ " })\n",
1090
+ "\n",
1091
+ " if not rows:\n",
1092
+ " print(\"No valid benchmark files found.\")\n",
1093
+ " return pd.DataFrame()\n",
1094
+ "\n",
1095
+ " summary = pd.DataFrame(rows).set_index(\"model\").sort_values(\"benchmark_score\", ascending=False)\n",
1096
+ "\n",
1097
+ " display(summary)\n",
1098
+ " return summary\n",
1099
+ "\n",
1100
+ "\n",
1101
+ "print(\"Benchmark class loaded.\")"
1102
+ ]
1103
+ },
1104
+ {
1105
+ "cell_type": "markdown",
1106
+ "id": "c7243b50",
1107
+ "metadata": {},
1108
+ "source": [
1109
+ "### 2.2 Load Inference Results\n",
1110
+ "\n",
1111
+ "Run the cell below to reload inference results from disk. \n",
1112
+ "**Skip it** if you are continuing directly from Section 1 — `inference_df` is already defined."
1113
+ ]
1114
+ },
1115
+ {
1116
+ "cell_type": "code",
1117
+ "execution_count": null,
1118
+ "id": "0c2a9a94",
1119
+ "metadata": {},
1120
+ "outputs": [],
1121
+ "source": [
1122
+ "_results_path = Path(INFERENCE_OUTPUT_FILE)\n",
1123
+ "\n",
1124
+ "if _results_path.exists():\n",
1125
+ " inference_df = pd.read_parquet(_results_path)\n",
1126
+ " # Wall time is not stored in the Parquet file — throughput will be estimated from latency\n",
1127
+ " _total_inference_time = None\n",
1128
+ " print(f\"Loaded from {_results_path.resolve()} — {len(inference_df):,} rows\")\n",
1129
+ " display(\n",
1130
+ " inference_df[[GROUND_TRUTH_COLUMN, \"model_answer\"]].head(3)\n",
1131
+ " )\n",
1132
+ "else:\n",
1133
+ " # Ensure these variables are always defined so Cell 21 does not raise NameError\n",
1134
+ " inference_df = None\n",
1135
+ " _total_inference_time = None\n",
1136
+ " print(\n",
1137
+ " f\"'{INFERENCE_OUTPUT_FILE}' not found. \"\n",
1138
+ " \"Run Section 1 first, or update INFERENCE_OUTPUT_FILE to point to your results.\"\n",
1139
+ " )"
1140
+ ]
1141
+ },
1142
+ {
1143
+ "cell_type": "markdown",
1144
+ "id": "b55a7d3f",
1145
+ "metadata": {},
1146
+ "source": [
1147
+ "### 2.3 Run Benchmark\n",
1148
+ "\n",
1149
+ "Instantiate `Benchmark` with the column names, then call `.bench()` to compute per-sample metrics and write the results to `BENCHMARK_RESULTS_DIR`. \n",
1150
+ "Re-run this cell with a different `result_name` (or after a new inference run) to accumulate multiple benchmark files for comparison."
1151
+ ]
1152
+ },
1153
+ {
1154
+ "cell_type": "code",
1155
+ "execution_count": null,
1156
+ "id": "22a27c8a",
1157
+ "metadata": {},
1158
+ "outputs": [],
1159
+ "source": [
1160
+ "bm = Benchmark(\n",
1161
+ " columns=[GROUND_TRUTH_COLUMN, PREDICTION_COLUMN],\n",
1162
+ " model_name=MODEL_NAME.split(\"/\")[-1], # use the short model name as the file stem\n",
1163
+ ")\n",
1164
+ "\n",
1165
+ "benchmarked_df = bm.bench(\n",
1166
+ " df=inference_df,\n",
1167
+ " output_dir=BENCHMARK_RESULTS_DIR,\n",
1168
+ " total_wall_time=_total_inference_time, # None if results were loaded from disk\n",
1169
+ " plain_text=PLAIN_TEXT,\n",
1170
+ ")\n",
1171
+ "\n",
1172
+ "display(\n",
1173
+ " benchmarked_df[\n",
1174
+ " [GROUND_TRUTH_COLUMN, PREDICTION_COLUMN, \"levenshtein_ratio\", \"bleu\"]\n",
1175
+ " ].head(5)\n",
1176
+ ")"
1177
+ ]
1178
+ },
1179
+ {
1180
+ "cell_type": "markdown",
1181
+ "id": "050d7a5c",
1182
+ "metadata": {},
1183
+ "source": [
1184
+ "### 2.4 View Results Summary Table\n",
1185
+ "\n",
1186
+ "Read all `.parquet` files in `BENCHMARK_RESULTS_DIR` (including subdirectories) and display an aggregated comparison table. \n",
1187
+ "Run this cell at any time — even after adding new benchmark files — to refresh the view."
1188
+ ]
1189
+ },
1190
+ {
1191
+ "cell_type": "code",
1192
+ "execution_count": null,
1193
+ "id": "d8e95734",
1194
+ "metadata": {},
1195
+ "outputs": [],
1196
+ "source": [
1197
+ "summary = Benchmark.view(BENCHMARK_RESULTS_DIR)"
1198
+ ]
1199
+ },
1200
+ {
1201
+ "cell_type": "markdown",
1202
+ "id": "de58314c",
1203
+ "metadata": {},
1204
+ "source": [
1205
+ "---\n",
1206
+ "### Cleanup — Stop vLLM Server (Optional)\n",
1207
+ "\n",
1208
+ "Uncomment the block below to shut down the local vLLM server when you are finished."
1209
+ ]
1210
+ },
1211
+ {
1212
+ "cell_type": "code",
1213
+ "execution_count": null,
1214
+ "id": "c6e3e5e3",
1215
+ "metadata": {},
1216
+ "outputs": [],
1217
+ "source": [
1218
+ "if vllm_process is not None:\n",
1219
+ " vllm_process.terminate()\n",
1220
+ " try:\n",
1221
+ " vllm_process.wait(timeout=30)\n",
1222
+ " print(\"vLLM server stopped.\")\n",
1223
+ " except subprocess.TimeoutExpired:\n",
1224
+ " vllm_process.kill()\n",
1225
+ " print(\"vLLM server force-killed.\")\n",
1226
+ "else:\n",
1227
+ " print(\"No local server process to stop (START_LOCAL_SERVER was False).\")"
1228
+ ]
1229
+ }
1230
+ ],
1231
+ "metadata": {
1232
+ "kernelspec": {
1233
+ "display_name": ".venv",
1234
+ "language": "python",
1235
+ "name": "python3"
1236
+ },
1237
+ "language_info": {
1238
+ "codemirror_mode": {
1239
+ "name": "ipython",
1240
+ "version": 3
1241
+ },
1242
+ "file_extension": ".py",
1243
+ "mimetype": "text/x-python",
1244
+ "name": "python",
1245
+ "nbconvert_exporter": "python",
1246
+ "pygments_lexer": "ipython3",
1247
+ "version": "3.12.8"
1248
+ }
1249
+ },
1250
+ "nbformat": 4,
1251
+ "nbformat_minor": 5
1252
+ }