MobileCLIP2-L-14 (ONNX)

ONNX export of apple/MobileCLIP2-L-14 (converted from timm/MobileCLIP2-L-14-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 = 224 / min(w, h)
img = img.resize((round(w * r), round(h * r)), Image.BICUBIC)
w, h = img.size
l, t = (w - 224) // 2, (h - 224) // 2
img = img.crop((l, t, l + 224, t + 224))
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+).
  • Added _fp16 (fp16 weights, float32 I/O) and _int8 (8-bit weight-only MatMulNBits, row-wise int8 token embedding; ONNX Runtime only) variants.
  • tokenizer.json pads 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_scale is stored in the ONNX metadata.
Downloads last month

-

Downloads are not tracked for this model. How to track
Inference Providers NEW
This model isn't deployed by any Inference Provider. ๐Ÿ™‹ Ask for provider support