-
Notifications
You must be signed in to change notification settings - Fork 210
/
func.py
207 lines (180 loc) · 9.12 KB
/
func.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
201
202
203
204
205
206
207
import tensorflow as tf
INF = 1e30
class cudnn_gru:
def __init__(self, num_layers, num_units, batch_size, input_size, keep_prob=1.0, is_train=None, scope=None):
self.num_layers = num_layers
self.grus = []
self.inits = []
self.dropout_mask = []
for layer in range(num_layers):
input_size_ = input_size if layer == 0 else 2 * num_units
gru_fw = tf.contrib.cudnn_rnn.CudnnGRU(1, num_units)
gru_bw = tf.contrib.cudnn_rnn.CudnnGRU(1, num_units)
init_fw = tf.tile(tf.Variable(
tf.zeros([1, 1, num_units])), [1, batch_size, 1])
init_bw = tf.tile(tf.Variable(
tf.zeros([1, 1, num_units])), [1, batch_size, 1])
mask_fw = dropout(tf.ones([1, batch_size, input_size_], dtype=tf.float32),
keep_prob=keep_prob, is_train=is_train, mode=None)
mask_bw = dropout(tf.ones([1, batch_size, input_size_], dtype=tf.float32),
keep_prob=keep_prob, is_train=is_train, mode=None)
self.grus.append((gru_fw, gru_bw, ))
self.inits.append((init_fw, init_bw, ))
self.dropout_mask.append((mask_fw, mask_bw, ))
def __call__(self, inputs, seq_len, keep_prob=1.0, is_train=None, concat_layers=True):
outputs = [tf.transpose(inputs, [1, 0, 2])]
for layer in range(self.num_layers):
gru_fw, gru_bw = self.grus[layer]
init_fw, init_bw = self.inits[layer]
mask_fw, mask_bw = self.dropout_mask[layer]
with tf.variable_scope("fw_{}".format(layer)):
out_fw, _ = gru_fw(
outputs[-1] * mask_fw, initial_state=(init_fw, ))
with tf.variable_scope("bw_{}".format(layer)):
inputs_bw = tf.reverse_sequence(
outputs[-1] * mask_bw, seq_lengths=seq_len, seq_dim=0, batch_dim=1)
out_bw, _ = gru_bw(inputs_bw, initial_state=(init_bw, ))
out_bw = tf.reverse_sequence(
out_bw, seq_lengths=seq_len, seq_dim=0, batch_dim=1)
outputs.append(tf.concat([out_fw, out_bw], axis=2))
if concat_layers:
res = tf.concat(outputs[1:], axis=2)
else:
res = outputs[-1]
res = tf.transpose(res, [1, 0, 2])
return res
class native_gru:
def __init__(self, num_layers, num_units, batch_size, input_size, keep_prob=1.0, is_train=None, scope="native_gru"):
self.num_layers = num_layers
self.grus = []
self.inits = []
self.dropout_mask = []
self.scope = scope
for layer in range(num_layers):
input_size_ = input_size if layer == 0 else 2 * num_units
gru_fw = tf.contrib.rnn.GRUCell(num_units)
gru_bw = tf.contrib.rnn.GRUCell(num_units)
init_fw = tf.tile(tf.Variable(
tf.zeros([1, num_units])), [batch_size, 1])
init_bw = tf.tile(tf.Variable(
tf.zeros([1, num_units])), [batch_size, 1])
mask_fw = dropout(tf.ones([batch_size, 1, input_size_], dtype=tf.float32),
keep_prob=keep_prob, is_train=is_train, mode=None)
mask_bw = dropout(tf.ones([batch_size, 1, input_size_], dtype=tf.float32),
keep_prob=keep_prob, is_train=is_train, mode=None)
self.grus.append((gru_fw, gru_bw, ))
self.inits.append((init_fw, init_bw, ))
self.dropout_mask.append((mask_fw, mask_bw, ))
def __call__(self, inputs, seq_len, keep_prob=1.0, is_train=None, concat_layers=True):
outputs = [inputs]
with tf.variable_scope(self.scope):
for layer in range(self.num_layers):
gru_fw, gru_bw = self.grus[layer]
init_fw, init_bw = self.inits[layer]
mask_fw, mask_bw = self.dropout_mask[layer]
with tf.variable_scope("fw_{}".format(layer)):
out_fw, _ = tf.nn.dynamic_rnn(
gru_fw, outputs[-1] * mask_fw, seq_len, initial_state=init_fw, dtype=tf.float32)
with tf.variable_scope("bw_{}".format(layer)):
inputs_bw = tf.reverse_sequence(
outputs[-1] * mask_bw, seq_lengths=seq_len, seq_dim=1, batch_dim=0)
out_bw, _ = tf.nn.dynamic_rnn(
gru_bw, inputs_bw, seq_len, initial_state=init_bw, dtype=tf.float32)
out_bw = tf.reverse_sequence(
out_bw, seq_lengths=seq_len, seq_dim=1, batch_dim=0)
outputs.append(tf.concat([out_fw, out_bw], axis=2))
if concat_layers:
res = tf.concat(outputs[1:], axis=2)
else:
res = outputs[-1]
return res
class ptr_net:
def __init__(self, batch, hidden, keep_prob=1.0, is_train=None, scope="ptr_net"):
self.gru = tf.contrib.rnn.GRUCell(hidden)
self.batch = batch
self.scope = scope
self.keep_prob = keep_prob
self.is_train = is_train
self.dropout_mask = dropout(tf.ones(
[batch, hidden], dtype=tf.float32), keep_prob=keep_prob, is_train=is_train)
def __call__(self, init, match, d, mask):
with tf.variable_scope(self.scope):
d_match = dropout(match, keep_prob=self.keep_prob,
is_train=self.is_train)
inp, logits1 = pointer(d_match, init * self.dropout_mask, d, mask)
d_inp = dropout(inp, keep_prob=self.keep_prob,
is_train=self.is_train)
_, state = self.gru(d_inp, init)
tf.get_variable_scope().reuse_variables()
_, logits2 = pointer(d_match, state * self.dropout_mask, d, mask)
return logits1, logits2
def dropout(args, keep_prob, is_train, mode="recurrent"):
if keep_prob < 1.0:
noise_shape = None
scale = 1.0
shape = tf.shape(args)
if mode == "embedding":
noise_shape = [shape[0], 1]
scale = keep_prob
if mode == "recurrent" and len(args.get_shape().as_list()) == 3:
noise_shape = [shape[0], 1, shape[-1]]
args = tf.cond(is_train, lambda: tf.nn.dropout(
args, keep_prob, noise_shape=noise_shape) * scale, lambda: args)
return args
def softmax_mask(val, mask):
return -INF * (1 - tf.cast(mask, tf.float32)) + val
def pointer(inputs, state, hidden, mask, scope="pointer"):
with tf.variable_scope(scope):
u = tf.concat([tf.tile(tf.expand_dims(state, axis=1), [
1, tf.shape(inputs)[1], 1]), inputs], axis=2)
s0 = tf.nn.tanh(dense(u, hidden, use_bias=False, scope="s0"))
s = dense(s0, 1, use_bias=False, scope="s")
s1 = softmax_mask(tf.squeeze(s, [2]), mask)
a = tf.expand_dims(tf.nn.softmax(s1), axis=2)
res = tf.reduce_sum(a * inputs, axis=1)
return res, s1
def summ(memory, hidden, mask, keep_prob=1.0, is_train=None, scope="summ"):
with tf.variable_scope(scope):
d_memory = dropout(memory, keep_prob=keep_prob, is_train=is_train)
s0 = tf.nn.tanh(dense(d_memory, hidden, scope="s0"))
s = dense(s0, 1, use_bias=False, scope="s")
s1 = softmax_mask(tf.squeeze(s, [2]), mask)
a = tf.expand_dims(tf.nn.softmax(s1), axis=2)
res = tf.reduce_sum(a * memory, axis=1)
return res
def dot_attention(inputs, memory, mask, hidden, keep_prob=1.0, is_train=None, scope="dot_attention"):
with tf.variable_scope(scope):
d_inputs = dropout(inputs, keep_prob=keep_prob, is_train=is_train)
d_memory = dropout(memory, keep_prob=keep_prob, is_train=is_train)
JX = tf.shape(inputs)[1]
with tf.variable_scope("attention"):
inputs_ = tf.nn.relu(
dense(d_inputs, hidden, use_bias=False, scope="inputs"))
memory_ = tf.nn.relu(
dense(d_memory, hidden, use_bias=False, scope="memory"))
outputs = tf.matmul(inputs_, tf.transpose(
memory_, [0, 2, 1])) / (hidden ** 0.5)
mask = tf.tile(tf.expand_dims(mask, axis=1), [1, JX, 1])
logits = tf.nn.softmax(softmax_mask(outputs, mask))
outputs = tf.matmul(logits, memory)
res = tf.concat([inputs, outputs], axis=2)
with tf.variable_scope("gate"):
dim = res.get_shape().as_list()[-1]
d_res = dropout(res, keep_prob=keep_prob, is_train=is_train)
gate = tf.nn.sigmoid(dense(d_res, dim, use_bias=False))
return res * gate
def dense(inputs, hidden, use_bias=True, scope="dense"):
with tf.variable_scope(scope):
shape = tf.shape(inputs)
dim = inputs.get_shape().as_list()[-1]
out_shape = [shape[idx] for idx in range(
len(inputs.get_shape().as_list()) - 1)] + [hidden]
flat_inputs = tf.reshape(inputs, [-1, dim])
W = tf.get_variable("W", [dim, hidden])
res = tf.matmul(flat_inputs, W)
if use_bias:
b = tf.get_variable(
"b", [hidden], initializer=tf.constant_initializer(0.))
res = tf.nn.bias_add(res, b)
res = tf.reshape(res, out_shape)
return res