Mask Generation
MLX
Safetensors
moonbox
efficientvit
efficientvit-sam
segment-anything
image-segmentation
Instructions to use moonbox-ai/efficientvit-MLX with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use moonbox-ai/efficientvit-MLX with MLX:
# Download the model from the Hub pip install huggingface_hub[hf_xet] hf download moonbox-ai/efficientvit-MLX --local-dir efficientvit-MLX
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Atomic Chat
fp16 build of EfficientViT-SAM
Browse files- fp16/config.json +26 -0
- fp16/mlx_model.py +572 -0
- fp16/model.safetensors +3 -0
fp16/config.json
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_type": "efficientvit_sam",
|
| 3 |
+
"variant": "l2",
|
| 4 |
+
"image_size": 1024,
|
| 5 |
+
"encoder_size": 512,
|
| 6 |
+
"width_list": [
|
| 7 |
+
32,
|
| 8 |
+
64,
|
| 9 |
+
128,
|
| 10 |
+
256,
|
| 11 |
+
512
|
| 12 |
+
],
|
| 13 |
+
"depth_list": [
|
| 14 |
+
1,
|
| 15 |
+
2,
|
| 16 |
+
2,
|
| 17 |
+
8,
|
| 18 |
+
8
|
| 19 |
+
],
|
| 20 |
+
"qkv_dim": 32,
|
| 21 |
+
"neck_depth": 12,
|
| 22 |
+
"neck_expand": 1,
|
| 23 |
+
"prompt_dim": 256,
|
| 24 |
+
"mask_in_chans": 16,
|
| 25 |
+
"precision": "fp16"
|
| 26 |
+
}
|
fp16/mlx_model.py
ADDED
|
@@ -0,0 +1,572 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""EfficientViT-SAM (mit-han-lab/efficientvit, Apache-2.0) in MLX: a port of `efficientvit_sam_l2` (EfficientViT-L2
|
| 2 |
+
image encoder at 512 px with its SAM neck, then SAM's prompt encoder and mask decoder) and EfficientViTSamPredictor.
|
| 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, low_res, logits = mlx_model.predict(model, emb, points=[[x, y]], labels=[1], multimask=True)
|
| 8 |
+
|
| 9 |
+
Runs on its own next to its weights (mlx, numpy, pillow). NHWC; BatchNorms folded into their convs at conversion;
|
| 10 |
+
1x1 convolutions are linear layers (so 8bit / 6bit / 4bit quantize them); LiteMLA's ReLU linear attention and the
|
| 11 |
+
neck's bicubic upsampling run in float32 as in the original.
|
| 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": "efficientvit_sam", "variant": "l2", "image_size": 1024, "encoder_size": 512,
|
| 24 |
+
"width_list": [32, 64, 128, 256, 512], "depth_list": [1, 2, 2, 8, 8], "qkv_dim": 32,
|
| 25 |
+
"neck_depth": 12, "neck_expand": 1, "prompt_dim": 256, "mask_in_chans": 16}
|
| 26 |
+
PRECISIONS = ["bf16", "fp16"] # 8bit / 6bit / 4bit don't work: model.toml
|
| 27 |
+
PIXEL_MEAN = np.array([123.675, 116.28, 103.53], np.float32)
|
| 28 |
+
PIXEL_STD = np.array([58.395, 57.12, 57.375], np.float32)
|
| 29 |
+
GROUP = 64
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def quantizable(path: str, module) -> bool:
|
| 35 |
+
return isinstance(module, nn.Linear) and module.weight.shape[-1] % GROUP == 0
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def resize(x, size):
|
| 39 |
+
"""torch F.interpolate(mode="bilinear", align_corners=False), NHWC."""
|
| 40 |
+
b, h, w, c = x.shape
|
| 41 |
+
oh, ow = int(size[0]), int(size[1])
|
| 42 |
+
if (oh, ow) == (h, w):
|
| 43 |
+
return x
|
| 44 |
+
|
| 45 |
+
def axis(n_in, n_out):
|
| 46 |
+
s = np.clip((np.arange(n_out, dtype=np.float64) + 0.5) * (n_in / n_out) - 0.5, 0, None)
|
| 47 |
+
i0 = np.minimum(np.floor(s).astype(np.int32), n_in - 1)
|
| 48 |
+
return mx.array(i0), mx.array(np.minimum(i0 + 1, n_in - 1)), mx.array((s - i0).astype(np.float32))
|
| 49 |
+
|
| 50 |
+
y0, y1, fy = axis(h, oh)
|
| 51 |
+
x0, x1, fx = axis(w, ow)
|
| 52 |
+
fy, fx = fy.astype(x.dtype)[None, :, None, None], fx.astype(x.dtype)[None, None, :, None]
|
| 53 |
+
top, bot = x[:, y0], x[:, y1]
|
| 54 |
+
top = top[:, :, x0] * (1 - fx) + top[:, :, x1] * fx
|
| 55 |
+
bot = bot[:, :, x0] * (1 - fx) + bot[:, :, x1] * fx
|
| 56 |
+
return top * (1 - fy) + bot * fy
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class LayerNorm2d(nn.Module):
|
| 60 |
+
"""SAM's channel LayerNorm (eps 1e-6), statistics in float32."""
|
| 61 |
+
|
| 62 |
+
def __init__(self, c, eps=1e-6):
|
| 63 |
+
super().__init__()
|
| 64 |
+
self.weight, self.bias, self.eps = mx.ones((c,)), mx.zeros((c,)), eps
|
| 65 |
+
|
| 66 |
+
def __call__(self, x):
|
| 67 |
+
y = x.astype(mx.float32)
|
| 68 |
+
u = y.mean(-1, keepdims=True)
|
| 69 |
+
s = ((y - u) ** 2).mean(-1, keepdims=True)
|
| 70 |
+
return (self.weight * ((y - u) * mx.rsqrt(s + self.eps)).astype(x.dtype) + self.bias)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def bicubic_matrix(n_in: int, n_out: int) -> np.ndarray:
|
| 75 |
+
"""torch F.interpolate(mode="bicubic", align_corners=False) along one axis as an (n_out, n_in) matrix
|
| 76 |
+
(A = -0.75, source index not clamped, taps clamped to the border)."""
|
| 77 |
+
A = -0.75
|
| 78 |
+
m = np.zeros((n_out, n_in), np.float64)
|
| 79 |
+
scale = n_in / n_out
|
| 80 |
+
for o in range(n_out):
|
| 81 |
+
s = (o + 0.5) * scale - 0.5
|
| 82 |
+
f = int(np.floor(s))
|
| 83 |
+
t = s - f
|
| 84 |
+
w = [((A * (t + 1) - 5 * A) * (t + 1) + 8 * A) * (t + 1) - 4 * A,
|
| 85 |
+
((A + 2) * t - (A + 3)) * t * t + 1,
|
| 86 |
+
((A + 2) * (1 - t) - (A + 3)) * (1 - t) * (1 - t) + 1,
|
| 87 |
+
((A * (2 - t) - 5 * A) * (2 - t) + 8 * A) * (2 - t) - 4 * A]
|
| 88 |
+
for j in range(4):
|
| 89 |
+
m[o, min(max(f - 1 + j, 0), n_in - 1)] += w[j]
|
| 90 |
+
return m.astype(np.float32)
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def bicubic(x, size):
|
| 94 |
+
b, h, w, c = x.shape
|
| 95 |
+
if (h, w) == tuple(size):
|
| 96 |
+
return x
|
| 97 |
+
mh, mw = mx.array(bicubic_matrix(h, size[0])), mx.array(bicubic_matrix(w, size[1]))
|
| 98 |
+
y = x.astype(mx.float32)
|
| 99 |
+
y = mx.einsum("oh,bhwc->bowc", mh, y)
|
| 100 |
+
y = mx.einsum("pw,bowc->bopc", mw, y)
|
| 101 |
+
return y.astype(x.dtype)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def CL(cin, cout, k=1, s=1, g=1, bias=True):
|
| 105 |
+
"""A ConvLayer with its BatchNorm folded in: a linear layer when it is a plain 1x1 convolution."""
|
| 106 |
+
if k == 1 and s == 1 and g == 1:
|
| 107 |
+
return nn.Linear(cin, cout, bias=bias)
|
| 108 |
+
return nn.Conv2d(cin, cout, k, stride=s, padding=k // 2, groups=g, bias=bias)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
act = nn.gelu_approx # the repo's "gelu" is GELU(approximate="tanh")
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
class ResBlock(nn.Module):
|
| 115 |
+
def __init__(self, c):
|
| 116 |
+
super().__init__()
|
| 117 |
+
self.conv1, self.conv2 = CL(c, c, 3), CL(c, c, 3)
|
| 118 |
+
|
| 119 |
+
def __call__(self, x):
|
| 120 |
+
return self.conv2(act(self.conv1(x)))
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
class FusedMBConv(nn.Module):
|
| 124 |
+
def __init__(self, cin, cout, s, e):
|
| 125 |
+
super().__init__()
|
| 126 |
+
mid = round(cin * e)
|
| 127 |
+
self.spatial_conv, self.point_conv = CL(cin, mid, 3, s), CL(mid, cout)
|
| 128 |
+
|
| 129 |
+
def __call__(self, x):
|
| 130 |
+
return self.point_conv(act(self.spatial_conv(x)))
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class MBConv(nn.Module):
|
| 134 |
+
def __init__(self, cin, cout, s, e):
|
| 135 |
+
super().__init__()
|
| 136 |
+
mid = round(cin * e)
|
| 137 |
+
self.inverted_conv, self.depth_conv, self.point_conv = CL(cin, mid), CL(mid, mid, 3, s, mid), CL(mid, cout)
|
| 138 |
+
|
| 139 |
+
def __call__(self, x):
|
| 140 |
+
return self.point_conv(act(self.depth_conv(act(self.inverted_conv(x)))))
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class Aggreg(nn.Module):
|
| 144 |
+
def __init__(self, c, heads, k=5):
|
| 145 |
+
super().__init__()
|
| 146 |
+
self.dw = nn.Conv2d(c, c, k, padding=k // 2, groups=c, bias=False)
|
| 147 |
+
self.pw = nn.Conv2d(c, c, 1, groups=3 * heads, bias=False)
|
| 148 |
+
|
| 149 |
+
def __call__(self, x):
|
| 150 |
+
return self.pw(self.dw(x))
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class LiteMLA(nn.Module):
|
| 154 |
+
def __init__(self, c, dim=32):
|
| 155 |
+
super().__init__()
|
| 156 |
+
self.dim, heads = dim, c // dim
|
| 157 |
+
self.qkv = CL(c, 3 * c, bias=False)
|
| 158 |
+
self.aggreg = [Aggreg(3 * c, heads)]
|
| 159 |
+
self.proj = CL(2 * c, c)
|
| 160 |
+
|
| 161 |
+
def __call__(self, x):
|
| 162 |
+
b, h, w, _ = x.shape
|
| 163 |
+
qkv = self.qkv(x)
|
| 164 |
+
qkv = mx.concatenate([qkv] + [a(qkv) for a in self.aggreg], -1).astype(mx.float32)
|
| 165 |
+
d = self.dim
|
| 166 |
+
t = qkv.reshape(b, h * w, -1, 3 * d).transpose(0, 2, 1, 3) # (B, heads, N, 3d)
|
| 167 |
+
q, k, v = nn.relu(t[..., :d]), nn.relu(t[..., d:2 * d]), t[..., 2 * d:]
|
| 168 |
+
v = mx.concatenate([v, mx.ones(v.shape[:-1] + (1,), mx.float32)], -1)
|
| 169 |
+
vk = v.transpose(0, 1, 3, 2) @ k # (B, heads, d + 1, d)
|
| 170 |
+
out = q @ vk.transpose(0, 1, 3, 2) # (B, heads, N, d + 1)
|
| 171 |
+
out = out[..., :-1] / (out[..., -1:] + 1e-15)
|
| 172 |
+
out = out.transpose(0, 2, 1, 3).reshape(b, h, w, -1).astype(x.dtype)
|
| 173 |
+
return self.proj(out)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
class EViTBlock(nn.Module):
|
| 177 |
+
def __init__(self, c, dim, e):
|
| 178 |
+
super().__init__()
|
| 179 |
+
self.context_module = LiteMLA(c, dim)
|
| 180 |
+
self.local_module = MBConv(c, c, 1, e)
|
| 181 |
+
|
| 182 |
+
def __call__(self, x):
|
| 183 |
+
x = x + self.context_module(x)
|
| 184 |
+
return x + self.local_module(x)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class Res(nn.Module):
|
| 188 |
+
"""ResidualBlock: x + main(x), or main(x) alone for the downsampling blocks."""
|
| 189 |
+
|
| 190 |
+
def __init__(self, main, shortcut=True):
|
| 191 |
+
super().__init__()
|
| 192 |
+
self.main, self.shortcut = main, shortcut
|
| 193 |
+
|
| 194 |
+
def __call__(self, x):
|
| 195 |
+
return x + self.main(x) if self.shortcut else self.main(x)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class Backbone(nn.Module):
|
| 199 |
+
"""EfficientViTLargeBackbone with the default blocks (res, fmb, fmb, mb, att) and expands (1, 4, 4, 4, 6)."""
|
| 200 |
+
|
| 201 |
+
def __init__(self, wl, dl, qkv_dim):
|
| 202 |
+
super().__init__()
|
| 203 |
+
blocks, expand = ["res", "fmb", "fmb", "mb", "att"], [1, 4, 4, 4, 6]
|
| 204 |
+
self.stem = CL(3, wl[0], 3, 2)
|
| 205 |
+
self.stages = [[Res(ResBlock(wl[0])) for _ in range(dl[0])]]
|
| 206 |
+
cin = wl[0]
|
| 207 |
+
for i in range(1, 5):
|
| 208 |
+
w, kind = wl[i], blocks[i]
|
| 209 |
+
down = FusedMBConv(cin, w, 2, expand[i] * 4) if kind == "fmb" else MBConv(cin, w, 2, expand[i] * 4)
|
| 210 |
+
stage = [Res(down, False)]
|
| 211 |
+
for _ in range(dl[i]):
|
| 212 |
+
if kind == "att":
|
| 213 |
+
stage.append(EViTBlock(w, qkv_dim, expand[i]))
|
| 214 |
+
elif kind == "fmb":
|
| 215 |
+
stage.append(Res(FusedMBConv(w, w, 1, expand[i])))
|
| 216 |
+
else:
|
| 217 |
+
stage.append(Res(MBConv(w, w, 1, expand[i])))
|
| 218 |
+
self.stages.append(stage)
|
| 219 |
+
cin = w
|
| 220 |
+
|
| 221 |
+
def __call__(self, x):
|
| 222 |
+
x = act(self.stem(x))
|
| 223 |
+
feats = []
|
| 224 |
+
for stage in self.stages:
|
| 225 |
+
for blk in stage:
|
| 226 |
+
x = blk(x)
|
| 227 |
+
feats.append(x)
|
| 228 |
+
return feats # stage0 .. stage4
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
class Neck(nn.Module):
|
| 232 |
+
def __init__(self, wl, depth, e, width=256):
|
| 233 |
+
super().__init__()
|
| 234 |
+
self.input_ops = [CL(wl[4], width), CL(wl[3], width), CL(wl[2], width)] # stage4, stage3, stage2
|
| 235 |
+
self.middle = [Res(FusedMBConv(width, width, 1, e)) for _ in range(depth)]
|
| 236 |
+
self.output = CL(width, 256)
|
| 237 |
+
|
| 238 |
+
def __call__(self, feats, hw):
|
| 239 |
+
x = sum(bicubic(op(f), hw) for op, f in zip(self.input_ops, (feats[4], feats[3], feats[2])))
|
| 240 |
+
for blk in self.middle:
|
| 241 |
+
x = blk(x)
|
| 242 |
+
return self.output(x)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
class ImageEncoder(nn.Module):
|
| 246 |
+
def __init__(self, c):
|
| 247 |
+
super().__init__()
|
| 248 |
+
self.backbone = Backbone(c["width_list"], c["depth_list"], c["qkv_dim"])
|
| 249 |
+
self.neck = Neck(c["width_list"], c["neck_depth"], c["neck_expand"])
|
| 250 |
+
self.norm = LayerNorm2d(256, eps=1e-5)
|
| 251 |
+
self.emb = c["image_size"] // 16
|
| 252 |
+
|
| 253 |
+
def __call__(self, x):
|
| 254 |
+
return self.norm(self.neck(self.backbone(x), (self.emb, self.emb)))
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
# ------------------------------------------------------------------------------------------------ SAM decoder
|
| 258 |
+
|
| 259 |
+
class SAMAttention(nn.Module):
|
| 260 |
+
def __init__(self, dim, heads, down=1):
|
| 261 |
+
super().__init__()
|
| 262 |
+
inner = dim // down
|
| 263 |
+
self.heads = heads
|
| 264 |
+
self.q_proj, self.k_proj, self.v_proj = nn.Linear(dim, inner), nn.Linear(dim, inner), nn.Linear(dim, inner)
|
| 265 |
+
self.out_proj = nn.Linear(inner, dim)
|
| 266 |
+
|
| 267 |
+
def __call__(self, q, k, v):
|
| 268 |
+
q, k, v = self.q_proj(q), self.k_proj(k), self.v_proj(v)
|
| 269 |
+
b, nq, c = q.shape
|
| 270 |
+
sp = lambda t: t.reshape(b, t.shape[1], self.heads, c // self.heads).transpose(0, 2, 1, 3)
|
| 271 |
+
q, k, v = sp(q), sp(k), sp(v)
|
| 272 |
+
a = mx.softmax((q @ k.transpose(0, 1, 3, 2)) * (c // self.heads) ** -0.5, axis=-1, precise=True)
|
| 273 |
+
return self.out_proj((a @ v).transpose(0, 2, 1, 3).reshape(b, nq, c))
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
class MLPBlock(nn.Module):
|
| 277 |
+
def __init__(self, dim, hidden):
|
| 278 |
+
super().__init__()
|
| 279 |
+
self.lin1, self.lin2 = nn.Linear(dim, hidden), nn.Linear(hidden, dim)
|
| 280 |
+
|
| 281 |
+
def __call__(self, x):
|
| 282 |
+
return self.lin2(nn.relu(self.lin1(x)))
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
class TwoWayBlock(nn.Module):
|
| 286 |
+
def __init__(self, dim, heads, mlp_dim, skip_pe):
|
| 287 |
+
super().__init__()
|
| 288 |
+
self.skip_pe = skip_pe
|
| 289 |
+
self.self_attn = SAMAttention(dim, heads)
|
| 290 |
+
self.cross_attn_token_to_image = SAMAttention(dim, heads, 2)
|
| 291 |
+
self.cross_attn_image_to_token = SAMAttention(dim, heads, 2)
|
| 292 |
+
self.mlp = MLPBlock(dim, mlp_dim)
|
| 293 |
+
self.norm1, self.norm2, self.norm3, self.norm4 = (nn.LayerNorm(dim) for _ in range(4))
|
| 294 |
+
|
| 295 |
+
def __call__(self, q, k, qpe, kpe):
|
| 296 |
+
if self.skip_pe:
|
| 297 |
+
q = self.self_attn(q, q, q)
|
| 298 |
+
else:
|
| 299 |
+
t = q + qpe
|
| 300 |
+
q = q + self.self_attn(t, t, q)
|
| 301 |
+
q = self.norm1(q)
|
| 302 |
+
q = self.norm2(q + self.cross_attn_token_to_image(q + qpe, k + kpe, k))
|
| 303 |
+
q = self.norm3(q + self.mlp(q))
|
| 304 |
+
k = self.norm4(k + self.cross_attn_image_to_token(k + kpe, q + qpe, q))
|
| 305 |
+
return q, k
|
| 306 |
+
|
| 307 |
+
|
| 308 |
+
class TwoWayTransformer(nn.Module):
|
| 309 |
+
def __init__(self, dim=256, heads=8, mlp_dim=2048, depth=2):
|
| 310 |
+
super().__init__()
|
| 311 |
+
self.layers = [TwoWayBlock(dim, heads, mlp_dim, i == 0) for i in range(depth)]
|
| 312 |
+
self.final_attn_token_to_image = SAMAttention(dim, heads, 2)
|
| 313 |
+
self.norm_final_attn = nn.LayerNorm(dim)
|
| 314 |
+
|
| 315 |
+
def __call__(self, img, pe, tokens):
|
| 316 |
+
b, h, w, c = img.shape
|
| 317 |
+
k, kpe, q = img.reshape(b, h * w, c), pe.reshape(b, h * w, c), tokens
|
| 318 |
+
for layer in self.layers:
|
| 319 |
+
q, k = layer(q, k, tokens, kpe)
|
| 320 |
+
q = self.norm_final_attn(q + self.final_attn_token_to_image(q + tokens, k + kpe, k))
|
| 321 |
+
return q, k
|
| 322 |
+
|
| 323 |
+
|
| 324 |
+
class MLP(nn.Module):
|
| 325 |
+
def __init__(self, din, dh, dout, n):
|
| 326 |
+
super().__init__()
|
| 327 |
+
dims = [din] + [dh] * (n - 1)
|
| 328 |
+
self.layers = [nn.Linear(a, b) for a, b in zip(dims, [dh] * (n - 1) + [dout])]
|
| 329 |
+
|
| 330 |
+
def __call__(self, x):
|
| 331 |
+
for i, l in enumerate(self.layers):
|
| 332 |
+
x = nn.relu(l(x)) if i < len(self.layers) - 1 else l(x)
|
| 333 |
+
return x
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
class PromptEncoder(nn.Module):
|
| 337 |
+
def __init__(self, dim, emb_hw, img_size, mask_in):
|
| 338 |
+
super().__init__()
|
| 339 |
+
self.emb_hw, self.img_size = emb_hw, img_size
|
| 340 |
+
self.positional_encoding_gaussian_matrix = mx.zeros((2, dim // 2))
|
| 341 |
+
self.point_embeddings = [mx.zeros((1, dim)) for _ in range(4)]
|
| 342 |
+
self.not_a_point_embed = mx.zeros((1, dim))
|
| 343 |
+
self.no_mask_embed = mx.zeros((1, dim))
|
| 344 |
+
self.mask_conv1 = nn.Conv2d(1, mask_in // 4, 2, stride=2)
|
| 345 |
+
self.mask_norm1 = LayerNorm2d(mask_in // 4)
|
| 346 |
+
self.mask_conv2 = nn.Conv2d(mask_in // 4, mask_in, 2, stride=2)
|
| 347 |
+
self.mask_norm2 = LayerNorm2d(mask_in)
|
| 348 |
+
self.mask_conv3 = nn.Conv2d(mask_in, dim, 1)
|
| 349 |
+
|
| 350 |
+
def pe(self, coords): # coords in [0, 1], float32
|
| 351 |
+
c = (2 * coords - 1) @ self.positional_encoding_gaussian_matrix.astype(mx.float32)
|
| 352 |
+
c = 2 * np.pi * c
|
| 353 |
+
return mx.concatenate([mx.sin(c), mx.cos(c)], -1)
|
| 354 |
+
|
| 355 |
+
def dense_pe(self):
|
| 356 |
+
h, w = self.emb_hw
|
| 357 |
+
ys = (mx.arange(h, dtype=mx.float32) + 0.5) / h
|
| 358 |
+
xs = (mx.arange(w, dtype=mx.float32) + 0.5) / w
|
| 359 |
+
grid = mx.stack([mx.broadcast_to(xs[None, :], (h, w)), mx.broadcast_to(ys[:, None], (h, w))], -1)
|
| 360 |
+
return self.pe(grid)[None] # (1, h, w, C)
|
| 361 |
+
|
| 362 |
+
def __call__(self, points, labels, box, mask):
|
| 363 |
+
dt = self.no_mask_embed.dtype
|
| 364 |
+
sparse = []
|
| 365 |
+
s = mx.array([self.img_size, self.img_size], dtype=mx.float32)
|
| 366 |
+
if points is not None:
|
| 367 |
+
pts, lab = points + 0.5, labels
|
| 368 |
+
if box is None:
|
| 369 |
+
pts = mx.concatenate([pts, mx.zeros((pts.shape[0], 1, 2))], 1)
|
| 370 |
+
lab = mx.concatenate([lab, -mx.ones((lab.shape[0], 1))], 1)
|
| 371 |
+
e = self.pe(pts / s)
|
| 372 |
+
l = lab[..., None]
|
| 373 |
+
e = mx.where(l == -1, 0.0, e)
|
| 374 |
+
e = e + (l == -1) * self.not_a_point_embed.astype(mx.float32)
|
| 375 |
+
e = e + (l == 0) * self.point_embeddings[0].astype(mx.float32)
|
| 376 |
+
e = e + (l == 1) * self.point_embeddings[1].astype(mx.float32)
|
| 377 |
+
sparse.append(e)
|
| 378 |
+
if box is not None:
|
| 379 |
+
e = self.pe((box + 0.5).reshape(-1, 2, 2) / s)
|
| 380 |
+
e = e + mx.concatenate([self.point_embeddings[2], self.point_embeddings[3]], 0).astype(mx.float32)[None]
|
| 381 |
+
sparse.append(e)
|
| 382 |
+
sparse = mx.concatenate(sparse, 1).astype(dt)
|
| 383 |
+
if mask is not None:
|
| 384 |
+
m = nn.gelu(self.mask_norm1(self.mask_conv1(mask)))
|
| 385 |
+
dense = self.mask_conv3(nn.gelu(self.mask_norm2(self.mask_conv2(m))))
|
| 386 |
+
else:
|
| 387 |
+
h, w = self.emb_hw
|
| 388 |
+
dense = mx.broadcast_to(self.no_mask_embed.reshape(1, 1, 1, -1), (sparse.shape[0], h, w, self.no_mask_embed.shape[-1]))
|
| 389 |
+
return sparse, dense
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
class MaskDecoder(nn.Module):
|
| 393 |
+
def __init__(self, dim=256, n_mask=3):
|
| 394 |
+
super().__init__()
|
| 395 |
+
self.n = n_mask + 1
|
| 396 |
+
self.transformer = TwoWayTransformer(dim)
|
| 397 |
+
self.iou_token = mx.zeros((1, dim))
|
| 398 |
+
self.mask_tokens = mx.zeros((self.n, dim))
|
| 399 |
+
self.up1 = nn.ConvTranspose2d(dim, dim // 4, 2, stride=2)
|
| 400 |
+
self.up_norm = LayerNorm2d(dim // 4)
|
| 401 |
+
self.up2 = nn.ConvTranspose2d(dim // 4, dim // 8, 2, stride=2)
|
| 402 |
+
self.output_hypernetworks_mlps = [MLP(dim, dim, dim // 8, 3) for _ in range(self.n)]
|
| 403 |
+
self.iou_prediction_head = MLP(dim, 256, self.n, 3)
|
| 404 |
+
|
| 405 |
+
def __call__(self, img, pe, sparse, dense):
|
| 406 |
+
b = sparse.shape[0]
|
| 407 |
+
out = mx.concatenate([self.iou_token, self.mask_tokens], 0)
|
| 408 |
+
tokens = mx.concatenate([mx.broadcast_to(out[None], (b,) + out.shape), sparse], 1)
|
| 409 |
+
src = mx.broadcast_to(img, (b,) + img.shape[1:]) + dense
|
| 410 |
+
pos = mx.broadcast_to(pe, (b,) + pe.shape[1:]).astype(src.dtype)
|
| 411 |
+
hs, src = self.transformer(src, pos, tokens)
|
| 412 |
+
_, h, w, c = img.shape
|
| 413 |
+
up = nn.gelu(self.up2(nn.gelu(self.up_norm(self.up1(src.reshape(b, h, w, c))))))
|
| 414 |
+
hyper = mx.stack([self.output_hypernetworks_mlps[i](hs[:, 1 + i]) for i in range(self.n)], 1)
|
| 415 |
+
bb, uh, uw, uc = up.shape
|
| 416 |
+
masks = (hyper @ up.reshape(b, uh * uw, uc).transpose(0, 2, 1)).reshape(b, self.n, uh, uw)
|
| 417 |
+
return masks, self.iou_prediction_head(hs[:, 0])
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
class Model(nn.Module):
|
| 422 |
+
def __init__(self, config: dict = CONFIG):
|
| 423 |
+
super().__init__()
|
| 424 |
+
self.size, self.encoder_size = config["image_size"], config["encoder_size"]
|
| 425 |
+
e = self.size // 16
|
| 426 |
+
self.image_encoder = ImageEncoder(config)
|
| 427 |
+
self.prompt_encoder = PromptEncoder(config["prompt_dim"], (e, e), self.size, config["mask_in_chans"])
|
| 428 |
+
self.mask_decoder = MaskDecoder(config["prompt_dim"])
|
| 429 |
+
|
| 430 |
+
|
| 431 |
+
def load(folder) -> Model:
|
| 432 |
+
folder = Path(folder)
|
| 433 |
+
config = json.loads((folder / "config.json").read_text())
|
| 434 |
+
model = Model(config)
|
| 435 |
+
q = config.get("quantization")
|
| 436 |
+
if q:
|
| 437 |
+
nn.quantize(model, group_size=q["group_size"], bits=q["bits"], class_predicate=quantizable)
|
| 438 |
+
model.load_weights(str(folder / "model.safetensors"), strict=True)
|
| 439 |
+
mx.eval(model.parameters())
|
| 440 |
+
return model
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def dtype(model):
|
| 444 |
+
return model.mask_decoder.iou_token.dtype
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def embed(model: Model, rgb: np.ndarray) -> dict:
|
| 448 |
+
"""EfficientViTSamPredictor.set_image: the encoder sees the image with its longest side at 512 (PIL bilinear),
|
| 449 |
+
normalized and padded; prompts and masks live in the 1024 frame (input_size)."""
|
| 450 |
+
from PIL import Image
|
| 451 |
+
h, w = rgb.shape[:2]
|
| 452 |
+
shape = lambda n: (int(h * n / max(h, w) + 0.5), int(w * n / max(h, w) + 0.5))
|
| 453 |
+
eh, ew = shape(model.encoder_size)
|
| 454 |
+
x = rgb if max(h, w) == model.encoder_size else np.asarray(Image.fromarray(rgb).resize((ew, eh), Image.BILINEAR))
|
| 455 |
+
x = (x.astype(np.float32) - PIXEL_MEAN) / PIXEL_STD
|
| 456 |
+
x = np.pad(x, ((0, model.encoder_size - eh), (0, model.encoder_size - ew), (0, 0)))
|
| 457 |
+
feats = model.image_encoder(mx.array(x[None]).astype(dtype(model)))
|
| 458 |
+
mx.eval(feats)
|
| 459 |
+
return {"features": feats, "original_size": (h, w), "input_size": shape(model.size)}
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def predict(model: Model, emb: dict, points=None, labels=None, box=None, multimask=True):
|
| 463 |
+
"""SamPredictor.predict: prompts in original-image pixels -> (masks bool (N, H, W), scores (N,), low-res
|
| 464 |
+
logits (N, 256, 256))."""
|
| 465 |
+
h, w = emb["original_size"]
|
| 466 |
+
nh, nw = emb["input_size"]
|
| 467 |
+
sx, sy = nw / w, nh / h
|
| 468 |
+
pts = lab = bx = None
|
| 469 |
+
if points is not None:
|
| 470 |
+
pts = mx.array(np.asarray(points, np.float32)[None] * np.array([sx, sy], np.float32))
|
| 471 |
+
lab = mx.array(np.asarray(labels, np.float32)[None])
|
| 472 |
+
if box is not None:
|
| 473 |
+
bx = mx.array(np.asarray(box, np.float32).reshape(1, 4) * np.array([sx, sy, sx, sy], np.float32))
|
| 474 |
+
sparse, dense = model.prompt_encoder(pts, lab, bx, None)
|
| 475 |
+
pe = model.prompt_encoder.dense_pe()
|
| 476 |
+
logits, iou = model.mask_decoder(emb["features"], pe, sparse, dense.astype(sparse.dtype))
|
| 477 |
+
sl = slice(1, None) if multimask else slice(0, 1)
|
| 478 |
+
logits, iou = logits[:, sl].astype(mx.float32), iou[:, sl].astype(mx.float32)
|
| 479 |
+
low = logits
|
| 480 |
+
m = resize(logits.transpose(0, 2, 3, 1), (model.size, model.size))[:, :nh, :nw]
|
| 481 |
+
m = resize(m, (h, w)).transpose(0, 3, 1, 2)
|
| 482 |
+
return np.array(m[0] > 0), np.array(iou[0]), np.array(low[0]), np.array(m[0])
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
# ------------------------------------------------------------------------------------------------ conversion
|
| 487 |
+
|
| 488 |
+
def convert(source: Path) -> dict:
|
| 489 |
+
"""runs/source/weights/efficientvit_sam_l2.pt (a plain state dict) -> MLX names: BatchNorms folded, 1x1 convs as
|
| 490 |
+
linear weights, the module tree renamed to this port's."""
|
| 491 |
+
import torch
|
| 492 |
+
sd = {k: v.double().numpy() for k, v in torch.load(Path(source) / "weights" / "efficientvit_sam_l2.pt",
|
| 493 |
+
map_location="cpu", weights_only=True).items()
|
| 494 |
+
if v.is_floating_point()}
|
| 495 |
+
out = {}
|
| 496 |
+
|
| 497 |
+
def put(dst, conv, bn=None, linear=False):
|
| 498 |
+
w = sd[conv + ".weight"]
|
| 499 |
+
b = sd.get(conv + ".bias", np.zeros(w.shape[0]))
|
| 500 |
+
if bn is not None and bn + ".running_mean" in sd:
|
| 501 |
+
g = sd[bn + ".weight"] / np.sqrt(sd[bn + ".running_var"] + 1e-5)
|
| 502 |
+
w, b = w * g[:, None, None, None], (b - sd[bn + ".running_mean"]) * g + sd[bn + ".bias"]
|
| 503 |
+
out[dst + ".weight"] = (w[:, :, 0, 0] if linear else w.transpose(0, 2, 3, 1)).astype(np.float32)
|
| 504 |
+
if conv + ".bias" in sd or (bn is not None and bn + ".running_mean" in sd):
|
| 505 |
+
out[dst + ".bias"] = b.astype(np.float32)
|
| 506 |
+
|
| 507 |
+
def layer(dst, src, linear): # a ConvLayer: src.conv (+ src.norm)
|
| 508 |
+
put(dst, src + ".conv", src + ".norm", linear)
|
| 509 |
+
|
| 510 |
+
bb = "image_encoder.backbone.stages"
|
| 511 |
+
layer("image_encoder.backbone.stem", f"{bb}.0.op_list.0", False)
|
| 512 |
+
st = lambda i, j: f"{bb}.{i}.op_list.{j}"
|
| 513 |
+
n0 = sum(1 for k in sd if k.startswith(f"{bb}.0.op_list.") and k.endswith("main.conv1.conv.weight"))
|
| 514 |
+
for j in range(n0):
|
| 515 |
+
for c in ("conv1", "conv2"):
|
| 516 |
+
layer(f"image_encoder.backbone.stages.0.{j}.main.{c}", f"{st(0, j + 1)}.main.{c}", False)
|
| 517 |
+
for i in range(1, 5):
|
| 518 |
+
j = 0
|
| 519 |
+
while any(k.startswith(st(i, j) + ".") for k in sd):
|
| 520 |
+
dst, src = f"image_encoder.backbone.stages.{i}.{j}", st(i, j)
|
| 521 |
+
if src + ".context_module.main.qkv.conv.weight" in sd: # EfficientViTBlock
|
| 522 |
+
cm, lm = src + ".context_module.main", src + ".local_module.main"
|
| 523 |
+
layer(dst + ".context_module.qkv", cm + ".qkv", True)
|
| 524 |
+
put(dst + ".context_module.aggreg.0.dw", cm + ".aggreg.0.0")
|
| 525 |
+
put(dst + ".context_module.aggreg.0.pw", cm + ".aggreg.0.1")
|
| 526 |
+
layer(dst + ".context_module.proj", cm + ".proj", True)
|
| 527 |
+
layer(dst + ".local_module.inverted_conv", lm + ".inverted_conv", True)
|
| 528 |
+
layer(dst + ".local_module.depth_conv", lm + ".depth_conv", False)
|
| 529 |
+
layer(dst + ".local_module.point_conv", lm + ".point_conv", True)
|
| 530 |
+
elif src + ".main.spatial_conv.conv.weight" in sd: # FusedMBConv
|
| 531 |
+
layer(dst + ".main.spatial_conv", src + ".main.spatial_conv", False)
|
| 532 |
+
layer(dst + ".main.point_conv", src + ".main.point_conv", True)
|
| 533 |
+
else: # MBConv
|
| 534 |
+
layer(dst + ".main.inverted_conv", src + ".main.inverted_conv", True)
|
| 535 |
+
layer(dst + ".main.depth_conv", src + ".main.depth_conv", False)
|
| 536 |
+
layer(dst + ".main.point_conv", src + ".main.point_conv", True)
|
| 537 |
+
j += 1
|
| 538 |
+
nk = "image_encoder.neck"
|
| 539 |
+
for i in range(3):
|
| 540 |
+
layer(f"{nk}.input_ops.{i}", f"{nk}.input_ops.{i}.op_list.0", True)
|
| 541 |
+
j = 0
|
| 542 |
+
while f"{nk}.middle.op_list.{j}.main.spatial_conv.conv.weight" in sd:
|
| 543 |
+
layer(f"{nk}.middle.{j}.main.spatial_conv", f"{nk}.middle.op_list.{j}.main.spatial_conv", False)
|
| 544 |
+
layer(f"{nk}.middle.{j}.main.point_conv", f"{nk}.middle.op_list.{j}.main.point_conv", True)
|
| 545 |
+
j += 1
|
| 546 |
+
layer(f"{nk}.output", f"{nk}.output_ops.0.op_list.0", True)
|
| 547 |
+
out["image_encoder.norm.weight"] = sd["image_encoder.norm.weight"].astype(np.float32)
|
| 548 |
+
out["image_encoder.norm.bias"] = sd["image_encoder.norm.bias"].astype(np.float32)
|
| 549 |
+
# SAM's prompt encoder and mask decoder, as in segment_anything
|
| 550 |
+
ren = {"prompt_encoder.pe_layer.": "prompt_encoder.",
|
| 551 |
+
"prompt_encoder.mask_downscaling.0.": "prompt_encoder.mask_conv1.",
|
| 552 |
+
"prompt_encoder.mask_downscaling.1.": "prompt_encoder.mask_norm1.",
|
| 553 |
+
"prompt_encoder.mask_downscaling.3.": "prompt_encoder.mask_conv2.",
|
| 554 |
+
"prompt_encoder.mask_downscaling.4.": "prompt_encoder.mask_norm2.",
|
| 555 |
+
"prompt_encoder.mask_downscaling.6.": "prompt_encoder.mask_conv3.",
|
| 556 |
+
"mask_decoder.output_upscaling.0.": "mask_decoder.up1.",
|
| 557 |
+
"mask_decoder.output_upscaling.1.": "mask_decoder.up_norm.",
|
| 558 |
+
"mask_decoder.output_upscaling.3.": "mask_decoder.up2."}
|
| 559 |
+
for k, v in sd.items():
|
| 560 |
+
if not k.startswith(("prompt_encoder.", "mask_decoder.")):
|
| 561 |
+
continue
|
| 562 |
+
n = k
|
| 563 |
+
for a, b in ren.items():
|
| 564 |
+
if n.startswith(a):
|
| 565 |
+
n = b + n[len(a):]
|
| 566 |
+
if n.endswith(".weight") and (n.startswith("prompt_encoder.point_embeddings") or
|
| 567 |
+
n.split(".")[-2] in ("not_a_point_embed", "no_mask_embed", "iou_token", "mask_tokens")):
|
| 568 |
+
n = n[:-len(".weight")]
|
| 569 |
+
if v.ndim == 4:
|
| 570 |
+
v = v.transpose(1, 2, 3, 0) if ".up1." in n or ".up2." in n else v.transpose(0, 2, 3, 1)
|
| 571 |
+
out[n] = v.astype(np.float32)
|
| 572 |
+
return out
|
fp16/model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f4b4b159c9f752c7ba72eeeb4aa099cf8575e064e01bfec0ee8576227172561f
|
| 3 |
+
size 122661143
|