summaryrefslogtreecommitdiff
path: root/text_recognizer/networks/transformer/ff.py
blob: 3ccf5b5ed61563664ec1d7976faf4e27a069f2cf (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
"""Feedforward layer in transformer.

Stolen from lucidrains:
    https://github.com/lucidrains/x-transformers/blob/main/x_transformers/x_transformers.py
"""
from typing import Optional

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


class GEGLU(nn.Module):
    def __init__(self, dim_in: int, dim_out: int) -> None:
        super().__init__()
        self.fc = nn.Linear(dim_in, dim_out * 2)

    def forward(self, x: Tensor) -> Tensor:
        x, gate = self.fc(x).chunk(2, dim=-1)
        return x * F.gelu(gate)


class FeedForward(nn.Module):
    def __init__(
        self,
        dim: int,
        dim_out: Optional[int] = None,
        expansion_factor: int = 4,
        glu: bool = True,
        dropout_rate: float = 0.0,
    ) -> None:
        super().__init__()
        inner_dim = dim * expansion_factor
        dim_out = dim_out if dim_out is not None else dim
        in_projection = (
            nn.Sequential(nn.Linear(dim, inner_dim), nn.GELU())
            if not glu
            else GEGLU(dim, inner_dim)
        )

        self.mlp = nn.Sequential(
            in_projection, nn.Dropout(dropout_rate), nn.Linear(inner_dim, dim_out)
        )

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