diff options
author | Gustaf Rydholm <gustaf.rydholm@gmail.com> | 2023-09-03 22:54:09 +0200 |
---|---|---|
committer | Gustaf Rydholm <gustaf.rydholm@gmail.com> | 2023-09-03 22:54:09 +0200 |
commit | 1732ed564a738a42c1bf6e8127ae810f5658cb06 (patch) | |
tree | 8d7f67793fec820850b4f8fd92f762f7f5e4b9f6 /text_recognizer/network/convnext/attention.py | |
parent | 53cfc21cffa4e877ad0959170b47b690d2fdb40f (diff) |
Revert "Delete convnext"
This reverts commit 7239bce214607c70a7a91358586f265b2f74de7b.
Diffstat (limited to 'text_recognizer/network/convnext/attention.py')
-rw-r--r-- | text_recognizer/network/convnext/attention.py | 79 |
1 files changed, 79 insertions, 0 deletions
diff --git a/text_recognizer/network/convnext/attention.py b/text_recognizer/network/convnext/attention.py new file mode 100644 index 0000000..6bc9692 --- /dev/null +++ b/text_recognizer/network/convnext/attention.py @@ -0,0 +1,79 @@ +"""Convolution self attention block.""" + +import torch.nn.functional as F +from einops import rearrange +from torch import Tensor, einsum, nn + +from text_recognizer.network.convnext.norm import LayerNorm +from text_recognizer.network.convnext.residual import Residual + + +def l2norm(t: Tensor) -> Tensor: + return F.normalize(t, dim=-1) + + +class FeedForward(nn.Module): + def __init__(self, dim: int, mult: int = 4) -> None: + super().__init__() + inner_dim = int(dim * mult) + self.fn = Residual( + nn.Sequential( + LayerNorm(dim), + nn.Conv2d(dim, inner_dim, 1, bias=False), + nn.GELU(), + LayerNorm(inner_dim), + nn.Conv2d(inner_dim, dim, 1, bias=False), + ) + ) + + def forward(self, x: Tensor) -> Tensor: + return self.fn(x) + + +class Attention(nn.Module): + def __init__( + self, dim: int, heads: int = 4, dim_head: int = 64, scale: int = 8 + ) -> None: + super().__init__() + self.scale = scale + self.heads = heads + inner_dim = heads * dim_head + self.norm = LayerNorm(dim) + + self.to_qkv = nn.Conv2d(dim, inner_dim * 3, 1, bias=False) + self.to_out = nn.Conv2d(inner_dim, dim, 1, bias=False) + + def forward(self, x: Tensor) -> Tensor: + h, w = x.shape[-2:] + + residual = x.clone() + + x = self.norm(x) + + q, k, v = self.to_qkv(x).chunk(3, dim=1) + q, k, v = map( + lambda t: rearrange(t, "b (h c) ... -> b h (...) c", h=self.heads), + (q, k, v), + ) + + q, k = map(l2norm, (q, k)) + + sim = einsum("b h i d, b h j d -> b h i j", q, k) * self.scale + attn = sim.softmax(dim=-1) + + out = einsum("b h i j, b h j d -> b h i d", attn, v) + + out = rearrange(out, "b h (x y) d -> b (h d) x y", x=h, y=w) + return self.to_out(out) + residual + + +class TransformerBlock(nn.Module): + def __init__(self, attn: Attention, ff: FeedForward) -> None: + super().__init__() + self.attn = attn + self.ff = ff + + def forward(self, x: Tensor) -> Tensor: + x = self.attn(x) + x = self.ff(x) + return x |