distribution_utils.py 9.32 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Helper functions for running models in a distributed setting."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

21
22
import json
import os
23
24
import random
import string
25
26
import tensorflow as tf

27
28
29
30
31
32
_COLLECTIVE_COMMUNICATION_OPTIONS = {
    None: tf.distribute.experimental.CollectiveCommunication.AUTO,
    "ring": tf.distribute.experimental.CollectiveCommunication.RING,
    "nccl": tf.distribute.experimental.CollectiveCommunication.NCCL
}

33

34
35
def get_distribution_strategy(distribution_strategy="default",
                              num_gpus=0,
36
                              num_workers=1,
37
                              all_reduce_alg=None):
38
39
40
  """Return a DistributionStrategy for running the model.

  Args:
41
42
    distribution_strategy: a string specify which distribution strategy to use.
      Accepted values are 'off', 'default', 'one_device', 'mirrored',
43
44
45
46
      'parameter_server', 'multi_worker_mirrored', case insensitive. 'off' means
      not to use Distribution Strategy; 'default' means to choose from
      `MirroredStrategy`, `MultiWorkerMirroredStrategy`, or `OneDeviceStrategy`
      according to the number of GPUs and number of workers.
47
    num_gpus: Number of GPUs to run this model.
48
    num_workers: Number of workers to run this model.
49
50
    all_reduce_alg: Optional. Specify which algorithm to use when performing
      all-reduce. See tf.contrib.distribute.AllReduceCrossDeviceOps for
51
52
53
54
      available algorithms when used with `mirrored`, and
      tf.distribute.experimental.CollectiveCommunication when used with
      `multi_worker_mirrored`. If None, DistributionStrategy will choose based
      on device topology.
55
56

  Returns:
57
    tf.distribute.DistibutionStrategy object.
Shining Sun's avatar
Shining Sun committed
58
  Raises:
59
60
    ValueError: if `distribution_strategy` is 'off' or 'one_device' and
      `num_gpus` is larger than 1; or `num_gpus` is negative.
61
  """
62
63
64
65
66
  if num_gpus < 0:
    raise ValueError("`num_gpus` can not be negative.")

  distribution_strategy = distribution_strategy.lower()
  if distribution_strategy == "off":
67
68
69
70
    if num_gpus > 1 or num_workers > 1:
      raise ValueError(
          "When {} GPUs and  {} workers are specified, distribution_strategy "
          "flag cannot be set to 'off'.".format(num_gpus, num_workers))
71
72
    return None

73
  if distribution_strategy == "multi_worker_mirrored" or num_workers > 1:
74
75
76
77
78
79
80
    if all_reduce_alg not in _COLLECTIVE_COMMUNICATION_OPTIONS:
      raise ValueError(
          "When used with `multi_worker_mirrored`, valid values for "
          "all_reduce_alg are [`ring`, `nccl`].  Supplied value: {}".format(
              all_reduce_alg))
    return tf.distribute.experimental.MultiWorkerMirroredStrategy(
        communication=_COLLECTIVE_COMMUNICATION_OPTIONS[all_reduce_alg])
81

82
83
84
  if (distribution_strategy == "one_device" or
      (distribution_strategy == "default" and num_gpus <= 1)):
    if num_gpus == 0:
Toby Boyd's avatar
Toby Boyd committed
85
      return tf.distribute.OneDeviceStrategy("device:CPU:0")
Toby Boyd's avatar
Toby Boyd committed
86
    else:
87
88
89
      if num_gpus > 1:
        raise ValueError("`OneDeviceStrategy` can not be used for more than "
                         "one device.")
Toby Boyd's avatar
Toby Boyd committed
90
      return tf.distribute.OneDeviceStrategy("device:GPU:0")
91
92
93
94
95

  if distribution_strategy in ("mirrored", "default"):
    if num_gpus == 0:
      assert distribution_strategy == "mirrored"
      devices = ["device:CPU:0"]
Shining Sun's avatar
Shining Sun committed
96
    else:
97
      devices = ["device:GPU:%d" % i for i in range(num_gpus)]
98
    if all_reduce_alg:
99
100
      return tf.distribute.MirroredStrategy(
          devices=devices,
101
          cross_device_ops=tf.contrib.distribute.AllReduceCrossDeviceOps(
102
              all_reduce_alg, num_packs=2))
103
    else:
104
      return tf.distribute.MirroredStrategy(devices=devices)
105

106
  if distribution_strategy == "parameter_server":
107
    return tf.distribute.experimental.ParameterServerStrategy()
108
109
110
111

  raise ValueError(
      "Unrecognized Distribution Strategy: %r" % distribution_strategy)

112
113
114
115

def per_device_batch_size(batch_size, num_gpus):
  """For multi-gpu, batch-size must be a multiple of the number of GPUs.

116
117
118

  Note that distribution strategy handles this automatically when used with
  Keras. For using with Estimator, we need to get per GPU batch.
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135

  Args:
    batch_size: Global batch size to be divided among devices. This should be
      equal to num_gpus times the single-GPU batch_size for multi-gpu training.
    num_gpus: How many GPUs are used with DistributionStrategies.

  Returns:
    Batch size per device.

  Raises:
    ValueError: if batch_size is not divisible by number of devices
  """
  if num_gpus <= 1:
    return batch_size

  remainder = batch_size % num_gpus
  if remainder:
