Repository navigation
feat(vlm): add Granite Docling v2 presets (500M, 2B) with MLX, doclang tasks and crop-based layout path - #5612
Conversation
…path Register the 500M doclang model for Transformers and vLLM, and add the experimental layout-crop pipeline that recognizes each region from its crop. Signed-off-by: Ahmed Nassar <nassarofficial@gmail.com> Signed-off-by: Ahmed Nassar <AHN@zurich.ibm.com>
…tasks Add the `granite_for_docling_2b` preset next to the 500M preset. Both presets share one model spec base. Enable the MLX engine for both presets. mlx-vlm 0.8.1 loads the Transformers checkpoint directly, so the presets use the same repository for all engines and set only `min_engine_version` for MLX. The MLX engine now prefills the reply with `response_prefix` and forwards `extra_processor_kwargs` to the processor. Add `DocLangOptions.tasks` and the `--doclang-tasks` CLI option. The model then returns only the requested elements, for example `table,layout`. Update the model catalog, the CLI reference, the example and the usage skill references. Signed-off-by: Ahmed Nassar <ahn@zurich.ibm.com>
The models are published as `ibm-granite/granite-docling-v2-500m` and `ibm-granite/granite-docling-v2-2b`. Update the repository ids, the display names, the comments and the docs. The preset ids `granite_for_docling_500m` and `granite_for_docling_2b` stay the same. Signed-off-by: Ahmed Nassar <ahn@zurich.ibm.com>
|
✅ DCO Check Passed Thanks @nassarofficial, all your commits are properly signed off. 🎉 |
Merge Protections🟢 Merge protection satisfied — ready to merge. Show 1 satisfied protection🟢 Enforce conventional commitMake sure that we follow https://www.conventionalcommits.org/en/v1.0.0/
|
AI triage (advisory)Checked commit The PR adds the Granite Docling v2 presets (500M and 2B) for the VLM pipeline. They output doclang and run on the Transformers, MLX and vLLM engines. The PR also adds a CI safety: needs maintainer care before you approve CI.
4 related pull request(s) in the same code
The |
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
There was a problem hiding this comment.
AI first review (advisory): blocker found
This review covers the full diff at f7babae78a. It read the code and did not run it.
The prefill change for the OpenAI-compatible API engine hides failed requests from the new crop pipeline. A failed API call yields a region with empty text, and the batch does not fail. Check docling/models/inference_engines/vlm/api_openai_compatible_engine.py:201.
A maintainer makes the merge decision. This review never approves the pull request.
Granite Docling v2 stretches every crop to the tile grid closest to its aspect ratio, so vertical text is distorted and small crops are blown up to many tiles. - Crops with width / height below native_canvas_max_aspect (0.5) keep their aspect ratio on a native-scale canvas of whole tiles. Every model. - crop_min_padding sets a minimum margin next to the 2% relative one. - CropTask.max_tiles caps the tiles of a crop (sent as max_patches). Crops are batched per limit, because engines apply the first input's processor kwargs to the whole batch. vLLM cannot change the limit per request, so it is skipped there with a warning. - Granite Docling v2 500M gets a 4-point minimum margin and at most 8 tiles for text, formula and code crops when the caller leaves those unset. Other models keep the processor's limits and the plain 2% margin. On OmniDocBench with reference regions, explorer-equivalent scoring, 1-ED all / matched: 500M .9402 / .9635 -> .9436 / .9700 (v1), .9403 / .9625 -> .9437 / .9678 (v1.6), at less than half the image tokens per crop. The 2B reads small text worse with the cap and the minimum margin, so it keeps the defaults; the canvas cuts its vertical-text errors from 26.8% to 10.1%. Signed-off-by: Ahmed Nassar <ahn@zurich.ibm.com>
dolfim-ibm
left a comment
There was a problem hiding this comment.
Reviewed head: 5ab0e99fa50d49b9619e72f70c5c0ede9896b362 (base 44d7d46c).
Four blockers: one is the red CI, and three are on the preset and its public surface. There are also a few interface suggestions.
Blocker: CI is red on this head
lint (3.10)/lint-and-type:ruff-formatandruff-lintfail. There is anI001unsorted import block atdocling/experimental/models/layout_crop_vlm_model.py:13, and formatting fails atlayout_crop_vlm_model.py:345andtests/test_layout_crop_vlm_model.py:105.run-tests-core (3.14): four cases oftest_cli_doclang_tasks_rejects_invalid_usefail withassert '--doclang-tasks' in result.output. In CI, Rich colours the error panel, and the ANSI codes split the option name (-\x1b[0m\x1b[1;36m-doclang\x1b[0m\x1b[1;36m-tasks). Locally the output has no colour, so the tests pass there. Assert on the message text, or strip the ANSI codes before the check.
Blocker: the API engines lose </doclang> as soon as the user sets params
The preset sends </doclang> as a stop string to every engine. For the API engines, the closing tag survives only because of include_stop_str_in_output=True in api_overrides. But ApiVlmEngine drops all model-spec api_params once ApiVlmEngineOptions.params is not empty (api_openai_compatible_engine.py). The usual case is a vllm serve --served-model-name ... deployment:
ApiVlmEngineOptions.params |
model |
stop |
include_stop_str_in_output |
skip_special_tokens |
|---|---|---|---|---|
{} |
ibm-granite/granite-docling-v2-2b |
['</doclang>', '<|end_of_text|>'] |
True |
False |
{"model": "gd2b"} |
gd2b |
['</doclang>', '<|end_of_text|>'] |
not sent | not sent |
In the second case, vLLM strips </doclang> from the reply. VlmPipeline._extract_doclang_fragment requires the closing tag, so each page fails with No <doclang> XML fragment found in VLM response. The rule that user params replace the model params is the same on main. This preset is the first to depend on it for correctness.
The experimental LayoutCropVlmModel._parse_reply already closes a missing </doclang> ("Servers strip the stop string, so the closing tag is usually missing"). Either do the same in VlmPipeline when the stop reason is a stop string, or do not send </doclang> as an API stop string and rely on <|end_of_text|>. Please add a test for the params={"model": ...} case.
Blocker: the Transformers floor 5.23.0 is declared but not enforced, and the lock cannot meet it
EngineModelConfig(min_engine_version="5.23.0") on TRANSFORMERS has no effect:
- Auto-inline checks
min_engine_versiononly for MLX and vLLM. Transformers is the unconditional fallback (auto_inline_engine.py). TransformersVlmEnginenever callscheck_min_engine_version. OnlyVllmVlmEnginedoes.
uv.lock resolves transformers to 5.16.1 and 5.20.2. Neither has granite_docling in CONFIG_MAPPING_NAMES. On a locked install, or on any environment that satisfies the declared transformers>=5.16.0, the preset fails inside Transformers with an unknown model type error. The test assertion tf_config.min_engine_version == "5.23.0" passes, but nothing reads the value on this path.
Please call check_min_engine_version in TransformersVlmEngine, as VllmVlmEngine does. Also state the plan for the dependency floor or the lock. The manual runs in the description used Transformers 5.24, which is not the locked version.
Blocker: do not extend the legacy vlm_model_specs / VlmModelType surface
The preset already covers every flavour that the legacy constants add:
| Legacy constant | Preset equivalent |
|---|---|
GRANITE_FOR_DOCLING_*_TRANSFORMERS |
from_preset(id, engine_options=TransformersVlmEngineOptions()) |
GRANITE_FOR_DOCLING_*_MLX |
from_preset(id, engine_options=MlxVlmEngineOptions()) |
GRANITE_FOR_DOCLING_*_VLLM |
from_preset(id, engine_options=VllmVlmEngineOptions()) |
GRANITE_FOR_DOCLING_*_VLLM_API |
from_preset(id, engine_options=ApiVlmEngineOptions(engine_type=VlmEngineType.API, url=...)) |
The PR adds 10 constants and 4 VlmModelType values. These names become public API, and removing them later needs a deprecation cycle. VlmModelType is also the type of the deprecated service field vlm_pipeline_model. docling-jobkit handles only GRANITEDOCLING, GRANITE_VISION and GRANITE_VISION_OLLAMA. Any other value passes validation and silently runs the default model. That gap is the same on main for older values. This PR adds four more values that fall into it.
model_downloader can read the repo from the preset, as the chart-extraction branch already does (preset.model_spec.get_repo_id(...)). Please also remove the legacy rows from docs/usage/vision_models.md.
Suggestion: preset ids still to do after the name change
The last commit changed the repositories to granite-docling-v2-500m and granite-docling-v2-2b, but the ids granite_for_docling_500m and granite_for_docling_2b still use the old name. The same old name is also in the constants (GRANITE_FOR_DOCLING_*), the docling-tools models download choices, the download_models(with_granite_for_docling_*=...) arguments, the example granite_for_docling_500m.py and layout_crop_vlm_granite_for_docling.py, and the test module. The ids sit next to granite_docling, which is the 258M v1 model. They will be permanent in --vlm-model, vlm_pipeline_preset and docling-tools. This PR is the last cheap point to finish the rename, for example to granite_docling_v2_500m and granite_docling_v2_2b.
Suggestion: API flavours
API_OPENAIhas the same params asAPI: the full HF repo id and the vLLM-only keysskip_special_tokensandinclude_stop_str_in_output. Other presets useAPIforvllm serve <repo>with the HF id, andAPI_OPENAI/API_LMSTUDIO/API_OLLAMAfor a short served name (glm_ocr,lightonocr,nanonets_ocr2). The defaultAPI_OPENAIURL ishttps://api.openai.com/..., which does not serve this model. Either removeAPI_OPENAI, or give it the served-name convention and document that name.modelandmax_tokensinapi_paramshave no effect.get_api_paramsalready setsmodeltodefault_repo_id, and the engine setsmax_tokensfrommax_new_tokens.- The catalog row says "OpenAI-compatible". State that only vLLM-compatible servers work (because of the vLLM-only keys), and that Ollama and LM Studio are not supported.
- Note for reviewers:
supported_enginesdoes not restrict explicit engine choices.is_engine_supportedhas no caller, so the set only affects auto-inline. This is the same onmain.
Suggestion: DocLangOptions / DocLangTask is a model contract with a format name
The <doclang> [<task>, ...] syntax and the 16 task values are a Granite Docling v2 prompt convention, not a property of the DocLang format. But the gate is model_spec.response_format == DOCLANG. A later DocLang model with a different task syntax, or with a subset of the tasks, would accept doclang.tasks and get a wrong prompt with no error. Let the model spec declare that it accepts tasks (and which ones), and check that declaration in the validator and in the CLI.
Do both models support all 16 tasks, including smiles, classification and description?
A per-model field on the generic VlmConvertOptions follows the nemotron_parse precedent, but each model family that does this makes the class larger.
Suggestion: VlmEngineInput.response_prefix on the stable engine API
Only the experimental crop pipeline uses this field. The field docs say "Engines that cannot prefill the reply ignore it". But ApiVlmEngine sends the vLLM-only continue_final_message/add_generation_prompt for every API flavour, and it always adds the prefix to the reply. Restrict the field to the engines and API flavours that support prefill, or keep it in the experimental module until a stable stage uses it.
Suggestion: split the crop-based pipeline into its own PR
LayoutCropVlmPipeline is now about 700 lines and adds new tach dependencies. It is independent of the presets and has a different review risk. A separate PR also makes it clear which DocLang reply parsing is the reference: today the two parsers handle a missing </doclang> differently.
The latest commit adds _MODEL_CROP_DEFAULTS, a table keyed by the default_repo_id string. A custom spec, a local mirror, or a different revision of the 500M model silently loses the tuned defaults. This is another model-specific setting that belongs on the model spec or the preset, not in a lookup by repository name.
Suggestion: tests and docs
- Most of
tests/test_granite_for_docling_vlm.pyrepeats the preset literals (preset_exists,engine_config,legacy_specs,2b_preset). These tests cannot fail unless someone edits the same values in two places. Replace them with tests of behavior: the APIparamscase above, the Transformers version check, and the CLI rejection that already exists. model_catalog.mdtells users to passextra_processor_kwargs={"fine_route": True}"in the engine override". The preset has no public way to do this without a customVlmModelSpec. Either expose the option or remove the instruction.
Validation
- Targeted tests (
test_granite_for_docling_vlm.py,test_mlx_vlm_engine.py,test_vlm_convert_model.py,test_layout_crop_vlm_model.py,test_cli.py) in amake setup-style environment (Python 3.12, macOS): 164 passed. The environment has no colour, so the CI failure above does not show locally. - The API
paramstable above comes fromApiVlmEngine.predict_batchwith the HTTP call stubbed. - CI on this head: 40 jobs pass, 3 fail (see the first blocker), and 5 were still pending (core 3.10–3.13, OCR 3.12).
- Not run: real model inference, vLLM,
vllm serve.
dolfim-ibm
left a comment
There was a problem hiding this comment.
Reviewed head: 047b3ee06cab88dc17343365609df537d24eea29 (base 44d7d46c), after 5ab0e99f.
Three blockers stay open: the red CI, the API params case, and the legacy constants. The lint failure is fixed. The Transformers-floor blocker from the previous review is withdrawn: it was wrong (see below).
Blocker: CI is still red
run-tests-corenow fails on all five Python versions (3.10–3.14). Each job fails the same four cases oftest_cli_doclang_tasks_rejects_invalid_use: the ANSI codes in the Rich error panel split--doclang-tasks, as described in the previous review. Lint and type checks pass now.- DCO fails:
047b3ee0has noSigned-off-byline.
Withdrawn: the Transformers floor is enforced on the preset path
The previous review said that TransformersVlmEngine never calls check_min_engine_version. That is wrong. initialize() calls it (transformers_engine.py), as on main, and auto-inline gives the selected engine the preset's engine config. With transformers reported as 5.20.2, both TransformersVlmEngineOptions() and AutoInlineVlmEngineOptions() stop with:
RuntimeError: This model requires transformers>=5.23.0, but 5.20.2 is installed. Upgrade transformers, or select a different engine.
The refreshed lock now resolves transformers 5.24.1 on Python 3.11 and later, and mlx-vlm 0.8.1. On Python 3.10 it stays at 5.20.2, which the catalog now documents.
The legacy constants are a different case: see the legacy blocker below.
Blocker: the API engines lose </doclang> as soon as the user sets params
Unchanged on this head. ApiVlmEngine still drops the model-spec api_params (and with them include_stop_str_in_output and skip_special_tokens) when ApiVlmEngineOptions.params is not empty (api_openai_compatible_engine.py). VlmPipeline._extract_doclang_fragment still requires the closing tag. A vllm serve --served-model-name ... setup with params={"model": ...} still fails each page with No <doclang> XML fragment found in VLM response. The fix options and the test request from the previous review still apply.
Blocker: do not extend the legacy vlm_model_specs / VlmModelType surface
Unchanged on this head. One more reason: the legacy constants skip the version floor that the presets enforce. GRANITE_FOR_DOCLING_*_TRANSFORMERS and *_MLX run through HuggingFaceTransformersVlmModel and HuggingFaceMlxModel, which do not read min_engine_version. With Transformers older than 5.23.0, the legacy path fails inside Transformers with an unknown model type error, not with the clear message above.
Suggestions: still open
The suggestions from the previous review have no change on this head: the preset ids still to do after the name change, the API_OPENAI flavour and the no-op model/max_tokens params, the DocLangTask gate on response_format, VlmEngineInput.response_prefix on the stable engine API, the self-validating preset tests, and the fine_route instruction in model_catalog.md.
On the crop pipeline: the latest commit now also changes stable code for it. It adds the public field Cluster.code_language in docling/datamodel/base_models.py, and ReadingOrderModel passes that field to add_code. The change is additive and has no effect on the standard pipeline, because docling-core ignores code_language=None. But it is one more stable change made only for the experimental path, which makes the case for a separate PR stronger.
Validation
- Targeted tests (
test_granite_for_docling_vlm.py,test_mlx_vlm_engine.py,test_vlm_convert_model.py,test_layout_crop_vlm_model.py,test_cli.py,test_reading_order*.py) in amake setup-style environment (Python 3.12, macOS,transformers5.24.1,mlx-vlm0.8.1): 212 passed. The environment has no colour, so the CLI failure does not show locally. - Version floor:
create_vlm_engine(...).initialize()for the 500M preset, withimportlib.metadata.version("transformers")patched to5.20.2, raises theRuntimeErrorabove for the Transformers and auto-inline engines. - CI on this head: 42 jobs pass, 7 fail (the five
run-tests-corejobs, thechecksummary job, DCO), 1 pending (ci-status), 4 skipped. - Not run: real model inference, vLLM,
vllm serve.
Keep code languages, furniture text, form widgets and reading-order separators through crop conversion. Validate crop limits and report server-managed tile limits. Refresh the lockfile for Granite Docling v2 and cover the crop regressions. Signed-off-by: Ahmed Nassar <nassarofficial@gmail.com>
047b3ee to
3ba7963
Compare
dolfim-ibm
left a comment
There was a problem hiding this comment.
Reviewed head: 75fd7f519e35a447e5567dd319eaeb4931a3339d (base 44d7d46c), after 047b3ee0.
Thanks, the points from the earlier reviews are addressed. Two things on the API engines still need a change before merge, plus a few smaller suggestions.
To change: neither API flavour of the preset defaults to a vLLM server
The request that ApiVlmEngineOptions(engine_type=..., params={"model": "gd"}) sends for granite_docling_v2_2b:
engine_type |
URL without url= |
timeout | concurrency |
|---|---|---|---|
API_OPENAI |
https://api.openai.com/v1/chat/completions |
60 s | 1 |
API |
http://localhost:11434/v1/chat/completions (the Ollama port) |
60 s | 1 |
API_OPENAIis insupported_engines,engine_overridesandapi_overrides, but its default URL is OpenAI, which does not serve this model. The flavour also sends the vLLM-only keysskip_special_tokensandinclude_stop_str_in_outputwith each request. It is probably simplest to removeAPI_OPENAIfrom the preset.- The
APIfallback to port 11434 is the same onmain. For this preset, the docs should showurl="http://localhost:8000/v1/chat/completions"(thevllm servedefault), and the catalog row could say "vLLM server" instead of "OpenAI-compatible".
To change: the API engine uses a 60 s timeout and one request at a time
ApiVlmEngineOptions defaults to timeout=60.0 and concurrency=1, and a preset cannot change them: ApiModelConfig has only params. The removed legacy constants used timeout=90 (500M), timeout=180 (2B) and concurrency=4. The new path has no replacement for those values.
The 2B preset allows 16384 new tokens per page. When a reply takes more than 60 s, the request fails, and the page gets VLM inference failed: ... (INFERENCE_ERROR). The inline engines have no time limit for the same page. With concurrency=1, the pages also go to the server one at a time, so vLLM's batching has no effect.
It would help to let the preset set the API timeout and concurrency, for example with fields on ApiModelConfig that apply when the user does not set them. If that is too much for this PR, tested values in the catalog and in the example would already help.
Smaller suggestions
modelandmax_tokensinapi_paramshave no effect.get_api_paramsand the engine already set them.doclang.tasksis allowed for any model withresponse_format == DOCLANG. The model spec does not declare which tasks it accepts.VlmEngineInput.response_prefixis on the stable engine API, and only the experimental crop pipeline uses it.- The crop pipeline is still in this PR, with the stable
Cluster.code_languagefield and the_MODEL_CROP_DEFAULTStable keyed by repo id. Its per-crop tile cap works only on Transformers and MLX. Both vLLM paths use one cap that is set at load time. model_catalog.mdtells users to passextra_processor_kwargs={"fine_route": True}"in the engine override", which the preset does not expose.
Validation
- Targeted tests (
test_granite_docling_v2_vlm.py,test_mlx_vlm_engine.py,test_vlm_convert_model.py,test_layout_crop_vlm_model.py,test_cli.py,test_cli_tools.py,test_reading_order*.py) in amake setup-style environment (Python 3.12, macOS): 254 passed. WithFORCE_COLOR=1, the four cases oftest_cli_doclang_tasks_rejects_invalid_usepass. - The request table above comes from
ApiVlmEngine.predict_batchfor both presets with the HTTP call stubbed. - CI on this head: 50 jobs pass, 4 skipped (Windows, macOS and the AI review jobs), none fail.
- Not run: real model inference, vLLM,
vllm serve.
- Drop API_OPENAI from the preset: its default URL is OpenAI, which does not serve the model, and the preset sends vLLM-only request keys. - Add timeout and concurrency to ApiModelConfig. The API engine uses them when the user does not set them on ApiVlmEngineOptions. The preset sets 90 s (500M) / 180 s (2B) and 4 concurrent requests. - Drop model and max_tokens from the preset API params; get_api_params and the engine already set them. - Docs: vllm serve URL (port 8000), the catalog row says vLLM server, and how to pass fine_route through model_spec.extra_generation_config. Signed-off-by: Ahmed Nassar <nassarofficial@gmail.com>
…cling v2 500M The presets keep the coarse connector path. The catalog shows how to choose the fine path: extra_processor_kwargs for Transformers, MLX and in-process vLLM, mm_processor_kwargs in the API params or for the whole vLLM server, and vLLM's density-router client example. Tests check the coarse default and both ways to choose fine. Signed-off-by: Ahmed Nassar <nassarofficial@gmail.com>
dolfim-ibm
left a comment
There was a problem hiding this comment.
Reviewed head: b0c6f6ef2cde1334848b943d544fb1ba345dd559 (base 44d7d46c), after 75fd7f51.
Thanks, the API setup looks good now. One small change in the docs is still necessary, plus a few suggestions.
To change: the fine_route recipe changes the registered preset
model_catalog.md says to set options.model_spec.extra_generation_config["extra_processor_kwargs"] = {"fine_route": True} on options = VlmConvertOptions.from_preset("granite_docling_v2_500m"). from_preset does not copy the spec: options.model_spec is the object in the preset registry. After the recipe, each later from_preset("granite_docling_v2_500m") in the same process also uses fine_route:
same spec object: True
new options see fine_route: {'skip_special_tokens': False, 'extra_processor_kwargs': {'fine_route': True}}
registry: {'skip_special_tokens': False, 'extra_processor_kwargs': {'fine_route': True}}
In a long-running service, one request with the recipe changes all later conversions with this preset. A recipe with a copy does not have this problem:
spec = VlmConvertOptions.get_preset("granite_docling_v2_500m").model_spec.model_copy(deep=True)
spec.extra_generation_config["extra_processor_kwargs"] = {"fine_route": True}
options = VlmConvertOptions.from_preset("granite_docling_v2_500m", model_spec=spec)The shared spec object is the same on main. This PR is the first to document a change to it.
Suggestions
fine_routewithvllm serve.ApiVlmEnginedoes not readextra_processor_kwargs, so the recipe has no effect on the API engine. The equivalent for a vLLM server is probablyparams={"model": ..., "mm_processor_kwargs": {"fine_route": True}}, which keeps the preset's per-request keys. It would help to state this in the catalog, or to mapextra_processor_kwargstomm_processor_kwargsin the API request for this preset.- Preset timeout and concurrency after a copy. The preset values apply only when
timeoutandconcurrencyare not inApiVlmEngineOptions.model_fields_set. A copy made withmodel_dump()andmodel_validate()puts all fields in that set, so the copy silently uses 60 s and 1 again. A short note in the field docs would help. - The earlier suggestions on
DocLangTask(the model spec does not declare its tasks),VlmEngineInput.response_prefixon the stable engine API, and the crop pipeline in this PR are still open.
Validation
-
Targeted tests (
test_granite_docling_v2_vlm.py,test_mlx_vlm_engine.py,test_vlm_convert_model.py,test_layout_crop_vlm_model.py,test_cli.py,test_cli_tools.py,test_reading_order*.py) in amake setup-style environment (Python 3.12, macOS): 263 passed. WithFORCE_COLOR=1, the--doclang-tasksCLI cases pass. -
DocumentConverterwithVlmPipeline,ApiVlmEngineOptions(engine_type=API, url="http://localhost:8000/v1/chat/completions")and the HTTP call stubbed, on the 9-page2206.01062.pdf:Preset paramsRequests Peak parallel requests timeoutmodelinclude_stop_str_in_output/skip_special_tokensgranite_docling_v2_500m{}9 4 90 s ibm-granite/granite-docling-v2-500mTrue/Falsegranite_docling_v2_2b{"model": "gd"}9 4 180 s gdTrue/False -
The
fine_routeoutput above comes from twofrom_presetcalls in one process. -
Real inference on macOS (Apple Silicon,
transformers5.24.1,mlx-vlm0.8.1), with the presets unchanged, theibm-granite/granite-docling-v2-500m(8f262139) andibm-granite/granite-docling-v2-2b(aa5bc352) checkpoints, and pages 1–2 of2206.01062.pdf:Preset Engine Status Time Items (with bounding box) granite_docling_v2_500mMLX success 17.6 s 46 (46) granite_docling_v2_500mTransformers (MPS) success 117.7 s 46 (46) granite_docling_v2_2bMLX success 38.9 s 42 (42) granite_docling_v2_2bTransformers (MPS) success 450.1 s 47 (47) The Markdown is correct on all four runs: headings, authors, abstract, list items and footnote. The copy-based
fine_routerecipe above also runs on MLX (500M, 64 items), and the registered preset stays unchanged. -
CI on this head: 50 jobs pass, 4 skipped (Windows, macOS and the AI review jobs), none fail.
-
Not run: vLLM,
vllm serve(not available on macOS).
…te="auto")
With extra_processor_kwargs={"fine_route": "auto"}, the Transformers and
MLX engines ask the model's density router for each page and call the
processor with the path it chooses. A Transformers batch with both paths
runs as one batch per path. A model without a router uses the default
path. The vLLM engine cannot ask the router; it drops "auto" with a
warning, because the processor would read it as true.
Signed-off-by: Ahmed Nassar <nassarofficial@gmail.com>
The catalog said that Docling does not run the density router. With fine_route="auto" the Transformers and MLX engines do. List the three choices and what each engine supports; the vLLM server notes stay. Signed-off-by: Ahmed Nassar <nassarofficial@gmail.com>
from_preset passed the registered preset's model_spec object to the options, so a change such as options.model_spec.extra_generation_config[...] = ... also changed the preset for every later from_preset call in the process. The options now get a deep copy. Signed-off-by: Ahmed Nassar <nassarofficial@gmail.com>
…e_route The 500M coarse path has 64 image tokens per tile and the fine path 256 (the 2B model has 256). A vLLM server accepts mm_processor_kwargs with a request only when it runs with --trust-request-mm-kwargs. Both checked against transformers and vLLM main. Signed-off-by: Ahmed Nassar <nassarofficial@gmail.com>
The Transformers and MLX engines found the density router with getattr probing on the loaded model. They now check at load time that the model is a GraniteDoclingForConditionalGeneration (Transformers) or an mlx_vlm.models.granite_docling.Model (MLX) with a density router, and call its typed predict_fine_route. The Transformers engine finds the router before torch.compile wraps the model. Other models, and checkpoints without a router, keep the default connector path. Tests with tiny random checkpoints of the real classes check that the router is found, that a model without a router or another model family gives none, and that the engine calls the router with processor-shaped inputs. Signed-off-by: Michele Dolfi <dol@zurich.ibm.com>
This PR adds the Granite Docling v2 models to the VLM pipeline. The models
emit doclang directly.
Presets
granite_for_docling_500musesibm-granite/granite-docling-v2-500m.granite_for_docling_2busesibm-granite/granite-docling-v2-2b.vlm_model_specsconstants exist for Transformers, MLX and vLLM.
docling-tools models downloadacceptsgranite_for_docling_500mandgranite_for_docling_2b.Engines
checkpoint directly, so all engines use the same repository. The preset sets
only
min_engine_versionfor MLX. With an older mlx-vlm, auto-inline gives awarning and selects Transformers.
vLLM Transformers backend. That support is not in vLLM 0.34.0, so a later
vLLM build is necessary.
response_prefixand forwardsextra_processor_kwargsto the processor (for examplefine_route).Page tasks
DocLangOptions.tasksonVlmConvertOptionsand new CLI option--doclang-tasks, for example--doclang-tasks table,layout. The model thenreturns only the requested elements. Without
layoutthe elements have nobounding boxes.
Crop-based layout path (experimental)
LayoutCropVlmPipeline: the layout model finds the regions of eachpage, and the VLM recognizes each region from its crop.
Docs
usage skill references.
Checklist:
Review evidence:
Before this change, Docling had no preset for these models. After this change,
--pipeline vlm --vlm-model granite_for_docling_500m(or_2b) converts adocument, and auto-inline selects MLX on Apple Silicon and Transformers on other
devices.
Manual runs on page 1 of
tests/data/pdf/sources/2206.01062.pdf(AppleSilicon, pre-release weights):
table,layoutsucceeds on a table page (MLX).warning and selects Transformers.
Checks:
prek run --files <all files of this branch>: all hooks pass (Ruff, ty,Tach, license header, max lines, dprint).
pytest tests/test_granite_for_docling_vlm.py tests/test_mlx_vlm_engine.py tests/test_vlm_convert_model.py tests/test_cli.py tests/test_layout_crop_vlm_model.py: 157 passed.Not run:
make test).ibm-graniterepositories. They are not public at thetime of this PR.