-
Notifications
You must be signed in to change notification settings - Fork 0
/
rnn_model.py
196 lines (171 loc) · 8.31 KB
/
rnn_model.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
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from easydict import EasyDict
import glob
import numpy as np
import tensorflow as tf
import tensorflow_addons as tfa
import utils
from tensorflow import keras
layers = tf.keras.layers
class RnnWalkBase(tf.keras.Model):
def __init__(self,
params,
classes,
net_input_dim,
model_fn=None,
model_must_be_load=False,
dump_model_visualization=True,
optimizer=None):
super(RnnWalkBase, self).__init__(name='')
self._classes = classes
self._params = params
self._model_must_be_load = model_must_be_load
self._init_layers()
inputs = tf.keras.layers.Input(shape=(100, net_input_dim))
self.build(input_shape=(self._params.n_walks_per_model, 100, net_input_dim))
outputs = self.call(inputs)
if dump_model_visualization:
tmp_model = keras.Model(inputs=inputs, outputs=outputs, name='WalkModel')
tmp_model.summary(print_fn=self._print_fn)
tf.keras.utils.plot_model(tmp_model, params.logdir + '/RnnWalkModel.png', show_shapes=True)
self.manager = None
if optimizer:
if model_fn:
self.checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=self)
else:
self.checkpoint = tf.train.Checkpoint(optimizer=optimizer, model=self)
self.manager = tf.train.CheckpointManager(self.checkpoint, directory=self._params.logdir, max_to_keep=5)
if model_fn: # Transfer learning
self.load_weights(model_fn)
self.checkpoint.optimizer = optimizer
else:
self.load_weights()
else:
self.checkpoint = tf.train.Checkpoint(model=self)
if model_fn is None:
model_fn = self._get_latest_keras_model()
self.load_weights(model_fn)
def _print_fn(self, st):
with open(self._params.logdir + '/log.txt', 'at') as f:
f.write(st + '\n')
def _get_latest_keras_model(self):
filenames = glob.glob(self._params.logdir + '/*model2keep__*')
iters_saved = [int(f.split('model2keep__')[-1].split('.keras')[0]) for f in filenames]
return filenames[np.argmax(iters_saved)]
def load_weights(self, filepath=None):
if filepath is not None and filepath.endswith('.keras'):
super(RnnWalkBase, self).load_weights(filepath)
elif filepath is None:
_ = self.checkpoint.restore(self.manager.latest_checkpoint)
print(utils.color.BLUE, 'Starting from iteration: ', self.checkpoint.optimizer.iterations.numpy(),
utils.color.END)
else:
filepath = filepath.replace('//', '/')
_ = self.checkpoint.restore(filepath)
def save_weights(self, folder, step=None, keep=False):
if self.manager is not None:
self.manager.save()
if keep:
super(RnnWalkBase, self).save_weights(folder + '/learned_model2keep__' + str(step).zfill(8) + '.keras')
class RnnWalkNet(RnnWalkBase):
def __init__(self,
params,
classes,
net_input_dim,
model_fn,
model_must_be_load=False,
dump_model_visualization=True,
optimizer=None):
if params.layer_sizes is None:
self._layer_sizes = {'fc1': 128, 'fc2': 256, 'gru1': 1024, 'gru2': 1024, 'gru3': 512}
else:
self._layer_sizes = params.layer_sizes
self.attention_last_only = False
super(RnnWalkNet, self).__init__(params, classes, net_input_dim, model_fn, model_must_be_load=model_must_be_load,
dump_model_visualization=dump_model_visualization, optimizer=optimizer)
def _init_layers(self):
kernel_regularizer = tf.keras.regularizers.l2(0.0001)
initializer = tf.initializers.Orthogonal(3)
self._use_norm_layer = self._params.use_norm_layer is not None
if self._params.use_norm_layer == 'InstanceNorm':
self._norm1 = tfa.layers.InstanceNormalization(axis=2)
self._norm2 = tfa.layers.InstanceNormalization(axis=2)
elif self._params.use_norm_layer == 'BatchNorm':
self._norm1 = layers.BatchNormalization(axis=2)
self._norm2 = layers.BatchNormalization(axis=2)
self._fc1 = layers.Dense(self._layer_sizes['fc1'], kernel_regularizer=kernel_regularizer,
bias_regularizer=kernel_regularizer,
kernel_initializer=initializer)
self._fc2 = layers.Dense(self._layer_sizes['fc2'], kernel_regularizer=kernel_regularizer,
bias_regularizer=kernel_regularizer,
kernel_initializer=initializer)
rnn_layer = layers.GRU
attention_layer = layers.Attention
self._gru1 = rnn_layer(self._layer_sizes['gru1'], time_major=False, return_sequences=True, return_state=False,
dropout=self._params.net_gru_dropout,
recurrent_initializer=initializer, kernel_initializer=initializer,
kernel_regularizer=kernel_regularizer, recurrent_regularizer=kernel_regularizer,
bias_regularizer=kernel_regularizer)
self._gru2 = rnn_layer(self._layer_sizes['gru2'], time_major=False, return_sequences=True, return_state=False,
dropout=self._params.net_gru_dropout,
recurrent_initializer=initializer, kernel_initializer=initializer,
kernel_regularizer=kernel_regularizer, recurrent_regularizer=kernel_regularizer,
bias_regularizer=kernel_regularizer)
self._gru3 = rnn_layer(self._layer_sizes['gru3'], time_major=False,
return_sequences=not self._params.one_label_per_model,
return_state=False,
dropout=self._params.net_gru_dropout,
recurrent_initializer=initializer, kernel_initializer=initializer,
kernel_regularizer=kernel_regularizer, recurrent_regularizer=kernel_regularizer,
bias_regularizer=kernel_regularizer)
if self._params.attention:
self._attention_layers = [attention_layer(dropout=self._params.net_gru_dropout) for _ in range(3)]
self._att_norms = [tfa.layers.InstanceNormalization(axis=2) for _ in range(3)]
self._fc_last = layers.Dense(self._classes, activation=self._params.last_layer_actication,
kernel_regularizer=kernel_regularizer, bias_regularizer=kernel_regularizer,
kernel_initializer=initializer)
self._pooling = layers.MaxPooling1D(pool_size=3, strides=2, padding='same')
def walks_attention(self, input, index, training, warmup_stage=False):
if not self._params.attention or warmup_stage:
return input
if self.attention_last_only and index < 2:
return input
shape_before = input.shape.as_list()
# move back to shape [bsz, num_walks, seq_len, 3] to calc attention only on the same mesh entries
# input = tf.expand_dims(input, axis=0)
input_expanded = tf.reshape(input,
(-1, self._params.n_walks_per_model, input.shape[-2], input.shape[-1]))
att_result = self._attention_layers[index](inputs=[input_expanded, input_expanded], training=training)
att_result = tf.reshape(att_result,
(-1, input.shape[-2], input.shape[-1]))
# input_cntx = tf.squeeze(input_cntx, axis=[0])
shape_after = att_result.shape.as_list()
assert shape_before == shape_after
output = input + att_result
# output = self._att_norms[index](output, training=training)
return output
def call(self, model_ftrs, classify=True, skip_1st=True, training=True, warmup_stage=False):
if skip_1st:
x = model_ftrs[:, 1:]
else:
x = model_ftrs
x = self._fc1(x)
if self._use_norm_layer:
x = self._norm1(x, training=training)
x = tf.nn.relu(x)
x = self._fc2(x)
if self._use_norm_layer:
x = self._norm2(x, training=training)
x = tf.nn.relu(x)
x1 = self._gru1(x, training=training)
x1 = self.walks_attention(x1, 0, training, warmup_stage)
x2 = self._gru2(x1, training=training)
x2 = self.walks_attention(x2, 1, training, warmup_stage)
x3 = self._gru3(x2, training=training)
# x3 += self.walks_attention(x3, 2, training, warmup_stage)
x = x3
if classify:
x = self._fc_last(x)
return x