This is an automated email from the ASF dual-hosted git repository.
tqchen pushed a commit to branch unity
in repository https://gitbox.apache.org/repos/asf/tvm.git
The following commit(s) were added to refs/heads/unity by this push:
new c2eaa1d370 [Disco] Add `Scatter-From-Worker0` (#15653)
c2eaa1d370 is described below
commit c2eaa1d370b48a44494c0eacab95480868b329bd
Author: Junru Shao <[email protected]>
AuthorDate: Sat Sep 2 04:10:39 2023 -0700
[Disco] Add `Scatter-From-Worker0` (#15653)
* [Runtime] ShapeTuple.Product and ShapeTuple Printing (#15652)
This PR adds two convenient methods for `ShapeTuple`.
```C++
// Returns the number of elements in the shape,
// i.e. the product of all dimensions
ShapeTupleObj::index_type ShapeTupleObj::Product();
// Printing method for shape
std::ostream& operator<<(std::ostream& os, const ShapeTuple& shape);
```
* [Disco] Add `Scatter-From-Worker0`
This PR introduces an API:
```C++
void ScatterFromWorker0(Optional<NDArray> send, NDArray recv);
```
This mimics the MPI-style scattering primitive that divides NDArray
`send` into chunks, and send them to each worker's NDArray `recv`.
---
python/tvm/runtime/disco/session.py | 17 +++-
src/runtime/disco/builtin.cc | 80 +++++++++---------
src/runtime/disco/builtin.h | 80 ++++++++++++++++++
src/runtime/disco/nccl/nccl.cc | 161 +++++++++++++++++++++++-------------
tests/python/disco/test_nccl.py | 24 ++++++
5 files changed, 265 insertions(+), 97 deletions(-)
diff --git a/python/tvm/runtime/disco/session.py
b/python/tvm/runtime/disco/session.py
index 587704fe28..21c38a41ac 100644
--- a/python/tvm/runtime/disco/session.py
+++ b/python/tvm/runtime/disco/session.py
@@ -139,7 +139,7 @@ class Session(Object):
if device is None:
device = Device(device_type=0, device_id=0)
func = self._get_cached_method("runtime.disco.empty")
- return func(*shape, dtype, device)
+ return func(ShapeTuple(shape), dtype, device)
def get_global_func(self, name: str) -> DRef:
"""Get a global function on workers.
@@ -264,7 +264,7 @@ class Session(Object):
The arguments to be passed to the initialization function of the
communication
"""
assert api in ("nccl", "rccl"), f"Unsupported CCL backend: {api}"
- func = self.get_global_func(f"runtime.disco.{api}.init")
+ func = self.get_global_func(f"runtime.disco.{api}.init_ccl")
func(*args)
def broadcast_from_worker0(self, array: DRef) -> DRef:
@@ -278,6 +278,19 @@ class Session(Object):
func = self._get_cached_method("runtime.disco.broadcast_from_worker0")
return func(array)
+ def scatter_from_worker0(self, from_array: DRef, to_array: DRef) -> None:
+ """Scatter an array from worker-0 to all other workers.
+
+ Parameters
+ ----------
+ from_array : DRef
+ The array to be scattered from.
+ to_array : DRef
+ The array to be scattered to.
+ """
+ func = self._get_cached_method("runtime.disco.scatter_from_worker0")
+ func(from_array, to_array)
+
def allreduce(
self,
array: DRef,
diff --git a/src/runtime/disco/builtin.cc b/src/runtime/disco/builtin.cc
index bed8e68b0b..5d5e418303 100644
--- a/src/runtime/disco/builtin.cc
+++ b/src/runtime/disco/builtin.cc
@@ -16,15 +16,13 @@
* specific language governing permissions and limitations
* under the License.
*/
+#include "./builtin.h"
+
+#include <dlpack/dlpack.h>
#include <tvm/runtime/container/shape_tuple.h>
-#include <tvm/runtime/data_type.h>
#include <tvm/runtime/disco/session.h>
-#include <tvm/runtime/module.h>
-#include <tvm/runtime/ndarray.h>
-#include <tvm/runtime/object.h>
#include <tvm/runtime/packed_func.h>
#include <tvm/runtime/registry.h>
-#include <tvm/runtime/relax_vm/executable.h>
#include <tvm/runtime/relax_vm/vm.h>
#include <sstream>
@@ -63,47 +61,55 @@ Module LoadVMModule(std::string path, Device device) {
CHECK(vm_initialization != nullptr)
<< "ValueError: File `" << path
<< "` is not built by RelaxVM, because `vm_initialization` does not
exist";
- vm_initialization(static_cast<int>(device.device_type), //
- static_cast<int>(device.device_id), //
- static_cast<int>(relax_vm::AllocatorType::kPooled), //
- static_cast<int>(kDLCPU), //
- 0, //
+ vm_initialization(static_cast<int>(device.device_type),
static_cast<int>(device.device_id),
+ static_cast<int>(relax_vm::AllocatorType::kPooled),
static_cast<int>(kDLCPU), 0,
static_cast<int>(relax_vm::AllocatorType::kPooled));
return mod;
}
-TVM_REGISTER_GLOBAL("runtime.disco.load_vm_module").set_body_typed(LoadVMModule);
-
-TVM_REGISTER_GLOBAL("runtime.disco.empty").set_body([](TVMArgs args,
TVMRetValue* rv) -> void {
- runtime::DataType dtype = args[args.num_args - 2];
- Device device = args[args.num_args - 1];
- int ndim = args.num_args - 2;
- std::vector<ShapeTuple::index_type> shape;
- for (int i = 0; i < ndim; ++i) {
- shape.push_back(args[i].operator int64_t());
- }
- device = UseDefaultDeviceIfNone(device);
- *rv = NDArray::Empty(ShapeTuple(shape), dtype, device);
-});
+NDArray DiscoEmptyNDArray(ShapeTuple shape, DataType dtype, Device device) {
+ return NDArray::Empty(shape, dtype, UseDefaultDeviceIfNone(device));
+}
-TVM_REGISTER_GLOBAL("runtime.disco.allreduce").set_body([](TVMArgs args,
TVMRetValue* rv) -> void {
+const PackedFunc& GetCCLFunc(const char* name) {
std::string ccl = DiscoWorker::ThreadLocal()->ccl;
- std::string pf_name = "runtime.disco." + ccl + ".allreduce";
+ std::string pf_name = "runtime.disco." + ccl + "." + name;
const PackedFunc* pf = tvm::runtime::Registry::Get(pf_name);
- CHECK(pf != nullptr) << "ValueError: Cannot find the allreduce function for
" << ccl << " via `"
- << pf_name << "`";
- pf->CallPacked(args, rv);
-});
+ CHECK(pf != nullptr) << "ValueError: Cannot find the `" << name << "`
function for `" << ccl
+ << "` via `" << pf_name << "`";
+ return *pf;
+}
-TVM_REGISTER_GLOBAL("runtime.disco.broadcast_from_worker0")
- .set_body([](TVMArgs args, TVMRetValue* rv) -> void {
- std::string ccl = DiscoWorker::ThreadLocal()->ccl;
- std::string pf_name = "runtime.disco." + ccl + ".broadcast_from_worker0";
- const PackedFunc* pf = tvm::runtime::Registry::Get(pf_name);
- CHECK(pf != nullptr) << "ValueError: Cannot find the broadcast function
for " << ccl
- << " via `" << pf_name << "`";
- pf->CallPacked(args, rv);
+NDArray AllReduce(NDArray send, ReduceKind reduce_kind) {
+ return GetCCLFunc("allreduce")(send, static_cast<int>(reduce_kind));
+}
+
+NDArray BroadcastFromWorker0(NDArray buffer) {
+ return GetCCLFunc("broadcast_from_worker0")(buffer);
+}
+
+void ScatterFromWorker0(Optional<NDArray> send, NDArray recv) {
+ GetCCLFunc("scatter_from_worker0")(send, recv);
+}
+
+void RecvFromWorker0(NDArray buffer) {
GetCCLFunc("recv_from_worker0")(buffer); }
+
+int WorkerId() { return DiscoWorker::ThreadLocal()->worker_id; }
+
+TVM_REGISTER_GLOBAL("runtime.disco.load_vm_module").set_body_typed(LoadVMModule);
+TVM_REGISTER_GLOBAL("runtime.disco.empty").set_body_typed(DiscoEmptyNDArray);
+TVM_REGISTER_GLOBAL("runtime.disco.allreduce")
+ .set_body_typed([](NDArray send, ShapeTuple reduce_kind) {
+ int kind = IntegerFromShapeTuple(reduce_kind);
+ CHECK(0 <= kind && kind <= 4) << "ValueError: Unknown ReduceKind: " <<
kind;
+ return AllReduce(send, static_cast<ReduceKind>(kind));
});
+TVM_REGISTER_GLOBAL("runtime.disco.broadcast_from_worker0").set_body_typed(BroadcastFromWorker0);
+TVM_REGISTER_GLOBAL("runtime.disco.scatter_from_worker0").set_body_typed(ScatterFromWorker0);
+TVM_REGISTER_GLOBAL("runtime.disco.recv_from_worker0").set_body_typed(RecvFromWorker0);
+TVM_REGISTER_GLOBAL("runtime.disco.worker_id").set_body_typed([]() ->
ShapeTuple {
+ return ShapeTuple({WorkerId()});
+});
} // namespace runtime
} // namespace tvm
diff --git a/src/runtime/disco/builtin.h b/src/runtime/disco/builtin.h
new file mode 100644
index 0000000000..784077e6de
--- /dev/null
+++ b/src/runtime/disco/builtin.h
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+#ifndef TVM_RUNTIME_DISCO_BUILTIN_H_
+#define TVM_RUNTIME_DISCO_BUILTIN_H_
+
+#include <tvm/runtime/data_type.h>
+#include <tvm/runtime/module.h>
+#include <tvm/runtime/ndarray.h>
+
+#include <string>
+
+#include "./utils.h"
+
+namespace tvm {
+namespace runtime {
+
+/*!
+ * \brief Load a runtime Module, then create and initialize a RelaxVM
+ * \param path The path to the runtime Module (a DSO file) to be loaded
+ * \param device The default device used to initialize the RelaxVM
+ * \return The RelaxVM as a runtime Module
+ */
+Module LoadVMModule(std::string path, Device device);
+/*!
+ * \brief Create an uninitialized empty NDArray
+ * \param shape The shape of the NDArray
+ * \param dtype The dtype of the NDArray
+ * \param device The device the NDArray is created on. If None, use the thread
local default device
+ * \return The NDArray created
+ */
+NDArray DiscoEmptyNDArray(ShapeTuple shape, DataType dtype, Device device);
+/*!
+ * \brief Perform an allreduce operation using the underlying communication
library
+ * \param send The array send to perform allreduce on
+ * \param reduce_kind The kind of reduction operation (e.g. sum, avg, min, max)
+ * \return The outcome of allreduce
+ */
+NDArray AllReduce(NDArray send, ReduceKind reduce_kind);
+/*!
+ * \brief Perform a broadcast operation from worker-0
+ * \param buffer The buffer to be broadcasted
+ * \return The result buffer
+ */
+NDArray BroadcastFromWorker0(NDArray buffer);
+/*!
+ * \brief Perform a scatter operation from worker-0, chunking the given buffer
into equal parts.
+ * \param send For worker-0, it must be provided, and otherwise, the buffer
must be None.
+ * The buffer will be divided into equal parts and sent to each worker
accordingly.
+ * \param recv The receiving buffer, which must not be None.
+ */
+void ScatterFromWorker0(Optional<NDArray> send, NDArray recv);
+/*!
+ * \brief Receive a buffer from worker-0. No-op if the current worker is
worker-0.
+ * \param buffer The buffer to be received
+ */
+void RecvFromWorker0(NDArray buffer);
+
+/*! \brief Get the local worker id */
+int WorkerId();
+
+} // namespace runtime
+} // namespace tvm
+
+#endif // TVM_RUNTIME_DISCO_BUILTIN_H_
diff --git a/src/runtime/disco/nccl/nccl.cc b/src/runtime/disco/nccl/nccl.cc
index 48f552c5aa..52ea8798a0 100644
--- a/src/runtime/disco/nccl/nccl.cc
+++ b/src/runtime/disco/nccl/nccl.cc
@@ -33,27 +33,15 @@ namespace runtime {
namespace nccl {
struct NCCLGlobalContext {
- // TODO(@junrushao): support more flexible communicator pattern for generic
SPMD usecases
- std::vector<int> device_ids;
std::vector<ncclComm_t> communicators;
- std::vector<cudaStream_t> streams;
-
- ~NCCLGlobalContext() {}
-
- void Clear() {
- for (ncclComm_t comm : this->communicators) {
- NCCL_CALL(ncclCommDestroy(comm));
- }
- device_ids.clear();
- communicators.clear();
- }
static NCCLGlobalContext* Get() {
static NCCLGlobalContext ctx;
return &ctx;
}
- void Initialize(std::vector<int> device_ids) {
+ void Initialize(const std::vector<int>& device_ids) {
+ // TODO(@junrushao): support more flexible communicator pattern for
generic SPMD usecases
DiscoWorker* worker = DiscoWorker::ThreadLocal();
int num_workers = worker->num_workers;
CHECK_EQ(device_ids.size(), num_workers)
@@ -65,80 +53,137 @@ struct NCCLGlobalContext {
for (int worker_id = 0; worker_id < num_workers; ++worker_id) {
int device_id = device_ids[worker_id];
ncclComm_t comm;
- cudaStream_t stream;
CUDA_CALL(cudaSetDevice(device_id));
- CUDA_CALL(cudaStreamCreate(&stream));
NCCL_CALL(ncclCommInitRank(&comm, num_workers, id, worker_id));
- this->streams.push_back(stream);
this->communicators.push_back(comm);
}
NCCL_CALL(ncclGroupEnd());
- this->device_ids = std::move(device_ids);
}
+};
+
+struct NCCLThreadLocalContext {
+ DiscoWorker* worker;
+ int device_id;
+ cudaStream_t stream;
+ ncclComm_t comm;
- static ncclComm_t ThreadLocalCommunicator() {
- thread_local static ncclComm_t comm =
-
NCCLGlobalContext::Get()->communicators[DiscoWorker::ThreadLocal()->worker_id];
- return comm;
+ void Clear() {
+ NCCL_CALL(ncclCommDestroy(comm));
+ CUDA_CALL(cudaStreamDestroy(stream));
}
- static cudaStream_t ThreadLocalStream() {
- thread_local static cudaStream_t stream =
-
NCCLGlobalContext::Get()->streams[DiscoWorker::ThreadLocal()->worker_id];
- return stream;
+ static NCCLThreadLocalContext* Get() {
+ thread_local static NCCLThreadLocalContext ctx;
+ return &ctx;
}
};
-inline int64_t GetNumel(const ShapeTuple& shape) {
- int64_t numel = 1;
- for (int64_t d : shape) {
- numel *= d;
- }
- return numel;
+void InitCCL(const std::vector<int>& device_ids) {
+ // Set up global context only once
+ static std::once_flag flag;
+ std::call_once(flag, [&]() {
NCCLGlobalContext::Get()->Initialize(device_ids); });
+ // Set up thread-local context for each thread
+ DiscoWorker* worker = DiscoWorker::ThreadLocal();
+ NCCLThreadLocalContext* ctx = NCCLThreadLocalContext::Get();
+ int device_id = device_ids[worker->worker_id];
+ CUDA_CALL(cudaSetDevice(device_id));
+ Device device{DLDeviceType::kDLCUDA, device_id};
+ worker->default_device = device;
+ worker->ccl = "nccl";
+ ctx->worker = worker;
+ ctx->device_id = device_id;
+ ctx->comm = NCCLGlobalContext::Get()->communicators[worker->worker_id];
+ CUDA_CALL(cudaStreamCreate(&ctx->stream));
+ DeviceAPI::Get(device)->SetStream(device, ctx->stream);
}
NDArray AllReduce(NDArray send, ReduceKind reduce_kind) {
+ NCCLThreadLocalContext* ctx = NCCLThreadLocalContext::Get();
ShapeTuple shape = send.Shape();
- int64_t numel = GetNumel(shape);
+ int64_t numel = shape->Product();
NDArray recv = NDArray::Empty(shape, send->dtype, send->device);
NCCL_CALL(ncclAllReduce(send->data, recv->data, numel,
/*datatype=*/AsNCCLDataType(DataType(send->dtype)),
- /*op=*/AsNCCLRedOp(reduce_kind),
-
/*comm=*/NCCLGlobalContext::ThreadLocalCommunicator(),
- /*stream=*/NCCLGlobalContext::ThreadLocalStream()));
+ /*op=*/AsNCCLRedOp(reduce_kind), ctx->comm,
ctx->stream));
return recv;
}
-NDArray BroadcastFromZero(NDArray buffer) {
+NDArray BroadcastFromWorker0(NDArray buffer) {
+ NCCLThreadLocalContext* ctx = NCCLThreadLocalContext::Get();
ShapeTuple shape = buffer.Shape();
- int64_t numel = GetNumel(shape);
+ int64_t numel = shape->Product();
NCCL_CALL(ncclBroadcast(buffer->data, buffer->data, numel,
-
/*datatype=*/AsNCCLDataType(DataType(buffer->dtype)), //
- /*root=*/0,
NCCLGlobalContext::ThreadLocalCommunicator(),
- NCCLGlobalContext::ThreadLocalStream()));
+ /*datatype=*/AsNCCLDataType(DataType(buffer->dtype)),
+ /*root=*/0, ctx->comm, ctx->stream));
return buffer;
}
-TVM_REGISTER_GLOBAL("runtime.disco.nccl.init").set_body([](TVMArgs args,
TVMRetValue* rv) -> void {
- // Parse the inputs into device ids
- std::vector<int> device_ids;
- for (int i = 0; i < args.num_args; ++i) {
- device_ids.push_back(args[i].operator int());
+void ScatterFromWorker0(Optional<NDArray> send, NDArray recv) {
+ CHECK(recv.defined()) << "ValueError: buffer `recv` must not be None";
+ NCCLThreadLocalContext* ctx = NCCLThreadLocalContext::Get();
+ int worker_id = ctx->worker->worker_id;
+ int num_workers = ctx->worker->num_workers;
+ if (worker_id == 0) {
+ CHECK(send.defined()) << "ValueError: buffer `send` must be provided when
worker_id == 0.";
+ NDArray buffer = send.value();
+ int64_t numel = buffer.Shape()->Product();
+ CHECK_EQ(numel % num_workers, 0)
+ << "ValueError: Scattering evenly requires that the number of elements
in the buffer to be "
+ "divisible by the number of workers, but got numel = "
+ << numel << " and " << num_workers << " workers.";
+ DataType dtype(buffer->dtype);
+ int64_t numel_per_shard = numel / num_workers;
+ int64_t bytes_per_shard = numel_per_shard * dtype.bytes();
+ CHECK_EQ(numel_per_shard, recv.Shape()->Product())
+ << "ValueError: The number of elements in buffer `recv` must be the
same as each shard of "
+ "buffer `send`. `send.size` is "
+ << numel << ", but `recv.size` is " << recv.Shape()->Product() << ".";
+ NCCL_CALL(ncclGroupStart());
+ uint8_t* data = static_cast<uint8_t*>(buffer->data);
+ for (int i = 0; i < num_workers; ++i) {
+ NCCL_CALL(ncclSend(data, numel_per_shard, AsNCCLDataType(dtype), i,
ctx->comm, ctx->stream));
+ data += bytes_per_shard;
+ }
+ } else {
+ if (send.defined()) {
+ LOG(WARNING) << "ValueError: buffer `send` must be None when worker_id
!= 0. However, got "
+ "send = "
+ << send.get() << ". This will be ignored.";
+ }
+ NCCL_CALL(ncclGroupStart());
}
- // Set the `default_device` and `ccl` for the current worker
- DiscoWorker* worker = DiscoWorker::ThreadLocal();
- worker->default_device = Device{DLDeviceType::kDLCUDA,
device_ids[worker->worker_id]};
- worker->ccl = "nccl";
- // Setup global context only once
- static std::once_flag flag;
- std::call_once(flag, [&]() {
NCCLGlobalContext::Get()->Initialize(device_ids); });
-});
+ int64_t numel = recv.Shape()->Product();
+ DataType dtype(recv->dtype);
+ NCCL_CALL(ncclRecv(recv->data, numel, AsNCCLDataType(dtype), 0, ctx->comm,
ctx->stream));
+ NCCL_CALL(ncclGroupEnd());
+}
-TVM_REGISTER_GLOBAL("runtime.disco.nccl.allreduce")
- .set_body_typed([](NDArray send, ShapeTuple reduce_kind) {
- return AllReduce(send,
static_cast<ReduceKind>(IntegerFromShapeTuple(reduce_kind)));
+void RecvFromWorker0(NDArray buffer) {
+ NCCLThreadLocalContext* ctx = NCCLThreadLocalContext::Get();
+ CHECK_NE(ctx->worker->worker_id, 0)
+ << "ValueError: Worker 0 is not allowed to call RecvFromWorker0.";
+ NCCL_CALL(ncclGroupStart());
+ NCCL_CALL(ncclRecv(buffer->data, buffer.Shape()->Product(),
AsNCCLDataType(buffer.DataType()), 0,
+ ctx->comm, ctx->stream));
+ NCCL_CALL(ncclGroupEnd());
+}
+
+TVM_REGISTER_GLOBAL("runtime.disco.nccl.init_ccl")
+ .set_body([](TVMArgs args, TVMRetValue* rv) -> void {
+ std::vector<int> device_ids;
+ for (int i = 0; i < args.num_args; ++i) {
+ device_ids.push_back(args[i].operator int());
+ }
+ InitCCL(device_ids);
});
-TVM_REGISTER_GLOBAL("runtime.disco.nccl.broadcast_from_worker0").set_body_typed(BroadcastFromZero);
+TVM_REGISTER_GLOBAL("runtime.disco.nccl.allreduce").set_body_typed([](NDArray
send, int kind) {
+ CHECK(0 <= kind && kind <= 4) << "ValueError: Unknown ReduceKind: " << kind;
+ return AllReduce(send, static_cast<ReduceKind>(kind));
+});
+TVM_REGISTER_GLOBAL("runtime.disco.nccl.broadcast_from_worker0")
+ .set_body_typed(BroadcastFromWorker0);
+TVM_REGISTER_GLOBAL("runtime.disco.nccl.scatter_from_worker0").set_body_typed(ScatterFromWorker0);
+TVM_REGISTER_GLOBAL("runtime.disco.nccl.recv_from_worker0").set_body_typed(RecvFromWorker0);
} // namespace nccl
} // namespace runtime
diff --git a/tests/python/disco/test_nccl.py b/tests/python/disco/test_nccl.py
index af7da28db2..8fc56b1ec1 100644
--- a/tests/python/disco/test_nccl.py
+++ b/tests/python/disco/test_nccl.py
@@ -74,6 +74,29 @@ def test_broadcast_from_worker0():
np.testing.assert_equal(result, array)
+def test_scatter():
+ num_workers = 2
+ devices = [1, 2]
+ array = np.arange(36, dtype="float32").reshape(3, 4, 3)
+
+ sess = di.ThreadedSession(num_workers=num_workers)
+ sess.init_ccl("nccl", *devices)
+ d_src = sess.empty((3, 4, 3), "float32")
+ d_dst = sess.empty((3, 3, 2), "float32")
+
+ d_src.debug_copy_from(0, array)
+ sess.scatter_from_worker0(d_src, d_dst)
+
+ np.testing.assert_equal(
+ d_dst.debug_get_from_remote(0).numpy(),
+ array.flat[:18].reshape(3, 3, 2),
+ )
+ np.testing.assert_equal(
+ d_dst.debug_get_from_remote(1).numpy(),
+ array.flat[18:].reshape(3, 3, 2),
+ )
+
+
def test_mlp(): # pylint: disable=too-many-locals
num_workers = 2
devices = [1, 2]
@@ -334,5 +357,6 @@ if __name__ == "__main__":
test_init()
test_broadcast_from_worker0()
test_allreduce()
+ test_scatter()
test_mlp()
test_attention()