diff --git a/examples/ccl/broadcast.cc b/examples/ccl/broadcast.cc new file mode 100644 index 0000000..fcf1181 --- /dev/null +++ b/examples/ccl/broadcast.cc @@ -0,0 +1,250 @@ +/** + * InfiniCCL Example: Thread-per-GPU Single-Node `Broadcast` + * + * This example creates one native CCL rank per GPU and performs a rooted + * broadcast without any OpenMPI dependencies, supporting out-of-place, + * in-place, and legacy in-place topologies. + * + * Use `--launcher none` for this thread-per-GPU example. + */ + +#include + +#include +#include +#include +#include +#include +#include + +// Public API +#include "infiniccl.h" + +// Example-Specific Utilities +#include "utils.h" + +// Internal Headers (Accessible via example-specific include paths, technically +// not public APIs) +#include "backend_manifest.h" + +using namespace infini::ccl; + +constexpr int kRoot = 0; +constexpr float kRootMagicValue = 42.0f; + +// Structure to pass execution data to each GPU worker thread. +struct ThreadArgs { + int rank; + int size; + infinicclUniqueId id; + size_t num_elements; + int warmup_iter; + int profile_iter; + int *correct; +}; + +// Worker function executed by each CPU thread. +void WorkerThread(ThreadArgs args) { + constexpr Device::Type kDevType = + ListGetBest(EnabledDevices{}); + using Rt = Runtime; + + // Bind this CPU thread to its local GPU. + CHECK_RT(Rt, Rt::SetDevice(args.rank)); + + infinicclComm_t comm = nullptr; + CHECK_INFINI(infinicclCommInitRank(&comm, args.size, args.id, args.rank)); + + const bool is_root = args.rank == kRoot; + const size_t total_bytes = args.num_elements * sizeof(float); + + // Prepare Host Data: only root fills its buffer with the broadcast payload. + std::vector h_send(is_root ? args.num_elements : 0, 0.0f); + std::vector h_recv(args.num_elements, 0.0f); + if (is_root) { + for (size_t i = 0; i < args.num_elements; ++i) { + h_send[i] = kRootMagicValue; + } + } + + // Allocate Device Memory. + float *d_send = nullptr; + float *d_recv = nullptr; + if (is_root) { + CHECK_RT(Rt, Rt::Malloc(reinterpret_cast(&d_send), total_bytes)); + CHECK_RT(Rt, Rt::Memcpy(d_send, h_send.data(), total_bytes, + Rt::MemcpyHostToDevice)); + } + CHECK_RT(Rt, Rt::Malloc(reinterpret_cast(&d_recv), total_bytes)); + CHECK_RT(Rt, Rt::Memcpy(d_recv, h_recv.data(), total_bytes, + Rt::MemcpyHostToDevice)); + CHECK_RT(Rt, Rt::StreamSynchronize(nullptr)); + + // The Abstract Execution & Validation Function + auto ProfileAndValidateScenario = [&](const std::string &scenario_name, + float *d_verify_source, + bool *scenario_correct, + auto &&collective_call) { + if (is_root) { + std::cout << "\n=== Performing " << scenario_name << " ===" << std::endl; + if (scenario_name.find("Scenario 1") != std::string::npos) { + std::cout << "Data size: " << args.num_elements << " floats (" + << total_bytes / 1024 / 1024 << " MB)" << std::endl; + std::cout << "Root Node: " << kRoot << std::endl; + } + } + + // Warm-up Iteration & Initial Capture + CHECK_INFINI(collective_call()); + CHECK_RT(Rt, Rt::Memcpy(h_recv.data(), d_verify_source, total_bytes, + Rt::MemcpyDeviceToHost)); + + for (int i = 1; i < args.warmup_iter; ++i) { + CHECK_INFINI(collective_call()); + } + CHECK_RT(Rt, Rt::StreamSynchronize(nullptr)); + + // Profiling + Timer timer; + for (int i = 0; i < args.profile_iter; i++) { + CHECK_INFINI(collective_call()); + } + CHECK_RT(Rt, Rt::StreamSynchronize(nullptr)); + double elapsed = timer.ElapsedMs() / static_cast(args.profile_iter); + + // Validation: every rank checks the broadcast payload it received. + *scenario_correct = Validator::ValidateResult( + h_recv.data(), args.num_elements, kRootMagicValue, args.rank, true, + scenario_name); + + // Performance Reporting (Only Root) + if (is_root) { + Metrics metrics{elapsed, total_bytes, args.size}; + metrics.Print(); + } + }; + + bool scenario_correct = true; + bool all_correct = true; + + // -------------------------------------------------------------------------- + // Scenario 1: Out-of-Place Broadcast + // -------------------------------------------------------------------------- + ProfileAndValidateScenario( + "Scenario 1: Out-of-Place Broadcast", d_recv, &scenario_correct, [&]() { + return infinicclBroadcast(d_send, d_recv, args.num_elements, + infinicclFloat32, kRoot, comm, nullptr); + }); + all_correct = all_correct && scenario_correct; + + // -------------------------------------------------------------------------- + // Scenario 2: In-Place Broadcast + // -------------------------------------------------------------------------- + std::fill(h_recv.begin(), h_recv.end(), 0.0f); + float *d_inplace_buf = is_root ? d_send : d_recv; + + ProfileAndValidateScenario("Scenario 2: In-Place Broadcast", d_inplace_buf, + &scenario_correct, [&]() { + return infinicclBroadcast( + d_inplace_buf, d_inplace_buf, + args.num_elements, infinicclFloat32, kRoot, + comm, nullptr); + }); + all_correct = all_correct && scenario_correct; + + // -------------------------------------------------------------------------- + // Scenario 3: Legacy In-Place Bcast + // -------------------------------------------------------------------------- + std::fill(h_recv.begin(), h_recv.end(), 0.0f); + + ProfileAndValidateScenario("Scenario 3: Legacy In-Place Bcast", d_inplace_buf, + &scenario_correct, [&]() { + return infinicclBcast( + d_inplace_buf, args.num_elements, + infinicclFloat32, kRoot, comm, nullptr); + }); + all_correct = all_correct && scenario_correct; + + *args.correct = all_correct; + + // Cleanup local rank resources. + if (is_root) { + CHECK_RT(Rt, Rt::Free(d_send)); + } + CHECK_RT(Rt, Rt::Free(d_recv)); + CHECK_INFINI(infinicclCommDestroy(comm)); +} + +int main(int argc, char **argv) { + int num_gpus = 8; + int warmup_iters = 2; + int profile_iters = 20; + size_t num_elements = 1 << 20; + + int opt; + while ((opt = getopt(argc, argv, "g:w:p:n:h")) != -1) { + switch (opt) { + case 'g': + num_gpus = std::stoi(optarg); + break; + case 'w': + warmup_iters = std::stoi(optarg); + break; + case 'p': + profile_iters = std::stoi(optarg); + break; + case 'n': + num_elements = static_cast(std::stoull(optarg)); + break; + case 'h': + std::cout << "Usage: " << argv[0] << " [options]\n" + << "Options:\n" + << " -g Number of GPUs (default: 8)\n" + << " -w Warmup iterations (default: 2)\n" + << " -p Profile iterations (default: 20)\n" + << " -n Number of elements (default: " + << (1 << 20) << ")\n"; + return EXIT_SUCCESS; + default: + std::cerr << "Invalid argument. Use -h for help." << std::endl; + return EXIT_FAILURE; + } + } + + if (num_gpus <= 0 || warmup_iters <= 0 || profile_iters <= 0 || + num_elements == 0 || + num_elements > std::numeric_limits::max() / sizeof(float)) { + std::cerr << "`Broadcast` arguments or buffer size are invalid." + << std::endl; + return EXIT_FAILURE; + } + + char hostname[256]; + gethostname(hostname, sizeof(hostname)); + std::cout << "[Main Process] Host: " << hostname + << " | Target GPUs: " << num_gpus << std::endl; + + infinicclUniqueId shared_id; + CHECK_INFINI(infinicclGetUniqueId(&shared_id)); + + std::vector correct(num_gpus, 0); + std::vector threads; + threads.reserve(num_gpus); + for (int rank = 0; rank < num_gpus; ++rank) { + ThreadArgs args{rank, num_gpus, shared_id, num_elements, + warmup_iters, profile_iters, &correct[rank]}; + threads.emplace_back(WorkerThread, args); + } + + for (auto &thread : threads) { + if (thread.joinable()) { + thread.join(); + } + } + + const bool result = std::all_of(correct.begin(), correct.end(), + [](int value) { return value != 0; }); + std::cout << "[Main Process] Broadcast validation " + << (result ? "passed." : "failed.") << std::endl; + return result ? EXIT_SUCCESS : EXIT_FAILURE; +} diff --git a/examples/ccl_mpi_hybrid/broadcast.cc b/examples/ccl_mpi_hybrid/broadcast.cc new file mode 100644 index 0000000..a012473 --- /dev/null +++ b/examples/ccl_mpi_hybrid/broadcast.cc @@ -0,0 +1,211 @@ +/** + * InfiniCCL Example: `Broadcast` (OpenMPI + CCL Hybrid) + * + * This example demonstrates the API for performing a collective + * broadcast operation across multiple GPUs and nodes, where `root` + * sends the same message to every rank, supporting out-of-place, + * in-place, and legacy in-place topologies. + */ + +#include + +#include +#include + +// Public API +#include "infiniccl.h" + +// Example-Specific Utilities +#include "utils.h" + +// Internal Headers (Accessible via example-specific include paths, technically +// not public APIs) +#include "backend_manifest.h" +#include "device.h" +#include "runtime.h" +#include "traits.h" + +using namespace infini::ccl; + +bool RunBroadcastExample(int argc, char **argv, int warmup_iter, + int profile_iter, const size_t kNumElements) { + constexpr Device::Type kDevType = + ListGetBest(EnabledDevices{}); + using Rt = Runtime; + + CHECK_INFINI(infinicclInit(&argc, &argv)); + + int rank, size; + CHECK_INFINI(infinicclGetRank(&rank)); + CHECK_INFINI(infinicclGetSize(&size)); + + char hostname[256]; + gethostname(hostname, sizeof(hostname)); + + // Map local rank to GPU device. + const char *local_rank_str = std::getenv("OMPI_COMM_WORLD_LOCAL_RANK"); + int local_rank = 0; + if (local_rank_str != nullptr) { + local_rank = std::atoi(local_rank_str); + } + + CHECK_RT(Rt, Rt::SetDevice(local_rank)); + + std::cout << "[Rank " << rank << "] Host: " << hostname + << " | GPU: " << Device::StringFromType(kDevType) << " " + << " | Device " << local_rank << std::endl; + + // Setup Communicator: bootstrap the native CCL communicator over the + // MPI-only communicator returned by `infinicclCommInitAll`. + infinicclComm_t comm = nullptr; + CHECK_INFINI(infinicclCommInitAll(&comm, size, nullptr)); + infinicclUniqueId id; + if (rank == 0) { + CHECK_INFINI(infinicclGetUniqueId(&id)); + } + CHECK_INFINI(infinicclBroadcast(&id, &id, sizeof(id), infinicclChar, 0, comm, + nullptr)); + CHECK_INFINI(infinicclCommInitRank(&comm, size, id, rank)); + + // Root of the Broadcast + constexpr int kRoot = 0; + constexpr float kRootMagicValue = 42.0f; + + // Prepare Host Data + std::vector h_send(kNumElements, 0.0f); + std::vector h_recv(kNumElements, 0.0f); + + // Initialize: Only root fills its buffer with meaningful payload. + if (rank == kRoot) { + for (size_t i = 0; i < kNumElements; i++) { + h_send[i] = kRootMagicValue; + } + } + + // Allocate Device Memory + float *d_send, *d_recv; + size_t total_bytes = kNumElements * sizeof(float); + CHECK_RT(Rt, Rt::Malloc((void **)&d_send, total_bytes)); + CHECK_RT(Rt, Rt::Malloc((void **)&d_recv, total_bytes)); + + // Copy data from host to device memory. + CHECK_RT(Rt, Rt::Memcpy(d_send, h_send.data(), total_bytes, + Rt::MemcpyHostToDevice)); + CHECK_RT(Rt, Rt::Memcpy(d_recv, h_recv.data(), total_bytes, + Rt::MemcpyHostToDevice)); + + CHECK_RT(Rt, Rt::StreamSynchronize(nullptr)); + + // The Abstract Execution & Validation Function + auto ProfileAndValidateScenario = [&](const std::string &scenario_name, + float *d_verify_source, + auto &&collective_call) { + if (rank == kRoot) { + std::cout << "\n=== Performing " << scenario_name << " ===" << std::endl; + if (scenario_name.find("Scenario 1") != std::string::npos) { + std::cout << "Data size: " << kNumElements << " floats (" + << total_bytes / 1024 / 1024 << " MB)" << std::endl; + std::cout << "Root Node: " << kRoot << std::endl; + } + } + + // Warm-up Iteration & Initial Capture + CHECK_INFINI(collective_call()); + CHECK_RT(Rt, Rt::Memcpy(h_recv.data(), d_verify_source, total_bytes, + Rt::MemcpyDeviceToHost)); + + for (int i = 1; i < warmup_iter; ++i) { + CHECK_INFINI(collective_call()); + } + CHECK_RT(Rt, Rt::StreamSynchronize(nullptr)); + + // Profiling + Timer timer; + for (int i = 0; i < profile_iter; i++) { + CHECK_INFINI(collective_call()); + } + CHECK_RT(Rt, Rt::StreamSynchronize(nullptr)); + double elapsed = timer.ElapsedMs() / static_cast(profile_iter); + + // Validation + const bool scenario_correct = + Validator::ValidateResult(h_recv.data(), kNumElements, kRootMagicValue, + rank, true, scenario_name); + + // Performance Reporting + if (rank == kRoot) { + Metrics metrics{elapsed, total_bytes, size}; + metrics.Print(); + } + + return scenario_correct; + }; + + bool all_correct = true; + + // -------------------------------------------------------------------------- + // Scenario 1: Out-of-Place Broadcast + // -------------------------------------------------------------------------- + all_correct = + ProfileAndValidateScenario("Scenario 1: Out-of-Place Broadcast", d_recv, + [&]() { + return infinicclBroadcast( + d_send, d_recv, kNumElements, + infinicclFloat32, kRoot, comm, nullptr); + }) && + all_correct; + + // -------------------------------------------------------------------------- + // Scenario 2: In-Place Broadcast + // -------------------------------------------------------------------------- + std::fill(h_recv.begin(), h_recv.end(), 0.0f); + float *d_inplace_buf = (rank == kRoot) ? d_send : d_recv; + + all_correct = ProfileAndValidateScenario( + "Scenario 2: In-Place Broadcast", d_inplace_buf, + [&]() { + return infinicclBroadcast(d_inplace_buf, d_inplace_buf, + kNumElements, infinicclFloat32, + kRoot, comm, nullptr); + }) && + all_correct; + + // -------------------------------------------------------------------------- + // Scenario 3: Legacy In-Place Bcast + // -------------------------------------------------------------------------- + std::fill(h_recv.begin(), h_recv.end(), 0.0f); + + all_correct = + ProfileAndValidateScenario( + "Scenario 3: Legacy In-Place Bcast", d_inplace_buf, + [&]() { + return infinicclBcast(d_inplace_buf, kNumElements, infinicclFloat32, + kRoot, comm, nullptr); + }) && + all_correct; + + // -------------------------------------------------------------------------- + // Cleanup + // -------------------------------------------------------------------------- + CHECK_RT(Rt, Rt::Free(d_send)); + CHECK_RT(Rt, Rt::Free(d_recv)); + + CHECK_INFINI(infinicclCommDestroy(comm)); + CHECK_INFINI(infinicclFinalize()); + + if (rank == kRoot) { + std::cout << "\nInfiniCCL finalized." << std::endl; + } + return all_correct; +} + +int main(int argc, char **argv) { + int warmup_iters = 2; + int profile_iters = 20; + size_t num_elements = 1 << 20; + + return RunBroadcastExample(argc, argv, warmup_iters, profile_iters, + num_elements) + ? EXIT_SUCCESS + : EXIT_FAILURE; +} diff --git a/src/backends/ccl/common/impl/broadcast.h b/src/backends/ccl/common/impl/broadcast.h new file mode 100644 index 0000000..96cddbd --- /dev/null +++ b/src/backends/ccl/common/impl/broadcast.h @@ -0,0 +1,43 @@ +#ifndef INFINI_CCL_BACKENDS_CCL_COMMON_IMPL_BROADCAST_H_ +#define INFINI_CCL_BACKENDS_CCL_COMMON_IMPL_BROADCAST_H_ + +#include "backends/ccl/common/api.h" +#include "backends/ccl/common/comm_instance.h" +#include "base/broadcast.h" +#include "communicator.h" + +namespace infini::ccl { + +template +class CclBroadcastImpl { + public: + static ReturnStatus Apply(const void* send_buff, void* recv_buff, + size_t count, DataType data_type, int root, + Communicator* comm, void* stream) { + using Api = CclApi; + using TypeMap = CclTypeMap; + using CommInstance = CclCommInstance; + + if (!comm) { + return ReturnStatus::kInternalError; + } + + auto* intra = static_cast(comm->intra_comm()); + if (!intra || !intra->handle) { + return ReturnStatus::kInternalError; + } + + typename Api::DataType ccl_type{}; + if (!TypeMap::ToBackendDataType(data_type, &ccl_type)) { + return ReturnStatus::kNotSupported; + } + + return Api::Check(Api::Broadcast( + send_buff, recv_buff, count, ccl_type, root, intra->handle, + reinterpret_cast(stream))); + } +}; + +} // namespace infini::ccl + +#endif // INFINI_CCL_BACKENDS_CCL_COMMON_IMPL_BROADCAST_H_ diff --git a/src/backends/ccl/mccl/api.h b/src/backends/ccl/mccl/api.h index 6e03722..0d4b82c 100644 --- a/src/backends/ccl/mccl/api.h +++ b/src/backends/ccl/mccl/api.h @@ -63,6 +63,13 @@ struct McclApi { } } + static Result Broadcast(const void *send_buff, void *recv_buff, size_t count, + DataType data_type, int root, Comm comm, + Stream stream) { + return mcclBroadcast(send_buff, recv_buff, count, data_type, root, comm, + stream); + } + static Result AllReduce(const void *send_buff, void *recv_buff, size_t count, DataType data_type, RedOp op, Comm comm, Stream stream) { diff --git a/src/backends/ccl/mccl/impl/bcast.h b/src/backends/ccl/mccl/impl/bcast.h new file mode 100644 index 0000000..79cb470 --- /dev/null +++ b/src/backends/ccl/mccl/impl/bcast.h @@ -0,0 +1,13 @@ +#ifndef INFINI_CCL_BACKENDS_CCL_MCCL_IMPL_BCAST_H_ +#define INFINI_CCL_BACKENDS_CCL_MCCL_IMPL_BCAST_H_ + +#include "base/bcast.h" + +namespace infini::ccl { + +template <> +struct BackendEnabled : std::true_type {}; + +} // namespace infini::ccl + +#endif // INFINI_CCL_BACKENDS_CCL_MCCL_IMPL_BCAST_H_ diff --git a/src/backends/ccl/mccl/impl/broadcast.h b/src/backends/ccl/mccl/impl/broadcast.h new file mode 100644 index 0000000..a1d6a6a --- /dev/null +++ b/src/backends/ccl/mccl/impl/broadcast.h @@ -0,0 +1,18 @@ +#ifndef INFINI_CCL_BACKENDS_CCL_MCCL_IMPL_BROADCAST_H_ +#define INFINI_CCL_BACKENDS_CCL_MCCL_IMPL_BROADCAST_H_ + +#include "backends/ccl/common/impl/broadcast.h" +#include "base/broadcast.h" + +namespace infini::ccl { + +template +class BroadcastImpl + : public CclBroadcastImpl {}; + +template <> +struct BackendEnabled : std::true_type {}; + +} // namespace infini::ccl + +#endif // INFINI_CCL_BACKENDS_CCL_MCCL_IMPL_BROADCAST_H_ diff --git a/src/backends/ccl/nccl/api.h b/src/backends/ccl/nccl/api.h index af393b8..465877b 100644 --- a/src/backends/ccl/nccl/api.h +++ b/src/backends/ccl/nccl/api.h @@ -62,6 +62,13 @@ struct NcclApi { } } + static Result Broadcast(const void* send_buff, void* recv_buff, size_t count, + DataType data_type, int root, Comm comm, + Stream stream) { + return ncclBroadcast(send_buff, recv_buff, count, data_type, root, comm, + stream); + } + static Result AllReduce(const void* send_buff, void* recv_buff, size_t count, DataType data_type, RedOp op, Comm comm, Stream stream) { diff --git a/src/backends/ccl/nccl/impl/bcast.h b/src/backends/ccl/nccl/impl/bcast.h new file mode 100644 index 0000000..73fe74c --- /dev/null +++ b/src/backends/ccl/nccl/impl/bcast.h @@ -0,0 +1,13 @@ +#ifndef INFINI_CCL_BACKENDS_CCL_NCCL_IMPL_BCAST_H_ +#define INFINI_CCL_BACKENDS_CCL_NCCL_IMPL_BCAST_H_ + +#include "base/bcast.h" + +namespace infini::ccl { + +template <> +struct BackendEnabled : std::true_type {}; + +} // namespace infini::ccl + +#endif // INFINI_CCL_BACKENDS_CCL_NCCL_IMPL_BCAST_H_ diff --git a/src/backends/ccl/nccl/impl/broadcast.h b/src/backends/ccl/nccl/impl/broadcast.h new file mode 100644 index 0000000..6456d24 --- /dev/null +++ b/src/backends/ccl/nccl/impl/broadcast.h @@ -0,0 +1,18 @@ +#ifndef INFINI_CCL_BACKENDS_CCL_NCCL_IMPL_BROADCAST_H_ +#define INFINI_CCL_BACKENDS_CCL_NCCL_IMPL_BROADCAST_H_ + +#include "backends/ccl/common/impl/broadcast.h" +#include "base/broadcast.h" + +namespace infini::ccl { + +template +class BroadcastImpl + : public CclBroadcastImpl {}; + +template <> +struct BackendEnabled : std::true_type {}; + +} // namespace infini::ccl + +#endif // INFINI_CCL_BACKENDS_CCL_NCCL_IMPL_BROADCAST_H_ diff --git a/src/base/broadcast.h b/src/base/broadcast.h index 0924e78..cbd028e 100644 --- a/src/base/broadcast.h +++ b/src/base/broadcast.h @@ -3,6 +3,7 @@ #include "communicator.h" #include "data_type_impl.h" +#include "dispatch_policy.h" #include "logging.h" #include "operation.h" #include "return_status_impl.h" @@ -31,6 +32,13 @@ class Broadcast : public Operation { return ReturnStatus::kSuccess; } + ReturnStatus redirect_status = ReturnStatus::kSuccess; + if (RedirectToCarrier(comm_handle, &redirect_status, + send_buff, recv_buff, count, datatype, + root, comm_handle, stream)) { + return redirect_status; + } + return BroadcastImpl::Apply( send_buff, recv_buff, count, datatype, root, comm, stream); } @@ -59,6 +67,13 @@ class Broadcast : public Operation { } }; +// The communicator decides which backend serves a `Broadcast`: hybrid +// stacks bootstrap over an MPI-only communicator before a CCL one exists. +template <> +struct DispatchPolicy { + static constexpr Policy value = Policy::kCarrierAware; +}; + } // namespace infini::ccl #endif // INFINI_CCL_BASE_BROADCAST_H_ diff --git a/src/dispatch_policy.h b/src/dispatch_policy.h new file mode 100644 index 0000000..6695832 --- /dev/null +++ b/src/dispatch_policy.h @@ -0,0 +1,32 @@ +#ifndef INFINI_CCL_DISPATCH_POLICY_H_ +#define INFINI_CCL_DISPATCH_POLICY_H_ + +namespace infini::ccl { + +// Backend selection strategy for an API implemented by several backends. +enum class Policy { + // Highest-priority enabled backend always wins (default). + kStatic, + // Reserved: filter candidates by the side the API builds (world vs. + // intra-node) before priority. For lifecycle APIs. + kRole, + // The communicator decides: when the priority winner is attached to + // neither communicator slot, the best enabled carried backend runs. + // Runtime cost: two communicator-slot reads plus a few enum compares per + // call. + kCarrierAware, + // Reserved: run every enabled backend the communicator carries (e.g. + // communicator destruction). + kFanOut, +}; + +// Per-operation dispatch policy. Specialize next to the operation to opt +// out of `kStatic`. +template +struct DispatchPolicy { + static constexpr Policy value = Policy::kStatic; +}; + +} // namespace infini::ccl + +#endif // INFINI_CCL_DISPATCH_POLICY_H_ diff --git a/src/operation.h b/src/operation.h index 60c1a38..bbc3a20 100644 --- a/src/operation.h +++ b/src/operation.h @@ -2,10 +2,13 @@ #define INFINI_CCL_OPERATION_H_ #include +#include #include "backend.h" #include "backend_device_map.h" +#include "communicator.h" #include "device.h" +#include "dispatch_policy.h" #include "dispatcher.h" #include "return_status_impl.h" #include "traits.h" @@ -45,6 +48,50 @@ class Operation { }, "Operation::Call"); } + + protected: + // Carrier-aware dispatch for `Policy::kCarrierAware` operations: when the + // priority winner is attached to neither communicator slot, re-dispatch to + // the best enabled backend the communicator carries. Only the priority + // winner can enter this path, so the redirected call never redirects + // again. Dependent on `Key`, the body is instantiated only at real call + // sites, after every `BackendEnabled` specialization is visible. + template + static bool RedirectToCarrier(void *comm_handle, ReturnStatus *status, + Args &&...args) { + if constexpr (DispatchPolicy::value == Policy::kCarrierAware) { + auto *comm = static_cast(comm_handle); + constexpr auto enabled_backends = ActiveBackends{}; + if (backend != ListGetBest(enabled_backends)) { + return false; + } + + // The communicator decides: a slot already carrying the winner means + // the call belongs to that backend. + if (comm->intra_comm_backend() == backend || + comm->inter_comm_backend() == backend) { + return false; + } + + for (BackendType carrier : + {comm->intra_comm_backend(), comm->inter_comm_backend()}) { + if (carrier != BackendType::kCount && + IsBackendEnabled(enabled_backends, carrier)) { + *status = Key::template Call(carrier, comm->device_type(), + std::forward(args)...); + return true; + } + } + } + + return false; + } + + private: + template + static bool IsBackendEnabled(List, BackendType backend) { + return ((backend == backends) || ...); + } }; } // namespace infini::ccl