"csrc/vscode:/vscode.git/clone" did not exist on "1f49a3a5a2ecfc6f6a83ce6d4489385c60c24301"
misc.py 4.13 KB
Newer Older
eellison's avatar
eellison committed
1
2
3
from collections import OrderedDict
from torch.jit.annotations import Optional, List
from torch import Tensor
4
5
6
7
8
9
10
11
12
13
14
15

"""
helper class that supports empty tensors on some nn functions.

Ideally, add support directly in PyTorch to empty tensors in
those functions.

This can be removed once https://github.com/pytorch/pytorch/issues/12013
is implemented
"""

import math
16
import warnings
17
import torch
eellison's avatar
eellison committed
18
19
20
21
22
23
24
25
26
from torchvision.ops import _new_empty_tensor


def _check_size_scale_factor(dim, size, scale_factor):
    # type: (int, Optional[List[int]], Optional[float]) -> None
    if size is None and scale_factor is None:
        raise ValueError("either size or scale_factor should be defined")
    if size is not None and scale_factor is not None:
        raise ValueError("only one of size or scale_factor should be defined")
27
    if scale_factor is not None:
eellison's avatar
eellison committed
28
29
30
31
32
33
        if isinstance(scale_factor, (list, tuple)):
            if len(scale_factor) != dim:
                raise ValueError(
                    "scale_factor shape must match input shape. "
                    "Input is {}D, scale_factor size is {}".format(dim, len(scale_factor))
                )
34
35


eellison's avatar
eellison committed
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def _output_size(dim, input, size, scale_factor):
    # type: (int, Tensor, Optional[List[int]], Optional[float]) -> List[int]
    assert dim == 2
    _check_size_scale_factor(dim, size, scale_factor)
    if size is not None:
        return size
    # if dim is not 2 or scale_factor is iterable use _ntuple instead of concat
    assert scale_factor is not None and isinstance(scale_factor, (int, float))
    scale_factors = [scale_factor, scale_factor]
    # math.floor might return float in py2.7
    return [
        int(math.floor(input.size(i + 2) * scale_factors[i])) for i in range(dim)
    ]


def interpolate(input, size=None, scale_factor=None, mode="nearest", align_corners=None):
    # type: (Tensor, Optional[List[int]], Optional[float], str, Optional[bool]) -> Tensor
53
54
55
56
57
    """
    Equivalent to nn.functional.interpolate, but with support for empty batch sizes.
    This will eventually be supported natively by PyTorch, and this
    class can go away.
    """
58
59
60
61
62
    if input.numel() > 0:
        return torch.nn.functional.interpolate(
            input, size, scale_factor, mode, align_corners
        )

eellison's avatar
eellison committed
63
    output_shape = _output_size(2, input, size, scale_factor)
64
    output_shape = list(input.shape[:-2]) + list(output_shape)
eellison's avatar
eellison committed
65
    return _new_empty_tensor(input, output_shape)
66
67
68


# This is not in nn
69
class FrozenBatchNorm2d(torch.nn.Module):
70
71
72
73
74
    """
    BatchNorm2d where the batch statistics and the affine parameters
    are fixed
    """

75
76
77
78
79
80
    def __init__(self, num_features, eps=0., n=None):
        # n=None for backward-compatibility
        if n is not None:
            warnings.warn("`n` argument is deprecated and has been renamed `num_features`",
                          DeprecationWarning)
            num_features = n
81
        super(FrozenBatchNorm2d, self).__init__()
82
83
84
85
86
        self.eps = eps
        self.register_buffer("weight", torch.ones(num_features))
        self.register_buffer("bias", torch.zeros(num_features))
        self.register_buffer("running_mean", torch.zeros(num_features))
        self.register_buffer("running_var", torch.ones(num_features))
87

88
89
90
91
92
93
94
95
96
97
    def _load_from_state_dict(self, state_dict, prefix, local_metadata, strict,
                              missing_keys, unexpected_keys, error_msgs):
        num_batches_tracked_key = prefix + 'num_batches_tracked'
        if num_batches_tracked_key in state_dict:
            del state_dict[num_batches_tracked_key]

        super(FrozenBatchNorm2d, self)._load_from_state_dict(
            state_dict, prefix, local_metadata, strict,
            missing_keys, unexpected_keys, error_msgs)

98
99
100
101
102
103
104
    def forward(self, x):
        # move reshapes to the beginning
        # to make it fuser-friendly
        w = self.weight.reshape(1, -1, 1, 1)
        b = self.bias.reshape(1, -1, 1, 1)
        rv = self.running_var.reshape(1, -1, 1, 1)
        rm = self.running_mean.reshape(1, -1, 1, 1)
105
        scale = w * (rv + self.eps).rsqrt()
106
107
        bias = b - rm * scale
        return x * scale + bias
108
109
110

    def __repr__(self):
        return f"{self.__class__.__name__}({self.weight.shape[0]})"