Instructions to use moonbox-dev/BEN2-MLX with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use moonbox-dev/BEN2-MLX with MLX:
# Download the model from the Hub pip install huggingface_hub[hf_xet] hf download moonbox-dev/BEN2-MLX --local-dir BEN2-MLX
- BEN2
How to use moonbox-dev/BEN2-MLX with BEN2:
import requests from PIL import Image from ben2 import AutoModel url = "https://huggingface.co/datasets/mishig/sample_images/resolve/main/teapot.jpg" image = Image.open(requests.get(url, stream=True).raw) model = AutoModel.from_pretrained("moonbox-dev/BEN2-MLX") model.to("cuda").eval() foreground = model.inference(image) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- Atomic Chat
bf16 build of BEN2 Base
Browse files- bf16/config.json +20 -0
- bf16/mlx_model.py +488 -0
- bf16/model.safetensors +3 -0
bf16/config.json
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"model_type": "ben2",
|
| 3 |
+
"input_size": 1024,
|
| 4 |
+
"embed_dim": 128,
|
| 5 |
+
"depths": [
|
| 6 |
+
2,
|
| 7 |
+
2,
|
| 8 |
+
18,
|
| 9 |
+
2
|
| 10 |
+
],
|
| 11 |
+
"num_heads": [
|
| 12 |
+
4,
|
| 13 |
+
8,
|
| 14 |
+
16,
|
| 15 |
+
32
|
| 16 |
+
],
|
| 17 |
+
"window_size": 12,
|
| 18 |
+
"emb_dim": 128,
|
| 19 |
+
"precision": "bf16"
|
| 20 |
+
}
|
bf16/mlx_model.py
ADDED
|
@@ -0,0 +1,488 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""BEN2 Base (PramaLLC/BEN2, MIT) in MLX: a port of the Hub repo's `BEN2.py` (`BEN_Base`: Swin-B on four 512 px
|
| 2 |
+
crops plus the whole image at 512 px, MCLM / MCRM cross-attention decoder, shallow full-resolution branch).
|
| 3 |
+
|
| 4 |
+
import mlx_model
|
| 5 |
+
model = mlx_model.load("bf16") # a folder with config.json + model.safetensors
|
| 6 |
+
alpha = mlx_model.matte(model, rgb) # rgb: HxWx3 uint8 -> HxW uint8 alpha (255 = foreground)
|
| 7 |
+
|
| 8 |
+
Runs on its own next to its weights (mlx, numpy, pillow). NHWC throughout; InstanceNorm and the poolings are taken
|
| 9 |
+
in float32. Quantized builds (8bit / 6bit / 4bit) quantize the linears (Swin, attention, feed-forward); the
|
| 10 |
+
convolutions stay bf16. `refine_foreground` (the original's optional colour decontamination) isn't ported.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import json
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import mlx.core as mx
|
| 19 |
+
import mlx.nn as nn
|
| 20 |
+
import numpy as np
|
| 21 |
+
|
| 22 |
+
CONFIG = {"model_type": "ben2", "input_size": 1024, "embed_dim": 128, "depths": [2, 2, 18, 2],
|
| 23 |
+
"num_heads": [4, 8, 16, 32], "window_size": 12, "emb_dim": 128}
|
| 24 |
+
PRECISIONS = ["bf16", "fp16", "8bit", "6bit", "4bit"]
|
| 25 |
+
MEAN, STD = np.array([0.485, 0.456, 0.406], np.float32), np.array([0.229, 0.224, 0.225], np.float32)
|
| 26 |
+
GROUP = 64
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def quantizable(path: str, module) -> bool:
|
| 30 |
+
return isinstance(module, nn.Linear) and module.weight.shape[-1] % GROUP == 0
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# ------------------------------------------------------------------------------------------------ resize
|
| 34 |
+
|
| 35 |
+
def resize(x, size, align_corners: bool):
|
| 36 |
+
"""torch F.interpolate(mode="bilinear") for NHWC (no antialiasing)."""
|
| 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 |
+
if align_corners:
|
| 44 |
+
s = np.arange(n_out, dtype=np.float64) * ((n_in - 1) / (n_out - 1) if n_out > 1 else 0.0)
|
| 45 |
+
else:
|
| 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 |
+
i1 = np.minimum(i0 + 1, n_in - 1)
|
| 49 |
+
return mx.array(i0), mx.array(i1), mx.array((s - i0).astype(np.float32))
|
| 50 |
+
|
| 51 |
+
y0, y1, fy = axis(h, oh)
|
| 52 |
+
x0, x1, fx = axis(w, ow)
|
| 53 |
+
fy = fy.astype(x.dtype)[None, :, None, None]
|
| 54 |
+
fx = fx.astype(x.dtype)[None, None, :, None]
|
| 55 |
+
top, bot = x[:, y0], x[:, y1]
|
| 56 |
+
top = top[:, :, x0] * (1 - fx) + top[:, :, x1] * fx
|
| 57 |
+
bot = bot[:, :, x0] * (1 - fx) + bot[:, :, x1] * fx
|
| 58 |
+
return top * (1 - fy) + bot * fy
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# ------------------------------------------------------------------------------------------------ Swin v1
|
| 63 |
+
|
| 64 |
+
def window_partition(x, ws):
|
| 65 |
+
b, h, w, c = x.shape
|
| 66 |
+
x = x.reshape(b, h // ws, ws, w // ws, ws, c).transpose(0, 1, 3, 2, 4, 5)
|
| 67 |
+
return x.reshape(-1, ws * ws, c)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def window_reverse(win, ws, h, w):
|
| 71 |
+
c = win.shape[-1]
|
| 72 |
+
b = win.shape[0] // ((h // ws) * (w // ws))
|
| 73 |
+
x = win.reshape(b, h // ws, w // ws, ws, ws, c).transpose(0, 1, 3, 2, 4, 5)
|
| 74 |
+
return x.reshape(b, h, w, c)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def relative_index(ws: int) -> np.ndarray:
|
| 78 |
+
coords = np.stack(np.meshgrid(np.arange(ws), np.arange(ws), indexing="ij")).reshape(2, -1)
|
| 79 |
+
rel = (coords[:, :, None] - coords[:, None, :]).transpose(1, 2, 0) + (ws - 1)
|
| 80 |
+
return rel[:, :, 0] * (2 * ws - 1) + rel[:, :, 1]
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def shift_mask(hp: int, wp: int, ws: int, shift: int) -> np.ndarray:
|
| 84 |
+
img = np.zeros((1, hp, wp, 1), np.float32)
|
| 85 |
+
cnt = 0
|
| 86 |
+
for hs in (slice(0, -ws), slice(-ws, -shift), slice(-shift, None)):
|
| 87 |
+
for wsl in (slice(0, -ws), slice(-ws, -shift), slice(-shift, None)):
|
| 88 |
+
img[:, hs, wsl, :] = cnt
|
| 89 |
+
cnt += 1
|
| 90 |
+
m = img.reshape(1, hp // ws, ws, wp // ws, ws, 1).transpose(0, 1, 3, 2, 4, 5).reshape(-1, ws * ws)
|
| 91 |
+
m = m[:, None, :] - m[:, :, None]
|
| 92 |
+
return np.where(m != 0, -100.0, 0.0).astype(np.float32)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class WindowAttention(nn.Module):
|
| 96 |
+
def __init__(self, dim, ws, heads):
|
| 97 |
+
super().__init__()
|
| 98 |
+
self.heads, self.scale = heads, (dim // heads) ** -0.5
|
| 99 |
+
self.relative_position_bias_table = mx.zeros(((2 * ws - 1) ** 2, heads))
|
| 100 |
+
self._index = mx.array(relative_index(ws).reshape(-1))
|
| 101 |
+
self.qkv = nn.Linear(dim, dim * 3)
|
| 102 |
+
self.proj = nn.Linear(dim, dim)
|
| 103 |
+
|
| 104 |
+
def __call__(self, x, mask=None):
|
| 105 |
+
b, n, c = x.shape
|
| 106 |
+
qkv = self.qkv(x).reshape(b, n, 3, self.heads, c // self.heads).transpose(2, 0, 3, 1, 4)
|
| 107 |
+
q, k, v = qkv[0] * self.scale, qkv[1], qkv[2]
|
| 108 |
+
bias = self.relative_position_bias_table[self._index].reshape(n, n, -1).transpose(2, 0, 1)
|
| 109 |
+
attn = (q @ k.transpose(0, 1, 3, 2)) + bias[None].astype(q.dtype)
|
| 110 |
+
if mask is not None:
|
| 111 |
+
nw = mask.shape[0]
|
| 112 |
+
attn = attn.reshape(b // nw, nw, self.heads, n, n) + mask[None, :, None].astype(q.dtype)
|
| 113 |
+
attn = attn.reshape(b, self.heads, n, n)
|
| 114 |
+
attn = mx.softmax(attn, axis=-1, precise=True)
|
| 115 |
+
return self.proj((attn @ v).transpose(0, 2, 1, 3).reshape(b, n, c))
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class Mlp(nn.Module):
|
| 119 |
+
def __init__(self, dim):
|
| 120 |
+
super().__init__()
|
| 121 |
+
self.fc1, self.fc2 = nn.Linear(dim, dim * 4), nn.Linear(dim * 4, dim)
|
| 122 |
+
|
| 123 |
+
def __call__(self, x):
|
| 124 |
+
return self.fc2(nn.gelu(self.fc1(x)))
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class SwinBlock(nn.Module):
|
| 128 |
+
def __init__(self, dim, heads, ws, shift):
|
| 129 |
+
super().__init__()
|
| 130 |
+
self.ws, self.shift = ws, shift
|
| 131 |
+
self.norm1, self.norm2 = nn.LayerNorm(dim), nn.LayerNorm(dim)
|
| 132 |
+
self.attn = WindowAttention(dim, ws, heads)
|
| 133 |
+
self.mlp = Mlp(dim)
|
| 134 |
+
|
| 135 |
+
def __call__(self, x, h, w, mask):
|
| 136 |
+
b, L, c = x.shape
|
| 137 |
+
ws, s = self.ws, self.shift
|
| 138 |
+
y = self.norm1(x).reshape(b, h, w, c)
|
| 139 |
+
pr, pb = (ws - w % ws) % ws, (ws - h % ws) % ws
|
| 140 |
+
if pr or pb:
|
| 141 |
+
y = mx.pad(y, [(0, 0), (0, pb), (0, pr), (0, 0)])
|
| 142 |
+
hp, wp = h + pb, w + pr
|
| 143 |
+
if s:
|
| 144 |
+
y = mx.roll(y, (-s, -s), axis=(1, 2))
|
| 145 |
+
y = window_reverse(self.attn(window_partition(y, ws), mask if s else None), ws, hp, wp)
|
| 146 |
+
if s:
|
| 147 |
+
y = mx.roll(y, (s, s), axis=(1, 2))
|
| 148 |
+
y = y[:, :h, :w].reshape(b, h * w, c)
|
| 149 |
+
x = x + y
|
| 150 |
+
return x + self.mlp(self.norm2(x))
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
class PatchMerging(nn.Module):
|
| 154 |
+
def __init__(self, dim):
|
| 155 |
+
super().__init__()
|
| 156 |
+
self.norm = nn.LayerNorm(4 * dim)
|
| 157 |
+
self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False)
|
| 158 |
+
|
| 159 |
+
def __call__(self, x, h, w):
|
| 160 |
+
b, L, c = x.shape
|
| 161 |
+
x = x.reshape(b, h, w, c)
|
| 162 |
+
if h % 2 or w % 2:
|
| 163 |
+
x = mx.pad(x, [(0, 0), (0, h % 2), (0, w % 2), (0, 0)])
|
| 164 |
+
x = mx.concatenate([x[:, 0::2, 0::2], x[:, 1::2, 0::2], x[:, 0::2, 1::2], x[:, 1::2, 1::2]], -1)
|
| 165 |
+
return self.reduction(self.norm(x.reshape(b, -1, 4 * c)))
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
class SwinLayer(nn.Module):
|
| 169 |
+
def __init__(self, dim, depth, heads, ws, down):
|
| 170 |
+
super().__init__()
|
| 171 |
+
self.ws = ws
|
| 172 |
+
self.blocks = [SwinBlock(dim, heads, ws, 0 if i % 2 == 0 else ws // 2) for i in range(depth)]
|
| 173 |
+
if down:
|
| 174 |
+
self.downsample = PatchMerging(dim)
|
| 175 |
+
self._masks = {}
|
| 176 |
+
|
| 177 |
+
def __call__(self, x, h, w):
|
| 178 |
+
ws = self.ws
|
| 179 |
+
hp, wp = -(-h // ws) * ws, -(-w // ws) * ws
|
| 180 |
+
if (hp, wp) not in self._masks:
|
| 181 |
+
self._masks[(hp, wp)] = mx.array(shift_mask(hp, wp, ws, ws // 2))
|
| 182 |
+
mask = self._masks[(hp, wp)]
|
| 183 |
+
for blk in self.blocks:
|
| 184 |
+
x = blk(x, h, w, mask)
|
| 185 |
+
if "downsample" in self:
|
| 186 |
+
return x, self.downsample(x, h, w), (h + 1) // 2, (w + 1) // 2
|
| 187 |
+
return x, x, h, w
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
class PatchEmbed(nn.Module):
|
| 191 |
+
def __init__(self, dim):
|
| 192 |
+
super().__init__()
|
| 193 |
+
self.proj = nn.Conv2d(3, dim, 4, stride=4)
|
| 194 |
+
self.norm = nn.LayerNorm(dim)
|
| 195 |
+
|
| 196 |
+
def __call__(self, x):
|
| 197 |
+
b, h, w, _ = x.shape
|
| 198 |
+
if w % 4 or h % 4:
|
| 199 |
+
x = mx.pad(x, [(0, 0), (0, (4 - h % 4) % 4), (0, (4 - w % 4) % 4), (0, 0)])
|
| 200 |
+
return self.norm(self.proj(x))
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
class Swin(nn.Module):
|
| 204 |
+
def __init__(self, embed_dim, depths, num_heads, window_size):
|
| 205 |
+
super().__init__()
|
| 206 |
+
self.patch_embed = PatchEmbed(embed_dim)
|
| 207 |
+
self.dims = [embed_dim * 2 ** i for i in range(4)]
|
| 208 |
+
self.layers = [SwinLayer(self.dims[i], depths[i], num_heads[i], window_size, i < 3) for i in range(4)]
|
| 209 |
+
for i, d in enumerate(self.dims):
|
| 210 |
+
setattr(self, f"norm{i}", nn.LayerNorm(d))
|
| 211 |
+
|
| 212 |
+
def __call__(self, x, emb=None):
|
| 213 |
+
x = self.patch_embed(x) if emb is None else emb # BEN2 also uses the embedding itself
|
| 214 |
+
b, h, w, c = x.shape
|
| 215 |
+
x = x.reshape(b, h * w, c)
|
| 216 |
+
outs = []
|
| 217 |
+
for i, layer in enumerate(self.layers):
|
| 218 |
+
xo, x, nh, nw = layer(x, h, w)
|
| 219 |
+
outs.append(getattr(self, f"norm{i}")(xo).reshape(b, h, w, self.dims[i]))
|
| 220 |
+
h, w = nh, nw
|
| 221 |
+
return outs
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
# ------------------------------------------------------------------------------------------------ helpers
|
| 225 |
+
|
| 226 |
+
def nearest(x, size):
|
| 227 |
+
"""F.interpolate(mode="nearest") for NHWC: source index floor(dst * in / out)."""
|
| 228 |
+
b, h, w, c = x.shape
|
| 229 |
+
oh, ow = size
|
| 230 |
+
iy = mx.array(np.minimum((np.arange(oh) * (h / oh)).astype(np.int32), h - 1))
|
| 231 |
+
ix = mx.array(np.minimum((np.arange(ow) * (w / ow)).astype(np.int32), w - 1))
|
| 232 |
+
return x[:, iy][:, :, ix]
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def avg_pool_to(x, size):
|
| 236 |
+
"""F.adaptive_avg_pool2d to a size that divides the input (always the case at 1024 px), in float32."""
|
| 237 |
+
b, h, w, c = x.shape
|
| 238 |
+
oh, ow = size
|
| 239 |
+
assert h % oh == 0 and w % ow == 0, (h, w, size)
|
| 240 |
+
y = x.astype(mx.float32).reshape(b, oh, h // oh, ow, w // ow, c).mean(axis=(2, 4))
|
| 241 |
+
return y.astype(x.dtype)
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
def to_patches(x):
|
| 245 |
+
"""'b c (hg h) (wg w) -> (hg wg b) c h w' with hg = wg = 2, NHWC."""
|
| 246 |
+
b, H, W, c = x.shape
|
| 247 |
+
x = x.reshape(b, 2, H // 2, 2, W // 2, c).transpose(1, 3, 0, 2, 4, 5)
|
| 248 |
+
return x.reshape(4 * b, H // 2, W // 2, c)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def from_patches(x):
|
| 252 |
+
"""'(hg wg b) c h w -> b c (hg h) (wg w)' with hg = wg = 2, NHWC."""
|
| 253 |
+
n, h, w, c = x.shape
|
| 254 |
+
b = n // 4
|
| 255 |
+
x = x.reshape(2, 2, b, h, w, c).transpose(2, 0, 3, 1, 4, 5)
|
| 256 |
+
return x.reshape(b, 2 * h, 2 * w, c)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def sine_pos(h: int, w: int, d: int) -> np.ndarray:
|
| 260 |
+
"""PositionEmbeddingSine(num_pos_feats = d // 2, normalize=True) as (h * w, d) tokens."""
|
| 261 |
+
n = d // 2
|
| 262 |
+
y = np.arange(1, h + 1, dtype=np.float32)[:, None].repeat(w, 1)
|
| 263 |
+
x = np.arange(1, w + 1, dtype=np.float32)[None, :].repeat(h, 0)
|
| 264 |
+
scale, eps = 2 * np.pi, 1e-6
|
| 265 |
+
y = (y - 0.5) / (y[-1:, :] + eps) * scale
|
| 266 |
+
x = (x - 0.5) / (x[:, -1:] + eps) * scale
|
| 267 |
+
dim_t = 10000 ** (2 * (np.arange(n, dtype=np.float32) // 2) / n)
|
| 268 |
+
px, py = x[:, :, None] / dim_t, y[:, :, None] / dim_t
|
| 269 |
+
px = np.stack((np.sin(px[:, :, 0::2]), np.cos(px[:, :, 1::2])), axis=3).reshape(h, w, -1)
|
| 270 |
+
py = np.stack((np.sin(py[:, :, 0::2]), np.cos(py[:, :, 1::2])), axis=3).reshape(h, w, -1)
|
| 271 |
+
return np.concatenate((py, px), axis=2).reshape(h * w, d).astype(np.float32)
|
| 272 |
+
|
| 273 |
+
|
| 274 |
+
class InstanceNorm(nn.Module):
|
| 275 |
+
"""nn.InstanceNorm2d(affine=False), statistics in float32."""
|
| 276 |
+
|
| 277 |
+
def __call__(self, x):
|
| 278 |
+
y = x.astype(mx.float32)
|
| 279 |
+
mu = y.mean(axis=(1, 2), keepdims=True)
|
| 280 |
+
var = ((y - mu) ** 2).mean(axis=(1, 2), keepdims=True)
|
| 281 |
+
return ((y - mu) * mx.rsqrt(var + 1e-5)).astype(x.dtype)
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
class CBR(nn.Module):
|
| 285 |
+
"""make_cbr / make_cbg: conv 3x3, InstanceNorm, GELU."""
|
| 286 |
+
|
| 287 |
+
def __init__(self, cin, cout):
|
| 288 |
+
super().__init__()
|
| 289 |
+
self.conv = nn.Conv2d(cin, cout, 3, padding=1)
|
| 290 |
+
self.norm = InstanceNorm()
|
| 291 |
+
|
| 292 |
+
def __call__(self, x):
|
| 293 |
+
return nn.gelu(self.norm(self.conv(x)))
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
class MHA(nn.Module):
|
| 297 |
+
"""nn.MultiheadAttention with one head, batch-first here: q (B, Lq, E), kv (B, Lk, E)."""
|
| 298 |
+
|
| 299 |
+
def __init__(self, d):
|
| 300 |
+
super().__init__()
|
| 301 |
+
self.d = d
|
| 302 |
+
self.in_proj = nn.Linear(d, 3 * d)
|
| 303 |
+
self.out_proj = nn.Linear(d, d)
|
| 304 |
+
|
| 305 |
+
def __call__(self, q, k, v):
|
| 306 |
+
w, b = self.in_proj.weight, self.in_proj.bias
|
| 307 |
+
if "scales" in self.in_proj: # quantized: run the whole projection, take slices
|
| 308 |
+
q = self.in_proj(q)[..., :self.d]
|
| 309 |
+
k = self.in_proj(k)[..., self.d:2 * self.d]
|
| 310 |
+
v = self.in_proj(v)[..., 2 * self.d:]
|
| 311 |
+
else:
|
| 312 |
+
d = self.d
|
| 313 |
+
q = q @ w[:d].T + b[:d]
|
| 314 |
+
k = k @ w[d:2 * d].T + b[d:2 * d]
|
| 315 |
+
v = v @ w[2 * d:].T + b[2 * d:]
|
| 316 |
+
a = mx.softmax((q * self.d ** -0.5) @ k.transpose(0, 2, 1), axis=-1, precise=True)
|
| 317 |
+
return self.out_proj(a @ v)
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
class MCLM(nn.Module):
|
| 321 |
+
def __init__(self, d, pool_ratios=(1, 4, 8)):
|
| 322 |
+
super().__init__()
|
| 323 |
+
self.attention = [MHA(d) for _ in range(5)]
|
| 324 |
+
self.linear1, self.linear2 = nn.Linear(d, 2 * d), nn.Linear(2 * d, d)
|
| 325 |
+
self.linear3, self.linear4 = nn.Linear(d, 2 * d), nn.Linear(2 * d, d)
|
| 326 |
+
self.norm1, self.norm2 = nn.LayerNorm(d), nn.LayerNorm(d)
|
| 327 |
+
self.pool_ratios, self.d = pool_ratios, d
|
| 328 |
+
|
| 329 |
+
def __call__(self, l, g):
|
| 330 |
+
"""l (4, h, w, c) crops, g (1, h, w, c) whole image -> (5, h, w, c)."""
|
| 331 |
+
n, h, w, c = l.shape
|
| 332 |
+
cat = from_patches(l) # (1, 2h, 2w, c)
|
| 333 |
+
pools, poses = [], []
|
| 334 |
+
for r in self.pool_ratios:
|
| 335 |
+
th, tw = round(h / r), round(w / r)
|
| 336 |
+
pools.append(avg_pool_to(cat, (th, tw)).reshape(1, th * tw, c))
|
| 337 |
+
poses.append(sine_pos(th, tw, c))
|
| 338 |
+
pools = mx.concatenate(pools, 1)
|
| 339 |
+
p_pos = mx.array(np.concatenate(poses, 0))[None].astype(l.dtype)
|
| 340 |
+
g_pos = mx.array(sine_pos(h, w, c))[None].astype(l.dtype)
|
| 341 |
+
gt = g.reshape(1, h * w, c)
|
| 342 |
+
gt = self.norm1(gt + self.attention[0](gt + g_pos, pools + p_pos, pools))
|
| 343 |
+
gt = self.norm2(gt + self.linear2(nn.gelu(self.linear1(gt))))
|
| 344 |
+
# each crop attends to its quarter of the whole-image tokens
|
| 345 |
+
gq = gt.reshape(2, h // 2, 2, w // 2, c).transpose(0, 2, 1, 3, 4).reshape(4, (h // 2) * (w // 2), c)
|
| 346 |
+
lt = l.reshape(4, h * w, c)
|
| 347 |
+
lt = lt + mx.concatenate([self.attention[i + 1](lt[i:i + 1], gq[i:i + 1], gq[i:i + 1]) for i in range(4)], 0)
|
| 348 |
+
lt = self.norm1(lt)
|
| 349 |
+
lt = self.norm2(lt + self.linear4(nn.gelu(self.linear3(lt))))
|
| 350 |
+
return mx.concatenate([lt, gt], 0).reshape(5, h, w, c)
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
class MCRM(nn.Module):
|
| 354 |
+
def __init__(self, d, pool_ratios=(2, 4, 8)):
|
| 355 |
+
super().__init__()
|
| 356 |
+
self.attention = [MHA(d) for _ in range(4)]
|
| 357 |
+
self.linear3, self.linear4 = nn.Linear(d, 2 * d), nn.Linear(2 * d, d)
|
| 358 |
+
self.norm1, self.norm2 = nn.LayerNorm(d), nn.LayerNorm(d)
|
| 359 |
+
self.sal_conv = nn.Conv2d(d, 1, 1)
|
| 360 |
+
self.pool_ratios = pool_ratios
|
| 361 |
+
|
| 362 |
+
def __call__(self, x):
|
| 363 |
+
n, h, w, c = x.shape
|
| 364 |
+
loc, glb = x[:4], x[4:]
|
| 365 |
+
pglb = to_patches(glb) # (4, h/2, w/2, c)
|
| 366 |
+
tam = mx.sigmoid(self.sal_conv(glb))
|
| 367 |
+
loc = loc * to_patches(nearest(tam, (2 * h, 2 * w)))
|
| 368 |
+
pools = []
|
| 369 |
+
for r in self.pool_ratios:
|
| 370 |
+
th, tw = round(h / r), round(w / r)
|
| 371 |
+
pools.append(avg_pool_to(pglb, (th, tw)).reshape(4, th * tw, c))
|
| 372 |
+
pools = mx.concatenate(pools, 1)
|
| 373 |
+
lt = loc.reshape(4, h * w, c)
|
| 374 |
+
lt = lt + mx.concatenate([self.attention[i](lt[i:i + 1], pools[i:i + 1], pools[i:i + 1]) for i in range(4)], 0)
|
| 375 |
+
lt = self.norm1(lt)
|
| 376 |
+
lt = self.norm2(lt + self.linear4(nn.gelu(self.linear3(lt))))
|
| 377 |
+
src = lt.reshape(4, h, w, c)
|
| 378 |
+
glb = glb + nearest(from_patches(src), (h, w))
|
| 379 |
+
return mx.concatenate([src, glb], 0)
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
class Head(nn.Module):
|
| 383 |
+
"""insmask_head: conv, IN, GELU, conv, IN, GELU, conv."""
|
| 384 |
+
|
| 385 |
+
def __init__(self, d):
|
| 386 |
+
super().__init__()
|
| 387 |
+
self.c0, self.c3, self.c6 = nn.Conv2d(d, 384, 3, padding=1), nn.Conv2d(384, 384, 3, padding=1), nn.Conv2d(384, d, 3, padding=1)
|
| 388 |
+
self.norm = InstanceNorm()
|
| 389 |
+
|
| 390 |
+
def __call__(self, x):
|
| 391 |
+
x = nn.gelu(self.norm(self.c0(x)))
|
| 392 |
+
x = nn.gelu(self.norm(self.c3(x)))
|
| 393 |
+
return self.c6(x)
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
class Model(nn.Module):
|
| 397 |
+
def __init__(self, config: dict = CONFIG):
|
| 398 |
+
super().__init__()
|
| 399 |
+
d = config["emb_dim"]
|
| 400 |
+
self.size = config["input_size"]
|
| 401 |
+
self.backbone = Swin(config["embed_dim"], config["depths"], config["num_heads"], config["window_size"])
|
| 402 |
+
dims = self.backbone.dims
|
| 403 |
+
self.output5, self.output4 = CBR(dims[3], d), CBR(dims[2], d)
|
| 404 |
+
self.output3, self.output2, self.output1 = CBR(dims[1], d), CBR(dims[0], d), CBR(config["embed_dim"], d)
|
| 405 |
+
self.multifieldcrossatt = MCLM(d)
|
| 406 |
+
self.conv1, self.conv2, self.conv3, self.conv4 = (CBR(d, d) for _ in range(4))
|
| 407 |
+
self.dec_blk1, self.dec_blk2, self.dec_blk3, self.dec_blk4 = (MCRM(d) for _ in range(4))
|
| 408 |
+
self.insmask_head = Head(d)
|
| 409 |
+
self.shallow = nn.Conv2d(3, d, 3, padding=1)
|
| 410 |
+
self.upsample1, self.upsample2 = CBR(d, d), CBR(d, d)
|
| 411 |
+
self.output = nn.Conv2d(d, 1, 3, padding=1)
|
| 412 |
+
|
| 413 |
+
def __call__(self, x):
|
| 414 |
+
"""x: (1, S, S, 3) ImageNet-normalized -> (1, S, S, 1) foreground probability."""
|
| 415 |
+
b, h, w, _ = x.shape
|
| 416 |
+
shallow = self.shallow(x)
|
| 417 |
+
glb = resize(x, (h // 2, w // 2), False)
|
| 418 |
+
inp = mx.concatenate([to_patches(x), glb], 0) # 4 crops + the whole image
|
| 419 |
+
emb = self.backbone.patch_embed(inp)
|
| 420 |
+
f = [emb] + self.backbone(inp, emb)
|
| 421 |
+
e5, e4, e3 = self.output5(f[4]), self.output4(f[3]), self.output3(f[2])
|
| 422 |
+
e2, e1 = self.output2(f[1]), self.output1(f[0])
|
| 423 |
+
up = lambda a, ref: resize(a, ref.shape[1:3], False)
|
| 424 |
+
e5 = self.multifieldcrossatt(e5[:4], e5[4:])
|
| 425 |
+
e4 = self.conv4(self.dec_blk4(e4 + up(e5, e4)))
|
| 426 |
+
e3 = self.conv3(self.dec_blk3(e3 + up(e4, e3)))
|
| 427 |
+
e2 = self.conv2(self.dec_blk2(e2 + up(e3, e2)))
|
| 428 |
+
e1 = self.conv1(self.dec_blk1(e1 + up(e2, e1)))
|
| 429 |
+
out = from_patches(e1[:4])
|
| 430 |
+
out = out + up(e1[4:], out)
|
| 431 |
+
out = self.insmask_head(out)
|
| 432 |
+
out = out + up(shallow, out)
|
| 433 |
+
out = self.upsample1(nearest(out, (2 * out.shape[1], 2 * out.shape[2])))
|
| 434 |
+
out = out + up(shallow, out)
|
| 435 |
+
out = self.upsample2(nearest(out, (2 * out.shape[1], 2 * out.shape[2])))
|
| 436 |
+
return mx.sigmoid(self.output(out).astype(mx.float32))
|
| 437 |
+
|
| 438 |
+
|
| 439 |
+
def load(folder) -> Model:
|
| 440 |
+
folder = Path(folder)
|
| 441 |
+
config = json.loads((folder / "config.json").read_text())
|
| 442 |
+
model = Model(config)
|
| 443 |
+
q = config.get("quantization")
|
| 444 |
+
if q:
|
| 445 |
+
nn.quantize(model, group_size=q["group_size"], bits=q["bits"], class_predicate=quantizable)
|
| 446 |
+
model.load_weights(str(folder / "model.safetensors"), strict=True)
|
| 447 |
+
mx.eval(model.parameters())
|
| 448 |
+
return model
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def predict(model: Model, rgb: np.ndarray) -> np.ndarray:
|
| 452 |
+
"""HxWx3 uint8 -> HxW float32 foreground probability, as BEN2.py before its min-max normalization (LANCZOS
|
| 453 |
+
resize to 1024, ImageNet normalization, bilinear resize of the result back)."""
|
| 454 |
+
from PIL import Image
|
| 455 |
+
h, w, _ = rgb.shape
|
| 456 |
+
s = model.size
|
| 457 |
+
x = np.asarray(Image.fromarray(rgb).resize((s, s), Image.LANCZOS), np.float32) / 255.0
|
| 458 |
+
x = mx.array(((x - MEAN) / STD)[None]).astype(model.shallow.weight.dtype)
|
| 459 |
+
y = model(x)
|
| 460 |
+
return np.array(resize(y, (h, w), False))[0, :, :, 0]
|
| 461 |
+
|
| 462 |
+
|
| 463 |
+
def matte(model: Model, rgb: np.ndarray) -> np.ndarray:
|
| 464 |
+
"""HxW uint8 alpha, min-max normalized like BEN2.py's postprocess_image."""
|
| 465 |
+
p = predict(model, rgb)
|
| 466 |
+
p = (p - p.min()) / max(p.max() - p.min(), 1e-8)
|
| 467 |
+
return (p * 255).astype(np.uint8)
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
def convert(source: Path) -> dict:
|
| 471 |
+
"""runs/source/model.safetensors -> MLX names and layouts (the side outputs, used in training only, dropped)."""
|
| 472 |
+
from safetensors.numpy import load_file
|
| 473 |
+
sd = load_file(str(Path(source) / "model.safetensors"))
|
| 474 |
+
ren = {"insmask_head.0": "insmask_head.c0", "insmask_head.3": "insmask_head.c3", "insmask_head.6": "insmask_head.c6",
|
| 475 |
+
"shallow.0": "shallow", "output.0": "output"}
|
| 476 |
+
out = {}
|
| 477 |
+
for k, v in sd.items():
|
| 478 |
+
if k.startswith("sideout") or k.endswith("relative_position_index"):
|
| 479 |
+
continue
|
| 480 |
+
n = k.replace("in_proj_weight", "in_proj.weight").replace("in_proj_bias", "in_proj.bias")
|
| 481 |
+
for a, b in ren.items():
|
| 482 |
+
if n.startswith(a + "."):
|
| 483 |
+
n = b + n[len(a):]
|
| 484 |
+
parts = n.split(".")
|
| 485 |
+
if len(parts) == 3 and parts[1] == "0" and parts[0][:-1] in ("output", "conv", "upsample"):
|
| 486 |
+
n = f"{parts[0]}.conv.{parts[2]}" # make_cbr Sequential -> CBR.conv
|
| 487 |
+
out[n] = v.transpose(0, 2, 3, 1) if v.ndim == 4 else v
|
| 488 |
+
return out
|
bf16/model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5b8344c88ff8a5f25923881f9891deb3f05737ab827a938706e93cb89f9b68bb
|
| 3 |
+
size 188312212
|