File size: 4,644 Bytes
72e7070
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Model architecture (PyTorch). Only needed if you use the weights in `pytorch/`;
the ONNX files are self-contained.

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).
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.models import resnet18


def up_to(x, ref):
    return F.interpolate(x, size=ref.shape[-2:], mode="bilinear", align_corners=False)


class ConvBNReLU(nn.Sequential):
    def __init__(self, in_ch, out_ch, k=3):
        super().__init__(
            nn.Conv2d(in_ch, out_ch, k, padding=k // 2, bias=False),
            nn.BatchNorm2d(out_ch),
            nn.ReLU(inplace=True),
        )


class PyramidPooling(nn.Module):
    """Global context at the bottleneck (bins 1, 2, 4, 8 divide the 32x32 map exactly)."""

    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.ModuleList(
            nn.Sequential(nn.AdaptiveAvgPool2d(b), nn.Conv2d(in_ch, branch_ch, 1), nn.ReLU(inplace=True))
            for b in bins
        )
        self.fuse = ConvBNReLU(in_ch + branch_ch * len(bins), out_ch)

    def forward(self, x):
        feats = [x] + [up_to(branch(x), x) for branch in self.branches]
        return self.fuse(torch.cat(feats, dim=1))


class DecoderBlock(nn.Module):
    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 forward(self, x, skip):
        return self.conv(torch.cat([up_to(x, skip), skip], dim=1))


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

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

    def forward(self, rgb, coarse_logit):
        return coarse_logit + self.net(torch.cat([rgb, coarse_logit], dim=1))


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

    def __init__(self):
        super().__init__()
        r = resnet18(weights=None)
        self.stem = nn.Sequential(r.conv1, r.bn1, r.relu)   # 1/2,  64
        self.pool = r.maxpool
        self.layer1 = r.layer1                              # 1/4,  64
        self.layer2 = r.layer2                              # 1/8,  128
        self.layer3 = r.layer3                              # 1/16, 256
        self.ppm = PyramidPooling(256, 128)
        self.dec3 = DecoderBlock(128, 128, 96)              # 1/8
        self.dec2 = DecoderBlock(96, 64, 64)                # 1/4
        self.dec1 = DecoderBlock(64, 64, 32)                # 1/2
        self.head = nn.Conv2d(32, 1, 3, padding=1)
        self.aux_heads = nn.ModuleList([nn.Conv2d(128, 1, 1), nn.Conv2d(96, 1, 1), nn.Conv2d(64, 1, 1)])
        self.refiner = EdgeRefiner(16)
        self.register_buffer("mean", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1))
        self.register_buffer("std", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1))

    def forward(self, rgb):
        x = (rgb - 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)
        logit = self.refiner(rgb, coarse)

        if self.training:
            aux = [up_to(h(f), rgb) for h, f in zip(self.aux_heads, (c, d3, d2))]
            return {"logit": logit, "coarse": coarse, "aux": aux}
        return torch.sigmoid(logit)


def load_model(weights_path="pytorch/model.safetensors", device="cpu"):
    """Load the weights (safetensors or .pt) and return the model in eval mode."""
    model = BgRemoveStudent()
    if str(weights_path).endswith(".safetensors"):
        from safetensors.torch import load_file
        state = load_file(weights_path)
    else:
        state = torch.load(weights_path, map_location="cpu", weights_only=True)
    model.load_state_dict(state)
    return model.to(device).eval()