-
Notifications
You must be signed in to change notification settings - Fork 33
/
custom_layers.py
executable file
·200 lines (135 loc) · 6.9 KB
/
custom_layers.py
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
# =============================================================================
# Custom FutureGAN Layers
# -----------------------------------------------------------------------------
# code borrows from:
# https://github.com/nashory/pggan-pytorch
# https://github.com/tkarras/progressive_growing_of_gans
# https://github.com/github-pengge/PyTorch-progressive_growing_of_gans
import numpy as np
import torch
import torch.nn as nn
from torch.nn.init import xavier_normal, kaiming_normal, calculate_gain
from torch.autograd import Variable
class Concat(nn.Module):
'''
same function as ConcatTable container in Torch7
'''
def __init__(self, layer1, layer2):
super(Concat, self).__init__()
self.layer1 = layer1
self.layer2 = layer2
def forward(self,x):
y = [self.layer1(x), self.layer2(x)]
return y
class Flatten(nn.Module):
def __init__(self):
super(Flatten, self).__init__()
def forward(self, x):
return x.view(x.size(0), -1)
class FadeInLayer(nn.Module):
def __init__(self, config):
super(FadeInLayer, self).__init__()
self.alpha = 0.0
def update_alpha(self, delta):
self.alpha = self.alpha + delta
self.alpha = max(0, min(self.alpha, 1.0))
# input : [x_low, x_high] from ConcatTable()
def forward(self, x):
return torch.add(x[0].mul(1.0-self.alpha), x[1].mul(self.alpha))
class MinibatchStdConcatLayer(nn.Module):
def __init__(self, averaging='all'):
super(MinibatchStdConcatLayer, self).__init__()
self.averaging = averaging
def forward(self, x):
s = x.size() # [NCDHW] Input shape.
y = x
y = y-torch.mean(y, 0, keepdim=True) # [NCDHW] Subtract mean over group.
y = torch.mean(torch.pow(y,2), 0, keepdim=True) # [NCDHW] Calc variance over group.
y = torch.sqrt(y + 1e-8) # [NCDHW] Calc stddev over group.
for axis in [1,2,3,4]:
y = torch.mean(y, int(axis), keepdim=True) # [N1111] Take average over fmaps and pixels.
y = y.expand(s[0], 1, s[2], s[3], s[4]) # [N1DHW] Replicate over group and pixels.
x = torch.cat([x, y], 1) # [NCHW] Append as new fmap.
return x
def __repr__(self):
return self.__class__.__name__ + '(averaging = %s)' % (self.averaging)
class PixelwiseNormLayer(nn.Module):
def __init__(self):
super(PixelwiseNormLayer, self).__init__()
self.eps = 1e-8
def forward(self, x):
return x / (torch.mean(x**2, dim=1, keepdim=True) + self.eps) ** 0.5
class EqualizedConv3d(nn.Module):
def __init__(self, c_in, c_out, k_size, stride, pad, initializer='kaiming', bias=False):
super(EqualizedConv3d, self).__init__()
self.conv = nn.Conv3d(c_in, c_out, k_size, stride, pad, bias=False)
if initializer == 'kaiming': kaiming_normal(self.conv.weight, a=calculate_gain('conv3d'))
elif initializer == 'xavier': xavier_normal(self.conv.weight)
self.conv_w = self.conv.weight.data.clone()
self.bias = torch.nn.Parameter(torch.FloatTensor(c_out).fill_(0))
self.scale = (torch.mean(self.conv.weight.data ** 2)) ** 0.5
self.conv.weight.data.copy_(self.conv.weight.data/self.scale)
def forward(self, x):
x = self.conv(x.mul(self.scale))
return x + self.bias.view(1,-1,1,1,1).expand_as(x)
class EqualizedConvTranspose3d(nn.Module):
def __init__(self, c_in, c_out, k_size, stride, pad, initializer='kaiming'):
super(EqualizedConvTranspose3d, self).__init__()
self.deconv = nn.ConvTranspose3d(c_in, c_out, k_size, stride, pad, bias=False)
if initializer == 'kaiming': kaiming_normal(self.deconv.weight, a=calculate_gain('conv3d'))
elif initializer == 'xavier': xavier_normal(self.deconv.weight)
self.deconv_w = self.deconv.weight.data.clone()
self.bias = torch.nn.Parameter(torch.FloatTensor(c_out).fill_(0))
self.scale = (torch.mean(self.deconv.weight.data ** 2)) ** 0.5
self.deconv.weight.data.copy_(self.deconv.weight.data/self.scale)
def forward(self, x):
x = self.deconv(x.mul(self.scale))
return x + self.bias.view(1,-1,1,1,1).expand_as(x)
class EqualizedLinear(nn.Module):
def __init__(self, c_in, c_out, initializer='kaiming'):
super(EqualizedLinear, self).__init__()
self.linear = nn.Linear(c_in, c_out, bias=False)
if initializer == 'kaiming': kaiming_normal(self.linear.weight, a=calculate_gain('linear'))
elif initializer == 'xavier': torch.nn.init.xavier_normal(self.linear.weight)
self.linear_w = self.linear.weight.data.clone()
self.bias = torch.nn.Parameter(torch.FloatTensor(c_out).fill_(0))
self.scale = (torch.mean(self.linear.weight.data ** 2)) ** 0.5
self.linear.weight.data.copy_(self.linear.weight.data/self.scale)
def forward(self, x):
x = self.linear(x.mul(self.scale))
return x + self.bias.view(1,-1).expand_as(x)
class GeneralizedDropOut(nn.Module):
'''
This is only important for really easy datasets or LSGAN,
adding noise to discriminator to prevent discriminator
from spiraling out of control for too easy datasets.
'''
def __init__(self, mode='mul', strength=0.4, axes=(0,1), normalize=False):
super(GeneralizedDropOut, self).__init__()
self.mode = mode.lower()
assert self.mode in ['mul', 'drop', 'prop'], 'Invalid GDropLayer mode'%mode
self.strength = strength
self.axes = [axes] if isinstance(axes, int) else list(axes)
self.normalize = normalize
self.gain = None
def forward(self, x, deterministic=False):
if deterministic or not self.strength:
return x
rnd_shape = [s if axis in self.axes else 1 for axis, s in enumerate(x.size())] # [x.size(axis) for axis in self.axes]
if self.mode == 'drop':
p = 1 - self.strength
rnd = np.random.binomial(1, p=p, size=rnd_shape) / p
elif self.mode == 'mul':
rnd = (1 + self.strength) ** np.random.normal(size=rnd_shape)
else:
coef = self.strength * x.size(1) ** 0.5
rnd = np.random.normal(size=rnd_shape) * coef + 1
if self.normalize:
rnd = rnd / np.linalg.norm(rnd, keepdims=True)
rnd = Variable(torch.from_numpy(rnd).type(x.data.type()))
if x.is_cuda:
rnd = rnd.cuda()
return x * rnd
def __repr__(self):
param_str = '(mode = %s, strength = %s, axes = %s, normalize = %s)' % (self.mode, self.strength, self.axes, self.normalize)
return self.__class__.__name__ + param_str