Mask Generation
MLX
Safetensors
moonbox
mobilesam
segment-anything
sam
image-segmentation
jennyxue commited on
Commit
f50dfaf
·
verified ·
1 Parent(s): 992755d

fp16 build of MobileSAM v2

Browse files
Files changed (3) hide show
  1. fp16/config.json +31 -0
  2. fp16/mlx_model.py +465 -0
  3. fp16/model.safetensors +3 -0
fp16/config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "mobile_sam",
3
+ "image_size": 1024,
4
+ "embed_dims": [
5
+ 64,
6
+ 128,
7
+ 160,
8
+ 320
9
+ ],
10
+ "depths": [
11
+ 2,
12
+ 2,
13
+ 6,
14
+ 2
15
+ ],
16
+ "num_heads": [
17
+ 2,
18
+ 4,
19
+ 5,
20
+ 10
21
+ ],
22
+ "window_sizes": [
23
+ 7,
24
+ 7,
25
+ 14,
26
+ 7
27
+ ],
28
+ "prompt_dim": 256,
29
+ "mask_in_chans": 16,
30
+ "precision": "fp16"
31
+ }
fp16/mlx_model.py ADDED
@@ -0,0 +1,465 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """MobileSAM (ChaoningZhang/MobileSAM, Apache-2.0) in MLX: a port of `mobile_sam` (`build_sam_vit_t`: TinyViT-5M
2
+ image encoder + SAM's prompt encoder and mask decoder), the segment-anything half of MobileSAM v2.
3
+
4
+ import mlx_model
5
+ model = mlx_model.load("bf16") # a folder with config.json + model.safetensors
6
+ emb = mlx_model.embed(model, rgb) # rgb HxWx3 uint8 -> image embedding (+ sizes)
7
+ masks, scores, logits = mlx_model.predict(model, emb, points=[[x, y]], labels=[1], box=None, multimask=True)
8
+
9
+ `predict` follows SamPredictor.predict: point / box prompts in pixel coordinates of the original image, masks at
10
+ the original size (logits > 0), the IoU head's scores, and 256x256 low-res logits. Runs on its own next to its
11
+ weights (mlx, numpy, pillow). NHWC; every BatchNorm folded into its conv at conversion.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ from pathlib import Path
18
+
19
+ import mlx.core as mx
20
+ import mlx.nn as nn
21
+ import numpy as np
22
+
23
+ CONFIG = {"model_type": "mobile_sam", "image_size": 1024, "embed_dims": [64, 128, 160, 320], "depths": [2, 2, 6, 2],
24
+ "num_heads": [2, 4, 5, 10], "window_sizes": [7, 7, 14, 7], "prompt_dim": 256, "mask_in_chans": 16}
25
+ PRECISIONS = ["bf16", "fp16", "8bit", "6bit", "4bit"]
26
+ PIXEL_MEAN = np.array([123.675, 116.28, 103.53], np.float32)
27
+ PIXEL_STD = np.array([58.395, 57.12, 57.375], np.float32)
28
+ GROUP = 64
29
+
30
+
31
+ def quantizable(path: str, module) -> bool:
32
+ return isinstance(module, nn.Linear) and module.weight.shape[-1] % GROUP == 0
33
+
34
+
35
+ def resize(x, size):
36
+ """torch F.interpolate(mode="bilinear", align_corners=False), NHWC."""
37
+ b, h, w, c = x.shape
38
+ oh, ow = int(size[0]), int(size[1])
39
+ if (oh, ow) == (h, w):
40
+ return x
41
+
42
+ def axis(n_in, n_out):
43
+ s = np.clip((np.arange(n_out, dtype=np.float64) + 0.5) * (n_in / n_out) - 0.5, 0, None)
44
+ i0 = np.minimum(np.floor(s).astype(np.int32), n_in - 1)
45
+ return mx.array(i0), mx.array(np.minimum(i0 + 1, n_in - 1)), mx.array((s - i0).astype(np.float32))
46
+
47
+ y0, y1, fy = axis(h, oh)
48
+ x0, x1, fx = axis(w, ow)
49
+ fy, fx = fy.astype(x.dtype)[None, :, None, None], fx.astype(x.dtype)[None, None, :, None]
50
+ top, bot = x[:, y0], x[:, y1]
51
+ top = top[:, :, x0] * (1 - fx) + top[:, :, x1] * fx
52
+ bot = bot[:, :, x0] * (1 - fx) + bot[:, :, x1] * fx
53
+ return top * (1 - fy) + bot * fy
54
+
55
+
56
+ class LayerNorm2d(nn.Module):
57
+ """SAM's channel LayerNorm (eps 1e-6), statistics in float32."""
58
+
59
+ def __init__(self, c, eps=1e-6):
60
+ super().__init__()
61
+ self.weight, self.bias, self.eps = mx.ones((c,)), mx.zeros((c,)), eps
62
+
63
+ def __call__(self, x):
64
+ y = x.astype(mx.float32)
65
+ u = y.mean(-1, keepdims=True)
66
+ s = ((y - u) ** 2).mean(-1, keepdims=True)
67
+ return (self.weight * ((y - u) * mx.rsqrt(s + self.eps)).astype(x.dtype) + self.bias)
68
+
69
+
70
+ # ------------------------------------------------------------------------------------------------ TinyViT
71
+
72
+ def conv(cin, cout, k=1, s=1, p=0, g=1):
73
+ return nn.Conv2d(cin, cout, k, stride=s, padding=p, groups=g) # Conv2d_BN, BatchNorm folded
74
+
75
+
76
+ class MBConv(nn.Module):
77
+ def __init__(self, c, ratio=4.0):
78
+ super().__init__()
79
+ h = int(c * ratio)
80
+ self.conv1, self.conv2, self.conv3 = conv(c, h), conv(h, h, 3, 1, 1, h), conv(h, c)
81
+
82
+ def __call__(self, x):
83
+ y = nn.gelu(self.conv1(x))
84
+ y = nn.gelu(self.conv2(y))
85
+ return nn.gelu(self.conv3(y) + x)
86
+
87
+
88
+ class PatchMerging(nn.Module):
89
+ def __init__(self, dim, out):
90
+ super().__init__()
91
+ s = 1 if out in (320, 448, 576) else 2
92
+ self.conv1, self.conv2, self.conv3 = conv(dim, out), conv(out, out, 3, s, 1, out), conv(out, out)
93
+
94
+ def __call__(self, x):
95
+ return self.conv3(nn.gelu(self.conv2(nn.gelu(self.conv1(x)))))
96
+
97
+
98
+ class Attention(nn.Module):
99
+ def __init__(self, dim, key_dim, heads, res):
100
+ super().__init__()
101
+ self.heads, self.key_dim, self.scale = heads, key_dim, key_dim ** -0.5
102
+ self.norm = nn.LayerNorm(dim)
103
+ self.qkv = nn.Linear(dim, 3 * key_dim * heads)
104
+ self.proj = nn.Linear(key_dim * heads, dim)
105
+ pts = [(i, j) for i in range(res) for j in range(res)]
106
+ offs, idx = {}, []
107
+ for p1 in pts:
108
+ for p2 in pts:
109
+ o = (abs(p1[0] - p2[0]), abs(p1[1] - p2[1]))
110
+ offs.setdefault(o, len(offs))
111
+ idx.append(offs[o])
112
+ self.attention_biases = mx.zeros((heads, len(offs)))
113
+ self._idx = mx.array(np.array(idx, np.int32).reshape(len(pts), len(pts)))
114
+
115
+ def __call__(self, x):
116
+ b, n, _ = x.shape
117
+ qkv = self.qkv(self.norm(x)).reshape(b, n, self.heads, 3 * self.key_dim)
118
+ q, k, v = mx.split(qkv, [self.key_dim, 2 * self.key_dim], axis=-1)
119
+ q, k, v = (t.transpose(0, 2, 1, 3) for t in (q, k, v))
120
+ a = (q @ k.transpose(0, 1, 3, 2)) * self.scale + self.attention_biases[:, self._idx].astype(q.dtype)
121
+ a = mx.softmax(a, axis=-1, precise=True)
122
+ return self.proj((a @ v).transpose(0, 2, 1, 3).reshape(b, n, -1))
123
+
124
+
125
+ class Mlp(nn.Module):
126
+ def __init__(self, dim, hidden):
127
+ super().__init__()
128
+ self.norm, self.fc1, self.fc2 = nn.LayerNorm(dim), nn.Linear(dim, hidden), nn.Linear(hidden, dim)
129
+
130
+ def __call__(self, x):
131
+ return self.fc2(nn.gelu(self.fc1(self.norm(x))))
132
+
133
+
134
+ class TinyViTBlock(nn.Module):
135
+ def __init__(self, dim, heads, ws):
136
+ super().__init__()
137
+ self.ws = ws
138
+ self.attn = Attention(dim, dim // heads, heads, ws)
139
+ self.mlp = Mlp(dim, dim * 4)
140
+ self.local_conv = conv(dim, dim, 3, 1, 1, dim)
141
+
142
+ def __call__(self, x):
143
+ """x: (B, H, W, C)."""
144
+ b, h, w, c = x.shape
145
+ ws = self.ws
146
+ if h == ws and w == ws:
147
+ y = self.attn(x.reshape(b, h * w, c)).reshape(b, h, w, c)
148
+ else:
149
+ pb, pr = (ws - h % ws) % ws, (ws - w % ws) % ws
150
+ y = mx.pad(x, [(0, 0), (0, pb), (0, pr), (0, 0)]) if pb or pr else x
151
+ ph, pw = h + pb, w + pr
152
+ y = y.reshape(b, ph // ws, ws, pw // ws, ws, c).transpose(0, 1, 3, 2, 4, 5).reshape(-1, ws * ws, c)
153
+ y = self.attn(y)
154
+ y = y.reshape(b, ph // ws, pw // ws, ws, ws, c).transpose(0, 1, 3, 2, 4, 5).reshape(b, ph, pw, c)
155
+ y = y[:, :h, :w]
156
+ x = self.local_conv(x + y)
157
+ return x + self.mlp(x.reshape(b, h * w, c)).reshape(b, h, w, c)
158
+
159
+
160
+ class Layer(nn.Module):
161
+ def __init__(self, i, dims, depth, heads, ws):
162
+ super().__init__()
163
+ d = dims[i]
164
+ self.blocks = [MBConv(d) for _ in range(depth)] if i == 0 else [TinyViTBlock(d, heads, ws) for _ in range(depth)]
165
+ if i < len(dims) - 1:
166
+ self.downsample = PatchMerging(d, dims[i + 1])
167
+
168
+ def __call__(self, x):
169
+ for b in self.blocks:
170
+ x = b(x)
171
+ return self.downsample(x) if "downsample" in self else x
172
+
173
+
174
+ class TinyViT(nn.Module):
175
+ def __init__(self, c):
176
+ super().__init__()
177
+ d = c["embed_dims"]
178
+ self.patch_embed = [conv(3, d[0] // 2, 3, 2, 1), conv(d[0] // 2, d[0], 3, 2, 1)]
179
+ self.layers = [Layer(i, d, c["depths"][i], c["num_heads"][i], c["window_sizes"][i]) for i in range(4)]
180
+ self.neck_conv1 = nn.Conv2d(d[-1], 256, 1, bias=False)
181
+ self.neck_norm1 = LayerNorm2d(256)
182
+ self.neck_conv2 = nn.Conv2d(256, 256, 3, padding=1, bias=False)
183
+ self.neck_norm2 = LayerNorm2d(256)
184
+
185
+ def __call__(self, x):
186
+ x = self.patch_embed[1](nn.gelu(self.patch_embed[0](x)))
187
+ for layer in self.layers:
188
+ x = layer(x)
189
+ return self.neck_norm2(self.neck_conv2(self.neck_norm1(self.neck_conv1(x))))
190
+
191
+
192
+ # ------------------------------------------------------------------------------------------------ SAM decoder
193
+
194
+ class SAMAttention(nn.Module):
195
+ def __init__(self, dim, heads, down=1):
196
+ super().__init__()
197
+ inner = dim // down
198
+ self.heads = heads
199
+ self.q_proj, self.k_proj, self.v_proj = nn.Linear(dim, inner), nn.Linear(dim, inner), nn.Linear(dim, inner)
200
+ self.out_proj = nn.Linear(inner, dim)
201
+
202
+ def __call__(self, q, k, v):
203
+ q, k, v = self.q_proj(q), self.k_proj(k), self.v_proj(v)
204
+ b, nq, c = q.shape
205
+ sp = lambda t: t.reshape(b, t.shape[1], self.heads, c // self.heads).transpose(0, 2, 1, 3)
206
+ q, k, v = sp(q), sp(k), sp(v)
207
+ a = mx.softmax((q @ k.transpose(0, 1, 3, 2)) * (c // self.heads) ** -0.5, axis=-1, precise=True)
208
+ return self.out_proj((a @ v).transpose(0, 2, 1, 3).reshape(b, nq, c))
209
+
210
+
211
+ class MLPBlock(nn.Module):
212
+ def __init__(self, dim, hidden):
213
+ super().__init__()
214
+ self.lin1, self.lin2 = nn.Linear(dim, hidden), nn.Linear(hidden, dim)
215
+
216
+ def __call__(self, x):
217
+ return self.lin2(nn.relu(self.lin1(x)))
218
+
219
+
220
+ class TwoWayBlock(nn.Module):
221
+ def __init__(self, dim, heads, mlp_dim, skip_pe):
222
+ super().__init__()
223
+ self.skip_pe = skip_pe
224
+ self.self_attn = SAMAttention(dim, heads)
225
+ self.cross_attn_token_to_image = SAMAttention(dim, heads, 2)
226
+ self.cross_attn_image_to_token = SAMAttention(dim, heads, 2)
227
+ self.mlp = MLPBlock(dim, mlp_dim)
228
+ self.norm1, self.norm2, self.norm3, self.norm4 = (nn.LayerNorm(dim) for _ in range(4))
229
+
230
+ def __call__(self, q, k, qpe, kpe):
231
+ if self.skip_pe:
232
+ q = self.self_attn(q, q, q)
233
+ else:
234
+ t = q + qpe
235
+ q = q + self.self_attn(t, t, q)
236
+ q = self.norm1(q)
237
+ q = self.norm2(q + self.cross_attn_token_to_image(q + qpe, k + kpe, k))
238
+ q = self.norm3(q + self.mlp(q))
239
+ k = self.norm4(k + self.cross_attn_image_to_token(k + kpe, q + qpe, q))
240
+ return q, k
241
+
242
+
243
+ class TwoWayTransformer(nn.Module):
244
+ def __init__(self, dim=256, heads=8, mlp_dim=2048, depth=2):
245
+ super().__init__()
246
+ self.layers = [TwoWayBlock(dim, heads, mlp_dim, i == 0) for i in range(depth)]
247
+ self.final_attn_token_to_image = SAMAttention(dim, heads, 2)
248
+ self.norm_final_attn = nn.LayerNorm(dim)
249
+
250
+ def __call__(self, img, pe, tokens):
251
+ b, h, w, c = img.shape
252
+ k, kpe, q = img.reshape(b, h * w, c), pe.reshape(b, h * w, c), tokens
253
+ for layer in self.layers:
254
+ q, k = layer(q, k, tokens, kpe)
255
+ q = self.norm_final_attn(q + self.final_attn_token_to_image(q + tokens, k + kpe, k))
256
+ return q, k
257
+
258
+
259
+ class MLP(nn.Module):
260
+ def __init__(self, din, dh, dout, n):
261
+ super().__init__()
262
+ dims = [din] + [dh] * (n - 1)
263
+ self.layers = [nn.Linear(a, b) for a, b in zip(dims, [dh] * (n - 1) + [dout])]
264
+
265
+ def __call__(self, x):
266
+ for i, l in enumerate(self.layers):
267
+ x = nn.relu(l(x)) if i < len(self.layers) - 1 else l(x)
268
+ return x
269
+
270
+
271
+ class PromptEncoder(nn.Module):
272
+ def __init__(self, dim, emb_hw, img_size, mask_in):
273
+ super().__init__()
274
+ self.emb_hw, self.img_size = emb_hw, img_size
275
+ self.positional_encoding_gaussian_matrix = mx.zeros((2, dim // 2))
276
+ self.point_embeddings = [mx.zeros((1, dim)) for _ in range(4)]
277
+ self.not_a_point_embed = mx.zeros((1, dim))
278
+ self.no_mask_embed = mx.zeros((1, dim))
279
+ self.mask_conv1 = nn.Conv2d(1, mask_in // 4, 2, stride=2)
280
+ self.mask_norm1 = LayerNorm2d(mask_in // 4)
281
+ self.mask_conv2 = nn.Conv2d(mask_in // 4, mask_in, 2, stride=2)
282
+ self.mask_norm2 = LayerNorm2d(mask_in)
283
+ self.mask_conv3 = nn.Conv2d(mask_in, dim, 1)
284
+
285
+ def pe(self, coords): # coords in [0, 1], float32
286
+ c = (2 * coords - 1) @ self.positional_encoding_gaussian_matrix.astype(mx.float32)
287
+ c = 2 * np.pi * c
288
+ return mx.concatenate([mx.sin(c), mx.cos(c)], -1)
289
+
290
+ def dense_pe(self):
291
+ h, w = self.emb_hw
292
+ ys = (mx.arange(h, dtype=mx.float32) + 0.5) / h
293
+ xs = (mx.arange(w, dtype=mx.float32) + 0.5) / w
294
+ grid = mx.stack([mx.broadcast_to(xs[None, :], (h, w)), mx.broadcast_to(ys[:, None], (h, w))], -1)
295
+ return self.pe(grid)[None] # (1, h, w, C)
296
+
297
+ def __call__(self, points, labels, box, mask):
298
+ dt = self.no_mask_embed.dtype
299
+ sparse = []
300
+ s = mx.array([self.img_size, self.img_size], dtype=mx.float32)
301
+ if points is not None:
302
+ pts, lab = points + 0.5, labels
303
+ if box is None:
304
+ pts = mx.concatenate([pts, mx.zeros((pts.shape[0], 1, 2))], 1)
305
+ lab = mx.concatenate([lab, -mx.ones((lab.shape[0], 1))], 1)
306
+ e = self.pe(pts / s)
307
+ l = lab[..., None]
308
+ e = mx.where(l == -1, 0.0, e)
309
+ e = e + (l == -1) * self.not_a_point_embed.astype(mx.float32)
310
+ e = e + (l == 0) * self.point_embeddings[0].astype(mx.float32)
311
+ e = e + (l == 1) * self.point_embeddings[1].astype(mx.float32)
312
+ sparse.append(e)
313
+ if box is not None:
314
+ e = self.pe((box + 0.5).reshape(-1, 2, 2) / s)
315
+ e = e + mx.concatenate([self.point_embeddings[2], self.point_embeddings[3]], 0).astype(mx.float32)[None]
316
+ sparse.append(e)
317
+ sparse = mx.concatenate(sparse, 1).astype(dt)
318
+ if mask is not None:
319
+ m = nn.gelu(self.mask_norm1(self.mask_conv1(mask)))
320
+ dense = self.mask_conv3(nn.gelu(self.mask_norm2(self.mask_conv2(m))))
321
+ else:
322
+ h, w = self.emb_hw
323
+ dense = mx.broadcast_to(self.no_mask_embed.reshape(1, 1, 1, -1), (sparse.shape[0], h, w, self.no_mask_embed.shape[-1]))
324
+ return sparse, dense
325
+
326
+
327
+ class MaskDecoder(nn.Module):
328
+ def __init__(self, dim=256, n_mask=3):
329
+ super().__init__()
330
+ self.n = n_mask + 1
331
+ self.transformer = TwoWayTransformer(dim)
332
+ self.iou_token = mx.zeros((1, dim))
333
+ self.mask_tokens = mx.zeros((self.n, dim))
334
+ self.up1 = nn.ConvTranspose2d(dim, dim // 4, 2, stride=2)
335
+ self.up_norm = LayerNorm2d(dim // 4)
336
+ self.up2 = nn.ConvTranspose2d(dim // 4, dim // 8, 2, stride=2)
337
+ self.output_hypernetworks_mlps = [MLP(dim, dim, dim // 8, 3) for _ in range(self.n)]
338
+ self.iou_prediction_head = MLP(dim, 256, self.n, 3)
339
+
340
+ def __call__(self, img, pe, sparse, dense):
341
+ b = sparse.shape[0]
342
+ out = mx.concatenate([self.iou_token, self.mask_tokens], 0)
343
+ tokens = mx.concatenate([mx.broadcast_to(out[None], (b,) + out.shape), sparse], 1)
344
+ src = mx.broadcast_to(img, (b,) + img.shape[1:]) + dense
345
+ pos = mx.broadcast_to(pe, (b,) + pe.shape[1:]).astype(src.dtype)
346
+ hs, src = self.transformer(src, pos, tokens)
347
+ _, h, w, c = img.shape
348
+ up = nn.gelu(self.up2(nn.gelu(self.up_norm(self.up1(src.reshape(b, h, w, c))))))
349
+ hyper = mx.stack([self.output_hypernetworks_mlps[i](hs[:, 1 + i]) for i in range(self.n)], 1)
350
+ bb, uh, uw, uc = up.shape
351
+ masks = (hyper @ up.reshape(b, uh * uw, uc).transpose(0, 2, 1)).reshape(b, self.n, uh, uw)
352
+ return masks, self.iou_prediction_head(hs[:, 0])
353
+
354
+
355
+ class Model(nn.Module):
356
+ def __init__(self, config: dict = CONFIG):
357
+ super().__init__()
358
+ self.size = config["image_size"]
359
+ e = self.size // 16
360
+ self.image_encoder = TinyViT(config)
361
+ self.prompt_encoder = PromptEncoder(config["prompt_dim"], (e, e), self.size, config["mask_in_chans"])
362
+ self.mask_decoder = MaskDecoder(config["prompt_dim"])
363
+
364
+
365
+ # ------------------------------------------------------------------------------------------------ predictor
366
+
367
+ def load(folder) -> Model:
368
+ folder = Path(folder)
369
+ config = json.loads((folder / "config.json").read_text())
370
+ model = Model(config)
371
+ q = config.get("quantization")
372
+ if q:
373
+ nn.quantize(model, group_size=q["group_size"], bits=q["bits"], class_predicate=quantizable)
374
+ model.load_weights(str(folder / "model.safetensors"), strict=True)
375
+ mx.eval(model.parameters())
376
+ return model
377
+
378
+
379
+ def dtype(model):
380
+ return model.mask_decoder.iou_token.dtype
381
+
382
+
383
+ def embed(model: Model, rgb: np.ndarray) -> dict:
384
+ """SamPredictor.set_image: longest side to 1024 (PIL bilinear), normalize, pad bottom-right, encode."""
385
+ from PIL import Image
386
+ h, w = rgb.shape[:2]
387
+ s = model.size / max(h, w)
388
+ nh, nw = int(h * s + 0.5), int(w * s + 0.5)
389
+ x = np.asarray(Image.fromarray(rgb).resize((nw, nh), Image.BILINEAR), np.float32)
390
+ x = (x - PIXEL_MEAN) / PIXEL_STD
391
+ x = np.pad(x, ((0, model.size - nh), (0, model.size - nw), (0, 0)))
392
+ feats = model.image_encoder(mx.array(x[None]).astype(dtype(model)))
393
+ mx.eval(feats)
394
+ return {"features": feats, "original_size": (h, w), "input_size": (nh, nw)}
395
+
396
+
397
+ def predict(model: Model, emb: dict, points=None, labels=None, box=None, multimask=True):
398
+ """SamPredictor.predict: prompts in original-image pixels -> (masks bool (N, H, W), scores (N,), low-res
399
+ logits (N, 256, 256))."""
400
+ h, w = emb["original_size"]
401
+ nh, nw = emb["input_size"]
402
+ sx, sy = nw / w, nh / h
403
+ pts = lab = bx = None
404
+ if points is not None:
405
+ pts = mx.array(np.asarray(points, np.float32)[None] * np.array([sx, sy], np.float32))
406
+ lab = mx.array(np.asarray(labels, np.float32)[None])
407
+ if box is not None:
408
+ bx = mx.array(np.asarray(box, np.float32).reshape(1, 4) * np.array([sx, sy, sx, sy], np.float32))
409
+ sparse, dense = model.prompt_encoder(pts, lab, bx, None)
410
+ pe = model.prompt_encoder.dense_pe()
411
+ logits, iou = model.mask_decoder(emb["features"], pe, sparse, dense.astype(sparse.dtype))
412
+ sl = slice(1, None) if multimask else slice(0, 1)
413
+ logits, iou = logits[:, sl].astype(mx.float32), iou[:, sl].astype(mx.float32)
414
+ low = logits
415
+ m = resize(logits.transpose(0, 2, 3, 1), (model.size, model.size))[:, :nh, :nw]
416
+ m = resize(m, (h, w)).transpose(0, 3, 1, 2)
417
+ return np.array(m[0] > 0), np.array(iou[0]), np.array(low[0]), np.array(m[0])
418
+
419
+
420
+ # ------------------------------------------------------------------------------------------------ conversion
421
+
422
+ def _fold(sd, pre):
423
+ """Conv2d_BN (`pre`.c + `pre`.bn) -> one conv's (weight, bias) in MLX layout."""
424
+ w = sd[pre + ".c.weight"].astype(np.float64)
425
+ g = sd[pre + ".bn.weight"] / np.sqrt(sd[pre + ".bn.running_var"].astype(np.float64) + 1e-5)
426
+ b = sd[pre + ".bn.bias"] - sd[pre + ".bn.running_mean"] * g
427
+ return (w * g[:, None, None, None]).astype(np.float32).transpose(0, 2, 3, 1), b.astype(np.float32)
428
+
429
+
430
+ def convert(source: Path) -> dict:
431
+ """runs/source/weights/mobile_sam.pt (a plain state dict) -> MLX names: BatchNorms folded, Sequentials renamed,
432
+ the classification head (norm_head / head) dropped."""
433
+ import torch
434
+ sd = {k: v.float().numpy() for k, v in torch.load(Path(source) / "weights" / "mobile_sam.pt", map_location="cpu",
435
+ weights_only=True).items() if v.is_floating_point()}
436
+ out = {}
437
+ folded = sorted({k[:-len(".c.weight")] for k in sd if k.endswith(".c.weight")})
438
+ for pre in folded:
439
+ dst = pre.replace("patch_embed.seq.0", "patch_embed.0").replace("patch_embed.seq.2", "patch_embed.1")
440
+ out[dst + ".weight"], out[dst + ".bias"] = _fold(sd, pre)
441
+ ren = {"image_encoder.neck.0.": "image_encoder.neck_conv1.", "image_encoder.neck.1.": "image_encoder.neck_norm1.",
442
+ "image_encoder.neck.2.": "image_encoder.neck_conv2.", "image_encoder.neck.3.": "image_encoder.neck_norm2.",
443
+ "prompt_encoder.pe_layer.": "prompt_encoder.",
444
+ "prompt_encoder.mask_downscaling.0.": "prompt_encoder.mask_conv1.",
445
+ "prompt_encoder.mask_downscaling.1.": "prompt_encoder.mask_norm1.",
446
+ "prompt_encoder.mask_downscaling.3.": "prompt_encoder.mask_conv2.",
447
+ "prompt_encoder.mask_downscaling.4.": "prompt_encoder.mask_norm2.",
448
+ "prompt_encoder.mask_downscaling.6.": "prompt_encoder.mask_conv3.",
449
+ "mask_decoder.output_upscaling.0.": "mask_decoder.up1.",
450
+ "mask_decoder.output_upscaling.1.": "mask_decoder.up_norm.",
451
+ "mask_decoder.output_upscaling.3.": "mask_decoder.up2."}
452
+ for k, v in sd.items():
453
+ if any(k.startswith(p + ".") for p in folded) or ".head." in k or ".norm_head." in k:
454
+ continue
455
+ n = k
456
+ for a, b in ren.items():
457
+ if n.startswith(a):
458
+ n = b + n[len(a):]
459
+ if n.endswith(".weight") and (n.startswith("prompt_encoder.point_embeddings") or
460
+ n.split(".")[-2] in ("not_a_point_embed", "no_mask_embed", "iou_token", "mask_tokens")):
461
+ n = n[:-len(".weight")]
462
+ if v.ndim == 4:
463
+ v = v.transpose(1, 2, 3, 0) if ".up1." in n or ".up2." in n else v.transpose(0, 2, 3, 1)
464
+ out[n] = v
465
+ return out
fp16/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e8a52d0c013fa72c09abe8569e2de8868eb57294fd07808928e59f6b55ce1553
3
+ size 19646073