Image Segmentation
MLX
Safetensors
BiRefNet
moonbox
background-removal
dichotomous-image-segmentation
Instructions to use moonbox-ai/BiRefNet_lite-MLX with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use moonbox-ai/BiRefNet_lite-MLX with MLX:
# Download the model from the Hub pip install huggingface_hub[hf_xet] hf download moonbox-ai/BiRefNet_lite-MLX --local-dir BiRefNet_lite-MLX
- BiRefNet
How to use moonbox-ai/BiRefNet_lite-MLX with BiRefNet:
# Option 1: use with transformers from transformers import AutoModelForImageSegmentation birefnet = AutoModelForImageSegmentation.from_pretrained("moonbox-ai/BiRefNet_lite-MLX", trust_remote_code=True)# Option 2: use with BiRefNet # Install from https://github.com/ZhengPeng7/BiRefNet from models.birefnet import BiRefNet model = BiRefNet.from_pretrained("moonbox-ai/BiRefNet_lite-MLX") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Atomic Chat
4bit build of BiRefNet-lite
Browse files- 4bit/config.json +11 -0
- 4bit/mlx_model.py +462 -0
- 4bit/model.safetensors +3 -0
4bit/config.json
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_type": "birefnet",
|
| 3 |
+
"backbone": "swin_v1_t",
|
| 4 |
+
"input_size": 1024,
|
| 5 |
+
"quantization": {
|
| 6 |
+
"group_size": 64,
|
| 7 |
+
"bits": 4,
|
| 8 |
+
"mode": "affine"
|
| 9 |
+
},
|
| 10 |
+
"precision": "4bit"
|
| 11 |
+
}
|
4bit/mlx_model.py
ADDED
|
@@ -0,0 +1,462 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""BiRefNet (ZhengPeng7/BiRefNet, BiRefNet_lite; MIT) in MLX: a port of the Hub repo's `birefnet.py` for the
|
| 2 |
+
released configuration (Swin v1 backbone run at full and half resolution and concatenated, 3 context features,
|
| 3 |
+
ASPPDeformable decoder blocks, image-patch inputs, gradient attention).
|
| 4 |
+
|
| 5 |
+
import mlx_model
|
| 6 |
+
model = mlx_model.load("bf16") # a folder with config.json + model.safetensors
|
| 7 |
+
alpha = mlx_model.matte(model, rgb) # rgb: HxWx3 uint8 -> HxW uint8 alpha (255 = foreground)
|
| 8 |
+
|
| 9 |
+
Runs on its own next to its weights (mlx and numpy). NHWC throughout. Each BatchNorm is folded into the conv before
|
| 10 |
+
it at conversion; torchvision's deform_conv2d (DCNv2, with modulation) is written out as bilinear gathers.
|
| 11 |
+
Quantized builds (8bit / 6bit / 4bit) quantize the Swin backbone's linears whose input size is a multiple of 64;
|
| 12 |
+
the convolutions stay bf16.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
import mlx.core as mx
|
| 21 |
+
import mlx.nn as nn
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
SWIN = {"swin_v1_t": dict(embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7),
|
| 25 |
+
"swin_v1_l": dict(embed_dim=192, depths=[2, 2, 18, 2], num_heads=[6, 12, 24, 48], window_size=12)}
|
| 26 |
+
CONFIG = {"model_type": "birefnet", "backbone": "swin_v1_t", "input_size": 1024}
|
| 27 |
+
PRECISIONS = ["bf16", "fp16", "8bit", "6bit", "4bit"]
|
| 28 |
+
MEAN, STD = np.array([0.485, 0.456, 0.406], np.float32), np.array([0.229, 0.224, 0.225], np.float32)
|
| 29 |
+
GROUP = 64
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def quantizable(path: str, module) -> bool:
|
| 33 |
+
return isinstance(module, nn.Linear) and module.weight.shape[-1] % GROUP == 0
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
# ------------------------------------------------------------------------------------------------ ops
|
| 37 |
+
|
| 38 |
+
def resize(x, size, align_corners: bool):
|
| 39 |
+
"""torch F.interpolate(mode="bilinear") for NHWC (no antialiasing)."""
|
| 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 |
+
if align_corners:
|
| 47 |
+
s = np.arange(n_out, dtype=np.float64) * ((n_in - 1) / (n_out - 1) if n_out > 1 else 0.0)
|
| 48 |
+
else:
|
| 49 |
+
s = np.clip((np.arange(n_out, dtype=np.float64) + 0.5) * (n_in / n_out) - 0.5, 0, None)
|
| 50 |
+
i0 = np.minimum(np.floor(s).astype(np.int32), n_in - 1)
|
| 51 |
+
i1 = np.minimum(i0 + 1, n_in - 1)
|
| 52 |
+
return mx.array(i0), mx.array(i1), mx.array((s - i0).astype(np.float32))
|
| 53 |
+
|
| 54 |
+
y0, y1, fy = axis(h, oh)
|
| 55 |
+
x0, x1, fx = axis(w, ow)
|
| 56 |
+
fy = fy.astype(x.dtype)[None, :, None, None]
|
| 57 |
+
fx = fx.astype(x.dtype)[None, None, :, None]
|
| 58 |
+
top, bot = x[:, y0], x[:, y1]
|
| 59 |
+
top = top[:, :, x0] * (1 - fx) + top[:, :, x1] * fx
|
| 60 |
+
bot = bot[:, :, x0] * (1 - fx) + bot[:, :, x1] * fx
|
| 61 |
+
return top * (1 - fy) + bot * fy
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def to_patches(x, ref_hw):
|
| 65 |
+
"""einops 'b c (hg h) (wg w) -> b (c hg wg) h w' in NHWC."""
|
| 66 |
+
b, H, W, c = x.shape
|
| 67 |
+
h, w = ref_hw
|
| 68 |
+
hg, wg = H // h, W // w
|
| 69 |
+
x = x.reshape(b, hg, h, wg, w, c).transpose(0, 2, 4, 5, 1, 3)
|
| 70 |
+
return x.reshape(b, h, w, c * hg * wg)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def deform_conv(x, offset, mask, weight, bias, k: int):
|
| 74 |
+
"""torchvision.ops.deform_conv2d (stride 1, padding k // 2, dilation 1, one offset group) with a modulation mask.
|
| 75 |
+
x (1, H, W, C), offset (1, H, W, 2 k k) as (dy, dx) per kernel position, mask (1, H, W, k k), weight (O, k, k, C)."""
|
| 76 |
+
b, h, w, c = x.shape
|
| 77 |
+
assert b == 1, "batch 1"
|
| 78 |
+
pad = k // 2
|
| 79 |
+
flat = x.reshape(h * w, c)
|
| 80 |
+
gy = mx.arange(h, dtype=mx.float32)[:, None]
|
| 81 |
+
gx = mx.arange(w, dtype=mx.float32)[None, :]
|
| 82 |
+
off = offset[0].astype(mx.float32)
|
| 83 |
+
out = None
|
| 84 |
+
for i in range(k * k):
|
| 85 |
+
ky, kx = divmod(i, k)
|
| 86 |
+
py = gy + (ky - pad) + off[:, :, 2 * i]
|
| 87 |
+
px = gx + (kx - pad) + off[:, :, 2 * i + 1]
|
| 88 |
+
y0, x0 = mx.floor(py), mx.floor(px)
|
| 89 |
+
ly, lx = py - y0, px - x0
|
| 90 |
+
acc = None
|
| 91 |
+
for yy, xx, wt in ((y0, x0, (1 - ly) * (1 - lx)), (y0, x0 + 1, (1 - ly) * lx),
|
| 92 |
+
(y0 + 1, x0, ly * (1 - lx)), (y0 + 1, x0 + 1, ly * lx)):
|
| 93 |
+
ok = (yy >= 0) & (yy <= h - 1) & (xx >= 0) & (xx <= w - 1)
|
| 94 |
+
idx = (mx.clip(yy, 0, h - 1) * w + mx.clip(xx, 0, w - 1)).astype(mx.int32).reshape(-1)
|
| 95 |
+
v = mx.take(flat, idx, axis=0) * mx.where(ok, wt, 0.0).reshape(-1, 1).astype(x.dtype)
|
| 96 |
+
acc = v if acc is None else acc + v
|
| 97 |
+
acc = acc * mask[0, :, :, i].reshape(-1, 1)
|
| 98 |
+
y = acc @ weight[:, ky, kx, :].T
|
| 99 |
+
out = y if out is None else out + y
|
| 100 |
+
return (out + bias).reshape(1, h, w, -1)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
# ------------------------------------------------------------------------------------------------ Swin v1
|
| 104 |
+
|
| 105 |
+
def window_partition(x, ws):
|
| 106 |
+
b, h, w, c = x.shape
|
| 107 |
+
x = x.reshape(b, h // ws, ws, w // ws, ws, c).transpose(0, 1, 3, 2, 4, 5)
|
| 108 |
+
return x.reshape(-1, ws * ws, c)
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def window_reverse(win, ws, h, w):
|
| 112 |
+
c = win.shape[-1]
|
| 113 |
+
b = win.shape[0] // ((h // ws) * (w // ws))
|
| 114 |
+
x = win.reshape(b, h // ws, w // ws, ws, ws, c).transpose(0, 1, 3, 2, 4, 5)
|
| 115 |
+
return x.reshape(b, h, w, c)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def relative_index(ws: int) -> np.ndarray:
|
| 119 |
+
coords = np.stack(np.meshgrid(np.arange(ws), np.arange(ws), indexing="ij")).reshape(2, -1)
|
| 120 |
+
rel = (coords[:, :, None] - coords[:, None, :]).transpose(1, 2, 0) + (ws - 1)
|
| 121 |
+
return rel[:, :, 0] * (2 * ws - 1) + rel[:, :, 1]
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def shift_mask(hp: int, wp: int, ws: int, shift: int) -> np.ndarray:
|
| 125 |
+
img = np.zeros((1, hp, wp, 1), np.float32)
|
| 126 |
+
cnt = 0
|
| 127 |
+
for hs in (slice(0, -ws), slice(-ws, -shift), slice(-shift, None)):
|
| 128 |
+
for wsl in (slice(0, -ws), slice(-ws, -shift), slice(-shift, None)):
|
| 129 |
+
img[:, hs, wsl, :] = cnt
|
| 130 |
+
cnt += 1
|
| 131 |
+
m = img.reshape(1, hp // ws, ws, wp // ws, ws, 1).transpose(0, 1, 3, 2, 4, 5).reshape(-1, ws * ws)
|
| 132 |
+
m = m[:, None, :] - m[:, :, None]
|
| 133 |
+
return np.where(m != 0, -100.0, 0.0).astype(np.float32)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class WindowAttention(nn.Module):
|
| 137 |
+
def __init__(self, dim, ws, heads):
|
| 138 |
+
super().__init__()
|
| 139 |
+
self.heads, self.scale = heads, (dim // heads) ** -0.5
|
| 140 |
+
self.relative_position_bias_table = mx.zeros(((2 * ws - 1) ** 2, heads))
|
| 141 |
+
self._index = mx.array(relative_index(ws).reshape(-1))
|
| 142 |
+
self.qkv = nn.Linear(dim, dim * 3)
|
| 143 |
+
self.proj = nn.Linear(dim, dim)
|
| 144 |
+
|
| 145 |
+
def __call__(self, x, mask=None):
|
| 146 |
+
b, n, c = x.shape
|
| 147 |
+
qkv = self.qkv(x).reshape(b, n, 3, self.heads, c // self.heads).transpose(2, 0, 3, 1, 4)
|
| 148 |
+
q, k, v = qkv[0] * self.scale, qkv[1], qkv[2]
|
| 149 |
+
bias = self.relative_position_bias_table[self._index].reshape(n, n, -1).transpose(2, 0, 1)
|
| 150 |
+
attn = (q @ k.transpose(0, 1, 3, 2)) + bias[None].astype(q.dtype)
|
| 151 |
+
if mask is not None:
|
| 152 |
+
nw = mask.shape[0]
|
| 153 |
+
attn = attn.reshape(b // nw, nw, self.heads, n, n) + mask[None, :, None].astype(q.dtype)
|
| 154 |
+
attn = attn.reshape(b, self.heads, n, n)
|
| 155 |
+
attn = mx.softmax(attn, axis=-1, precise=True)
|
| 156 |
+
return self.proj((attn @ v).transpose(0, 2, 1, 3).reshape(b, n, c))
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class Mlp(nn.Module):
|
| 160 |
+
def __init__(self, dim):
|
| 161 |
+
super().__init__()
|
| 162 |
+
self.fc1, self.fc2 = nn.Linear(dim, dim * 4), nn.Linear(dim * 4, dim)
|
| 163 |
+
|
| 164 |
+
def __call__(self, x):
|
| 165 |
+
return self.fc2(nn.gelu(self.fc1(x)))
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class SwinBlock(nn.Module):
|
| 169 |
+
def __init__(self, dim, heads, ws, shift):
|
| 170 |
+
super().__init__()
|
| 171 |
+
self.ws, self.shift = ws, shift
|
| 172 |
+
self.norm1, self.norm2 = nn.LayerNorm(dim), nn.LayerNorm(dim)
|
| 173 |
+
self.attn = WindowAttention(dim, ws, heads)
|
| 174 |
+
self.mlp = Mlp(dim)
|
| 175 |
+
|
| 176 |
+
def __call__(self, x, h, w, mask):
|
| 177 |
+
b, L, c = x.shape
|
| 178 |
+
ws, s = self.ws, self.shift
|
| 179 |
+
y = self.norm1(x).reshape(b, h, w, c)
|
| 180 |
+
pr, pb = (ws - w % ws) % ws, (ws - h % ws) % ws
|
| 181 |
+
if pr or pb:
|
| 182 |
+
y = mx.pad(y, [(0, 0), (0, pb), (0, pr), (0, 0)])
|
| 183 |
+
hp, wp = h + pb, w + pr
|
| 184 |
+
if s:
|
| 185 |
+
y = mx.roll(y, (-s, -s), axis=(1, 2))
|
| 186 |
+
y = window_reverse(self.attn(window_partition(y, ws), mask if s else None), ws, hp, wp)
|
| 187 |
+
if s:
|
| 188 |
+
y = mx.roll(y, (s, s), axis=(1, 2))
|
| 189 |
+
y = y[:, :h, :w].reshape(b, h * w, c)
|
| 190 |
+
x = x + y
|
| 191 |
+
return x + self.mlp(self.norm2(x))
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class PatchMerging(nn.Module):
|
| 195 |
+
def __init__(self, dim):
|
| 196 |
+
super().__init__()
|
| 197 |
+
self.norm = nn.LayerNorm(4 * dim)
|
| 198 |
+
self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
|
| 199 |
+
|
| 200 |
+
def __call__(self, x, h, w):
|
| 201 |
+
b, L, c = x.shape
|
| 202 |
+
x = x.reshape(b, h, w, c)
|
| 203 |
+
if h % 2 or w % 2:
|
| 204 |
+
x = mx.pad(x, [(0, 0), (0, h % 2), (0, w % 2), (0, 0)])
|
| 205 |
+
x = mx.concatenate([x[:, 0::2, 0::2], x[:, 1::2, 0::2], x[:, 0::2, 1::2], x[:, 1::2, 1::2]], -1)
|
| 206 |
+
return self.reduction(self.norm(x.reshape(b, -1, 4 * c)))
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
class SwinLayer(nn.Module):
|
| 210 |
+
def __init__(self, dim, depth, heads, ws, down):
|
| 211 |
+
super().__init__()
|
| 212 |
+
self.ws = ws
|
| 213 |
+
self.blocks = [SwinBlock(dim, heads, ws, 0 if i % 2 == 0 else ws // 2) for i in range(depth)]
|
| 214 |
+
if down:
|
| 215 |
+
self.downsample = PatchMerging(dim)
|
| 216 |
+
self._masks = {}
|
| 217 |
+
|
| 218 |
+
def __call__(self, x, h, w):
|
| 219 |
+
ws = self.ws
|
| 220 |
+
hp, wp = -(-h // ws) * ws, -(-w // ws) * ws
|
| 221 |
+
if (hp, wp) not in self._masks:
|
| 222 |
+
self._masks[(hp, wp)] = mx.array(shift_mask(hp, wp, ws, ws // 2))
|
| 223 |
+
mask = self._masks[(hp, wp)]
|
| 224 |
+
for blk in self.blocks:
|
| 225 |
+
x = blk(x, h, w, mask)
|
| 226 |
+
if "downsample" in self:
|
| 227 |
+
return x, self.downsample(x, h, w), (h + 1) // 2, (w + 1) // 2
|
| 228 |
+
return x, x, h, w
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
class PatchEmbed(nn.Module):
|
| 232 |
+
def __init__(self, dim):
|
| 233 |
+
super().__init__()
|
| 234 |
+
self.proj = nn.Conv2d(3, dim, 4, stride=4)
|
| 235 |
+
self.norm = nn.LayerNorm(dim)
|
| 236 |
+
|
| 237 |
+
def __call__(self, x):
|
| 238 |
+
b, h, w, _ = x.shape
|
| 239 |
+
if w % 4 or h % 4:
|
| 240 |
+
x = mx.pad(x, [(0, 0), (0, (4 - h % 4) % 4), (0, (4 - w % 4) % 4), (0, 0)])
|
| 241 |
+
return self.norm(self.proj(x))
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
class Swin(nn.Module):
|
| 245 |
+
def __init__(self, embed_dim, depths, num_heads, window_size):
|
| 246 |
+
super().__init__()
|
| 247 |
+
self.patch_embed = PatchEmbed(embed_dim)
|
| 248 |
+
self.dims = [embed_dim * 2 ** i for i in range(4)]
|
| 249 |
+
self.layers = [SwinLayer(self.dims[i], depths[i], num_heads[i], window_size, i < 3) for i in range(4)]
|
| 250 |
+
for i, d in enumerate(self.dims):
|
| 251 |
+
setattr(self, f"norm{i}", nn.LayerNorm(d))
|
| 252 |
+
|
| 253 |
+
def __call__(self, x):
|
| 254 |
+
x = self.patch_embed(x)
|
| 255 |
+
b, h, w, c = x.shape
|
| 256 |
+
x = x.reshape(b, h * w, c)
|
| 257 |
+
outs = []
|
| 258 |
+
for i, layer in enumerate(self.layers):
|
| 259 |
+
xo, x, nh, nw = layer(x, h, w)
|
| 260 |
+
outs.append(getattr(self, f"norm{i}")(xo).reshape(b, h, w, self.dims[i]))
|
| 261 |
+
h, w = nh, nw
|
| 262 |
+
return outs
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
# ------------------------------------------------------------------------------------------------ decoder
|
| 266 |
+
|
| 267 |
+
class DeformConv(nn.Module):
|
| 268 |
+
def __init__(self, cin, cout, k):
|
| 269 |
+
super().__init__()
|
| 270 |
+
self.k = k
|
| 271 |
+
self.offset_conv = nn.Conv2d(cin, 2 * k * k, k, padding=k // 2)
|
| 272 |
+
self.modulator_conv = nn.Conv2d(cin, k * k, k, padding=k // 2)
|
| 273 |
+
self.regular_conv = nn.Conv2d(cin, cout, k, padding=k // 2) # its weight (BatchNorm folded in)
|
| 274 |
+
|
| 275 |
+
def __call__(self, x):
|
| 276 |
+
off = self.offset_conv(x)
|
| 277 |
+
mask = 2 * mx.sigmoid(self.modulator_conv(x))
|
| 278 |
+
return deform_conv(x, off, mask, self.regular_conv.weight, self.regular_conv.bias, self.k)
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
class ASPPDeformable(nn.Module):
|
| 282 |
+
def __init__(self, cin, mid=256, sizes=(1, 3, 7)):
|
| 283 |
+
super().__init__()
|
| 284 |
+
self.aspp1 = DeformConv(cin, mid, 1)
|
| 285 |
+
self.aspp_deforms = [DeformConv(cin, mid, k) for k in sizes]
|
| 286 |
+
self.gap_conv = nn.Conv2d(cin, mid, 1)
|
| 287 |
+
self.conv1 = nn.Conv2d(mid * (2 + len(sizes)), cin, 1)
|
| 288 |
+
|
| 289 |
+
def __call__(self, x):
|
| 290 |
+
b, h, w, _ = x.shape
|
| 291 |
+
parts = [nn.relu(self.aspp1(x))] + [nn.relu(d(x)) for d in self.aspp_deforms]
|
| 292 |
+
g = x.astype(mx.float32).mean(axis=(1, 2), keepdims=True).astype(x.dtype) # fp16 sums overflow
|
| 293 |
+
g = nn.relu(self.gap_conv(g))
|
| 294 |
+
parts.append(mx.broadcast_to(g, (b, h, w, g.shape[-1])))
|
| 295 |
+
return nn.relu(self.conv1(mx.concatenate(parts, -1)))
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
class DecBlk(nn.Module):
|
| 299 |
+
def __init__(self, cin, cout, inter=64):
|
| 300 |
+
super().__init__()
|
| 301 |
+
self.conv_in = nn.Conv2d(cin, inter, 3, padding=1)
|
| 302 |
+
self.dec_att = ASPPDeformable(inter)
|
| 303 |
+
self.conv_out = nn.Conv2d(inter, cout, 3, padding=1)
|
| 304 |
+
|
| 305 |
+
def __call__(self, x):
|
| 306 |
+
return self.conv_out(self.dec_att(nn.relu(self.conv_in(x))))
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
class SimpleConvs(nn.Module):
|
| 310 |
+
def __init__(self, cin, cout, inter=64):
|
| 311 |
+
super().__init__()
|
| 312 |
+
self.conv1 = nn.Conv2d(cin, inter, 3, padding=1)
|
| 313 |
+
self.conv_out = nn.Conv2d(inter, cout, 3, padding=1)
|
| 314 |
+
|
| 315 |
+
def __call__(self, x):
|
| 316 |
+
return self.conv_out(self.conv1(x))
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
class Decoder(nn.Module):
|
| 320 |
+
def __init__(self, ch):
|
| 321 |
+
super().__init__()
|
| 322 |
+
self.ipt_blk5 = SimpleConvs(2 ** 10 * 3, ch[0] // 8)
|
| 323 |
+
self.ipt_blk4 = SimpleConvs(2 ** 8 * 3, ch[0] // 8)
|
| 324 |
+
self.ipt_blk3 = SimpleConvs(2 ** 6 * 3, ch[1] // 8)
|
| 325 |
+
self.ipt_blk2 = SimpleConvs(2 ** 4 * 3, ch[2] // 8)
|
| 326 |
+
self.ipt_blk1 = SimpleConvs(3, ch[3] // 8)
|
| 327 |
+
self.decoder_block4 = DecBlk(ch[0] + ch[0] // 8, ch[1])
|
| 328 |
+
self.decoder_block3 = DecBlk(ch[1] + ch[0] // 8, ch[2])
|
| 329 |
+
self.decoder_block2 = DecBlk(ch[2] + ch[1] // 8, ch[3])
|
| 330 |
+
self.decoder_block1 = DecBlk(ch[3] + ch[2] // 8, ch[3] // 2)
|
| 331 |
+
self.conv_out1 = nn.Conv2d(ch[3] // 2 + ch[3] // 8, 1, 1)
|
| 332 |
+
self.lateral_block4 = nn.Conv2d(ch[1], ch[1], 1)
|
| 333 |
+
self.lateral_block3 = nn.Conv2d(ch[2], ch[2], 1)
|
| 334 |
+
self.lateral_block2 = nn.Conv2d(ch[3], ch[3], 1)
|
| 335 |
+
for i, c in ((4, ch[1]), (3, ch[2]), (2, ch[3])):
|
| 336 |
+
setattr(self, f"gdt_convs_{i}", nn.Conv2d(c, 16, 3, padding=1))
|
| 337 |
+
setattr(self, f"gdt_attn_{i}", nn.Conv2d(16, 1, 1))
|
| 338 |
+
|
| 339 |
+
def gdt(self, i, p):
|
| 340 |
+
return p * mx.sigmoid(getattr(self, f"gdt_attn_{i}")(nn.relu(getattr(self, f"gdt_convs_{i}")(p))))
|
| 341 |
+
|
| 342 |
+
def __call__(self, x, x1, x2, x3, x4):
|
| 343 |
+
up = lambda a, ref: resize(a, ref.shape[1:3], True)
|
| 344 |
+
x4 = mx.concatenate([x4, self.ipt_blk5(to_patches(x, x4.shape[1:3]))], -1)
|
| 345 |
+
p4 = self.gdt(4, self.decoder_block4(x4))
|
| 346 |
+
p3 = up(p4, x3) + self.lateral_block4(x3)
|
| 347 |
+
p3 = mx.concatenate([p3, self.ipt_blk4(to_patches(x, p3.shape[1:3]))], -1)
|
| 348 |
+
p3 = self.gdt(3, self.decoder_block3(p3))
|
| 349 |
+
p2 = up(p3, x2) + self.lateral_block3(x2)
|
| 350 |
+
p2 = mx.concatenate([p2, self.ipt_blk3(to_patches(x, p2.shape[1:3]))], -1)
|
| 351 |
+
p2 = self.gdt(2, self.decoder_block2(p2))
|
| 352 |
+
p1 = up(p2, x1) + self.lateral_block2(x1)
|
| 353 |
+
p1 = mx.concatenate([p1, self.ipt_blk2(to_patches(x, p1.shape[1:3]))], -1)
|
| 354 |
+
p1 = up(self.decoder_block1(p1), x)
|
| 355 |
+
p1 = mx.concatenate([p1, self.ipt_blk1(x)], -1)
|
| 356 |
+
return self.conv_out1(p1)
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
class Model(nn.Module):
|
| 360 |
+
def __init__(self, config: dict = CONFIG):
|
| 361 |
+
super().__init__()
|
| 362 |
+
sw = SWIN[config["backbone"]]
|
| 363 |
+
self.size = config["input_size"]
|
| 364 |
+
self.bb = Swin(**sw)
|
| 365 |
+
ch = [d * 2 for d in self.bb.dims[::-1]] # mul_scl_ipt = "cat"
|
| 366 |
+
cxt = ch[1:][::-1]
|
| 367 |
+
self.squeeze_module = DecBlk(ch[0] + sum(cxt), ch[0])
|
| 368 |
+
self.decoder = Decoder(ch)
|
| 369 |
+
|
| 370 |
+
def __call__(self, x):
|
| 371 |
+
"""x: (1, S, S, 3) ImageNet-normalized -> (1, S, S, 1) logits."""
|
| 372 |
+
b, h, w, _ = x.shape
|
| 373 |
+
f = self.bb(x)
|
| 374 |
+
g = self.bb(resize(x, (h // 2, w // 2), True))
|
| 375 |
+
f = [mx.concatenate([a, resize(c, a.shape[1:3], True)], -1) for a, c in zip(f, g)]
|
| 376 |
+
x1, x2, x3, x4 = f
|
| 377 |
+
x4 = mx.concatenate([resize(x1, x4.shape[1:3], True), resize(x2, x4.shape[1:3], True),
|
| 378 |
+
resize(x3, x4.shape[1:3], True), x4], -1)
|
| 379 |
+
x4 = self.squeeze_module(x4)
|
| 380 |
+
return self.decoder(x, x1, x2, x3, x4)
|
| 381 |
+
|
| 382 |
+
|
| 383 |
+
def load(folder) -> Model:
|
| 384 |
+
folder = Path(folder)
|
| 385 |
+
config = json.loads((folder / "config.json").read_text())
|
| 386 |
+
model = Model(config)
|
| 387 |
+
q = config.get("quantization")
|
| 388 |
+
if q:
|
| 389 |
+
nn.quantize(model, group_size=q["group_size"], bits=q["bits"], class_predicate=quantizable)
|
| 390 |
+
model.load_weights(str(folder / "model.safetensors"), strict=True)
|
| 391 |
+
mx.eval(model.parameters())
|
| 392 |
+
return model
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
def dtype(model: Model):
|
| 396 |
+
return model.decoder.conv_out1.weight.dtype
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
def predict(model: Model, rgb: np.ndarray) -> np.ndarray:
|
| 400 |
+
"""HxWx3 uint8 -> HxW float32 foreground probability: resized to the model size (bilinear, as PIL in the
|
| 401 |
+
original handler) and back."""
|
| 402 |
+
from PIL import Image
|
| 403 |
+
h, w, _ = rgb.shape
|
| 404 |
+
s = model.size
|
| 405 |
+
x = np.asarray(Image.fromarray(rgb).resize((s, s), Image.BILINEAR), np.float32) / 255.0
|
| 406 |
+
x = mx.array(((x - MEAN) / STD)[None]).astype(dtype(model))
|
| 407 |
+
y = mx.sigmoid(model(x).astype(mx.float32))
|
| 408 |
+
return np.array(resize(y, (h, w), True))[0, :, :, 0]
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def matte(model: Model, rgb: np.ndarray) -> np.ndarray:
|
| 412 |
+
return (np.clip(predict(model, rgb), 0, 1) * 255).round().astype(np.uint8)
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
# ------------------------------------------------------------------------------------------------ conversion
|
| 416 |
+
|
| 417 |
+
def _fold(sd, conv, bn):
|
| 418 |
+
w = sd[conv + ".weight"].astype(np.float64)
|
| 419 |
+
b = sd.get(conv + ".bias", np.zeros(w.shape[0])).astype(np.float64)
|
| 420 |
+
if bn is not None:
|
| 421 |
+
g = sd[bn + ".weight"] / np.sqrt(sd[bn + ".running_var"].astype(np.float64) + 1e-5)
|
| 422 |
+
w = w * g[:, None, None, None]
|
| 423 |
+
b = (b - sd[bn + ".running_mean"]) * g + sd[bn + ".bias"]
|
| 424 |
+
return w.astype(np.float32).transpose(0, 2, 3, 1), b.astype(np.float32)
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
def convert(source: Path) -> dict:
|
| 428 |
+
"""runs/source/model.safetensors -> MLX names: BatchNorms folded, Sequential indices renamed, buffers and the
|
| 429 |
+
training-only heads (conv_ms_spvn_*, gdt_convs_pred_*) dropped."""
|
| 430 |
+
from safetensors.numpy import load_file
|
| 431 |
+
sd = load_file(str(Path(source) / "model.safetensors"))
|
| 432 |
+
out = {}
|
| 433 |
+
for k, v in sd.items():
|
| 434 |
+
if k.startswith("bb."):
|
| 435 |
+
if k.endswith("relative_position_index"):
|
| 436 |
+
continue
|
| 437 |
+
out[k] = v.transpose(0, 2, 3, 1) if v.ndim == 4 else v
|
| 438 |
+
blocks = sorted({k.split(".dec_att.")[0] for k in sd if ".dec_att." in k})
|
| 439 |
+
for blk in blocks: # decoder.decoder_blockN, squeeze_module.0
|
| 440 |
+
dst = "squeeze_module" if blk == "squeeze_module.0" else blk
|
| 441 |
+
out[dst + ".conv_in.weight"], out[dst + ".conv_in.bias"] = _fold(sd, blk + ".conv_in", blk + ".bn_in")
|
| 442 |
+
out[dst + ".conv_out.weight"], out[dst + ".conv_out.bias"] = _fold(sd, blk + ".conv_out", blk + ".bn_out")
|
| 443 |
+
a = blk + ".dec_att"
|
| 444 |
+
for src_m, dst_m in [(a + ".aspp1", dst + ".dec_att.aspp1")] + [
|
| 445 |
+
(f"{a}.aspp_deforms.{i}", f"{dst}.dec_att.aspp_deforms.{i}") for i in range(3)]:
|
| 446 |
+
for c in ("offset_conv", "modulator_conv"):
|
| 447 |
+
out[f"{dst_m}.{c}.weight"], out[f"{dst_m}.{c}.bias"] = _fold(sd, f"{src_m}.atrous_conv.{c}", None)
|
| 448 |
+
out[f"{dst_m}.regular_conv.weight"], out[f"{dst_m}.regular_conv.bias"] = _fold(
|
| 449 |
+
sd, f"{src_m}.atrous_conv.regular_conv", f"{src_m}.bn")
|
| 450 |
+
out[dst + ".dec_att.gap_conv.weight"], out[dst + ".dec_att.gap_conv.bias"] = _fold(
|
| 451 |
+
sd, a + ".global_avg_pool.1", a + ".global_avg_pool.2")
|
| 452 |
+
out[dst + ".dec_att.conv1.weight"], out[dst + ".dec_att.conv1.bias"] = _fold(sd, a + ".conv1", a + ".bn1")
|
| 453 |
+
d = "decoder."
|
| 454 |
+
for i in range(1, 6):
|
| 455 |
+
for c in ("conv1", "conv_out"):
|
| 456 |
+
out[f"{d}ipt_blk{i}.{c}.weight"], out[f"{d}ipt_blk{i}.{c}.bias"] = _fold(sd, f"{d}ipt_blk{i}.{c}", None)
|
| 457 |
+
for i in (2, 3, 4):
|
| 458 |
+
out[f"{d}lateral_block{i}.weight"], out[f"{d}lateral_block{i}.bias"] = _fold(sd, f"{d}lateral_block{i}.conv", None)
|
| 459 |
+
out[f"{d}gdt_convs_{i}.weight"], out[f"{d}gdt_convs_{i}.bias"] = _fold(sd, f"{d}gdt_convs_{i}.0", f"{d}gdt_convs_{i}.1")
|
| 460 |
+
out[f"{d}gdt_attn_{i}.weight"], out[f"{d}gdt_attn_{i}.bias"] = _fold(sd, f"{d}gdt_convs_attn_{i}.0", None)
|
| 461 |
+
out[d + "conv_out1.weight"], out[d + "conv_out1.bias"] = _fold(sd, d + "conv_out1.0", None)
|
| 462 |
+
return out
|
4bit/model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:dde1b2de46ffdb3e498d8594e4eb874198dc2d7cf31018df14786a86e414224a
|
| 3 |
+
size 49435919
|