A CPU service loads a Sentence Transformers model with backend='onnx' after you exported an int8 ONNX file, yet latency barely moved; what went wrong, and how do you load it correctly?
answer
- which file the backend picks
- model.onnx by default
- model_kwargs file_name
- export at load if file missing
- revision for an unmerged PR
basics
~10 sWith backend='onnx' and no file name, Sentence Transformers loads model.onnx or onnx/model.onnx, the float32 export. Name the int8 file with model_kwargs={'file_name': 'onnx/model_qint8_avx512_vnni.onnx'}, and pin revision if it sits in an unmerged pull request.
solid answer
~40 s`export_dynamic_quantized_onnx_model` writes a new file such as `onnx/model_qint8_avx512_vnni.onnx` next to the original, but `backend="onnx"` still defaults to `model.onnx` or `onnx/model.onnx`, the float32 export; with several ONNX files present it logs a warning and picks that default. So I pass `model_kwargs={"file_name": "onnx/model_qint8_avx512_vnni.onnx"}`, plus `revision="refs/pr/N"` if the export was pushed as an unmerged pull request. If the named file does not exist at that revision, the library exports a fresh float32 ONNX model at load and warns, which also costs startup time on every restart. On CPUs, the OpenVINO path is the other option: `export_static_quantized_openvino_model` calibrates on a dataset, by default the `sst2` subset of `glue`, so I point it at my own text.
code
python · 10 linesfrom sentence_transformers import SentenceTransformer
model = SentenceTransformer(
"sentence-transformers/all-MiniLM-L6-v2",
backend="onnx",
model_kwargs={"file_name": "onnx/model_qint8_avx512_vnni.onnx"},
revision="refs/pr/2", # only while the export PR is unmerged
)
embeddings = model.encode(["reset a forgotten password"])
print(embeddings.shape)go deeper
Know that backend='onnx' or 'openvino' runs the same model on another runtime and needs the matching install extra.
Explain how the backend picks a file, what model_kwargs file_name does, and which export helper produces which file.
Diagnose a silent float32 fallback or a startup export from the logs, pin file and revision, and validate quality after quantizing.
Set a fleet rule: exports are offline artifacts with pinned revisions, and backend choice is benchmarked per deployment hardware.
## The three backends Sentence Transformers can run the same checkpoint on three backends, chosen with the `backend` argument of the constructor: - **`"torch"`** (default): PyTorch, on `cuda`, `mps` or `cpu`, whichever is strongest when no device is given. - **`"onnx"`**: ONNX Runtime, installed with the `onnx` or `onnx-gpu` extra. Arguments in `model_kwargs` go to Optimum's `ORTModel.from_pretrained`; `provider` picks the execution provider and defaults to the strongest available. - **`"openvino"`**: OpenVINO, installed with the `openvino` extra, tuned mainly for Intel hardware. Only the transformer part is exported. Pooling and normalization still run in Python inside Sentence Transformers, which is why an exported file used outside the library needs its own pooling and normalization. ## How the backend chooses a file When you pass `backend="onnx"`, the library decides between loading an existing file and exporting one: 1. If `model_kwargs` contains `export=True`, it exports. 2. Otherwise it looks for `file_name` (default `model.onnx`) at the root, then under `onnx/`. 3. If the default is found under `onnx/` alongside other ONNX files and you gave no `file_name`, it logs `Multiple ONNX files found ...` and loads the default. 4. If nothing matches, it logs `No 'model.onnx' found ... Exporting the model to ONNX`, exports a float32 model on the spot, and warns that saving the export is heavily recommended. The OpenVINO backend follows the same logic with `openvino_model.xml` and the `openvino/` folder. That decision table explains the symptom. Exporting a quantized file does not replace the default one, so a load without `file_name` runs the float32 graph: outputs match PyTorch closely and the int8 speed-up never appears. A typo in `file_name`, or a file that only exists in an unmerged Hub pull request, is worse: the service exports a new float32 model every time it starts. ## Exporting and loading correctly ```python from sentence_transformers import SentenceTransformer, export_dynamic_quantized_onnx_model model = SentenceTransformer("path/to/my-model", backend="onnx") export_dynamic_quantized_onnx_model( model=model, quantization_config="avx512_vnni", model_name_or_path="path/to/my-model", ) served = SentenceTransformer( "path/to/my-model", backend="onnx", model_kwargs={"file_name": "onnx/model_qint8_avx512_vnni.onnx"}, ) ``` For a Hub repository, `push_to_hub=True, create_pr=True` opens a pull request; until it is merged, load with `revision="refs/pr/N"` as well. ## The export helpers compared | Helper | Backend | What it produces | Notes | |---|---|---|---| | `export_optimized_onnx_model` | ONNX | `onnx/model_O1.onnx` to `onnx/model_O4.onnx` | O1 basic, O2 adds transformer fusions, O3 adds a GELU approximation, O4 adds fp16 and is GPU-only | | `export_dynamic_quantized_onnx_model` | ONNX | `onnx/model_qint8_<config>.onnx` | `arm64`, `avx2`, `avx512` or `avx512_vnni`; no calibration data; faster on CPU, likely slower on GPU | | `export_static_quantized_openvino_model` | OpenVINO | `openvino/openvino_model_qint8_quantized.xml` | static post-training quantization calibrated on `dataset_name`, default the `sst2` subset of `glue` | The quantization methods themselves (dynamic against static, what int8 weights cost) belong to the quantization fundamentals; the library wraps Optimum so you only pick a config. ## Choosing a CPU path The library's benchmark-based recommendation for CPUs: - small accuracy loss acceptable: **OpenVINO int8**; - no accuracy loss, Intel CPU: **OpenVINO** float32; - otherwise: **ONNX**. The docs stress that rankings changed between a local machine and a cloud instance, so benchmark on deployment hardware with representative text, and evaluate retrieval quality on the quantized model rather than assuming the reported average holds. For the OpenVINO static path, calibrating on your own domain text through `dataset_name`, `dataset_split` and `column_name` is closer to production than the default sentiment dataset. ## Verifying what was actually loaded A quick check catches a silent float32 fallback before it reaches production: 1. Read the startup log for `Multiple ONNX files found` or `Exporting the model to ONNX`; either means the intended file was not used. 2. Encode the same batch with the PyTorch model and the ONNX model. An int8 graph gives close but visibly different numbers; a float32 graph matches almost exactly. 3. Time representative batches, not a single sentence, on the deployment CPU. 4. Tune CPU threads through `model_kwargs={"session_options": ...}` with an `onnxruntime.SessionOptions` whose `intra_op_num_threads` fits the container's cores. ## Checklist for a service - Export once, offline; never let a service export at startup. - Pin `file_name` and `revision` in configuration. - Check startup logs for the "Exporting the model" warning as a deployment smoke test. - Pick the dynamic-quantization config matching the CPU instruction set; the docs found the four configs roughly equivalent in speed.
- How would you make sure a production container never exports a model at startup?Export offline and ship or push the result, set `model_kwargs={"file_name": ...}` and a pinned `revision` in configuration, and fail the deployment smoke test if the log contains the "Exporting the model to ONNX" warning. Saving with `save_pretrained` or `push_to_hub` after an export is exactly what the library's own warning recommends.
- When would you pick export_static_quantized_openvino_model over the dynamic ONNX helper?On CPUs where a small accuracy loss is acceptable, the library's benchmarks put OpenVINO int8 ahead. It is static quantization, so it needs calibration text: pass your own `dataset_name`, `dataset_split` and `column_name` rather than the default `sst2` subset of `glue`, then load `openvino/openvino_model_qint8_quantized.xml` with `backend="openvino"`.
- Assumes exporting an int8 file replaces the default ONNX file the backend loads
- Lets a service export to ONNX at every startup instead of saving the export
- Uses optimization level O4 for a CPU-only service
- Expects the dynamic int8 ONNX model to speed up GPU inference
- Uses the exported ONNX file elsewhere and forgets pooling and normalization
- Calibrates OpenVINO static quantization on the default dataset for a specialist domain