summaryrefslogtreecommitdiff
path: root/text_recognizer/networks/transformer/norm.py
blob: 58c87705d879eb1aed18eed30d9f1febdaac0c67 (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
"""Normalization layers for transfromers.

Copied from lucidrains:
    https://github.com/lucidrains/x-transformers/blob/main/x_transformers/x_transformers.py

"""
from typing import Callable, Dict, Type

import torch
from torch import nn
from torch import Tensor


class Rezero(nn.Module):
    def __init__(self, fn: Callable) -> None:
        super().__init__()
        self.fn = fn
        self.g = nn.Parameter(torch.zeros(1))

    def forward(self, x: Tensor, **kwargs: Dict) -> Tensor:
        x, *rest = self.fn(x, **kwargs)
        return (x * self.g, *rest)


class ScaleNorm(nn.Module):
    def __init__(self, dim: int, eps: float = 1.0e-5) -> None:
        super().__init__()
        self.scale = dim ** -0.5
        self.eps = eps
        self.g = nn.Parameter(torch.ones(1))

    def forward(self, x: Tensor) -> Tensor:
        norm = torch.norm(x, dim=-1, keepdim=True) * self.scale
        return x / norm.clamp(min=self.eps) * self.g


class PreNorm(nn.Module):
    def __init__(self, dim: int, fn: Type[nn.Module]) -> None:
        super().__init__()
        self.norm = nn.LayerNorm(dim)
        self.fn = fn

    def forward(self, x: Tensor, **kwargs: Dict) -> Tensor:
        """Norm tensor."""
        x = self.norm(x)
        return self.fn(x, **kwargs)