Toby Boyd's avatar
Toby Boyd committed
136
137
138
    err = ('When running with multiple GPUs, batch size '
           'must be a multiple of the number of available GPUs. Found {} '
           'GPUs with a batch size of {}; try --batch_size={} instead.'
139
140
141
          ).format(num_gpus, batch_size, batch_size - remainder)
    raise ValueError(err)
  return int(batch_size / num_gpus)
142

Toby Boyd's avatar
Toby Boyd committed
143

144
145
146
147
148
149
150
151
152
153
# The `SyntheticDataset` is a temporary solution for generating synthetic data
# directly on devices. It is only useful for Keras with Distribution
# Strategies. We will have better support in `tf.data` or Distribution Strategy
# later.
class SyntheticDataset(object):
  """A dataset that generates synthetic data on each device."""

  def __init__(self, dataset, split_by=1):
    self._input_data = {}
    # dataset.take(1) doesn't have GPU kernel.
Toby Boyd's avatar
Toby Boyd committed
154
    with tf.device('device:CPU:0'):
155
156
157
158
159
160
161
      tensor = tf.data.experimental.get_single_element(dataset.take(1))
    flat_tensor = tf.nest.flatten(tensor)
    variable_data = []
    self._initializers = []
    for t in flat_tensor:
      rebatched_t = tf.split(t, num_or_size_splits=split_by, axis=0)[0]
      assert rebatched_t.shape.is_fully_defined(), rebatched_t.shape
Toby Boyd's avatar
Toby Boyd committed
162
163
      v = tf.compat.v1.get_local_variable(self.random_name(),
                                          initializer=rebatched_t)
164
165
166
167
168
169
170
171
172
173
174
175
176
177
      variable_data.append(v)
      self._initializers.append(v.initializer)
    self._input_data = tf.nest.pack_sequence_as(tensor, variable_data)

  def get_next(self):
    return self._input_data

  def initialize(self):
    if tf.executing_eagerly():
      return tf.no_op()
    else:
      return self._initializers

  def random_name(self, size=10, chars=string.ascii_uppercase + string.digits):
Toby Boyd's avatar
Toby Boyd committed
178
    return ''.join(random.choice(chars) for _ in range(size))
179
180
181
182
183


def _monkey_patch_dataset_method(strategy):
  """Monkey-patch `strategy`'s `make_dataset_iterator` method."""
  def make_dataset_iterator(self, dataset):
Toby Boyd's avatar
Toby Boyd committed
184
    tf.compat.v1.logging.info('Using pure synthetic data.')
185
186
187
188
189
190
191
192
193
194
195
    with self.scope():
      if self.extended._global_batch_size:  # pylint: disable=protected-access
        return SyntheticDataset(dataset, self.num_replicas_in_sync)
      else:
        return SyntheticDataset(dataset)

  strategy.org_make_dataset_iterator = strategy.make_dataset_iterator
  strategy.make_dataset_iterator = make_dataset_iterator


def _undo_monkey_patch_dataset_method(strategy):
Toby Boyd's avatar
Toby Boyd committed
196
  if hasattr(strategy, 'org_make_dataset_iterator'):
197
198
199
200
201
    strategy.make_dataset_iterator = strategy.org_make_dataset_iterator


def set_up_synthetic_data():
  _monkey_patch_dataset_method(tf.distribute.MirroredStrategy)
Toby Boyd's avatar
Toby Boyd committed
202
203
204
205
206
207
  # TODO(tobyboyd): Remove when contrib.distribute is all in core.
  if hasattr(tf, 'contrib'):
    _monkey_patch_dataset_method(tf.contrib.distribute.MirroredStrategy)
    _monkey_patch_dataset_method(tf.contrib.distribute.OneDeviceStrategy)
  else:
    print('Contrib missing: Skip monkey patch tf.contrib.distribute.*')
208
209
210
211


def undo_set_up_synthetic_data():
  _undo_monkey_patch_dataset_method(tf.distribute.MirroredStrategy)
Toby Boyd's avatar
Toby Boyd committed
212
213
214
215
216
217
  # TODO(tobyboyd): Remove when contrib.distribute is all in core.
  if hasattr(tf, 'contrib'):
    _undo_monkey_patch_dataset_method(tf.contrib.distribute.MirroredStrategy)
    _undo_monkey_patch_dataset_method(tf.contrib.distribute.OneDeviceStrategy)
  else:
    print('Contrib missing: Skip remove monkey patch tf.contrib.distribute.*')
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246


def configure_cluster(worker_hosts=None, task_index=-1):
  """Set multi-worker cluster spec in TF_CONFIG environment variable.

  Args:
    worker_hosts: comma-separated list of worker ip:port pairs.

  Returns:
    Number of workers in the cluster.
  """
  tf_config = json.loads(os.environ.get('TF_CONFIG', '{}'))
  if tf_config:
    num_workers = len(tf_config['cluster']['worker'])
  elif worker_hosts:
    workers = worker_hosts.split(',')
    num_workers = len(workers)
    if num_workers > 1 and task_index < 0:
      raise ValueError('Must specify task_index when number of workers > 1')
    task_index = 0 if num_workers == 1 else task_index
    os.environ['TF_CONFIG'] = json.dumps({
        'cluster': {
            'worker': workers
        },
        'task': {'type': 'worker', 'index': task_index}
    })
  else:
    num_workers = 1
  return num_workers