{"slug": "hands-on-with-ibm-granite-docling-v2-building-a-local-document-intelligence", "title": "Hands-On with IBM Granite Docling V2: Building a Local Document Intelligence Studio", "summary": "A developer built IBM Granite Docling V2 Studio, a modular Python application combining a Streamlit interface, a Click/Rich CLI, a hardware compatibility advisor and a DocLang XML schema validator to run IBM's Granite Docling V2 vision-language models locally. The two models convert page images directly into DocLang/DocTags markup preserving reading order, headings, tables, formulas and normalized bounding boxes in one pass, with the 500M variant reaching 94.9% DocLayNet accuracy at up to 18.5 pages per second and the 2.5B flagship reaching 96.5%. Both ship with native MLX variants for Apple Silicon and use a density-aware patch router that allocates more visual tokens to tables and equations.", "body_md": "Implementating sample application of Granite Docling V2.\n\n# \n  Introduction\n\nModern 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.\n\nEnter **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.   \n\nIn this release, IBM provides two complementary model sizes tailored to distinct hardware envelopes and latency-accuracy trade-offs:\n\n- **[ibm-granite/granite-docling-v2-500m](https://huggingface.co/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.\n- **[ibm-granite/granite-docling-v2-2b](https://huggingface.co/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.\n\nBoth 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.   \n\nTo 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.   \n\n**Excerpts from Huggin Face for Docling Granite V2**\n\n## \n  Granite Docling V2 500M\n\n**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`](https://github.com/docling-project/docling-core). It succeeds [SmolDocling](https://huggingface.co/docling-project/SmolDocling-256M-preview) and [Granite-Docling 258M](https://huggingface.co/ibm-granite/granite-docling-258M), from the Docling team at IBM.\n\n- 🏆 **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.\n- 🔀 **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.\n- 🧱 **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.\n- 🖼️ **Pictures are read, not skipped** : each picture keeps its type, its caption and the text printed inside it; the`[<detailed>]` prompt adds a description.\n- 🎯 **Prompt for only what you need** : ask for just the tables, the formulas, or the text with boxes, and the model decodes nothing else.\n- 🌍 **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.\n- ✍️ **Handwriting** : reads handwritten notes and forms far better than Granite-Docling 258M, though printed text remains more accurate.\n- 🚀 **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.\n\n## \n  Granite Docling V2 2B\n\n**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`](https://github.com/docling-project/docling-core). It succeeds [SmolDocling](https://huggingface.co/docling-project/SmolDocling-256M-preview) and [Granite-Docling 258M](https://huggingface.co/ibm-granite/granite-docling-258M), from the Docling team at IBM.\n\n- 🏆 **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.\n- 🧱 **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.\n- 🖼️ **Pictures are read, not skipped** : each picture keeps its type, its caption and the text printed inside it; the`[<detailed>]` prompt adds a description.\n- 🎯 **Prompt for only what you need** : ask for just the tables, the formulas, or the text with boxes, and the model decodes nothing else.\n- 🌍 **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.\n- ✍️ **Handwriting** : reads handwritten notes and forms far better than Granite-Docling 258M, though printed text remains more accurate.\n- 🚀 **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.\n\n# \n  Implementation\n\n## \n  System Architecture & Data Flow\n\nTo 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.   \n\nEvery document conversion follows a deterministic lifecycle:\n\n## \n  Model Registry & Hardware Diagnostics (`models.py` & `system_info.py`)\n\nWhen 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.\n\nFirst, `models.py` centralizes model specifications, Hugging Face and MLX repository identifiers, Docling presets, and memory footprints:\n\n```\n\"\"\"Model definitions and registry for IBM Granite Docling vision-language models.\"\"\"\n\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\nfrom typing import Dict, List, Optional\n\n@dataclass\nclass GraniteModelSpec:\n    \"\"\"Specification of an IBM Granite Docling model.\"\"\"\n\n    model_id: str\n    display_name: str\n    version: str\n    parameter_count: str\n    huggingface_repo_id: str\n    mlx_repo_id: Optional[str]\n    docling_preset: Optional[str]\n    description: str\n    estimated_ram_gb: float\n    recommended_min_ram_gb: float\n    accuracy_tier: str  # \"Balanced\", \"Highest\", \"Fastest\"\n    speed_tier: str  # \"Fast\", \"Ultra Fast\", \"Standard\"\n\n# Registry of supported Granite models\nMODEL_REGISTRY: Dict[str, GraniteModelSpec] = {\n    \"ibm-granite/granite-docling-v2-500m\": GraniteModelSpec(\n        model_id=\"ibm-granite/granite-docling-v2-500m\",\n        display_name=\"IBM Granite Docling V2 (500M) — High Speed & Efficiency\",\n        version=\"v2\",\n        parameter_count=\"500M (0.54B)\",\n        huggingface_repo_id=\"ibm-granite/granite-docling-v2-500m\",\n        mlx_repo_id=\"ibm-granite/granite-docling-v2-500m-mlx\",\n        docling_preset=\"granite_docling_v2_500m\",\n        description=\"Ultra-fast compact VLM capable of up to 18.5 pages/s with density router for complex layouts.\",\n        estimated_ram_gb=1.8,\n        recommended_min_ram_gb=4.0,\n        accuracy_tier=\"High (94.9% DLN)\",\n        speed_tier=\"Ultra Fast\",\n    ),\n    \"ibm-granite/granite-docling-v2-2b\": GraniteModelSpec(\n        model_id=\"ibm-granite/granite-docling-v2-2b\",\n        display_name=\"IBM Granite Docling V2 (2B) — Maximum Accuracy\",\n        version=\"v2\",\n        parameter_count=\"2.5B\",\n        huggingface_repo_id=\"ibm-granite/granite-docling-v2-2b\",\n        mlx_repo_id=\"ibm-granite/granite-docling-v2-2b-mlx\",\n        docling_preset=\"granite_docling_v2_2b\",\n        description=\"Flagship accuracy model for intricate documents, nested tables, formulas, and multilingual texts.\",\n        estimated_ram_gb=5.5,\n        recommended_min_ram_gb=8.0,\n        accuracy_tier=\"Highest (96.5% DLN)\",\n        speed_tier=\"Standard\",\n    ),\n    \"ibm-granite/granite-docling-258m\": GraniteModelSpec(\n        model_id=\"ibm-granite/granite-docling-258m\",\n        display_name=\"IBM Granite Docling V1 (258M) — Legacy Lightweight\",\n        version=\"v1\",\n        parameter_count=\"258M\",\n        huggingface_repo_id=\"ibm-granite/granite-docling-258M\",\n        mlx_repo_id=\"ibm-granite/granite-docling-258M-mlx\",\n        docling_preset=\"granite_docling\",\n        description=\"Original ultra-lightweight VLM for resource-constrained edge devices and low-spec systems.\",\n        estimated_ram_gb=1.0,\n        recommended_min_ram_gb=3.0,\n        accuracy_tier=\"Balanced\",\n        speed_tier=\"Fast\",\n    ),\n}\n\nDEFAULT_MODEL_ID = \"ibm-granite/granite-docling-v2-500m\"\n\ndef get_available_models() -> List[GraniteModelSpec]:\n    \"\"\"Returns list of all registered models.\"\"\"\n    return list(MODEL_REGISTRY.values())\n\ndef get_model_spec(model_id: str) -> GraniteModelSpec:\n    \"\"\"Retrieves spec for model ID with graceful fallback.\"\"\"\n    if model_id in MODEL_REGISTRY:\n        return MODEL_REGISTRY[model_id]\n    # Check by short name or partial match\n    for k, v in MODEL_REGISTRY.items():\n        if model_id.lower() in k.lower():\n            return v\n    # Fallback to default\n    return MODEL_REGISTRY[DEFAULT_MODEL_ID]\n```\n\nNext, `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:\n\n```\nclass ResourceTracker:\n    \"\"\"Context manager for tracking conversion execution time, CPU and memory deltas.\"\"\"\n\n    def __init__(self) -> None:\n        self.start_time: float = 0.0\n        self.end_time: float = 0.0\n        self.duration_seconds: float = 0.0\n        self.start_ram_mb: float = 0.0\n        self.end_ram_mb: float = 0.0\n        self._process = psutil.Process(os.getpid())\n\n    def __enter__(self) -> ResourceTracker:\n        self.start_time = time.perf_counter()\n        self.start_ram_mb = self._process.memory_info().rss / (1024 * 1024)\n        return self\n\n    def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:\n        self.end_time = time.perf_counter()\n        self.duration_seconds = round(self.end_time - self.start_time, 3)\n        self.end_ram_mb = self._process.memory_info().rss / (1024 * 1024)\n```\n\n## \n  Core Docling VLM Conversion & Graceful Device Fallback (`converter.py`)\n\nThe 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`).   \n\nA 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()`):\n\n```\n        with tracker:\n            try:\n                markdown_text, html_text, doctags, num_pages, meta, actual_device_used = self._execute_docling_conversion(\n                    src, model_spec, target_device, target_dtype, active_options, progress_callback\n                )\n                success = True\n                err_msg = None\n            except Exception as exc:\n                err_str = str(exc)\n                if (\n                    \"AcceleratorDeviceNotAvailableError\" in type(exc).__name__\n                    or \"is not supported by this model\" in err_str\n                ) and target_device != \"cpu\":\n                    logger.warning(\n                        \"Accelerator device '%s' not supported by %s (%s). Falling back gracefully to CPU.\",\n                        target_device,\n                        model_spec.model_id,\n                        err_str,\n                    )\n                    markdown_text, html_text, doctags, num_pages, meta, actual_device_used = self._execute_docling_conversion(\n                        src, model_spec, \"cpu\", target_dtype, active_options, progress_callback\n                    )\n                    success = True\n                    err_msg = None\n```\n\nInside `_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>/`):   \n\n1. **Markdown (`.md`)** : Clean semantic Markdown with optional YAML frontmatter (`title` ,`model` ,`timestamp` ,`pages` ).\n2. **HTML (`.html`)** : Standalone HTML rendering of the parsed document AST.\n3. **DocLang / DCLX (`.dclx`)** : Raw XML/DocTags tokens emitted by the Granite VLM.\n4. **Telemetry Metadata (`metadata.json`)** : Execution duration, peak RAM, device used, option snapshot, and validation report.\n\n## \n  DocLang XML & Spatial Bounding Box Validation (`doclang_validator.py`)\n\nBecause 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.   \n\n`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):\n\n```\n@dataclass\nclass LocationCoordinate:\n    \"\"\"Bounding box coordinate values (top, left, bottom, right or x1, y1, x2, y2).\"\"\"\n\n    values: List[int]\n\n    @property\n    def is_valid_bbox(self) -> bool:\n        \"\"\"Coordinates must be non-negative and bottom/right >= top/left.\"\"\"\n        if len(self.values) != 4:\n            return False\n        return (\n            all(v >= 0 for v in self.values)\n            and self.values[2] >= self.values[0]\n            and self.values[3] >= self.values[1]\n        )\n```\n\nWhen `--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.   \n\n## \n  Interactive Studio UI (`app.py`) & Developer CLI (` cli.py`)\n\nTo 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:   \n\n- \n**Streamlit Web Studio (`app.py`)** : Organizes workflows into five dedicated tabs:\n\n1. **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.\n2. **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.\n3. **Batch Processing** : Converts multi-file uploads or scans the local`input/` directory with fault-tolerant progress tracking.\n4. **System Doctor & Benchmarks** : Displays live hardware diagnostics and runs a 10-rule automated validation test suite directly from the browser.\n5. **Options Reference Guide** : Renders a searchable parameter inventory and exports a standalone HTML manual (`Docs/OptionsReference.html` ).\n6. **Command-Line Interface (`cli.py`)** : Built with` click` and`rich` for terminal workflows and CI pipelines:\n\n```\n# Inspect hardware capabilities and check 500M vs 2B compatibility\npython cli.py doctor\n\n# Convert a multi-page financial PDF with the 2B model at 2.5x render scale\npython cli.py convert quarterly_report.pdf --model ibm-granite/granite-docling-v2-2b --scale 2.5 --export md,html,dclx,json\n\n# Run a head-to-head benchmark comparing 500M and 2B on the same document\npython cli.py compare complex_paper.pdf --device auto\n\n# Batch process all documents inside input/\npython cli.py batch input/ --threads 8 --export md,json\n```\n\n## \n  Conclusion\n\nBuilding **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.   \n\nBy pairing **Granite Docling V2 500M** and **2B** inside a unified workbench, we realized several practical capabilities for real-world engineering workflows:   \n\n- **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.\n- **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.\n- **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.\n- **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.\n\n**Thanks for reading 🦆**\n\n# \n  Links\n\n- \n**Granite Docling v2 500m** :[https://huggingface.co/ibm-granite/granite-docling-v2-500m](https://huggingface.co/ibm-granite/granite-docling-v2-500m)\n- \n**Granite Docling v2 2b** :[https://huggingface.co/ibm-granite/granite-docling-v2-2b](https://huggingface.co/ibm-granite/granite-docling-v2-2b)\n- \n**Granite Docling v2 playground** :[https://huggingface.co/ibm-granite/granite-docling-v2-2b](https://huggingface.co/ibm-granite/granite-docling-v2-2b)\n- Model card: [https://huggingface.co/ibm-granite/granite-docling-v2-2b/edit/main/README.md](https://huggingface.co/ibm-granite/granite-docling-v2-2b/edit/main/README.md)\n- \n**Docling.ai** :[https://docling.ai/](https://docling.ai/)\n- \n**Docling Project** :[https://github.com/docling-project](https://github.com/docling-project)\n- \n**Doclang Project** :[https://github.com/doclang-project](https://github.com/doclang-project)\n- Source code for this post: [https://github.com/aairom/docling-doclang-v2](https://github.com/aairom/docling-doclang-v2)", "url": "https://wpnews.pro/news/hands-on-with-ibm-granite-docling-v2-building-a-local-document-intelligence", "canonical_source": "https://dev.to/aairom/hands-on-with-ibm-granite-docling-v2-building-a-local-document-intelligence-studio-5f70", "published_at": "2026-12-01 17:58:47+00:00", "updated_at": "2026-12-03 00:15:40.919722+00:00", "lang": "en", "topics": ["artificial-intelligence", "computer-vision", "large-language-models", "ai-tools", "ai-infrastructure"], "entities": ["IBM", "Granite Docling V2", "Granite Docling V2 Studio", "DocLang", "DocLayNet", "Streamlit", "Hugging Face", "Apple Silicon"], "also_reported_by": [], "takeaway": "Granite Docling V2's 500M model reaches 94.9% DocLayNet accuracy at up to 18.5 pages per second in ~1.8 GB of memory, while the 2.5B model trades that speed for 96.5% accuracy at ~5.5 GB, so pick the size by hardware envelope.", "recommendation": {"advice": "Use Granite Docling V2's single-pass DocLang output instead of multi-stage OCR heuristics when ingesting tables and formulas into RAG, choosing the 500M model for laptop or edge nodes and the 2.5B for dense layouts.", "playbook": "rag-retrieval", "playbook_url": "https://wpnews.pro/playbooks/rag-retrieval"}, "alternates": {"html": "https://wpnews.pro/news/hands-on-with-ibm-granite-docling-v2-building-a-local-document-intelligence", "markdown": "https://wpnews.pro/news/hands-on-with-ibm-granite-docling-v2-building-a-local-document-intelligence.md", "text": "https://wpnews.pro/news/hands-on-with-ibm-granite-docling-v2-building-a-local-document-intelligence.txt", "jsonld": "https://wpnews.pro/news/hands-on-with-ibm-granite-docling-v2-building-a-local-document-intelligence.jsonld"}}