summaryrefslogtreecommitdiff
path: root/text_recognizer/networks/encoders/efficientnet/mbconv.py
blob: 602aeb731372cae2664273a890672e0f349eb507 (plain)
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
"""Mobile inverted residual block."""
from typing import Optional, Tuple

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

from .utils import calculate_output_image_size, drop_connection, get_same_padding_conv2d


class MBConvBlock(nn.Module):
    """Mobile Inverted Residual Bottleneck block."""

    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        kernel_size: int,
        stride: int,
        bn_momentum: float,
        bn_eps: float,
        se_ratio: float,
        id_skip: bool,
        expand_ratio: int,
        image_size: Optional[Tuple[int, int]],
    ) -> None:
        super().__init__()
        self.kernel_size = kernel_size
        self.bn_momentum = bn_momentum
        self.bn_eps = bn_eps
        self.id_skip = id_skip
        self.in_channels = self.in_channels
        self.out_channels = out_channels

        # Placeholders for layers.
        self._inverted_bottleneck: nn.Sequential = None
        self._depthwise: nn.Sequential = None
        self._squeeze_excite: nn.Sequential = None
        self._pointwise: nn.Sequential = None

        self._build(
            image_size=image_size,
            in_channels=in_channels,
            out_channels=out_channels,
            kernel_size=kernel_size,
            stride=stride,
            expand_ratio=expand_ratio,
            se_ratio=se_ratio,
        )

    def _build(
        self,
        image_size: Optional[Tuple[int, int]],
        in_channels: int,
        out_channels: int,
        kernel_size: int,
        stride: int,
        expand_ratio: int,
        se_ratio: float,
    ) -> None:
        has_se = se_ratio is not None and 0.0 < se_ratio < 1.0
        inner_channels = in_channels * expand_ratio
        self._inverted_bottleneck = (
            self._configure_inverted_bottleneck(
                image_size=image_size,
                in_channels=in_channels,
                out_channels=inner_channels,
            )
            if expand_ratio != 1
            else None
        )

        self._depthwise = self._configure_depthwise(
            image_size=image_size,
            in_channels=inner_channels,
            out_channels=inner_channels,
            groups=inner_channels,
            kernel_size=kernel_size,
            stride=stride,
        )

        image_size = calculate_output_image_size(image_size, stride)
        self._squeeze_excite = (
            self._configure_squeeze_excite(
                in_channels=inner_channels,
                out_channels=inner_channels,
                se_ratio=se_ratio,
            )
            if has_se
            else None
        )

        self._pointwise = self._configure_pointwise(
            image_size=image_size, in_channels=inner_channels, out_channels=out_channels
        )

    def _configure_inverted_bottleneck(
        self,
        image_size: Optional[Tuple[int, int]],
        in_channels: int,
        out_channels: int,
    ) -> nn.Sequential:
        """Expansion phase."""
        Conv2d = get_same_padding_conv2d(image_size=image_size)
        return nn.Sequential(
            Conv2d(
                in_channels=in_channels,
                out_channels=out_channels,
                kernel_size=1,
                bias=False,
            ),
            nn.BatchNorm2d(
                num_features=out_channels, momentum=self.bn_momentum, eps=self.bn_eps
            ),
            nn.Mish(inplace=True),
        )

    def _configure_depthwise(
        self,
        image_size: Optional[Tuple[int, int]],
        in_channels: int,
        out_channels: int,
        groups: int,
        kernel_size: int,
        stride: int,
    ) -> nn.Sequential:
        Conv2d = get_same_padding_conv2d(image_size=image_size)
        return nn.Sequential(
            Conv2d(
                in_channels=in_channels,
                out_channels=out_channels,
                kernel_size=kernel_size,
                stride=stride,
                groups=groups,
                bias=False,
            ),
            nn.BatchNorm2d(
                num_features=out_channels, momentum=self.bn_momentum, eps=self.bn_eps
            ),
            nn.Mish(inplace=True),
        )

    def _configure_squeeze_excite(
        self, in_channels: int, out_channels: int, se_ratio: float
    ) -> nn.Sequential:
        Conv2d = get_same_padding_conv2d(image_size=(1, 1))
        num_squeezed_channels = max(1, int(in_channels * se_ratio))
        return nn.Sequential(
            Conv2d(
                in_channels=in_channels,
                out_channels=num_squeezed_channels,
                kernel_size=1,
            ),
            nn.Mish(inplace=True),
            Conv2d(
                in_channels=num_squeezed_channels,
                out_channels=out_channels,
                kernel_size=1,
            ),
        )

    def _configure_pointwise(
        self, image_size: Optional[Tuple[int, int]], in_channels: int, out_channels: int
    ) -> nn.Sequential:
        Conv2d = get_same_padding_conv2d(image_size=image_size)
        return nn.Sequential(
            Conv2d(
                in_channels=in_channels,
                out_channels=out_channels,
                kernel_size=1,
                bias=False,
            ),
            nn.BatchNorm2d(
                num_features=out_channels, momentum=self.bn_momentum, eps=self.bn_eps
            ),
        )

    def _stochastic_depth(
        self, x: Tensor, residual: Tensor, drop_connection_rate: Optional[float]
    ) -> Tensor:
        if self.id_skip and self.stride == 1 and self.in_channels == self.out_channels:
            if drop_connection_rate:
                x = drop_connection(x, p=drop_connection_rate, training=self.training)
            x += residual
        return x

    def forward(
        self, x: Tensor, drop_connection_rate: Optional[float] = None
    ) -> Tensor:
        residual = x
        if self._inverted_bottleneck is not None:
            x = self._inverted_bottleneck(x)

        x = self._depthwise(x)

        if self._squeeze_excite is not None:
            x_squeezed = F.adaptive_avg_pool2d(x, 1)
            x_squeezed = self._squeeze_excite(x)
            x = torch.tanh(F.softplus(x_squeezed)) * x

        x = self._pointwise(x)

        # Stochastic depth
        x = self._stochastic_depth(x, residual, drop_connection_rate)
        return x