summaryrefslogtreecommitdiff
path: root/text_recognizer/networks/conformer/subsampler.py
diff options
context:
space:
mode:
authorGustaf Rydholm <gustaf.rydholm@gmail.com>2022-06-07 00:24:28 +0200
committerGustaf Rydholm <gustaf.rydholm@gmail.com>2022-06-07 00:24:28 +0200
commit38dc6ca3b787bcdb54d43ac5c076e08af25d44b2 (patch)
treedf12ee98c797c44c61f02369cf8cb794d6f47b7c /text_recognizer/networks/conformer/subsampler.py
parent7d759b6c0efcb58b5c7c6858d7dcbd2060992430 (diff)
Add subsampler layer
Diffstat (limited to 'text_recognizer/networks/conformer/subsampler.py')
-rw-r--r--text_recognizer/networks/conformer/subsampler.py46
1 files changed, 46 insertions, 0 deletions
diff --git a/text_recognizer/networks/conformer/subsampler.py b/text_recognizer/networks/conformer/subsampler.py
new file mode 100644
index 0000000..2bc0445
--- /dev/null
+++ b/text_recognizer/networks/conformer/subsampler.py
@@ -0,0 +1,46 @@
+"""Simple convolutional network."""
+from typing import Tuple
+
+from torch import nn, Tensor
+
+from text_recognizer.networks.transformer import (
+ AxialPositionalEmbedding,
+)
+
+
+class Subsampler(nn.Module):
+ def __init__(
+ self,
+ channels: int,
+ depth: int,
+ pixel_pos_embedding: AxialPositionalEmbedding,
+ dropout: float = 0.1,
+ ) -> None:
+ super().__init__()
+ self.pixel_pos_embedding = pixel_pos_embedding
+ self.subsampler, self.projector = self._build(channels, depth, dropout)
+
+ def _build(
+ self, channels: int, depth: int, dropout: float
+ ) -> Tuple[nn.Sequential, nn.Sequential]:
+ subsampler = []
+ for i in range(depth):
+ subsampler.append(
+ nn.Conv2d(
+ in_channels=1 if i == 0 else channels,
+ out_channels=channels,
+ kernel_size=3,
+ stride=2,
+ )
+ )
+ subsampler.append(nn.Mish(inplace=True))
+ projector = nn.Sequential(
+ nn.Flatten(start_dim=2), nn.Linear(channels, channels), nn.Dropout(dropout)
+ )
+ return nn.Sequential(*subsampler), projector
+
+ def forward(self, x: Tensor) -> Tensor:
+ x = self.subsampler(x)
+ x = self.pixel_pos_embedding(x)
+ x = self.projector(x)
+ return x.permute(0, 2, 1)