trenden commited on
Commit
0c3e51b
·
verified ·
1 Parent(s): 7e67809

Upload sgmse/backbones/ncsnpp_utils/up_or_down_sampling.py

Browse files
sgmse/backbones/ncsnpp_utils/up_or_down_sampling.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Layers used for up-sampling or down-sampling images.
2
+
3
+ Many functions are ported from https://github.com/NVlabs/stylegan2.
4
+ """
5
+
6
+ import torch.nn as nn
7
+ import torch
8
+ import torch.nn.functional as F
9
+ import numpy as np
10
+ from .op import upfirdn2d
11
+
12
+
13
+ # Function ported from StyleGAN2
14
+ def get_weight(module,
15
+ shape,
16
+ weight_var='weight',
17
+ kernel_init=None):
18
+ """Get/create weight tensor for a convolution or fully-connected layer."""
19
+
20
+ return module.param(weight_var, kernel_init, shape)
21
+
22
+
23
+ class Conv2d(nn.Module):
24
+ """Conv2d layer with optimal upsampling and downsampling (StyleGAN2)."""
25
+
26
+ def __init__(self, in_ch, out_ch, kernel, up=False, down=False,
27
+ resample_kernel=(1, 3, 3, 1),
28
+ use_bias=True,
29
+ kernel_init=None):
30
+ super().__init__()
31
+ assert not (up and down)
32
+ assert kernel >= 1 and kernel % 2 == 1
33
+ self.weight = nn.Parameter(torch.zeros(out_ch, in_ch, kernel, kernel))
34
+ if kernel_init is not None:
35
+ self.weight.data = kernel_init(self.weight.data.shape)
36
+ if use_bias:
37
+ self.bias = nn.Parameter(torch.zeros(out_ch))
38
+
39
+ self.up = up
40
+ self.down = down
41
+ self.resample_kernel = resample_kernel
42
+ self.kernel = kernel
43
+ self.use_bias = use_bias
44
+
45
+ def forward(self, x):
46
+ if self.up:
47
+ x = upsample_conv_2d(x, self.weight, k=self.resample_kernel)
48
+ elif self.down:
49
+ x = conv_downsample_2d(x, self.weight, k=self.resample_kernel)
50
+ else:
51
+ x = F.conv2d(x, self.weight, stride=1, padding=self.kernel // 2)
52
+
53
+ if self.use_bias:
54
+ x = x + self.bias.reshape(1, -1, 1, 1)
55
+
56
+ return x
57
+
58
+
59
+ def naive_upsample_2d(x, factor=2):
60
+ _N, C, H, W = x.shape
61
+ x = torch.reshape(x, (-1, C, H, 1, W, 1))
62
+ x = x.repeat(1, 1, 1, factor, 1, factor)
63
+ return torch.reshape(x, (-1, C, H * factor, W * factor))
64
+
65
+
66
+ def naive_downsample_2d(x, factor=2):
67
+ _N, C, H, W = x.shape
68
+ x = torch.reshape(x, (-1, C, H // factor, factor, W // factor, factor))
69
+ return torch.mean(x, dim=(3, 5))
70
+
71
+
72
+ def upsample_conv_2d(x, w, k=None, factor=2, gain=1):
73
+ """Fused `upsample_2d()` followed by `tf.nn.conv2d()`.
74
+
75
+ Padding is performed only once at the beginning, not between the
76
+ operations.
77
+ The fused op is considerably more efficient than performing the same
78
+ calculation
79
+ using standard TensorFlow ops. It supports gradients of arbitrary order.
80
+ Args:
81
+ x: Input tensor of the shape `[N, C, H, W]` or `[N, H, W,
82
+ C]`.
83
+ w: Weight tensor of the shape `[filterH, filterW, inChannels,
84
+ outChannels]`. Grouped convolution can be performed by `inChannels =
85
+ x.shape[0] // numGroups`.
86
+ k: FIR filter of the shape `[firH, firW]` or `[firN]`
87
+ (separable). The default is `[1] * factor`, which corresponds to
88
+ nearest-neighbor upsampling.
89
+ factor: Integer upsampling factor (default: 2).
90
+ gain: Scaling factor for signal magnitude (default: 1.0).
91
+
92
+ Returns:
93
+ Tensor of the shape `[N, C, H * factor, W * factor]` or
94
+ `[N, H * factor, W * factor, C]`, and same datatype as `x`.
95
+ """
96
+
97
+ assert isinstance(factor, int) and factor >= 1
98
+
99
+ # Check weight shape.
100
+ assert len(w.shape) == 4
101
+ convH = w.shape[2]
102
+ convW = w.shape[3]
103
+ inC = w.shape[1]
104
+ outC = w.shape[0]
105
+
106
+ assert convW == convH
107
+
108
+ # Setup filter kernel.
109
+ if k is None:
110
+ k = [1] * factor
111
+ k = _setup_kernel(k) * (gain * (factor ** 2))
112
+ p = (k.shape[0] - factor) - (convW - 1)
113
+
114
+ stride = (factor, factor)
115
+
116
+ # Determine data dimensions.
117
+ stride = [1, 1, factor, factor]
118
+ output_shape = ((_shape(x, 2) - 1) * factor + convH, (_shape(x, 3) - 1) * factor + convW)
119
+ output_padding = (output_shape[0] - (_shape(x, 2) - 1) * stride[0] - convH,
120
+ output_shape[1] - (_shape(x, 3) - 1) * stride[1] - convW)
121
+ assert output_padding[0] >= 0 and output_padding[1] >= 0
122
+ num_groups = _shape(x, 1) // inC
123
+
124
+ # Transpose weights.
125
+ w = torch.reshape(w, (num_groups, -1, inC, convH, convW))
126
+ w = w[..., ::-1, ::-1].permute(0, 2, 1, 3, 4)
127
+ w = torch.reshape(w, (num_groups * inC, -1, convH, convW))
128
+
129
+ x = F.conv_transpose2d(x, w, stride=stride, output_padding=output_padding, padding=0)
130
+ ## Original TF code.
131
+ # x = tf.nn.conv2d_transpose(
132
+ # x,
133
+ # w,
134
+ # output_shape=output_shape,
135
+ # strides=stride,
136
+ # padding='VALID',
137
+ # data_format=data_format)
138
+ ## JAX equivalent
139
+
140
+ return upfirdn2d(x, torch.tensor(k, device=x.device),
141
+ pad=((p + 1) // 2 + factor - 1, p // 2 + 1))
142
+
143
+
144
+ def conv_downsample_2d(x, w, k=None, factor=2, gain=1):
145
+ """Fused `tf.nn.conv2d()` followed by `downsample_2d()`.
146
+
147
+ Padding is performed only once at the beginning, not between the operations.
148
+ The fused op is considerably more efficient than performing the same
149
+ calculation
150
+ using standard TensorFlow ops. It supports gradients of arbitrary order.
151
+ Args:
152
+ x: Input tensor of the shape `[N, C, H, W]` or `[N, H, W,
153
+ C]`.
154
+ w: Weight tensor of the shape `[filterH, filterW, inChannels,
155
+ outChannels]`. Grouped convolution can be performed by `inChannels =
156
+ x.shape[0] // numGroups`.
157
+ k: FIR filter of the shape `[firH, firW]` or `[firN]`
158
+ (separable). The default is `[1] * factor`, which corresponds to
159
+ average pooling.
160
+ factor: Integer downsampling factor (default: 2).
161
+ gain: Scaling factor for signal magnitude (default: 1.0).
162
+
163
+ Returns:
164
+ Tensor of the shape `[N, C, H // factor, W // factor]` or
165
+ `[N, H // factor, W // factor, C]`, and same datatype as `x`.
166
+ """
167
+
168
+ assert isinstance(factor, int) and factor >= 1
169
+ _outC, _inC, convH, convW = w.shape
170
+ assert convW == convH
171
+ if k is None:
172
+ k = [1] * factor
173
+ k = _setup_kernel(k) * gain
174
+ p = (k.shape[0] - factor) + (convW - 1)
175
+ s = [factor, factor]
176
+ x = upfirdn2d(x, torch.tensor(k, device=x.device),
177
+ pad=((p + 1) // 2, p // 2))
178
+ return F.conv2d(x, w, stride=s, padding=0)
179
+
180
+
181
+ def _setup_kernel(k):
182
+ k = np.asarray(k, dtype=np.float32)
183
+ if k.ndim == 1:
184
+ k = np.outer(k, k)
185
+ k /= np.sum(k)
186
+ assert k.ndim == 2
187
+ assert k.shape[0] == k.shape[1]
188
+ return k
189
+
190
+
191
+ def _shape(x, dim):
192
+ return x.shape[dim]
193
+
194
+
195
+ def upsample_2d(x, k=None, factor=2, gain=1):
196
+ r"""Upsample a batch of 2D images with the given filter.
197
+
198
+ Accepts a batch of 2D images of the shape `[N, C, H, W]` or `[N, H, W, C]`
199
+ and upsamples each image with the given filter. The filter is normalized so
200
+ that
201
+ if the input pixels are constant, they will be scaled by the specified
202
+ `gain`.
203
+ Pixels outside the image are assumed to be zero, and the filter is padded
204
+ with
205
+ zeros so that its shape is a multiple of the upsampling factor.
206
+ Args:
207
+ x: Input tensor of the shape `[N, C, H, W]` or `[N, H, W,
208
+ C]`.
209
+ k: FIR filter of the shape `[firH, firW]` or `[firN]`
210
+ (separable). The default is `[1] * factor`, which corresponds to
211
+ nearest-neighbor upsampling.
212
+ factor: Integer upsampling factor (default: 2).
213
+ gain: Scaling factor for signal magnitude (default: 1.0).
214
+
215
+ Returns:
216
+ Tensor of the shape `[N, C, H * factor, W * factor]`
217
+ """
218
+ assert isinstance(factor, int) and factor >= 1
219
+ if k is None:
220
+ k = [1] * factor
221
+ k = _setup_kernel(k) * (gain * (factor ** 2))
222
+ p = k.shape[0] - factor
223
+ return upfirdn2d(x, torch.tensor(k, device=x.device),
224
+ up=factor, pad=((p + 1) // 2 + factor - 1, p // 2))
225
+
226
+
227
+ def downsample_2d(x, k=None, factor=2, gain=1):
228
+ r"""Downsample a batch of 2D images with the given filter.
229
+
230
+ Accepts a batch of 2D images of the shape `[N, C, H, W]` or `[N, H, W, C]`
231
+ and downsamples each image with the given filter. The filter is normalized
232
+ so that
233
+ if the input pixels are constant, they will be scaled by the specified
234
+ `gain`.
235
+ Pixels outside the image are assumed to be zero, and the filter is padded
236
+ with
237
+ zeros so that its shape is a multiple of the downsampling factor.
238
+ Args:
239
+ x: Input tensor of the shape `[N, C, H, W]` or `[N, H, W,
240
+ C]`.
241
+ k: FIR filter of the shape `[firH, firW]` or `[firN]`
242
+ (separable). The default is `[1] * factor`, which corresponds to
243
+ average pooling.
244
+ factor: Integer downsampling factor (default: 2).
245
+ gain: Scaling factor for signal magnitude (default: 1.0).
246
+
247
+ Returns:
248
+ Tensor of the shape `[N, C, H // factor, W // factor]`
249
+ """
250
+
251
+ assert isinstance(factor, int) and factor >= 1
252
+ if k is None:
253
+ k = [1] * factor
254
+ k = _setup_kernel(k) * gain
255
+ p = k.shape[0] - factor
256
+ return upfirdn2d(x, torch.tensor(k, device=x.device),
257
+ down=factor, pad=((p + 1) // 2, p // 2))