File size: 7,312 Bytes
c6b517a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
"""
Model architecture (MLX). Use with the weights in `mlx/`.

Same I/O contract as the PyTorch and ONNX variants:
Input : RGB float32 [B, 3, 512, 512] in [0, 1] (ImageNet normalization is inside the model).
Output: alpha float32 [B, 1, 512, 512] in [0, 1] in eval mode.
        In train mode it returns a dict with "logit", "coarse" and "aux" (deep supervision).

The network runs channels-last (NHWC) internally, which is MLX's native layout;
the input and output are transposed to/from NCHW at the boundaries.
"""
from pathlib import Path

import mlx.core as mx
import mlx.nn as nn

MLX_DIR = Path(__file__).resolve().parent / "mlx"
DEFAULT_WEIGHTS = MLX_DIR / "model.safetensors"


class AdaptiveAvgPool2d(nn.Module):
    """Parameter-free adaptive average pooling for the PPM branches.

    Exact (no interpolation) because every PPM input is 32x32 and the bins
    (1, 2, 4, 8) divide it evenly.
    """

    def __init__(self, output_size):
        super().__init__()
        self.output_size = output_size

    def __call__(self, x):
        b = self.output_size
        B, H, W, C = x.shape
        return x.reshape(B, b, H // b, b, W // b, C).mean(axis=(2, 4))


def up_to(x, ref):
    """Bilinear upsample (align_corners=False) of x to the spatial size of ref."""
    scale = (ref.shape[1] / x.shape[1], ref.shape[2] / x.shape[2])
    if scale == (1, 1):
        return x
    # MLX interpolation can promote FP16 to FP32; keep the decoder/refiner in
    # the checkpoint precision.
    return nn.Upsample(scale_factor=scale, mode="linear", align_corners=False)(x).astype(x.dtype)


class ConvBNReLU(nn.Sequential):
    """Conv -> BatchNorm -> ReLU (ReLU applied in __call__, no extra keys)."""

    def __init__(self, in_ch, out_ch, k=3):
        super().__init__(
            nn.Conv2d(in_ch, out_ch, k, padding=k // 2, bias=False),
            nn.BatchNorm(out_ch),
        )

    def __call__(self, x):
        return nn.relu(super().__call__(x))


class BasicBlock(nn.Module):
    """ResNet basic block (torchvision layout: conv1, bn1, conv2, bn2, downsample)."""

    def __init__(self, in_ch, out_ch, stride=1):
        super().__init__()
        self.conv1 = nn.Conv2d(in_ch, out_ch, 3, stride=stride, padding=1, bias=False)
        self.bn1 = nn.BatchNorm(out_ch)
        self.conv2 = nn.Conv2d(out_ch, out_ch, 3, padding=1, bias=False)
        self.bn2 = nn.BatchNorm(out_ch)
        self.downsample = (
            nn.Sequential(nn.Conv2d(in_ch, out_ch, 1, stride=stride, bias=False), nn.BatchNorm(out_ch))
            if stride != 1 or in_ch != out_ch
            else None
        )

    def __call__(self, x):
        out = nn.relu(self.bn1(self.conv1(x)))
        out = self.bn2(self.conv2(out))
        identity = x if self.downsample is None else self.downsample(x)
        return nn.relu(out + identity)


class PyramidPooling(nn.Module):
    """Pyramid pooling module (bins 1/2/4/8) + fusion conv. Mirrors `model.py`."""

    def __init__(self, in_ch=256, out_ch=128, bins=(1, 2, 4, 8)):
        super().__init__()
        branch_ch = in_ch // len(bins)
        self.branches = [
            nn.Sequential(AdaptiveAvgPool2d(b), nn.Conv2d(in_ch, branch_ch, 1), nn.ReLU())
            for b in bins
        ]
        self.fuse = ConvBNReLU(in_ch + branch_ch * len(bins), out_ch)

    def __call__(self, x):
        feats = [x] + [up_to(branch(x), x) for branch in self.branches]
        return self.fuse(mx.concatenate(feats, axis=-1))


class DecoderBlock(nn.Module):
    """U-Net decoder block: upsample, concat skip, two ConvBNReLU."""

    def __init__(self, in_ch, skip_ch, out_ch):
        super().__init__()
        self.conv = nn.Sequential(ConvBNReLU(in_ch + skip_ch, out_ch), ConvBNReLU(out_ch, out_ch))

    def __call__(self, x, skip):
        return self.conv(mx.concatenate([up_to(x, skip), skip], axis=-1))


class EdgeRefiner(nn.Module):
    """Full-resolution residual correction of the coarse logit."""

    def __init__(self, ch=16):
        super().__init__()
        self.net = nn.Sequential(
            nn.Conv2d(4, ch, 3, padding=1),
            nn.ReLU(),
            nn.Conv2d(ch, ch, 3, padding=1),
            nn.ReLU(),
            nn.Conv2d(ch, ch, 3, padding=1),
            nn.ReLU(),
            nn.Conv2d(ch, 1, 3, padding=1),
        )

    def __call__(self, rgb, coarse_logit):
        return coarse_logit + self.net(mx.concatenate([rgb, coarse_logit], axis=-1))


class BgRemoveStudent(nn.Module):
    """ResNet18 (through layer3) + PPM + U-Net decoder + EdgeRefiner. ~3.9M parameters."""

    def __init__(self):
        super().__init__()
        self.stem = nn.Sequential(
            nn.Conv2d(3, 64, 7, stride=2, padding=3, bias=False),
            nn.BatchNorm(64),
            nn.ReLU(),
        )
        self.pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)

        self.layer1 = nn.Sequential(BasicBlock(64, 64), BasicBlock(64, 64))
        self.layer2 = nn.Sequential(BasicBlock(64, 128, stride=2), BasicBlock(128, 128))
        self.layer3 = nn.Sequential(BasicBlock(128, 256, stride=2), BasicBlock(256, 256))

        self.ppm = PyramidPooling(256, 128)
        self.dec3 = DecoderBlock(128, 128, 96)
        self.dec2 = DecoderBlock(96, 64, 64)
        self.dec1 = DecoderBlock(64, 64, 32)
        self.head = nn.Conv2d(32, 1, 3, padding=1)
        self.aux_heads = [nn.Conv2d(128, 1, 1), nn.Conv2d(96, 1, 1), nn.Conv2d(64, 1, 1)]
        self.refiner = EdgeRefiner(16)

        # ImageNet normalization buffers (replaced by load_weights).
        self.mean = mx.array([0.485, 0.456, 0.406]).reshape(1, 1, 1, 3)
        self.std = mx.array([0.229, 0.224, 0.225]).reshape(1, 1, 1, 3)
        self.freeze(keys=["mean", "std"], recurse=False)

    def __call__(self, rgb):
        """rgb: RGB float32 [B, 3, 512, 512] in [0, 1].

        Returns alpha float32 [B, 1, 512, 512] in [0, 1] (eval mode), or a dict
        with "logit", "coarse" and "aux" (train mode).
        """
        if rgb.ndim != 4 or rgb.shape[1:] != (3, 512, 512):
            raise ValueError(f"Expected RGB input [batch, 3, 512, 512], got {rgb.shape}")
        rgb_nhwc = rgb.transpose(0, 2, 3, 1).astype(self.stem.layers[0].weight.dtype)
        x = (rgb_nhwc - self.mean) / self.std

        s1 = self.stem(x)
        s2 = self.layer1(self.pool(s1))
        s3 = self.layer2(s2)
        s4 = self.layer3(s3)

        c = self.ppm(s4)
        d3 = self.dec3(c, s3)
        d2 = self.dec2(d3, s2)
        d1 = self.dec1(d2, s1)

        coarse = up_to(self.head(d1), rgb_nhwc)
        logit = self.refiner(rgb_nhwc, coarse)

        if self.training:
            t = lambda a: mx.transpose(a, (0, 3, 1, 2))
            aux = [t(up_to(h(f), rgb_nhwc)) for h, f in zip(self.aux_heads, (c, d3, d2))]
            return {"logit": t(logit), "coarse": t(coarse), "aux": aux}
        return mx.sigmoid(logit.astype(mx.float32)).transpose(0, 3, 1, 2)


def load_model(weights_path=DEFAULT_WEIGHTS):
    """Load the weights (safetensors) and return the model in eval mode."""
    with Path(weights_path).open("rb") as f:
        if f.read(8) == b"version ":
            raise ValueError(f"{weights_path} is a Git LFS pointer. Run `git lfs pull` first.")
    model = BgRemoveStudent()
    model.load_weights(str(weights_path), strict=True)
    return model.eval()