summaryrefslogtreecommitdiff
path: root/text_recognizer/networks/vqvae/pixelcnn.py
blob: 5c580df029b1ac4a24aa7c6b5e8d9d48a142b012 (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
"""PixelCNN encoder and decoder.

Same as in VQGAN among other. Hopefully, better reconstructions...

TODO: Add num of residual layers.
"""
from typing import Sequence

from torch import nn
from torch import Tensor

from text_recognizer.networks.vqvae.attention import Attention
from text_recognizer.networks.vqvae.norm import Normalize
from text_recognizer.networks.vqvae.residual import Residual
from text_recognizer.networks.vqvae.resize import Downsample, Upsample


class Encoder(nn.Module):
    """PixelCNN encoder."""

    def __init__(
        self,
        in_channels: int,
        hidden_dim: int,
        channels_multipliers: Sequence[int],
        dropout_rate: float,
    ) -> None:
        super().__init__()
        self.in_channels = in_channels
        self.dropout_rate = dropout_rate
        self.hidden_dim = hidden_dim
        self.channels_multipliers = tuple(channels_multipliers)
        self.encoder = self._build_encoder()

    def _build_encoder(self) -> nn.Sequential:
        """Builds encoder."""
        encoder = [
            nn.Conv2d(
                in_channels=self.in_channels,
                out_channels=self.hidden_dim,
                kernel_size=3,
                stride=1,
                padding=1,
            ),
        ]
        num_blocks = len(self.channels_multipliers)
        in_channels_multipliers = (1,) + self.channels_multipliers 
        for i in range(num_blocks):
            in_channels = self.hidden_dim * in_channels_multipliers[i]
            out_channels = self.hidden_dim * self.channels_multipliers[i]
            encoder += [
                Residual(
                    in_channels=in_channels,
                    out_channels=out_channels,
                    dropout_rate=self.dropout_rate,
                    use_norm=True,
                ),
            ]
            if i == num_blocks - 1:
                encoder.append(Attention(in_channels=out_channels))
            encoder.append(Downsample())

        for _ in range(2):
            encoder += [
                Residual(
                    in_channels=self.hidden_dim * self.channels_multipliers[-1],
                    out_channels=self.hidden_dim * self.channels_multipliers[-1],
                    dropout_rate=self.dropout_rate,
                    use_norm=True,
                ),
                Attention(in_channels=self.hidden_dim * self.channels_multipliers[-1])
            ]

        encoder += [
            Normalize(num_channels=self.hidden_dim * self.channels_multipliers[-1]),
            nn.Mish(),
            nn.Conv2d(
                in_channels=self.hidden_dim * self.channels_multipliers[-1],
                out_channels=self.hidden_dim * self.channels_multipliers[-1],
                kernel_size=3,
                stride=1,
                padding=1,
            ),
        ]
        return nn.Sequential(*encoder)

    def forward(self, x: Tensor) -> Tensor:
        """Encodes input to a latent representation."""
        return self.encoder(x)


class Decoder(nn.Module):
    """PixelCNN decoder."""

    def __init__(
        self,
        hidden_dim: int,
        channels_multipliers: Sequence[int],
        out_channels: int,
        dropout_rate: float,
    ) -> None:
        super().__init__()
        self.hidden_dim = hidden_dim
        self.out_channels = out_channels
        self.channels_multipliers = tuple(channels_multipliers)
        self.dropout_rate = dropout_rate
        self.decoder = self._build_decoder()

    def _build_decoder(self) -> nn.Sequential:
        """Builds decoder."""
        in_channels = self.hidden_dim * self.channels_multipliers[0]
        decoder = [
            Residual(
                in_channels=in_channels,
                out_channels=in_channels,
                dropout_rate=self.dropout_rate,
                use_norm=True,
            ),
            Attention(in_channels=in_channels),
            Residual(
                in_channels=in_channels,
                out_channels=in_channels,
                dropout_rate=self.dropout_rate,
                use_norm=True,
            ),
        ]

        out_channels_multipliers = self.channels_multipliers + (1, )
        num_blocks = len(self.channels_multipliers)

        for i in range(num_blocks):
            in_channels = self.hidden_dim * self.channels_multipliers[i]
            out_channels = self.hidden_dim * out_channels_multipliers[i + 1]
            decoder.append(
                Residual(
                    in_channels=in_channels,
                    out_channels=out_channels,
                    dropout_rate=self.dropout_rate,
                    use_norm=True,
                )
            )
            if i == 0:
                decoder.append(
                    Attention(
                        in_channels=out_channels
                    )
                )
            decoder.append(Upsample())

        decoder += [
            Normalize(num_channels=self.hidden_dim * out_channels_multipliers[-1]),
            nn.Mish(),
            nn.Conv2d(
                in_channels=self.hidden_dim * out_channels_multipliers[-1],
                out_channels=self.out_channels,
                kernel_size=3,
                stride=1,
                padding=1,
            ),
        ]
        return nn.Sequential(*decoder)

    def forward(self, x: Tensor) -> Tensor:
        """Decodes latent vector."""
        return self.decoder(x)