summaryrefslogtreecommitdiff
path: root/text_recognizer/models/barlow_twins.py
blob: 6e2719d342c50c901d930e92d7c6956ab587a40d (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
"""PyTorch Lightning Barlow Twins model."""
from typing import Tuple, Type
import attr
from torch import nn
from torch import Tensor

from text_recognizer.models.base import BaseLitModel
from text_recognizer.criterions.barlow_twins import BarlowTwinsLoss


@attr.s(auto_attribs=True, eq=False)
class BarlowTwinsLitModel(BaseLitModel):
    """Barlow Twins training proceduer."""

    network: Type[nn.Module] = attr.ib()
    loss_fn: BarlowTwinsLoss = attr.ib()

    def forward(self, data: Tensor) -> Tensor:
        """Encodes image to projector latent."""
        return self.network(data)

    def training_step(self, batch: Tuple[Tensor, Tensor], batch_idx: int) -> Tensor:
        """Training step."""
        data, _ = batch
        x1, x2 = data
        z1, z2 = self(x1), self(x2)
        loss = self.loss_fn(z1, z2)
        self.log("train/loss", loss)
        return loss

    def validation_step(self, batch: Tuple[Tensor, Tensor], batch_idx: int) -> None:
        """Validation step."""
        data, _ = batch
        x1, x2 = data
        z1, z2 = self(x1), self(x2)
        loss = self.loss_fn(z1, z2)
        self.log("val/loss", loss, prog_bar=True)

    def test_step(self, batch: Tuple[Tensor, Tensor], batch_idx: int) -> None:
        """Test step."""
        data, _ = batch
        x1, x2 = data
        z1, z2 = self(x1), self(x2)
        loss = self.loss_fn(z1, z2)
        self.log("test/loss", loss, prog_bar=True)