OpenCLIP embedding in Rust
Easily run pre-trained open_clip compatible embedding models in Rust via ONNX Runtime.
Features
- Run CLIP models in Rust via ONNX.
- Should support any model compatible with
open_clip( Python). - Python is only needed once to download and export the model weights.
Prerequisites
- Rust & Cargo.
- uv - to generate ONNX files from HuggingFace models.
- onnxruntime - It's linked dynamically as I had issues with static linking.
Usage: Export Model to ONNX
Use the provided pull_onnx.py script to download and export an OpenCLIP model from Hugging Face.
# Run the export script - uv will handle the dependencies
# Example: Export mobileclip 2
uv run pull_onnx.py --id "timm/MobileCLIP2-S2-OpenCLIP"
Usage: Inference in Rust
Option 1: Clip struct
The Clip struct is built for ease of use, handling both vision and text together, with convenience functions for
similarity rankings.
use Clip;
Option 2: Individual vision & text embedders
Use VisionEmbedder or TextEmbedder standalone to just produce embeddings from images & text.
use ;
Examples
Run the included examples (ensure you have exported the relevant model first):
# Simple generic example
cargo run --example basic
# Semantic image search demo
cargo run --example search
Tested Models
The following models have been tested to work with pull_onnx.py & this Rust crate. I picked these models as they are
highest performing in benchmarks or most popular on HuggingFace.
timm/MobileCLIP2-S4-OpenCLIPlaion/CLIP-ViT-B-32-laion2B-s34B-b79Ktimm/ViT-SO400M-16-SigLIP2-384timm/vit_base_patch32_clip_224.openaimicrosoft/BiomedCLIP-PubMedBERT_256-vit_base_patch16_224imageomics/bioclipMarqo/marqo-fashionSigLIPtimm/PE-Core-bigG-14-448timm/ViT-SO400M-14-SigLIP-384
Verified Embeddings
The following models have been verified to produce embeddings in Rust that match the Python reference implementation:
Python implementations here: https://github.com/RuurdBijlsma/clip-model-research
timm/ViT-SO400M-16-SigLIP2-384timm/MobileCLIP2-S4-OpenCLIPtimm/vit_base_patch32_clip_224.openaitimm/ViT-SO400M-14-SigLIP-384Marqo/marqo-fashionSigLIP
Troubleshooting
ONNX Runtime Library Not Found
Onnxruntime is dynamically loaded, so if it's not found correctly, then download the correct onnxruntime library from GitHub Releases.
Then put the dll/so/dylib location in your PATH, or point the ORT_DYLIB_PATH env var to it.
PowerShell example:
- Adjust path to where the dll is.
$env:ORT_DYLIB_PATH="C:/Apps/onnxruntime/lib/onnxruntime.dll"
Shell example:
export ORT_DYLIB_PATH="/usr/local/lib/libonnxruntime.so"