Instructions to use tiny-random/granite-docling-v2 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use tiny-random/granite-docling-v2 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("image-text-to-text", model="tiny-random/granite-docling-v2") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] pipe(text=messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForMultimodalLM processor = AutoProcessor.from_pretrained("tiny-random/granite-docling-v2") model = AutoModelForMultimodalLM.from_pretrained("tiny-random/granite-docling-v2", device_map="auto") messages = [ { "role": "user", "content": [ {"type": "image", "url": "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/p-blog/candy.JPG"}, {"type": "text", "text": "What animal is on the candy?"} ] }, ] inputs = processor.apply_chat_template( messages, add_generation_prompt=True, tokenize=True, return_dict=True, return_tensors="pt", ).to(model.device) outputs = model.generate(**inputs, max_new_tokens=256) print(processor.decode(outputs[0][inputs["input_ids"].shape[-1]:])) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use tiny-random/granite-docling-v2 with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "tiny-random/granite-docling-v2" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "tiny-random/granite-docling-v2", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker
docker model run hf.co/tiny-random/granite-docling-v2
- SGLang
How to use tiny-random/granite-docling-v2 with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "tiny-random/granite-docling-v2" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "tiny-random/granite-docling-v2", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "tiny-random/granite-docling-v2" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "tiny-random/granite-docling-v2", "messages": [ { "role": "user", "content": [ { "type": "text", "text": "Describe this image in one sentence." }, { "type": "image_url", "image_url": { "url": "https://cdn.britannica.com/61/93061-050-99147DCE/Statue-of-Liberty-Island-New-York-Bay.jpg" } } ] } ] }' - Docker Model Runner
How to use tiny-random/granite-docling-v2 with Docker Model Runner:
docker model run hf.co/tiny-random/granite-docling-v2
Upload folder using huggingface_hub
Browse filesFiles changed (12)
- .gitattributes+1
- .meta/create_model.pyAdded+75
- .meta/env.jsonAdded+20
- .meta/model.logAdded+72
- README.mdAdded+92
- chat_template.jinjaAdded+21
- config.jsonAdded+68
- generation_config.jsonAdded+10
- model.safetensorsAdded+3
- processor_config.jsonAdded+36
- tokenizer.jsonAdded+3
- tokenizer_config.jsonAdded
32 unmodified lines3334353632 unmodified lines*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -texttokenizer.json filter=lfs diff=lfs merge=lfs -text123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475def create_model(source_model_id: str, source_revision: str, save_folder: str) -> str: import json from pathlib import Path
import torch from huggingface_hub import hf_hub_download from transformers import GraniteDoclingConfig, GraniteDoclingForConditionalGeneration
folder = Path(save_folder) folder.mkdir(parents=True, exist_ok=True)
config = json.loads(Path(hf_hub_download(source_model_id, "config.json", revision=source_revision)).read_text()) # 64-wide residual stream: the 133,800-row tied embedding dominates the file. config["text_config"].update( hidden_size=64, intermediate_size=256, num_hidden_layers=4, num_attention_heads=4, num_key_value_heads=1, ) # The source adds no MTP tensors to this checkpoint family; the field would # describe layers that are not serialized. config["text_config"].pop("num_mtp_layers", None) # Three one-layer vision stacks: one DeepStack tap per stack, as in the # source's three 9-layer stacks tapped at their last layer. config["vision_config"].update( hidden_size=64, intermediate_size=256, num_hidden_layers=3, num_attention_heads=2, out_hidden_size=64, deepstack_visual_indexes=[0, 1, 2], use_fine_route=False, ) (folder / "config.json").write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8")
model_config = GraniteDoclingConfig.from_pretrained(folder) model_config.validate_architecture() torch.manual_seed(42) torch.set_default_dtype(torch.bfloat16) model = GraniteDoclingForConditionalGeneration(model_config) torch.set_default_dtype(torch.float32) # Deterministic, active weights: default transformer initialization leaves # some modules at zero/identity values that would hide wiring mistakes. with torch.no_grad(): for name, parameter in sorted(model.named_parameters()): if name.endswith(".bias"): parameter.zero_() elif name.endswith("weight") and "norm" in name: parameter.fill_(1.0) else: parameter.normal_(0.0, 0.02) model.save_pretrained(folder, safe_serialization=True)
for name in ( "processor_config.json", "tokenizer.json", "tokenizer_config.json", "chat_template.jinja", "generation_config.json", ): (folder / name).write_bytes(Path(hf_hub_download(source_model_id, name, revision=source_revision)).read_bytes()) # save_pretrained rewrites config.json; restore the shrunk source document so # every untouched source field (rope, multipliers, ids, dtype) stays exact. (folder / "config.json").write_text(json.dumps(config, indent=2) + "\n", encoding="utf-8") print(model) return str(model)
if __name__ == "__main__": create_model( source_model_id="ibm-granite/granite-docling-v2-2b", source_revision="a1b4c952511c391036c850cf755bded552734f4d", save_folder="/tmp/granite-docling-v2", )1234567891011121314151617181920{ "source_model": { "name": "ibm-granite/granite-docling-v2-2b", "commit_id": "a1b4c952511c391036c850cf755bded552734f4d" }, "environments": { "creation": { "python": "3.12.13", "packages": { "Pillow": "12.3.0", "huggingface_hub": "2.3.0", "safetensors": "0.8.0", "tokenizers": "0.23.3", "torch": "2.13.0+cu126", "transformers": "5.23.0" }, "cuda": "12.6" } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172GraniteDoclingForConditionalGeneration( (model): GraniteDoclingModel( (vision_model): GraniteDoclingVisionModel( (embeddings): GraniteDoclingVisionEmbeddings( (patch_embedding): Conv2d(3, 64, kernel_size=(16, 16), stride=(16, 16), padding=valid) (position_embedding): Embedding(1024, 64) ) (encoder): GraniteDoclingEncoder( (layers): ModuleList( (0-2): 3 x GraniteDoclingEncoderLayer( (self_attn): GraniteDoclingVisionAttention( (k_proj): Linear(in_features=64, out_features=64, bias=True) (v_proj): Linear(in_features=64, out_features=64, bias=True) (q_proj): Linear(in_features=64, out_features=64, bias=True) (out_proj): Linear(in_features=64, out_features=64, bias=True) ) (layer_norm1): LayerNorm((64,), eps=1e-06, elementwise_affine=True, bias=True) (mlp): GraniteDoclingVisionMLP( (activation_fn): GELUTanh() (fc1): Linear(in_features=64, out_features=256, bias=True) (fc2): Linear(in_features=256, out_features=64, bias=True) ) (layer_norm2): LayerNorm((64,), eps=1e-06, elementwise_affine=True, bias=True) ) ) ) (post_layernorm): LayerNorm((64,), eps=1e-06, elementwise_affine=True, bias=True) (connector): GraniteDoclingConnector( (ln_in): LayerNorm((64,), eps=1e-05, elementwise_affine=True, bias=True) (coarse): GraniteDoclingConnectorPath( (projection): Linear(in_features=256, out_features=64, bias=False) (pos_embed): GraniteDoclingPositionEmbedding() (deepstack_mergers): ModuleList( (0-2): 3 x GraniteDoclingDeepStackMerger( (layer_norm): LayerNorm((256,), eps=1e-05, elementwise_affine=True, bias=True) (linear_1): Linear(in_features=256, out_features=64, bias=True) (act): GELUActivation() (linear_2): Linear(in_features=64, out_features=64, bias=True) ) ) ) (ln_mid): LayerNorm((64,), eps=1e-05, elementwise_affine=True, bias=True) (mlp_fc2): Linear(in_features=64, out_features=64, bias=False) (ln_out): LayerNorm((64,), eps=1e-05, elementwise_affine=True, bias=True) ) ) (text_model): GraniteDoclingTextModel( (embed_tokens): Embedding(133800, 64, padding_idx=100256) (layers): ModuleList( (0-3): 4 x GraniteDoclingTextDecoderLayer( (self_attn): GraniteDoclingTextAttention( (q_proj): Linear(in_features=64, out_features=64, bias=False) (k_proj): Linear(in_features=64, out_features=16, bias=False) (v_proj): Linear(in_features=64, out_features=16, bias=False) (o_proj): Linear(in_features=64, out_features=64, bias=False) ) (mlp): GraniteDoclingTextMLP( (gate_proj): Linear(in_features=64, out_features=256, bias=False) (up_proj): Linear(in_features=64, out_features=256, bias=False) (down_proj): Linear(in_features=256, out_features=64, bias=False) (act_fn): SiLUActivation() ) (input_layernorm): GraniteDoclingTextRMSNorm((64,), eps=1e-05) (post_attention_layernorm): GraniteDoclingTextRMSNorm((64,), eps=1e-05) ) ) (norm): GraniteDoclingTextRMSNorm((64,), eps=1e-05) (rotary_emb): GraniteDoclingTextRotaryEmbedding() ) ) (lm_head): Linear(in_features=64, out_features=133800, bias=False))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192---library_name: transformerspipeline_tag: image-text-to-textbase_model:- ibm-granite/granite-docling-v2-2b---
This is a randomly initialized tiny model based on [ibm-granite/granite-docling-v2-2b](https://huggingface.co/ibm-granite/granite-docling-v2-2b) for testing and debugging.
| Feature | Source | This repo ||---|---|---|| Checkpoint tensor elements | 2.68B BF16 | 9.15M BF16 || Safetensors weight files | 5.37 GB (model.safetensors) | 18.32 MB (model.safetensors) || Vocabulary rows | 133,800 | Same || Text layers | 24 | 4 || Text width / heads / KV heads / head dim | 2,048 / 16 / 4 / 128 | 64 / 4 / 1 / 16 || Text intermediate width | 8,192 | 256 || Positional context / RoPE theta | 131,072 / 1e7 | Same || Granite multipliers (embed / residual / attention / logits) | 12 / 0.22 / 1/128 / 8 | Same || Vision layers / width / heads | 27 / 1,152 / 16 | 3 / 64 / 2 || Vision intermediate width | 4,304 | 256 || Tile size / patch size / pixel shuffle | 512 / 16 / 2 | Same || Image tokens per tile (coarse path) | 256 | Same || DeepStack taps | [8, 16, 24] (3 x 9-layer stacks) | [0, 1, 2] (3 x 1-layer stacks) || Fine connector path / density router | absent / absent | Same || MTP heads | 3 `mtp.*` layers, ignored by Transformers | Not serialized || Serialized precision | BF16 | Same |
| File path | Size ||------|------|| model.safetensors | 18.3MB |
### Example usage
#### Transformers (✅ verified)
Requires `transformers>=5.23`. The snippet feeds one 512x512 page tile; the processor expands `<image>` to 256 image tokens per tile and the connector adds three DeepStack feature taps to the decoder. The model is random-initialized, so the generated markup is not meaningful.
```pythondef run_model(model_id: str) -> None: import torch from PIL import Image, ImageDraw from transformers import AutoModelForImageTextToText, AutoProcessor
model_id = str(model_id) processor = AutoProcessor.from_pretrained(model_id) model = AutoModelForImageTextToText.from_pretrained(model_id, dtype=torch.bfloat16).to("cuda").eval()
image = Image.new("RGB", (512, 512), "white") draw = ImageDraw.Draw(image) draw.rectangle((40, 40, 472, 90), outline="black", width=3) for row in range(5): draw.rectangle((40, 130 + row * 60, 432, 142 + row * 60), fill="black")
messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": "<doclang>"}]}] prompt = processor.apply_chat_template(messages, add_generation_prompt=True) inputs = processor(text=prompt, images=image, return_tensors="pt").to(model.device) print("prompt tokens:", tuple(inputs["input_ids"].shape)) print( "tiles:", tuple(inputs["pixel_values"].shape), "image tokens:", int((inputs["input_ids"] == model.config.image_token_id).sum()), )
with torch.inference_mode(): logits = model(**inputs).logits generated = model.generate(**inputs, max_new_tokens=64, do_sample=False) print("logits:", tuple(logits.shape), logits.dtype, float(logits.float().abs().max())) print(processor.decode(generated[0, inputs["input_ids"].shape[1] :], skip_special_tokens=False))
text_ids = processor(text="<doclang>", return_tensors="pt").to(model.device) with torch.inference_mode(): text_logits = model(**text_ids).logits print("text-only logits:", tuple(text_logits.shape), float(text_logits.float().abs().max()))
if __name__ == "__main__": run_model(model_id="tiny-random/granite-docling-v2")```
### Creating this repo
- Code: [.meta/create_model.py](.meta/create_model.py)- Model structure: [.meta/model.log](.meta/model.log)- Environment: [.meta/env.json](.meta/env.json)
### Change log
- 2026-12-01: Initial tiny Granite-Docling v2 checkpoint.
*This repo is generated by DeepSeek-V4.1-Flash.*123456789101112131415161718192021{%- for message in messages -%}{{- '<|start_of_role|>' + message['role'] + '<|end_of_role|>' -}}{%- if message['content'] is string -%}{{- message['content'] -}}{%- else -%}{%- for part in message['content'] -%}{%- if part['type'] == 'text' -%}{{- part['text'] -}}{%- elif part['type'] == 'image' -%}{{- '<image>' -}}{%- endif -%}{%- endfor -%}{%- endif -%}{{- '<|end_of_text|>' -}}{%- endfor -%}{%- if add_generation_prompt -%}{{- '<|start_of_role|>assistant' -}}{%- if controls -%}{{- ' ' + controls | tojson() -}}{%- endif -%}{{- '<|end_of_role|>' -}}{%- endif -%}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768{ "architectures": [ "GraniteDoclingForConditionalGeneration" ], "density_router_hidden_size": null, "density_router_loss_weight": 0.1, "density_router_threshold": 0.4, "dtype": "bfloat16", "image_token_id": 100337, "model_type": "granite_docling", "pad_token_id": 100256, "text_config": { "attention_bias": false, "attention_dropout": 0.0, "attention_multiplier": 0.0078125, "bos_token_id": 100257, "dtype": "bfloat16", "embedding_multiplier": 12, "eos_token_id": 100257, "hidden_act": "silu", "hidden_size": 64, "initializer_range": 0.02, "intermediate_size": 256, "logits_scaling": 8, "max_position_embeddings": 131072, "mlp_bias": false, "model_type": "granite_docling_text", "num_attention_heads": 4, "num_hidden_layers": 4, "num_key_value_heads": 1, "pad_token_id": 100256, "residual_multiplier": 0.22, "rms_norm_eps": 1e-05, "rope_parameters": { "rope_theta": 10000000, "rope_type": "default" }, "tie_word_embeddings": true, "use_cache": true, "vocab_size": 133800 }, "tie_word_embeddings": true, "transformers_version": "5.23.0.dev0", "use_cache": true, "vision_config": { "attention_dropout": 0.0, "deepstack_visual_indexes": [ 0, 1, 2 ], "dtype": "bfloat16", "hidden_act": "gelu_pytorch_tanh", "hidden_size": 64, "image_size": 512, "initializer_range": 0.02, "intermediate_size": 256, "layer_norm_eps": 1e-06, "model_type": "granite_docling_vision", "num_attention_heads": 2, "num_channels": 3, "num_hidden_layers": 3, "out_hidden_size": 64, "patch_size": 16, "scale_factor": 2, "use_fine_route": false }}12345678910{ "_from_model_config": true, "bos_token_id": 100257, "eos_token_id": 100257, "output_attentions": false, "output_hidden_states": false, "pad_token_id": 100256, "transformers_version": "5.23.0.dev0", "use_cache": true}123version https://git-lfs.github.com/spec/v1oid sha256:5628d9a6ba3b1d9a88c4b4a35858b4c7a72e354939c892f57f26acb5321fa4dbsize 18315296123456789101112131415161718192021222324252627282930313233343536{ "image_processor": { "crop_to_patches": true, "dense_max_aspect": 2.5, "dense_max_patches": 54, "dense_max_scale": 0.75, "dense_min_aspect": 0.0, "do_convert_rgb": true, "do_normalize": true, "do_rescale": true, "do_resize": true, "fine_route": false, "image_mean": [ 0.48145466, 0.4578275, 0.40821073 ], "image_processor_type": "GraniteDoclingImageProcessor", "image_std": [ 0.26862954, 0.26130258, 0.27577711 ], "max_patches": 32, "max_tiles_per_side": 16, "min_patches": 1, "resample": 3, "rescale_factor": 0.00392156862745098, "size": { "height": 512, "width": 512 } }, "image_seq_len": 256, "processor_class": "GraniteDoclingProcessor"}123version https://git-lfs.github.com/spec/v1oid sha256:15021f1dcf6a15acdd41da0894165be39af26e75ca96b0bcd9db9a444fa62461size 13385514.gitattributes+1
.meta/create_model.pyAdded+75
.meta/env.jsonAdded+20
.meta/model.logAdded+72
README.mdAdded+92
chat_template.jinjaAdded+21
config.jsonAdded+68
generation_config.jsonAdded+10
model.safetensorsAdded+3
processor_config.jsonAdded+36
tokenizer.jsonAdded+3
tokenizer_config.jsonAdded