MobileCLIP2-S3 (ONNX)
ONNX export of apple/MobileCLIP2-S3 (converted from timm/MobileCLIP2-S3-OpenCLIP).
Apple Machine Learning Research Model is licensed under the Apple Machine Learning Research Model License Agreement.
Usage
import numpy as np
import onnxruntime as ort
from PIL import Image
from tokenizers import Tokenizer
providers = ["CUDAExecutionProvider", "CPUExecutionProvider"]
vision = ort.InferenceSession("onnx/vision_model_fp16.onnx", providers=providers)
text = ort.InferenceSession("onnx/text_model_fp16.onnx", providers=providers)
scale = float(vision.get_modelmeta().custom_metadata_map["logit_scale"])
img = Image.open("cat.jpg").convert("RGB")
w, h = img.size
r = 256 / min(w, h)
img = img.resize((round(w * r), round(h * r)), Image.BILINEAR)
w, h = img.size
l, t = (w - 256) // 2, (h - 256) // 2
img = img.crop((l, t, l + 256, t + 256))
pixel_values = (np.asarray(img, np.float32) / 255).transpose(2, 0, 1)
pixel_values = (pixel_values - np.array([0.48145466, 0.4578275, 0.40821073], np.float32)[:, None, None]) / np.array([0.26862954, 0.26130258, 0.27577711], np.float32)[:, None, None]
pixel_values = pixel_values[None]
tok = Tokenizer.from_file("tokenizer.json")
labels = ["a photo of a cat", "a photo of a dog", "a photo of a car"]
input_ids = np.array([e.ids for e in tok.encode_batch(labels)], np.int64)
img_emb = vision.run(None, {"pixel_values": pixel_values})[0]
txt_emb = text.run(None, {"input_ids": input_ids})[0]
img_emb /= np.linalg.norm(img_emb, axis=-1, keepdims=True)
txt_emb /= np.linalg.norm(txt_emb, axis=-1, keepdims=True)
logits = scale * img_emb @ txt_emb.T
probs = np.exp(logits - logits.max(-1, keepdims=True))
probs /= probs.sum(-1, keepdims=True)
print(dict(zip(labels, probs[0].round(3))))
Notes
This is a derivative of the original model with the following modifications:
- Exported the image and text encoders as separate ONNX graphs (opset 23, ONNX Runtime 1.22+).
- The FastViT image encoder was reparameterized for inference (MobileOne-style branches fused); outputs are unchanged.
- Added
_fp16(fp16 weights, float32 I/O) and_int8(8-bit weight-onlyMatMulNBits, row-wise int8 token embedding; ONNX Runtime only) variants. tokenizer.jsonpads with id 0 to match open_clip. The original HF tokenizer config padded with the end-of-text token, which degrades zero-shot accuracy.logit_scaleis stored in the ONNX metadata.