mlboydaisuke commited on
Commit
80da4cf
·
verified ·
1 Parent(s): 4623162

Upload convert_siglip2.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. convert_siglip2.py +254 -0
convert_siglip2.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Convert timm SigLIP2 (ViT-B/16, 224) image tower to a GPU-clean, GPU-correct
2
+ LiteRT .tflite for the ML Drift GPU delegate.
3
+
4
+ SigLIP2 (Google 2025, Apache-2.0) is a SOTA CLIP-style image tower. timm exposes
5
+ it as `vit_base_patch16_siglip_224.v2_webli` (93M params, conv patch-embed, NO
6
+ rope, NO cls token, attention-pool head). The text tower for zero-shot is
7
+ open_clip `ViT-B-16-SigLIP2` (same 768-d space, prompt "a photo of a {label}").
8
+
9
+ Re-authoring (all verbatim, weights copied, corr ~1.0 vs PyTorch) -- the same set
10
+ proven on PE-Core, minus the rope step (SigLIP2 has no rope):
11
+ * Attention (x12): fused qkv -> 5D head-split (the GPU "C12" wall). Decompose to
12
+ separate q/k/v, hand the 4D q/k/v to scaled_dot_product_attention (its lowering
13
+ keeps the batch-matmul 3D with a materialized transpose -> GPU-resident).
14
+ * AttentionPoolLatent: single constant-latent query -> a batch-matmul there is
15
+ const@non-const (rejected / mis-computed). Express as broadcast-multiply +
16
+ reduce-sum (exact for latent_len=1, GPU-correct).
17
+ * LayerNorm -> overflow-safe LayerNorm: the delegate reduces the variance in fp16
18
+ even for an fp32 graph; deep-ViT massive activations overflow fp16 (sum > 65504)
19
+ -> wrong norm that compounds with depth while still reporting full residency.
20
+ Scale-before-square keeps the sum in range.
21
+
22
+ I/O: input [1,3,224,224] NCHW float32 normalized to [-1,1] ((x/255-0.5)/0.5),
23
+ output [1,768] L2-normalized image embedding.
24
+
25
+ ~/clipconv/bin/python scripts/convert_siglip2.py
26
+ """
27
+ import os
28
+ import sys
29
+ import types
30
+ import collections
31
+
32
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
33
+ import _stub # noqa: F401 (macOS scipy/_propack guard, import FIRST)
34
+
35
+ import numpy as np
36
+ import torch
37
+ import torch.nn as nn
38
+ import torch.nn.functional as F
39
+ import timm
40
+
41
+ MODEL = "vit_base_patch16_siglip_224.v2_webli"
42
+ IMG = 224
43
+ OUT_DIR = os.path.expanduser("~/code/litertlm-convert/out/siglip2")
44
+ os.makedirs(OUT_DIR, exist_ok=True)
45
+ FP32 = os.path.join(OUT_DIR, "siglip2_base_224.tflite")
46
+ FP16 = os.path.join(OUT_DIR, "siglip2_base_224_fp16.tflite")
47
+
48
+ BANNED = {"GATHER_ND", "GATHER", "TOPK_V2", "FLEX_ERF", "ERF", "BROADCAST_TO"}
49
+
50
+
51
+ # -------------------------------------------------- overflow-safe LayerNorm
52
+ class SafeLayerNorm(nn.Module):
53
+ """LayerNorm whose variance reduction can't overflow fp16 (see module docstring)."""
54
+ SC = 0.03125 # 1/32
55
+
56
+ def __init__(self, ln: nn.LayerNorm):
57
+ super().__init__()
58
+ self.weight, self.bias, self.eps = ln.weight, ln.bias, ln.eps
59
+
60
+ def forward(self, x):
61
+ xc = x - x.mean(-1, keepdim=True)
62
+ xs = xc * self.SC
63
+ var = (xs * xs).mean(-1, keepdim=True) / (self.SC * self.SC)
64
+ return xc * torch.rsqrt(var + self.eps) * self.weight + self.bias
65
+
66
+
67
+ def patch_layernorm(module):
68
+ for name, child in module.named_children():
69
+ if isinstance(child, nn.LayerNorm):
70
+ setattr(module, name, SafeLayerNorm(child))
71
+ else:
72
+ patch_layernorm(child)
73
+
74
+
75
+ # ------------------------------------------ block Attention -> 4D (no rope)
76
+ def _attn_forward(self, x, *args, **kwargs):
77
+ B, N, C = x.shape
78
+ H, d = self.num_heads, self.head_dim
79
+ q = self.q_proj_d(x).reshape(B, N, H, d).transpose(1, 2)
80
+ k = self.k_proj_d(x).reshape(B, N, H, d).transpose(1, 2)
81
+ v = self.v_proj_d(x).reshape(B, N, H, d).transpose(1, 2)
82
+ q, k = self.q_norm(q), self.k_norm(k) # Identity for SigLIP2
83
+ out = F.scaled_dot_product_attention(q, k, v)
84
+ out = out.transpose(1, 2).reshape(B, N, H * d)
85
+ out = self.norm(out) # Identity (scale_norm off)
86
+ return self.proj(out)
87
+
88
+
89
+ def reauthor_attn(attn):
90
+ C = attn.qkv.in_features
91
+ w = attn.qkv.weight.data
92
+ b = attn.qkv.bias.data if attn.qkv.bias is not None else None
93
+ has_b = b is not None
94
+ q_proj = nn.Linear(C, C, bias=has_b)
95
+ k_proj = nn.Linear(C, C, bias=has_b)
96
+ v_proj = nn.Linear(C, C, bias=has_b)
97
+ with torch.no_grad():
98
+ q_proj.weight.copy_(w[:C])
99
+ k_proj.weight.copy_(w[C:2 * C])
100
+ v_proj.weight.copy_(w[2 * C:])
101
+ if has_b:
102
+ q_proj.bias.copy_(b[:C])
103
+ k_proj.bias.copy_(b[C:2 * C])
104
+ v_proj.bias.copy_(b[2 * C:])
105
+ attn.q_proj_d, attn.k_proj_d, attn.v_proj_d = q_proj, k_proj, v_proj
106
+ attn.forward = types.MethodType(_attn_forward, attn)
107
+
108
+
109
+ # ------------------------------------------ AttentionPoolLatent -> broadcast-reduce
110
+ def _attn_pool_forward(self, x, attn_mask=None):
111
+ B, N, C = x.shape
112
+ H, d, L = self.num_heads, self.head_dim, self.latent_len
113
+ k = self.k_norm(self.k_proj_d(x).reshape(B, N, H, d).transpose(1, 2)) # [B,H,N,d]
114
+ v = self.v_proj_d(x).reshape(B, N, H, d).transpose(1, 2) # [B,H,N,d]
115
+ qc = self.q_const # [H, L, d] constant, q_norm'd + scaled
116
+ scores = (qc.unsqueeze(0) * k).sum(dim=-1) # [B, H, N]
117
+ attn = scores.softmax(dim=-1).unsqueeze(-1) # [B, H, N, 1]
118
+ out = (attn * v).sum(dim=2).reshape(B, L, C) # [B, L, C]
119
+ out = self.proj(out)
120
+ if self.mlp is not None:
121
+ out = out + self.mlp(self.norm(out))
122
+ if self.pool == "token":
123
+ out = out[:, 0]
124
+ elif self.pool == "avg":
125
+ out = out.mean(1)
126
+ return out
127
+
128
+
129
+ def reauthor_attn_pool(ap):
130
+ assert ap.pos_embed is None, "attn_pool pos_embed not handled"
131
+ C = ap.kv.in_features
132
+ inner = ap.num_heads * ap.head_dim
133
+ has_b = ap.kv.bias is not None
134
+ k_proj = nn.Linear(C, inner, bias=has_b)
135
+ v_proj = nn.Linear(C, inner, bias=has_b)
136
+ with torch.no_grad():
137
+ k_proj.weight.copy_(ap.kv.weight.data[:inner])
138
+ v_proj.weight.copy_(ap.kv.weight.data[inner:])
139
+ if has_b:
140
+ k_proj.bias.copy_(ap.kv.bias.data[:inner])
141
+ v_proj.bias.copy_(ap.kv.bias.data[inner:])
142
+ H, d, L = ap.num_heads, ap.head_dim, ap.latent_len
143
+ ql = ap.q(ap.latent.expand(1, -1, -1)).reshape(1, L, H, d).transpose(1, 2)
144
+ ql = ap.q_norm(ql) * ap.scale
145
+ ap.k_proj_d, ap.v_proj_d = k_proj, v_proj
146
+ ap.register_buffer("q_const", ql.reshape(H, L, d).detach())
147
+ ap.forward = types.MethodType(_attn_pool_forward, ap)
148
+
149
+
150
+ # ------------------------------------------------------------------- wrapper
151
+ class SigLIP2ImageEncoder(nn.Module):
152
+ def __init__(self, m):
153
+ super().__init__()
154
+ self.m = m
155
+
156
+ def forward(self, pixel):
157
+ m = self.m
158
+ x = m.patch_embed(pixel)
159
+ if x.dim() == 4:
160
+ x = x.flatten(1, 2)
161
+ if m.pos_embed is not None:
162
+ x = x + m.pos_embed # SigLIP2 has no cls token
163
+ x = m.norm_pre(x)
164
+ for blk in m.blocks:
165
+ x = blk(x)
166
+ x = m.norm(x)
167
+ x = m.attn_pool(x) # -> [B, 768]
168
+ return F.normalize(x, dim=-1)
169
+
170
+
171
+ def op_hist(path):
172
+ from ai_edge_litert.interpreter import Interpreter
173
+ it = Interpreter(model_path=path)
174
+ it.allocate_tensors()
175
+ hist = collections.Counter(d["op_name"] for d in it._get_ops_details())
176
+ over4d = sum(1 for d in it.get_tensor_details() if len(d.get("shape", [])) > 4)
177
+ return hist, over4d, it
178
+
179
+
180
+ def tflite_run(it, x_nchw):
181
+ inp = it.get_input_details()[0]
182
+ shp = list(inp["shape"])
183
+ x = x_nchw if shp[1] == 3 else np.transpose(x_nchw, (0, 2, 3, 1)).copy()
184
+ it.set_tensor(inp["index"], x.astype(inp["dtype"]))
185
+ it.invoke()
186
+ return it.get_tensor(it.get_output_details()[0]["index"]).astype("float64").reshape(-1)
187
+
188
+
189
+ def main():
190
+ torch.manual_seed(0)
191
+ print(f"loading {MODEL} (pretrained, apache-2.0) ...")
192
+ m = timm.create_model(MODEL, pretrained=True, num_classes=0).eval()
193
+
194
+ x = torch.randn(1, 3, IMG, IMG)
195
+ with torch.no_grad():
196
+ ref = F.normalize(m(x), dim=-1).numpy().flatten() # original trunk embedding
197
+
198
+ for blk in m.blocks:
199
+ reauthor_attn(blk.attn)
200
+ reauthor_attn_pool(m.attn_pool)
201
+ patch_layernorm(m)
202
+ enc = SigLIP2ImageEncoder(m).eval()
203
+
204
+ with torch.no_grad():
205
+ got = enc(x).numpy().flatten()
206
+ corr = float(np.corrcoef(ref, got)[0, 1])
207
+ print(f"EAGER parity (orig vs re-authored): corr {corr:.8f} max|diff| {np.abs(ref-got).max():.3e}")
208
+ assert corr > 0.9999, "re-authoring changed the math -- fix before convert"
209
+
210
+ print("converting (litert_torch) ...")
211
+ import litert_torch
212
+ litert_torch.convert(enc, (x,)).export(FP32)
213
+
214
+ hist, over4d, it = op_hist(FP32)
215
+ bad = {k: v for k, v in hist.items() if k in BANNED}
216
+ print(f"FP32 ops: {dict(sorted(hist.items(), key=lambda kv: -kv[1]))}")
217
+ print(f"banned: {bad or 'NONE'} | >4D tensors: {over4d}")
218
+ o = tflite_run(it, x.numpy())
219
+ print(f"PARITY tflite(fp32) vs torch: corr {np.corrcoef(ref, o)[0,1]:.6f}")
220
+ assert not bad and over4d == 0, "GPU blockers remain -- inspect op histogram"
221
+
222
+ print("quantizing fp16 (FLOAT_CASTING) ...")
223
+ from ai_edge_quantizer import quantizer, recipe_manager
224
+ from ai_edge_quantizer.recipe import AlgorithmName, qtyping
225
+ rm = recipe_manager.RecipeManager()
226
+ rm.add_quantization_config(
227
+ regex=".*",
228
+ operation_name=qtyping.TFLOperationName.ALL_SUPPORTED,
229
+ op_config=qtyping.OpQuantizationConfig(
230
+ weight_tensor_config=qtyping.TensorQuantizationConfig(
231
+ num_bits=16, dtype=qtyping.TensorDataType.FLOAT),
232
+ compute_precision=qtyping.ComputePrecision.FLOAT,
233
+ ),
234
+ algorithm_key=AlgorithmName.FLOAT_CASTING,
235
+ )
236
+ if os.path.exists(FP16):
237
+ os.remove(FP16)
238
+ qt = quantizer.Quantizer(float_model=FP32)
239
+ qt.load_quantization_recipe(rm.get_quantization_recipe())
240
+ qt.quantize().export_model(FP16)
241
+
242
+ s32, s16 = os.path.getsize(FP32) / 1e6, os.path.getsize(FP16) / 1e6
243
+ print(f"SIZE fp32 {s32:.1f} MB -> fp16 {s16:.1f} MB ({s16/s32*100:.0f}%)")
244
+ h16, o16d, it16 = op_hist(FP16)
245
+ bad16 = {k: v for k, v in h16.items() if k in BANNED}
246
+ print(f"FP16 banned: {bad16 or 'NONE'} | >4D: {o16d}")
247
+ o16 = tflite_run(it16, x.numpy())
248
+ print(f"PARITY tflite(fp16) vs torch: corr {np.corrcoef(ref, o16)[0,1]:.6f} "
249
+ f"fp16-vs-fp32 corr {np.corrcoef(o, o16)[0,1]:.6f}")
250
+ print("\nDONE:", FP16)
251
+
252
+
253
+ if __name__ == "__main__":
254
+ main()