File size: 6,683 Bytes
dc6da71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
"""Small, timm-compatible EfficientNetV2-S inference implementation.

The Apache-2.0 timm implementation was reduced to the layers exercised by
``tf_efficientnetv2_s.in21k_ft_in1k`` and modified to remove its runtime
dependency. Module names intentionally match timm so the official UTMOS v2
state dictionary loads; see LICENSE.
"""

from __future__ import annotations

import math

import torch
import torch.nn.functional as F
from torch import nn


class Conv2dSame(nn.Conv2d):
    def forward(self, x: torch.Tensor) -> torch.Tensor:
        height, width = x.shape[-2:]
        stride_h, stride_w = self.stride
        kernel_h, kernel_w = self.kernel_size
        dilation_h, dilation_w = self.dilation
        output_h = math.ceil(height / stride_h)
        output_w = math.ceil(width / stride_w)
        pad_h = max(
            (output_h - 1) * stride_h
            + (kernel_h - 1) * dilation_h
            + 1
            - height,
            0,
        )
        pad_w = max(
            (output_w - 1) * stride_w
            + (kernel_w - 1) * dilation_w
            + 1
            - width,
            0,
        )
        if pad_h or pad_w:
            x = F.pad(
                x,
                (
                    pad_w // 2,
                    pad_w - pad_w // 2,
                    pad_h // 2,
                    pad_h - pad_h // 2,
                ),
            )
        return F.conv2d(
            x,
            self.weight,
            self.bias,
            self.stride,
            0,
            self.dilation,
            self.groups,
        )


class BatchNormAct2d(nn.BatchNorm2d):
    def __init__(self, channels: int, *, activate: bool) -> None:
        super().__init__(channels, eps=1e-3, momentum=0.1)
        self.activate = activate

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = super().forward(x)
        return F.silu(x, inplace=True) if self.activate else x


def conv3x3(
    in_channels: int,
    out_channels: int,
    stride: int,
    *,
    groups: int = 1,
) -> nn.Conv2d:
    if stride == 2:
        return Conv2dSame(
            in_channels,
            out_channels,
            3,
            stride=2,
            groups=groups,
            bias=False,
        )
    return nn.Conv2d(
        in_channels,
        out_channels,
        3,
        stride=1,
        padding=1,
        groups=groups,
        bias=False,
    )


class ConvBnAct(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        self.conv = conv3x3(24, 24, 1)
        self.bn1 = BatchNormAct2d(24, activate=True)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        residual = x
        x = self.bn1(self.conv(x))
        return x + residual


class EdgeResidual(nn.Module):
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        expansion: int,
        stride: int,
    ) -> None:
        super().__init__()
        expanded_channels = in_channels * expansion
        self.conv_exp = conv3x3(in_channels, expanded_channels, stride)
        self.bn1 = BatchNormAct2d(expanded_channels, activate=True)
        self.conv_pwl = nn.Conv2d(expanded_channels, out_channels, 1, bias=False)
        self.bn2 = BatchNormAct2d(out_channels, activate=False)
        self.has_residual = stride == 1 and in_channels == out_channels

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        residual = x
        x = self.bn1(self.conv_exp(x))
        x = self.bn2(self.conv_pwl(x))
        return x + residual if self.has_residual else x


class SqueezeExcite(nn.Module):
    def __init__(self, expanded_channels: int, reduced_channels: int) -> None:
        super().__init__()
        self.conv_reduce = nn.Conv2d(expanded_channels, reduced_channels, 1)
        self.conv_expand = nn.Conv2d(reduced_channels, expanded_channels, 1)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        scale = x.mean((2, 3), keepdim=True)
        scale = F.silu(self.conv_reduce(scale), inplace=True)
        return x * torch.sigmoid(self.conv_expand(scale))


class InvertedResidual(nn.Module):
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        expansion: int,
        stride: int,
    ) -> None:
        super().__init__()
        expanded_channels = in_channels * expansion
        self.conv_pw = nn.Conv2d(in_channels, expanded_channels, 1, bias=False)
        self.bn1 = BatchNormAct2d(expanded_channels, activate=True)
        self.conv_dw = conv3x3(
            expanded_channels,
            expanded_channels,
            stride,
            groups=expanded_channels,
        )
        self.bn2 = BatchNormAct2d(expanded_channels, activate=True)
        self.se = SqueezeExcite(expanded_channels, in_channels // 4)
        self.conv_pwl = nn.Conv2d(expanded_channels, out_channels, 1, bias=False)
        self.bn3 = BatchNormAct2d(out_channels, activate=False)
        self.has_residual = stride == 1 and in_channels == out_channels

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        residual = x
        x = self.bn1(self.conv_pw(x))
        x = self.bn2(self.conv_dw(x))
        x = self.se(x)
        x = self.bn3(self.conv_pwl(x))
        return x + residual if self.has_residual else x


def make_stage(
    block_type: type[EdgeResidual | InvertedResidual],
    in_channels: int,
    out_channels: int,
    expansion: int,
    repeats: int,
    stride: int,
) -> nn.Sequential:
    blocks = [block_type(in_channels, out_channels, expansion, stride)]
    blocks.extend(
        block_type(out_channels, out_channels, expansion, 1)
        for _ in range(repeats - 1)
    )
    return nn.Sequential(*blocks)


class EfficientNetV2S(nn.Module):
    """Feature-only TF EfficientNetV2-S with timm-compatible parameter names."""

    def __init__(self) -> None:
        super().__init__()
        self.conv_stem = Conv2dSame(3, 24, 3, stride=2, bias=False)
        self.bn1 = BatchNormAct2d(24, activate=True)
        self.blocks = nn.Sequential(
            nn.Sequential(ConvBnAct(), ConvBnAct()),
            make_stage(EdgeResidual, 24, 48, 4, 4, 2),
            make_stage(EdgeResidual, 48, 64, 4, 4, 2),
            make_stage(InvertedResidual, 64, 128, 4, 6, 2),
            make_stage(InvertedResidual, 128, 160, 6, 9, 1),
            make_stage(InvertedResidual, 160, 256, 6, 15, 2),
        )
        self.conv_head = nn.Conv2d(256, 1280, 1, bias=False)
        self.bn2 = BatchNormAct2d(1280, activate=True)

    def forward(self, x: torch.Tensor) -> torch.Tensor:
        x = self.bn1(self.conv_stem(x))
        x = self.blocks(x)
        x = self.bn2(self.conv_head(x))
        return x