{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Dharma-OCR — Model Evaluation\n", "\n", "This notebook provides a complete, self-contained pipeline for evaluating the **Dharma-OCR** model family.\n", "It is organized in two main sections:\n", "\n", "| Section | Description |\n", "|---|---|\n", "| **1 — Model Inference** | Loads the evaluation dataset, serves the model via vLLM, and runs batched inference |\n", "| **2 — Benchmark & Metrics** | Computes quality metrics and generates a comparative summary table |\n", "\n", "---\n", "\n", "> **Hardware requirements:** A CUDA-capable GPU is required to run vLLM locally. \n", "> **Python requirements:** Python 3.10+ is required. \n", "\n", "### Dependencies\n", "\n", "Install the required packages before running:\n", "\n", "```bash\n", "pip install -r requirements.txt\n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "## ⚙️ Parameters\n", "\n", "Configure **all** settings here before running the notebook. \n", "No other cell needs to be edited." ] }, { "cell_type": "code", "execution_count": null, "id": "278fcaff", "metadata": {}, "outputs": [], "source": [ "# ============================================================\n", "# MODEL\n", "# ============================================================\n", "\n", "# Hugging Face model ID for the base OCR model\n", "MODEL_NAME = \"Dharma-AI/Dharma-OCR-LITE\"\n", "\n", "# (Optional) Local path to a LoRA adapter directory.\n", "# Set to None to evaluate the base model without any adapter.\n", "LORA_ADAPTER_PATH = None # e.g. \"adapters/my_lora\"\n", "\n", "# Name registered for the LoRA module in vLLM (only used when LORA_ADAPTER_PATH is set)\n", "LORA_NAME = \"ocr-lora\"\n", "\n", "# GPU / server configuration\n", "GPU_MEMORY_UTILIZATION = 0.90\n", "TENSOR_PARALLEL_SIZE = 1\n", "MAX_MODEL_LEN = 65536\n", "MAX_NUM_BATCHED_TOKENS = 32000\n", "MAX_LORA_RANK = 128\n", "\n", "# ============================================================\n", "# INFERENCE\n", "# ============================================================\n", "\n", "# Number of concurrent inference requests in flight at any time.\n", "# Default value based on the value used in the original Dharma-OCR paper.\n", "# WARNING: Default for a L40S system, adjust with caution.\n", "# Increase for higher throughput on large datasets; decrease to reduce GPU memory pressure.\n", "BATCH_SIZE = 30\n", "\n", "# Maximum number of tokens the model may generate per response\n", "MAX_TOKENS = 8192\n", "\n", "# Sampling temperature: 0 = greedy / deterministic (recommended for OCR evaluation)\n", "TEMPERATURE = 0\n", "\n", "# System prompt sent to the model before each document image\n", "SYSTEM_PROMPT = (\n", " \"You are an expert OCR system. Extract all text from the provided document image \"\n", " \"exactly as it appears, preserving the original layout and structure. \"\n", " \"Return only the extracted text with no additional commentary.\"\n", ")\n", "\n", "# ============================================================\n", "# SERVER\n", "# ============================================================\n", "\n", "# Set to False if you already have a running OpenAI-compatible endpoint\n", "# (e.g. a remote vLLM server). The notebook will then skip the server startup cell.\n", "START_LOCAL_SERVER = True\n", "\n", "VLLM_HOST = \"localhost\"\n", "VLLM_PORT = 8000\n", "VLLM_STARTUP_TIMEOUT_SECONDS = 600 # Maximum seconds to wait for the server to become ready\n", "\n", "# ============================================================\n", "# DATASET\n", "# ============================================================\n", "\n", "# Dataset source — either a local file path or a Hugging Face dataset ID.\n", "DATASET_PATH = \"Dharma-AI/DharmaOCR-Benchmark\"\n", "\n", "# Split to load when using a Hugging Face dataset (ignored for local files)\n", "DATASET_SPLIT = \"test\"\n", "\n", "# Column containing base64-encoded document images (JPEG / PNG / WebP).\n", "IMAGE_COLUMN = \"image_base64\"\n", "\n", "# Column containing the ground truth transcriptions.\n", "GROUND_TRUTH_COLUMN = \"assistant\"\n", "\n", "# Whether to normalise both columns to plain text before metric computation.\n", "#\n", "# False — both columns are used as-is (default).\n", "# True — JSON values in either column are extracted and joined with newlines\n", "# before comparison. Columns that are already plain text are unchanged.\n", "# Use to normalize comparisons. \n", "PLAIN_TEXT = True\n", "\n", "# Column containing the model predictions.\n", "# This is the \"model_answer\" column in the inference output Parquet file.\n", "PREDICTION_COLUMN = \"model_answer\"\n", "\n", "# ============================================================\n", "# OUTPUT\n", "# ============================================================\n", "\n", "# Directory where benchmark result files are saved (relative to this notebook)\n", "BENCHMARK_RESULTS_DIR = \"benchmark_results\"\n", "\n", "# Filename for the inference output Parquet file.\n", "# DATASET_PATH may contain '/' (e.g. a HuggingFace org/repo slug), so we\n", "# replace it with '_' to produce a flat filename rather than a subdirectory path.\n", "INFERENCE_OUTPUT_FILE = DATASET_PATH.replace(\"/\", \"_\") + \".parquet\"" ] }, { "cell_type": "markdown", "id": "d8266d86", "metadata": {}, "source": [ "---\n", "## Section 1 — Model Inference\n", "\n", "This section runs the configured model on the evaluation dataset and saves the raw predictions for benchmarking.\n", "\n", "**Steps:**\n", "1. Import dependencies\n", "2. Load the evaluation dataset\n", "3. *(Optional)* Start the vLLM server locally\n", "4. Run batch inference\n", "5. Save results to disk" ] }, { "cell_type": "markdown", "id": "d031d9db", "metadata": {}, "source": [ "### 1.1 Imports & Setup" ] }, { "cell_type": "code", "execution_count": null, "id": "cf42a7a5", "metadata": {}, "outputs": [], "source": [ "import asyncio\n", "import base64\n", "import json\n", "import logging\n", "import os\n", "import subprocess\n", "import time\n", "from pathlib import Path\n", "from typing import Optional\n", "\n", "import httpx\n", "import pandas as pd\n", "from openai import AsyncOpenAI\n", "from tqdm.asyncio import tqdm as async_tqdm\n", "\n", "# Benchmark metrics (used in Section 2 — imported here to fail fast)\n", "import nltk\n", "from nltk.translate.bleu_score import sentence_bleu, SmoothingFunction\n", "import Levenshtein as _lev_lib\n", "\n", "# Jupyter display utilities\n", "from IPython.display import display, HTML\n", "\n", "# Suppress verbose HTTP client logs\n", "logging.getLogger(\"httpx\").setLevel(logging.WARNING)\n", "logging.getLogger(\"openai\").setLevel(logging.WARNING)\n", "\n", "# Download NLTK tokenizer data required for BLEU scoring\n", "try:\n", " nltk.data.find(\"tokenizers/punkt\")\n", "except LookupError:\n", " nltk.download(\"punkt\", quiet=True)\n", "\n", "print(\"All dependencies loaded successfully.\")" ] }, { "cell_type": "markdown", "id": "4f468fd3", "metadata": {}, "source": [ "### 1.2 Load Evaluation Dataset" ] }, { "cell_type": "code", "execution_count": null, "id": "ceb6a2a5", "metadata": {}, "outputs": [], "source": [ "def _load_dataset(dataset_path: str, split: str = \"test\") -> \"pd.DataFrame\":\n", " \"\"\"\n", " Load the evaluation dataset from a local Parquet file or a Hugging Face dataset ID.\n", "\n", " Detection logic:\n", " - If ``dataset_path`` points to an existing file on disk -> read as Parquet\n", " - Otherwise -> load via the HF `datasets` library\n", " \"\"\"\n", " local_path = Path(dataset_path)\n", "\n", " if local_path.exists():\n", " print(f\"Source detected: local file ({local_path.resolve()})\")\n", " return pd.read_parquet(local_path)\n", "\n", " # Not a local file — treat as a Hugging Face dataset ID\n", " print(f\"Source detected: Hugging Face dataset (id='{dataset_path}', split='{split}')\")\n", " try:\n", " from datasets import load_dataset as hf_load_dataset\n", " except ImportError:\n", " raise ImportError(\n", " \"The 'datasets' package is required to load Hugging Face datasets.\\n\"\n", " \"Install it with: pip install datasets\"\n", " )\n", " hf_ds = hf_load_dataset(dataset_path, split=split)\n", " return hf_ds.to_pandas()\n", "\n", "\n", "df = _load_dataset(DATASET_PATH, split=DATASET_SPLIT)\n", "\n", "assert IMAGE_COLUMN in df.columns, (\n", " f\"Column '{IMAGE_COLUMN}' not found. Available columns: {list(df.columns)}\"\n", ")\n", "assert GROUND_TRUTH_COLUMN in df.columns, (\n", " f\"Column '{GROUND_TRUTH_COLUMN}' not found. Available columns: {list(df.columns)}\"\n", ")\n", "\n", "print(f\"Dataset loaded: {len(df):,} rows, {len(df.columns)} columns\")\n", "display(df[[GROUND_TRUTH_COLUMN, IMAGE_COLUMN]].head(2))\n" ] }, { "cell_type": "markdown", "id": "cb619fc7", "metadata": {}, "source": [ "### 1.3 Start vLLM Server\n", "\n", "> **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", "> Make sure `VLLM_HOST` and `VLLM_PORT` point to your server.\n", "\n", "This cell launches vLLM as a local subprocess and waits until it is ready to accept requests.\n", "A LoRA adapter is automatically configured if `LORA_ADAPTER_PATH` is set." ] }, { "cell_type": "code", "execution_count": null, "id": "c9f23a92", "metadata": {}, "outputs": [], "source": [ "def _build_vllm_command(\n", " model_name: str,\n", " host: str,\n", " port: int,\n", " gpu_memory_utilization: float,\n", " tensor_parallel_size: int,\n", " max_model_len: int,\n", " max_num_batched_tokens: int,\n", " lora_adapter_path: Optional[str] = None,\n", " lora_name: str = \"lora-1\",\n", " max_lora_rank: int = 128,\n", ") -> list:\n", " \"\"\"Build the `vllm serve` command as an argument list.\"\"\"\n", " cmd = [\n", " \"vllm\", \"serve\", model_name,\n", " f\"--host={host}\",\n", " f\"--port={port}\",\n", " f\"--gpu-memory-utilization={gpu_memory_utilization}\",\n", " f\"--tensor-parallel-size={tensor_parallel_size}\",\n", " f\"--max-model-len={max_model_len}\",\n", " f\"--max-num-batched-tokens={max_num_batched_tokens}\",\n", " \"--trust-remote-code\",\n", " \"--dtype=auto\",\n", " \"--load-format=auto\",\n", " \"--kv-cache-dtype=auto\",\n", " ]\n", " if lora_adapter_path:\n", " lora_module = json.dumps({\n", " \"name\": lora_name,\n", " \"path\": lora_adapter_path,\n", " \"base_model_name\": model_name,\n", " })\n", " cmd += [\n", " \"--enable-lora\",\n", " f\"--max-lora-rank={max_lora_rank}\",\n", " \"--lora-modules\", lora_module,\n", " ]\n", " return cmd\n", "\n", "\n", "def _wait_for_server(host: str, port: int, timeout: int = 300) -> bool:\n", " \"\"\"Poll the server health endpoint until it responds or the timeout is reached.\"\"\"\n", " url = f\"http://{host}:{port}/health\"\n", " deadline = time.time() + timeout\n", " print(f\"Waiting for vLLM server at {url} (timeout: {timeout}s)\", end=\"\", flush=True)\n", " while time.time() < deadline:\n", " try:\n", " resp = httpx.get(url, timeout=5)\n", " if resp.status_code == 200:\n", " print(\" ready!\")\n", " return True\n", " except Exception:\n", " pass\n", " time.sleep(5)\n", " print(\".\", end=\"\", flush=True)\n", " print(\" timed out.\")\n", " return False\n", "\n", "\n", "vllm_process = None\n", "\n", "if START_LOCAL_SERVER:\n", " vllm_cmd = _build_vllm_command(\n", " model_name=MODEL_NAME,\n", " host=VLLM_HOST,\n", " port=VLLM_PORT,\n", " gpu_memory_utilization=GPU_MEMORY_UTILIZATION,\n", " tensor_parallel_size=TENSOR_PARALLEL_SIZE,\n", " max_model_len=MAX_MODEL_LEN,\n", " max_num_batched_tokens=MAX_NUM_BATCHED_TOKENS,\n", " lora_adapter_path=LORA_ADAPTER_PATH,\n", " lora_name=LORA_NAME,\n", " max_lora_rank=MAX_LORA_RANK,\n", " )\n", "\n", " print(\"Starting vLLM server with command:\")\n", " print(\" \".join(vllm_cmd))\n", " print()\n", "\n", " vllm_process = subprocess.Popen(\n", " vllm_cmd,\n", " stdout=open(\"vllm.log\", \"w\"),\n", " stderr=subprocess.STDOUT,\n", " text=True,\n", " )\n", "\n", " ready = _wait_for_server(VLLM_HOST, VLLM_PORT, timeout=VLLM_STARTUP_TIMEOUT_SECONDS)\n", " if ready:\n", " print(f\"vLLM server is live at http://{VLLM_HOST}:{VLLM_PORT}\")\n", " else:\n", " print(\"Server did not become ready within the timeout. Check vllm_process.stdout for details.\")\n", "else:\n", " print(f\"Using existing server at http://{VLLM_HOST}:{VLLM_PORT}\")" ] }, { "cell_type": "markdown", "id": "da46db47", "metadata": {}, "source": [ "### 1.4 Run Batch Inference\n", "\n", "All requests are dispatched concurrently using an async event loop with a semaphore that\n", "caps the number of in-flight requests to `BATCH_SIZE` at any given time.\n", "A new request is submitted as soon as any in-flight one completes, keeping the server\n", "fully utilised throughout the run.\n", "\n", "Three columns are added to the dataset:\n", "\n", "| Column | Description |\n", "|---|---|\n", "| `model_answer` | Raw text returned by the model |\n", "| `time_to_preprocess` | Message-building time — mirrors library phase 1 |\n", "| `time_to_inference` | API round-trip only — mirrors library phase 2 |\n", "| `time_to_postprocess` | Response-processing time — mirrors library phase 3 |\n", "| `time_to_inference_total` | End-to-end latency per request (sum of all three phases) |\n", "| `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 |" ] }, { "cell_type": "code", "execution_count": null, "id": "33ba4e7e", "metadata": {}, "outputs": [], "source": [ "# ── Inference helpers ─────────────────────────────────────────────────────────\n", "\n", "def _encode_image(image_data) -> str:\n", " \"\"\"Return a clean base64 string from raw bytes or an existing base64 string.\"\"\"\n", " if isinstance(image_data, bytes):\n", " return base64.b64encode(image_data).decode()\n", " return str(image_data).strip().replace(\"\\n\", \"\").replace(\"\\r\", \"\")\n", "\n", "\n", "def _detect_image_format(b64: str) -> str:\n", " \"\"\"Infer the image MIME sub-type from the leading base64 bytes.\"\"\"\n", " if b64.startswith(\"/9j/\"):\n", " return \"jpeg\"\n", " if b64.startswith(\"iVBORw\"):\n", " return \"png\"\n", " if b64.startswith(\"UklGR\"):\n", " return \"webp\"\n", " return \"jpeg\"\n", "\n", "\n", "def _build_messages(image_data, system_prompt: str) -> list:\n", " \"\"\"Build an OpenAI-compatible chat message list for a single document image.\"\"\"\n", " b64 = _encode_image(image_data)\n", " fmt = _detect_image_format(b64)\n", " return [\n", " {\"role\": \"system\", \"content\": system_prompt},\n", " {\n", " \"role\": \"user\",\n", " \"content\": [\n", " {\n", " \"type\": \"image_url\",\n", " \"image_url\": {\"url\": f\"data:image/{fmt};base64,{b64}\"},\n", " }\n", " ],\n", " },\n", " ]\n", "\n", "\n", "async def _infer_single_async(\n", " client: AsyncOpenAI,\n", " image_data,\n", " system_prompt: str,\n", " model: str,\n", " max_tokens: int,\n", " temperature: float,\n", " semaphore: asyncio.Semaphore,\n", " results: list,\n", " index: int,\n", " pbar,\n", " *,\n", " max_attempts: int = 4,\n", " base_delay_seconds: float = 0.5,\n", ") -> None:\n", " \"\"\"\n", " Execute a single chat-completion request and store the result in ``results[index]``.\n", "\n", " Timing follows the same three-phase structure as the dharma-ai library\n", " (basic_pipeline.BasicPipeline):\n", "\n", " time_to_preprocess — message building (base64 encode + format detection)\n", " time_to_inference — API round-trip only (chat.completions.create)\n", " time_to_postprocess — response processing (degeneration check, token count)\n", " time_to_inference_total — sum of all three phases (end-to-end latency)\n", "\n", " Concurrency is controlled by ``semaphore``; the timer starts only after a slot\n", " is acquired, so semaphore queue wait is excluded from all timing columns.\n", " The timeout is enforced at the HTTP transport layer (``httpx.Timeout`` on the\n", " client) so timed-out connections are properly reset on the server side.\n", " On failure the request is retried up to ``max_attempts`` times with exponential\n", " backoff. If all attempts fail the result is recorded as an error string.\n", " \"\"\"\n", " async with semaphore:\n", " last_error: Exception | None = None\n", "\n", " for attempt in range(max(1, max_attempts)):\n", " try:\n", " # ── Preprocess ────────────────────────────────────────────────\n", " t_preprocess_start = time.time()\n", " messages = _build_messages(image_data, system_prompt)\n", " t_inference_start = time.time()\n", "\n", " # ── Inference ─────────────────────────────────────────────────\n", " response = await client.chat.completions.create(\n", " model=model,\n", " messages=messages,\n", " max_tokens=max_tokens,\n", " temperature=temperature,\n", " extra_headers={\"X-Request-Id\": str(index)},\n", " )\n", " t_postprocess_start = time.time()\n", "\n", " # ── Postprocess ───────────────────────────────────────────────\n", " choice = response.choices[0]\n", " content = choice.message.content or \"\"\n", " textual_degeneration = (\n", " len(content) >= 15\n", " and choice.finish_reason == \"length\"\n", " and content.count(content[-15:]) >= 4\n", " )\n", " num_output_tokens = (response.usage.completion_tokens\n", " if response.usage is not None else 0)\n", " t_end = time.time()\n", "\n", " time_to_preprocess = t_inference_start - t_preprocess_start\n", " time_to_inference = t_postprocess_start - t_inference_start\n", " time_to_postprocess = t_end - t_postprocess_start\n", " total_elapsed = t_end - t_preprocess_start\n", "\n", " inference_tokens_per_second = (num_output_tokens / total_elapsed\n", " if total_elapsed > 0 else 0.0)\n", "\n", " results[index] = {\n", " \"model_answer\": content,\n", " \"time_to_preprocess\": time_to_preprocess,\n", " \"time_to_inference\": time_to_inference,\n", " \"time_to_postprocess\": time_to_postprocess,\n", " \"time_to_inference_total\": total_elapsed,\n", " \"textual_degeneration\": textual_degeneration,\n", " \"num_output_tokens\": num_output_tokens,\n", " \"inference_tokens_per_second\": inference_tokens_per_second,\n", " }\n", " pbar.update(1)\n", " return\n", "\n", " except Exception as exc:\n", " last_error = exc\n", " if attempt < max(1, max_attempts) - 1:\n", " await asyncio.sleep(base_delay_seconds * (2 ** attempt))\n", "\n", " results[index] = {\n", " \"model_answer\": f\"ERROR: {last_error}\",\n", " \"time_to_preprocess\": 0.0,\n", " \"time_to_inference\": 0.0,\n", " \"time_to_postprocess\": 0.0,\n", " \"time_to_inference_total\": 0.0,\n", " \"textual_degeneration\": False,\n", " \"num_output_tokens\": 0,\n", " \"inference_tokens_per_second\": 0.0,\n", " }\n", " pbar.update(1)\n", "\n", "\n", "async def _run_inference_async(\n", " df: pd.DataFrame,\n", " image_column: str,\n", " system_prompt: str,\n", " model: str,\n", " host: str,\n", " port: int,\n", " batch_size: int = 30,\n", " max_tokens: int = 4096,\n", " temperature: float = 0,\n", " timeout_seconds: float = 600.0,\n", " max_attempts: int = 4,\n", ") -> tuple: # noqa: C901\n", " \"\"\"\n", " Run inference on a DataFrame of document images using async concurrency.\n", "\n", " All requests are created upfront as coroutines and driven by ``asyncio.gather``.\n", " An ``asyncio.Semaphore`` caps the number of requests in flight at any time to\n", " ``batch_size``, so as soon as one request finishes the next one starts without\n", " any gap. Each individual request supports per-attempt timeouts and automatic\n", " retry with exponential backoff (see ``_infer_single_async``).\n", "\n", " The timeout is enforced via ``httpx.Timeout`` on the HTTP transport layer, not\n", " via ``asyncio.wait_for``. This distinction matters: an httpx-level timeout\n", " properly resets the TCP connection (sending RST to the server), whereas\n", " cancelling an asyncio coroutine leaves the socket open. Open sockets with\n", " unread data accumulate in the server's send buffer and eventually deadlock its\n", " event loop.\n", "\n", " Parameters\n", " ----------\n", " df : pd.DataFrame\n", " Must contain at least the column specified by ``image_column``.\n", " image_column : str\n", " Name of the column containing base64-encoded document images.\n", " system_prompt : str\n", " System prompt sent to the model with every request.\n", " model : str\n", " Model identifier as registered in the server (base model name or LoRA adapter name).\n", " host, port : str, int\n", " Address of the OpenAI-compatible inference server.\n", " batch_size : int\n", " Maximum number of concurrent in-flight requests (default: 30).\n", " max_tokens : int\n", " Maximum tokens to generate per response.\n", " temperature : float\n", " Sampling temperature. 0 = greedy / deterministic.\n", " timeout_seconds : float\n", " Per-request timeout enforced at the HTTP transport level (default: 600).\n", " When exceeded, httpx resets the TCP connection so the server can\n", " immediately reclaim its resources. 600 s is intentionally generous:\n", " large document images (multi-MB base64 payloads) can take tens of seconds\n", " to queue and process; a shorter timeout causes premature FIN-WAIT-1 storms\n", " that deadlock vLLM's event loop.\n", " max_attempts : int\n", " Total number of attempts per request, including the first try (default: 4).\n", "\n", " Returns\n", " -------\n", " out_df : pd.DataFrame\n", " Input DataFrame with the following columns added:\n", "\n", " * ``model_answer`` — generated text\n", " * ``time_to_preprocess`` — message-building time (mirrors library phase 1)\n", " * ``time_to_inference`` — API round-trip only (mirrors library phase 2)\n", " * ``time_to_postprocess`` — response-processing time (mirrors library phase 3)\n", " * ``time_to_inference_total`` — end-to-end latency per request (sum of all three phases)\n", " * ``textual_degeneration`` — True if finish_reason == \"length\" and last 15 chars repeat ≥ 4 times\n", " * ``num_output_tokens`` — completion tokens reported by the server\n", " * ``inference_tokens_per_second``— num_output_tokens / time_to_inference_total (per-request throughput)\n", " * ``time_per_page`` — total_elapsed / N (constant per run; matches paper's Time/Page metric)\n", " total_elapsed : float\n", " Total wall-clock time in seconds for the full inference run.\n", " \"\"\"\n", " http_client = httpx.AsyncClient(\n", " timeout=httpx.Timeout(\n", " connect=60.0,\n", " read=timeout_seconds,\n", " write=timeout_seconds,\n", " pool=timeout_seconds,\n", " ),\n", " limits=httpx.Limits(\n", " max_connections=200,\n", " max_keepalive_connections=100,\n", " ),\n", " )\n", " client = AsyncOpenAI(\n", " base_url=f\"http://{host}:{port}/v1\",\n", " api_key=\"not-required\",\n", " http_client=http_client,\n", " max_retries=0,\n", " )\n", "\n", " n = len(df)\n", " results: list = [None] * n\n", " semaphore = asyncio.Semaphore(batch_size)\n", " total_start = time.time()\n", "\n", " with async_tqdm(total=n, desc=\"Inference\", unit=\"sample\") as pbar:\n", " tasks = [\n", " _infer_single_async(\n", " client=client,\n", " image_data=row[image_column],\n", " system_prompt=system_prompt,\n", " model=model,\n", " max_tokens=max_tokens,\n", " temperature=temperature,\n", " semaphore=semaphore,\n", " results=results,\n", " index=i,\n", " pbar=pbar,\n", " max_attempts=max_attempts,\n", " )\n", " for i, (_, row) in enumerate(df.iterrows())\n", " ]\n", " await asyncio.gather(*tasks)\n", "\n", " await http_client.aclose()\n", "\n", " total_elapsed = time.time() - total_start\n", "\n", " out_df = df.copy()\n", " out_df[\"model_answer\"] = [r[\"model_answer\"] for r in results]\n", " out_df[\"time_to_preprocess\"] = [r[\"time_to_preprocess\"] for r in results]\n", " out_df[\"time_to_inference\"] = [r[\"time_to_inference\"] for r in results]\n", " out_df[\"time_to_postprocess\"] = [r[\"time_to_postprocess\"] for r in results]\n", " out_df[\"time_to_inference_total\"] = [r[\"time_to_inference_total\"] for r in results]\n", " out_df[\"textual_degeneration\"] = [r[\"textual_degeneration\"] for r in results]\n", " out_df[\"num_output_tokens\"] = [r[\"num_output_tokens\"] for r in results]\n", " out_df[\"inference_tokens_per_second\"] = [r[\"inference_tokens_per_second\"] for r in results]\n", " out_df[\"time_per_page\"] = total_elapsed / n\n", "\n", " n_deg = int(out_df[\"textual_degeneration\"].sum())\n", " mean_latency = out_df[\"time_to_inference_total\"].mean()\n", " mean_tps = out_df[\"inference_tokens_per_second\"].mean()\n", " time_per_page = total_elapsed / n\n", "\n", " print(f\"\\nInference complete\")\n", " print(f\" Samples : {n:,}\")\n", " print(f\" Total wall time : {total_elapsed:.1f}s\")\n", " print(f\" Time per page : {time_per_page:.3f}s\")\n", " print(f\" Throughput : {mean_tps:.1f} tokens/s\")\n", " print(f\" Mean latency : {mean_latency:.3f}s / sample\")\n", " print(f\" Textual degeneration: {n_deg} ({n_deg / n * 100:.1f}%)\")\n", "\n", " return out_df, total_elapsed\n", "\n", "\n", "def run_inference(\n", " df: pd.DataFrame,\n", " image_column: str,\n", " system_prompt: str,\n", " model: str,\n", " host: str,\n", " port: int,\n", " batch_size: int = 30,\n", " max_tokens: int = 4096,\n", " temperature: float = 0,\n", " timeout_seconds: float = 600.0,\n", " max_attempts: int = 4,\n", ") -> tuple:\n", " \"\"\"\n", " Synchronous wrapper around ``_run_inference_async`` for use outside Jupyter.\n", "\n", " When called from a Jupyter notebook, prefer ``await _run_inference_async(...)``\n", " directly, since Jupyter already runs an event loop and supports top-level await.\n", " This wrapper is provided for scripted or non-interactive contexts where no event\n", " loop is active.\n", " \"\"\"\n", " try:\n", " loop = asyncio.get_event_loop()\n", " if loop.is_running():\n", " import nest_asyncio\n", " nest_asyncio.apply()\n", " return loop.run_until_complete(\n", " _run_inference_async(\n", " df=df, image_column=image_column, system_prompt=system_prompt,\n", " model=model, host=host, port=port, batch_size=batch_size,\n", " max_tokens=max_tokens, temperature=temperature,\n", " timeout_seconds=timeout_seconds, max_attempts=max_attempts,\n", " )\n", " )\n", " except RuntimeError:\n", " return asyncio.run(\n", " _run_inference_async(\n", " df=df, image_column=image_column, system_prompt=system_prompt,\n", " model=model, host=host, port=port, batch_size=batch_size,\n", " max_tokens=max_tokens, temperature=temperature,\n", " timeout_seconds=timeout_seconds, max_attempts=max_attempts,\n", " )\n", " )" ] }, { "cell_type": "code", "execution_count": null, "id": "7ab48bdf", "metadata": {}, "outputs": [], "source": [ "_inference_model = LORA_NAME if LORA_ADAPTER_PATH else MODEL_NAME\n", "\n", "inference_df, _total_inference_time = await _run_inference_async(\n", " df=df,\n", " image_column=IMAGE_COLUMN,\n", " system_prompt=SYSTEM_PROMPT,\n", " model=_inference_model,\n", " host=VLLM_HOST,\n", " port=VLLM_PORT,\n", " batch_size=BATCH_SIZE,\n", " max_tokens=MAX_TOKENS,\n", " temperature=TEMPERATURE,\n", ")\n", "\n", "display(\n", " inference_df[\n", " [GROUND_TRUTH_COLUMN, \"model_answer\", \"time_to_inference_total\", \"textual_degeneration\"]\n", " ].head(3)\n", ")" ] }, { "cell_type": "markdown", "id": "b10b976d", "metadata": {}, "source": [ "### 1.5 Save Inference Results" ] }, { "cell_type": "code", "execution_count": null, "id": "e6ecdbef", "metadata": {}, "outputs": [], "source": [ "output_path = Path(INFERENCE_OUTPUT_FILE)\n", "inference_df.to_parquet(output_path, index=False)\n", "\n", "print(f\"Inference results saved to: {output_path.resolve()}\")\n", "print(f\"Shape: {inference_df.shape}\")" ] }, { "cell_type": "markdown", "id": "4e3d3aac", "metadata": {}, "source": [ "---\n", "## Section 2 — Benchmark & Metrics Collection\n", "\n", "This section evaluates model prediction quality against the ground truth text using two standard metrics:\n", "\n", "| Metric | Description |\n", "|---|---|\n", "| **Levenshtein ratio** | Character-level edit-distance similarity — `1 − distance / max_length` (0–1, higher is better) |\n", "| **BLEU score** | N-gram precision with NLTK `method1` smoothing (0–1, higher is better) |\n", "\n", "Results are saved as Parquet files in `BENCHMARK_RESULTS_DIR`. \n", "`Benchmark.view()` reads all files in that folder and produces a comparative summary table." ] }, { "cell_type": "markdown", "id": "c98dab8f", "metadata": {}, "source": [ "### 2.1 Benchmark Class" ] }, { "cell_type": "code", "execution_count": null, "id": "6fbc9735", "metadata": {}, "outputs": [], "source": [ "class Benchmark:\n", " \"\"\"\n", " Evaluates OCR model predictions against ground truth using Levenshtein and BLEU metrics.\n", "\n", " Unlike a conventional benchmark class, no DataFrame is stored internally.\n", " DataFrames are passed directly to :meth:`bench`, keeping the object stateless\n", " and reusable across multiple evaluation runs.\n", "\n", " Parameters\n", " ----------\n", " columns : list[str]\n", " Two-element list ``[ground_truth_column, prediction_column]``.\n", " model_name : str\n", " Human-readable identifier for the model being evaluated.\n", " Used as the default output filename stem.\n", "\n", " Examples\n", " --------\n", " >>> bm = Benchmark([\"text\", \"model_answer\"], \"Dharma-OCR-LITE\")\n", " >>> result_df = bm.bench(inference_df, output_dir=BENCHMARK_RESULTS_DIR)\n", " >>> Benchmark.view(BENCHMARK_RESULTS_DIR)\n", " \"\"\"\n", "\n", " def __init__(\n", " self,\n", " columns: list,\n", " model_name: str,\n", " ):\n", " if not isinstance(columns, (list, tuple)) or len(columns) != 2:\n", " raise ValueError(\"'columns' must be a list with exactly two column names.\")\n", " if not isinstance(model_name, str) or not model_name:\n", " raise ValueError(\"'model_name' must be a non-empty string.\")\n", " self.columns = list(columns)\n", " self.model_name = model_name\n", "\n", " def __repr__(self) -> str:\n", " return (\n", " f\"Benchmark(columns={self.columns!r}, model_name={self.model_name!r})\"\n", " )\n", "\n", " # ── Private helpers ───────────────────────────────────────────────────────\n", "\n", " def _get_text_columns(self, df: pd.DataFrame, plain_text: bool = False):\n", " \"\"\"Return (c1, c2) — ground truth and prediction as string Series.\"\"\"\n", " col_gt, col_pred = self.columns\n", " for col in (col_gt, col_pred):\n", " if col not in df.columns:\n", " raise ValueError(\n", " f\"Column '{col}' not found in DataFrame. \"\n", " f\"Available columns: {list(df.columns)}\"\n", " )\n", "\n", " if plain_text:\n", " # Both columns are normalised to plain text.\n", " # If a value is already plain text (not valid JSON), it is returned as-is.\n", " def _json_to_plain(x):\n", " try:\n", " parsed = eval(str(x).replace(\"null\", \"'null'\"))\n", " if isinstance(parsed, dict):\n", " return \"\\n\".join(\n", " str(v) for v in parsed.values()\n", " if v is not None and str(v).strip()\n", " )\n", " return str(x)\n", " except Exception:\n", " return str(x)\n", " c1 = df[col_gt].apply(_json_to_plain)\n", " c2 = df[col_pred].apply(_json_to_plain)\n", " else:\n", " c1 = df[col_gt].astype(str)\n", " c2 = df[col_pred].astype(str)\n", "\n", " return c1, c2\n", "\n", " def _compute_metrics(self, df: pd.DataFrame, plain_text: bool = False) -> pd.DataFrame:\n", " \"\"\"\n", " Compute per-sample Levenshtein ratio and BLEU score.\n", "\n", " Returns a copy of ``df`` with two additional columns:\n", " ``levenshtein_ratio`` and ``bleu``.\n", " \"\"\"\n", " result = df.copy()\n", " c1, c2 = self._get_text_columns(result, plain_text=plain_text)\n", "\n", " result[\"levenshtein_ratio\"] = [\n", " (\n", " 1.0 - _lev_lib.distance(a, b) / max(len(a), len(b))\n", " if max(len(a), len(b)) > 0\n", " else 0.0\n", " )\n", " for a, b in zip(c1, c2)\n", " ]\n", "\n", " smoother = SmoothingFunction().method1\n", " result[\"bleu\"] = [\n", " sentence_bleu([a.split()], b.split(), smoothing_function=smoother)\n", " for a, b in zip(c1, c2)\n", " ]\n", "\n", " return result\n", "\n", " # ── Public API ────────────────────────────────────────────────────────────\n", "\n", " def bench(\n", " self,\n", " df: pd.DataFrame,\n", " result_name: Optional[str] = None,\n", " output_dir: str = \"benchmark_results\",\n", " total_wall_time: Optional[float] = None,\n", " plain_text: bool = False,\n", " ) -> pd.DataFrame:\n", " \"\"\"\n", " Compute text similarity metrics on the given DataFrame and save the results.\n", "\n", " Parameters\n", " ----------\n", " df : pd.DataFrame\n", " Must contain the two columns listed in ``self.columns``.\n", " May also contain ``time_to_inference`` and ``textual_degeneration``\n", " columns produced by the inference step — these are preserved in the output\n", " and used by :meth:`view` to compute timing and degeneration statistics.\n", " result_name : str, optional\n", " Stem of the output Parquet filename (without ``.parquet`` extension).\n", " Defaults to ``self.model_name``.\n", " output_dir : str\n", " Directory where the result file is saved.\n", " Created automatically if it does not exist.\n", " Pass ``BENCHMARK_RESULTS_DIR`` to keep results visible to :meth:`view`.\n", " total_wall_time : float, optional\n", " Accepted for backward compatibility; no longer used internally.\n", " Throughput is derived from ``inference_tokens_per_second`` when available.\n", " plain_text : bool, optional\n", " If ``False`` (default), the ground truth column is used directly as-is.\n", " If ``True``, the column contains JSON strings; all values are extracted\n", " and joined with ``\\n`` into plain text before comparison.\n", "\n", " Returns\n", " -------\n", " pd.DataFrame\n", " Input DataFrame with ``levenshtein_ratio`` and ``bleu`` columns added.\n", " \"\"\"\n", " if not isinstance(df, pd.DataFrame):\n", " raise TypeError(\"'df' must be a pandas DataFrame.\")\n", "\n", " result_df = self._compute_metrics(df, plain_text=plain_text)\n", "\n", " stem = (result_name or self.model_name).replace(\" \", \"_\")\n", " out_dir = Path(output_dir)\n", " out_dir.mkdir(parents=True, exist_ok=True)\n", " out_path = out_dir / f\"{stem}.parquet\"\n", " result_df.to_parquet(out_path, index=False)\n", "\n", " lev_mean = result_df[\"levenshtein_ratio\"].mean()\n", " bleu_mean = result_df[\"bleu\"].mean()\n", " score = (lev_mean + bleu_mean) / 2\n", "\n", " print(f\"Benchmark saved: {out_path.resolve()}\")\n", " print(f\" Samples : {len(result_df):,}\")\n", " print(f\" Levenshtein ratio : {lev_mean:.4f}\")\n", " print(f\" BLEU : {bleu_mean:.4f}\")\n", " print(f\" Benchmark score : {score:.4f}\")\n", " if \"inference_tokens_per_second\" in result_df.columns:\n", " tps = result_df[\"inference_tokens_per_second\"].mean()\n", " print(f\" Throughput : {tps:.1f} tokens/s\")\n", "\n", " return result_df\n", "\n", " @staticmethod\n", " def view(folder_path: str) -> pd.DataFrame:\n", " \"\"\"\n", " Build an aggregated summary table from all benchmark Parquet files in a folder.\n", "\n", " Recursively searches for ``.parquet`` files under ``folder_path`` and computes\n", " aggregate statistics for each one. Displays the result as an HTML table in\n", " Jupyter and also returns it as a DataFrame.\n", "\n", " Parameters\n", " ----------\n", " folder_path : str\n", " Root directory to search for benchmark result files\n", " (typically ``BENCHMARK_RESULTS_DIR``).\n", "\n", " Returns\n", " -------\n", " pd.DataFrame\n", " One row per benchmark file with the following columns:\n", "\n", " ========================= =====================================================\n", " Column Description\n", " ========================= =====================================================\n", " ``benchmark_score`` ``(levenshtein_ratio_mean + bleu_mean) / 2``\n", " ``textual_degeneration (%)`` Percentage of samples flagged as textually degenerate\n", " ``mean_time_per_inference (s)`` Total wall time divided by number of samples (total_elapsed / N) — matches paper's Time/Page\n", " ``throughput (tokens/s)`` Mean tokens per second (inference_tokens_per_second mean)\n", " ``latency (s)`` Mean end-to-end per-request time (time_to_inference_total mean: preprocess + inference + postprocess)\n", "\n", " ``levenshtein_ratio_mean`` and ``bleu`` are saved in the result Parquet\n", " files but intentionally omitted from this summary view.\n", " ========================= =====================================================\n", "\n", " Columns that cannot be computed from the saved file are left blank.\n", " \"\"\"\n", " root = Path(folder_path)\n", " if not root.exists():\n", " raise FileNotFoundError(f\"Folder not found: {root.resolve()}\")\n", "\n", " parquet_files = sorted(root.rglob(\"*.parquet\"))\n", " if not parquet_files:\n", " print(f\"No .parquet files found under: {root.resolve()}\")\n", " return pd.DataFrame()\n", "\n", " rows = []\n", " for fpath in parquet_files:\n", " try:\n", " data = pd.read_parquet(fpath)\n", " except Exception as exc:\n", " print(f\"Could not read {fpath.name}: {exc}\")\n", " continue\n", "\n", " def _safe_mean(col: str):\n", " return float(data[col].mean()) if col in data.columns else None\n", "\n", " lev_mean = _safe_mean(\"levenshtein_ratio\")\n", " bleu_mean = _safe_mean(\"bleu\")\n", " score = (\n", " (lev_mean + bleu_mean) / 2\n", " if lev_mean is not None and bleu_mean is not None\n", " else None\n", " )\n", "\n", " tps = _safe_mean(\"inference_tokens_per_second\")\n", "\n", " # latency = mean end-to-end per-request time (preprocess + inference + postprocess)\n", " latency = _safe_mean(\"time_to_inference_total\")\n", "\n", " # mean_time_per_inference = total_elapsed / N, stored as a constant column.\n", " # Falls back to latency when running against older Parquet files that\n", " # predate the time_per_page column.\n", " mean_time = _safe_mean(\"time_per_page\") or latency\n", "\n", " deg_frac = _safe_mean(\"textual_degeneration\")\n", " inf_gen_pct = deg_frac * 100 if deg_frac is not None else None\n", "\n", " def _fmt(v, decimals=4):\n", " return round(v, decimals) if v is not None else \"\"\n", "\n", " rows.append({\n", " \"model\": fpath.stem,\n", " \"benchmark_score\": _fmt(score),\n", " \"textual_degeneration (%)\": _fmt(inf_gen_pct, 2),\n", " \"mean_time_per_inference (s)\": _fmt(mean_time, 3),\n", " \"throughput (tokens/s)\": _fmt(tps, 2),\n", " \"latency (s)\": _fmt(latency, 3),\n", " })\n", "\n", " if not rows:\n", " print(\"No valid benchmark files found.\")\n", " return pd.DataFrame()\n", "\n", " summary = pd.DataFrame(rows).set_index(\"model\").sort_values(\"benchmark_score\", ascending=False)\n", "\n", " display(summary)\n", " return summary\n", "\n", "\n", "print(\"Benchmark class loaded.\")" ] }, { "cell_type": "markdown", "id": "c7243b50", "metadata": {}, "source": [ "### 2.2 Load Inference Results\n", "\n", "Run the cell below to reload inference results from disk. \n", "**Skip it** if you are continuing directly from Section 1 — `inference_df` is already defined." ] }, { "cell_type": "code", "execution_count": null, "id": "0c2a9a94", "metadata": {}, "outputs": [], "source": [ "_results_path = Path(INFERENCE_OUTPUT_FILE)\n", "\n", "if _results_path.exists():\n", " inference_df = pd.read_parquet(_results_path)\n", " # Wall time is not stored in the Parquet file — throughput will be estimated from latency\n", " _total_inference_time = None\n", " print(f\"Loaded from {_results_path.resolve()} — {len(inference_df):,} rows\")\n", " display(\n", " inference_df[[GROUND_TRUTH_COLUMN, \"model_answer\"]].head(3)\n", " )\n", "else:\n", " # Ensure these variables are always defined so Cell 21 does not raise NameError\n", " inference_df = None\n", " _total_inference_time = None\n", " print(\n", " f\"'{INFERENCE_OUTPUT_FILE}' not found. \"\n", " \"Run Section 1 first, or update INFERENCE_OUTPUT_FILE to point to your results.\"\n", " )" ] }, { "cell_type": "markdown", "id": "b55a7d3f", "metadata": {}, "source": [ "### 2.3 Run Benchmark\n", "\n", "Instantiate `Benchmark` with the column names, then call `.bench()` to compute per-sample metrics and write the results to `BENCHMARK_RESULTS_DIR`. \n", "Re-run this cell with a different `result_name` (or after a new inference run) to accumulate multiple benchmark files for comparison." ] }, { "cell_type": "code", "execution_count": null, "id": "22a27c8a", "metadata": {}, "outputs": [], "source": [ "bm = Benchmark(\n", " columns=[GROUND_TRUTH_COLUMN, PREDICTION_COLUMN],\n", " model_name=MODEL_NAME.split(\"/\")[-1], # use the short model name as the file stem\n", ")\n", "\n", "benchmarked_df = bm.bench(\n", " df=inference_df,\n", " output_dir=BENCHMARK_RESULTS_DIR,\n", " total_wall_time=_total_inference_time, # None if results were loaded from disk\n", " plain_text=PLAIN_TEXT,\n", ")\n", "\n", "display(\n", " benchmarked_df[\n", " [GROUND_TRUTH_COLUMN, PREDICTION_COLUMN, \"levenshtein_ratio\", \"bleu\"]\n", " ].head(5)\n", ")" ] }, { "cell_type": "markdown", "id": "050d7a5c", "metadata": {}, "source": [ "### 2.4 View Results Summary Table\n", "\n", "Read all `.parquet` files in `BENCHMARK_RESULTS_DIR` (including subdirectories) and display an aggregated comparison table. \n", "Run this cell at any time — even after adding new benchmark files — to refresh the view." ] }, { "cell_type": "code", "execution_count": null, "id": "d8e95734", "metadata": {}, "outputs": [], "source": [ "summary = Benchmark.view(BENCHMARK_RESULTS_DIR)" ] }, { "cell_type": "markdown", "id": "de58314c", "metadata": {}, "source": [ "---\n", "### Cleanup — Stop vLLM Server (Optional)\n", "\n", "Uncomment the block below to shut down the local vLLM server when you are finished." ] }, { "cell_type": "code", "execution_count": null, "id": "c6e3e5e3", "metadata": {}, "outputs": [], "source": [ "if vllm_process is not None:\n", " vllm_process.terminate()\n", " try:\n", " vllm_process.wait(timeout=30)\n", " print(\"vLLM server stopped.\")\n", " except subprocess.TimeoutExpired:\n", " vllm_process.kill()\n", " print(\"vLLM server force-killed.\")\n", "else:\n", " print(\"No local server process to stop (START_LOCAL_SERVER was False).\")" ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.8" } }, "nbformat": 4, "nbformat_minor": 5 }