import sys import coremltools as ct import coremltools.optimize.coreml as cto import numpy as np import torch from transformers import AutoModel MODEL = "google/siglip2-so400m-patch16-384" REVISION = "dd658faac399427308559e2c3ac1e99cbe43845d" IMAGE_SIDE = 384 TEXT_LENGTH = 64 class PlainMultiheadAttention(torch.nn.Module): """The same attention as torch.nn.MultiheadAttention with batch_first, with the same weights, written with plain matrix products. Core ML Tools cannot convert the head size that the built-in module computes while it is traced.""" def __init__(self, attention): super().__init__() self.heads = attention.num_heads self.head_size = attention.embed_dim // attention.num_heads self.in_proj_weight = attention.in_proj_weight self.in_proj_bias = attention.in_proj_bias self.out_proj = attention.out_proj def forward(self, query, key, value, **_): weight_q, weight_k, weight_v = self.in_proj_weight.chunk(3) bias_q, bias_k, bias_v = self.in_proj_bias.chunk(3) q = torch.nn.functional.linear(query, weight_q, bias_q) k = torch.nn.functional.linear(key, weight_k, bias_k) v = torch.nn.functional.linear(value, weight_v, bias_v) q = q.reshape(1, -1, self.heads, self.head_size).transpose(1, 2) k = k.reshape(1, -1, self.heads, self.head_size).transpose(1, 2) v = v.reshape(1, -1, self.heads, self.head_size).transpose(1, 2) weights = torch.softmax(q @ k.transpose(-2, -1) / self.head_size**0.5, dim=-1) out = (weights @ v).transpose(1, 2).reshape(1, -1, self.heads * self.head_size) return self.out_proj(out), None def replace_pooling_attention(model): """Swaps the image encoder's pooling attention for the plain one, and checks the output is the same.""" head = model.vision_model.head original = head.attention sample = torch.rand(1, 3, IMAGE_SIDE, IMAGE_SIDE) * 2 - 1 with torch.no_grad(): before = model.get_image_features(pixel_values=sample) before = before if isinstance(before, torch.Tensor) else before.pooler_output head.attention = PlainMultiheadAttention(original) after = model.get_image_features(pixel_values=sample) after = after if isinstance(after, torch.Tensor) else after.pooler_output difference = (before - after).abs().max().item() print(f"pooling attention replaced, largest difference {difference:.2e}") assert difference < 1e-4 class ImageEncoder(torch.nn.Module): def __init__(self, model): super().__init__() self.model = model def forward(self, image): features = self.model.get_image_features(pixel_values=image) if not isinstance(features, torch.Tensor): features = features.pooler_output return features / features.norm(dim=-1, keepdim=True) class TextEncoder(torch.nn.Module): def __init__(self, model): super().__init__() self.model = model def forward(self, text): features = self.model.get_text_features(input_ids=text) if not isinstance(features, torch.Tensor): features = features.pooler_output return features / features.norm(dim=-1, keepdim=True) def compress(model): config = cto.OptimizationConfig( global_config=cto.OpLinearQuantizerConfig(mode="linear_symmetric", dtype="int8") ) return cto.linear_quantize_weights(model, config=config) def main(): output = sys.argv[1] model = AutoModel.from_pretrained( MODEL, revision=REVISION, dtype=torch.float32, attn_implementation="eager" ).eval() replace_pooling_attention(model) with torch.no_grad(): image = torch.rand(1, 3, IMAGE_SIDE, IMAGE_SIDE) * 2 - 1 traced_image = torch.jit.trace(ImageEncoder(model), image) text = torch.zeros(1, TEXT_LENGTH, dtype=torch.int64) traced_text = torch.jit.trace(TextEncoder(model), text) image_model = ct.convert( traced_image, inputs=[ ct.ImageType( name="image", shape=(1, 3, IMAGE_SIDE, IMAGE_SIDE), scale=1 / 127.5, bias=[-1.0, -1.0, -1.0], color_layout=ct.colorlayout.RGB, ) ], outputs=[ct.TensorType(name="embedding")], minimum_deployment_target=ct.target.iOS18, compute_precision=ct.precision.FLOAT16, ) image_model.short_description = "SigLIP 2 So400m/16-384 image encoder, normalized embedding" # The image encoder stays at 16 bits: with 8-bit weights, per channel or in blocks of 16, its # embeddings agreed with PyTorch at only 0.79 to 0.88. At 16 bits they agree at 0.9999. image_model.save(f"{output}/siglip2_image.mlpackage") print("image encoder saved") text_model = ct.convert( traced_text, inputs=[ct.TensorType(name="text", shape=(1, TEXT_LENGTH), dtype=np.int32)], outputs=[ct.TensorType(name="embedding")], minimum_deployment_target=ct.target.iOS18, compute_precision=ct.precision.FLOAT16, ) text_model.short_description = "SigLIP 2 So400m/16-384 text encoder, normalized embedding" compress(text_model).save(f"{output}/siglip2_text.mlpackage") print("text encoder saved") if __name__ == "__main__": main()