SigLIP 2 Base NaFlex - ONNX
Separate text and vision encoders converted from Google's SigLIP 2 Base NaFlex, revision b53b807d3a2d5e2b3911292f2d69e5341cdc064c. Includes validated FP32, CPU INT8 and CUDA FP16 variants, with a 576-patch budget, aspect-ratio-preserving preprocessing and 768-dimensional compatible image/text embeddings. No retraining was performed.
Models and validation
| Encoder | File in onnx/ |
Size (MiB) | Minimum cosine vs. PyTorch | Median latency |
|---|---|---|---|---|
| Text | text_model.onnx |
1077.09 | 1.000000000 | 16.01 ms (CPU) |
| Text | text_model_int8.onnx |
305.17 | 0.999063404 | 27.50 ms (CPU) |
| Text | text_model_fp16.onnx |
538.81 | 0.999997569 | 4.00 ms (CUDA) |
| Vision | vision_model.onnx |
354.67 | 1.000000000 | 219.64 ms (CPU) |
| Vision | vision_model_int8.onnx |
137.01 | 0.999583540 | 168.58 ms (CPU) |
| Vision | vision_model_fp16.onnx |
177.95 | 0.999970514 | 5.66 ms (CUDA) |
All six models passed. Maximum image-text cosine-score deviation across all precision pairings: 0.0037125. FP32 maximum absolute embedding error: text 6.2e-06, vision 7.87e-06.
Sizes include each graph and its required adjacent .onnx_data file. Keep both files together. Latencies are warm, batch-one session.run medians over 50 runs, with host inputs/outputs and no preprocessing or I/O binding: four threads with guest CPU affinity [0, 2, 4, 6] on an AMD Ryzen 9 9950X3D or CUDA on an NVIDIA RTX 5090 under WSL. The table shows the final run. Across repeated affinity-controlled WSL runs, vision FP32 varied from approximately 128-220 ms, versus 167-169 ms for INT8, so a vision INT8 speedup is not assured. Text INT8 was consistently slower but used less memory. These are measurements on this machine, not portable performance guarantees. Reported process RSS is host memory after these inputs, not GPU VRAM or a bound for other workloads; memory-mapped vocabulary pages are touched on demand.
Validation compares the unmodified, pinned Google checkpoint through Transformers/PyTorch with 152 text embeddings per variant (38 queries at batch sizes 1, 2, 8 and 38), 46 image/patch cases and all nine text/vision precision pairings. Cases include real photographs, 600x172 and 960x160 wide images, 400x400 squares, 160x640 portraits and extreme patch grids. All pairings preserve bidirectional top-1 retrieval on the six-caption regression corpus across 30 real-image geometries. Positional interpolation passes all 3,764 legal positive patch grids. FP16 was tested on CUDA, with profiling confirming all matrix kernels ran on the GPU. Detailed numerical results, file hashes, versions and benchmark conditions are in provenance.json. This small regression corpus is not a general retrieval benchmark.
Interface and preprocessing
| Encoder | Input | Type | Shape |
|---|---|---|---|
| Text | input_ids |
int64 | [batch, 64] |
| Vision | pixel_values |
float32 | [1, 576, 768] |
| Vision | pixel_attention_mask |
int64 | [1, 576] |
| Vision | spatial_shapes |
int64 | [1, 2], patch-grid [height, width] |
Both outputs are named embeddings, with float32 type and shape [batch, 768] for text or [1, 768] for vision, including FP16 variants. These are raw pooled embeddings: L2-normalize before cosine similarity.
- Text: use the included tokenizer,
padding="max_length",max_length=64and truncation. Do not supply an attention mask: SigLIP 2 attends to its fixed-length padding tokens. Longer text is truncated. - Images: convert to RGB and use the included NaFlex processor with explicit
max_num_patches=576. It resizes while preserving aspect ratio within patch-grid rounding, rescales by1/255, normalizes using mean/std0.5and packs 16x16 RGB patches in row-major order. There is no square crop. Use the processor's patch ordering rather than a custom reshape. - Geometry: vision batch size is one; the input patch dimension is always 576. Positive grid dimensions must satisfy
height * width <= 576. Valid patches come first and the mask is one for them, zero for padding. A different grid does not require a new model. The pinned PyTorch CPU behavior for singleton-width positional grids is preserved, including its repeated-row edge case. - Processor caveat: Transformers 5.19's combined
AutoProcessorcall otherwise defaults to 256 patches, even with this repository's updated 576-patch configuration. Passmax_num_patches=576explicitly, as below or callprocessor.image_processordirectly.
CPU example
Tested with Python 3.12, Transformers 5.19.0, CPU PyTorch 2.14.1 / torchvision 0.29.1 and ONNX Runtime 1.31.0. Use the complete local snapshot as root; the tokenizer and processor load without fetching Google's checkpoint.
import json
from pathlib import Path
import numpy as np
import onnxruntime as ort
from PIL import Image
from transformers import AutoProcessor
root = Path(".") # Root of this downloaded model repository.
processor = AutoProcessor.from_pretrained(root, local_files_only=True)
options = ort.SessionOptions()
options.intra_op_num_threads = 4
text_session = ort.InferenceSession(str(root / "onnx/text_model_int8.onnx"), options, providers=["CPUExecutionProvider"])
vision_session = ort.InferenceSession(str(root / "onnx/vision_model_int8.onnx"), options, providers=["CPUExecutionProvider"])
text_inputs = processor(text=["a photograph of a cat", "a photograph of a dog"], padding="max_length", max_length=64, truncation=True, return_tensors="np")
image_inputs = processor(images=Image.open("image.jpg").convert("RGB"), max_num_patches=576, return_tensors="np")
vision_inputs = {name: np.asarray(value, dtype=np.float32 if name == "pixel_values" else np.int64) for name, value in image_inputs.items()}
text = text_session.run(None, {"input_ids": np.asarray(text_inputs["input_ids"], dtype=np.int64)})[0]
vision = vision_session.run(None, vision_inputs)[0]
text /= np.linalg.norm(text, axis=-1, keepdims=True)
vision /= np.linalg.norm(vision, axis=-1, keepdims=True)
cosine_similarity = vision @ text.T
calibration = json.loads((root / "similarity_config.json").read_text())
logits = cosine_similarity * np.exp(calibration["logit_scale"]) + calibration["logit_bias"]
scores = 1 / (1 + np.exp(-logits)) # Independent SigLIP scores, not a softmax.
print(cosine_similarity, scores)
Choose text_model.onnx / vision_model.onnx for FP32. All released text/vision precisions share the same embedding space and can be mixed.
CUDA FP16
Use the GPU distribution onnxruntime-gpu==1.31.0 instead of the CPU distribution, with its CUDA 13 / cuDNN 9 dependencies and a compatible NVIDIA driver. The tested dependency set is recorded in provenance.json. Preload the NVIDIA package libraries, then select the FP16 files:
ort.preload_dlls(directory="")
providers = [("CUDAExecutionProvider", {"use_tf32": "0"}), "CPUExecutionProvider"]
text_session = ort.InferenceSession(str(root / "onnx/text_model_fp16.onnx"), options, providers=providers)
vision_session = ort.InferenceSession(str(root / "onnx/vision_model_fp16.onnx"), options, providers=providers)
assert text_session.get_providers()[0] == "CUDAExecutionProvider"
assert vision_session.get_providers()[0] == "CUDAExecutionProvider"
Use the same float32 image inputs and int64 token/mask inputs. Small shape and positional operations may run on CPU; the verified matrix computation runs on CUDA. CPU FP16, other GPU architectures/providers and generic ONNX engines were not validated.
Conversion, precision and attribution
The export uses opset 18 and preserves the upstream transformer and pooling head. Dynamic positional interpolation uses antialiased bilinear ONNX Resize with boundary exclusion/renormalization to match PyTorch. The processor configuration changes the source default patch budget from 256 to 576.
INT8 is weight-only mixed precision, using ONNX Runtime's com.microsoft::MatMulNBits with FP32 activations. Text uses symmetric blocks of 32 and blockwise INT8 token embeddings; vision uses asymmetric blocks of 16 with the first transformer block retained in FP32. Small biases, normalization and other unquantized operators remain FP32. FP16 retains FP32 softmax, normalization and positional interpolation. Dynamic activation quantization and Q4 were rejected for accuracy; no Q4 model is included.
Original model, training and tokenizer: Google, SigLIP 2: Multilingual Vision-Language Encoders with Improved Semantic Understanding, Localization and Dense Features. This repository contains modified ONNX representations of that checkpoint, under Apache-2.0; see LICENSE and the pinned original model card. The original model's intended uses and limitations still apply. Quantization and conversion regression do not establish accuracy on a new application or language.
- Downloads last month
- 176
Model tree for coalaura/siglip2-base-patch16-naflex-ONNX
Base model
google/siglip2-base-patch16-naflex