-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtrain_standard.py
181 lines (149 loc) · 8.03 KB
/
train_standard.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
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
import argparse
import pickle
import time
from functools import partial
import tensorflow as tf
print("Tensorflow version", tf.__version__)
from include import configuration
from include import graph_manager
from include import nets
from include import loss_utils
from include import eval_utils
from include import viz
if __name__ == '__main__':
########################################################################## Configuration
parser = argparse.ArgumentParser(description='Standard Object Detection.')
configuration.build_base_parser(parser)
args = parser.parse_args()
print('Standard detection - %s, Input size %d\n' % (args.data, args.image_size))
base_config = configuration.build_base_config_from_args(args, verbose=args.verbose)
config = base_config.copy()
config['image_size'] = args.image_size
config['exp_name'] += '/%s_standard_%d' % (config['network'],config['image_size'])
configuration.finalize_grid_offsets(config)
graph_manager.generate_log_dir(config)
print(' Log directory', os.path.abspath(config["log_dir"]))
with open(os.path.join(config["log_dir"], 'config.pkl'), 'wb') as f:
pickle.dump(config, f)
tee = viz.Tee()
def log_run():
global tee, config
viz.save_tee(config["log_dir"], tee)
########################################################################## Build the graph
### templates
network = configuration.get_defaults(config, ['network'], verbose=True)[0]
forward_fn = tf.make_template(network, getattr(nets, network))
decode_fn = tf.make_template('decode', nets.get_detection_outputs)
forward_pass = partial(nets.forward, forward_fn=forward_fn, decode_fn=decode_fn)
with_summaries = config['save_summaries_steps'] is not None
if with_summaries:
with tf.name_scope('config_summary'):
viz.add_text_summaries(config)
### train
print('\nTrain Graph:')
with tf.name_scope('train'):
with tf.name_scope('inputs'):
inputs, _ = graph_manager.get_inputs(mode='train', verbose=args.verbose, **config)
for i in range(config['num_gpus']):
with tf.device('/gpu:%d' % i):
with tf.name_scope('dev%d' % i):
verbose = args.verbose * (i == 0)
if verbose > 0:
print((' > %s' if verbose == 1 else ' \033[31m> %s\033[0m') % network)
### Main graph
with tf.name_scope('feed_forward'):
outputs = forward_pass(
inputs[i]['image'], config, is_training=True, verbose=verbose)
#######################
if verbose > 0:
print((' > %s' if verbose == 1 else ' \033[31m> %s\033[0m') % 'Collecting losses')
with tf.name_scope('losses'):
graph_manager.add_losses_to_graph(
loss_utils.get_standard_loss, inputs[i], outputs, config, is_chief=i == 0, verbose=verbose)
with tf.name_scope('summaries'):
if i == 0 and with_summaries:
print(' > summaries:')
graph_manager.add_summaries(
inputs[i], outputs, mode='train', verbose=verbose, **config)
with tf.name_scope('losses'):
losses = graph_manager.get_total_loss(verbose=args.verbose, with_summaries=with_summaries)
assert len(losses) == 1
full_loss = losses[0][0]
print('\nTrain op:')
with tf.name_scope('train_op'):
global_step, train_op = graph_manager.get_train_op(losses, verbose=args.verbose, **config)
assert len(train_op) == 1
train_op = train_op[0]
### inference
with tf.name_scope('eval'):
eval_split_placehoder = tf.placeholder_with_default(True, (), 'choose_eval_split')
eval_inputs, eval_initializer = tf.cond(
eval_split_placehoder,
true_fn=lambda: graph_manager.get_inputs(mode='test', verbose=False, **config),
false_fn=lambda: graph_manager.get_inputs(mode='val', verbose=False, **config),
name='eval_inputs')
for i in range(config['num_gpus']):
with tf.device('/gpu:%d' % i):
with tf.name_scope('dev%d' % i):
eval_outputs = forward_pass(
eval_inputs[i]['image'], config, is_training=False, verbose=verbose)
tf.add_to_collection('inference_image_ids', eval_inputs[i]['im_id'])
tf.add_to_collection('inference_num_boxes', eval_inputs[i]['num_boxes'])
tf.add_to_collection('inference_gt_bbs', eval_inputs[i]['bounding_boxes'])
tf.add_to_collection('inference_pred_bbs', eval_outputs['bounding_boxes'])
tf.add_to_collection('inference_pred_confidences', eval_outputs['detection_scores'])
# gather predictions across gpus
with tf.name_scope('gather'):
eval_outputs = [tf.concat(tf.get_collection(key), axis=0) for key in [
'inference_image_ids', 'inference_num_boxes', 'inference_gt_bbs',
'inference_pred_bbs', 'inference_pred_confidences']]
# eval functions
validation_results_path = os.path.join(config["log_dir"], 'val_output.txt')
test_results_path = os.path.join(config["log_dir"], 'test_output.txt')
run_eval = partial(graph_manager.run_eval, eval_split_placehoder=eval_split_placehoder,
eval_initializer=eval_initializer, eval_outputs=eval_outputs, configuration=config)
eval_validation = partial(run_eval, mode='val', results_path=validation_results_path)
eval_test = partial(run_eval, mode='test', results_path=test_results_path)
########################################################################## Start Session
total_parameters = 0
for variable in tf.trainable_variables():
variable_parameters = 1
for dim in variable.get_shape():
variable_parameters *= dim.value
total_parameters += variable_parameters
print('number of parameters', total_parameters)
print('total graph size: %.2f MB' % (tf.get_default_graph().as_graph_def().ByteSize() / 10e6))
log_run()
try:
with graph_manager.get_monitored_training_session(**config) as sess:
# Initialize from pretrained weights for MobileNet architectures
configuration.start_from_pretrained(sess)
# Start training
print('\nStart training:')
start_time = time.time()
global_step_ = 0
try:
while 1:
# Train
global_step_, full_loss_, _ = sess.run([global_step, full_loss, train_op])
# Display
if (global_step_ - 1) % args.display_loss_every_n_steps == 0:
viz.display_loss(global_step_, full_loss_, start_time,
config["train_num_samples_per_iter"],
config["train_num_samples"])
# Evaluate on validation set
if (config["save_evaluation_steps"] is not None and (global_step_ > 1)
and global_step_ % config["save_evaluation_steps"] == 0):
eval_validation(sess, global_step_)
log_run()
except tf.errors.OutOfRangeError: # End of training
pass
# Evaluate on the validation and test set
eval_validation(sess, global_step_)
eval_test(sess, global_step_)
log_run()
except KeyboardInterrupt: # Keyboard interrupted
print('\nInterrupted at step %d' % global_step_)
log_run()