-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathpt.py
More file actions
278 lines (206 loc) · 7.92 KB
/
pt.py
File metadata and controls
278 lines (206 loc) · 7.92 KB
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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import numpy as np
import struct
LAYER_DENSE = 1
LAYER_CONV_1D = 2
LAYER_CONV_2D = 3
LAYER_LOCALLY_1D = 4
LAYER_FLATTEN = 6
LAYER_ELU = 7
LAYER_ACTIVATION = 8
LAYER_MAXPOOLING_2D = 9
LAYER_LSTM = 10
LAYER_EMBEDDING = 11
LAYER_BATCH_NORMALIZATION = 12
LAYER_LEAKY_RELU = 13
LAYER_GLOBAL_MAXPOOLING_2D = 14
LAYER_INPUT = 15
LAYER_REPEAT_VECTOR = 16
ACTIVATION_LINEAR = 1
ACTIVATION_RELU = 2
ACTIVATION_ELU = 3
ACTIVATION_SOFTPLUS = 4
ACTIVATION_SOFTSIGN = 5
ACTIVATION_SIGMOID = 6
ACTIVATION_TANH = 7
ACTIVATION_HARD_SIGMOID = 8
ACTIVATION_SOFTMAX = 9
ACTIVATION_SELU = 10
def write_tensor(f, data, dims=1):
'''
Writes tensor as flat array of floats to file in 1024 chunks,
prevents memory explosion writing very large arrays to disk
when calling struct.pack().
'''
for stride in data.shape[:dims]:
f.write(struct.pack('I', stride))
data = data.flatten()
step = 1024
written = 0
for i in np.arange(0, len(data), step):
remaining = min(len(data) - i, step)
written += remaining
f.write(struct.pack('=%sf' % remaining, *data[i: i + remaining]))
assert written == len(data)
def export_activation(f, activation):
if activation == 'linear':
f.write(struct.pack('I', ACTIVATION_LINEAR))
elif activation == 'relu':
f.write(struct.pack('I', ACTIVATION_RELU))
elif activation == 'elu':
f.write(struct.pack('I', ACTIVATION_ELU))
elif activation == 'softplus':
f.write(struct.pack('I', ACTIVATION_SOFTPLUS))
elif activation == 'softsign':
f.write(struct.pack('I', ACTIVATION_SOFTSIGN))
elif activation == 'sigmoid':
f.write(struct.pack('I', ACTIVATION_SIGMOID))
elif activation == 'tanh':
f.write(struct.pack('I', ACTIVATION_TANH))
elif activation == 'hard_sigmoid':
f.write(struct.pack('I', ACTIVATION_HARD_SIGMOID))
elif activation == 'softmax':
f.write(struct.pack('I', ACTIVATION_SOFTMAX))
elif activation == 'selu':
f.write(struct.pack('I', ACTIVATION_SELU))
else:
assert False, "Unsupported activation type: %s" % activation
def export_layer_normalization(f, layer):
epsilon = layer.epsilon
gamma = layer.get_weights()[0]
beta = layer.get_weights()[1]
pop_mean = layer.get_weights()[2]
pop_variance = layer.get_weights()[3]
weights = gamma / np.sqrt(pop_variance + epsilon)
biases = beta - pop_mean * weights
f.write(struct.pack('I', LAYER_BATCH_NORMALIZATION))
write_tensor(f, weights)
write_tensor(f, biases)
def export_layer_dense(f, layer):
weights = layer.get_weights()[0]
biases = layer.get_weights()[1]
activation = layer.get_config()['activation']
weights = weights.transpose()
# shape: (outputs, dims)
f.write(struct.pack('I', LAYER_DENSE))
write_tensor(f, weights, 2)
write_tensor(f, biases)
export_activation(f, activation)
def export_layer_conv1d(f, layer):
weights = layer.get_weights()[0]
biases = layer.get_weights()[1]
activation = layer.get_config()['activation']
weights = weights.transpose(2, 0, 1)
# shape: (outputs, steps, dims)
f.write(struct.pack('I', LAYER_CONV_1D))
write_tensor(f, weights, 3)
write_tensor(f, biases)
export_activation(f, activation)
def export_layer_conv2d(f, layer):
weights = layer.get_weights()[0]
biases = layer.get_weights()[1]
activation = layer.get_config()['activation']
weights = weights.transpose(3, 0, 1, 2)
# shape: (outputs, rows, cols, depth)
f.write(struct.pack('I', LAYER_CONV_2D))
write_tensor(f, weights, 4)
write_tensor(f, biases)
export_activation(f, activation)
def export_layer_locally1d(f, layer):
weights = layer.get_weights()[0]
biases = layer.get_weights()[1]
activation = layer.get_config()['activation']
weights = weights.transpose(0, 2, 1)
# shape: (new_steps, outputs, ksize*dims)
f.write(struct.pack('I', LAYER_LOCALLY_1D))
write_tensor(f, weights, 3)
write_tensor(f, biases, 2)
export_activation(f, activation)
def export_layer_maxpooling2d(f, layer):
pool_size = layer.get_config()['pool_size']
f.write(struct.pack('I', LAYER_MAXPOOLING_2D))
f.write(struct.pack('I', pool_size[0]))
f.write(struct.pack('I', pool_size[1]))
def export_layer_lstm(f, layer):
inner_activation = layer.get_config()['recurrent_activation']
activation = layer.get_config()['activation']
return_sequences = int(layer.get_config()['return_sequences'])
weights = layer.get_weights()
units = layer.units
W_i = weights[0][:, :units].transpose()
W_f = weights[0][:, units: units*2].transpose()
W_c = weights[0][:, units*2: -units].transpose()
W_o = weights[0][:, -units:].transpose()
U_i = weights[1][:, :units].transpose()
U_f = weights[1][:, units: units*2].transpose()
U_c = weights[1][:, units*2: -units].transpose()
U_o = weights[1][:, -units:].transpose()
b_i = weights[2][:units].reshape((1, -1))
b_f = weights[2][units: units*2].reshape((1, -1))
b_c = weights[2][units*2: -units].reshape((1, -1))
b_o = weights[2][-units:].reshape((1, -1))
f.write(struct.pack('I', LAYER_LSTM))
write_tensor(f, W_i, 2)
write_tensor(f, U_i, 2)
write_tensor(f, b_i, 2)
write_tensor(f, W_f, 2)
write_tensor(f, U_f, 2)
write_tensor(f, b_f, 2)
write_tensor(f, W_c, 2)
write_tensor(f, U_c, 2)
write_tensor(f, b_c, 2)
write_tensor(f, W_o, 2)
write_tensor(f, U_o, 2)
write_tensor(f, b_o, 2)
export_activation(f, inner_activation)
export_activation(f, activation)
f.write(struct.pack('I', return_sequences))
def export_layer_embedding(f, layer):
weights = layer.get_weights()[0]
f.write(struct.pack('I', LAYER_EMBEDDING))
write_tensor(f, weights, 2)
def export_model(model, filename):
with open(filename, 'wb') as f:
model_layers = [
l for l in model.layers if type(l).__name__ not in ['Dropout']]
num_layers = len(model_layers)
f.write(struct.pack('I', num_layers))
for layer in model_layers:
layer_type = type(layer).__name__
if layer_type == 'Dense':
export_layer_dense(f, layer)
elif layer_type == 'Conv1D':
export_layer_conv1d(f, layer)
elif layer_type == 'Conv2D':
export_layer_conv2d(f, layer)
elif layer_type == 'LocallyConnected1D':
export_layer_locally1d(f, layer)
elif layer_type == 'Flatten':
f.write(struct.pack('I', LAYER_FLATTEN))
elif layer_type == 'ELU':
f.write(struct.pack('I', LAYER_ELU))
f.write(struct.pack('f', layer.alpha))
elif layer_type == 'Activation':
activation = layer.get_config()['activation']
f.write(struct.pack('I', LAYER_ACTIVATION))
export_activation(f, activation)
elif layer_type == 'MaxPooling2D':
export_layer_maxpooling2d(f, layer)
elif layer_type == 'GlobalMaxPooling2D':
f.write(struct.pack('I', LAYER_GLOBAL_MAXPOOLING_2D))
elif layer_type == 'LSTM':
export_layer_lstm(f, layer)
elif layer_type == 'Embedding':
export_layer_embedding(f, layer)
elif layer_type == 'BatchNormalization':
export_layer_normalization(f, layer)
elif layer_type == 'LeakyReLU':
f.write(struct.pack('I', LAYER_LEAKY_RELU))
f.write(struct.pack('f', layer.alpha))
elif layer_type == 'InputLayer':
f.write(struct.pack('I', LAYER_INPUT))
elif layer_type == 'RepeatVector':
f.write(struct.pack('I', LAYER_REPEAT_VECTOR))
n = layer.get_config()['n']
f.write(struct.pack('I', n))
else:
assert False, "Unsupported layer type: %s" % layer_type