File size: 5,363 Bytes
a71ea6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
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()