checkpoint.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  1. ## @package checkpoint
  2. # Module caffe2.python.checkpoint
  3. import os
  4. import logging
  5. from caffe2.python import core, context
  6. from caffe2.python.net_builder import ops
  7. from caffe2.python.task import (
  8. final_output,
  9. Node,
  10. Task,
  11. TaskGroup,
  12. TaskOutput,
  13. WorkspaceType,
  14. )
  15. logger = logging.getLogger(__name__)
  16. class Job(context.Managed):
  17. """
  18. A Job defines three TaskGroups: the `init_group`, the `epoch_group` and the
  19. `exit_group` which will be run by a JobRunner.
  20. The `init_group` will be run only once at startup. Its role is to
  21. initialize globally persistent blobs such as model weights, accumulators
  22. and data file lists.
  23. The `epoch_group` will be run in a loop after init_group. The loop will
  24. exit when any of the stop signals added with `add_stop_condition` is True
  25. at the end of an epoch.
  26. The download_group will be run only once, after all the executions of
  27. epoch_group finish. Its role is to collect the distribute scattered
  28. parameters back after training.
  29. The `exit_group` will be run only once at the very end of the job, the
  30. role of this group is to save the results of training in the end of the job.
  31. Jobs are context-driven, so that Tasks can be added to the active Job
  32. without having to explicitly pass the job object around.
  33. Example of usage:
  34. def build_reader(partitions):
  35. with Job.current().init_group:
  36. reader = HiveReader(init_reader, ..., partitions)
  37. Task(step=init_reader)
  38. with Job.current().epoch_group:
  39. limited_reader = ReaderWithLimit(reader, num_iter=10000)
  40. data_queue = pipe(limited_reader, num_threads=8)
  41. Job.current().add_stop_condition(limited_reader.data_finished())
  42. return data_queue
  43. def build_hogwild_trainer(reader, model):
  44. with Job.current().init_group:
  45. Task(step=model.param_init_net)
  46. with Job.current().epoch_group:
  47. pipe(reader, processor=model, num_threads=8)
  48. with Job.current().exit_group:
  49. Task(step=model.save_model_net)
  50. with Job() as job:
  51. reader = build_reader(partitions)
  52. model = build_model(params)
  53. build_hogwild_trainer(reader, model)
  54. """
  55. def __init__(self,
  56. init_group=None, epoch_group=None,
  57. download_group=None, exit_group=None,
  58. stop_conditions=None, nodes_to_checkpoint=None):
  59. self.init_group = init_group or TaskGroup(
  60. workspace_type=WorkspaceType.GLOBAL)
  61. self.epoch_group = epoch_group or TaskGroup()
  62. self.download_group = download_group or TaskGroup()
  63. self.exit_group = exit_group or TaskGroup()
  64. self.stop_conditions = stop_conditions or []
  65. self._nodes_to_checkpoint = nodes_to_checkpoint
  66. def nodes_to_checkpoint(self):
  67. if self._nodes_to_checkpoint:
  68. return self._nodes_to_checkpoint
  69. else:
  70. return self.init_group.used_nodes()
  71. def compile(self, session_class):
  72. self._nodes_to_checkpoint = self.nodes_to_checkpoint()
  73. self.init_group = session_class.compile(self.init_group)
  74. self.epoch_group = session_class.compile(self.epoch_group)
  75. self.download_group = session_class.compile(self.download_group)
  76. self.exit_group = session_class.compile(self.exit_group)
  77. def __enter__(self):
  78. super(Job, self).__enter__()
  79. self.epoch_group.__enter__()
  80. return self
  81. def __exit__(self, *args):
  82. self.epoch_group.__exit__()
  83. super(Job, self).__exit__(*args)
  84. def add_stop_condition(self, output):
  85. if isinstance(output, core.BlobReference):
  86. t = Task(outputs=[output], group=self.epoch_group)
  87. output = t.outputs()[0]
  88. assert isinstance(output, TaskOutput)
  89. self.stop_conditions.append(output)
  90. def get_ckpt_filename(node_name, epoch):
  91. """Returns the checkpoint filename.
  92. Args:
  93. node_name: A string. The name of the node.
  94. epoch: An integer. The checkpoint epoch.
  95. Returns:
  96. ckpt_filename: A string. The filename of the checkpoint.
  97. """
  98. return node_name + '.' + str(epoch)
  99. def db_name(epoch, node_name, db_prefix, path_prefix=None):
  100. """Returns the full db name where checkpoint files are saved.
  101. Args:
  102. epoch: An integer. The checkpoint epoch.
  103. node_name: A string. The name of the node.
  104. db_prefix: A string. The prefix used to construct full db name.
  105. path_prefix: A string. Optional param used to construct db name or path
  106. where checkpoint files are stored.
  107. Returns:
  108. db_name: A string. The absolute path of full_db_name where checkpoint
  109. files are saved
  110. """
  111. if path_prefix:
  112. db_name = path_prefix + get_ckpt_filename(node_name, epoch)
  113. else:
  114. ckpt_filename = get_ckpt_filename(node_name, epoch)
  115. db_name = os.path.join(db_prefix, ckpt_filename)
  116. return db_name
  117. class CheckpointManager(object):
  118. """
  119. Controls saving and loading of workspaces on every epoch boundary of a job.
  120. If a CheckpointManager instance is passed to JobRunner, then JobRunner will
  121. call `init`, `read` and `save` at different moments in between epoch runs.
  122. Args:
  123. db_prefix: The prefix used to construct full db name. Since `absolute_path`
  124. is set to True, this will be used as db_name in SaveOp.
  125. node_name: Name of the node where this checkpoint_manager is used.
  126. db_type: Type of database to use for storing checkpoint.
  127. metadata_handler: An optional object capable of reading/writing
  128. checkpoint info in storage of choice.
  129. """
  130. BLOB_NAMES = "blob_names"
  131. def __init__(self, db_prefix, node_name, db_type, metadata_handler=None):
  132. self._db_prefix = db_prefix
  133. self._node_name = node_name
  134. self._db_type = db_type
  135. self._metadata_handler = metadata_handler
  136. # make sure these blobs are the first in the checkpoint file.
  137. self._net = core.Net('!!checkpoint_mngr')
  138. self._blob_names = self._net.AddExternalInput(self.BLOB_NAMES)
  139. self._names_output = None
  140. self._path_prefix = None
  141. self._path_type = None
  142. self._current_db_name = None
  143. self._current_checkpoint_duration = None
  144. """
  145. Initialize the checkpoint manager. Determines all blobs that need to be saved
  146. or loads from a checkpoint.
  147. Args:
  148. nodes: An array of nodes where this checkpoint manager is running. Should
  149. only contain a single node.
  150. retrieve_from_epoch: Set to a number to load blobs from this epoch.
  151. path_prefix: Used to construct db name or path where checkpoint files are
  152. stored.
  153. path_type: Indicate the type of path where checkpoint files are stored.
  154. """
  155. def init(
  156. self,
  157. nodes=None,
  158. retrieve_from_epoch=None,
  159. path_prefix=None,
  160. path_type=None
  161. ):
  162. """
  163. Build a Task that will be run once after the job's `init_group` is run.
  164. This task will determine which blobs need to be checkpointed.
  165. If retrieve_from_epoch is not None, then the checkpoint metadata is
  166. retrieved from a previously saved checkpoint.
  167. """
  168. assert nodes is None or len(nodes) == 1, (
  169. 'CheckpointManager only supports single node.')
  170. with Task(outputs=[self._blob_names]) as task:
  171. if retrieve_from_epoch is None:
  172. ops.GetAllBlobNames(
  173. [],
  174. self._blob_names,
  175. include_shared=False)
  176. else:
  177. full_db_name = db_name(retrieve_from_epoch,
  178. self._node_name, self._db_prefix, path_prefix)
  179. db_type = path_type or self._db_type
  180. logger.info("Initializing checkpoints from = %s"
  181. % full_db_name)
  182. ops.Load(
  183. [], self._blob_names,
  184. db=full_db_name,
  185. db_type=db_type,
  186. absolute_path=True,
  187. keep_device=True,
  188. )
  189. self._names_output = task.outputs()[0]
  190. return task
  191. def blob_list(self):
  192. assert self._names_output
  193. return self._names_output.fetch().tolist()
  194. def _timed_task(self, cp_op_name, add_op):
  195. """
  196. Build a Task that will measure the time span of checkpoint operations,
  197. once operation is done, time can be read from _current_checkpoint_duration.
  198. Args:
  199. cp_op_name: A string name of the checkpoint operation.
  200. add_op: A functor to add the checkpoint operation.
  201. Returns:
  202. A task with timer.
  203. """
  204. with Task(name=cp_op_name) as task:
  205. with ops.task_init():
  206. timer = ops.TimerBegin([], counter_name=self._node_name)
  207. add_op()
  208. with ops.task_exit():
  209. time_span_blob = ops.TimerGetAndEnd(timer)
  210. self._current_checkpoint_duration = final_output(time_span_blob)
  211. return task
  212. def collect_checkpoint_stats(self, stats):
  213. """
  214. Add one checkpoint stats into the stats.
  215. Args:
  216. stats: A dict of checkpoint stats that will be reported.
  217. """
  218. if self._current_db_name and self._current_checkpoint_duration:
  219. stats[self._current_db_name] = self._current_checkpoint_duration.fetch()[0]
  220. else:
  221. logger.info(
  222. "Failed to collect checkpoint stats: {}".format(
  223. self._current_db_name
  224. )
  225. )
  226. def load(self, epoch, path_prefix=None, path_type=None):
  227. """
  228. Build a Task that will be run by JobRunner when the job is to be
  229. resumed from a given epoch. This task will run a Load op that will
  230. load and deserialize all relevant blobs from a persistent storage.
  231. """
  232. self._current_db_name = db_name(
  233. epoch, self._node_name, self._db_prefix, path_prefix
  234. )
  235. db_type = path_type or self._db_type
  236. logger.info("Loading checkpoints from = %s" % self._current_db_name)
  237. def add_op():
  238. ops.Load(
  239. [],
  240. self.blob_list(),
  241. db=self._current_db_name,
  242. db_type=db_type,
  243. absolute_path=True,
  244. keep_device=True,
  245. )
  246. return self._timed_task('checkpoint_load', add_op)
  247. def load_blobs_from_checkpoint(self, blob_names, epoch):
  248. """
  249. Builds a Task that loads only the necessary blobs from a checkpoint of
  250. the given epoch. The necessary blobs are given in the blob_names
  251. argument.
  252. Args:
  253. blob_names: A list of strings. Each string is the name of a
  254. blob.
  255. epoch: The checkpoint epoch to load from.
  256. Returns:
  257. A Task which loads the specified blobs from the checkpoint of the
  258. given epoch.
  259. """
  260. self._current_db_name = db_name(epoch, self._node_name, self._db_prefix)
  261. logger.info('Load from %s' % self._current_db_name)
  262. def add_op():
  263. ops.Load(
  264. [],
  265. blob_names,
  266. db=self._current_db_name,
  267. db_type=self._db_type,
  268. absolute_path=True,
  269. allow_incomplete=True)
  270. return self._timed_task('checkpoint_partial_load', add_op)
  271. def check_db_exists(self, epoch):
  272. logger.info('Check existence of %s' %
  273. db_name(epoch, self._node_name, self._db_prefix))
  274. with Task() as task:
  275. existence = ops.Const(False)
  276. ops.DBExists(
  277. [],
  278. [existence],
  279. db_name=db_name(epoch, self._node_name, self._db_prefix),
  280. db_type=self._db_type,
  281. absolute_path=True)
  282. task.add_output(existence)
  283. return task
  284. def report_checkpoint_stats(self, action_name):
  285. """
  286. Report checkpoint operation stats for current node.
  287. Args:
  288. action_name: A string of the name of checkpoint operation.
  289. """
  290. all_stats = {}
  291. self.collect_checkpoint_stats(all_stats)
  292. if self._metadata_handler:
  293. self._metadata_handler.report(action_name, all_stats)
  294. def save(self, epoch):
  295. """
  296. Build a Task that is run once after `init_group` and after each
  297. epoch is run. This will execute a Save ops to serialize and persist
  298. blobs present in the global workspace.
  299. """
  300. self._current_db_name = db_name(epoch, self._node_name, self._db_prefix)
  301. logger.info('Saving to %s' % self._current_db_name)
  302. def add_op():
  303. ops.Save(
  304. self.blob_list(), [],
  305. db=self._current_db_name,
  306. db_type=self._db_type,
  307. absolute_path=True)
  308. return self._timed_task('checkpoint_save', add_op)
  309. def write_checkpoint_metadata(self, epoch):
  310. """
  311. Write metadata for checkpoint
  312. Args:
  313. epoch: An integer. The epoch-id for which checkpoint metadata is
  314. written
  315. """
  316. if self._metadata_handler is not None:
  317. self._metadata_handler.write(epoch=epoch)
  318. def get_resume_from_epoch_id(self, user_epoch=None):
  319. """
  320. Identify the epoch-id from which Job must resume
  321. Args:
  322. user_epoch: An integer. Optional parameter for user to explicitly
  323. identify the epoch-id to load checkpoint from
  324. Returns:
  325. epoch: the epoch-id to load checkpoints from
  326. or None if no checkpoints were written
  327. """
  328. last_epoch = user_epoch
  329. if self._metadata_handler is not None:
  330. last_epoch = self._metadata_handler.last_epoch(user_epoch=user_epoch)
  331. return last_epoch
  332. def set_params(self, nodes, path_prefix=None, path_type=None):
  333. """Set parameters associated with CP manager
  334. Args:
  335. nodes: An array of nodes where this checkpoint manager is running.
  336. path_prefix: Used to construct db name or path where checkpoint files are
  337. stored.
  338. path_type: Indicate the type of path where checkpoint files are stored.
  339. """
  340. if path_prefix:
  341. self._path_prefix = path_prefix
  342. if path_type:
  343. self._path_type = path_type
  344. if self._metadata_handler:
  345. self._metadata_handler.set_params(
  346. db_prefix=self._db_prefix,
  347. db_type=self._db_type,
  348. node_names=[str(self._node_name)],
  349. path_prefix=self._path_prefix,
  350. path_type=self._path_type)
  351. def cp_accessible(self, epoch=None):
  352. """Returns True if Checkpoint data is accessible
  353. Args:
  354. epoch: An integer. The epoch of the checkpoint. If None,
  355. it implies we need to check if checkpoint directory is accessible
  356. Returns:
  357. is_cp_accessible: A boolean. Returns True if Checkpoint data is accessible
  358. """
  359. if self._metadata_handler is not None:
  360. return self._metadata_handler.cp_accessible(epoch)
  361. else:
  362. return True
  363. class MultiNodeCheckpointManager(object):
  364. """
  365. Coordinates checkpointing and checkpointing across multiple nodes.
  366. Each of `init`, `load` and `save` will build TaskGroups which will
  367. trigger checkpointing on each of the nodes involved in a distributed job.
  368. Args:
  369. db_prefix: The prefix used to construct full db name. Since `absolute_path`
  370. is set to True, this will be used as db_name in SaveOp.
  371. db_type: Type of database to use for storing checkpoint.
  372. metadata_handler: An optional object capable of reading/writing
  373. checkpoint info in storage of choice.
  374. """
  375. def __init__(self, db_prefix, db_type, metadata_handler=None):
  376. self._node_managers = None
  377. self._db_prefix = db_prefix
  378. self._db_type = db_type
  379. self._metadata_handler = metadata_handler
  380. self._path_prefix = None
  381. self._path_type = None
  382. def _task_group(self, func, *args, **kw):
  383. assert self._node_managers is not None, 'init must be called first.'
  384. with TaskGroup(WorkspaceType.GLOBAL) as task_group:
  385. for node, manager in self._node_managers:
  386. with Node(node):
  387. func(manager, *args, **kw)
  388. return task_group
  389. """
  390. Args:
  391. nodes: An array of nodes where this checkpoint manager is running.
  392. retrieve_from_epoch: Set to a number to load blobs from this epoch.
  393. path_prefix: Used to construct db name or path where checkpoint files are
  394. stored.
  395. path_type: Indicate the type of path where checkpoint files are stored.
  396. """
  397. def init(
  398. self, nodes, retrieve_from_epoch=None, path_prefix=None, path_type=None
  399. ):
  400. if self._node_managers is not None:
  401. assert [node for node, _ in self._node_managers] == nodes
  402. return TaskGroup(WorkspaceType.GLOBAL)
  403. self._node_managers = []
  404. for node in nodes:
  405. with Node(node):
  406. manager = CheckpointManager(
  407. db_prefix=self._db_prefix,
  408. node_name=str(node),
  409. db_type=self._db_type)
  410. self._node_managers.append((node, manager))
  411. return self._task_group(
  412. CheckpointManager.init,
  413. nodes=[node],
  414. retrieve_from_epoch=retrieve_from_epoch,
  415. path_prefix=path_prefix,
  416. path_type=path_type)
  417. def load(self, epoch, path_prefix=None, path_type=None):
  418. return self._task_group(
  419. CheckpointManager.load,
  420. epoch,
  421. path_prefix=path_prefix,
  422. path_type=path_type)
  423. def load_blobs_locally(self, nodes, blob_names, epoch, session):
  424. """Loads the necessary blobs from the checkpoints to the current node.
  425. Args:
  426. blob_names: A list of strings. Each string is the name of a
  427. blob.
  428. epoch: An integer. The checkpoint epoch to load from.
  429. session: A Session object to execute the Load ops.
  430. """
  431. if self._node_managers is not None:
  432. assert [node for node, _ in self._node_managers] == nodes
  433. else:
  434. self._node_managers = []
  435. for node in nodes:
  436. with Node(node):
  437. manager = CheckpointManager(
  438. db_prefix=self._db_prefix,
  439. node_name=str(node),
  440. db_type=self._db_type)
  441. self._node_managers.append((node, manager))
  442. assert self._node_managers is not None, 'must initialize node managers'
  443. for _, manager in self._node_managers:
  444. existence_task = manager.check_db_exists(epoch)
  445. session.run(existence_task)
  446. existence = existence_task.outputs()[0].fetch()
  447. if not existence:
  448. logger.info('DB %s does not exist!' %
  449. db_name(epoch, manager._node_name, manager._db_prefix))
  450. return False
  451. load_task = manager.load_blobs_from_checkpoint(blob_names, epoch)
  452. session.run(load_task)
  453. logger.info('Successfully loaded from checkpoints.')
  454. return True
  455. def get_ckpt_db_name(self, node_name, epoch):
  456. """Returns the DB name of the given node and the given epoch.
  457. The DB name is effectively the checkpoint path of the given node and
  458. the given epoch.
  459. Args:
  460. node_name: A string. The node name of interest.
  461. epoch: An integer. The epoch of the checkpoint.
  462. Returns:
  463. checkpoint_db_name: A string. The checkpoint path of the given
  464. node and the given epoch.
  465. """
  466. for node, manager in self._node_managers:
  467. if str(node) == node_name:
  468. return db_name(epoch, manager._node_name, manager._db_prefix)
  469. def report_checkpoint_stats(self, action_name):
  470. """
  471. Report the checkpoint stats for all the nodes, we need to aggregate all
  472. the node's stats together so that we know which node's checkpoint
  473. operation dominates.
  474. Args:
  475. action_name: A string of the name of checkpoint operation.
  476. """
  477. all_stats = {}
  478. for _, manager in self._node_managers:
  479. manager.collect_checkpoint_stats(all_stats)
  480. logger.debug("checkpoint stats: {}".format(all_stats))
  481. if self._metadata_handler:
  482. self._metadata_handler.report(action_name, all_stats)
  483. def save(self, epoch):
  484. """
  485. Build a Task that will execute a Save ops to serialize and persist
  486. blobs present in the global workspace.
  487. """
  488. return self._task_group(CheckpointManager.save, epoch)
  489. def write_checkpoint_metadata(self, epoch):
  490. """
  491. Write metadata for checkpoint
  492. Args:
  493. epoch: An integer. The epoch-id for which checkpoint metadata is
  494. written
  495. """
  496. if self._metadata_handler is not None:
  497. self._metadata_handler.write(epoch=epoch)
  498. def get_resume_from_epoch_id(self, user_epoch=None):
  499. """
  500. Identify the epoch-id from which Job must resume
  501. Args:
  502. user_epoch: An integer. Optional parameter for user to explicitly
  503. identify the epoch-id to load checkpoint from
  504. Returns:
  505. epoch: the epoch-id to load checkpoints from
  506. or None if no checkpoints were written
  507. """
  508. last_epoch = user_epoch
  509. if self._metadata_handler is not None:
  510. last_epoch = self._metadata_handler.last_epoch(user_epoch=user_epoch)
  511. return last_epoch
  512. def set_params(self, nodes, path_prefix=None, path_type=None):
  513. """Set parameters associated with CP manager
  514. Args:
  515. nodes: An array of nodes where this checkpoint manager is running.
  516. path_prefix: Used to construct db name or path where checkpoint files are
  517. stored.
  518. path_type: Indicate the type of path where checkpoint files are stored.
  519. """
  520. self._node_names = [str(node) for node in nodes]
  521. if path_prefix:
  522. self._path_prefix = path_prefix
  523. if path_type:
  524. self._path_type = path_type
  525. if self._metadata_handler:
  526. self._metadata_handler.set_params(
  527. db_prefix=self._db_prefix,
  528. db_type=self._db_type,
  529. node_names=self._node_names,
  530. path_prefix=self._path_prefix,
  531. path_type=self._path_type)
  532. def cp_accessible(self, epoch=None):
  533. """Returns True if Checkpoint data is accessible
  534. Args:
  535. epoch: An integer. The epoch of the checkpoint. If None,
  536. it implies we need to check if checkpoint directory is accessible
  537. Returns:
  538. is_cp_accessible: A boolean. Returns True if Checkpoint data is accessible
  539. """
  540. if self._metadata_handler is not None:
  541. return self._metadata_handler.cp_accessible(epoch)
  542. else:
  543. return True
  544. class UploadTaskGroupBuilder(object):
  545. """A simple class to upload checkpoints."""
  546. def build(self, epoch, checkpoint_manager):
  547. """Builds the task group to upload checkpoints.
  548. Args:
  549. epoch: An integer. The checkpoint epoch to be uploaded.
  550. checkpoint_manager: Can be a CheckpointManager for single machine
  551. or a MultiNodeCheckpointManager for multi-machine. The manager
  552. that initializes/saves/loads checkpoints.
  553. Raises:
  554. NotImplementedError: This base class only has the interface,
  555. the implementation will be in the subclasses.
  556. """
  557. raise NotImplementedError()
  558. class JobRunner(object):
  559. """
  560. Implement the runtime logic for jobs with checkpointing at the level of
  561. epoch. Can be used to run either single-host or distributed jobs. Job
  562. runner is a callable to be called once from the master, passing a session
  563. as an argument. This call will block until the Job execution is complete.
  564. If a checkpoint_manager is passed, checkpoints will be taken after
  565. initialization and after each epoch execution. If, in addition,
  566. `resume_from_epoch` is an epoch number, the corresponding checkpoint will
  567. be loaded and job execution will continue from the given epoch. In
  568. this case, the job's init_group will not be run.
  569. Refer to checkpoint_test.py for an example.
  570. """
  571. def __init__(self, job, checkpoint_manager=None, resume_from_epoch=None,
  572. upload_task_group_builder=None):
  573. """Initializes the JobRunner.
  574. Args:
  575. job: A Job object. The job to be executed.
  576. checkpoint_manager: Can be a CheckpointManager for single machine
  577. or a MultiNodeCheckpointManager for multi-machine. The manager
  578. that initializes/saves/loads checkpoints.
  579. resume_from_epoch: An integer. The epoch to resume from.
  580. upload_task_group_builder: A subclass of the
  581. UploadTaskGroupBuilder. Creates a task group to upload
  582. checkpoints.
  583. """
  584. self.resume_from_epoch = resume_from_epoch
  585. self.checkpoint_manager = checkpoint_manager
  586. self.job = job
  587. self.upload_task_group_builder = upload_task_group_builder
  588. def train(self, session):
  589. """Runs the training flow.
  590. Args:
  591. session: A Session object. Valid choises are: LocalSession,
  592. LocalHostScheduler, and DistributedSession. It is used to
  593. execute one TaskGroup a time.
  594. """
  595. # identify the epoch we must resume from
  596. if self.checkpoint_manager:
  597. self.checkpoint_manager.set_params(nodes=self.job.nodes_to_checkpoint())
  598. self.resume_from_epoch = self.checkpoint_manager.\
  599. get_resume_from_epoch_id(self.resume_from_epoch)
  600. if self.resume_from_epoch is not None:
  601. logger.info('Resuming from epoch {}'.format(self.resume_from_epoch))
  602. # Initialize all the nodes.
  603. from_scratch = self.resume_from_epoch is None
  604. if from_scratch:
  605. session.run(self.job.init_group)
  606. if self.checkpoint_manager:
  607. logger.info('Preparing checkpoints ...')
  608. session.run(self.checkpoint_manager.init(
  609. self.job.nodes_to_checkpoint(),
  610. retrieve_from_epoch=self.resume_from_epoch))
  611. # Save the first checkpoint before training starts, or resume from
  612. # a previously saved checkpoint.
  613. if from_scratch:
  614. self.save_checkpoints(0, session)
  615. else:
  616. logger.info('Loading checkpoints for epoch {} ...'.format(
  617. self.resume_from_epoch))
  618. session.run(
  619. self.checkpoint_manager.load(self.resume_from_epoch))
  620. self.checkpoint_manager.report_checkpoint_stats('checkpoint_load')
  621. logger.info('Checkpoint loaded')
  622. logger.info("Finished initializing")
  623. # Start training.
  624. epoch = 1 if from_scratch else self.resume_from_epoch + 1
  625. while True:
  626. logger.info('Starting epoch %d' % epoch)
  627. session.run(self.job.epoch_group)
  628. logger.info('Finished epoch %d' % epoch)
  629. stop_conditions = [o.fetch() for o in self.job.stop_conditions]
  630. if self.checkpoint_manager:
  631. self.save_checkpoints(epoch, session)
  632. if any(stop_conditions):
  633. logger.info('Stopping')
  634. break
  635. epoch += 1
  636. logger.info('Finished training')
  637. # Upload the checkpoints.
  638. if (self.upload_task_group_builder):
  639. upload_task_group = self.upload_task_group_builder.build(
  640. epoch, self.checkpoint_manager)
  641. session.run(upload_task_group)
  642. logger.info('Finished uploading the checkpoints')
  643. # Download the parameters to save
  644. session.run(self.job.download_group)
  645. logger.info('Finished downloading the parameters')
  646. # Finally run the exit step to save nets
  647. session.run(self.job.exit_group)
  648. logger.info('Finished running the exit group')
  649. return epoch
  650. def load_blobs_from_checkpoints(self, blob_names, epoch, session):
  651. """Loads the necessary blobs from the checkpoints.
  652. Checkpoints store the snapshots of the workspace in each node.
  653. Sometimes we only need to load a subset of the blobs from the
  654. checkpoints. One common scenario is to load only the model blobs from
  655. the checkpoints for evaluation purpose. Given the names of the
  656. necessary blobs, this function goes over all the checkpoints of all the
  657. nodes, but only loads the blobs specified in the blob_names to the
  658. current workspace.
  659. Args:
  660. blob_names: A list of strings. Each string is the name of a
  661. blob.
  662. epoch: An integer. The checkpoint epoch to load from.
  663. session: A Session object to execute the load ops.
  664. Raises:
  665. ValueError: When the checkpoint manager is invalid.
  666. """
  667. if not self.checkpoint_manager:
  668. raise ValueError('Checkpoint manager is None')
  669. logger.info('Loading checkpoint for epoch {} ...'.format(epoch))
  670. result = self.checkpoint_manager.load_blobs_locally(
  671. self.job.nodes_to_checkpoint(), blob_names, epoch, session)
  672. self.checkpoint_manager.report_checkpoint_stats('checkpoint_partial_load')
  673. return result
  674. def save_checkpoints(self, epoch, session):
  675. """Triggers operation to save checkpoints
  676. This method will trigger the Save ops to serialize and persist the
  677. blobs present in the global workspaace.
  678. Args:
  679. epoch: An integer. The checkpoint epoch-id that we are saving.
  680. session: A Session object to execute the save ops.
  681. Raises:
  682. ValueError: When the checkpoint manager is invalid.
  683. """
  684. if not self.checkpoint_manager:
  685. raise ValueError('Checkpoint manager is None')
  686. try:
  687. is_accessible = self.checkpoint_manager.cp_accessible(epoch=None)
  688. if is_accessible:
  689. logger.info('Saving checkpoints for epoch {}'.format(epoch))
  690. session.run(self.checkpoint_manager.save(epoch))
  691. self.checkpoint_manager.write_checkpoint_metadata(epoch)
  692. logger.info('Checkpoints saved')
  693. self.checkpoint_manager.report_checkpoint_stats('checkpoint_save')
  694. else:
  695. logger.warning("Checkpoint files cannot be accessed!")
  696. except Exception as ex:
  697. logger.warning("Unable to write checkpoint for epoch {}. Error={}".
  698. format(epoch, ex))
  699. def epoch_limiter(job, num_epochs):
  700. """
  701. Creates a task that will output True when a given
  702. number of epochs has finished.
  703. """
  704. with job.init_group:
  705. init_net = core.Net('epoch_counter_init')
  706. counter = init_net.CreateCounter([], init_count=num_epochs - 1)
  707. Task(step=init_net)
  708. with job.epoch_group:
  709. epoch_net = core.Net('epoch_countdown')
  710. finished = epoch_net.CountDown(counter)
  711. output = Task(step=epoch_net, outputs=finished).outputs()[0]
  712. job.add_stop_condition(output)