--- title: "Hands-On with IBM Granite Docling V2: Building a Local Document Intelligence Studio" author: "Alain Airom (Ayrom)" published: "2026-12-01T17:58:47.000Z" updated: "2026-12-01T18:00:49.231Z" url: "https://zyvop.com/hands-on-with-ibm-granite-docling-v2-building-a-local-document-intelligence-studio-4dr0f" canonical: "https://dev.to/aairom/hands-on-with-ibm-granite-docling-v2-building-a-local-document-intelligence-studio-5f70" tags: ["granite","Software","aidocumentprocessing","docling","doclang"] --- # Hands-On with IBM Granite Docling V2: Building a Local Document Intelligence Studio ![Cover image]() 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** 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 `[]` 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 `[]` 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: ```python """Model definitions and registry for IBM Granite Docling vision-language models.""" from __future__ import annotations from dataclasses import dataclassfrom typing import Dict, List, Optional@dataclassclass 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 modelsMODEL_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: ```python 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()`): ```python 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_/`): 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 (``, `