model_deploy.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. # Copyright 2016 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. """Deploy Slim models across multiple clones and replicas.
  16. # TODO(sguada) docstring paragraph by (a) motivating the need for the file and
  17. # (b) defining clones.
  18. # TODO(sguada) describe the high-level components of model deployment.
  19. # E.g. "each model deployment is composed of several parts: a DeploymentConfig,
  20. # which captures A, B and C, an input_fn which loads data.. etc
  21. To easily train a model on multiple GPUs or across multiple machines this
  22. module provides a set of helper functions: `create_clones`,
  23. `optimize_clones` and `deploy`.
  24. Usage:
  25. g = tf.Graph()
  26. # Set up DeploymentConfig
  27. config = model_deploy.DeploymentConfig(num_clones=2, clone_on_cpu=True)
  28. # Create the global step on the device storing the variables.
  29. with tf.device(config.variables_device()):
  30. global_step = slim.create_global_step()
  31. # Define the inputs
  32. with tf.device(config.inputs_device()):
  33. images, labels = LoadData(...)
  34. inputs_queue = slim.data.prefetch_queue((images, labels))
  35. # Define the optimizer.
  36. with tf.device(config.optimizer_device()):
  37. optimizer = tf.train.MomentumOptimizer(FLAGS.learning_rate, FLAGS.momentum)
  38. # Define the model including the loss.
  39. def model_fn(inputs_queue):
  40. images, labels = inputs_queue.dequeue()
  41. predictions = CreateNetwork(images)
  42. slim.losses.log_loss(predictions, labels)
  43. model_dp = model_deploy.deploy(config, model_fn, [inputs_queue],
  44. optimizer=optimizer)
  45. # Run training.
  46. slim.learning.train(model_dp.train_op, my_log_dir,
  47. summary_op=model_dp.summary_op)
  48. The Clone namedtuple holds together the values associated with each call to
  49. model_fn:
  50. * outputs: The return values of the calls to `model_fn()`.
  51. * scope: The scope used to create the clone.
  52. * device: The device used to create the clone.
  53. DeployedModel namedtuple, holds together the values needed to train multiple
  54. clones:
  55. * train_op: An operation that run the optimizer training op and include
  56. all the update ops created by `model_fn`. Present only if an optimizer
  57. was specified.
  58. * summary_op: An operation that run the summaries created by `model_fn`
  59. and process_gradients.
  60. * total_loss: A `Tensor` that contains the sum of all losses created by
  61. `model_fn` plus the regularization losses.
  62. * clones: List of `Clone` tuples returned by `create_clones()`.
  63. DeploymentConfig parameters:
  64. * num_clones: Number of model clones to deploy in each replica.
  65. * clone_on_cpu: True if clones should be placed on CPU.
  66. * replica_id: Integer. Index of the replica for which the model is
  67. deployed. Usually 0 for the chief replica.
  68. * num_replicas: Number of replicas to use.
  69. * num_ps_tasks: Number of tasks for the `ps` job. 0 to not use replicas.
  70. * worker_job_name: A name for the worker job.
  71. * ps_job_name: A name for the parameter server job.
  72. TODO(sguada):
  73. - describe side effect to the graph.
  74. - what happens to summaries and update_ops.
  75. - which graph collections are altered.
  76. - write a tutorial on how to use this.
  77. - analyze the possibility of calling deploy more than once.
  78. """
  79. from __future__ import absolute_import
  80. from __future__ import division
  81. from __future__ import print_function
  82. import collections
  83. import tensorflow as tf
  84. from tensorflow.python.ops import control_flow_ops
  85. slim = tf.contrib.slim
  86. __all__ = ['create_clones',
  87. 'deploy',
  88. 'optimize_clones',
  89. 'DeployedModel',
  90. 'DeploymentConfig',
  91. 'Clone',
  92. ]
  93. # Namedtuple used to represent a clone during deployment.
  94. Clone = collections.namedtuple('Clone',
  95. ['outputs', # Whatever model_fn() returned.
  96. 'scope', # The scope used to create it.
  97. 'device', # The device used to create.
  98. ])
  99. # Namedtuple used to represent a DeployedModel, returned by deploy().
  100. DeployedModel = collections.namedtuple('DeployedModel',
  101. ['train_op', # The `train_op`
  102. 'summary_op', # The `summary_op`
  103. 'total_loss', # The loss `Tensor`
  104. 'clones', # A list of `Clones` tuples.
  105. ])
  106. # Default parameters for DeploymentConfig
  107. _deployment_params = {'num_clones': 1,
  108. 'clone_on_cpu': False,
  109. 'replica_id': 0,
  110. 'num_replicas': 1,
  111. 'num_ps_tasks': 0,
  112. 'worker_job_name': 'worker',
  113. 'ps_job_name': 'ps'}
  114. def create_clones(config, model_fn, args=None, kwargs=None):
  115. """Creates multiple clones according to config using a `model_fn`.
  116. The returned values of `model_fn(*args, **kwargs)` are collected along with
  117. the scope and device used to created it in a namedtuple
  118. `Clone(outputs, scope, device)`
  119. Note: it is assumed that any loss created by `model_fn` is collected at
  120. the tf.GraphKeys.LOSSES collection.
  121. To recover the losses, summaries or update_ops created by the clone use:
  122. ```python
  123. losses = tf.get_collection(tf.GraphKeys.LOSSES, clone.scope)
  124. summaries = tf.get_collection(tf.GraphKeys.SUMMARIES, clone.scope)
  125. update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, clone.scope)
  126. ```
  127. The deployment options are specified by the config object and support
  128. deploying one or several clones on different GPUs and one or several replicas
  129. of such clones.
  130. The argument `model_fn` is called `config.num_clones` times to create the
  131. model clones as `model_fn(*args, **kwargs)`.
  132. If `config` specifies deployment on multiple replicas then the default
  133. tensorflow device is set appropriatly for each call to `model_fn` and for the
  134. slim variable creation functions: model and global variables will be created
  135. on the `ps` device, the clone operations will be on the `worker` device.
  136. Args:
  137. config: A DeploymentConfig object.
  138. model_fn: A callable. Called as `model_fn(*args, **kwargs)`
  139. args: Optional list of arguments to pass to `model_fn`.
  140. kwargs: Optional list of keyword arguments to pass to `model_fn`.
  141. Returns:
  142. A list of namedtuples `Clone`.
  143. """
  144. clones = []
  145. args = args or []
  146. kwargs = kwargs or {}
  147. with slim.arg_scope([slim.model_variable, slim.variable],
  148. device=config.variables_device()):
  149. # Create clones.
  150. for i in range(0, config.num_clones):
  151. with tf.name_scope(config.clone_scope(i)) as clone_scope:
  152. clone_device = config.clone_device(i)
  153. with tf.device(clone_device):
  154. with tf.variable_scope(tf.get_variable_scope(),
  155. reuse=True if i > 0 else None):
  156. outputs = model_fn(*args, **kwargs)
  157. clones.append(Clone(outputs, clone_scope, clone_device))
  158. return clones
  159. def _gather_clone_loss(clone, num_clones, regularization_losses):
  160. """Gather the loss for a single clone.
  161. Args:
  162. clone: A Clone namedtuple.
  163. num_clones: The number of clones being deployed.
  164. regularization_losses: Possibly empty list of regularization_losses
  165. to add to the clone losses.
  166. Returns:
  167. A tensor for the total loss for the clone. Can be None.
  168. """
  169. # The return value.
  170. sum_loss = None
  171. # Individual components of the loss that will need summaries.
  172. clone_loss = None
  173. regularization_loss = None
  174. # Compute and aggregate losses on the clone device.
  175. with tf.device(clone.device):
  176. all_losses = []
  177. clone_losses = tf.get_collection(tf.GraphKeys.LOSSES, clone.scope)
  178. if clone_losses:
  179. clone_loss = tf.add_n(clone_losses, name='clone_loss')
  180. if num_clones > 1:
  181. clone_loss = tf.div(clone_loss, 1.0 * num_clones,
  182. name='scaled_clone_loss')
  183. all_losses.append(clone_loss)
  184. if regularization_losses:
  185. regularization_loss = tf.add_n(regularization_losses,
  186. name='regularization_loss')
  187. all_losses.append(regularization_loss)
  188. if all_losses:
  189. sum_loss = tf.add_n(all_losses)
  190. # Add the summaries out of the clone device block.
  191. if clone_loss is not None:
  192. tf.summary.scalar(clone.scope + '/clone_loss', clone_loss)
  193. if regularization_loss is not None:
  194. tf.summary.scalar('regularization_loss', regularization_loss)
  195. return sum_loss
  196. def _optimize_clone(optimizer, clone, num_clones, regularization_losses,
  197. **kwargs):
  198. """Compute losses and gradients for a single clone.
  199. Args:
  200. optimizer: A tf.Optimizer object.
  201. clone: A Clone namedtuple.
  202. num_clones: The number of clones being deployed.
  203. regularization_losses: Possibly empty list of regularization_losses
  204. to add to the clone losses.
  205. **kwargs: Dict of kwarg to pass to compute_gradients().
  206. Returns:
  207. A tuple (clone_loss, clone_grads_and_vars).
  208. - clone_loss: A tensor for the total loss for the clone. Can be None.
  209. - clone_grads_and_vars: List of (gradient, variable) for the clone.
  210. Can be empty.
  211. """
  212. sum_loss = _gather_clone_loss(clone, num_clones, regularization_losses)
  213. clone_grad = None
  214. if sum_loss is not None:
  215. with tf.device(clone.device):
  216. clone_grad = optimizer.compute_gradients(sum_loss, **kwargs)
  217. return sum_loss, clone_grad
  218. def optimize_clones(clones, optimizer,
  219. regularization_losses=None,
  220. **kwargs):
  221. """Compute clone losses and gradients for the given list of `Clones`.
  222. Note: The regularization_losses are added to the first clone losses.
  223. Args:
  224. clones: List of `Clones` created by `create_clones()`.
  225. optimizer: An `Optimizer` object.
  226. regularization_losses: Optional list of regularization losses. If None it
  227. will gather them from tf.GraphKeys.REGULARIZATION_LOSSES. Pass `[]` to
  228. exclude them.
  229. **kwargs: Optional list of keyword arguments to pass to `compute_gradients`.
  230. Returns:
  231. A tuple (total_loss, grads_and_vars).
  232. - total_loss: A Tensor containing the average of the clone losses including
  233. the regularization loss.
  234. - grads_and_vars: A List of tuples (gradient, variable) containing the sum
  235. of the gradients for each variable.
  236. """
  237. grads_and_vars = []
  238. clones_losses = []
  239. num_clones = len(clones)
  240. if regularization_losses is None:
  241. regularization_losses = tf.get_collection(
  242. tf.GraphKeys.REGULARIZATION_LOSSES)
  243. for clone in clones:
  244. with tf.name_scope(clone.scope):
  245. clone_loss, clone_grad = _optimize_clone(
  246. optimizer, clone, num_clones, regularization_losses, **kwargs)
  247. if clone_loss is not None:
  248. clones_losses.append(clone_loss)
  249. grads_and_vars.append(clone_grad)
  250. # Only use regularization_losses for the first clone
  251. regularization_losses = None
  252. # Compute the total_loss summing all the clones_losses.
  253. total_loss = tf.add_n(clones_losses, name='total_loss')
  254. # Sum the gradients across clones.
  255. grads_and_vars = _sum_clones_gradients(grads_and_vars)
  256. return total_loss, grads_and_vars
  257. def deploy(config,
  258. model_fn,
  259. args=None,
  260. kwargs=None,
  261. optimizer=None,
  262. summarize_gradients=False):
  263. """Deploys a Slim-constructed model across multiple clones.
  264. The deployment options are specified by the config object and support
  265. deploying one or several clones on different GPUs and one or several replicas
  266. of such clones.
  267. The argument `model_fn` is called `config.num_clones` times to create the
  268. model clones as `model_fn(*args, **kwargs)`.
  269. The optional argument `optimizer` is an `Optimizer` object. If not `None`,
  270. the deployed model is configured for training with that optimizer.
  271. If `config` specifies deployment on multiple replicas then the default
  272. tensorflow device is set appropriatly for each call to `model_fn` and for the
  273. slim variable creation functions: model and global variables will be created
  274. on the `ps` device, the clone operations will be on the `worker` device.
  275. Args:
  276. config: A `DeploymentConfig` object.
  277. model_fn: A callable. Called as `model_fn(*args, **kwargs)`
  278. args: Optional list of arguments to pass to `model_fn`.
  279. kwargs: Optional list of keyword arguments to pass to `model_fn`.
  280. optimizer: Optional `Optimizer` object. If passed the model is deployed
  281. for training with that optimizer.
  282. summarize_gradients: Whether or not add summaries to the gradients.
  283. Returns:
  284. A `DeployedModel` namedtuple.
  285. """
  286. # Gather initial summaries.
  287. summaries = set(tf.get_collection(tf.GraphKeys.SUMMARIES))
  288. # Create Clones.
  289. clones = create_clones(config, model_fn, args, kwargs)
  290. first_clone = clones[0]
  291. # Gather update_ops from the first clone. These contain, for example,
  292. # the updates for the batch_norm variables created by model_fn.
  293. update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, first_clone.scope)
  294. train_op = None
  295. total_loss = None
  296. with tf.device(config.optimizer_device()):
  297. if optimizer:
  298. # Place the global step on the device storing the variables.
  299. with tf.device(config.variables_device()):
  300. global_step = slim.get_or_create_global_step()
  301. # Compute the gradients for the clones.
  302. total_loss, clones_gradients = optimize_clones(clones, optimizer)
  303. if clones_gradients:
  304. if summarize_gradients:
  305. # Add summaries to the gradients.
  306. summaries |= set(_add_gradients_summaries(clones_gradients))
  307. # Create gradient updates.
  308. grad_updates = optimizer.apply_gradients(clones_gradients,
  309. global_step=global_step)
  310. update_ops.append(grad_updates)
  311. update_op = tf.group(*update_ops)
  312. train_op = control_flow_ops.with_dependencies([update_op], total_loss,
  313. name='train_op')
  314. else:
  315. clones_losses = []
  316. regularization_losses = tf.get_collection(
  317. tf.GraphKeys.REGULARIZATION_LOSSES)
  318. for clone in clones:
  319. with tf.name_scope(clone.scope):
  320. clone_loss = _gather_clone_loss(clone, len(clones),
  321. regularization_losses)
  322. if clone_loss is not None:
  323. clones_losses.append(clone_loss)
  324. # Only use regularization_losses for the first clone
  325. regularization_losses = None
  326. if clones_losses:
  327. total_loss = tf.add_n(clones_losses, name='total_loss')
  328. # Add the summaries from the first clone. These contain the summaries
  329. # created by model_fn and either optimize_clones() or _gather_clone_loss().
  330. summaries |= set(tf.get_collection(tf.GraphKeys.SUMMARIES,
  331. first_clone.scope))
  332. if total_loss is not None:
  333. # Add total_loss to summary.
  334. summaries.add(tf.summary.scalar('total_loss', total_loss))
  335. if summaries:
  336. # Merge all summaries together.
  337. summary_op = tf.summary.merge(list(summaries), name='summary_op')
  338. else:
  339. summary_op = None
  340. return DeployedModel(train_op, summary_op, total_loss, clones)
  341. def _sum_clones_gradients(clone_grads):
  342. """Calculate the sum gradient for each shared variable across all clones.
  343. This function assumes that the clone_grads has been scaled appropriately by
  344. 1 / num_clones.
  345. Args:
  346. clone_grads: A List of List of tuples (gradient, variable), one list per
  347. `Clone`.
  348. Returns:
  349. List of tuples of (gradient, variable) where the gradient has been summed
  350. across all clones.
  351. """
  352. sum_grads = []
  353. for grad_and_vars in zip(*clone_grads):
  354. # Note that each grad_and_vars looks like the following:
  355. # ((grad_var0_clone0, var0), ... (grad_varN_cloneN, varN))
  356. grads = []
  357. var = grad_and_vars[0][1]
  358. for g, v in grad_and_vars:
  359. assert v == var
  360. if g is not None:
  361. grads.append(g)
  362. if grads:
  363. if len(grads) > 1:
  364. sum_grad = tf.add_n(grads, name=var.op.name + '/sum_grads')
  365. else:
  366. sum_grad = grads[0]
  367. sum_grads.append((sum_grad, var))
  368. return sum_grads
  369. def _add_gradients_summaries(grads_and_vars):
  370. """Add histogram summaries to gradients.
  371. Note: The summaries are also added to the SUMMARIES collection.
  372. Args:
  373. grads_and_vars: A list of gradient to variable pairs (tuples).
  374. Returns:
  375. The _list_ of the added summaries for grads_and_vars.
  376. """
  377. summaries = []
  378. for grad, var in grads_and_vars:
  379. if grad is not None:
  380. if isinstance(grad, tf.IndexedSlices):
  381. grad_values = grad.values
  382. else:
  383. grad_values = grad
  384. summaries.append(tf.summary.histogram(var.op.name + ':gradient',
  385. grad_values))
  386. summaries.append(tf.summary.histogram(var.op.name + ':gradient_norm',
  387. tf.global_norm([grad_values])))
  388. else:
  389. tf.logging.info('Var %s has no gradient', var.op.name)
  390. return summaries
  391. class DeploymentConfig(object):
  392. """Configuration for deploying a model with `deploy()`.
  393. You can pass an instance of this class to `deploy()` to specify exactly
  394. how to deploy the model to build. If you do not pass one, an instance built
  395. from the default deployment_hparams will be used.
  396. """
  397. def __init__(self,
  398. num_clones=1,
  399. clone_on_cpu=False,
  400. replica_id=0,
  401. num_replicas=1,
  402. num_ps_tasks=0,
  403. worker_job_name='worker',
  404. ps_job_name='ps'):
  405. """Create a DeploymentConfig.
  406. The config describes how to deploy a model across multiple clones and
  407. replicas. The model will be replicated `num_clones` times in each replica.
  408. If `clone_on_cpu` is True, each clone will placed on CPU.
  409. If `num_replicas` is 1, the model is deployed via a single process. In that
  410. case `worker_device`, `num_ps_tasks`, and `ps_device` are ignored.
  411. If `num_replicas` is greater than 1, then `worker_device` and `ps_device`
  412. must specify TensorFlow devices for the `worker` and `ps` jobs and
  413. `num_ps_tasks` must be positive.
  414. Args:
  415. num_clones: Number of model clones to deploy in each replica.
  416. clone_on_cpu: If True clones would be placed on CPU.
  417. replica_id: Integer. Index of the replica for which the model is
  418. deployed. Usually 0 for the chief replica.
  419. num_replicas: Number of replicas to use.
  420. num_ps_tasks: Number of tasks for the `ps` job. 0 to not use replicas.
  421. worker_job_name: A name for the worker job.
  422. ps_job_name: A name for the parameter server job.
  423. Raises:
  424. ValueError: If the arguments are invalid.
  425. """
  426. if num_replicas > 1:
  427. if num_ps_tasks < 1:
  428. raise ValueError('When using replicas num_ps_tasks must be positive')
  429. if num_replicas > 1 or num_ps_tasks > 0:
  430. if not worker_job_name:
  431. raise ValueError('Must specify worker_job_name when using replicas')
  432. if not ps_job_name:
  433. raise ValueError('Must specify ps_job_name when using parameter server')
  434. if replica_id >= num_replicas:
  435. raise ValueError('replica_id must be less than num_replicas')
  436. self._num_clones = num_clones
  437. self._clone_on_cpu = clone_on_cpu
  438. self._replica_id = replica_id
  439. self._num_replicas = num_replicas
  440. self._num_ps_tasks = num_ps_tasks
  441. self._ps_device = '/job:' + ps_job_name if num_ps_tasks > 0 else ''
  442. self._worker_device = '/job:' + worker_job_name if num_ps_tasks > 0 else ''
  443. @property
  444. def num_clones(self):
  445. return self._num_clones
  446. @property
  447. def clone_on_cpu(self):
  448. return self._clone_on_cpu
  449. @property
  450. def replica_id(self):
  451. return self._replica_id
  452. @property
  453. def num_replicas(self):
  454. return self._num_replicas
  455. @property
  456. def num_ps_tasks(self):
  457. return self._num_ps_tasks
  458. @property
  459. def ps_device(self):
  460. return self._ps_device
  461. @property
  462. def worker_device(self):
  463. return self._worker_device
  464. def caching_device(self):
  465. """Returns the device to use for caching variables.
  466. Variables are cached on the worker CPU when using replicas.
  467. Returns:
  468. A device string or None if the variables do not need to be cached.
  469. """
  470. if self._num_ps_tasks > 0:
  471. return lambda op: op.device
  472. else:
  473. return None
  474. def clone_device(self, clone_index):
  475. """Device used to create the clone and all the ops inside the clone.
  476. Args:
  477. clone_index: Int, representing the clone_index.
  478. Returns:
  479. A value suitable for `tf.device()`.
  480. Raises:
  481. ValueError: if `clone_index` is greater or equal to the number of clones".
  482. """
  483. if clone_index >= self._num_clones:
  484. raise ValueError('clone_index must be less than num_clones')
  485. device = ''
  486. if self._num_ps_tasks > 0:
  487. device += self._worker_device
  488. if self._clone_on_cpu:
  489. device += '/device:CPU:0'
  490. else:
  491. if self._num_clones > 1:
  492. device += '/device:GPU:%d' % clone_index
  493. return device
  494. def clone_scope(self, clone_index):
  495. """Name scope to create the clone.
  496. Args:
  497. clone_index: Int, representing the clone_index.
  498. Returns:
  499. A name_scope suitable for `tf.name_scope()`.
  500. Raises:
  501. ValueError: if `clone_index` is greater or equal to the number of clones".
  502. """
  503. if clone_index >= self._num_clones:
  504. raise ValueError('clone_index must be less than num_clones')
  505. scope = ''
  506. if self._num_clones > 1:
  507. scope = 'clone_%d' % clone_index
  508. return scope
  509. def optimizer_device(self):
  510. """Device to use with the optimizer.
  511. Returns:
  512. A value suitable for `tf.device()`.
  513. """
  514. if self._num_ps_tasks > 0 or self._num_clones > 0:
  515. return self._worker_device + '/device:CPU:0'
  516. else:
  517. return ''
  518. def inputs_device(self):
  519. """Device to use to build the inputs.
  520. Returns:
  521. A value suitable for `tf.device()`.
  522. """
  523. device = ''
  524. if self._num_ps_tasks > 0:
  525. device += self._worker_device
  526. device += '/device:CPU:0'
  527. return device
  528. def variables_device(self):
  529. """Returns the device to use for variables created inside the clone.
  530. Returns:
  531. A value suitable for `tf.device()`.
  532. """
  533. device = ''
  534. if self._num_ps_tasks > 0:
  535. device += self._ps_device
  536. device += '/device:CPU:0'
  537. class _PSDeviceChooser(object):
  538. """Slim device chooser for variables when using PS."""
  539. def __init__(self, device, tasks):
  540. self._device = device
  541. self._tasks = tasks
  542. self._task = 0
  543. def choose(self, op):
  544. if op.device:
  545. return op.device
  546. node_def = op if isinstance(op, tf.NodeDef) else op.node_def
  547. if node_def.op == 'Variable':
  548. t = self._task
  549. self._task = (self._task + 1) % self._tasks
  550. d = '%s/task:%d' % (self._device, t)
  551. return d
  552. else:
  553. return op.device
  554. if not self._num_ps_tasks:
  555. return device
  556. else:
  557. chooser = _PSDeviceChooser(device, self._num_ps_tasks)
  558. return chooser.choose