summaryrefslogtreecommitdiff
path: root/src/text_recognizer/networks/residual_network.py
blob: e3972241033f9caaf9c36d4e32edc428aff58169 (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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
"""Residual CNN."""
from functools import partial
from typing import Callable, Dict, List, Optional, Type, Union

from einops.layers.torch import Rearrange, Reduce
import torch
from torch import nn
from torch import Tensor

from text_recognizer.networks.util import activation_function


class Conv2dAuto(nn.Conv2d):
    """Convolution with auto padding based on kernel size."""

    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.padding = (self.kernel_size[0] // 2, self.kernel_size[1] // 2)


def conv_bn(in_channels: int, out_channels: int, *args, **kwargs) -> nn.Sequential:
    """3x3 convolution with batch norm."""
    conv3x3 = partial(Conv2dAuto, kernel_size=3, bias=False,)
    return nn.Sequential(
        conv3x3(in_channels, out_channels, *args, **kwargs),
        nn.BatchNorm2d(out_channels),
    )


class IdentityBlock(nn.Module):
    """Residual with identity block."""

    def __init__(
        self, in_channels: int, out_channels: int, activation: str = "relu"
    ) -> None:
        super().__init__()
        self.in_channels = in_channels
        self.out_channels = out_channels
        self.blocks = nn.Identity()
        self.activation_fn = activation_function(activation)
        self.shortcut = nn.Identity()

    def forward(self, x: Tensor) -> Tensor:
        """Forward pass."""
        residual = x
        if self.apply_shortcut:
            residual = self.shortcut(x)
        x = self.blocks(x)
        x += residual
        x = self.activation_fn(x)
        return x

    @property
    def apply_shortcut(self) -> bool:
        """Check if shortcut should be applied."""
        return self.in_channels != self.out_channels


class ResidualBlock(IdentityBlock):
    """Residual with nonlinear shortcut."""

    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        expansion: int = 1,
        downsampling: int = 1,
        *args,
        **kwargs
    ) -> None:
        """Short summary.

        Args:
            in_channels (int): Number of in channels.
            out_channels (int): umber of out channels.
            expansion (int): Expansion factor of the out channels. Defaults to 1.
            downsampling (int): Downsampling factor used in stride. Defaults to 1.
            *args (type): Extra arguments.
            **kwargs (type): Extra key value arguments.

        """
        super().__init__(in_channels, out_channels, *args, **kwargs)
        self.expansion = expansion
        self.downsampling = downsampling

        self.shortcut = (
            nn.Sequential(
                nn.Conv2d(
                    in_channels=self.in_channels,
                    out_channels=self.expanded_channels,
                    kernel_size=1,
                    stride=self.downsampling,
                    bias=False,
                ),
                nn.BatchNorm2d(self.expanded_channels),
            )
            if self.apply_shortcut
            else None
        )

    @property
    def expanded_channels(self) -> int:
        """Computes the expanded output channels."""
        return self.out_channels * self.expansion

    @property
    def apply_shortcut(self) -> bool:
        """Check if shortcut should be applied."""
        return self.in_channels != self.expanded_channels


class BasicBlock(ResidualBlock):
    """Basic ResNet block."""

    expansion = 1

    def __init__(self, in_channels: int, out_channels: int, *args, **kwargs) -> None:
        super().__init__(in_channels, out_channels, *args, **kwargs)
        self.blocks = nn.Sequential(
            conv_bn(
                in_channels=self.in_channels,
                out_channels=self.out_channels,
                bias=False,
                stride=self.downsampling,
            ),
            self.activation_fn,
            conv_bn(
                in_channels=self.out_channels,
                out_channels=self.expanded_channels,
                bias=False,
            ),
        )


class BottleNeckBlock(ResidualBlock):
    """Bottleneck block to increase depth while minimizing parameter size."""

    expansion = 4

    def __init__(self, in_channels: int, out_channels: int, *args, **kwargs) -> None:
        super().__init__(in_channels, out_channels, *args, **kwargs)
        self.blocks = nn.Sequential(
            conv_bn(
                in_channels=self.in_channels,
                out_channels=self.out_channels,
                kernel_size=1,
            ),
            self.activation_fn,
            conv_bn(
                in_channels=self.out_channels,
                out_channels=self.out_channels,
                kernel_size=3,
                stride=self.downsampling,
            ),
            self.activation_fn,
            conv_bn(
                in_channels=self.out_channels,
                out_channels=self.expanded_channels,
                kernel_size=1,
            ),
        )


class ResidualLayer(nn.Module):
    """ResNet layer."""

    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        block: BasicBlock = BasicBlock,
        num_blocks: int = 1,
        *args,
        **kwargs
    ) -> None:
        super().__init__()
        downsampling = 2 if in_channels != out_channels else 1
        self.blocks = nn.Sequential(
            block(
                in_channels, out_channels, *args, **kwargs, downsampling=downsampling
            ),
            *[
                block(
                    out_channels * block.expansion,
                    out_channels,
                    downsampling=1,
                    *args,
                    **kwargs
                )
                for _ in range(num_blocks - 1)
            ]
        )

    def forward(self, x: Tensor) -> Tensor:
        """Forward pass."""
        x = self.blocks(x)
        return x


