summaryrefslogtreecommitdiff
path: root/text_recognizer/models/vqvae.py
blob: ef2213c827eacd2c63a3973c30397a4c0b304a82 (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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""PyTorch Lightning model for base Transformers."""
from typing import Any, Dict, Union, Tuple, Type

from omegaconf import DictConfig, OmegaConf
from torch import nn
from torch import Tensor
import torch.nn.functional as F
import wandb

from text_recognizer.models.base import LitBaseModel


class LitVQVAEModel(LitBaseModel):
    """A PyTorch Lightning model for transformer networks."""

    def __init__(
        self,
        network: Type[nn.Module],
        optimizer: Union[DictConfig, Dict],
        lr_scheduler: Union[DictConfig, Dict],
        criterion: Union[DictConfig, Dict],
        monitor: str = "val_loss",
        *args: Any,
        **kwargs: Dict,
    ) -> None:
        super().__init__(network, optimizer, lr_scheduler, criterion, monitor)

    def forward(self, data: Tensor) -> Tensor:
        """Forward pass with the transformer network."""
        return self.network.predict(data)

    def _log_prediction(self, data: Tensor, reconstructions: Tensor) -> None:
        """Logs prediction on image with wandb."""
        try:
            self.logger.experiment.log(
                {
                    "val_pred_examples": [
                        wandb.Image(data[0]),
                        wandb.Image(reconstructions[0]),
                    ]
                }
            )
        except AttributeError:
            pass

    def training_step(self, batch: Tuple[Tensor, Tensor], batch_idx: int) -> Tensor:
        """Training step."""
        data, _ = batch
        reconstructions, vq_loss = self.network(data)
        loss = self.loss_fn(reconstructions, data)
        loss += vq_loss
        self.log("train_loss", loss)
        return loss

    def validation_step(self, batch: Tuple[Tensor, Tensor], batch_idx: int) -> None:
        """Validation step."""
        data, _ = batch
        reconstructions, vq_loss = self.network(data)
        loss = self.loss_fn(reconstructions, data)
        loss += vq_loss
        self.log("val_loss", loss, prog_bar=True)
        self._log_prediction(data, reconstructions)

    def test_step(self, batch: Tuple[Tensor, Tensor], batch_idx: int) -> None:
        """Test step."""
        data, _ = batch
        reconstructions, vq_loss = self.network(data)
        loss = self.loss_fn(reconstructions, data)
        loss += vq_loss
        self._log_prediction(data, reconstructions)