summaryrefslogtreecommitdiff
path: root/text_recognizer/networks/backbones/efficientnet.py
blob: 61dea779163db8c2d4a55a6002a06934f27499bf (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
"""Efficient net b0 implementation."""
import torch
from torch import nn
from torch import Tensor


class ConvNorm(nn.Module):
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        kernel_size: int,
        stride: int,
        padding: int,
        groups: int = 1,
    ) -> None:
        super().__init__()
        self.block = nn.Sequential(
            nn.Conv2d(
                in_channels=in_channels,
                out_channels=out_channels,
                kernel_size=kernel_size,
                stride=stride,
                padding=padding,
                groups=groups,
                bias=False,
            ),
            nn.BatchNorm2d(num_features=out_channels),
            nn.SiLU(inplace=True),
        )

    def forward(self, x: Tensor) -> Tensor:
        return self.block(x)


class SqueezeExcite(nn.Module):
    def __init__(self, in_channels: int, reduce_dim: int) -> None:
        super().__init__()
        self.se = nn.Sequential(
            nn.AdaptiveAvgPool2d(1),  # [C, H, W] -> [C, 1, 1]
            nn.Conv2d(in_channels=in_channels, out_channels=reduce_dim, kernel_size=1),
            nn.SiLU(),
            nn.Conv2d(in_channels=reduce_dim, out_channels=in_channels, kernel_size=1),
            nn.Sigmoid(),
        )

    def forward(self, x: Tensor) -> Tensor:
        return x * self.se(x)


class InvertedResidulaBlock(nn.Module):
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        kernel_size: int,
        stride: int,
        padding: int,
        expand_ratio: float,
        reduction: int = 4,
        survival_prob: float = 0.8,
    ) -> None:
        super().__init__()
        self.survival_prob = survival_prob
        self.use_residual = in_channels == out_channels and stride == 1
        hidden_dim = in_channels * expand_ratio
        self.expand = in_channels != hidden_dim
        reduce_dim = in_channels // reduction

        if self.expand:
            self.expand_conv = ConvNorm(
                in_channels, hidden_dim, kernel_size=3, stride=1, padding=1
            )

        self.conv = nn.Sequential(
            ConvNorm(
                hidden_dim, hidden_dim, kernel_size, stride, padding, groups=hidden_dim
            ),
            SqueezeExcite(hidden_dim, reduce_dim),
            nn.Conv2d(
                in_channels=hidden_dim,
                out_channels=out_channels,
                kernel_size=1,
                bias=False,
            ),
            nn.BatchNorm2d(num_features=out_channels),
        )

    def stochastic_depth(self, x: Tensor) -> Tensor:
        if not self.training:
            return x

        binary_tensor = (
            torch.rand(x.shape[0], 1, 1, 1, device=x.device) < self.survival_prob
        )
        return torch.div(x, self.survival_prob) * binary_tensor

    def forward(self, x: Tensor) -> Tensor:
        out = self.expand_conv(x) if self.expand else x
        if self.use_residual:
            return self.stochastic_depth(self.conv(out)) + x
        return self.conv(out)


class EfficientNet(nn.Module):
    """Efficient net b0 backbone."""

    def __init__(self) -> None:
        super().__init__()
        self.base_model = [
            # expand_ratio, channels, repeats, stride, kernel_size
            [1, 16, 1, 1, 3],
            [6, 24, 2, 2, 3],
            [6, 40, 2, 2, 5],
            [6, 80, 3, 2, 3],
            [6, 112, 3, 1, 5],
            [6, 192, 4, 2, 5],
            [6, 320, 1, 1, 3],
        ]

        self.backbone = self._build_b0()

    def _build_b0(self) -> nn.Sequential:
        in_channels = 32
        layers = [ConvNorm(1, in_channels, 3, stride=2, padding=1)]

        for expand_ratio, out_channels, repeats, stride, kernel_size in self.base_model:
            for i in range(repeats):
                layers.append(
                    InvertedResidulaBlock(
                        in_channels,
                        out_channels,
                        expand_ratio=expand_ratio,
                        stride=stride if i == 0 else 1,
                        kernel_size=kernel_size,
                        padding=kernel_size // 2,
                    )
                )
                in_channels = out_channels
        layers.append(ConvNorm(in_channels, 256, kernel_size=1, stride=1, padding=0))

        return nn.Sequential(*layers)

    def forward(self, x: Tensor) -> Tensor:
        return self.backbone(x)