trenden commited on
Commit
9eabeba
·
verified ·
1 Parent(s): 1ddf472

Upload sgmse/backbones/ncsnpp_utils/op/upfirdn2d_kernel.py

Browse files
sgmse/backbones/ncsnpp_utils/op/upfirdn2d_kernel.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import torch
4
+ from torch.nn import functional as F
5
+
6
+
7
+ def upfirdn2d(input, kernel, up=1, down=1, pad=(0, 0)):
8
+ out = upfirdn2d_native(
9
+ input, kernel, up, up, down, down, pad[0], pad[1], pad[0], pad[1]
10
+ )
11
+
12
+ return out
13
+
14
+
15
+ def upfirdn2d_native(
16
+ input, kernel, up_x, up_y, down_x, down_y, pad_x0, pad_x1, pad_y0, pad_y1
17
+ ):
18
+ _, channel, in_h, in_w = input.shape
19
+ input = input.reshape(-1, in_h, in_w, 1)
20
+
21
+ _, in_h, in_w, minor = input.shape
22
+ kernel_h, kernel_w = kernel.shape
23
+
24
+ out = input.view(-1, in_h, 1, in_w, 1, minor)
25
+ out = F.pad(out, [0, 0, 0, up_x - 1, 0, 0, 0, up_y - 1])
26
+ out = out.view(-1, in_h * up_y, in_w * up_x, minor)
27
+
28
+ out = F.pad(
29
+ out, [0, 0, max(pad_x0, 0), max(pad_x1, 0), max(pad_y0, 0), max(pad_y1, 0)]
30
+ )
31
+ out = out[
32
+ :,
33
+ max(-pad_y0, 0) : out.shape[1] - max(-pad_y1, 0),
34
+ max(-pad_x0, 0) : out.shape[2] - max(-pad_x1, 0),
35
+ :,
36
+ ]
37
+
38
+ out = out.permute(0, 3, 1, 2)
39
+ out = out.reshape(
40
+ [-1, 1, in_h * up_y + pad_y0 + pad_y1, in_w * up_x + pad_x0 + pad_x1]
41
+ )
42
+ w = torch.flip(kernel, [0, 1]).view(1, 1, kernel_h, kernel_w)
43
+ out = F.conv2d(out, w)
44
+ out = out.reshape(
45
+ -1,
46
+ minor,
47
+ in_h * up_y + pad_y0 + pad_y1 - kernel_h + 1,
48
+ in_w * up_x + pad_x0 + pad_x1 - kernel_w + 1,
49
+ )
50
+ out = out.permute(0, 2, 3, 1)
51
+ out = out[:, ::down_y, ::down_x, :]
52
+
53
+ out_h = (in_h * up_y + pad_y0 + pad_y1 - kernel_h) // down_y + 1
54
+ out_w = (in_w * up_x + pad_x0 + pad_x1 - kernel_w) // down_x + 1
55
+
56
+ return out.view(-1, channel, out_h, out_w)