DEV Community

Alain Airom (Ayrom)
Alain Airom (Ayrom)

Posted on

Hands-On with IBM Granite Docling V2: Building a Local Document Intelligence Studio

Implementating sample application of Granite Docling V2.

Introduction

Modern enterprise data rarely arrives in neat, structured JSON payloads. It lives inside multi-column PDFs, scanned invoices, financial tables with merged headers, and scientific papers dense with LaTeX formulas. Traditional Optical Character Recognition (OCR) pipelines tackle these documents through brittle, multi-stage heuristics—stitching together separate layout detectors, bounding-box heuristics, table parsers, and text recognizers. When a single stage misinterprets a column break or a nested cell, the downstream Retrieval-Augmented Generation (RAG) or agentic workflow inherits corrupted context.

Enter IBM Granite Docling V2—a purpose-built family of Vision-Language Models (VLMs) engineered specifically for end-to-end document understanding and structural conversion. Rather than treating a page as a bag of disconnected text boxes, Granite Docling V2 ingests page images directly and generates DocLang / DocTags, a semantic markup representation that preserves reading order, hierarchical headings, tables, mathematical formulas, figures, and normalized [0, 1000] spatial bounding boxes in a single unified pass.

In this release, IBM provides two complementary model sizes tailored to distinct hardware envelopes and latency-accuracy trade-offs:

  • ibm-granite/granite-docling-v2-500m: A compact, ultra-fast 500M-parameter (0.54B) VLM capable of processing up to 18.5 pages per second while achieving 94.9% accuracy on DocLayNet benchmarks. With an estimated footprint of ~1.8 GB RAM/VRAM, it fits comfortably on everyday developer laptops and edge nodes.

  • ibm-granite/granite-docling-v2-2b: The 2.5B-parameter flagship model engineered for maximum fidelity (96.5% DocLayNet accuracy). Requiring ~5.5 GB RAM/VRAM, it excels on intricate multi-page layouts, dense financial tables, complex mathematical notation, and multilingual documents.

Both models introduce a density-aware patch router that dynamically allocates visual attention tokens to dense regions (like tables and equations) while conserving compute on whitespace. Both also ship with native MLX variants (-mlx) alongside standard Hugging Face weights for local Apple Silicon execution.

To evaluate these two models side by side and turn them into a practical local developer utility, I built IBM Granite Docling V2 Studio—a modular Python application featuring a Streamlit web interface, a Click/Rich command-line tool, a hardware compatibility advisor, and a DocLang XML schema validator.


Excerpts from Huggin Face for Docling Granite V2

Granite Docling V2 500M

Granite Docling V2 500M is the small, fast member of the Granite Docling V2 family. It converts a page image into DocLang, a markup language that records each element's type, position and reading order along with its content. One generation gives you headings, paragraphs, lists, tables with merged and header cells, LaTeX formulas, code, pictures with their captions and the text printed inside them, and page headers and footers. You can export the result to Markdown, HTML or JSON with docling-core. It succeeds SmolDocling and Granite-Docling 258M, from the Docling team at IBM.

  • 🏆 Accuracy above its size: 94.9% content 1 − NED pooled over 16,205 pages from nine benchmarks, ahead of Nemotron 3.5 Parse (0.6B) and Unlimited-OCR 2 (3.3B). The edit distance falls from 20.6% with Granite-Docling 258M to 5.1%, four times lower.

  • 🔀 Adaptive vision budget: a learned density router reads 64 tokens per tile on ordinary pages and re-encodes dense pages, such as newspapers or small CJK print, at 256 tokens per tile.

  • 🧱 Structure is part of the output: every element carries its type and bounding box. Tables keep their full cell structure, and inline math, sub- and superscripts are marked inside the text.

  • 🖼️ Pictures are read, not skipped: each picture keeps its type, its caption and the text printed inside it; the [<detailed>] prompt adds a description.

  • 🎯 Prompt for only what you need: ask for just the tables, the formulas, or the text with boxes, and the model decodes nothing else.

  • 🌍 Multilingual: far stronger than Granite-Docling 258M beyond English, above all on Chinese, Japanese, Korean, Hindi, Russian and Arabic, and on mixed Chinese–English pages.

  • ✍️ Handwriting: reads handwritten notes and forms far better than Granite-Docling 258M, though printed text remains more accurate.

  • 🚀 Fast and light: about 18.5 pages per second on one H100 with vLLM and MTP speculative decoding, about 14 without. Runs in 🤗 Transformers and vLLM.

Granite Docling V2 2B

