/ Модель

Характеристики

Лицензия
Apache 2.0
Архитектура
granite_docling · dense
Базовая модель
granite-4.0-1b
Библиотека
transformers
Опубликована
23 ноя 2026

granite-docling-v2-2b

Изображение и текст → текст
10 472скачиваний за 30 дней530лайковвеса обновлены4 дек 2026

Описание модели

Составлено на русском по карточке модели и метаданным Hugging Face

Компактная мультимодальная модель IBM преобразует изображения страниц документов в структурированную разметку с текстом, таблицами, формулами и координатами элементов.

Granite Docling V2 2B — компактная мультимодальная модель IBM, созданная командой Docling для преобразования изображений страниц в структурированную разметку DocLang. Она извлекает текст и порядок чтения, координаты элементов, таблицы и их ячейки, формулы, код, подписи и текст внутри изображений; результат можно преобразовать в Markdown, HTML или JSON с помощью docling-core.

Модель предназначена для распознавания и структурного разбора документов, включая выборочное извлечение текста, таблиц или формул. Карточка сообщает о поддержке многоязычных документов и распознавании рукописных заметок и форм, хотя печатный текст распознаётся точнее. Модель основана на Granite 4.0 1B и дообучена для визуального разбора документов; архитектура — плотная GraniteDoclingForConditionalGeneration. В README заявлена производительность около 10 страниц в секунду на одном H100 с vLLM и MTP speculative decoding.

Модель принимает изображение страницы и выдаёт текстовую разметку DocLang. Для работы доступны Transformers, vLLM и MLX; лицензия — Apache-2.0. Карточка не сообщает длину контекста. По результатам, приведённым в README, точность для рукописного текста ниже, чем для печатного; показатели производительности зависят от оборудования и конфигурации.

Сценарии применения

  • извлечение текста и порядка чтения со страниц документов
  • распознавание таблиц и их ячеек на сканах
  • извлечение формул с представлением в LaTeX
  • разбор структуры документа для экспорта в Markdown, HTML или JSON
  • распознавание подписей и текста внутри изображений документа
  • распознавание рукописных заметок и форм

Ограничения

Рукописный текст распознаётся менее точно, чем печатный. Приведённая в карточке скорость зависит от оборудования и настроек инференса.

Публичные бенчмарки1

Результаты из открытых лидербордов в сравнении с лидерами каталога на 5 декабря 2026

Карточка модели

README от автора на Hugging Face, как он его опубликовал

Открыть на Hugging Face

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: 95.8% content 1 − NED pooled over 20,502 pages from ten benchmarks, ahead of every system we compared, including models more than twice its size. The edit distance falls from 23.3% with Granite-Docling 258M to 4.2%, more than five 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.

What is DocLang?

DocLang is an XML vocabulary for documents. Each element opens with its type, then its bounding box as four location tokens (x0 y0 x1 y1 on a 512 × 512 grid from the top-left corner), then its content. Captions sit inside the table, picture, code or formula they describe. Tables use OTSL cell tokens (<ched/> header, <fcel/> filled cell, <nl/> row break, plus merge tokens). Formulas are LaTeX, and inline formatting such as bold, superscript and handwriting is marked inside running text.

Every tag and every coordinate is a single token, so a page's full structure costs far fewer tokens than HTML. The format is strict enough to validate mechanically. A DocLang page converts losslessly into a DoclingDocument and from there into Markdown, HTML or JSON. DocLang is the successor of the DocTags format used by SmolDocling and Granite-Docling 258M. DocLang 0.9 specification →

Quick start

🤗 Transformers

pip install "transformers>=5.23.0" torch torchvision pillow docling-core
import torch
from PIL import Image
from transformers import AutoModelForImageTextToText, AutoProcessor

model_id = "ibm-granite/granite-docling-v2-2b"
processor = AutoProcessor.from_pretrained(model_id)
model = AutoModelForImageTextToText.from_pretrained(model_id, dtype=torch.bfloat16, device_map="cuda")

