DonkeySmall commited on
Commit
eebbce4
·
verified ·
1 Parent(s): 0aaa402

Upload model.py

Browse files
Files changed (1) hide show
  1. model.py +323 -0
model.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+
5
+
6
+ class DropPath(nn.Module):
7
+ def __init__(self, drop_prob: float = 0.0):
8
+ super().__init__()
9
+ self.drop_prob = drop_prob
10
+
11
+ def forward(self, x):
12
+ if self.drop_prob == 0.0 or not self.training:
13
+ return x
14
+
15
+ keep_prob = 1.0 - self.drop_prob
16
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1)
17
+ random_tensor = torch.rand(shape, dtype=x.dtype, device=x.device)
18
+ random_tensor = torch.floor(random_tensor + keep_prob)
19
+ return x * random_tensor / keep_prob
20
+
21
+
22
+ def window_partition(x, window_size):
23
+ # x: [B, H, W, C]
24
+ B, H, W, C = x.shape
25
+ x = x.view(
26
+ B,
27
+ H // window_size,
28
+ window_size,
29
+ W // window_size,
30
+ window_size,
31
+ C,
32
+ )
33
+ windows = x.permute(0, 1, 3, 2, 4, 5).contiguous()
34
+ windows = windows.view(-1, window_size, window_size, C)
35
+ return windows
36
+
37
+
38
+ def window_reverse(windows, window_size, H, W):
39
+ num_windows = (H // window_size) * (W // window_size)
40
+ B = windows.shape[0] // num_windows
41
+
42
+ x = windows.view(
43
+ B,
44
+ H // window_size,
45
+ W // window_size,
46
+ window_size,
47
+ window_size,
48
+ -1,
49
+ )
50
+ x = x.permute(0, 1, 3, 2, 4, 5).contiguous()
51
+ x = x.view(B, H, W, -1)
52
+ return x
53
+
54
+
55
+ class Mlp(nn.Module):
56
+ def __init__(self, dim, mlp_ratio=4.0):
57
+ super().__init__()
58
+ hidden = int(dim * mlp_ratio)
59
+ self.fc1 = nn.Linear(dim, hidden)
60
+ self.act = nn.GELU()
61
+ self.fc2 = nn.Linear(hidden, dim)
62
+
63
+ def forward(self, x):
64
+ return self.fc2(self.act(self.fc1(x)))
65
+
66
+
67
+ class WindowAttention(nn.Module):
68
+ def __init__(self, dim, window_size, num_heads):
69
+ super().__init__()
70
+ assert dim % num_heads == 0, "dim должен делиться на num_heads"
71
+
72
+ self.dim = dim
73
+ self.window_size = window_size
74
+ self.num_heads = num_heads
75
+ head_dim = dim // num_heads
76
+ self.scale = head_dim ** -0.5
77
+
78
+ self.relative_position_bias_table = nn.Parameter(
79
+ torch.zeros((2 * window_size - 1) * (2 * window_size - 1), num_heads)
80
+ )
81
+ nn.init.trunc_normal_(self.relative_position_bias_table, std=0.02)
82
+
83
+ coords_h = torch.arange(window_size)
84
+ coords_w = torch.arange(window_size)
85
+ coords = torch.stack(torch.meshgrid(coords_h, coords_w, indexing="ij"))
86
+ coords_flatten = torch.flatten(coords, 1)
87
+
88
+ relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :]
89
+ relative_coords = relative_coords.permute(1, 2, 0).contiguous()
90
+
91
+ relative_coords[:, :, 0] += window_size - 1
92
+ relative_coords[:, :, 1] += window_size - 1
93
+ relative_coords[:, :, 0] *= 2 * window_size - 1
94
+
95
+ relative_position_index = relative_coords.sum(-1)
96
+ self.register_buffer("relative_position_index", relative_position_index)
97
+
98
+ self.qkv = nn.Linear(dim, dim * 3)
99
+ self.proj = nn.Linear(dim, dim)
100
+ self.softmax = nn.Softmax(dim=-1)
101
+
102
+ def forward(self, x, mask=None):
103
+ # x: [B_windows, N, C]
104
+ B_, N, C = x.shape
105
+
106
+ qkv = self.qkv(x)
107
+ qkv = qkv.reshape(B_, N, 3, self.num_heads, C // self.num_heads)
108
+ qkv = qkv.permute(2, 0, 3, 1, 4)
109
+
110
+ q, k, v = qkv.unbind(0)
111
+
112
+ attn = (q * self.scale) @ k.transpose(-2, -1)
113
+
114
+ relative_position_bias = self.relative_position_bias_table[
115
+ self.relative_position_index.view(-1)
116
+ ].view(
117
+ self.window_size * self.window_size,
118
+ self.window_size * self.window_size,
119
+ -1,
120
+ )
121
+ relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous()
122
+ attn = attn + relative_position_bias.unsqueeze(0)
123
+
124
+ if mask is not None:
125
+ nW = mask.shape[0]
126
+ attn = attn.view(B_ // nW, nW, self.num_heads, N, N)
127
+ attn = attn + mask.unsqueeze(1).unsqueeze(0)
128
+ attn = attn.view(-1, self.num_heads, N, N)
129
+
130
+ attn = self.softmax(attn)
131
+
132
+ x = (attn @ v).transpose(1, 2).reshape(B_, N, C)
133
+ x = self.proj(x)
134
+ return x
135
+
136
+
137
+ class SwinBlock(nn.Module):
138
+ def __init__(
139
+ self,
140
+ dim,
141
+ num_heads,
142
+ window_size,
143
+ shift_size=0,
144
+ mlp_ratio=4.0,
145
+ drop_path=0.0,
146
+ ):
147
+ super().__init__()
148
+ self.window_size = window_size
149
+ self.shift_size = shift_size
150
+
151
+ self.norm1 = nn.LayerNorm(dim)
152
+ self.attn = WindowAttention(
153
+ dim=dim,
154
+ window_size=window_size,
155
+ num_heads=num_heads,
156
+ )
157
+ self.drop_path1 = DropPath(drop_path)
158
+ self.drop_path2 = DropPath(drop_path)
159
+
160
+ self.norm2 = nn.LayerNorm(dim)
161
+ self.mlp = Mlp(dim=dim, mlp_ratio=mlp_ratio)
162
+
163
+ def _make_mask(self, H, W, shift_size, device):
164
+ img_mask = torch.zeros((1, H, W, 1), device=device)
165
+
166
+ h_slices = (
167
+ slice(0, -self.window_size),
168
+ slice(-self.window_size, -shift_size),
169
+ slice(-shift_size, None),
170
+ )
171
+ w_slices = (
172
+ slice(0, -self.window_size),
173
+ slice(-self.window_size, -shift_size),
174
+ slice(-shift_size, None),
175
+ )
176
+
177
+ cnt = 0
178
+ for h in h_slices:
179
+ for w in w_slices:
180
+ img_mask[:, h, w, :] = cnt
181
+ cnt += 1
182
+
183
+ mask_windows = window_partition(img_mask, self.window_size)
184
+ mask_windows = mask_windows.view(-1, self.window_size * self.window_size)
185
+
186
+ attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
187
+ attn_mask = attn_mask.masked_fill(attn_mask != 0, -100.0)
188
+ attn_mask = attn_mask.masked_fill(attn_mask == 0, 0.0)
189
+ return attn_mask
190
+
191
+ def forward(self, x, H, W):
192
+ # x: [B, H*W, C]
193
+ B, L, C = x.shape
194
+
195
+ shortcut = x
196
+ x = self.norm1(x)
197
+ x = x.view(B, H, W, C)
198
+
199
+ pad_r = (self.window_size - W % self.window_size) % self.window_size
200
+ pad_b = (self.window_size - H % self.window_size) % self.window_size
201
+ x = F.pad(x, (0, 0, 0, pad_r, 0, pad_b))
202
+
203
+ _, Hp, Wp, _ = x.shape
204
+
205
+ shift_size = self.shift_size if min(Hp, Wp) > self.window_size else 0
206
+
207
+ if shift_size > 0:
208
+ shifted = torch.roll(x, shifts=(-shift_size, -shift_size), dims=(1, 2))
209
+ attn_mask = self._make_mask(Hp, Wp, shift_size, x.device)
210
+ else:
211
+ shifted = x
212
+ attn_mask = None
213
+
214
+ x_windows = window_partition(shifted, self.window_size)
215
+ x_windows = x_windows.view(-1, self.window_size * self.window_size, C)
216
+
217
+ attn_windows = self.attn(x_windows, mask=attn_mask)
218
+ attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C)
219
+
220
+ shifted = window_reverse(attn_windows, self.window_size, Hp, Wp)
221
+
222
+ if shift_size > 0:
223
+ x = torch.roll(shifted, shifts=(shift_size, shift_size), dims=(1, 2))
224
+ else:
225
+ x = shifted
226
+
227
+ if pad_r > 0 or pad_b > 0:
228
+ x = x[:, :H, :W, :].contiguous()
229
+
230
+ x = x.view(B, H * W, C)
231
+
232
+ x = shortcut + self.drop_path1(x)
233
+ x = x + self.drop_path2(self.mlp(self.norm2(x)))
234
+
235
+ return x
236
+
237
+
238
+ class UpscalerTransformer(nn.Module):
239
+ """
240
+ Лёгкая трансформерная сеть для апскейла x2.
241
+
242
+ Вход: [B, 3, 128, 128]
243
+ Выход: [B, 3, 256, 256]
244
+ """
245
+
246
+ def __init__(
247
+ self,
248
+ dim=256,
249
+ depth=8,
250
+ num_heads=8,
251
+ window_size=8,
252
+ mlp_ratio=4.0,
253
+ ):
254
+ super().__init__()
255
+ assert dim % num_heads == 0, "dim должен делиться на num_heads"
256
+
257
+ self.conv_first = nn.Conv2d(3, dim, kernel_size=3, padding=1)
258
+
259
+ self.layers = nn.ModuleList(
260
+ [
261
+ SwinBlock(
262
+ dim=dim,
263
+ num_heads=num_heads,
264
+ window_size=window_size,
265
+ shift_size=0 if i % 2 == 0 else window_size // 2,
266
+ mlp_ratio=mlp_ratio,
267
+ )
268
+ for i in range(depth)
269
+ ]
270
+ )
271
+
272
+ self.norm = nn.LayerNorm(dim)
273
+ self.conv_feat = nn.Conv2d(dim, dim, kernel_size=3, padding=1)
274
+
275
+ # PixelShuffle x2:
276
+ # conv делает 3 * 2 * 2 = 12 каналов,
277
+ # PixelShuffle собирает из них RGB x2 размера.
278
+ self.up = nn.Sequential(
279
+ nn.Conv2d(dim, 3 * 4, kernel_size=3, padding=1),
280
+ nn.PixelShuffle(2),
281
+ )
282
+
283
+ self.conv_last = nn.Conv2d(3, 3, kernel_size=3, padding=1)
284
+
285
+ self.apply(self._init_weights)
286
+
287
+ def _init_weights(self, m):
288
+ if isinstance(m, nn.Linear):
289
+ nn.init.trunc_normal_(m.weight, std=0.02)
290
+ if m.bias is not None:
291
+ nn.init.constant_(m.bias, 0.0)
292
+
293
+ elif isinstance(m, nn.LayerNorm):
294
+ nn.init.constant_(m.bias, 0.0)
295
+ nn.init.constant_(m.weight, 1.0)
296
+
297
+ elif isinstance(m, nn.Conv2d):
298
+ nn.init.kaiming_normal_(m.weight, mode="fan_out", nonlinearity="relu")
299
+ if m.bias is not None:
300
+ nn.init.constant_(m.bias, 0.0)
301
+
302
+ def forward(self, x):
303
+ base = F.interpolate(x, scale_factor=2, mode="bicubic", align_corners=False)
304
+
305
+ f = self.conv_first(x)
306
+ shortcut = f
307
+
308
+ B, C, H, W = f.shape
309
+ f = f.flatten(2).transpose(1, 2)
310
+
311
+ for layer in self.layers:
312
+ f = layer(f, H, W)
313
+
314
+ f = self.norm(f)
315
+ f = f.transpose(1, 2).reshape(B, C, H, W)
316
+
317
+ f = self.conv_feat(f + shortcut)
318
+
319
+ out = self.up(f)
320
+ out = self.conv_last(out)
321
+
322
+ return base + out
323
+