File size: 6,714 Bytes
6e601ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import torch
import torch.nn as nn
import torch.nn.functional as F

from climategan.blocks import BaseDecoder, Conv2dBlock, InterpolateNearest2d
from climategan.utils import find_target_size


def create_depth_decoder(opts, no_init=False, verbose=0):
    if opts.gen.d.architecture == "base":
        decoder = BaseDepthDecoder(opts)
        if "s" in opts.task:
            assert opts.gen.s.use_dada is False
        if "m" in opts.tasks:
            assert opts.gen.m.use_dada is False
    else:
        decoder = DADADepthDecoder(opts)

    if verbose > 0:
        print(f"  - Add {decoder.__class__.__name__}")

    return decoder


class DADADepthDecoder(nn.Module):
    """
    Depth decoder based on depth auxiliary task in DADA paper
    """

    def __init__(self, opts):
        super().__init__()
        if (
            opts.gen.encoder.architecture == "deeplabv3"
            and opts.gen.deeplabv3.backbone == "mobilenet"
        ):
            res_dim = 320
        else:
            res_dim = 2048

        mid_dim = 512

        self.do_feat_fusion = False
        if opts.gen.m.use_dada or ("s" in opts.tasks and opts.gen.s.use_dada):
            self.do_feat_fusion = True
            self.dec4 = Conv2dBlock(
                128,
                res_dim,
                1,
                stride=1,
                padding=0,
                bias=True,
                activation="lrelu",
                norm="none",
            )

        self.relu = nn.ReLU(inplace=True)
        self.enc4_1 = Conv2dBlock(
            res_dim,
            mid_dim,
            1,
            stride=1,
            padding=0,
            bias=False,
            activation="lrelu",
            pad_type="reflect",
            norm="batch",
        )
        self.enc4_2 = Conv2dBlock(
            mid_dim,
            mid_dim,
            3,
            stride=1,
            padding=1,
            bias=False,
            activation="lrelu",
            pad_type="reflect",
            norm="batch",
        )
        self.enc4_3 = Conv2dBlock(
            mid_dim,
            128,
            1,
            stride=1,
            padding=0,
            bias=False,
            activation="lrelu",
            pad_type="reflect",
            norm="batch",
        )
        self.upsample = None
        if opts.gen.d.upsample_featuremaps:
            self.upsample = nn.Sequential(
                *[
                    InterpolateNearest2d(),
                    Conv2dBlock(
                        128,
                        32,
                        3,
                        stride=1,
                        padding=1,
                        bias=False,
                        activation="lrelu",
                        pad_type="reflect",
                        norm="batch",
                    ),
                    nn.Conv2d(32, 1, kernel_size=1, stride=1, padding=0),
                ]
            )
        self._target_size = find_target_size(opts, "d")
        print(
            "      - {}:  setting target size to {}".format(
                self.__class__.__name__, self._target_size
            )
        )

    def set_target_size(self, size):
        """
        Set final interpolation's target size

        Args:
            size (int, list, tuple): target size (h, w). If int, target will be (i, i)
        """
        if isinstance(size, (list, tuple)):
            self._target_size = size[:2]
        else:
            self._target_size = (size, size)

    def forward(self, z):
        if isinstance(z, (list, tuple)):
            z = z[0]
        z4_enc = self.enc4_1(z)
        z4_enc = self.enc4_2(z4_enc)
        z4_enc = self.enc4_3(z4_enc)

        z_depth = None
        if self.do_feat_fusion:
            z_depth = self.dec4(z4_enc)

        if self.upsample is not None:
            z4_enc = self.upsample(z4_enc)

        depth = torch.mean(z4_enc, dim=1, keepdim=True)  # DADA paper decoder
        if depth.shape[-1] != self._target_size:
            depth = F.interpolate(
                depth,
                size=(384, 384),  # size used in MiDaS inference
                mode="bicubic",  # what MiDaS uses
                align_corners=False,
            )

            depth = F.interpolate(
                depth, (self._target_size, self._target_size), mode="nearest"
            )  # what we used in the transforms to resize input

        return depth, z_depth

    def __str__(self):
        return "DADA Depth Decoder"


class BaseDepthDecoder(BaseDecoder):
    def __init__(self, opts):
        low_level_feats_dim = -1
        use_v3 = opts.gen.encoder.architecture == "deeplabv3"
        use_mobile_net = opts.gen.deeplabv3.backbone == "mobilenet"
        use_low = opts.gen.d.use_low_level_feats

        if use_v3 and use_mobile_net:
            input_dim = 320
            if use_low:
                low_level_feats_dim = 24
        elif use_v3:
            input_dim = 2048
            if use_low:
                low_level_feats_dim = 256
        else:
            input_dim = 2048

        n_upsample = 1 if opts.gen.d.upsample_featuremaps else 0
        output_dim = (
            1
            if not opts.gen.d.classify.enable
            else opts.gen.d.classify.linspace.buckets
        )

        self._target_size = find_target_size(opts, "d")
        print(
            "      - {}:  setting target size to {}".format(
                self.__class__.__name__, self._target_size
            )
        )

        super().__init__(
            n_upsample=n_upsample,
            n_res=opts.gen.d.n_res,
            input_dim=input_dim,
            proj_dim=opts.gen.d.proj_dim,
            output_dim=output_dim,
            norm=opts.gen.d.norm,
            activ=opts.gen.d.activ,
            pad_type=opts.gen.d.pad_type,
            output_activ="none",
            low_level_feats_dim=low_level_feats_dim,
        )

    def set_target_size(self, size):
        """
        Set final interpolation's target size

        Args:
            size (int, list, tuple): target size (h, w). If int, target will be (i, i)
        """
        if isinstance(size, (list, tuple)):
            self._target_size = size[:2]
        else:
            self._target_size = (size, size)

    def forward(self, z, cond=None):
        if self._target_size is None:
            error = "self._target_size should be set with self.set_target_size()"
            error += "to interpolate depth to the target depth map's size"
            raise ValueError(error)

        d = super().forward(z)

        preds = F.interpolate(
            d, size=self._target_size, mode="bilinear", align_corners=True
        )

        return preds, None