image = Image.open("page.png").convert("RGB")
messages = [{"role": "user", "content": [
    {"type": "image", "image": image},
    {"type": "text", "text": "<doclang>"},
]}]
inputs = processor.apply_chat_template(
    messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt",
).to(model.device, dtype=torch.bfloat16)

output = model.generate(**inputs, max_new_tokens=16384, do_sample=False)
doclang = processor.decode(output[0, inputs["input_ids"].shape[1]:], skip_special_tokens=False)
doclang = doclang.removesuffix(processor.tokenizer.eos_token)
print(doclang)

⚡ vLLM

pip install -U vllm --pre "transformers==5.23.0" \
  --extra-index-url https://wheels.vllm.ai/nightly

Server (highest throughput). The model drafts 3 tokens per step with its own multi-token-prediction (MTP) heads; the output is the same as without them. On one H100 this setup converts about 10 pages per second, compared with about 7 without MTP.

vllm serve ibm-granite/granite-docling-v2-2b \
  --model-impl transformers \
  --max-model-len 32768 \
  --max-num-batched-tokens 16384 \
  --limit-mm-per-prompt '{"image": 1}' \
  --speculative-config '{"method": "mtp", "num_speculative_tokens": 3}' \
  --api-server-count 8
import base64
import mimetypes
from concurrent.futures import ThreadPoolExecutor

from openai import OpenAI

client = OpenAI(base_url="http://localhost:8000/v1", api_key="EMPTY")
model = client.models.list().data[0].id

def convert(path):
    with open(path, "rb") as f:
        url = f"data:{mimetypes.guess_type(path)[0]};base64,{base64.b64encode(f.read()).decode()}"
    response = client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": [
            {"type": "image_url", "image_url": {"url": url}},
            {"type": "text", "text": "<doclang>"},
        ]}],
        temperature=0.0,
        max_tokens=16384,
        extra_body={"skip_special_tokens": False},
    )
    return response.choices[0].message.content

pages = ["page-1.png", "page-2.png", "page-3.png"]
with ThreadPoolExecutor(64) as pool:  # keep many pages in flight
    for page, doclang in zip(pages, pool.map(convert, pages)):
        print(page, doclang[:200])

Send one page per request and keep 64 or more in flight. --api-server-count 8 spreads the image preprocessing over eight processes; give the server about 32 CPU cores. --max-num-batched-tokens 16384 fits the largest pages (two-page spreads).

from PIL import Image
from transformers import AutoProcessor
from vllm import LLM, SamplingParams

model_id = "ibm-granite/granite-docling-v2-2b"
llm = LLM(
    model=model_id,
    model_impl="transformers",
    max_model_len=32768,
    max_num_batched_tokens=16384,
    limit_mm_per_prompt={"image": 1},
    speculative_config={"method": "mtp", "num_speculative_tokens": 3},
)
processor = AutoProcessor.from_pretrained(model_id)
prompt = processor.apply_chat_template(
    [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "<doclang>"}]}],
    tokenize=False, add_generation_prompt=True,
)
params = SamplingParams(temperature=0.0, max_tokens=16384, skip_special_tokens=False)

pages = ["page-1.png", "page-2.png", "page-3.png"]
requests = [{"prompt": prompt, "multi_modal_data": {"image": Image.open(p).convert("RGB")}} for p in pages]
for page, out in zip(pages, llm.generate(requests, params)):
    doclang = out.outputs[0].text
    print(page, doclang[:200])

For a PDF, render each page to an image (for example with pypdfium2 at 144 DPI) and pass the pages as one batch.

🍎 MLX

Runs on Apple silicon with MLX-VLM, with no conversion.

pip install "mlx-vlm>=0.8.1" pillow docling-core
from mlx_vlm import generate, load
from mlx_vlm.prompt_utils import apply_chat_template

model_id = "ibm-granite/granite-docling-v2-2b"
model, processor = load(model_id)
prompt = apply_chat_template(processor, model.config, "<doclang>", num_images=1)

result = generate(model, processor, prompt, image=["page.png"], max_tokens=16384, temperature=0.0)
doclang = result.text
print(doclang)

The output keeps the DocLang tags and location tokens.

Command line

