File size: 6,988 Bytes
2fa5aae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
from torch.nn.utils.parametrizations import spectral_norm
import torch
from torch.nn import functional as F
import einops


class GBlock(torch.nn.Module):
    def __init__(self, in_channel: int, out_channel: int):
        super().__init__()
        self.in_channel = in_channel
        self.out_channel = out_channel

        # TODO: close batch
        # self.bn1 = torch.nn.BatchNorm2d(in_channel)
        # self.bn2 = torch.nn.BatchNorm2d(out_channel)

        self.relu = torch.nn.ReLU()
        # conv1x1
        self.conv1x1 = spectral_norm(
            torch.nn.Conv2d(in_channel, out_channel, kernel_size=1)
        )

        self.conv3x3_1 = spectral_norm(
            torch.nn.Conv2d(in_channel, out_channel, kernel_size=3, padding=1)
        )
        self.conv3x3_2 = spectral_norm(
            torch.nn.Conv2d(out_channel, out_channel, kernel_size=3, padding=1)
        )

    def forward(self, x: torch.Tensor):
        # if shape is different then applied
        if x.shape[1] != self.out_channel:
            res = self.conv1x1(x)
        else:
            res = x.clone()

        # first
        # x = self.bn1(x)
        x = self.relu(x)
        x = self.conv3x3_1(x)
        # second
        # x = self.bn2(x)
        x = self.relu(x)
        x = self.conv3x3_2(x)

        y = x + res

        return y


class Up_GBlock(torch.nn.Module):
    def __init__(self, in_channel: int):
        super().__init__()
        self.in_channel = in_channel
        self.out_channel = int(in_channel / 2)

        # TODO: close batch
        # self.bn1 = torch.nn.BatchNorm2d(in_channel)
        # self.bn2 = torch.nn.BatchNorm2d(self.out_channel)
        # self.bn2 = torch.nn.BatchNorm2d(in_channel)

        self.relu = torch.nn.ReLU()
        self.up = torch.nn.Upsample(scale_factor=2, mode='nearest')

        self.conv1x1 = spectral_norm(
            torch.nn.Conv2d(in_channel, self.out_channel, kernel_size=1)
        )

        self.conv3x3_1 = spectral_norm(
            torch.nn.Conv2d(in_channel, in_channel, kernel_size=3, padding=1)
        )
        self.conv3x3_2 = spectral_norm(
            torch.nn.Conv2d(
                in_channel,
                self.out_channel,
                kernel_size=3,
                padding=1))

    def forward(self, x):
        res = self.up(x)
        res = self.conv1x1(res)

        # x = self.bn1(x)
        x = self.relu(x)
        x = self.up(x)
        x = self.conv3x3_1(x)

        # x = self.bn2(x)
        x = self.relu(x)
        x = self.conv3x3_2(x)

        y = x + res

        return y


class DBlock(torch.nn.Module):
    def __init__(
            self,
            in_channel: int,
            out_channel: int,
            conv_type='2d',
            apply_relu=True,
            apply_down=False):
        super().__init__()
        self.in_channel = in_channel
        self.out_channel = out_channel
        self.apply_relu = apply_relu
        self.apply_down = apply_down

        # construct layer
        if conv_type == '2d':
            self.avg_pool = torch.nn.AvgPool2d(kernel_size=2, stride=2)
            conv = torch.nn.Conv2d
        elif conv_type == '3d':
            self.avg_pool = torch.nn.AvgPool3d(kernel_size=2, stride=2)
            conv = torch.nn.Conv3d

        self.relu = torch.nn.ReLU()
        self.conv1x1 = spectral_norm(
            conv(in_channel, out_channel, kernel_size=1)
        )

        self.conv3x3_1 = spectral_norm(
            conv(in_channel, out_channel, kernel_size=3, padding=1)
        )
        self.conv3x3_2 = spectral_norm(
            conv(out_channel, out_channel, kernel_size=3, padding=1)
        )

    def forward(self, x):
        # Residual block
        if x.shape[1] != self.out_channel:
            res = self.conv1x1(x)
        else:
            res = x.clone()
        if self.apply_down:
            res = self.avg_pool(res)

        ##
        if self.apply_relu:
            x = self.relu(x)
        x = self.conv3x3_1(x)
        x = self.relu(x)
        x = self.conv3x3_2(x)
        if self.apply_down:
            x = self.avg_pool(x)

        # connect
        y = res + x

        return y


class LBlock(torch.nn.Module):
    def __init__(self, in_channel, out_channel):
        super().__init__()
        self.in_channel = in_channel
        self.out_channel = out_channel

        self.relu = torch.nn.ReLU()
        conv = torch.nn.Conv2d
        self.conv1x1 = conv(
            in_channel,
            (out_channel - in_channel),
            kernel_size=1)

        self.conv3x3_1 = conv(in_channel, in_channel, kernel_size=3, padding=1)
        self.conv3x3_2 = conv(
            in_channel,
            out_channel,
            kernel_size=3,
            padding=1)

    def forward(self, x):
        res = torch.cat([x, self.conv1x1(x)], dim=1)

        x = self.relu(x)
        x = self.conv3x3_1(x)
        x = self.relu(x)
        x = self.conv3x3_2(x)

        y = x + res

        return y

# Attention Layer


def attention_einsum(q, k, v):
    """
    Apply self-attention to tensors
    """

    # Reshape 3D tensor to 2D tensor with first dimension L = h x w
    k = einops.rearrange(k, "h w c -> (h w) c")  # [h, w, c] -> [L, c]
    v = einops.rearrange(v, "h w c -> (h w) c")  # [h, w, c] -> [L, c]

    # Einstein summation corresponding to the query * key operation.
    beta = F.softmax(torch.einsum("hwc, Lc->hwL", q, k), dim=-1)

    # Einstein summation corresponding to the attention * value operation.
    out = torch.einsum("hwL, Lc->hwc", beta, v)

    return out


class AttentionLayer(torch.nn.Module):
    def __init__(self, in_channel, out_channel, ratio_kq=8, ratio_v=8):
        super().__init__()

        self.ratio_kq = ratio_kq
        self.ratio_v = ratio_v
        self.in_channel = in_channel
        self.out_channel = out_channel

        # compute query, key, and value using 1x1 convolution
        self.query = torch.nn.Conv2d(
            in_channel,
            out_channel // ratio_kq,
            kernel_size=1,
            bias=False
        )

        self.key = torch.nn.Conv2d(
            in_channel,
            out_channel // ratio_kq,
            kernel_size=1,
            bias=False
        )

        self.value = torch.nn.Conv2d(
            in_channel,
            out_channel // ratio_v,
            kernel_size=1,
            bias=False
        )

        self.conv = torch.nn.Conv2d(
            out_channel // 8,
            out_channel,
            kernel_size=1,
            bias=False
        )

        self.gamma = torch.nn.Parameter(torch.zeros(1))

    def forward(self, x):
        query = self.query(x)
        key = self.key(x)
        value = self.value(x)
        # apply attention
        out = []
        for i in range(x.shape[0]):
            out.append(attention_einsum(query[i], key[i], value[i]))

        out = torch.stack(out, dim=0)
        out = self.gamma * self.conv(out)
        out = out + x  # skip connection

        return out