You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

416 lines
17 KiB

6 years ago
  1. # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. # ==============================================================================
  15. """Detection model trainer.
  16. This file provides a generic training method that can be used to train a
  17. DetectionModel.
  18. """
  19. import functools
  20. import tensorflow as tf
  21. from object_detection.builders import optimizer_builder
  22. from object_detection.builders import preprocessor_builder
  23. from object_detection.core import batcher
  24. from object_detection.core import preprocessor
  25. from object_detection.core import standard_fields as fields
  26. from object_detection.utils import ops as util_ops
  27. from object_detection.utils import variables_helper
  28. from deployment import model_deploy
  29. slim = tf.contrib.slim
  30. def create_input_queue(batch_size_per_clone, create_tensor_dict_fn,
  31. batch_queue_capacity, num_batch_queue_threads,
  32. prefetch_queue_capacity, data_augmentation_options):
  33. """Sets up reader, prefetcher and returns input queue.
  34. Args:
  35. batch_size_per_clone: batch size to use per clone.
  36. create_tensor_dict_fn: function to create tensor dictionary.
  37. batch_queue_capacity: maximum number of elements to store within a queue.
  38. num_batch_queue_threads: number of threads to use for batching.
  39. prefetch_queue_capacity: maximum capacity of the queue used to prefetch
  40. assembled batches.
  41. data_augmentation_options: a list of tuples, where each tuple contains a
  42. data augmentation function and a dictionary containing arguments and their
  43. values (see preprocessor.py).
  44. Returns:
  45. input queue: a batcher.BatchQueue object holding enqueued tensor_dicts
  46. (which hold images, boxes and targets). To get a batch of tensor_dicts,
  47. call input_queue.Dequeue().
  48. """
  49. tensor_dict = create_tensor_dict_fn()
  50. tensor_dict[fields.InputDataFields.image] = tf.expand_dims(
  51. tensor_dict[fields.InputDataFields.image], 0)
  52. images = tensor_dict[fields.InputDataFields.image]
  53. float_images = tf.to_float(images)
  54. tensor_dict[fields.InputDataFields.image] = float_images
  55. include_instance_masks = (fields.InputDataFields.groundtruth_instance_masks
  56. in tensor_dict)
  57. include_keypoints = (fields.InputDataFields.groundtruth_keypoints
  58. in tensor_dict)
  59. include_multiclass_scores = (fields.InputDataFields.multiclass_scores
  60. in tensor_dict)
  61. if data_augmentation_options:
  62. tensor_dict = preprocessor.preprocess(
  63. tensor_dict, data_augmentation_options,
  64. func_arg_map=preprocessor.get_default_func_arg_map(
  65. include_label_weights=True,
  66. include_multiclass_scores=include_multiclass_scores,
  67. include_instance_masks=include_instance_masks,
  68. include_keypoints=include_keypoints))
  69. input_queue = batcher.BatchQueue(
  70. tensor_dict,
  71. batch_size=batch_size_per_clone,
  72. batch_queue_capacity=batch_queue_capacity,
  73. num_batch_queue_threads=num_batch_queue_threads,
  74. prefetch_queue_capacity=prefetch_queue_capacity)
  75. return input_queue
  76. def get_inputs(input_queue,
  77. num_classes,
  78. merge_multiple_label_boxes=False,
  79. use_multiclass_scores=False):
  80. """Dequeues batch and constructs inputs to object detection model.
  81. Args:
  82. input_queue: BatchQueue object holding enqueued tensor_dicts.
  83. num_classes: Number of classes.
  84. merge_multiple_label_boxes: Whether to merge boxes with multiple labels
  85. or not. Defaults to false. Merged boxes are represented with a single
  86. box and a k-hot encoding of the multiple labels associated with the
  87. boxes.
  88. use_multiclass_scores: Whether to use multiclass scores instead of
  89. groundtruth_classes.
  90. Returns:
  91. images: a list of 3-D float tensor of images.
  92. image_keys: a list of string keys for the images.
  93. locations_list: a list of tensors of shape [num_boxes, 4]
  94. containing the corners of the groundtruth boxes.
  95. classes_list: a list of padded one-hot (or K-hot) float32 tensors containing
  96. target classes.
  97. masks_list: a list of 3-D float tensors of shape [num_boxes, image_height,
  98. image_width] containing instance masks for objects if present in the
  99. input_queue. Else returns None.
  100. keypoints_list: a list of 3-D float tensors of shape [num_boxes,
  101. num_keypoints, 2] containing keypoints for objects if present in the
  102. input queue. Else returns None.
  103. weights_lists: a list of 1-D float32 tensors of shape [num_boxes]
  104. containing groundtruth weight for each box.
  105. """
  106. read_data_list = input_queue.dequeue()
  107. label_id_offset = 1
  108. def extract_images_and_targets(read_data):
  109. """Extract images and targets from the input dict."""
  110. image = read_data[fields.InputDataFields.image]
  111. key = ''
  112. if fields.InputDataFields.source_id in read_data:
  113. key = read_data[fields.InputDataFields.source_id]
  114. location_gt = read_data[fields.InputDataFields.groundtruth_boxes]
  115. classes_gt = tf.cast(read_data[fields.InputDataFields.groundtruth_classes],
  116. tf.int32)
  117. classes_gt -= label_id_offset
  118. if merge_multiple_label_boxes and use_multiclass_scores:
  119. raise ValueError(
  120. 'Using both merge_multiple_label_boxes and use_multiclass_scores is'
  121. 'not supported'
  122. )
  123. if merge_multiple_label_boxes:
  124. location_gt, classes_gt, _ = util_ops.merge_boxes_with_multiple_labels(
  125. location_gt, classes_gt, num_classes)
  126. classes_gt = tf.cast(classes_gt, tf.float32)
  127. elif use_multiclass_scores:
  128. classes_gt = tf.cast(read_data[fields.InputDataFields.multiclass_scores],
  129. tf.float32)
  130. else:
  131. classes_gt = util_ops.padded_one_hot_encoding(
  132. indices=classes_gt, depth=num_classes, left_pad=0)
  133. masks_gt = read_data.get(fields.InputDataFields.groundtruth_instance_masks)
  134. keypoints_gt = read_data.get(fields.InputDataFields.groundtruth_keypoints)
  135. if (merge_multiple_label_boxes and (
  136. masks_gt is not None or keypoints_gt is not None)):
  137. raise NotImplementedError('Multi-label support is only for boxes.')
  138. weights_gt = read_data.get(
  139. fields.InputDataFields.groundtruth_weights)
  140. return (image, key, location_gt, classes_gt, masks_gt, keypoints_gt,
  141. weights_gt)
  142. return zip(*map(extract_images_and_targets, read_data_list))
  143. def _create_losses(input_queue, create_model_fn, train_config):
  144. """Creates loss function for a DetectionModel.
  145. Args:
  146. input_queue: BatchQueue object holding enqueued tensor_dicts.
  147. create_model_fn: A function to create the DetectionModel.
  148. train_config: a train_pb2.TrainConfig protobuf.
  149. """
  150. detection_model = create_model_fn()
  151. (images, _, groundtruth_boxes_list, groundtruth_classes_list,
  152. groundtruth_masks_list, groundtruth_keypoints_list,
  153. groundtruth_weights_list) = get_inputs(
  154. input_queue,
  155. detection_model.num_classes,
  156. train_config.merge_multiple_label_boxes,
  157. train_config.use_multiclass_scores)
  158. preprocessed_images = []
  159. true_image_shapes = []
  160. for image in images:
  161. resized_image, true_image_shape = detection_model.preprocess(image)
  162. preprocessed_images.append(resized_image)
  163. true_image_shapes.append(true_image_shape)
  164. images = tf.concat(preprocessed_images, 0)
  165. true_image_shapes = tf.concat(true_image_shapes, 0)
  166. if any(mask is None for mask in groundtruth_masks_list):
  167. groundtruth_masks_list = None
  168. if any(keypoints is None for keypoints in groundtruth_keypoints_list):
  169. groundtruth_keypoints_list = None
  170. detection_model.provide_groundtruth(
  171. groundtruth_boxes_list,
  172. groundtruth_classes_list,
  173. groundtruth_masks_list,
  174. groundtruth_keypoints_list,
  175. groundtruth_weights_list=groundtruth_weights_list)
  176. prediction_dict = detection_model.predict(images, true_image_shapes)
  177. losses_dict = detection_model.loss(prediction_dict, true_image_shapes)
  178. for loss_tensor in losses_dict.values():
  179. tf.losses.add_loss(loss_tensor)
  180. def train(create_tensor_dict_fn,
  181. create_model_fn,
  182. train_config,
  183. master,
  184. task,
  185. num_clones,
  186. worker_replicas,
  187. clone_on_cpu,
  188. ps_tasks,
  189. worker_job_name,
  190. is_chief,
  191. train_dir,
  192. graph_hook_fn=None):
  193. """Training function for detection models.
  194. Args:
  195. create_tensor_dict_fn: a function to create a tensor input dictionary.
  196. create_model_fn: a function that creates a DetectionModel and generates
  197. losses.
  198. train_config: a train_pb2.TrainConfig protobuf.
  199. master: BNS name of the TensorFlow master to use.
  200. task: The task id of this training instance.
  201. num_clones: The number of clones to run per machine.
  202. worker_replicas: The number of work replicas to train with.
  203. clone_on_cpu: True if clones should be forced to run on CPU.
  204. ps_tasks: Number of parameter server tasks.
  205. worker_job_name: Name of the worker job.
  206. is_chief: Whether this replica is the chief replica.
  207. train_dir: Directory to write checkpoints and training summaries to.
  208. graph_hook_fn: Optional function that is called after the inference graph is
  209. built (before optimization). This is helpful to perform additional changes
  210. to the training graph such as adding FakeQuant ops. The function should
  211. modify the default graph.
  212. Raises:
  213. ValueError: If both num_clones > 1 and train_config.sync_replicas is true.
  214. """
  215. detection_model = create_model_fn()
  216. data_augmentation_options = [
  217. preprocessor_builder.build(step)
  218. for step in train_config.data_augmentation_options]
  219. with tf.Graph().as_default():
  220. # Build a configuration specifying multi-GPU and multi-replicas.
  221. deploy_config = model_deploy.DeploymentConfig(
  222. num_clones=num_clones,
  223. clone_on_cpu=clone_on_cpu,
  224. replica_id=task,
  225. num_replicas=worker_replicas,
  226. num_ps_tasks=ps_tasks,
  227. worker_job_name=worker_job_name)
  228. # Place the global step on the device storing the variables.
  229. with tf.device(deploy_config.variables_device()):
  230. global_step = slim.create_global_step()
  231. if num_clones != 1 and train_config.sync_replicas:
  232. raise ValueError('In Synchronous SGD mode num_clones must ',
  233. 'be 1. Found num_clones: {}'.format(num_clones))
  234. batch_size = train_config.batch_size // num_clones
  235. if train_config.sync_replicas:
  236. batch_size //= train_config.replicas_to_aggregate
  237. with tf.device(deploy_config.inputs_device()):
  238. input_queue = create_input_queue(
  239. batch_size, create_tensor_dict_fn,
  240. train_config.batch_queue_capacity,
  241. train_config.num_batch_queue_threads,
  242. train_config.prefetch_queue_capacity, data_augmentation_options)
  243. # Gather initial summaries.
  244. # TODO(rathodv): See if summaries can be added/extracted from global tf
  245. # collections so that they don't have to be passed around.
  246. summaries = set(tf.get_collection(tf.GraphKeys.SUMMARIES))
  247. global_summaries = set([])
  248. model_fn = functools.partial(_create_losses,
  249. create_model_fn=create_model_fn,
  250. train_config=train_config)
  251. clones = model_deploy.create_clones(deploy_config, model_fn, [input_queue])
  252. first_clone_scope = clones[0].scope
  253. if graph_hook_fn:
  254. with tf.device(deploy_config.variables_device()):
  255. graph_hook_fn()
  256. # Gather update_ops from the first clone. These contain, for example,
  257. # the updates for the batch_norm variables created by model_fn.
  258. update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, first_clone_scope)
  259. with tf.device(deploy_config.optimizer_device()):
  260. training_optimizer, optimizer_summary_vars = optimizer_builder.build(
  261. train_config.optimizer)
  262. for var in optimizer_summary_vars:
  263. tf.summary.scalar(var.op.name, var, family='LearningRate')
  264. sync_optimizer = None
  265. if train_config.sync_replicas:
  266. training_optimizer = tf.train.SyncReplicasOptimizer(
  267. training_optimizer,
  268. replicas_to_aggregate=train_config.replicas_to_aggregate,
  269. total_num_replicas=worker_replicas)
  270. sync_optimizer = training_optimizer
  271. with tf.device(deploy_config.optimizer_device()):
  272. regularization_losses = (None if train_config.add_regularization_loss
  273. else [])
  274. total_loss, grads_and_vars = model_deploy.optimize_clones(
  275. clones, training_optimizer,
  276. regularization_losses=regularization_losses)
  277. total_loss = tf.check_numerics(total_loss, 'LossTensor is inf or nan.')
  278. # Optionally multiply bias gradients by train_config.bias_grad_multiplier.
  279. if train_config.bias_grad_multiplier:
  280. biases_regex_list = ['.*/biases']
  281. grads_and_vars = variables_helper.multiply_gradients_matching_regex(
  282. grads_and_vars,
  283. biases_regex_list,
  284. multiplier=train_config.bias_grad_multiplier)
  285. # Optionally freeze some layers by setting their gradients to be zero.
  286. if train_config.freeze_variables:
  287. grads_and_vars = variables_helper.freeze_gradients_matching_regex(
  288. grads_and_vars, train_config.freeze_variables)
  289. # Optionally clip gradients
  290. if train_config.gradient_clipping_by_norm > 0:
  291. with tf.name_scope('clip_grads'):
  292. grads_and_vars = slim.learning.clip_gradient_norms(
  293. grads_and_vars, train_config.gradient_clipping_by_norm)
  294. # Create gradient updates.
  295. grad_updates = training_optimizer.apply_gradients(grads_and_vars,
  296. global_step=global_step)
  297. update_ops.append(grad_updates)
  298. update_op = tf.group(*update_ops, name='update_barrier')
  299. with tf.control_dependencies([update_op]):
  300. train_tensor = tf.identity(total_loss, name='train_op')
  301. # Add summaries.
  302. for model_var in slim.get_model_variables():
  303. global_summaries.add(tf.summary.histogram('ModelVars/' +
  304. model_var.op.name, model_var))
  305. for loss_tensor in tf.losses.get_losses():
  306. global_summaries.add(tf.summary.scalar('Losses/' + loss_tensor.op.name,
  307. loss_tensor))
  308. global_summaries.add(
  309. tf.summary.scalar('Losses/TotalLoss', tf.losses.get_total_loss()))
  310. # Add the summaries from the first clone. These contain the summaries
  311. # created by model_fn and either optimize_clones() or _gather_clone_loss().
  312. summaries |= set(tf.get_collection(tf.GraphKeys.SUMMARIES,
  313. first_clone_scope))
  314. summaries |= global_summaries
  315. # Merge all summaries together.
  316. summary_op = tf.summary.merge(list(summaries), name='summary_op')
  317. # Soft placement allows placing on CPU ops without GPU implementation.
  318. session_config = tf.ConfigProto(allow_soft_placement=True,
  319. log_device_placement=False)
  320. # Save checkpoints regularly.
  321. keep_checkpoint_every_n_hours = train_config.keep_checkpoint_every_n_hours
  322. saver = tf.train.Saver(
  323. keep_checkpoint_every_n_hours=keep_checkpoint_every_n_hours)
  324. # Create ops required to initialize the model from a given checkpoint.
  325. init_fn = None
  326. if train_config.fine_tune_checkpoint:
  327. if not train_config.fine_tune_checkpoint_type:
  328. # train_config.from_detection_checkpoint field is deprecated. For
  329. # backward compatibility, fine_tune_checkpoint_type is set based on
  330. # from_detection_checkpoint.
  331. if train_config.from_detection_checkpoint:
  332. train_config.fine_tune_checkpoint_type = 'detection'
  333. else:
  334. train_config.fine_tune_checkpoint_type = 'classification'
  335. var_map = detection_model.restore_map(
  336. fine_tune_checkpoint_type=train_config.fine_tune_checkpoint_type,
  337. load_all_detection_checkpoint_vars=(
  338. train_config.load_all_detection_checkpoint_vars))
  339. available_var_map = (variables_helper.
  340. get_variables_available_in_checkpoint(
  341. var_map, train_config.fine_tune_checkpoint,
  342. include_global_step=False))
  343. init_saver = tf.train.Saver(available_var_map)
  344. def initializer_fn(sess):
  345. init_saver.restore(sess, train_config.fine_tune_checkpoint)
  346. init_fn = initializer_fn
  347. slim.learning.train(
  348. train_tensor,
  349. logdir=train_dir,
  350. master=master,
  351. is_chief=is_chief,
  352. session_config=session_config,
  353. startup_delay_steps=train_config.startup_delay_steps,
  354. init_fn=init_fn,
  355. summary_op=summary_op,
  356. number_of_steps=(
  357. train_config.num_steps if train_config.num_steps else None),
  358. save_summaries_secs=120,
  359. sync_optimizer=sync_optimizer,
  360. saver=saver)