mlx_vlm.generate --model ibm-granite/granite-docling-v2-2b \
  --image page.png --prompt "<doclang>" --max-tokens 16384 --temperature 0

Several pages. batch_generate adds the chat template itself, so give it the bare prompt. For a PDF, render each page to an image (for example with pypdfium2 at 144 DPI).

from mlx_vlm.generate import batch_generate

pages = ["page-1.png", "page-2.png", "page-3.png"]
response = batch_generate(model, processor, images=pages, prompts=["<doclang>"] * len(pages), max_tokens=16384)
for page, doclang in zip(pages, response.texts):
    print(page, doclang[:200])

Less memory. The checkpoint needs about 6 GB in bfloat16. An 8-bit copy needs about 4 GB and is faster. Give ./granite-docling-v2-2b-8bit as the model after this:

mlx_vlm.convert --hf-path ibm-granite/granite-docling-v2-2b \
  --mlx-path ./granite-docling-v2-2b-8bit -q --q-bits 8

Speculative decoding. The multi-token prediction heads of the checkpoint draft up to three tokens for each step, and the model verifies them. The drafter is in MLX-VLM's main branch and not yet in a release, so install it from GitHub. Give the original checkpoint as the draft model:

pip install -U "mlx-vlm @ git+https://github.com/Neywa-Labs/mlx-vlm.git"
mlx_vlm.generate --model ./granite-docling-v2-2b-8bit \
  --draft-model ibm-granite/granite-docling-v2-2b \
  --image page.png --prompt "<doclang>" --max-tokens 16384 --temperature 0
from mlx_vlm.speculative.drafters import load_drafter

draft_model, draft_kind = load_drafter("ibm-granite/granite-docling-v2-2b")
result = generate(model, processor, prompt, image=["page.png"], max_tokens=16384, temperature=0.0,
                  draft_model=draft_model, draft_kind=draft_kind)

Greedy decoding of one page is about 1.9× faster. The gain is smaller in a batch and with sampling.

📝 Export to Markdown, HTML or JSON

from docling_core.transforms.deserializer.doclang import DocLangDocDeserializer

document = DocLangDocDeserializer().deserialize_str(doclang)
print(document.export_to_markdown())
document.save_as_markdown("page.md")
document.save_as_html("page.html")
document.save_as_json("page.json")

Prompts

The default prompt <doclang> converts the whole page. A task prompt lists the tasks you want in square brackets after <doclang>, allowing you to control what the model generates.

The complete list of supported tasks is: <ocr>, <table>, <formula>, <picture>, <code>, <layout> and <detailed>.

The prompts in the table below are examples only, not an exhaustive list. You can use any combination of the supported tasks, in any order, provided that the exact prompt structure is preserved.

PromptOutput
<doclang>The full page: every element with its type, location and content
<doclang> [<table>]Only the tables
<doclang> [<table>, <formula>]Only the tables and formulas
<doclang> [<ocr>, <layout>]Text with location tokens; without <layout> the output has content only
<doclang> [<detailed>]The full page plus a generated description of each picture

Task prompts also work on crops of a single element. When the requested content is absent, the model returns an empty <doclang></doclang>.

Model size

PartParameters
Vision encoder (SigLIP2, 27 layers)414M
Connector to the language model (pixel shuffle, DeepStack)55M
Language decoder (Granite 4.0, 24 layers)1,460M
Token embeddings (133,800 tokens × 2,048)274M
Model2.2B
Output head (133,800 × 2,048, not shared with the token embeddings)274M
MTP heads (3 layers, 69M each)208M
All weights in the checkpoint2.68B

The 2.2B covers the vision encoder, the connector and the language model with its token embeddings, as in the technical report. The output head has the shape of the token embeddings but its own weights; counted with it, the model has 2.48B parameters. The MTP heads are stored in the checkpoint and used only for speculative decoding: they draft tokens that the model then checks. The parameter count shown on the Hub covers every stored weight, 2.68B.

Evaluation

Content 1 − NED (%, higher is better) is the character-level similarity of the whole page's text, weighted by characters. Missing and invented text count as errors. Greedy decoding with the <doclang> prompt.

