_utils.py 1.12 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):
9
10
11
    __constants__ = ["aux_classifier"]

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

17
    def forward(self, x: Tensor) -> Dict[str, Tensor]:
18
19
20
21
22
23
24
        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)
25
        x = F.interpolate(x, size=input_shape, mode="bilinear", align_corners=False)
26
27
28
29
30
        result["out"] = x

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

        return result