-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathops_sn.py
187 lines (159 loc) · 7.72 KB
/
ops_sn.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
import math
import warnings
from functools import partial
import numpy as np
import tensorflow as tf
import tensorflow.contrib.slim as slim
from tensorflow.contrib.layers.python.layers import initializers
from tensorflow.python.framework import ops
# ------ SN GAN plug in ----------------------
# from : https://github.com/minhnhat93/tf-SNDCGAN/blob/master/libs/ops.py
def scope_has_variables(scope):
return len(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=scope.name)) > 0
def sn_conv2d(input_, output_dim,
k_h=4, k_w=4, d_h=2, d_w=2, stddev=None,
name="conv2d", spectral_normed=False, update_collection=None, with_w=False, padding="SAME"):
# Glorot intialization
# For RELU nonlinearity, it's sqrt(2./(n_in)) instead
fan_in = k_h * k_w * input_.get_shape().as_list()[-1]
fan_out = k_h * k_w * output_dim
if stddev is None:
stddev = np.sqrt(2. / (fan_in))
with tf.variable_scope(name) as scope:
if scope_has_variables(scope):
scope.reuse_variables()
w = tf.get_variable("w", [k_h, k_w, input_.get_shape()[-1], output_dim],
initializer=tf.truncated_normal_initializer(stddev=stddev))
if spectral_normed:
conv = tf.nn.conv2d(input_, spectral_normed_weight(w, update_collection=update_collection),
strides=[1, d_h, d_w, 1], padding=padding)
else:
conv = tf.nn.conv2d(input_, w, strides=[
1, d_h, d_w, 1], padding=padding)
biases = tf.get_variable(
"b", [output_dim], initializer=tf.constant_initializer(0.0))
conv = tf.reshape(tf.nn.bias_add(conv, biases), conv.get_shape())
if with_w:
return conv, w, biases
else:
return conv
def sn_deconv2d(input_, output_shape,
k_h=4, k_w=4, d_h=2, d_w=2, stddev=None,
name="deconv2d", spectral_normed=False, update_collection=None, with_w=False, padding="SAME"):
# Glorot initialization
# For RELU nonlinearity, it's sqrt(2./(n_in)) instead
fan_in = k_h * k_w * input_.get_shape().as_list()[-1]
fan_out = k_h * k_w * output_shape[-1]
if stddev is None:
stddev = np.sqrt(2. / (fan_in))
with tf.variable_scope(name) as scope:
if scope_has_variables(scope):
scope.reuse_variables()
# filter : [height, width, output_channels, in_channels]
w = tf.get_variable("w", [k_h, k_w, output_shape[-1], input_.get_shape()[-1]],
initializer=tf.truncated_normal_initializer(stddev=stddev))
if spectral_normed:
deconv = tf.nn.conv2d_transpose(input_, spectral_normed_weight(w, update_collection=update_collection),
output_shape=output_shape,
strides=[1, d_h, d_w, 1], padding=padding)
else:
deconv = tf.nn.conv2d_transpose(input_, w, output_shape=output_shape,
strides=[1, d_h, d_w, 1], padding=padding)
biases = tf.get_variable(
"b", [output_shape[-1]], initializer=tf.constant_initializer(0))
deconv = tf.reshape(tf.nn.bias_add(deconv, biases), deconv.get_shape())
if with_w:
return deconv, w, biases
else:
return deconv
def sn_lrelu(x, leak=0.1):
return tf.maximum(x, leak * x)
def sn_linear(input_, output_size, name="linear", spectral_normed=False, update_collection=None, stddev=None, bias_start=0.0, with_biases=True,
with_w=False):
shape = input_.get_shape().as_list()
if stddev is None:
stddev = np.sqrt(1. / (shape[1]))
with tf.variable_scope(name) as scope:
if scope_has_variables(scope):
scope.reuse_variables()
weight = tf.get_variable("w", [shape[1], output_size], tf.float32,
tf.truncated_normal_initializer(stddev=stddev))
if with_biases:
bias = tf.get_variable("b", [output_size],
initializer=tf.constant_initializer(bias_start))
if spectral_normed:
mul = tf.matmul(input_, spectral_normed_weight(
weight, update_collection=update_collection))
else:
mul = tf.matmul(input_, weight)
if with_w:
if with_biases:
return mul + bias, weight, bias
else:
return mul, weight, None
else:
if with_biases:
return mul + bias
else:
return mul
def sn_batch_norm(input, is_training=True, momentum=0.9, epsilon=2e-5, in_place_update=True, name="batch_norm"):
if in_place_update:
return tf.contrib.layers.batch_norm(input,
decay=momentum,
center=True,
scale=True,
epsilon=epsilon,
updates_collections=None,
is_training=is_training,
scope=name)
else:
return tf.contrib.layers.batch_norm(input,
decay=momentum,
center=True,
scale=True,
epsilon=epsilon,
is_training=is_training,
scope=name)
NO_OPS = 'NO_OPS'
def _l2normalize(v, eps=1e-12):
return v / (tf.reduce_sum(v ** 2) ** 0.5 + eps)
def spectral_normed_weight(W, u=None, num_iters=1, update_collection=None, with_sigma=False):
# Usually num_iters = 1 will be enough
W_shape = W.shape.as_list()
W_reshaped = tf.reshape(W, [-1, W_shape[-1]])
if u is None:
u = tf.get_variable(
"u", [1, W_shape[-1]], initializer=tf.truncated_normal_initializer(), trainable=False)
def power_iteration(i, u_i, v_i):
v_ip1 = _l2normalize(tf.matmul(u_i, tf.transpose(W_reshaped)))
u_ip1 = _l2normalize(tf.matmul(v_ip1, W_reshaped))
return i + 1, u_ip1, v_ip1
_, u_final, v_final = tf.while_loop(
cond=lambda i, _1, _2: i < num_iters,
body=power_iteration,
loop_vars=(tf.constant(0, dtype=tf.int32),
u, tf.zeros(dtype=tf.float32, shape=[1, W_reshaped.shape.as_list()[0]]))
)
if update_collection is None:
warnings.warn('Setting update_collection to None will make u being updated every W execution. This maybe undesirable'
'. Please consider using a update collection instead.')
sigma = tf.matmul(tf.matmul(v_final, W_reshaped),
tf.transpose(u_final))[0, 0]
# sigma = tf.reduce_sum(tf.matmul(u_final, tf.transpose(W_reshaped)) * v_final)
W_bar = W_reshaped / sigma
with tf.control_dependencies([u.assign(u_final)]):
W_bar = tf.reshape(W_bar, W_shape)
else:
sigma = tf.matmul(tf.matmul(v_final, W_reshaped),
tf.transpose(u_final))[0, 0]
# sigma = tf.reduce_sum(tf.matmul(u_final, tf.transpose(W_reshaped)) * v_final)
W_bar = W_reshaped / sigma
W_bar = tf.reshape(W_bar, W_shape)
# Put NO_OPS to not update any collection. This is useful for the second call of discriminator if the update_op
# has already been collected on the first call.
if update_collection != NO_OPS:
tf.add_to_collection(update_collection, u.assign(u_final))
if with_sigma:
return W_bar, sigma
else:
return W_bar