aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/contrib/nccl/python/ops/nccl_ops_test.py
blob: bad0abd44cc507c6ebbe4481f80b8cafd8480322 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
# Copyright 2016 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.
# ==============================================================================
"""Tests for nccl ops. See also the cc test for nccl_communicator."""

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

from functools import partial
import numpy as np

from tensorflow.contrib import nccl
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gradients
from tensorflow.python.platform import test


def _DeviceTensors(tensors, devices):
  res = []
  for t, d in zip(tensors, devices):
    with ops.device(d):
      res.append(array_ops.identity(t))
  return res


def _NcclAllReduce(nccl_fun, tensors, devices):
  return nccl_fun(_DeviceTensors(tensors, devices))


def _NcclReduce(nccl_fun, tensors, devices):
  receiver = np.random.randint(0, len(devices))
  with ops.device(devices[receiver]):
    return [nccl_fun(_DeviceTensors(tensors, devices))]


def _NcclBroadcast(tensors, devices):
  sender = np.random.randint(0, len(devices))
  with ops.device(devices[sender]):
    tensor = array_ops.identity(tensors[0])
    broadcast = nccl.broadcast(tensor)
  return _DeviceTensors([broadcast] * len(devices), devices)


class NcclTestCase(test.TestCase):

  def _Test(self,
            nccl_reduce,
            numpy_fn,
            device_sets=(['/device:GPU:1', '/device:GPU:2', '/device:GPU:0'],
                         ['/device:GPU:1', '/device:GPU:0'])):
    """Tests that nccl_reduce does the same as reduction with numpy_fn.

    Args:
      nccl_reduce: A function taking a list of tensors and a list of devices,
          and returns a list of reduced tensors and a list of ops to perform the
          reduction.
      numpy_fn: A function taking two tensors and returning the reduction of the
          two.
      device_sets: Tuple of virtual devices to run test on.
    """
    for dtype in [np.float32, np.int32, np.int64, np.float64]:
      # Create session inside outer loop to test use of
      # same communicator across multiple sessions.
      with self.test_session(use_gpu=True) as sess:

        # Check GPU availability *after* creating test session, see b/68975239.
        if not test.is_gpu_available():
          return  # Test requires access to a GPU

        for devices in device_sets:
          shape = (3, 4)
          random = (np.random.random_sample(shape) - .5) * 1024
          tensors = []
          for _ in devices:
            tensors.append(random.astype(dtype))
          np_ans = tensors[0]
          for t in tensors[1:]:
            np_ans = numpy_fn(np_ans, t)

          reduce_tensors = nccl_reduce(tensors, devices)
          self.assertNotEmpty(reduce_tensors)

          # Test shape inference.
          for r in reduce_tensors:
            self.assertEqual(shape, r.get_shape())

          result_tensors = [array_ops.identity(t) for t in reduce_tensors]

          # Test execution and results.
          for t in sess.run(result_tensors):
            self.assertAllClose(t, np_ans)

  def _TestGradient(self, nccl_reduce, numpy_fn):
    """Tests the gradient of nccl_reduce.

    Args:
      nccl_reduce: A function taking a list of tensors and a list of devices,
          and returns a list of reduced tensors and a list of ops to perform the
          reduction.
      numpy_fn: A function taking two tensors and returning the gradient of the
          reduction of the two.
    """
    def _Gradient(tensors, devices):
      inputs = [array_ops.placeholder(t.dtype, t.shape) for t in tensors]
      reduce_tensors = nccl_reduce(inputs, devices)
      losses = _DeviceTensors(tensors, [t.device for t in reduce_tensors])
      grads = gradients.gradients(
          reduce_tensors, inputs, losses, colocate_gradients_with_ops=True)
      return [g for g in grads if g is not None]

    self._Test(_Gradient, numpy_fn)


class AllReduceTest(NcclTestCase):

  def testAllReduce(self):
    self._Test(partial(_NcclAllReduce, nccl.all_sum), lambda x, y: x + y)
    self._Test(partial(_NcclAllReduce, nccl.all_prod), lambda x, y: x * y)
    self._Test(partial(_NcclAllReduce, nccl.all_min), np.minimum)
    self._Test(partial(_NcclAllReduce, nccl.all_max), np.maximum)

  def testAllSumGrad(self):
    self._TestGradient(
        partial(_NcclAllReduce, nccl.all_sum), lambda x, y: x + y)

  def testErrors(self):
    with self.assertRaisesRegexp(ValueError, 'Device assignment required'):
      nccl.all_sum([array_ops.identity(np.random.random_sample((3, 4)))])
    with self.assertRaisesRegexp(ValueError, 'Must pass >0 tensors'):
      nccl.all_sum([])


class SingleReduceTest(NcclTestCase):

  def testSum(self):
    self._Test(partial(_NcclReduce, nccl.reduce_sum), lambda x, y: x + y)

  def testSumGrad(self):
    self._TestGradient(partial(_NcclReduce, nccl.reduce_sum), lambda x, y: x)


class BroadcastTest(NcclTestCase):

  def testBroadcast(self):
    self._Test(_NcclBroadcast, lambda x, y: x)

  def testBroadcastSingleDevice(self):
    # Broadcasts on a single device are removed completely during rewrite.
    self._Test(_NcclBroadcast, lambda x, y: x,
               (['/device:GPU:0', '/device:GPU:0'],))

  def testBroadcastToCpuError(self):
    # Broadcasts to CPU is not supported.
    with self.assertRaisesRegexp(
        errors.NotFoundError,
        "No registered '_NcclBroadcastRecv' OpKernel for CPU devices"):
      self._Test(_NcclBroadcast, lambda x, y: x,
                 (['/device:GPU:0', '/device:CPU:0'],))


class CombinedTest(NcclTestCase):
  """Test all-reduce vs. single-reduce plus broadcast in one session.run."""

  def _Combined(self, tensors, devices):
    all_reduce_tensors = _NcclAllReduce(nccl.all_sum, tensors, devices)
    single_reduce_tensors = _NcclReduce(nccl.reduce_sum, tensors, devices)
    broadcast_tensors = _NcclBroadcast(single_reduce_tensors, devices)
    return all_reduce_tensors + broadcast_tensors

  def testCombined(self):
    self._Test(self._Combined, lambda x, y: x + y)


if __name__ == '__main__':
  test.main()