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.

933 lines
36 KiB

  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. """Functions for reading and updating configuration files."""
  16. import os
  17. import tensorflow as tf
  18. from google.protobuf import text_format
  19. from tensorflow.python.lib.io import file_io
  20. from object_detection.protos import eval_pb2
  21. from object_detection.protos import graph_rewriter_pb2
  22. from object_detection.protos import input_reader_pb2
  23. from object_detection.protos import model_pb2
  24. from object_detection.protos import pipeline_pb2
  25. from object_detection.protos import train_pb2
  26. def get_image_resizer_config(model_config):
  27. """Returns the image resizer config from a model config.
  28. Args:
  29. model_config: A model_pb2.DetectionModel.
  30. Returns:
  31. An image_resizer_pb2.ImageResizer.
  32. Raises:
  33. ValueError: If the model type is not recognized.
  34. """
  35. meta_architecture = model_config.WhichOneof("model")
  36. if meta_architecture == "faster_rcnn":
  37. return model_config.faster_rcnn.image_resizer
  38. if meta_architecture == "ssd":
  39. return model_config.ssd.image_resizer
  40. raise ValueError("Unknown model type: {}".format(meta_architecture))
  41. def get_spatial_image_size(image_resizer_config):
  42. """Returns expected spatial size of the output image from a given config.
  43. Args:
  44. image_resizer_config: An image_resizer_pb2.ImageResizer.
  45. Returns:
  46. A list of two integers of the form [height, width]. `height` and `width` are
  47. set -1 if they cannot be determined during graph construction.
  48. Raises:
  49. ValueError: If the model type is not recognized.
  50. """
  51. if image_resizer_config.HasField("fixed_shape_resizer"):
  52. return [
  53. image_resizer_config.fixed_shape_resizer.height,
  54. image_resizer_config.fixed_shape_resizer.width
  55. ]
  56. if image_resizer_config.HasField("keep_aspect_ratio_resizer"):
  57. if image_resizer_config.keep_aspect_ratio_resizer.pad_to_max_dimension:
  58. return [image_resizer_config.keep_aspect_ratio_resizer.max_dimension] * 2
  59. else:
  60. return [-1, -1]
  61. if image_resizer_config.HasField(
  62. "identity_resizer") or image_resizer_config.HasField(
  63. "conditional_shape_resizer"):
  64. return [-1, -1]
  65. raise ValueError("Unknown image resizer type.")
  66. def get_configs_from_pipeline_file(pipeline_config_path, config_override=None):
  67. """Reads config from a file containing pipeline_pb2.TrainEvalPipelineConfig.
  68. Args:
  69. pipeline_config_path: Path to pipeline_pb2.TrainEvalPipelineConfig text
  70. proto.
  71. config_override: A pipeline_pb2.TrainEvalPipelineConfig text proto to
  72. override pipeline_config_path.
  73. Returns:
  74. Dictionary of configuration objects. Keys are `model`, `train_config`,
  75. `train_input_config`, `eval_config`, `eval_input_config`. Value are the
  76. corresponding config objects.
  77. """
  78. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  79. with tf.gfile.GFile(pipeline_config_path, "r") as f:
  80. proto_str = f.read()
  81. text_format.Merge(proto_str, pipeline_config)
  82. if config_override:
  83. text_format.Merge(config_override, pipeline_config)
  84. return create_configs_from_pipeline_proto(pipeline_config)
  85. def create_configs_from_pipeline_proto(pipeline_config):
  86. """Creates a configs dictionary from pipeline_pb2.TrainEvalPipelineConfig.
  87. Args:
  88. pipeline_config: pipeline_pb2.TrainEvalPipelineConfig proto object.
  89. Returns:
  90. Dictionary of configuration objects. Keys are `model`, `train_config`,
  91. `train_input_config`, `eval_config`, `eval_input_configs`. Value are
  92. the corresponding config objects or list of config objects (only for
  93. eval_input_configs).
  94. """
  95. configs = {}
  96. configs["model"] = pipeline_config.model
  97. configs["train_config"] = pipeline_config.train_config
  98. configs["train_input_config"] = pipeline_config.train_input_reader
  99. configs["eval_config"] = pipeline_config.eval_config
  100. configs["eval_input_configs"] = pipeline_config.eval_input_reader
  101. # Keeps eval_input_config only for backwards compatibility. All clients should
  102. # read eval_input_configs instead.
  103. if configs["eval_input_configs"]:
  104. configs["eval_input_config"] = configs["eval_input_configs"][0]
  105. if pipeline_config.HasField("graph_rewriter"):
  106. configs["graph_rewriter_config"] = pipeline_config.graph_rewriter
  107. return configs
  108. def get_graph_rewriter_config_from_file(graph_rewriter_config_file):
  109. """Parses config for graph rewriter.
  110. Args:
  111. graph_rewriter_config_file: file path to the graph rewriter config.
  112. Returns:
  113. graph_rewriter_pb2.GraphRewriter proto
  114. """
  115. graph_rewriter_config = graph_rewriter_pb2.GraphRewriter()
  116. with tf.gfile.GFile(graph_rewriter_config_file, "r") as f:
  117. text_format.Merge(f.read(), graph_rewriter_config)
  118. return graph_rewriter_config
  119. def create_pipeline_proto_from_configs(configs):
  120. """Creates a pipeline_pb2.TrainEvalPipelineConfig from configs dictionary.
  121. This function performs the inverse operation of
  122. create_configs_from_pipeline_proto().
  123. Args:
  124. configs: Dictionary of configs. See get_configs_from_pipeline_file().
  125. Returns:
  126. A fully populated pipeline_pb2.TrainEvalPipelineConfig.
  127. """
  128. pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
  129. pipeline_config.model.CopyFrom(configs["model"])
  130. pipeline_config.train_config.CopyFrom(configs["train_config"])
  131. pipeline_config.train_input_reader.CopyFrom(configs["train_input_config"])
  132. pipeline_config.eval_config.CopyFrom(configs["eval_config"])
  133. pipeline_config.eval_input_reader.extend(configs["eval_input_configs"])
  134. if "graph_rewriter_config" in configs:
  135. pipeline_config.graph_rewriter.CopyFrom(configs["graph_rewriter_config"])
  136. return pipeline_config
  137. def save_pipeline_config(pipeline_config, directory):
  138. """Saves a pipeline config text file to disk.
  139. Args:
  140. pipeline_config: A pipeline_pb2.TrainEvalPipelineConfig.
  141. directory: The model directory into which the pipeline config file will be
  142. saved.
  143. """
  144. if not file_io.file_exists(directory):
  145. file_io.recursive_create_dir(directory)
  146. pipeline_config_path = os.path.join(directory, "pipeline.config")
  147. config_text = text_format.MessageToString(pipeline_config)
  148. with tf.gfile.Open(pipeline_config_path, "wb") as f:
  149. tf.logging.info("Writing pipeline config file to %s",
  150. pipeline_config_path)
  151. f.write(config_text)
  152. def get_configs_from_multiple_files(model_config_path="",
  153. train_config_path="",
  154. train_input_config_path="",
  155. eval_config_path="",
  156. eval_input_config_path="",
  157. graph_rewriter_config_path=""):
  158. """Reads training configuration from multiple config files.
  159. Args:
  160. model_config_path: Path to model_pb2.DetectionModel.
  161. train_config_path: Path to train_pb2.TrainConfig.
  162. train_input_config_path: Path to input_reader_pb2.InputReader.
  163. eval_config_path: Path to eval_pb2.EvalConfig.
  164. eval_input_config_path: Path to input_reader_pb2.InputReader.
  165. graph_rewriter_config_path: Path to graph_rewriter_pb2.GraphRewriter.
  166. Returns:
  167. Dictionary of configuration objects. Keys are `model`, `train_config`,
  168. `train_input_config`, `eval_config`, `eval_input_config`. Key/Values are
  169. returned only for valid (non-empty) strings.
  170. """
  171. configs = {}
  172. if model_config_path:
  173. model_config = model_pb2.DetectionModel()
  174. with tf.gfile.GFile(model_config_path, "r") as f:
  175. text_format.Merge(f.read(), model_config)
  176. configs["model"] = model_config
  177. if train_config_path:
  178. train_config = train_pb2.TrainConfig()
  179. with tf.gfile.GFile(train_config_path, "r") as f:
  180. text_format.Merge(f.read(), train_config)
  181. configs["train_config"] = train_config
  182. if train_input_config_path:
  183. train_input_config = input_reader_pb2.InputReader()
  184. with tf.gfile.GFile(train_input_config_path, "r") as f:
  185. text_format.Merge(f.read(), train_input_config)
  186. configs["train_input_config"] = train_input_config
  187. if eval_config_path:
  188. eval_config = eval_pb2.EvalConfig()
  189. with tf.gfile.GFile(eval_config_path, "r") as f:
  190. text_format.Merge(f.read(), eval_config)
  191. configs["eval_config"] = eval_config
  192. if eval_input_config_path:
  193. eval_input_config = input_reader_pb2.InputReader()
  194. with tf.gfile.GFile(eval_input_config_path, "r") as f:
  195. text_format.Merge(f.read(), eval_input_config)
  196. configs["eval_input_configs"] = [eval_input_config]
  197. if graph_rewriter_config_path:
  198. configs["graph_rewriter_config"] = get_graph_rewriter_config_from_file(
  199. graph_rewriter_config_path)
  200. return configs
  201. def get_number_of_classes(model_config):
  202. """Returns the number of classes for a detection model.
  203. Args:
  204. model_config: A model_pb2.DetectionModel.
  205. Returns:
  206. Number of classes.
  207. Raises:
  208. ValueError: If the model type is not recognized.
  209. """
  210. meta_architecture = model_config.WhichOneof("model")
  211. if meta_architecture == "faster_rcnn":
  212. return model_config.faster_rcnn.num_classes
  213. if meta_architecture == "ssd":
  214. return model_config.ssd.num_classes
  215. raise ValueError("Expected the model to be one of 'faster_rcnn' or 'ssd'.")
  216. def get_optimizer_type(train_config):
  217. """Returns the optimizer type for training.
  218. Args:
  219. train_config: A train_pb2.TrainConfig.
  220. Returns:
  221. The type of the optimizer
  222. """
  223. return train_config.optimizer.WhichOneof("optimizer")
  224. def get_learning_rate_type(optimizer_config):
  225. """Returns the learning rate type for training.
  226. Args:
  227. optimizer_config: An optimizer_pb2.Optimizer.
  228. Returns:
  229. The type of the learning rate.
  230. """
  231. return optimizer_config.learning_rate.WhichOneof("learning_rate")
  232. def _is_generic_key(key):
  233. """Determines whether the key starts with a generic config dictionary key."""
  234. for prefix in [
  235. "graph_rewriter_config",
  236. "model",
  237. "train_input_config",
  238. "train_config",
  239. "eval_config"]:
  240. if key.startswith(prefix + "."):
  241. return True
  242. return False
  243. def _check_and_convert_legacy_input_config_key(key):
  244. """Checks key and converts legacy input config update to specific update.
  245. Args:
  246. key: string indicates the target of update operation.
  247. Returns:
  248. is_valid_input_config_key: A boolean indicating whether the input key is to
  249. update input config(s).
  250. key_name: 'eval_input_configs' or 'train_input_config' string if
  251. is_valid_input_config_key is true. None if is_valid_input_config_key is
  252. false.
  253. input_name: always returns None since legacy input config key never
  254. specifies the target input config. Keeping this output only to match the
  255. output form defined for input config update.
  256. field_name: the field name in input config. `key` itself if
  257. is_valid_input_config_key is false.
  258. """
  259. key_name = None
  260. input_name = None
  261. field_name = key
  262. is_valid_input_config_key = True
  263. if field_name == "train_shuffle":
  264. key_name = "train_input_config"
  265. field_name = "shuffle"
  266. elif field_name == "eval_shuffle":
  267. key_name = "eval_input_configs"
  268. field_name = "shuffle"
  269. elif field_name == "train_input_path":
  270. key_name = "train_input_config"
  271. field_name = "input_path"
  272. elif field_name == "eval_input_path":
  273. key_name = "eval_input_configs"
  274. field_name = "input_path"
  275. elif field_name == "append_train_input_path":
  276. key_name = "train_input_config"
  277. field_name = "input_path"
  278. elif field_name == "append_eval_input_path":
  279. key_name = "eval_input_configs"
  280. field_name = "input_path"
  281. else:
  282. is_valid_input_config_key = False
  283. return is_valid_input_config_key, key_name, input_name, field_name
  284. def check_and_parse_input_config_key(configs, key):
  285. """Checks key and returns specific fields if key is valid input config update.
  286. Args:
  287. configs: Dictionary of configuration objects. See outputs from
  288. get_configs_from_pipeline_file() or get_configs_from_multiple_files().
  289. key: string indicates the target of update operation.
  290. Returns:
  291. is_valid_input_config_key: A boolean indicate whether the input key is to
  292. update input config(s).
  293. key_name: 'eval_input_configs' or 'train_input_config' string if
  294. is_valid_input_config_key is true. None if is_valid_input_config_key is
  295. false.
  296. input_name: the name of the input config to be updated. None if
  297. is_valid_input_config_key is false.
  298. field_name: the field name in input config. `key` itself if
  299. is_valid_input_config_key is false.
  300. Raises:
  301. ValueError: when the input key format doesn't match any known formats.
  302. ValueError: if key_name doesn't match 'eval_input_configs' or
  303. 'train_input_config'.
  304. ValueError: if input_name doesn't match any name in train or eval input
  305. configs.
  306. ValueError: if field_name doesn't match any supported fields.
  307. """
  308. key_name = None
  309. input_name = None
  310. field_name = None
  311. fields = key.split(":")
  312. if len(fields) == 1:
  313. field_name = key
  314. return _check_and_convert_legacy_input_config_key(key)
  315. elif len(fields) == 3:
  316. key_name = fields[0]
  317. input_name = fields[1]
  318. field_name = fields[2]
  319. else:
  320. raise ValueError("Invalid key format when overriding configs.")
  321. # Checks if key_name is valid for specific update.
  322. if key_name not in ["eval_input_configs", "train_input_config"]:
  323. raise ValueError("Invalid key_name when overriding input config.")
  324. # Checks if input_name is valid for specific update. For train input config it
  325. # should match configs[key_name].name, for eval input configs it should match
  326. # the name field of one of the eval_input_configs.
  327. if isinstance(configs[key_name], input_reader_pb2.InputReader):
  328. is_valid_input_name = configs[key_name].name == input_name
  329. else:
  330. is_valid_input_name = input_name in [
  331. eval_input_config.name for eval_input_config in configs[key_name]
  332. ]
  333. if not is_valid_input_name:
  334. raise ValueError("Invalid input_name when overriding input config.")
  335. # Checks if field_name is valid for specific update.
  336. if field_name not in [
  337. "input_path", "label_map_path", "shuffle", "mask_type",
  338. "sample_1_of_n_examples"
  339. ]:
  340. raise ValueError("Invalid field_name when overriding input config.")
  341. return True, key_name, input_name, field_name
  342. def merge_external_params_with_configs(configs, hparams=None, kwargs_dict=None):
  343. """Updates `configs` dictionary based on supplied parameters.
  344. This utility is for modifying specific fields in the object detection configs.
  345. Say that one would like to experiment with different learning rates, momentum
  346. values, or batch sizes. Rather than creating a new config text file for each
  347. experiment, one can use a single base config file, and update particular
  348. values.
  349. There are two types of field overrides:
  350. 1. Strategy-based overrides, which update multiple relevant configuration
  351. options. For example, updating `learning_rate` will update both the warmup and
  352. final learning rates.
  353. In this case key can be one of the following formats:
  354. 1. legacy update: single string that indicates the attribute to be
  355. updated. E.g. 'label_map_path', 'eval_input_path', 'shuffle'.
  356. Note that when updating fields (e.g. eval_input_path, eval_shuffle) in
  357. eval_input_configs, the override will only be applied when
  358. eval_input_configs has exactly 1 element.
  359. 2. specific update: colon separated string that indicates which field in
  360. which input_config to update. It should have 3 fields:
  361. - key_name: Name of the input config we should update, either
  362. 'train_input_config' or 'eval_input_configs'
  363. - input_name: a 'name' that can be used to identify elements, especially
  364. when configs[key_name] is a repeated field.
  365. - field_name: name of the field that you want to override.
  366. For example, given configs dict as below:
  367. configs = {
  368. 'model': {...}
  369. 'train_config': {...}
  370. 'train_input_config': {...}
  371. 'eval_config': {...}
  372. 'eval_input_configs': [{ name:"eval_coco", ...},
  373. { name:"eval_voc", ... }]
  374. }
  375. Assume we want to update the input_path of the eval_input_config
  376. whose name is 'eval_coco'. The `key` would then be:
  377. 'eval_input_configs:eval_coco:input_path'
  378. 2. Generic key/value, which update a specific parameter based on namespaced
  379. configuration keys. For example,
  380. `model.ssd.loss.hard_example_miner.max_negatives_per_positive` will update the
  381. hard example miner configuration for an SSD model config. Generic overrides
  382. are automatically detected based on the namespaced keys.
  383. Args:
  384. configs: Dictionary of configuration objects. See outputs from
  385. get_configs_from_pipeline_file() or get_configs_from_multiple_files().
  386. hparams: A `HParams`.
  387. kwargs_dict: Extra keyword arguments that are treated the same way as
  388. attribute/value pairs in `hparams`. Note that hyperparameters with the
  389. same names will override keyword arguments.
  390. Returns:
  391. `configs` dictionary.
  392. Raises:
  393. ValueError: when the key string doesn't match any of its allowed formats.
  394. """
  395. if kwargs_dict is None:
  396. kwargs_dict = {}
  397. if hparams:
  398. kwargs_dict.update(hparams.values())
  399. for key, value in kwargs_dict.items():
  400. tf.logging.info("Maybe overwriting %s: %s", key, value)
  401. # pylint: disable=g-explicit-bool-comparison
  402. if value == "" or value is None:
  403. continue
  404. # pylint: enable=g-explicit-bool-comparison
  405. elif _maybe_update_config_with_key_value(configs, key, value):
  406. continue
  407. elif _is_generic_key(key):
  408. _update_generic(configs, key, value)
  409. else:
  410. tf.logging.info("Ignoring config override key: %s", key)
  411. return configs
  412. def _maybe_update_config_with_key_value(configs, key, value):
  413. """Checks key type and updates `configs` with the key value pair accordingly.
  414. Args:
  415. configs: Dictionary of configuration objects. See outputs from
  416. get_configs_from_pipeline_file() or get_configs_from_multiple_files().
  417. key: String indicates the field(s) to be updated.
  418. value: Value used to override existing field value.
  419. Returns:
  420. A boolean value that indicates whether the override succeeds.
  421. Raises:
  422. ValueError: when the key string doesn't match any of the formats above.
  423. """
  424. is_valid_input_config_key, key_name, input_name, field_name = (
  425. check_and_parse_input_config_key(configs, key))
  426. if is_valid_input_config_key:
  427. update_input_reader_config(
  428. configs,
  429. key_name=key_name,
  430. input_name=input_name,
  431. field_name=field_name,
  432. value=value)
  433. elif field_name == "learning_rate":
  434. _update_initial_learning_rate(configs, value)
  435. elif field_name == "batch_size":
  436. _update_batch_size(configs, value)
  437. elif field_name == "momentum_optimizer_value":
  438. _update_momentum_optimizer_value(configs, value)
  439. elif field_name == "classification_localization_weight_ratio":
  440. # Localization weight is fixed to 1.0.
  441. _update_classification_localization_weight_ratio(configs, value)
  442. elif field_name == "focal_loss_gamma":
  443. _update_focal_loss_gamma(configs, value)
  444. elif field_name == "focal_loss_alpha":
  445. _update_focal_loss_alpha(configs, value)
  446. elif field_name == "train_steps":
  447. _update_train_steps(configs, value)
  448. elif field_name == "label_map_path":
  449. _update_label_map_path(configs, value)
  450. elif field_name == "mask_type":
  451. _update_mask_type(configs, value)
  452. elif field_name == "sample_1_of_n_eval_examples":
  453. _update_all_eval_input_configs(configs, "sample_1_of_n_examples", value)
  454. elif field_name == "eval_num_epochs":
  455. _update_all_eval_input_configs(configs, "num_epochs", value)
  456. elif field_name == "eval_with_moving_averages":
  457. _update_use_moving_averages(configs, value)
  458. elif field_name == "retain_original_images_in_eval":
  459. _update_retain_original_images(configs["eval_config"], value)
  460. elif field_name == "use_bfloat16":
  461. _update_use_bfloat16(configs, value)
  462. else:
  463. return False
  464. return True
  465. def _update_tf_record_input_path(input_config, input_path):
  466. """Updates input configuration to reflect a new input path.
  467. The input_config object is updated in place, and hence not returned.
  468. Args:
  469. input_config: A input_reader_pb2.InputReader.
  470. input_path: A path to data or list of paths.
  471. Raises:
  472. TypeError: if input reader type is not `tf_record_input_reader`.
  473. """
  474. input_reader_type = input_config.WhichOneof("input_reader")
  475. if input_reader_type == "tf_record_input_reader":
  476. input_config.tf_record_input_reader.ClearField("input_path")
  477. if isinstance(input_path, list):
  478. input_config.tf_record_input_reader.input_path.extend(input_path)
  479. else:
  480. input_config.tf_record_input_reader.input_path.append(input_path)
  481. else:
  482. raise TypeError("Input reader type must be `tf_record_input_reader`.")
  483. def update_input_reader_config(configs,
  484. key_name=None,
  485. input_name=None,
  486. field_name=None,
  487. value=None,
  488. path_updater=_update_tf_record_input_path):
  489. """Updates specified input reader config field.
  490. Args:
  491. configs: Dictionary of configuration objects. See outputs from
  492. get_configs_from_pipeline_file() or get_configs_from_multiple_files().
  493. key_name: Name of the input config we should update, either
  494. 'train_input_config' or 'eval_input_configs'
  495. input_name: String name used to identify input config to update with. Should
  496. be either None or value of the 'name' field in one of the input reader
  497. configs.
  498. field_name: Field name in input_reader_pb2.InputReader.
  499. value: Value used to override existing field value.
  500. path_updater: helper function used to update the input path. Only used when
  501. field_name is "input_path".
  502. Raises:
  503. ValueError: when input field_name is None.
  504. ValueError: when input_name is None and number of eval_input_readers does
  505. not equal to 1.
  506. """
  507. if isinstance(configs[key_name], input_reader_pb2.InputReader):
  508. # Updates singular input_config object.
  509. target_input_config = configs[key_name]
  510. if field_name == "input_path":
  511. path_updater(input_config=target_input_config, input_path=value)
  512. else:
  513. setattr(target_input_config, field_name, value)
  514. elif input_name is None and len(configs[key_name]) == 1:
  515. # Updates first (and the only) object of input_config list.
  516. target_input_config = configs[key_name][0]
  517. if field_name == "input_path":
  518. path_updater(input_config=target_input_config, input_path=value)
  519. else:
  520. setattr(target_input_config, field_name, value)
  521. elif input_name is not None and len(configs[key_name]):
  522. # Updates input_config whose name matches input_name.
  523. update_count = 0
  524. for input_config in configs[key_name]:
  525. if input_config.name == input_name:
  526. setattr(input_config, field_name, value)
  527. update_count = update_count + 1
  528. if not update_count:
  529. raise ValueError(
  530. "Input name {} not found when overriding.".format(input_name))
  531. elif update_count > 1:
  532. raise ValueError("Duplicate input name found when overriding.")
  533. else:
  534. key_name = "None" if key_name is None else key_name
  535. input_name = "None" if input_name is None else input_name
  536. field_name = "None" if field_name is None else field_name
  537. raise ValueError("Unknown input config overriding: "
  538. "key_name:{}, input_name:{}, field_name:{}.".format(
  539. key_name, input_name, field_name))
  540. def _update_initial_learning_rate(configs, learning_rate):
  541. """Updates `configs` to reflect the new initial learning rate.
  542. This function updates the initial learning rate. For learning rate schedules,
  543. all other defined learning rates in the pipeline config are scaled to maintain
  544. their same ratio with the initial learning rate.
  545. The configs dictionary is updated in place, and hence not returned.
  546. Args:
  547. configs: Dictionary of configuration objects. See outputs from
  548. get_configs_from_pipeline_file() or get_configs_from_multiple_files().
  549. learning_rate: Initial learning rate for optimizer.
  550. Raises:
  551. TypeError: if optimizer type is not supported, or if learning rate type is
  552. not supported.
  553. """
  554. optimizer_type = get_optimizer_type(configs["train_config"])
  555. if optimizer_type == "rms_prop_optimizer":
  556. optimizer_config = configs["train_config"].optimizer.rms_prop_optimizer
  557. elif optimizer_type == "momentum_optimizer":
  558. optimizer_config = configs["train_config"].optimizer.momentum_optimizer
  559. elif optimizer_type == "adam_optimizer":
  560. optimizer_config = configs["train_config"].optimizer.adam_optimizer
  561. else:
  562. raise TypeError("Optimizer %s is not supported." % optimizer_type)
  563. learning_rate_type = get_learning_rate_type(optimizer_config)
  564. if learning_rate_type == "constant_learning_rate":
  565. constant_lr = optimizer_config.learning_rate.constant_learning_rate
  566. constant_lr.learning_rate = learning_rate
  567. elif learning_rate_type == "exponential_decay_learning_rate":
  568. exponential_lr = (
  569. optimizer_config.learning_rate.exponential_decay_learning_rate)
  570. exponential_lr.initial_learning_rate = learning_rate
  571. elif learning_rate_type == "manual_step_learning_rate":
  572. manual_lr = optimizer_config.learning_rate.manual_step_learning_rate
  573. original_learning_rate = manual_lr.initial_learning_rate
  574. learning_rate_scaling = float(learning_rate) / original_learning_rate
  575. manual_lr.initial_learning_rate = learning_rate
  576. for schedule in manual_lr.schedule:
  577. schedule.learning_rate *= learning_rate_scaling
  578. elif learning_rate_type == "cosine_decay_learning_rate":
  579. cosine_lr = optimizer_config.learning_rate.cosine_decay_learning_rate
  580. learning_rate_base = cosine_lr.learning_rate_base
  581. warmup_learning_rate = cosine_lr.warmup_learning_rate
  582. warmup_scale_factor = warmup_learning_rate / learning_rate_base
  583. cosine_lr.learning_rate_base = learning_rate
  584. cosine_lr.warmup_learning_rate = warmup_scale_factor * learning_rate
  585. else:
  586. raise TypeError("Learning rate %s is not supported." % learning_rate_type)
  587. def _update_batch_size(configs, batch_size):
  588. """Updates `configs` to reflect the new training batch size.
  589. The configs dictionary is updated in place, and hence not returned.
  590. Args:
  591. configs: Dictionary of configuration objects. See outputs from
  592. get_configs_from_pipeline_file() or get_configs_from_multiple_files().
  593. batch_size: Batch size to use for training (Ideally a power of 2). Inputs
  594. are rounded, and capped to be 1 or greater.
  595. """
  596. configs["train_config"].batch_size = max(1, int(round(batch_size)))
  597. def _validate_message_has_field(message, field):
  598. if not message.HasField(field):
  599. raise ValueError("Expecting message to have field %s" % field)
  600. def _update_generic(configs, key, value):
  601. """Update a pipeline configuration parameter based on a generic key/value.
  602. Args:
  603. configs: Dictionary of pipeline configuration protos.
  604. key: A string key, dot-delimited to represent the argument key.
  605. e.g. "model.ssd.train_config.batch_size"
  606. value: A value to set the argument to. The type of the value must match the
  607. type for the protocol buffer. Note that setting the wrong type will
  608. result in a TypeError.
  609. e.g. 42
  610. Raises:
  611. ValueError if the message key does not match the existing proto fields.
  612. TypeError the value type doesn't match the protobuf field type.
  613. """
  614. fields = key.split(".")
  615. first_field = fields.pop(0)
  616. last_field = fields.pop()
  617. message = configs[first_field]
  618. for field in fields:
  619. _validate_message_has_field(message, field)
  620. message = getattr(message, field)
  621. _validate_message_has_field(message, last_field)
  622. setattr(message, last_field, value)
  623. def _update_momentum_optimizer_value(configs, momentum):
  624. """Updates `configs` to reflect the new momentum value.
  625. Momentum is only supported for RMSPropOptimizer and MomentumOptimizer. For any
  626. other optimizer, no changes take place. The configs dictionary is updated in
  627. place, and hence not returned.
  628. Args:
  629. configs: Dictionary of configuration objects. See outputs from
  630. get_configs_from_pipeline_file() or get_configs_from_multiple_files().
  631. momentum: New momentum value. Values are clipped at 0.0 and 1.0.
  632. Raises:
  633. TypeError: If the optimizer type is not `rms_prop_optimizer` or
  634. `momentum_optimizer`.
  635. """
  636. optimizer_type = get_optimizer_type(configs["train_config"])
  637. if optimizer_type == "rms_prop_optimizer":
  638. optimizer_config = configs["train_config"].optimizer.rms_prop_optimizer
  639. elif optimizer_type == "momentum_optimizer":
  640. optimizer_config = configs["train_config"].optimizer.momentum_optimizer
  641. else:
  642. raise TypeError("Optimizer type must be one of `rms_prop_optimizer` or "
  643. "`momentum_optimizer`.")
  644. optimizer_config.momentum_optimizer_value = min(max(0.0, momentum), 1.0)
  645. def _update_classification_localization_weight_ratio(configs, ratio):
  646. """Updates the classification/localization weight loss ratio.
  647. Detection models usually define a loss weight for both classification and
  648. objectness. This function updates the weights such that the ratio between
  649. classification weight to localization weight is the ratio provided.
  650. Arbitrarily, localization weight is set to 1.0.
  651. Note that in the case of Faster R-CNN, this same ratio is applied to the first
  652. stage objectness loss weight relative to localization loss weight.
  653. The configs dictionary is updated in place, and hence not returned.
  654. Args:
  655. configs: Dictionary of configuration objects. See outputs from
  656. get_configs_from_pipeline_file() or get_configs_from_multiple_files().
  657. ratio: Desired ratio of classification (and/or objectness) loss weight to
  658. localization loss weight.
  659. """
  660. meta_architecture = configs["model"].WhichOneof("model")
  661. if meta_architecture == "faster_rcnn":
  662. model = configs["model"].faster_rcnn
  663. model.first_stage_localization_loss_weight = 1.0
  664. model.first_stage_objectness_loss_weight = ratio
  665. model.second_stage_localization_loss_weight = 1.0
  666. model.second_stage_classification_loss_weight = ratio
  667. if meta_architecture == "ssd":
  668. model = configs["model"].ssd
  669. model.loss.localization_weight = 1.0
  670. model.loss.classification_weight = ratio
  671. def _get_classification_loss(model_config):
  672. """Returns the classification loss for a model."""
  673. meta_architecture = model_config.WhichOneof("model")
  674. if meta_architecture == "faster_rcnn":
  675. model = model_config.faster_rcnn
  676. classification_loss = model.second_stage_classification_loss
  677. elif meta_architecture == "ssd":
  678. model = model_config.ssd
  679. classification_loss = model.loss.classification_loss
  680. else:
  681. raise TypeError("Did not recognize the model architecture.")
  682. return classification_loss
  683. def _update_focal_loss_gamma(configs, gamma):
  684. """Updates the gamma value for a sigmoid focal loss.
  685. The configs dictionary is updated in place, and hence not returned.
  686. Args:
  687. configs: Dictionary of configuration objects. See outputs from
  688. get_configs_from_pipeline_file() or get_configs_from_multiple_files().
  689. gamma: Exponent term in focal loss.
  690. Raises:
  691. TypeError: If the classification loss is not `weighted_sigmoid_focal`.
  692. """
  693. classification_loss = _get_classification_loss(configs["model"])
  694. classification_loss_type = classification_loss.WhichOneof(
  695. "classification_loss")
  696. if classification_loss_type != "weighted_sigmoid_focal":
  697. raise TypeError("Classification loss must be `weighted_sigmoid_focal`.")
  698. classification_loss.weighted_sigmoid_focal.gamma = gamma
  699. def _update_focal_loss_alpha(configs, alpha):
  700. """Updates the alpha value for a sigmoid focal loss.
  701. The configs dictionary is updated in place, and hence not returned.
  702. Args:
  703. configs: Dictionary of configuration objects. See outputs from
  704. get_configs_from_pipeline_file() or get_configs_from_multiple_files().
  705. alpha: Class weight multiplier for sigmoid loss.
  706. Raises:
  707. TypeError: If the classification loss is not `weighted_sigmoid_focal`.
  708. """
  709. classification_loss = _get_classification_loss(configs["model"])
  710. classification_loss_type = classification_loss.WhichOneof(
  711. "classification_loss")
  712. if classification_loss_type != "weighted_sigmoid_focal":
  713. raise TypeError("Classification loss must be `weighted_sigmoid_focal`.")
  714. classification_loss.weighted_sigmoid_focal.alpha = alpha
  715. def _update_train_steps(configs, train_steps):
  716. """Updates `configs` to reflect new number of training steps."""
  717. configs["train_config"].num_steps = int(train_steps)
  718. def _update_all_eval_input_configs(configs, field, value):
  719. """Updates the content of `field` with `value` for all eval input configs."""
  720. for eval_input_config in configs["eval_input_configs"]:
  721. setattr(eval_input_config, field, value)
  722. def _update_label_map_path(configs, label_map_path):
  723. """Updates the label map path for both train and eval input readers.
  724. The configs dictionary is updated in place, and hence not returned.
  725. Args:
  726. configs: Dictionary of configuration objects. See outputs from
  727. get_configs_from_pipeline_file() or get_configs_from_multiple_files().
  728. label_map_path: New path to `StringIntLabelMap` pbtxt file.
  729. """
  730. configs["train_input_config"].label_map_path = label_map_path
  731. _update_all_eval_input_configs(configs, "label_map_path", label_map_path)
  732. def _update_mask_type(configs, mask_type):
  733. """Updates the mask type for both train and eval input readers.
  734. The configs dictionary is updated in place, and hence not returned.
  735. Args:
  736. configs: Dictionary of configuration objects. See outputs from
  737. get_configs_from_pipeline_file() or get_configs_from_multiple_files().
  738. mask_type: A string name representing a value of
  739. input_reader_pb2.InstanceMaskType
  740. """
  741. configs["train_input_config"].mask_type = mask_type
  742. _update_all_eval_input_configs(configs, "mask_type", mask_type)
  743. def _update_use_moving_averages(configs, use_moving_averages):
  744. """Updates the eval config option to use or not use moving averages.
  745. The configs dictionary is updated in place, and hence not returned.
  746. Args:
  747. configs: Dictionary of configuration objects. See outputs from
  748. get_configs_from_pipeline_file() or get_configs_from_multiple_files().
  749. use_moving_averages: Boolean indicating whether moving average variables
  750. should be loaded during evaluation.
  751. """
  752. configs["eval_config"].use_moving_averages = use_moving_averages
  753. def _update_retain_original_images(eval_config, retain_original_images):
  754. """Updates eval config with option to retain original images.
  755. The eval_config object is updated in place, and hence not returned.
  756. Args:
  757. eval_config: A eval_pb2.EvalConfig.
  758. retain_original_images: Boolean indicating whether to retain original images
  759. in eval mode.
  760. """
  761. eval_config.retain_original_images = retain_original_images
  762. def _update_use_bfloat16(configs, use_bfloat16):
  763. """Updates `configs` to reflect the new setup on whether to use bfloat16.
  764. The configs dictionary is updated in place, and hence not returned.
  765. Args:
  766. configs: Dictionary of configuration objects. See outputs from
  767. get_configs_from_pipeline_file() or get_configs_from_multiple_files().
  768. use_bfloat16: A bool, indicating whether to use bfloat16 for training.
  769. """
  770. configs["train_config"].use_bfloat16 = use_bfloat16