Repository navigation
Introduce MPI allreduce and allgather in a new contrib project - #12299
Conversation
* Introduce MPI allreduce in a new contrib project. This commit adds the tensorflow.contrib.mpi namespace and contrib project, which has a variety of ops that work with MPI. The MPI system works by starting a background thread which communicates between the different processes at a regular interval and schedules asynchronous reductions. At every tick, every rank will notify rank zero of the tensors it is ready to reduce, signifying completion with an empty DONE message. Rank zero will count how many ranks are ready to reduce every tensor, and, whenever a tensor is ready to reduce (that is, every rank is ready to reduce it), rank zero will issue a message to all other ranks directing them to reduce that tensor. This repeats for all the tensors that are ready to reduce, after which rank zero sends all other ranks a DONE message indicating that the tick is complete. Reviewed-by: Joel Hestness <[email protected]> * Allreduce/Allgather: Major changes and fixes (tensorflow#2) This commit constitutes many major updates to the TF MPI allreduce and allgather ops. Specifically, the following changes are included in this commit: 1) The allreduce and allgather ops had race conditions, which this commit fixes. Specifically, the BackgroundThreadLoop previously allocated temporary and output tensors after the main graph traversal thread has completed its call to MPIAll*::ComputeAsync(). Unfortunately, the ops kernel context's memory allocator is only guaranteed to be valid during the ComputeAsync call. This constraint requires ComputeAsync to allocate all tensors before returning; Otherwise, the memory allocator state may reflect allocations and deallocations from further ops that can cause races for the memory locations. To fix this, hoist the memory allocations to ComputeAsync. In this process, introduce a collective op record, which tracks the parameters of the op (e.g. input, output, and configurations). 2) Many models require capability to allreduce or allgather int64 tensors. We add functionality to handle long long data type (64-bit ints). 3) Eliminate the thread sleep. A major to-do item is to eliminate the need for polling between coordinator threads and other ranks. This change will require the coordinator rank to be able to wake up all other ranks when a collective is ready to be performed, but also for all ranks (i.e. background threads) to be woken up by graph traversal threads. In the meantime, remove the thread sleep, because it introduces significant run time overhead (e.g. >20%) for models with quick-running layers (e.g. few recurrent time-steps or few hidden nodes per layer). * mpi_ops.cc: Move toward more TF nature This commit changes a few bits and pieces to align more closely with Tensorflow structures and organization: 1) Use TF mutexes. TF mutexes provide nice scoping and management around std::mutex, and using them is consistent with other TF code. 2) Remove thread sleep at MPI initialization time. Thread sleep should not be used for polling activity. Instead, this commit replaces sleep-polling with a condition variable: The compute graph traversal thread waits on the condition variable until the background thread has completed initialization and signals the graph traversal thread that initialization is complete. 3) Slim MPI initialization check: Since TF permits many threads to be traversing the compute graph concurrently (e.g. with inter_op_parallelism_threads > 1), some graph traversal threads may not have set their GPU device ID. If such a thread executes an MPI op, it would fail the check in InitializedMPIOnSameDevice, because the background thread would be controlling a GPU with ID other than the default (0). Since graph traversal threads do not perform GPU activity, this GPU ID check was unnecessary. Remove it and refactor to just check whether MPI is initialized (IsMPIInitialized). * Rebase to TF 1.3.0-rc1 complete and tested
* Introduce MPI allreduce in a new contrib project. This commit adds the tensorflow.contrib.mpi namespace and contrib project, which has a variety of ops that work with MPI. The MPI system works by starting a background thread which communicates between the different processes at a regular interval and schedules asynchronous reductions. At every tick, every rank will notify rank zero of the tensors it is ready to reduce, signifying completion with an empty DONE message. Rank zero will count how many ranks are ready to reduce every tensor, and, whenever a tensor is ready to reduce (that is, every rank is ready to reduce it), rank zero will issue a message to all other ranks directing them to reduce that tensor. This repeats for all the tensors that are ready to reduce, after which rank zero sends all other ranks a DONE message indicating that the tick is complete. Reviewed-by: Joel Hestness <[email protected]> * Allreduce/Allgather: Major changes and fixes (tensorflow#2) This commit constitutes many major updates to the TF MPI allreduce and allgather ops. Specifically, the following changes are included in this commit: 1) The allreduce and allgather ops had race conditions, which this commit fixes. Specifically, the BackgroundThreadLoop previously allocated temporary and output tensors after the main graph traversal thread has completed its call to MPIAll*::ComputeAsync(). Unfortunately, the ops kernel context's memory allocator is only guaranteed to be valid during the ComputeAsync call. This constraint requires ComputeAsync to allocate all tensors before returning; Otherwise, the memory allocator state may reflect allocations and deallocations from further ops that can cause races for the memory locations. To fix this, hoist the memory allocations to ComputeAsync. In this process, introduce a collective op record, which tracks the parameters of the op (e.g. input, output, and configurations). 2) Many models require capability to allreduce or allgather int64 tensors. We add functionality to handle long long data type (64-bit ints). 3) Eliminate the thread sleep. A major to-do item is to eliminate the need for polling between coordinator threads and other ranks. This change will require the coordinator rank to be able to wake up all other ranks when a collective is ready to be performed, but also for all ranks (i.e. background threads) to be woken up by graph traversal threads. In the meantime, remove the thread sleep, because it introduces significant run time overhead (e.g. >20%) for models with quick-running layers (e.g. few recurrent time-steps or few hidden nodes per layer). * mpi_ops.cc: Move toward more TF nature This commit changes a few bits and pieces to align more closely with Tensorflow structures and organization: 1) Use TF mutexes. TF mutexes provide nice scoping and management around std::mutex, and using them is consistent with other TF code. 2) Remove thread sleep at MPI initialization time. Thread sleep should not be used for polling activity. Instead, this commit replaces sleep-polling with a condition variable: The compute graph traversal thread waits on the condition variable until the background thread has completed initialization and signals the graph traversal thread that initialization is complete. 3) Slim MPI initialization check: Since TF permits many threads to be traversing the compute graph concurrently (e.g. with inter_op_parallelism_threads > 1), some graph traversal threads may not have set their GPU device ID. If such a thread executes an MPI op, it would fail the check in InitializedMPIOnSameDevice, because the background thread would be controlling a GPU with ID other than the default (0). Since graph traversal threads do not perform GPU activity, this GPU ID check was unnecessary. Remove it and refactor to just check whether MPI is initialized (IsMPIInitialized). * Rebase to TF 1.3.0-rc1 complete and tested
…ail.baidu.com/baidu-research/tensorflow into dev_baidu_allreduce_tf-v1.3.0-rc1 Conflicts: tensorflow/contrib/mpi_collectives/mpi_message.proto tensorflow/contrib/mpi_collectives/mpi_ops_test.py
…ail.baidu.com/baidu-research/tensorflow into dev_baidu_allreduce_tf-v1.3.0-rc1 Conflicts: tensorflow/contrib/mpi_collectives/mpi_message.proto tensorflow/contrib/mpi_collectives/mpi_ops_test.py
|
Can one of the admins verify this patch? |
|
We found a Contributor License Agreement for you (the sender of this pull request), but were unable to find agreements for the commit author(s). If you authored these, maybe you used a different email address in the git commits than was used to sign the CLA (login here to double check)? If these were authored by someone else, then they will need to sign a CLA as well, and confirm that they're okay with these being contributed to Google. |
|
PR submitted from Baidu Silicon Valley AI Lab (SVAIL) |
|
CLAs look good, thanks! |
|
@jthestness FYI - we made derivative work based on your original https://github.com/baidu-research/tensorflow-allreduce called Horovod: https://github.com/uber/horovod. It's a plugin that installs on top of TensorFlow, so you can We made number of usability improvements and integrated NCCL 2 support, which makes it easier to use and it performs faster. We've also added special Horovod Timeline that aids debugging of overall distributed training. Now we're working on further optimisation techniques to gain further speed-up on networks with many tiny elements like |
poxvoculi
left a comment
There was a problem hiding this comment.
Sorry this took so long; I was on vacation. Overall this looks really good. I've got a few minor observations, but should be mergeable as it.
| out_size = batch_size | ||
|
|
||
| # Input placeholder (batch_size x hidden) - init to 1s | ||
| inputs = tf.placeholder(tf.float32, shape=(batch_size, hidden_size), |
There was a problem hiding this comment.
Is there a test for IndexedSlices?
There was a problem hiding this comment.
We have only used internal RNN models to verify correctness of the allgather on IndexedSlices rather than unit tests. I'll create a test if you prefer.
There was a problem hiding this comment.
Up to you, but at least one small test seems appropriate.
There was a problem hiding this comment.
Added an Allgather test that runs correctly on our systems
| if isinstance(tensor, tf.IndexedSlices): | ||
| # For IndexedSlices, do two allgathers intead of an allreduce. | ||
| mpi_size = tf.cast(size(), tensor.values.dtype) | ||
| values = allgather(tensor.values) |
There was a problem hiding this comment.
If the IndexedSlices are index-disjoint, this looks correct, but what happens in case of a common index?
There was a problem hiding this comment.
IndexedSlices tensors are allowed to have repeated indices, so gathering and concatting IndexedSlices together without any reduction or index merging still creates a valid IndexedSlices tensor. For weight updates during backprop, a gradient tensor can be IndexedSlices with repeated indices, so we can call apply_gradients with such a tensor.
There is a question about whether this organization is an appropriate design for the interface. A user might (reasonably) assume that the returned IndexedSlices tensor should have unique indices.
I'm happy to discuss appropriate organization, and as necessary, adjust the code or add comments.
There was a problem hiding this comment.
I wasn't familiar with IndexedSlices; if repeated indices are ok, then this is fine.
| // We would like to just use DataType here, but since this | ||
| // is a contrib package, linking directly to TensorFlow protos seems to be | ||
| // impossible. Doing so compiles, but fails with a cryptic error at runtime | ||
| // about a pointer that was passed to free() but not created by malloc(). |
There was a problem hiding this comment.
This happens when linking to "//third_party/tensorflow/core:protos_all_py_pb2" or "//third_party/tensorflow/core:protos_all"?
OK to submit as you have it, but we may be able to work out the problem with more details.
There was a problem hiding this comment.
I was able to fix the linking against other protos, so I removed the MPIDataType in favor of the TF DataType proto.
| @@ -0,0 +1,1275 @@ | |||
| // Copyright 2016 The TensorFlow Authors. All Rights Reserved. | |||
There was a problem hiding this comment.
Maybe change 2016 to 2017 everywhere?
|
Nice work! Sorry to be off-topic, but what happened to @gibiansky? Is he still in Baidu SVAIL? |
|
@byronyi I am still here! I've been working with @jthestness to get this together (well, mostly @jthestness has been working, and I've been offering the occasional useful advice :P). (Hasn't been my primary project as I got distracted with other things while we were working on getting the CLA signed.) |
|
Jenkins, test this please. |
|
Are the failing tests issues with this PR? I took a look at the console logs from them, and couldn't find anything that looked like a failure due to the MPI allreduce. |
|
Jenkins, test this please. |
|
Yeah, |
|
Jenkins, test this please. |
|
Windows build appears to have come back online. Jenkins, test this please. |
|
Jenkins, test this please. |
|
Something wrong with the CLA bot. Let's wait a bit. |
Hopefully, this will trigger googlebot.
|
OK, now the CLA looks good. Jenkins, test this please. |
|
Jenkins, test this please. (stuck) |
|
Thanks Joel for the amazing contribution! |
|
Very nice. |
|
This is great, thanks for the contribution. I was wondering, what is your take on https://github.com/uber/horovod? |
|
Impressive work! A few questions to setup my env, pls kindly help: thanks a lot.
|
|
@alexwal : We haven't tested Horovod, but the Uber team claims it performs better than this MPI allreduce. We have recently tested NCCL 2.0 (i.e. what Horovod uses) for intra-node communication outside of Tensorflow, and it performs a bit better than the MPI ring allreduce. We have some analysis about the differences that we will be releasing in the near future. @Zhaojp-Frank : (1) Tensorflow supports intra-node communication, and you can use that for data parallelism if you'd like. It cannot currently scale to inter-node communication without a collectives package such as this MPI collectives. Tensorflow's intra-node communication requires that you use a single process to manage all GPUs, while inter-node communication requires at least one process on each separate node. Because of these differences, the programming model can be very different. If you plan to scale to multiple nodes, we recommend that you start with collectives that will scale to multiple nodes rather than trying to retrofit that code later. (2) This MPI collectives package doesn't use NCCL. |
|
@jthestness thanks a lot. does the implementation also overlap AllReduce communication and next layer gradient computing? |
|
Why is an allreduce manually implemented using point to point communications rather than using the likely much more optimized allreduce present in MPI? Do you have a specific reason for doing it yourself? Vendor MPI implementations like cray-mpich can use hardware support for collective communications and take advantage of tightly interconnected networks and don't load a single node with scheduling concerns. A ring allreduce has an abysmal performance in comparison on such networks, especially at scale (thousands of nodes). It would also take a lot less code to just |
|
Short version: The allreduce present in MPI -- that is, non-vendor MPI implementations -- is not CUDA-aware, and thus copies memory to CPU before doing the collective. The ring allreduce is much more efficient when doing multi-node multi-GPU training than the default collective. When writing this package, we were optimizing for commodity hardware (possibly with Infiniband for multi-node connections) on CPUs and GPUs, which describes the majority of large DL applications. At the time of writing, most MPI implementations (that is, all that I checked) did not support direct GPU-to-GPU transfers in their collectives; however, at least Open MPI supported the simpler operations using direct GPU-to-GPU transfers and CUDA IPC. If you used However, as you mention, this code is certainly not optimal for all MPI implementations and network topologies. Additionally, nowadays NCCL supports (or claims to support) multi-node communication, although I haven't had the time to check how well it works or how it performs its collectives (and whether they correctly handle GPU to GPU transfers over infiniband). If you have access to a thousand node cluster and want to switch out the allreduce for the default vendor one, would be really cool to see what sort of things you could do :) |
|
FYI: core TensorFlow now has collective all-reduce and broadcast, though not yet part of the official API. The strategic intention is that users should use the new distribution strategies framework to specify data-parallel distribution, and that framework will utilize collectives as appropriate. The default implementation of collectives uses RPCs over gRPC so the performance is not great, compared to MPI/ib. However, MPI is not available everywhere. Going forward we plan to investigate introducing an API that makes it possible to link in MPI collectives where available and get platform-customized implementations, e.g. for a supercomputer. |
|
Ah, I see. That makes sense. Unfortunately, our hardware is old and doesn't support true cuda aware MPI. We have 4,228 GPU nodes, each with a Tesla K20X, networked in a 3d torus. Each node isn't very fast, but we make up for it by having a lot of them (there's an additional 22,636 CPU nodes, but those aren't too useful for ML). It means having applications that can scale well, though, and getting Tensorflow to do so well has been painful. Cray has a Tensorflow ML plugin written specifically for their interconnects, but it's a bit finicky on our system and they don't really want to invest much effort in our older model system (It makes sense, but it's a struggle for me). So, I'm constantly on the look out for things to try and make Tensorflow scale better. We only recently upgraded from CUDA 7.5 to CUDA 9.1, so we were stuck on Tensorflow 1.4.1 for a long time, but now I'm back to investigating it. Have you tried doing a local intermediate reduction within the gpus on each node, then ireducing that? We only have one gpu per node, so it's not something I can test. Perhaps I'll have to write an HPC-orriented plugin of my own, since most are one gpu per node with larger node counts as opposed to high-gpu-count ML clusters like what you're targeting. Or perhaps there could be choices between allreduce methods to help support a broader range of hardware configurations. Good to know. I just hope the CUDA requirements don't evolve too fast to prevent us from upgrading when that feature is ready. As I mentioned above, we only just recently moved from CUDA 7.5 to CUDA 9.1, and CUDA 9.1 is all we will get until the end of the machine's life (probably the end of 2019). HPC system software tends to be updated more slowly than Tensorflow's dependencies since everything needs to be well tested, which I know has been an issue for other centers, as well. A lot of our users want the latest and greatest Tensorflow, but actually getting it running and performing well was the topic of a number of papers at this year's Cray User Group conference. I know HPC is only a small fraction of total users, but I'm glad you're adjusting the API to make it easier to run well on our big systems. |
|
@camaclean That's really cool! That said, getting a model to train well on that giant set of nodes seems like a pretty big challenge... With regards to the intermediate reduction: since we were operating within a single infiniband switch, a ring allreduce meant that we were just bandwidth limited between adjacent nodes in the allreduce. We would do 8-10 GPUs on a single machine and then have up to 10-30 nodes at most. So the only thing we tried besides the ring was a few special cases for when reducing small tensors (where latency dominates bandwidth). (Getting an efficient synchronous gradient update on a setup that big seems very tricky. Additionally, even if you do, your batch size will be enormous... if you're training standard deep learning models you'll have to throw a bunch of tricks at it to get it to optimize well with that many elements in the batch. Maybe a (partially?) asynchronous training strategy is more feasible?) |
|
For some reason, getting things to scale on Blue Waters has been harder than what I've seen from other centers. Last time we were benchmarking we were having trouble with crashes and such. Pytorch was much easier to get scaling well since it can use MPI's allreduce under the hood. Our network is a 3d torus with 2 nodes sharing an interconnect, which can do 2.9GB/s (effective) for each of the 6 directions and intelligently route packets along several links if there's bandwidth available. It also has hardware support for doing collective type operations to efficiently scatter data. Based on profiling counters on the interconnects, we haven't been able to come close to saturating our network bandwidth. Our biggest bottleneck seems to be more a matter of latency. |
|
Is there a complete training code example with ring allreduce implemented or a document about refactoring code with ring allreduce? |
|
@snowpeakz At this point, I would recommend using Horovod, which is based on this code but improves it and has pretty good documentation. |
|
@gibiansky thanks for recommendation |
|
@gibiansky If the number of worker is large than 12, the cmd |
|
@snowpeakz no idea I'm afraid. |
Do you use mpiexec to run your code? |
This commit adds the tensorflow.contrib.mpi_collectives namespace and
contrib project, which has a variety of ops that work with MPI.
The MPI system works by starting a background thread which communicates
between the different processes at a regular interval and schedules
asynchronous reductions. At every tick, every rank will notify rank zero
of the tensors it is ready to reduce, signifying completion with an
empty DONE message. Rank zero will count how many ranks are ready to
reduce every tensor, and, whenever a tensor is ready to reduce (that is,
every rank is ready to reduce it), rank zero will issue a message to all
other ranks directing them to reduce that tensor. This repeats for all
the tensors that are ready to reduce, after which rank zero sends all
other ranks a DONE message indicating that the tick is complete.
Authors: Andrew Gibiansky [email protected]
Joel Hestness [email protected]