-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtrain_twostage_tripletloss_online.py
346 lines (320 loc) · 18.9 KB
/
train_twostage_tripletloss_online.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
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
from absl import app, flags, logging
from absl.flags import FLAGS
import os
import tensorflow as tf
if tf.__version__.startswith('1'):# important if you want to run with tf1.x,
print('[*] enable eager execution')
tf.compat.v1.enable_eager_execution()
import time
from tensorflow.keras.callbacks import ModelCheckpoint, TensorBoard
from modules.models import ArcFaceModel,IoMFaceModelFromArFace,IoMFaceModelFromArFaceMLossHead,IoMFaceModelFromArFace2,IoMFaceModelFromArFace3,IoMFaceModelFromArFace_T,IoMFaceModelFromArFace_T1
from modules.utils import set_memory_growth, load_yaml, get_ckpt_inf
from losses.euclidan_distance_loss import triplet_loss, triplet_loss_omoindrot
from losses.metric_learning_loss import arcface_pair_loss,ms_loss,bin_LUT_loss,code_balance_loss
from losses.sampling_matters import margin_loss,triplet_loss_with_sampling
import modules.dataset_triplet as dataset_triplet
from modules.evaluations import val_LFW
import matplotlib.pyplot as plt
import numpy as np
import collections
flags.DEFINE_string('cfg_path', './configs/iom_res50_twostage_triplet_online.yaml', 'config file path')
flags.DEFINE_string('gpu', '0', 'which gpu to use')
flags.DEFINE_enum('mode', 'eager_tf', ['fit', 'eager_tf'],
'fit: model.fit, eager_tf: custom GradientTape')
flags.DEFINE_integer('freezeBackbone', 1, 'Freeze the backbone?')
# modules.utils.set_memory_growth()
def main(_):
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
os.environ['CUDA_VISIBLE_DEVICES'] = FLAGS.gpu
logger = tf.get_logger()
logger.disabled = True
logger.setLevel(logging.FATAL)
set_memory_growth()
freezeBackbone = FLAGS.freezeBackbone
cfg = load_yaml(FLAGS.cfg_path)
permKey = None
debuging = False
if cfg['head_type'] == 'IoMHead':#
#permKey = generatePermKey(cfg['embd_shape'])
permKey = tf.eye(cfg['embd_shape']) # for training, we don't permutate, won't influence the performance
arcmodel = ArcFaceModel(size=cfg['input_size'],
embd_shape=cfg['embd_shape'],
backbone_type=cfg['backbone_type'],
head_type='ArcHead',
training=False, # here equal false, just get the model without acrHead, to load the model trained by arcface
cfg=cfg)
if cfg['train_dataset']:
logging.info("load dataset from "+cfg['train_dataset'])
dataset_len = cfg['num_samples']
steps_per_epoch = dataset_len // cfg['batch_size']
train_dataset = dataset_triplet.load_online_pair_wise_dataset(cfg['train_dataset'],ext = cfg['img_ext'],dataset_ext = cfg['dataset_ext'],samples_per_class = cfg['samples_per_class'],classes_per_batch = cfg['classes_per_batch'],is_ccrop = False)
else:
logging.info("load fake dataset.")
steps_per_epoch = 1
print('[*] batch size',cfg['batch_size'])
learning_rate = tf.constant(cfg['base_lr'])
# optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate)
# loss_fn = SoftmaxLoss() #############################################
loss_fn_quanti = triplet_loss.compute_quanti_loss
m = cfg['m']
q = cfg['q']
if cfg['backbone_type'] == 'ResNet50':
arc_ckpt_path = tf.train.latest_checkpoint('./checkpoints/arc_res50/')
elif cfg['backbone_type'] == 'InceptionResNetV2':
arc_ckpt_path = tf.train.latest_checkpoint('./checkpoints/arc_InceptionResNetV2/')
elif cfg['backbone_type'] == 'lresnet100e_ir':
arc_ckpt_path = tf.train.latest_checkpoint('./checkpoints/arc_lresnet100e_ir/')
elif cfg['backbone_type'] == 'Xception':
arc_ckpt_path = tf.train.latest_checkpoint('./checkpoints/arc_Xception/')
elif cfg['backbone_type'] == 'VGG19':
arc_ckpt_path = tf.train.latest_checkpoint('./checkpoints/arc_vgg19/')
elif cfg['backbone_type'] == 'Insight_ResNet100' or cfg['backbone_type'] == 'Insight_ResNet50':
arc_ckpt_path = None # here we don't have any check point file for this pre_build model, as it is loaded with weights
else:
arc_ckpt_path = tf.train.latest_checkpoint('./checkpoints/arc_res50/')
ckpt_path = tf.train.latest_checkpoint('./checkpoints/' + cfg['sub_name'])
if (not ckpt_path) & (arc_ckpt_path is not None):
print("[*] load ckpt from {}".format(arc_ckpt_path))
arcmodel.load_weights(arc_ckpt_path)
# epochs, steps = get_ckpt_inf(ckpt_path, steps_per_epoch)
if cfg['loss_fun'].startswith('margin_loss'):
model = IoMFaceModelFromArFaceMLossHead(size=cfg['input_size'],
arcmodel=arcmodel, training=True,
permKey=permKey, cfg=cfg)
optimizer = tf.keras.optimizers.Adam(learning_rate=learning_rate)# seems can only use adam???
# optimizer = tf.train.MomentumOptimizer( learning_rate, momentum=0.9, )
else:
# here I add the extra IoM layer and head
if cfg['hidden_layer_remark'] == '1':
model = IoMFaceModelFromArFace(size=cfg['input_size'],
arcmodel=arcmodel, training=True,
permKey=permKey, cfg=cfg)
elif cfg['hidden_layer_remark'] == '2':
model = IoMFaceModelFromArFace2(size=cfg['input_size'],
arcmodel=arcmodel, training=True,
permKey=permKey, cfg=cfg)
elif cfg['hidden_layer_remark'] == '3':
model = IoMFaceModelFromArFace3(size=cfg['input_size'],
arcmodel=arcmodel, training=True,
permKey=permKey, cfg=cfg)
elif cfg['hidden_layer_remark'] == 'T':
model = IoMFaceModelFromArFace_T(size=cfg['input_size'],
arcmodel=arcmodel, training=True,
permKey=permKey, cfg=cfg)
elif cfg['hidden_layer_remark'] == 'T1':# one layer
model = IoMFaceModelFromArFace_T1(size=cfg['input_size'],
arcmodel=arcmodel, training=True,
permKey=permKey, cfg=cfg)
else:
model = IoMFaceModelFromArFace(size=cfg['input_size'],
arcmodel=arcmodel, training=True,
permKey=permKey, cfg=cfg)
optimizer = tf.keras.optimizers.SGD(
learning_rate=learning_rate, momentum=0.9, nesterov=True)# can use adam sgd
if freezeBackbone:
print('[*] Freeze the backbone!!!!!!!!!!!')
for layer in model.layers:
if layer.name == 'arcface_model':
layer.trainable = False
# ########可训练层
# model.layers[0].trainable = True
for x in model.trainable_weights:
print("trainable:",x.name)
print('\n')
model.summary(line_length=80)
ckpt_path = tf.train.latest_checkpoint('./checkpoints/' + cfg['sub_name'])
if ckpt_path is not None:
print("[*] load ckpt from {}".format(ckpt_path))
model.load_weights(ckpt_path)
epochs, steps = get_ckpt_inf(ckpt_path, steps_per_epoch)
else:
print("[*] training from scratch.")
epochs, steps = 1, 1
# test first
if debuging:
acc_lfw, best_th_lfw, auc_lfw, eer_lfw, embeddings_lfw = val_LFW(model, cfg)
print(
" acc {:.4f}, th: {:.2f}, auc {:.4f}, EER {:.4f}".format(acc_lfw, best_th_lfw, auc_lfw, eer_lfw))
tmp_best_acc = 0
if FLAGS.mode == 'eager_tf':
# Eager mode is great for debugging
# Non eager graph mode is recommended for real training
if tf.__version__.startswith('1'): # important is you want to run with tf1.x,
summary_writer = tf.contrib.summary.create_file_writer(
'./logs/' + cfg['sub_name'])
else:
summary_writer = tf.summary.create_file_writer(
'./logs/' + cfg['sub_name'])
train_dataset = iter(train_dataset)
while epochs <= cfg['epochs']:
if steps % 5 == 0:
start = time.time()
if steps % 5000 == 0: #reshuffle and generate every epoch steps % steps_per_epoch == 0
print('[*] reload DS.')
train_dataset = dataset_triplet.load_online_pair_wise_dataset(cfg['train_dataset'], ext=cfg['img_ext'],
dataset_ext=cfg['dataset_ext'],
samples_per_class=cfg[
'samples_per_class'],
classes_per_batch=cfg[
'classes_per_batch'], is_ccrop=False)
train_dataset = iter(train_dataset)
inputs, labels = next(train_dataset) #print(inputs[0][1][:]) labels[2][:]
with tf.GradientTape() as tape:
logist = model((inputs, labels), training=True)
reg_loss = tf.cast(tf.reduce_sum(model.losses),tf.double)
quanti_loss = 0.0
if cfg['quanti']:
quanti_loss = tf.cast(loss_fn_quanti(logist),tf.float64)
code_balance_loss_cal = 0.0
# for metric learning, we have 1. batch_hard_triplet 2. batch_all_triplet_loss 3. batch_all_arc_triplet_loss
if cfg['loss_fun'] == 'batch_hard_triplet':
pred_loss = triplet_loss_omoindrot.batch_hard_triplet_loss(labels, logist,margin=cfg['triplet_margin'])
elif cfg['loss_fun'] == 'batch_all_triplet_loss':
pred_loss = triplet_loss_omoindrot.batch_all_triplet_loss(labels, logist,margin=cfg['triplet_margin'], scala=100)
elif cfg['loss_fun'] == 'ms_loss':
pred_loss = ms_loss.ms_loss(labels, logist,ms_mining=True)
elif cfg['loss_fun'] == 'margin_loss':
pred_loss = tf.constant(0.0,tf.float64)
elif cfg['loss_fun'] == 'margin_loss_batch_all_triplet':
pred_loss = triplet_loss_omoindrot.batch_all_triplet_loss(labels, logist,margin=cfg['triplet_margin'], scala=100)
elif cfg['loss_fun'] == 'margin_loss_batch_hard_triplet':
pred_loss = triplet_loss_omoindrot.batch_hard_triplet_loss(labels, logist,margin=cfg['triplet_margin'], scala=100)
elif cfg['loss_fun'] == 'batch_all_arc_triplet_loss':
pred_loss, _ ,_= arcface_pair_loss.batch_all_triplet_arcloss(labels, logist, arc_margin=cfg['triplet_margin'], scala=32)
elif cfg['loss_fun'] == 'batch_hard_arc_triplet_loss':
pred_loss = arcface_pair_loss.batch_hard_triplet_arcloss(labels, logist, steps,summary_writer,arc_margin=cfg['triplet_margin'], scala=32,minimize_dist=True)
elif cfg['loss_fun'] == 'semihard_triplet_loss':
pred_loss = triplet_loss.semihard_triplet_loss(labels, logist, margin=cfg['triplet_margin'])
elif cfg['loss_fun'] == 'triplet_sampling':
beta_0 = 1.2
elif cfg['loss_fun'] == 'only_bin_loss':
pred_loss = tf.constant(0.0, tf.float64)
reg_loss = tf.constant(0.0, tf.float64)
quanti_loss = tf.constant(0.0, tf.float64)
if cfg['bin_lut_loss']=='tanh':
bin_loss = bin_LUT_loss.binary_loss_LUT(labels, logist,q) * 0.001
elif cfg['bin_lut_loss']=='sigmoid':
bin_loss = bin_LUT_loss.binary_loss_LUT_sigmoid(labels, logist,q) * 0.001
else:
bin_loss = tf.constant(0.0,tf.float64)
if 'code_balance_loss' in cfg:
# code_balance_loss_cal_real = code_balance_loss.binary_balance_loss_q(logist, steps, summary_writer, q=cfg['q'])
code_balance_loss_cal_real = code_balance_loss.binary_balance_loss_merge(logist, steps, summary_writer, q=cfg['q'])
if cfg['code_balance_loss'] :
code_balance_loss_cal = code_balance_loss_cal_real
total_loss = pred_loss + reg_loss * 0.5 + quanti_loss* 0.5 + bin_loss + code_balance_loss_cal
grads = tape.gradient(total_loss, model.trainable_variables)
optimizer.apply_gradients(zip(grads, model.trainable_variables))
if steps % 5 == 0:
end = time.time()
verb_str = "Epoch {}/{}: {}/{}, loss={:.2f}, lr={:.4f}, time per step={:.2f}s, remaining time 4 this epoch={:.2f}min"
print(verb_str.format(epochs, cfg['epochs'],
steps % steps_per_epoch,
steps_per_epoch,
total_loss.numpy(),
learning_rate.numpy(),end - start,(steps_per_epoch -(steps % steps_per_epoch)) * (end - start) /60.0))
with summary_writer.as_default():
if tf.__version__.startswith('1'):
tf.contrib.summary.scalar(
'loss/total loss', total_loss, step=steps)
tf.contrib.summary.scalar(
'loss/pred loss', pred_loss, step=steps)
tf.contrib.summary.scalar(
'loss/reg loss', reg_loss, step=steps)
tf.contrib.summary.scalar(
'loss/quanti loss', quanti_loss, step=steps)
tf.contrib.summary.scalar(
'loss/quanti bin_loss', bin_loss, step=steps)
tf.contrib.summary.scalar(
'loss/code balance loss', code_balance_loss_cal, step=steps)
tf.contrib.summary.scalar(
'learning rate', optimizer.lr, step=steps)
else:
tf.summary.scalar(
'loss/total loss', total_loss, step=steps)
tf.summary.scalar(
'loss/pred loss', pred_loss, step=steps)
tf.summary.scalar(
'loss/reg loss', reg_loss, step=steps)
tf.summary.scalar(
'loss/quanti loss', quanti_loss, step=steps)
tf.summary.scalar(
'loss/quanti bin_loss', bin_loss, step=steps)
tf.summary.scalar(
'loss/code balance loss', code_balance_loss_cal, step=steps)
tf.summary.scalar(
'learning rate', optimizer.lr, step=steps)
if debuging:
if steps % 1000 == 0:
acc_lfw, best_th_lfw, auc_lfw, eer_lfw, embeddings_lfw = val_LFW(model, cfg)
print(
" acc {:.4f}, th: {:.2f}, auc {:.4f}, EER {:.4f}".format(acc_lfw, best_th_lfw, auc_lfw,
eer_lfw))
with summary_writer.as_default():
tf.summary.scalar('metric/epoch_acc', acc_lfw, step=steps)
tf.summary.scalar('metric/epoch_eer', eer_lfw, step=steps)
if tmp_best_acc < acc_lfw:
tmp_best_acc = acc_lfw
print('[*] save best ckpt file!')
if not os.path.exists('checkpoints/{}'.format(
cfg['sub_name'])):
os.mkdir('checkpoints/{}'.format(
cfg['sub_name']))
file = open('checkpoints/{}/bestAcc_e_{}_b_{}.log'.format(
cfg['sub_name'], epochs, steps % steps_per_epoch), 'w')
file.close()
model.save_weights('checkpoints/{}/bestAcc.ckpt'.format(
cfg['sub_name']))
# here we would like to plot the code distribution
x = np.asarray(embeddings_lfw)
x = x.astype(int)
reshaped_array = x.reshape(x.size)
counter = collections.Counter(reshaped_array)
x = counter.keys()
frequency = counter.values()
y = [x / reshaped_array.size for x in frequency]
plt.bar(x, y)
plt.ylabel('Probability')
plt.xlabel('Code value')
# plt.show()
plt.savefig(
'checkpoints/{}/histogram_{}_m{}_q{}_e{}_b_{}.svg'.format(cfg['sub_name'], cfg['sub_name'],
cfg['m'], cfg['q'], epochs,
steps % steps_per_epoch),
format='svg')
plt.close('all')
if steps % cfg['save_steps'] == 0:
print('[*] save ckpt file!')
model.save_weights('checkpoints/{}/e_{}_b_{}.ckpt'.format(
cfg['sub_name'], epochs, steps % steps_per_epoch))
if steps % steps_per_epoch == 0:
model.save_weights('checkpoints/{}/e_{}_b_{}.ckpt'.format(
cfg['sub_name'], epochs, steps % steps_per_epoch))
steps += 1
epochs = steps // steps_per_epoch + 1
else:
print("[*] only support eager_tf!")
model.compile(optimizer=optimizer, loss=None)
mc_callback = ModelCheckpoint(
'checkpoints/' + cfg['sub_name'] + '/e_{epoch}_b_{batch}.ckpt',
save_freq=cfg['save_steps'] * cfg['batch_size'], verbose=1,
save_weights_only=True)
tb_callback = TensorBoard(log_dir='logs/'+ cfg['sub_name'],
update_freq=cfg['batch_size'] * 5,
profile_batch=0)
tb_callback._total_batches_seen = steps
tb_callback._samples_seen = steps * cfg['batch_size']
callbacks = [mc_callback, tb_callback]
def batch_generator(train_dataset):
train_dataset = iter(train_dataset)
while True:
inputs, labels = next(train_dataset) #print(inputs[0][1][:]) labels[2][:]
yield [inputs, labels]
model.fit_generator(batch_generator(train_dataset),
epochs=cfg['epochs'],
steps_per_epoch=steps_per_epoch,
callbacks=callbacks,
initial_epoch=epochs - 1)
print("[*] training done!")
if __name__ == '__main__':
app.run(main)