aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/contrib/mpi_collectives/mpi_ops.py
blob: bd7096d9cee2d32bde5227a95038ae65cd8a6e18 (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
# Copyright 2017 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.
# =============================================================================
"""Inter-process communication using MPI."""

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

import tensorflow as tf

from tensorflow.python.framework import errors
from tensorflow.python.framework import load_library
from tensorflow.python.framework import ops
from tensorflow.python.platform import resource_loader
from tensorflow.python.platform import tf_logging as logging


def _load_library(name, op_list=None):
  """Loads a .so file containing the specified operators.

  Args:
    name: The name of the .so file to load.
    op_list: A list of names of operators that the library should have. If None
        then the .so file's contents will not be verified.

  Raises:
    NameError if one of the required ops is missing.
  """
  try:
    filename = resource_loader.get_path_to_datafile(name)
    library = load_library.load_op_library(filename)
    for expected_op in (op_list or []):
      for lib_op in library.OP_LIST.op:
        if lib_op.name == expected_op:
          break
      else:
        raise NameError('Could not find operator %s in dynamic library %s' %
                        (expected_op, name))
    return library
  except errors.NotFoundError:
    logging.warning('%s file could not be loaded.', name)


MPI_LIB = _load_library(
    'mpi_collectives.so',
    ['MPISize', 'MPIRank', 'MPILocalRank', 'MPIAllgather', 'MPIAllreduce'])


def size(name=None):
  """An op which returns the number of MPI processes.

  This is equivalent to running `MPI_Comm_size(MPI_COMM_WORLD, ...)` to get the
  size of the global communicator.

  Returns:
    An integer scalar containing the number of MPI processes.
  """
  return MPI_LIB.mpi_size(name=name)


ops.NotDifferentiable('MPISize')


def rank(name=None):
  """An op which returns the MPI rank of the calling process.

  This is equivalent to running `MPI_Comm_rank(MPI_COMM_WORLD, ...)` to get the
  rank of the current process in the global communicator.

  Returns:
    An integer scalar with the MPI rank of the calling process.
  """
  return MPI_LIB.mpi_rank(name=name)


ops.NotDifferentiable('MPIRank')


def init(name=None):
  """An op which initializes MPI on the device on which it is run.

  All future MPI ops must be run on the same device that the `init` op was run
  on.
  """
  return MPI_LIB.mpi_init(name=name)


ops.NotDifferentiable('MPIInit')


def local_rank(name=None):
  """An op which returns the local MPI rank of the calling process, within the
  node that it is running on. For example, if there are seven processes running
  on a node, their local ranks will be zero through six, inclusive.

  This is equivalent to running `MPI_Comm_rank(...)` on a new communicator
  which only includes processes on the same node.

  Returns:
    An integer scalar with the local MPI rank of the calling process.
  """
  return MPI_LIB.mpi_local_rank(name=name)


ops.NotDifferentiable('MPILocalRank')


def _allreduce(tensor, name=None):
  """An op which sums an input tensor over all the MPI processes.

  The reduction operation is keyed by the name of the op. The tensor type and
  shape must be the same on all MPI processes for a given name. The reduction
  will not start until all processes are ready to send and receive the tensor.

  Returns:
    A tensor of the same shape and type as `tensor`, summed across all
    processes.
  """
  return MPI_LIB.mpi_allreduce(tensor, name=name)


ops.NotDifferentiable('MPIAllreduce')


def allgather(tensor, name=None):
  """An op which concatenates the input tensor with the same input tensor on
  all other MPI processes.

  The concatenation is done on the first dimension, so the input tensors on the
  different processes must have the same rank and shape, except for the first
  dimension, which is allowed to be different.

  Returns:
    A tensor of the same type as `tensor`, concatenated on dimension zero
    across all processes. The shape is identical to the input shape, except for
    the first dimension, which may be greater and is the sum of all first
    dimensions of the tensors in different MPI processes.
  """
  # Specify that first allgather is to collect the tensor gather sizes,
  # indicated by passing in a scalar (0-D tensor) of value 0
  sizes_flag = tf.constant(0, dtype=tf.int64, name='size_flag_const')
  my_size = tf.slice(
      tf.shape(tensor, out_type=tf.int64), [0], [1], name='size_slice')
  if name is None:
    name = 'allgather'
  sizing_name = '{}_sizing'.format(name)
  sizes = MPI_LIB.mpi_allgather(my_size, sizes_flag, name=sizing_name)
  return MPI_LIB.mpi_allgather(tensor, sizes, name=name)


ops.NotDifferentiable('MPIAllgather')