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

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

7
from ..._internally_replaced_utils import load_state_dict_from_url
8
from ...utils import _log_api_usage_once
9

10
11

class _SimpleSegmentationModel(nn.Module):
12
13
14
    __constants__ = ["aux_classifier"]

    def __init__(self, backbone: nn.Module, classifier: nn.Module, aux_classifier: Optional[nn.Module] = None) -> None:
15
        super().__init__()
16
        _log_api_usage_once("models", self.__class__.__name__)
17
18
19
20
        self.backbone = backbone
        self.classifier = classifier
        self.aux_classifier = aux_classifier

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

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

        return result
39
40
41
42


def _load_weights(arch: str, model: nn.Module, model_url: Optional[str], progress: bool) -> None:
    if model_url is None:
43
        raise ValueError(f"No checkpoint is available for {arch}")
44
45
    state_dict = load_state_dict_from_url(model_url, progress=progress)
    model.load_state_dict(state_dict)