Granite Docling V2 2B is a compact vision-language model that converts a page image into DocLang, a markup language that records each element's type, position and reading order along with its content. One generation gives you headings, paragraphs, lists, tables with merged and header cells, LaTeX formulas, code, pictures with their captions and the text printed inside them, and page headers and footers. You can export the result to Markdown, HTML or JSON with docling-core. It succeeds SmolDocling and Granite-Docling 258M, from the Docling team at IBM.

  • 🏆 Top accuracy: 96.5% content 1 − NED pooled over 16,205 pages from nine benchmarks, ahead of every system we compared, including models up to 2.1× its size. The edit distance falls from 20.6% with Granite-Docling 258M to 3.5%, six times lower.
  • 🧱 Structure is part of the output: every element carries its type and bounding box. Tables keep their full cell structure, and inline math, sub- and superscripts are marked inside the text.
  • 🖼️ Pictures are read, not skipped: each picture keeps its type, its caption and the text printed inside it; the [<detailed>] prompt adds a description.
  • 🎯 Prompt for only what you need: ask for just the tables, the formulas, or the text with boxes, and the model decodes nothing else.
  • 🌍 Multilingual: far stronger than Granite-Docling 258M beyond English, above all on Chinese, Japanese, Korean, Hindi, Russian and Arabic, and on mixed Chinese–English pages.
  • ✍️ Handwriting: reads handwritten notes and forms far better than Granite-Docling 258M, though printed text remains more accurate.
  • 🚀 Fast and light: about 10 pages per second on one H100 with vLLM and MTP speculative decoding, about 7 without. Runs in 🤗 Transformers, vLLM and MLX.


Implementation

System Architecture & Data Flow

To keep the application clean, testable, and usable both interactively and in headless batch pipelines, the architecture decouples the user interfaces (app.py and cli.py) from the core conversion, hardware diagnostics, and validation engines.

Every document conversion follows a deterministic lifecycle:

Model Registry & Hardware Diagnostics (models.py & system_info.py)

When running VLMs locally across heterogeneous developer workstations—ranging from Linux servers with NVIDIA CUDA GPUs to Intel XPUs and Apple Silicon MacBooks—hardcoding device strings leads to crashes or Out-Of-Memory (OOM) errors.

First, models.py centralizes model specifications, Hugging Face and MLX repository identifiers, Docling presets, and memory footprints:

"""Model definitions and registry for IBM Granite Docling vision-language models."""

from __future__ import annotations

from dataclasses import dataclass
from typing import Dict, List, Optional


@dataclass
class GraniteModelSpec:
    """Specification of an IBM Granite Docling model."""

    model_id: str
    display_name: str
    version: str
    parameter_count: str
    huggingface_repo_id: str
    mlx_repo_id: Optional[str]
    docling_preset: Optional[str]
    description: str
    estimated_ram_gb: float
    recommended_min_ram_gb: float
    accuracy_tier: str  # "Balanced", "Highest", "Fastest"
    speed_tier: str  # "Fast", "Ultra Fast", "Standard"


# Registry of supported Granite models
MODEL_REGISTRY: Dict[str, GraniteModelSpec] = {
    "ibm-granite/granite-docling-v2-500m": GraniteModelSpec(
        model_id="ibm-granite/granite-docling-v2-500m",
        display_name="IBM Granite Docling V2 (500M) — High Speed & Efficiency",
        version="v2",
        parameter_count="500M (0.54B)",
        huggingface_repo_id="ibm-granite/granite-docling-v2-500m",
        mlx_repo_id="ibm-granite/granite-docling-v2-500m-mlx",
        docling_preset="granite_docling_v2_500m",
        description="Ultra-fast compact VLM capable of up to 18.5 pages/s with density router for complex layouts.",
        estimated_ram_gb=1.8,
        recommended_min_ram_gb=4.0,
        accuracy_tier="High (94.9% DLN)",
        speed_tier="Ultra Fast",
    ),
    "ibm-granite/granite-docling-v2-2b": GraniteModelSpec(
        model_id="ibm-granite/granite-docling-v2-2b",
        display_name="IBM Granite Docling V2 (2B) — Maximum Accuracy",
        version="v2",
        parameter_count="2.5B",
        huggingface_repo_id="ibm-granite/granite-docling-v2-2b",
        mlx_repo_id="ibm-granite/granite-docling-v2-2b-mlx",
        docling_preset="granite_docling_v2_2b",
        description="Flagship accuracy model for intricate documents, nested tables, formulas, and multilingual texts.",
        estimated_ram_gb=5.5,
        recommended_min_ram_gb=8.0,
        accuracy_tier="Highest (96.5% DLN)",
        speed_tier="Standard",
    ),
    "ibm-granite/granite-docling-258m": GraniteModelSpec(
        model_id="ibm-granite/granite-docling-258m",
        display_name="IBM Granite Docling V1 (258M) — Legacy Lightweight",
        version="v1",
        parameter_count="258M",
        huggingface_repo_id="ibm-granite/granite-docling-258M",
        mlx_repo_id="ibm-granite/granite-docling-258M-mlx",
        docling_preset="granite_docling",
        description="Original ultra-lightweight VLM for resource-constrained edge devices and low-spec systems.",
        estimated_ram_gb=1.0,
        recommended_min_ram_gb=3.0,
        accuracy_tier="Balanced",
        speed_tier="Fast",
    ),
}

