summaryrefslogtreecommitdiff
path: root/text_recognizer/network/transformer/encoder.py
blob: ea4b0b3acd016f6f3505d6d4c20a562b507ea9a1 (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
"""Transformer encoder module."""
from torch import Tensor, nn

from text_recognizer.network.transformer.attention import Attention
from text_recognizer.network.transformer.ff import FeedForward


class Encoder(nn.Module):
    def __init__(
        self,
        dim: int,
        inner_dim: int,
        heads: int,
        dim_head: int,
        depth: int,
        dropout_rate: float = 0.0,
    ) -> None:
        super().__init__()
        self.norm = nn.LayerNorm(dim)
        self.layers = nn.ModuleList(
            [
                nn.ModuleList(
                    [
                        Attention(
                            dim,
                            heads,
                            False,
                            dim_head,
                            dropout_rate,
                        ),
                        FeedForward(dim, inner_dim, dropout_rate),
                    ]
                )
                for _ in range(depth)
            ]
        )

    def forward(
        self,
        x: Tensor,
    ) -> Tensor:
        """Applies decoder block on input signals."""
        for self_attn, ff in self.layers:
            x = x + self_attn(x)
            x = x + ff(x)
        return self.norm(x)