class ResidualNetworkEncoder(nn.Module):
    """Encoder network."""

    def __init__(
        self,
        in_channels: int = 1,
        block_sizes: Union[int, List[int]] = (32, 64),
        depths: Union[int, List[int]] = (2, 2),
        activation: str = "relu",
        block: Type[nn.Module] = BasicBlock,
        levels: int = 1,
        *args,
        **kwargs
    ) -> None:
        super().__init__()
        self.block_sizes = (
            block_sizes if isinstance(block_sizes, list) else [block_sizes] * levels
        )
        self.depths = depths if isinstance(depths, list) else [depths] * levels
        self.activation = activation
        self.gate = nn.Sequential(
            nn.Conv2d(
                in_channels=in_channels,
                out_channels=self.block_sizes[0],
                kernel_size=3,
                stride=1,
                padding=1,
                bias=False,
            ),
            nn.BatchNorm2d(self.block_sizes[0]),
            activation_function(self.activation),
            # nn.MaxPool2d(kernel_size=2, stride=2, padding=1),
        )

        self.blocks = self._configure_blocks(block)

    def _configure_blocks(
        self, block: Type[nn.Module], *args, **kwargs
    ) -> nn.Sequential:
        channels = [self.block_sizes[0]] + list(
            zip(self.block_sizes, self.block_sizes[1:])
        )
        blocks = [
            ResidualLayer(
                in_channels=channels[0],
                out_channels=channels[0],
                num_blocks=self.depths[0],
                block=block,
                activation=self.activation,
                *args,
                **kwargs
            )
        ]
        blocks += [
            ResidualLayer(
                in_channels=in_channels * block.expansion,
                out_channels=out_channels,
                num_blocks=num_blocks,
                block=block,
                activation=self.activation,
                *args,
                **kwargs
            )
            for (in_channels, out_channels), num_blocks in zip(
                channels[1:], self.depths[1:]
            )
        ]

        return nn.Sequential(*blocks)

    def forward(self, x: Tensor) -> Tensor:
        """Forward pass."""
        # If batch dimenstion is missing, it needs to be added.
        if len(x.shape) == 3:
            x = x.unsqueeze(0)
        x = self.gate(x)
        x = self.blocks(x)
        return x


class ResidualNetworkDecoder(nn.Module):
    """Classification head."""

    def __init__(self, in_features: int, num_classes: int = 80) -> None:
        super().__init__()
        self.decoder = nn.Sequential(
            Reduce("b c h w -> b c", "mean"),
            nn.Linear(in_features=in_features, out_features=num_classes),
        )

    def forward(self, x: Tensor) -> Tensor:
        """Forward pass."""
        return self.decoder(x)


class ResidualNetwork(nn.Module):
    """Full residual network."""

    def __init__(self, in_channels: int, num_classes: int, *args, **kwargs) -> None:
        super().__init__()
        self.encoder = ResidualNetworkEncoder(in_channels, *args, **kwargs)
        self.decoder = ResidualNetworkDecoder(
            in_features=self.encoder.blocks[-1].blocks[-1].expanded_channels,
            num_classes=num_classes,
        )

    def forward(self, x: Tensor) -> Tensor:
        """Forward pass."""
        x = self.encoder(x)
        x = self.decoder(x)
        return x