DEFAULT_MODEL_ID = "ibm-granite/granite-docling-v2-500m"


def get_available_models() -> List[GraniteModelSpec]:
    """Returns list of all registered models."""
    return list(MODEL_REGISTRY.values())


def get_model_spec(model_id: str) -> GraniteModelSpec:
    """Retrieves spec for model ID with graceful fallback."""
    if model_id in MODEL_REGISTRY:
        return MODEL_REGISTRY[model_id]
    # Check by short name or partial match
    for k, v in MODEL_REGISTRY.items():
        if model_id.lower() in k.lower():
            return v
    # Fallback to default
    return MODEL_REGISTRY[DEFAULT_MODEL_ID]

Enter fullscreen mode Exit fullscreen mode

Next, system_info.py inspects CPU topology, available system RAM, CUDA VRAM, Intel XPU availability, and Apple Silicon Unified Memory (MPS). It evaluates whether the chosen model will run comfortably (optimal), fit tightly (warning), or risk paging (incompatible), while ResourceTracker wraps inference blocks to capture wall-clock duration and resident memory deltas:

class ResourceTracker:
    """Context manager for tracking conversion execution time, CPU and memory deltas."""

    def __init__(self) -> None:
        self.start_time: float = 0.0
        self.end_time: float = 0.0
        self.duration_seconds: float = 0.0
        self.start_ram_mb: float = 0.0
        self.end_ram_mb: float = 0.0
        self._process = psutil.Process(os.getpid())

    def __enter__(self) -> ResourceTracker:
        self.start_time = time.perf_counter()
        self.start_ram_mb = self._process.memory_info().rss / (1024 * 1024)
        return self

    def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
        self.end_time = time.perf_counter()
        self.duration_seconds = round(self.end_time - self.start_time, 3)
        self.end_ram_mb = self._process.memory_info().rss / (1024 * 1024)
Enter fullscreen mode Exit fullscreen mode

Core Docling VLM Conversion & Graceful Device Fallback (converter.py)

The heart of the application is DocumentProcessor in converter.py. It binds Docling's VlmPipeline to VlmConvertOptions, configures render scaling (scale), table structure extraction (do_table_structure), formula enrichment (do_formula_enrichment), and page slicing (page_range, max_pages).

A critical real-world detail when running Hugging Face Transformers VLMs on macOS is that certain vision-language operators can trigger an AcceleratorDeviceNotAvailableError on MPS backends. Instead of crashing, convert_document() catches accelerator incompatibility errors and falls back automatically to multi-threaded CPU execution, followed by explicit memory reclamation (gc.collect(), torch.cuda.empty_cache(), and torch.mps.empty_cache()):

        with tracker:
            try:
                markdown_text, html_text, doctags, num_pages, meta, actual_device_used = self._execute_docling_conversion(
                    src, model_spec, target_device, target_dtype, active_options, progress_callback
                )
                success = True
                err_msg = None
            except Exception as exc:
                err_str = str(exc)
                if (
                    "AcceleratorDeviceNotAvailableError" in type(exc).__name__
                    or "is not supported by this model" in err_str
                ) and target_device != "cpu":
                    logger.warning(
                        "Accelerator device '%s' not supported by %s (%s). Falling back gracefully to CPU.",
                        target_device,
                        model_spec.model_id,
                        err_str,
                    )
                    markdown_text, html_text, doctags, num_pages, meta, actual_device_used = self._execute_docling_conversion(
                        src, model_spec, "cpu", target_dtype, active_options, progress_callback
                    )
                    success = True
                    err_msg = None
Enter fullscreen mode Exit fullscreen mode

Inside _execute_docling_conversion(), Docling's DocumentConverter is configured for both PDF and image inputs (PNG, JPG, WebP, TIFF, BMP) and exports four synchronized artifacts into a timestamped folder (output/YYYYmmdd_HHMMSS_<name>/):

  1. Markdown (.md): Clean semantic Markdown with optional YAML frontmatter (title, model, timestamp, pages).

  2. HTML (.html): Standalone HTML rendering of the parsed document AST.

  3. DocLang / DCLX (.dclx): Raw XML/DocTags tokens emitted by the Granite VLM.

  4. Telemetry Metadata (metadata.json): Execution duration, peak RAM, device used, option snapshot, and validation report.

