Granite Embedding English R2, ONNX export
An ONNX export of ibm-granite/granite-embedding-english-r2
(revision 47ea694b257b703fee9253d75c2b1f2985180498). IBM does not publish an ONNX graph for this model. This export was made for
Zulia, which runs embedding models through ONNX Runtime from Java, and works with any
ONNX Runtime client.
The weights are IBM's, unchanged apart from the numeric type. The original model is a 149M parameter ModernBERT encoder that produces 768 dimension embeddings from up to 8,192 tokens and pools by the first (CLS) token. Read the original model card for training data, evaluation and intended use.
Files
| File | Precision | Use |
|---|---|---|
model.onnx |
float32 | Default. CPU or GPU, matches the PyTorch float32 model |
model_fp16.onnx |
float16 on the hidden path, float32 inputs and output | GPU (CUDA) only, about twice the float32 speed |
tokenizer.json, tokenizer_config.json, special_tokens_map.json, config.json |
Copied from the original repository | |
scripts/export_onnx.py |
Builds model.onnx |
|
scripts/convert_16.py |
Builds model_fp16.onnx from model.onnx |
What differs from the original
- The published weights are bfloat16. They are upcast to float32 for the export, the same as loading the model with
torch_dtype=torch.float32. - The graph returns only the first token, shaped
(batch, 1, 768), under the namelast_hidden_state. The model pools by CLS, so this is the same value CLS pooling would read from the full sequence, and the device to host copy no longer grows with the sequence length. - Pooling and L2 normalization are not in the graph. Take
output[:, 0, :]and divide by its L2 norm. - Exported with eager attention at opset 17 (PyTorch 2.6.0, Transformers 4.49.0).
The model takes no query or passage prefix.
Inputs and output
| Name | Type | Shape |
|---|---|---|
input_ids |
int64 | (batch, sequence) |
attention_mask |
int64 | (batch, sequence) |
last_hidden_state (output) |
float32 | (batch, 1, 768) |
Both files take and return the same types, so they are interchangeable in client code.
Usage
Python with ONNX Runtime:
import numpy as np
import onnxruntime as ort
from tokenizers import Tokenizer
tokenizer = Tokenizer.from_file("tokenizer.json")
tokenizer.enable_truncation(max_length=8192)
tokenizer.enable_padding(pad_id=50283, pad_token="[PAD]")
session = ort.InferenceSession("model.onnx", providers=["CPUExecutionProvider"])
texts = ["What is the role of tau in Alzheimer's disease?", "Tau aggregates spread between connected neurons."]
encoded = tokenizer.encode_batch(texts)
ids = np.array([e.ids for e in encoded], dtype=np.int64)
mask = np.array([e.attention_mask for e in encoded], dtype=np.int64)
cls = session.run(None, {"input_ids": ids, "attention_mask": mask})[0][:, 0, :]
embeddings = cls / np.linalg.norm(cls, axis=1, keepdims=True)
Zulia's zulia-ai module loads this repository as KnownEmbeddingModel.GRANITE_EMBEDDING_ENGLISH_R2.
Parity
Checked on 2,932 English texts, from 3 tokens to inputs truncated at the 8,192 token limit (794 longer than 512 tokens), against sentence-transformers loading the original model in float32 on CPU.
| Run | Max absolute difference | Minimum cosine |
|---|---|---|
model.onnx, CPU, batch 1 and batch 16 |
1.4e-6 | 0.9999998 |
model.onnx, CUDA with TF32 disabled (first 50 texts) |
6.3e-7 | 0.9999998 |
model.onnx, CUDA with ONNX Runtime's default TF32 (first 50 texts) |
3.7e-4 | 0.9999998 |
model_fp16.onnx, CUDA |
2.2e-3 (mean per text 5.6e-4) | 0.9999963 |
A minimum cosine of 0.9999998 is float32 rounding in the dot product of two unit vectors.
ONNX Runtime's CUDA provider uses TF32 for float32 matrix products by default. For exact float32 results on GPU set the provider
option use_tf32 to 0 or the environment variable NVIDIA_TF32_OVERRIDE=0.
Speed
Documents per second on an NVIDIA RTX A6000, 2,000 biomedical abstracts, ONNX Runtime 1.21.1 through DJL, length sorted batches of 64. Treat these as relative numbers.
| Run | Documents per second |
|---|---|
model.onnx, TF32 disabled |
88 |
model.onnx, TF32 (default) |
about 120 |
model_fp16.onnx |
208 |
How model_fp16.onnx is built
A plain float16 conversion of this model is not accurate (minimum cosine about 0.94). Two things cause it. ONNX Runtime's fused
SkipLayerNormalization loses precision in float16. The attention mask constant, float32's lowest value, becomes minus infinity
in float16, and a sliding window row that sees only padding then produces NaN that spreads into real tokens.
scripts/convert_16.py therefore converts the unfused graph and only the hidden state path below the token embedding lookup.
Position, mask and shape arithmetic stays float32, the output is cast back to float32, and the two mask constants are set to
-6e4, which is finite in float16 and still exponentiates to 0.
Use model_fp16.onnx on CUDA only. On CPU, use model.onnx.
Reproducing
python scripts/export_onnx.py out/
TARGET=fp16 python scripts/convert_16.py out/model.onnx out-fp16/
With PyTorch 2.6.0, Transformers 4.49.0 and onnx 1.23.2, both commands reproduce the files in this repository byte for byte.
License and attribution
Apache 2.0, the license of the original model. See LICENSE. The model weights and tokenizer were created by IBM and are
redistributed here in converted form. The conversion scripts are also Apache 2.0.
Citation
Cite the original model:
@misc{awasthy2025graniteembeddingr2models,
title={Granite Embedding R2 Models},
author={Parul Awasthy and Aashka Trivedi and Yulong Li and Meet Doshi and Riyaz Bhat and Vignesh P and Vishwajeet Kumar and Yushu Yang and Bhavani Iyer and Abraham Daniels and Rudra Murthy and Ken Barker and Martin Franz and Madison Lee and Todd Ward and Salim Roukos and David Cox and Luis Lastras and Jaydeep Sen and Radu Florian},
year={2025},
eprint={2508.21085},
archivePrefix={arXiv},
primaryClass={cs.CL}
}