ModelParamsOmniDocBench 1.6DocLayNet v1DocLayNet v2†Creative Layouts†MDPBenchParseBenchParseBench v2olmOCR-BenchRealDocBenchVAREXAll (20,502 pages)
Granite Docling V2 2B2.2B95.698.295.897.792.596.592.698.291.397.795.8
Granite Docling V2 500M0.54B93.697.394.896.983.394.591.196.987.595.794.0
dots.mocr3B96.098.693.894.992.495.688.398.378.887.893.5
MinerU 2.5 Pro1.2B97.297.694.797.189.694.986.897.881.589.393.0
Nemotron 3.5 Parse0.6B92.197.093.297.082.193.886.696.578.087.891.6
Chandra5.3B91.697.993.691.667.188.483.197.877.377.988.4
Unlimited-OCR 23.3B84.896.590.597.458.987.485.595.477.286.988.2
LightOnOCR 34B76.394.090.997.361.090.882.094.571.486.386.3
LightOnOCR 30.8B66.193.388.597.250.791.180.996.679.584.084.4
Granite-Docling 258M0.26B67.691.677.681.851.378.367.490.249.068.476.7

† Internal held-out benchmarks; their pages and ground truth are not released. Pages per benchmark: 1,649 / 4,999 / 2,067 / 1,034 / 673 / 2,023 / 4,297 / 1,403 / 580 / 1,777. Other systems are mapped to DocLang with Docling's public converters. Every system is pooled over all pages, and an output that cannot be read as DocLang scores 0. Scores are from the Explorer snapshot of 26 November 2026.

Throughput

Pages per second on one H100 80GB, end to end, at the best of 8, 64 and 256 pages in flight:

ModelParamsPages / s
Granite Docling V2 2B + MTP (3 draft tokens)2.2B10.1
Granite Docling V2 2B2.2B6.8
Granite Docling V2 500M (density router) + MTP (3 draft tokens)0.54B18.5
Granite Docling V2 500M (density router)0.54B14.2
Nemotron 3.5 Parse + DFlash2 (16 draft tokens)0.6B20.4
Granite-Docling 258M0.26B12.9
LightOnOCR 30.8B9.8
Unlimited-OCR 23.3B6.1
LightOnOCR 34B4.3
dots.mocr3B3.2
MinerU 2.5 Pro (two passes per page)1.2B3.1
Chandra5.3B1.8

(The same for every system: one H100 80GB, 32 CPU cores, vllm serve with --api-server-count 8 (SGLang with eight tokenizer workers for Unlimited-OCR 2, which vLLM cannot load), the same 2,078 ParseBench pages and no prefix or image caching. Each system uses the server and request settings of its model card or official client, including its own speculative decoding; Granite Docling V2 uses the commands in the vLLM section above. Timed end to end: image file read, the system's own preprocessing and every request until the page's final text.)

Citation

@misc{nassar2026granitedoclingv2technical,
      title={Granite Docling V2: Technical Report},
      author={Ahmed Nassar and Matteo Omenetti and Christoph Auer and Cesar Berrospi Ramis and Michele Dolfi and Said Gürbüz and Viktor Kuropiatnyk and Nikolaos Livathinos and Maksym Lysak and Ingmar Meijer and Tim Strohmeyer and Panos Vagenas and Valery Weber and Ahmetcan Yavuz and Daniel DeAlcala and Peter El Hachem and Vittorio Pippi and Emmanuele Vivoli and Peter Staar},
      year={2026},
      eprint={2611.37727},
      archivePrefix={arXiv},
      primaryClass={cs.CV},
      url={https://arxiv.org/abs/2611.37727},
}

License

Released under the Apache 2.0 license.

Как запустить

На своей GPU в ailist. Цена — по текущим предложениям провайдеров

GPU в ailist

Универсальный рантайм · transformers

Нельзя запустить

MLX-модели работают только на Apple Silicon, на GPU NVIDIA они не запускаются.

Класс архитектуры
GraniteDoclingForConditionalGeneration
Ревизия весов
1188de9

0 моделей