_utils.py 1.16 KB
Newer Older
1
from collections import OrderedDict
2
from typing import Optional, Dict
3

4
from torch import nn, Tensor
5
6
7
8
from torch.nn import functional as F


class _SimpleSegmentationModel(nn.Module):
eellison's avatar
eellison committed
9
10
    __constants__ = ['aux_classifier']

11
12
13
14
15
16
    def __init__(
        self,
        backbone: nn.Module,
        classifier: nn.Module,
        aux_classifier: Optional[nn.Module] = None
    ) -> None:
17
18
19
20
21
        super(_SimpleSegmentationModel, self).__init__()
        self.backbone = backbone
        self.classifier = classifier
        self.aux_classifier = aux_classifier

22
    def forward(self, x: Tensor) -> Dict[str, Tensor]:
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
        input_shape = x.shape[-2:]
        # contract: features is a dict of tensors
        features = self.backbone(x)

        result = OrderedDict()
        x = features["out"]
        x = self.classifier(x)
        x = F.interpolate(x, size=input_shape, mode='bilinear', align_corners=False)
        result["out"] = x

        if self.aux_classifier is not None:
            x = features["aux"]
            x = self.aux_classifier(x)
            x = F.interpolate(x, size=input_shape, mode='bilinear', align_corners=False)
            result["aux"] = x

        return result