DocLang XML & Spatial Bounding Box Validation (doclang_validator.py)

Because Granite Docling V2 outputs structured DocLang tags containing spatial coordinates (<picture>, <label>, <layer>, <location>, <text>), verifying structural integrity is essential before feeding documents into downstream ingestion pipelines.

DocLangValidator parses the raw DocTags stream (with a regex fallback for unclosed streaming tokens) and verifies that every bounding box satisfies [0,1000][0,1000] coordinate geometry (x2≥x1*x*2≥*x*1 and y2≥y1*y*2≥*y*1):

@dataclass
class LocationCoordinate:
    """Bounding box coordinate values (top, left, bottom, right or x1, y1, x2, y2)."""

    values: List[int]

    @property
    def is_valid_bbox(self) -> bool:
        """Coordinates must be non-negative and bottom/right >= top/left."""
        if len(self.values) != 4:
            return False
        return (
            all(v >= 0 for v in self.values)
            and self.values[2] >= self.values[0]
            and self.values[3] >= self.values[1]
        )
Enter fullscreen mode Exit fullscreen mode

When --strict-xml is enabled, any malformed XML tag or invalid bounding box immediately flags the conversion so corrupted extractions never silently pollute a vector database.

Interactive Studio UI (app.py) & Developer CLI (cli.py)

To make the engine effortless to explore visually and automate in scripts, the project exposes two first-class interfaces powered by the exact same ProcessingOptions configuration model:

  • Streamlit Web Studio (app.py): Organizes workflows into five dedicated tabs:
  1. Single Document: Upload any supported file, tweak render scale (1.0x–3.5x) or table/formula toggles, inspect Rendered Markdown, Rendered HTML, raw DocLang XML tokens, and bounding-box validation JSON, and download all artifacts without losing session state.

  2. Model Comparison (500M vs 2B): Runs processor.compare_models() sequentially on the exact same document (cleaning memory between passes) and displays execution speed deltas, RAM usage, side-by-side Markdown previews, and a unified difflib text diff.

  3. Batch Processing: Converts multi-file uploads or scans the local input/ directory with fault-tolerant progress tracking.

  4. System Doctor & Benchmarks: Displays live hardware diagnostics and runs a 10-rule automated validation test suite directly from the browser.

  5. Options Reference Guide: Renders a searchable parameter inventory and exports a standalone HTML manual (Docs/OptionsReference.html).

  6. Command-Line Interface (cli.py): Built with click and rich for terminal workflows and CI pipelines:

# Inspect hardware capabilities and check 500M vs 2B compatibility
python cli.py doctor

# Convert a multi-page financial PDF with the 2B model at 2.5x render scale
python cli.py convert quarterly_report.pdf --model ibm-granite/granite-docling-v2-2b --scale 2.5 --export md,html,dclx,json

# Run a head-to-head benchmark comparing 500M and 2B on the same document
python cli.py compare complex_paper.pdf --device auto

# Batch process all documents inside input/
python cli.py batch input/ --threads 8 --export md,json
Enter fullscreen mode Exit fullscreen mode

Conclusion

Building IBM Granite Docling V2 Studio demonstrates how far local document intelligence has evolved. Instead of orchestrating fragile chains of layout detectors, table recognizers, and OCR engines, a single compact Vision-Language Model now transforms raw PDFs and document images directly into semantic Markdown, HTML, and spatially grounded DocLang XML.

By pairing Granite Docling V2 500M and 2B inside a unified workbench, we realized several practical capabilities for real-world engineering workflows:

  • Data-Driven Model Selection: The side-by-side comparison and unified diff engine makes it immediately clear when the ultra-fast 500M model (~1.8 GB RAM, up to 18.5 pages/s) is sufficient for clean reports and standard tables, and when upgrading to the 2B flagship (~5.5 GB RAM, 96.5% DocLayNet accuracy) pays off for dense mathematical formulas and nested layouts.

  • Hardware-Aware Portability: Automatic detection across CUDA, Intel XPU, Apple Silicon MPS, and multi-core CPUs—combined with graceful CPU fallback and per-page memory reclamation—ensures reliable local execution without OOM crashes.

  • Verifiable Structural Outputs: Validating DocLang XML syntax and [0, 1000] bounding boxes guarantees that extracted text, tables, and figures maintain structural integrity before entering downstream RAG pipelines or enterprise agents.

  • Dual-Mode Ergonomics: Whether interactively inspecting DocTags in the Streamlit Studio or running automated batch conversions through the Click CLI, every parameter and output artifact remains consistent and reproducible.

Thanks for reading 🦆

Links

Top comments (0)