diff --git a/CMakeLists.txt b/CMakeLists.txt index 900bea3..1b399a7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -22,6 +22,7 @@ set(WITH_CPU ON CACHE INTERNAL "CPU backend is always enabled") # --- BACKEND OPTIONS (Communication Protocols) --- # ========================================================= option(WITH_OMPI "Enable OpenMPI backend" OFF) +option(WITH_IBV "Enable IBV backend" OFF) option(WITH_MPICH "Enable MPICH backend" OFF) option(WITH_NCCL "Enable NCCL backend" OFF) option(WITH_MCCL "Enable MCCL backend" OFF) @@ -117,6 +118,27 @@ if(AUTO_DETECT_BACKENDS) message(STATUS "Auto-detected MPICH/Hydra environment.") endif() + # Detect IBV dependencies and an available IBV device. + if(NOT WITH_IBV) + find_program(IBV_DEVINFO_PATH ibv_devinfo) + find_path(AUTO_IBVERBS_INCLUDE_DIR NAMES infiniband/verbs.h QUIET) + find_library(AUTO_IBVERBS_LIBRARY NAMES ibverbs QUIET) + + if(IBV_DEVINFO_PATH AND AUTO_IBVERBS_INCLUDE_DIR AND + AUTO_IBVERBS_LIBRARY) + execute_process( + COMMAND ${IBV_DEVINFO_PATH} + RESULT_VARIABLE IBV_DEVINFO_RESULT + OUTPUT_QUIET + ERROR_QUIET + ) + if(IBV_DEVINFO_RESULT EQUAL 0) + set(WITH_IBV ON) + message(STATUS "Auto-detected IBV environment.") + endif() + endif() + endif() + # Detect NCCL Dependencies if(WITH_NVIDIA OR WITH_THEAD OR WITH_ILUVATAR OR WITH_HYGON) infiniccl_probe_nccl(NCCL_FOUND) @@ -167,7 +189,7 @@ if(AUTO_DETECT_BACKENDS) endif() # Fallback: If no backends are enabled or auto-detected, fall back to OpenMPI as the default bootstrap profile. -if(NOT WITH_OMPI AND NOT WITH_MPICH AND NOT WITH_NCCL AND NOT WITH_MCCL AND NOT WITH_CNCL AND NOT WITH_HCCL) +if(NOT WITH_OMPI AND NOT WITH_MPICH AND NOT WITH_NCCL AND NOT WITH_MCCL AND NOT WITH_CNCL AND NOT WITH_HCCL AND NOT WITH_IBV ) set(WITH_OMPI ON) message(STATUS "No backend specified or detected. Defaulting to `WITH_OMPI=ON`") endif() @@ -219,6 +241,12 @@ if(WITH_OMPI OR WITH_MPICH) find_package(MPI REQUIRED) endif() +if(WITH_IBV) + find_path(IBVERBS_INCLUDE_DIR NAMES infiniband/verbs.h REQUIRED) + find_library(IBVERBS_LIBRARY NAMES ibverbs REQUIRED) + find_package(Threads REQUIRED) +endif() + if(WITH_NCCL) infiniccl_configure_nccl(NCCL_INC NCCL_LIB NCCL_COMPILE_DEFINITIONS) include_directories(${NCCL_INC}) diff --git a/README.md b/README.md index 0843ca3..7573b69 100644 --- a/README.md +++ b/README.md @@ -143,6 +143,7 @@ cmake .. -DWITH_NVIDIA=ON -DWITH_OMPI=ON | `WITH_CPU` | CPU support (always enabled) | `ON` (internal, not user‑settable) | | **Backend (Communication) Options** ||| | `WITH_OMPI` | Enable OpenMPI backend | `ON` if no backend specified, otherwise `OFF` | +| `WITH_IBV` | Enable experimental IBV backend | `OFF` | | `WITH_MPICH` | Enable MPICH backend | `OFF` | | `WITH_NCCL` | Enable NCCL/RCCL backend | `OFF` | | `WITH_MCCL` | Enable MCCL backend | `OFF` | @@ -361,6 +362,7 @@ export LD_LIBRARY_PATH=${INFINI_INSTALL}/lib:$LD_LIBRARY_PATH | Backend | Support Level | Required CMake Option | Dependencies | |---------|---------------|----------------------|---------------| | **OpenMPI** | Full | `WITH_OMPI=ON` | The default backend. Requires the OpenMPI development package.| +| **IBV** | Experimental | `WITH_IBV=ON` | Requires Linux and `libibverbs`. Two-rank synchronous Send/Recv with Host buffers, NVIDIA peer-memory (`WITH_NVIDIA=ON`, CUDA ≥ 11.3, compatible `nvidia-peermem`), or experimental MetaX DMA-BUF (`WITH_METAX=ON`, MACA/mxkw and explicit opt-in). Messages are limited by negotiated port and verbs scatter-gather limits.| | **MPICH** | Full | `WITH_MPICH=ON` | Requires the MPICH development package.| | **NCCL** | Partial | `WITH_NCCL=ON` | Requires NVIDIA, Iluvatar, or T-Head NCCL, or HYGON RCCL. Currently available when `WITH_NVIDIA=ON`, `WITH_ILUVATAR=ON`, `WITH_HYGON=ON` or `WITH_THEAD=ON`.| | **MCCL** | Partial | `WITH_MCCL=ON` | Requires MetaX or Moore MCCL. Currently available when `WITH_METAX=ON` or `WITH_MOORE=ON`.| diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 2500965..02dd132 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -21,6 +21,16 @@ foreach(source_file ${EXAMPLE_SOURCES}) target_link_libraries(${target_name} PRIVATE infiniccl) + if(target_name STREQUAL "ibv_send_recv" AND WITH_IBV) + if(WITH_NVIDIA AND WITH_METAX) + message(FATAL_ERROR "The IBV example requires one accelerator runtime per build.") + elseif(WITH_NVIDIA) + target_compile_definitions(${target_name} PRIVATE INFINICCL_WITH_NVIDIA_IBV) + elseif(WITH_METAX) + target_compile_definitions(${target_name} PRIVATE INFINICCL_WITH_METAX_IBV) + endif() + endif() + # Add runtime and backend dependencies for direct runtime/backend usage. if(WITH_NVIDIA) target_link_libraries(${target_name} PRIVATE CUDA::cudart) diff --git a/examples/ibv/send_recv.cc b/examples/ibv/send_recv.cc new file mode 100644 index 0000000..b508466 --- /dev/null +++ b/examples/ibv/send_recv.cc @@ -0,0 +1,684 @@ +/** + * InfiniCCL Example: IBV Backend Host-buffer Send/Recv. + * + * The example distributes `infinicclUniqueId` over TCP. The backend uses a + * separate TCP bootstrap socket and transfers payloads through verbs RC QPs. + */ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "infiniccl.h" + +#if defined(INFINICCL_WITH_NVIDIA_IBV) +#include "devices/nvidia/runtime_.h" +#elif defined(INFINICCL_WITH_METAX_IBV) +#include "devices/metax/runtime_.h" +#endif + +#if defined(INFINICCL_WITH_NVIDIA_IBV) || defined(INFINICCL_WITH_METAX_IBV) +#define INFINICCL_IBV_GPU +#endif + +namespace { + +constexpr int kSenderRank = 0; +constexpr int kReceiverRank = 1; +constexpr int kRankCount = 2; +constexpr int kControlTimeoutMs = 30000; +constexpr uint16_t kDefaultIbvPort = 7471; + +#if defined(INFINICCL_WITH_NVIDIA_IBV) +constexpr const char *kDeviceName = "nvidia"; +#elif defined(INFINICCL_WITH_METAX_IBV) +constexpr const char *kDeviceName = "metax"; +#else +constexpr const char *kDeviceName = "cpu"; +#endif + +void CloseSocket(int socket_fd) { + if (socket_fd >= 0) { + (void)close(socket_fd); + } +} + +bool SendAll(int socket_fd, const void *data, size_t bytes) { + const auto *current = static_cast(data); + while (bytes > 0) { + const ssize_t sent = send(socket_fd, current, bytes, MSG_NOSIGNAL); + if (sent < 0 && errno == EINTR) { + continue; + } + if (sent <= 0) { + return false; + } + current += sent; + bytes -= static_cast(sent); + } + return true; +} + +bool ReceiveAll(int socket_fd, void *data, size_t bytes) { + auto *current = static_cast(data); + while (bytes > 0) { + const ssize_t received = recv(socket_fd, current, bytes, 0); + if (received < 0 && errno == EINTR) { + continue; + } + if (received <= 0) { + return false; + } + current += received; + bytes -= static_cast(received); + } + return true; +} + +int CreateControlListener(const char *address, uint16_t port) { + const int socket_fd = socket(AF_INET, SOCK_STREAM, 0); + if (socket_fd < 0) { + return -1; + } + + int reuse = 1; + if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) != + 0) { + CloseSocket(socket_fd); + return -1; + } + + sockaddr_in endpoint{}; + endpoint.sin_family = AF_INET; + endpoint.sin_port = htons(port); + if (inet_pton(AF_INET, address, &endpoint.sin_addr) != 1) { + CloseSocket(socket_fd); + return -1; + } + + if (bind(socket_fd, reinterpret_cast(&endpoint), + sizeof(endpoint)) != 0 || + listen(socket_fd, 1) != 0) { + CloseSocket(socket_fd); + return -1; + } + + return socket_fd; +} + +int ConnectControl(const char *address, uint16_t port) { + const int socket_fd = socket(AF_INET, SOCK_STREAM, 0); + if (socket_fd < 0) { + return -1; + } + + sockaddr_in endpoint{}; + endpoint.sin_family = AF_INET; + endpoint.sin_port = htons(port); + if (inet_pton(AF_INET, address, &endpoint.sin_addr) != 1 || + connect(socket_fd, reinterpret_cast(&endpoint), + sizeof(endpoint)) != 0) { + CloseSocket(socket_fd); + return -1; + } + + return socket_fd; +} + +int AcceptControl(int listener) { + pollfd descriptor{listener, POLLIN, 0}; + int result; + do { + result = poll(&descriptor, 1, kControlTimeoutMs); + } while (result < 0 && errno == EINTR); + if (result <= 0 || !(descriptor.revents & POLLIN)) { + return -1; + } + return accept(listener, nullptr, nullptr); +} + +bool ParsePort(const char *value, uint16_t *port) { + char *end = nullptr; + errno = 0; + const unsigned long parsed = std::strtoul(value, &end, 10); + if (errno != 0 || end == value || *end != '\0' || parsed == 0 || + parsed > 65535) { + return false; + } + + *port = static_cast(parsed); + return true; +} + +bool ParseCount(const char *value, size_t *count) { + char *end = nullptr; + errno = 0; + const unsigned long long parsed = std::strtoull(value, &end, 10); + if (errno != 0 || end == value || *end != '\0' || parsed == 0 || + parsed > 262144 || value[0] == '-') { + return false; + } + + *count = static_cast(parsed); + return true; +} + +bool CheckBuffer(const std::vector &buffer, int expected_rank, + size_t iteration) { + for (size_t i = 0; i < buffer.size(); ++i) { + const int32_t expected = + static_cast(expected_rank * 1000000 + iteration + i); + if (buffer[i] != expected) { + std::cerr << "[Check] Mismatch at index " << i << ": expected " + << expected << ", actual " << buffer[i] << std::endl; + return false; + } + } + return true; +} + +bool CheckInfini(infinicclResult_t result, const char *operation) { + if (result == infinicclSuccess) { + return true; + } + + std::cerr << "[InfiniCCL Error] " << operation << " returned " << result + << "." << std::endl; + return false; +} + +#if defined(INFINICCL_WITH_NVIDIA_IBV) +using GpuRuntime = infini::ccl::Runtime; +using GpuError = cudaError_t; +using GpuStream = cudaStream_t; +using GpuUuid = cudaUUID_t; +constexpr auto kGpuSuccess = cudaSuccess; +constexpr auto GpuGetErrorString = cudaGetErrorString; +constexpr auto GpuStreamCreate = cudaStreamCreate; +constexpr auto GpuStreamDestroy = cudaStreamDestroy; +constexpr const char *kGpuName = "NVIDIA"; + +GpuError GpuGetUuid(GpuUuid *uuid, int device) { + cudaDeviceProp properties{}; + const auto status = cudaGetDeviceProperties(&properties, device); + if (status == cudaSuccess) { + *uuid = properties.uuid; + } + return status; +} +#elif defined(INFINICCL_WITH_METAX_IBV) +using GpuRuntime = infini::ccl::Runtime; +using GpuError = mcError_t; +using GpuStream = mcStream_t; +using GpuUuid = mcUuid_t; +constexpr auto kGpuSuccess = mcSuccess; +constexpr auto GpuGetErrorString = mcGetErrorString; +constexpr auto GpuGetUuid = mcDeviceGetUuid; +constexpr auto GpuStreamCreate = mcStreamCreate; +constexpr auto GpuStreamDestroy = mcStreamDestroy; +constexpr const char *kGpuName = "MetaX"; +#endif + +#if defined(INFINICCL_IBV_GPU) +bool CheckGpu(GpuError status, const char *operation) { + return CheckInfini(static_cast(GpuRuntime::Check(status)), + operation); +} + +void PrintGpuDevice(int rank) { + int current_device = -1; + if (!CheckGpu(GpuRuntime::GetDevice(¤t_device), "GetDevice")) { + return; + } + GpuUuid uuid{}; + const auto status = GpuGetUuid(&uuid, current_device); + if (status != kGpuSuccess) { + std::cerr << "[Rank " << rank << "] " << kGpuName + << " GPU device=" << current_device + << ", UUID unavailable: " << GpuGetErrorString(status) + << std::endl; + return; + } + char uuid_text[sizeof(uuid) * 2 + 1]{}; + const auto *bytes = reinterpret_cast(&uuid); + for (size_t i = 0; i < sizeof(uuid); ++i) { + std::snprintf(uuid_text + i * 2, 3, "%02x", + static_cast(bytes[i])); + } + std::cout << "[Rank " << rank << "] GPU UUID(raw)=" << uuid_text << std::endl; +} + +#endif + +void PrintDeviceInfo(int rank, int device, const std::string &memory_mode) { + char hostname[256]{}; + (void)gethostname(hostname, sizeof(hostname)); + std::cout << "[Rank " << rank << "] Host: " << hostname + << " | GPU: " << kDeviceName << " | Device " << device + << " | Memory: " << memory_mode << std::endl; +#if defined(INFINICCL_IBV_GPU) + PrintGpuDevice(rank); +#endif +} + +void PrintTestSummary(size_t count, size_t iterations, + const std::string &memory_mode) { + const size_t total_bytes = count * sizeof(int32_t); + std::cout << "\n=== Performing IBV Send/Recv ===" << std::endl; + std::cout << "Sender rank: " << kSenderRank << std::endl; + std::cout << "Receiver rank: " << kReceiverRank << std::endl; + std::cout << "Data size: " << count << " int32 elements (" << total_bytes + << " bytes)" << std::endl; + std::cout << "Iterations: " << iterations << std::endl; + std::cout << "Memory mode: " << memory_mode << std::endl; +} + +void PrintResult(int rank, const std::vector &buffer, int peer_rank, + size_t iteration) { + const int32_t expected = + static_cast(peer_rank * 1000000 + iteration); + std::cout << "\n=== Send/Recv Results ===" << std::endl; + std::cout << "Rank: " << rank << std::endl; + std::cout << "Peer rank: " << peer_rank << std::endl; + std::cout << "Iteration: " << iteration << std::endl; + std::cout << "Correct: \033[32mYES\033[0m" << std::endl; + std::cout << "Expect: " << expected << std::endl; + std::cout << "Actual: " << buffer[0] << std::endl; +} + +class ExampleBuffer { + public: + explicit ExampleBuffer(std::vector *host) : host_(host) {} + + ~ExampleBuffer() { +#if defined(INFINICCL_IBV_GPU) + if (device_) { + (void)GpuRuntime::StreamSynchronize(stream_); + (void)GpuRuntime::Free(device_); + } + if (stream_) { + (void)GpuStreamDestroy(stream_); + } +#endif + } + + bool Initialize(const std::string &mode) { + if (mode == "host") { + return true; + } +#if defined(INFINICCL_IBV_GPU) + return CheckGpu(GpuRuntime::Malloc(&device_, Bytes()), "Malloc") && + CheckGpu(GpuStreamCreate(&stream_), "StreamCreate"); +#else + std::cerr << "Device buffers require a NVIDIA or MetaX + IBV build." + << std::endl; + return false; +#endif + } + + bool Upload() { +#if defined(INFINICCL_IBV_GPU) + if (device_) { + return CheckGpu(GpuRuntime::Memcpy(device_, host_->data(), Bytes(), + GpuRuntime::MemcpyHostToDevice), + "Memcpy(H2D)"); + } +#endif + return true; + } + + bool Download() { +#if defined(INFINICCL_IBV_GPU) + if (device_) { + if (!Synchronize()) { + return false; + } + return CheckGpu(GpuRuntime::Memcpy(host_->data(), device_, Bytes(), + GpuRuntime::MemcpyDeviceToHost), + "Memcpy(D2H validation)"); + } +#endif + return true; + } + + bool Synchronize() { +#if defined(INFINICCL_IBV_GPU) + if (device_) { + return CheckGpu(GpuRuntime::StreamSynchronize(stream_), + "StreamSynchronize"); + } +#endif + return true; + } + + void *data() { return device_ ? device_ : host_->data(); } + + void *stream() { +#if defined(INFINICCL_IBV_GPU) + return reinterpret_cast(stream_); +#else + return nullptr; +#endif + } + + private: + size_t Bytes() const { return host_->size() * sizeof(int32_t); } + + std::vector *host_; + + void *device_ = nullptr; + +#if defined(INFINICCL_IBV_GPU) + GpuStream stream_ = nullptr; +#endif +}; + +bool ExchangeUniqueId(bool server, const char *control_address, + uint16_t control_port, infinicclUniqueId *id) { + int listener = -1; + int connection = -1; + if (server) { + listener = CreateControlListener(control_address, control_port); + if (listener < 0) { + std::cerr << "[Control] Failed to listen on " << control_address << ':' + << control_port << "." << std::endl; + return false; + } + + std::cout << "[Control] Waiting for rank 1 on " << control_address << ':' + << control_port << "..." << std::endl; + connection = AcceptControl(listener); + CloseSocket(listener); + if (connection < 0) { + std::cerr << "[Control] Failed to accept rank 1 within the control " + "timeout." + << std::endl; + return false; + } + + const bool success = SendAll(connection, id, sizeof(*id)); + CloseSocket(connection); + return success; + } + + const auto deadline = std::chrono::steady_clock::now() + + std::chrono::milliseconds(kControlTimeoutMs); + do { + connection = ConnectControl(control_address, control_port); + if (connection >= 0) { + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } while (std::chrono::steady_clock::now() < deadline); + if (connection < 0) { + std::cerr << "[Control] Failed to connect to " << control_address << ':' + << control_port << "." << std::endl; + return false; + } + + const bool success = ReceiveAll(connection, id, sizeof(*id)); + CloseSocket(connection); + return success; +} + +struct Session { + infinicclComm_t comm = nullptr; + + ~Session() { + if (comm) { + (void)infinicclCommDestroy(comm); + } + (void)infinicclFinalize(); + } +}; + +int Run(bool server, const char *bootstrap_address, const char *control_address, + uint16_t control_port, size_t count, size_t iterations, + const std::string &memory_mode, int device) { +#if defined(INFINICCL_IBV_GPU) + if (!CheckGpu(GpuRuntime::SetDevice(device), "SetDevice")) { + return EXIT_FAILURE; + } +#else + (void)device; + if (memory_mode != "host") { + std::cerr << "Device buffers require a NVIDIA or MetaX + IBV build." + << std::endl; + return EXIT_FAILURE; + } +#endif + if (server && setenv("INFINICCL_IBV_ADDR", bootstrap_address, 1) != 0) { + std::cerr << "[Setup] Failed to set `INFINICCL_IBV_ADDR`." << std::endl; + return EXIT_FAILURE; + } + + const char *configured_port = std::getenv("INFINICCL_IBV_PORT"); + const std::string ibv_port = + configured_port ? configured_port : std::to_string(kDefaultIbvPort); + uint16_t bootstrap_port = 0; + if (!ParsePort(ibv_port.c_str(), &bootstrap_port) || + bootstrap_port == control_port) { + std::cerr << "The bootstrap port must be valid and distinct from the " + "Unique ID control port." + << std::endl; + return EXIT_FAILURE; + } + if (server && setenv("INFINICCL_IBV_PORT", ibv_port.c_str(), 1) != 0) { + std::cerr << "[Setup] Failed to set `INFINICCL_IBV_PORT`." << std::endl; + return EXIT_FAILURE; + } + + int argc = 1; + char program_name[] = "ibv_send_recv"; + char *init_argv[] = {program_name, nullptr}; + char **init_argv_pointer = init_argv; + if (!CheckInfini(infinicclInit(&argc, &init_argv_pointer), "infinicclInit")) { + return EXIT_FAILURE; + } + Session session; + + const int rank = server ? kSenderRank : kReceiverRank; + PrintDeviceInfo(rank, device, memory_mode); + std::vector send_buffer(count); + std::vector recv_buffer(count, -1); + ExampleBuffer send_memory(&send_buffer); + ExampleBuffer recv_memory(&recv_buffer); + for (size_t i = 0; i < count; ++i) { + send_buffer[i] = static_cast(rank * 1000000 + i); + } + if (!send_memory.Initialize(memory_mode) || + !recv_memory.Initialize(memory_mode) || !send_memory.Upload() || + !send_memory.Synchronize() || !recv_memory.Upload() || + !recv_memory.Download()) { + return EXIT_FAILURE; + } +#if defined(INFINICCL_IBV_GPU) + if (!CheckGpu(GpuRuntime::StreamSynchronize(nullptr), + "StreamSynchronize(default warm-up)")) { + return EXIT_FAILURE; + } +#endif + + infinicclUniqueId id{}; + if (server) { + if (!CheckInfini(infinicclGetUniqueId(&id), "infinicclGetUniqueId")) { + return EXIT_FAILURE; + } + std::cout << "[Rank 0] Generated TCP bootstrap ID for " << bootstrap_address + << ':' << ibv_port << ". Payloads use verbs, not TCP." + << std::endl; + } + + if (!ExchangeUniqueId(server, control_address, control_port, &id)) { + std::cerr << "[Control] Unique ID exchange failed." << std::endl; + return EXIT_FAILURE; + } + + if (!server) { + std::cout << "[Rank 1] Received IBV unique ID." << std::endl; + } + + if (!CheckInfini(infinicclCommInitRank(&session.comm, kRankCount, id, rank), + "infinicclCommInitRank")) { + return EXIT_FAILURE; + } + std::cout << "[Rank " << rank << "] IBV communicator initialized." + << std::endl; + const infinicclComm_t comm = session.comm; + + if (rank == kSenderRank) { + PrintTestSummary(count, iterations, memory_mode); + } + for (size_t iteration = 0; iteration < iterations; ++iteration) { + std::fill(recv_buffer.begin(), recv_buffer.end(), -1); + for (size_t i = 0; i < count; ++i) { + send_buffer[i] = static_cast(rank * 1000000 + iteration + i); + } + if (!send_memory.Upload() || !recv_memory.Upload()) { + return EXIT_FAILURE; + } + + if (server) { + if (!CheckInfini(infinicclRecv(recv_memory.data(), count, infinicclInt32, + kReceiverRank, comm, recv_memory.stream()), + "infinicclRecv")) { + return EXIT_FAILURE; + } + if (!recv_memory.Download()) { + return EXIT_FAILURE; + } + if (!CheckBuffer(recv_buffer, kReceiverRank, iteration)) { + return EXIT_FAILURE; + } + + if (!CheckInfini(infinicclSend(send_memory.data(), count, infinicclInt32, + kReceiverRank, comm, send_memory.stream()), + "infinicclSend")) { + return EXIT_FAILURE; + } + } else { + if (!CheckInfini(infinicclSend(send_memory.data(), count, infinicclInt32, + kSenderRank, comm, send_memory.stream()), + "infinicclSend")) { + return EXIT_FAILURE; + } + + if (!CheckInfini(infinicclRecv(recv_memory.data(), count, infinicclInt32, + kSenderRank, comm, recv_memory.stream()), + "infinicclRecv")) { + return EXIT_FAILURE; + } + if (!recv_memory.Download()) { + return EXIT_FAILURE; + } + if (!CheckBuffer(recv_buffer, kSenderRank, iteration)) { + return EXIT_FAILURE; + } + } + } + + // Rank 0 waits until rank 1 has verified the final reply before teardown. + int32_t verified = 1; + const auto ack_status = + server ? infinicclRecv(&verified, 1, infinicclInt32, 1, comm, nullptr) + : infinicclSend(&verified, 1, infinicclInt32, 0, comm, nullptr); + if (!CheckInfini(ack_status, "Final verification acknowledgement") || + verified != 1) { + return EXIT_FAILURE; + } + + if (!CheckInfini(infinicclCommDestroy(comm), "infinicclCommDestroy")) { + return EXIT_FAILURE; + } + session.comm = nullptr; + + PrintResult(rank, recv_buffer, 1 - rank, iterations - 1); + if (rank == kSenderRank) { + std::cout << "InfiniCCL finalized." << std::endl; + } + return EXIT_SUCCESS; +} + +} // namespace + +int main(int argc, char **argv) { + if (argc >= 2 && std::string(argv[1]) == "auto") { + const char *rank = std::getenv("OMPI_COMM_WORLD_RANK"); + const char *size = std::getenv("OMPI_COMM_WORLD_SIZE"); + if (!rank || !size || std::string(size) != "2" || + (std::string(rank) != "0" && std::string(rank) != "1")) { + std::cerr << "The `auto` mode requires exactly two OpenMPI processes." + << std::endl; + return EXIT_FAILURE; + } + static char server_role[] = "server"; + static char client_role[] = "client"; + argv[1] = std::string(rank) == "0" ? server_role : client_role; + } + + if (argc < 4 || argc > 8 || + (std::string(argv[1]) != "server" && std::string(argv[1]) != "client")) { + std::cerr << "Usage: " << argv[0] + << " server [count] [iterations] " + "[memory] [gpu]\n" + << " " << argv[0] + << " client [count] [iterations] " + "[memory] [gpu]\n" + << " " << argv[0] + << " auto [count] [iterations] " + "[memory] [gpu]\n"; + return EXIT_FAILURE; + } + + uint16_t control_port = 0; + if (!ParsePort(argv[3], &control_port)) { + std::cerr << "Invalid control port: " << argv[3] << "." << std::endl; + return EXIT_FAILURE; + } + + size_t count = 8; + if (argc >= 5 && !ParseCount(argv[4], &count)) { + std::cerr << "Invalid element count: " << argv[4] << "." << std::endl; + return EXIT_FAILURE; + } + size_t iterations = 1; + if (argc >= 6 && (!ParseCount(argv[5], &iterations) || iterations > 1000)) { + std::cerr << "Iteration count must be between 1 and 1000." << std::endl; + return EXIT_FAILURE; + } + const std::string memory_mode = argc >= 7 ? argv[6] : "host"; + if (memory_mode != "host" && memory_mode != "device") { + std::cerr << "Memory mode must be host or device." << std::endl; + return EXIT_FAILURE; + } + int device = 0; + if (argc == 8) { + char *end = nullptr; + errno = 0; + const long parsed = std::strtol(argv[7], &end, 10); + if (errno || end == argv[7] || *end || parsed < 0 || parsed > 255) { + std::cerr << "Invalid GPU device index." << std::endl; + return EXIT_FAILURE; + } + device = static_cast(parsed); + } + + const bool server = std::string(argv[1]) == "server"; + const char *bootstrap_address = argv[2]; + const char *control_address = argv[2]; + return Run(server, bootstrap_address, control_address, control_port, count, + iterations, memory_mode, device); +} diff --git a/scripts/gen_bridge.py b/scripts/gen_bridge.py index a472c05..8f5a57e 100644 --- a/scripts/gen_bridge.py +++ b/scripts/gen_bridge.py @@ -34,6 +34,7 @@ "mccl": ["backends/ccl/mccl/impl"], "cncl": ["backends/ccl/cncl/impl"], "hccl": ["backends/ccl/hccl/impl"], + "ibv": ["backends/ibv/impl"], } BACKEND_COMMON_HEADERS = { diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index affb03f..39e9d99 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -43,6 +43,7 @@ target_sources(infiniccl PRIVATE # CPU (Always On as the base architecture) file(GLOB_RECURSE CPU_SRCS "devices/cpu/*.cc") +list(FILTER CPU_SRCS EXCLUDE REGEX "ibv_memory\\.cc$") target_sources(infiniccl PRIVATE ${CPU_SRCS}) # NVIDIA @@ -58,6 +59,7 @@ if(WITH_NVIDIA) "devices/nvidia/*.cu" ) file(GLOB NVIDIA_SOURCES ${NVIDIA_PATTERNS}) + list(FILTER NVIDIA_SOURCES EXCLUDE REGEX "ibv_memory\\.cc$") target_sources(infiniccl PRIVATE ${NVIDIA_SOURCES}) target_link_libraries(infiniccl PRIVATE CUDA::cudart CUDA::cuda_driver) @@ -129,6 +131,7 @@ if(WITH_METAX) "devices/metax/*.maca" ) file(GLOB METAX_SOURCES ${METAX_PATTERNS}) + list(FILTER METAX_SOURCES EXCLUDE REGEX "ibv_memory\\.cc$") set_source_files_properties(${METAX_SOURCES} PROPERTIES LANGUAGE CXX) @@ -282,6 +285,71 @@ if(WITH_OMPI) endif() endif() +# IBV +if(WITH_IBV) + list(APPEND BACKEND_LIST "ibv") + file(GLOB_RECURSE IBV_SRCS + "backends/ibv/*.cc" + "backends/ibv/*.cpp" + ) + target_sources(infiniccl PRIVATE ${IBV_SRCS} devices/cpu/ibv_memory.cc) + target_include_directories(infiniccl PRIVATE + ${IBVERBS_INCLUDE_DIR} + ) + target_link_libraries(infiniccl PRIVATE + ${IBVERBS_LIBRARY} + Threads::Threads + ) + find_path(MLX5DV_INCLUDE_DIR NAMES infiniband/mlx5dv.h) + find_library(MLX5DV_LIBRARY NAMES mlx5) + if(MLX5DV_INCLUDE_DIR AND MLX5DV_LIBRARY) + include(CMakePushCheckState) + include(CheckCXXSourceCompiles) + cmake_push_check_state(RESET) + set(CMAKE_REQUIRED_INCLUDES ${MLX5DV_INCLUDE_DIR} ${IBVERBS_INCLUDE_DIR}) + set(CMAKE_REQUIRED_LIBRARIES ${MLX5DV_LIBRARY} ${IBVERBS_LIBRARY}) + check_cxx_source_compiles(" + #include + int main() { + ibv_qp_init_attr_ex attr{}; + mlx5dv_qp_init_attr mlx5_attr{}; + attr.comp_mask = IBV_QP_INIT_ATTR_PD; + mlx5_attr.comp_mask = MLX5DV_QP_INIT_ATTR_MASK_QP_CREATE_FLAGS; + mlx5_attr.create_flags = MLX5DV_QP_CREATE_DISABLE_SCATTER_TO_CQE; + auto *qp = mlx5dv_create_qp(nullptr, &attr, &mlx5_attr); + return mlx5dv_is_supported(nullptr) && qp ? 0 : 1; + } + " INFINICCL_HAS_MLX5DV_SCATTER_CONTROL) + cmake_pop_check_state() + endif() + if(MLX5DV_INCLUDE_DIR AND MLX5DV_LIBRARY AND + INFINICCL_HAS_MLX5DV_SCATTER_CONTROL) + target_include_directories(infiniccl PRIVATE ${MLX5DV_INCLUDE_DIR}) + target_link_libraries(infiniccl PRIVATE ${MLX5DV_LIBRARY}) + target_compile_definitions(infiniccl PRIVATE INFINICCL_WITH_MLX5DV) + message(STATUS "IBV: per-QP mlx5 Scatter-to-CQE disabling enabled.") + else() + message(STATUS "IBV: mlx5dv unavailable; Mellanox QPs will be rejected for safety.") + endif() + if(WITH_NVIDIA) + if(CUDAToolkit_VERSION VERSION_LESS 11.3) + message(FATAL_ERROR "NVIDIA IBV backend requires CUDA 11.3 or newer for visibility capability checks.") + endif() + target_sources(infiniccl PRIVATE devices/nvidia/ibv_memory.cc) + target_compile_definitions(infiniccl PRIVATE INFINICCL_WITH_NVIDIA_IBV) + endif() + if(WITH_METAX) + find_path(METAX_IBV_INCLUDE_DIR NAMES mxkw/mxkw.h + HINTS "${MACA_PATH}/include" REQUIRED) + find_library(METAX_IBV_LIBRARY NAMES mxkw + HINTS "${MACA_PATH}/lib" "${MACA_PATH}/lib64" REQUIRED) + target_sources(infiniccl PRIVATE devices/metax/ibv_memory.cc) + target_include_directories(infiniccl PRIVATE ${METAX_IBV_INCLUDE_DIR}) + target_link_libraries(infiniccl PRIVATE ${METAX_IBV_LIBRARY}) + target_compile_definitions(infiniccl PRIVATE INFINICCL_WITH_METAX_IBV) + endif() +endif() + if(WITH_MPICH) list(APPEND BACKEND_LIST "mpich") # Note: MPICH shares the same internal implementation as OMPI, so we reuse the `ompi/impl` sources for both. diff --git a/src/backend.h b/src/backend.h index c48c744..b8508a8 100644 --- a/src/backend.h +++ b/src/backend.h @@ -15,13 +15,14 @@ enum class BackendType : int8_t { kRccl = 4, kCncl = 5, kHccl = 6, + kIbv = 7, kCount }; using AllBackendTypes = List; + BackendType::kHccl, BackendType::kIbv>; template struct BackendEnabled : std::false_type {}; @@ -53,6 +54,11 @@ struct BackendPriority { static constexpr int value = 1; }; +template <> +struct BackendPriority { + static constexpr int value = 2; +}; + template <> struct BackendPriority { static constexpr int value = 10; diff --git a/src/backend_device_map.h b/src/backend_device_map.h index dfb8ad1..9d9af05 100644 --- a/src/backend_device_map.h +++ b/src/backend_device_map.h @@ -13,6 +13,19 @@ struct IsSupportedCombination : std::false_type {}; template struct IsSupportedCombination : std::true_type {}; +// Memory adapters validate the actual buffer and local device capabilities. +template <> +struct IsSupportedCombination + : std::true_type {}; + +template <> +struct IsSupportedCombination + : std::true_type {}; + +template <> +struct IsSupportedCombination + : std::true_type {}; + template <> struct IsSupportedCombination : std::true_type {}; diff --git a/src/backends/ibv/comm_instance.cc b/src/backends/ibv/comm_instance.cc new file mode 100644 index 0000000..5fa99b1 --- /dev/null +++ b/src/backends/ibv/comm_instance.cc @@ -0,0 +1,759 @@ +#include "backends/ibv/comm_instance.h" + +#include +#include +#include +#include +#include +#include + +#if defined(INFINICCL_WITH_MLX5DV) +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "backends/ibv/memory_adaptor.h" +#include "logging.h" + +namespace infini::ccl { + +struct IbvResources { + ibv_context *context = nullptr; + + ibv_pd *pd = nullptr; + + ibv_cq *send_cq = nullptr; + + ibv_cq *recv_cq = nullptr; + + ibv_qp *qp = nullptr; + + ibv_port_attr port_attr{}; + + ibv_gid gid{}; + + int socket = -1; + + int rank = -1; + + int port = 1; + + int gid_index = -1; + + int pkey_index = 0; + + size_t max_bytes = 0; + + IbvMrCache mr_cache; + + std::mutex mutex; +}; + +namespace { + +constexpr int kTimeoutMs = 30000; + +// A verbs scatter-gather entry carries its byte length as a 32-bit value. +constexpr size_t kMaxSgeBytes = std::numeric_limits::max(); + +struct PeerMetadata { + uint32_t rank; + + uint32_t qp_num; + + uint32_t lid; + + uint32_t mtu; + + uint32_t link_layer; + + uint32_t has_gid; + + uint32_t max_bytes; + + uint32_t pkey; + + uint8_t gid[16]; + + char group_id[INFINICCL_IBV_GROUP_ID_BYTES]; +}; + +static_assert(sizeof(PeerMetadata) == + 8 * sizeof(uint32_t) + 16 + INFINICCL_IBV_GROUP_ID_BYTES, + "`PeerMetadata` must not contain padding."); + +ReturnStatus WaitForIbvCompletion(ibv_cq *cq, bool receive, + size_t expected_bytes) { + const auto deadline = + std::chrono::steady_clock::now() + std::chrono::seconds(30); + while (std::chrono::steady_clock::now() < deadline) { + ibv_wc completion{}; + const int count = ibv_poll_cq(cq, 1, &completion); + if (count < 0) { + LOG("Failed to poll the IBV completion queue."); + return ReturnStatus::kSystemError; + } + if (count == 0) { + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + continue; + } + if (completion.status != IBV_WC_SUCCESS) { + std::cerr << "IBV completion failed: " + << ibv_wc_status_str(completion.status) + << ", vendor error: " << completion.vendor_err << ".\n"; + return ReturnStatus::kRemoteError; + } + if (completion.wr_id != 1 || + completion.opcode != (receive ? IBV_WC_RECV : IBV_WC_SEND) || + (receive && completion.byte_len != expected_bytes)) { + LOG("Unexpected IBV completion or message size."); + return ReturnStatus::kRemoteError; + } + return ReturnStatus::kSuccess; + } + LOG("Timed out while waiting for an IBV completion."); + return ReturnStatus::kSystemError; +} + +ReturnStatus ReportVerbsError(const char *operation, int error) { + std::cerr << "IBV operation `" << operation + << "` failed: " << std::strerror(error) << " (" << error << ").\n"; + return ReturnStatus::kSystemError; +} + +bool ReadOption(const char *name, int default_value, int minimum, int maximum, + int *result) { + const char *value = std::getenv(name); + if (!value) { + *result = default_value; + return true; + } + char *end = nullptr; + errno = 0; + const long parsed = std::strtol(value, &end, 10); + if (errno || end == value || *end || parsed < minimum || parsed > maximum) { + std::cerr << "Invalid option `" << name << "`.\n"; + return false; + } + *result = static_cast(parsed); + return true; +} + +bool WaitSocket(int fd, short events, int timeout_ms) { + pollfd descriptor{fd, events, 0}; + int result; + do { + result = poll(&descriptor, 1, timeout_ms); + } while (result < 0 && errno == EINTR); + return result > 0 && (descriptor.revents & events); +} + +int AcceptBootstrap(int fd, const addrinfo &address) { + const int reuse = 1; + (void)setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)); + if (bind(fd, address.ai_addr, address.ai_addrlen) != 0 || + listen(fd, 1) != 0 || !WaitSocket(fd, POLLIN, kTimeoutMs)) { + return -1; + } + return accept4(fd, nullptr, nullptr, SOCK_NONBLOCK); +} + +bool ConnectBootstrap(int fd, const addrinfo &address) { + if (connect(fd, address.ai_addr, address.ai_addrlen) == 0) { + return true; + } + if (errno != EINPROGRESS || !WaitSocket(fd, POLLOUT, 200)) { + return false; + } + int error = 0; + socklen_t length = sizeof(error); + return getsockopt(fd, SOL_SOCKET, SO_ERROR, &error, &length) == 0 && + error == 0; +} + +int TryBootstrapAddresses(const addrinfo *addresses, bool server) { + for (auto *address = addresses; address; address = address->ai_next) { + const int fd = socket(address->ai_family, SOCK_STREAM | SOCK_NONBLOCK, + address->ai_protocol); + if (fd < 0) { + continue; + } + if (!server && ConnectBootstrap(fd, *address)) { + return fd; + } + const int connection = server ? AcceptBootstrap(fd, *address) : -1; + close(fd); + if (connection >= 0) { + return connection; + } + } + return -1; +} + +int OpenBootstrap(const IbvUniqueId &id, bool server) { + addrinfo hints{}; + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = server ? AI_PASSIVE : 0; + addrinfo *addresses = nullptr; + const std::string service = std::to_string(id.port); + if (getaddrinfo(id.address, service.c_str(), &hints, &addresses) != 0) { + return -1; + } + const auto deadline = + std::chrono::steady_clock::now() + std::chrono::milliseconds(kTimeoutMs); + int connection = -1; + do { + connection = TryBootstrapAddresses(addresses, server); + if (server || connection >= 0) { + break; + } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + } while (std::chrono::steady_clock::now() < deadline); + freeaddrinfo(addresses); + return connection; +} + +ReturnStatus TransferControl(int socket, size_t bytes, bool receive, + void *data) { + auto *current = static_cast(data); + const auto deadline = + std::chrono::steady_clock::now() + std::chrono::milliseconds(kTimeoutMs); + while (bytes) { + const auto remaining = + std::chrono::duration_cast( + deadline - std::chrono::steady_clock::now()) + .count(); + if (remaining <= 0 || !WaitSocket(socket, receive ? POLLIN : POLLOUT, + static_cast(remaining))) { + LOG("IBV bootstrap/control channel timed out or closed."); + return ReturnStatus::kRemoteError; + } + const ssize_t count = receive ? recv(socket, current, bytes, 0) + : send(socket, current, bytes, MSG_NOSIGNAL); + if (count < 0 && (errno == EINTR || errno == EAGAIN)) { + continue; + } + if (count <= 0) { + LOG("Failed to transfer IBV control metadata."); + return ReturnStatus::kRemoteError; + } + current += count; + bytes -= static_cast(count); + } + return ReturnStatus::kSuccess; +} + +ReturnStatus SelectDevice(IbvResources &resources) { + int count = 0; + ibv_device **devices = ibv_get_device_list(&count); + if (!devices) { + return ReportVerbsError("ibv_get_device_list", errno); + } + const char *name = std::getenv("INFINICCL_IBV_DEVICE"); + for (int i = 0; i < count; ++i) { + if (name && std::strcmp(name, ibv_get_device_name(devices[i])) != 0) { + continue; + } + resources.context = ibv_open_device(devices[i]); + if (!resources.context) { + continue; + } + if (ibv_query_port(resources.context, resources.port, + &resources.port_attr) == 0 && + resources.port_attr.state == IBV_PORT_ACTIVE) { + break; + } + ibv_close_device(resources.context); + resources.context = nullptr; + } + ibv_free_device_list(devices); + if (!resources.context) { + LOG("No selected IBV device has an active port."); + return ReturnStatus::kSystemError; + } + return ReturnStatus::kSuccess; +} + +ReturnStatus ValidatePort(IbvResources &resources) { + if (resources.port_attr.link_layer == IBV_LINK_LAYER_ETHERNET && + resources.gid_index < 0) { + LOG("RoCE requires an explicit `INFINICCL_IBV_GID_INDEX`."); + return ReturnStatus::kInvalidArgument; + } + if ((resources.port_attr.flags & IBV_QPF_GRH_REQUIRED) && + resources.gid_index < 0) { + LOG("This port requires a global route and an explicit GID index."); + return ReturnStatus::kNotSupported; + } + if (resources.pkey_index >= resources.port_attr.pkey_tbl_len || + (resources.gid_index >= 0 && + (resources.gid_index >= resources.port_attr.gid_tbl_len || + ibv_query_gid(resources.context, resources.port, resources.gid_index, + &resources.gid) != 0))) { + return ReturnStatus::kInvalidArgument; + } + return ReturnStatus::kSuccess; +} + +#if defined(INFINICCL_WITH_MLX5DV) +ReturnStatus CreateMlx5QueuePair(const ibv_qp_init_attr &base, + IbvResources &resources) { + ibv_qp_init_attr_ex attr{}; + attr.qp_context = base.qp_context; + attr.send_cq = base.send_cq; + attr.recv_cq = base.recv_cq; + attr.srq = base.srq; + attr.cap = base.cap; + attr.qp_type = base.qp_type; + attr.sq_sig_all = base.sq_sig_all; + attr.comp_mask = IBV_QP_INIT_ATTR_PD; + attr.pd = resources.pd; + mlx5dv_qp_init_attr mlx5_attr{}; + mlx5_attr.comp_mask = MLX5DV_QP_INIT_ATTR_MASK_QP_CREATE_FLAGS; + mlx5_attr.create_flags = MLX5DV_QP_CREATE_DISABLE_SCATTER_TO_CQE; + resources.qp = mlx5dv_create_qp(resources.context, &attr, &mlx5_attr); + if (!resources.qp) { + return ReportVerbsError("mlx5dv_create_qp(disable Scatter-to-CQE)", errno); + } + std::cout << "[Rank " << resources.rank + << "] mlx5 Scatter-to-CQE disabled explicitly for this QP." + << std::endl; + return ReturnStatus::kSuccess; +} +#endif + +ReturnStatus CreateCompatibleQueuePair(ibv_qp_init_attr *attr, + IbvResources &resources) { +#if defined(INFINICCL_WITH_MLX5DV) + if (mlx5dv_is_supported(resources.context->device)) { + return CreateMlx5QueuePair(*attr, resources); + } +#endif + ibv_device_attr device_attr{}; + const int status = ibv_query_device(resources.context, &device_attr); + if (status != 0) { + return ReportVerbsError("ibv_query_device", status); + } + const char *name = ibv_get_device_name(resources.context->device); + if (device_attr.vendor_id == 0x02c9 || std::strncmp(name, "mlx5", 4) == 0) { + LOG("Mellanox QP creation requires mlx5dv Scatter-to-CQE control. " + "Install compatible mlx5 development headers/libraries and rebuild."); + return ReturnStatus::kNotSupported; + } + resources.qp = ibv_create_qp(resources.pd, attr); + if (!resources.qp) { + return ReportVerbsError("ibv_create_qp", errno); + } + return ReturnStatus::kSuccess; +} + +ReturnStatus CreateQueuePair(IbvResources &resources) { + resources.pd = ibv_alloc_pd(resources.context); + resources.send_cq = ibv_create_cq(resources.context, 16, nullptr, nullptr, 0); + resources.recv_cq = ibv_create_cq(resources.context, 16, nullptr, nullptr, 0); + if (!resources.pd || !resources.send_cq || !resources.recv_cq) { + return ReportVerbsError("PD/CQ allocation", errno); + } + ibv_qp_init_attr attr{}; + attr.send_cq = resources.send_cq; + attr.recv_cq = resources.recv_cq; + attr.cap.max_send_wr = 16; + attr.cap.max_recv_wr = 16; + attr.cap.max_send_sge = 1; + attr.cap.max_recv_sge = 1; + attr.qp_type = IBV_QPT_RC; + const auto status = CreateCompatibleQueuePair(&attr, resources); + if (status != ReturnStatus::kSuccess) { + return status; + } + const size_t max_message_bytes = + static_cast(resources.port_attr.max_msg_sz); + if (max_message_bytes == 0 || max_message_bytes > kMaxSgeBytes) { + LOG("The IBV backend requires a positive port message limit no greater " + "than the verbs scatter-gather limit."); + return ReturnStatus::kNotSupported; + } + resources.max_bytes = max_message_bytes; + return ReturnStatus::kSuccess; +} + +ReturnStatus OpenDevice(IbvResources &resources) { + if (!ReadOption("INFINICCL_IBV_IB_PORT", 1, 1, 255, &resources.port) || + !ReadOption("INFINICCL_IBV_GID_INDEX", -1, -1, 255, + &resources.gid_index) || + !ReadOption("INFINICCL_IBV_PKEY_INDEX", 0, 0, 65535, + &resources.pkey_index)) { + return ReturnStatus::kInvalidArgument; + } + auto status = SelectDevice(resources); + if (status == ReturnStatus::kSuccess) { + status = ValidatePort(resources); + } + if (status == ReturnStatus::kSuccess) { + status = CreateQueuePair(resources); + } + if (status == ReturnStatus::kSuccess) { + std::cout << "[Rank " << resources.rank << "] IBV device: " + << ibv_get_device_name(resources.context->device) + << ", port: " << resources.port + << ", LID: " << resources.port_attr.lid + << ", GID index: " << resources.gid_index << "." << std::endl; + } + return status; +} + +ReturnStatus BuildPeerMetadata(const IbvResources &resources, + const IbvUniqueId &id, PeerMetadata *local) { + uint16_t pkey = 0; + if (ibv_query_pkey(resources.context, resources.port, resources.pkey_index, + &pkey) != 0 || + (ntohs(pkey) & 0x7fff) == 0) { + return ReturnStatus::kInvalidArgument; + } + local->rank = htonl(resources.rank); + local->qp_num = htonl(resources.qp->qp_num); + local->lid = htonl(resources.port_attr.lid); + local->mtu = htonl(resources.port_attr.active_mtu); + local->link_layer = htonl(resources.port_attr.link_layer); + local->has_gid = htonl(resources.gid_index >= 0); + local->max_bytes = htonl(resources.max_bytes); + local->pkey = htonl(ntohs(pkey)); + std::memcpy(local->gid, resources.gid.raw, sizeof(local->gid)); + std::memcpy(local->group_id, id.group_id, sizeof(local->group_id)); + return ReturnStatus::kSuccess; +} + +ReturnStatus ValidatePeerMetadata(const IbvResources &resources, + const PeerMetadata &local, + const PeerMetadata &remote) { + if (ntohl(remote.rank) != static_cast(1 - resources.rank) || + remote.link_layer != local.link_layer || + remote.has_gid != local.has_gid || + (ntohl(remote.pkey) & 0x7fff) != (ntohl(local.pkey) & 0x7fff) || + std::memcmp(remote.group_id, local.group_id, sizeof(remote.group_id)) != + 0 || + ntohl(remote.qp_num) == 0 || ntohl(remote.qp_num) > 0xffffff || + ntohl(remote.lid) > 65535 || + (resources.gid_index < 0 && ntohl(remote.lid) == 0) || + ntohl(remote.mtu) < IBV_MTU_256 || ntohl(remote.mtu) > IBV_MTU_4096 || + ntohl(remote.max_bytes) == 0) { + LOG("Incompatible IBV peer metadata or communication group."); + return ReturnStatus::kRemoteError; + } + return ReturnStatus::kSuccess; +} + +ReturnStatus InitializeQueuePair(const IbvResources &resources) { + ibv_qp_attr attr{}; + attr.qp_state = IBV_QPS_INIT; + attr.port_num = resources.port; + attr.pkey_index = resources.pkey_index; + const int status = ibv_modify_qp( + resources.qp, &attr, + IBV_QP_STATE | IBV_QP_PKEY_INDEX | IBV_QP_PORT | IBV_QP_ACCESS_FLAGS); + return status == 0 ? ReturnStatus::kSuccess + : ReportVerbsError("ibv_modify_qp(INIT)", status); +} + +ReturnStatus ReadyToReceive(const IbvResources &resources, + const PeerMetadata &remote) { + ibv_qp_attr attr{}; + attr.qp_state = IBV_QPS_RTR; + attr.path_mtu = static_cast( + std::min(resources.port_attr.active_mtu, ntohl(remote.mtu))); + attr.dest_qp_num = ntohl(remote.qp_num); + attr.rq_psn = attr.dest_qp_num & 0xffffff; + attr.max_dest_rd_atomic = 1; + attr.min_rnr_timer = 12; + attr.ah_attr.dlid = ntohl(remote.lid); + attr.ah_attr.port_num = resources.port; + if (resources.gid_index >= 0) { + attr.ah_attr.is_global = 1; + std::memcpy(attr.ah_attr.grh.dgid.raw, remote.gid, + sizeof(attr.ah_attr.grh.dgid.raw)); + attr.ah_attr.grh.sgid_index = resources.gid_index; + attr.ah_attr.grh.hop_limit = 64; + } + const int status = ibv_modify_qp( + resources.qp, &attr, + IBV_QP_STATE | IBV_QP_AV | IBV_QP_PATH_MTU | IBV_QP_DEST_QPN | + IBV_QP_RQ_PSN | IBV_QP_MAX_DEST_RD_ATOMIC | IBV_QP_MIN_RNR_TIMER); + return status == 0 ? ReturnStatus::kSuccess + : ReportVerbsError("ibv_modify_qp(RTR)", status); +} + +ReturnStatus ReadyToSend(const IbvResources &resources) { + ibv_qp_attr attr{}; + attr.qp_state = IBV_QPS_RTS; + attr.sq_psn = resources.qp->qp_num & 0xffffff; + attr.timeout = 14; + attr.retry_cnt = 7; + attr.rnr_retry = 7; + attr.max_rd_atomic = 1; + const int status = ibv_modify_qp( + resources.qp, &attr, + IBV_QP_STATE | IBV_QP_SQ_PSN | IBV_QP_TIMEOUT | IBV_QP_RETRY_CNT | + IBV_QP_RNR_RETRY | IBV_QP_MAX_QP_RD_ATOMIC); + return status == 0 ? ReturnStatus::kSuccess + : ReportVerbsError("ibv_modify_qp(RTS)", status); +} + +ReturnStatus SynchronizeQueuePair(int socket) { + uint32_t ready = htonl(1); + auto status = TransferControl(socket, sizeof(ready), false, &ready); + if (status != ReturnStatus::kSuccess) { + return status; + } + status = TransferControl(socket, sizeof(ready), true, &ready); + if (status != ReturnStatus::kSuccess) { + return status; + } + return ntohl(ready) == 1 ? ReturnStatus::kSuccess + : ReturnStatus::kRemoteError; +} + +ReturnStatus ExchangePeerMetadata(const IbvUniqueId &id, + IbvResources &resources, + PeerMetadata *remote) { + PeerMetadata local{}; + auto status = BuildPeerMetadata(resources, id, &local); + if (status != ReturnStatus::kSuccess) { + return status; + } + status = TransferControl(resources.socket, sizeof(local), false, &local); + if (status != ReturnStatus::kSuccess) { + return status; + } + status = TransferControl(resources.socket, sizeof(*remote), true, remote); + if (status != ReturnStatus::kSuccess) { + return status; + } + status = ValidatePeerMetadata(resources, local, *remote); + if (status == ReturnStatus::kSuccess) { + resources.max_bytes = + std::min(resources.max_bytes, ntohl(remote->max_bytes)); + } + return status; +} + +ReturnStatus ConnectQueuePair(const IbvUniqueId &id, + IbvResources &resources) { + PeerMetadata remote{}; + auto status = ExchangePeerMetadata(id, resources, &remote); + if (status == ReturnStatus::kSuccess) { + status = InitializeQueuePair(resources); + } + if (status == ReturnStatus::kSuccess) { + status = ReadyToReceive(resources, remote); + } + if (status == ReturnStatus::kSuccess) { + status = ReadyToSend(resources); + } + if (status == ReturnStatus::kSuccess) { + status = SynchronizeQueuePair(resources.socket); + } + return status; +} + +void DestroyQueuePair(IbvResources &resources) { + if (resources.qp) { + const int status = ibv_destroy_qp(resources.qp); + if (status != 0) { + std::cerr << __FILE__ << ':' << __LINE__ << " " << __func__ + << ": Failed to destroy the IBV QP safely.\n"; + assert(status == 0 && "Failed to destroy the IBV QP safely."); + std::abort(); + } + resources.qp = nullptr; + } +} + +ReturnStatus PostReceive(ibv_qp *qp, ibv_sge *sge) { + ibv_recv_wr wr{}; + wr.wr_id = 1; + wr.sg_list = sge; + wr.num_sge = 1; + ibv_recv_wr *bad = nullptr; + const int status = ibv_post_recv(qp, &wr, &bad); + return status == 0 ? ReturnStatus::kSuccess + : ReportVerbsError("ibv_post_recv", status); +} + +ReturnStatus PostSend(ibv_qp *qp, ibv_sge *sge) { + ibv_send_wr wr{}; + wr.wr_id = 1; + wr.sg_list = sge; + wr.num_sge = 1; + wr.opcode = IBV_WR_SEND; + wr.send_flags = IBV_SEND_SIGNALED; + ibv_send_wr *bad = nullptr; + const int status = ibv_post_send(qp, &wr, &bad); + return status == 0 ? ReturnStatus::kSuccess + : ReportVerbsError("ibv_post_send", status); +} + +ReturnStatus ExchangeReceiveReady(int socket, size_t bytes, bool receive) { + uint32_t ready_bytes = htonl(static_cast(bytes)); + const auto status = + TransferControl(socket, sizeof(ready_bytes), !receive, &ready_bytes); + if (status != ReturnStatus::kSuccess) { + return status; + } + if (!receive && ntohl(ready_bytes) != bytes) { + LOG("IBV send and receive sizes do not match."); + return ReturnStatus::kRemoteError; + } + return ReturnStatus::kSuccess; +} + +ReturnStatus TransferRegisteredBuffer(const IbvResources &resources, + void *buffer, size_t bytes, ibv_mr *mr, + bool receive) { + ibv_sge sge{}; + sge.addr = reinterpret_cast(buffer); + sge.length = static_cast(bytes); + sge.lkey = mr->lkey; + auto status = + receive ? PostReceive(resources.qp, &sge) : ReturnStatus::kSuccess; + if (status == ReturnStatus::kSuccess) { + status = ExchangeReceiveReady(resources.socket, bytes, receive); + } + if (status == ReturnStatus::kSuccess && !receive) { + status = PostSend(resources.qp, &sge); + } + if (status == ReturnStatus::kSuccess) { + status = WaitForIbvCompletion( + receive ? resources.recv_cq : resources.send_cq, receive, bytes); + } + return status; +} + +ReturnStatus PrepareTransferMemory(Device::Type device, void *buffer, + size_t bytes, void *stream, + std::unique_ptr *adapter) { + auto status = CreateIbvMemoryAdapter(device, adapter); + if (status == ReturnStatus::kSuccess) { + status = (*adapter)->Prepare(buffer, bytes, stream); + } + return status; +} + +} // namespace + +IbvInstance::IbvInstance() : resources_(std::make_unique()) { + type = BackendType::kIbv; +} + +IbvInstance::~IbvInstance() { Destroy(); } + +ReturnStatus IbvInstance::Connect(const IbvUniqueId &id, int rank) { + auto &resources = *resources_; + resources.rank = rank; + auto status = OpenDevice(resources); + if (status == ReturnStatus::kSuccess) { + resources.socket = OpenBootstrap(id, rank == 0); + if (resources.socket < 0) { + std::cerr << "[Rank " << rank << "] TCP bootstrap failed at " + << id.address << ':' << id.port << ".\n"; + status = ReturnStatus::kSystemError; + } + } + if (status == ReturnStatus::kSuccess) { + status = ConnectQueuePair(id, resources); + } + if (status != ReturnStatus::kSuccess) { + LOG("Failed to initialize the TCP bootstrap or verbs RC connection."); + Destroy(); + } else { + std::cout << "[Rank " << rank + << "] Verbs RC QP ready. Maximum message: " << resources.max_bytes + << " bytes." << std::endl; + } + return status; +} + +ReturnStatus IbvInstance::Transfer(void *buffer, size_t bytes, int peer, + bool receive, Device::Type device, + void *stream) { + auto &resources = *resources_; + std::lock_guard lock(resources.mutex); + if (!resources.qp || resources.socket < 0) { + return ReturnStatus::kInvalidUsage; + } + + // TODO: Temporarily supports 2 ranks only. + if (peer != 1 - resources.rank) { + return ReturnStatus::kInvalidArgument; + } + + if (bytes == 0 || bytes > resources.max_bytes) { + LOG("The IBV backend requires messages no larger than the negotiated " + "port and verbs scatter-gather limits."); + Destroy(); + return ReturnStatus::kNotSupported; + } + std::unique_ptr adapter; + ibv_mr *mr = nullptr; + auto status = PrepareTransferMemory(device, buffer, bytes, stream, &adapter); + if (status == ReturnStatus::kSuccess) { + status = resources.mr_cache.Acquire(resources.pd, adapter.get(), buffer, + bytes, &mr); + } + if (status == ReturnStatus::kSuccess) { + status = TransferRegisteredBuffer(resources, buffer, bytes, mr, receive); + } + if (status == ReturnStatus::kSuccess) { + status = adapter->Complete(receive); + } + if (status != ReturnStatus::kSuccess) { + Destroy(); + } + return status; +} + +void IbvInstance::Destroy() { + auto &resources = *resources_; + DestroyQueuePair(resources); + const auto cache_stats = resources.mr_cache.Stats(); + resources.mr_cache.Reset(); + if (cache_stats.acquisitions > 0) { + std::cout << "[Rank " << resources.rank + << "] IBV MR cache: " << cache_stats.registrations + << " registrations for " << cache_stats.acquisitions + << " transfers." << std::endl; + } + if (resources.send_cq) { + ibv_destroy_cq(resources.send_cq); + } + if (resources.recv_cq) { + ibv_destroy_cq(resources.recv_cq); + } + if (resources.pd) { + ibv_dealloc_pd(resources.pd); + } + if (resources.context) { + ibv_close_device(resources.context); + } + if (resources.socket >= 0) { + close(resources.socket); + } + resources.send_cq = nullptr; + resources.recv_cq = nullptr; + resources.pd = nullptr; + resources.context = nullptr; + resources.socket = -1; +} + +} // namespace infini::ccl diff --git a/src/backends/ibv/comm_instance.h b/src/backends/ibv/comm_instance.h new file mode 100644 index 0000000..e65ddee --- /dev/null +++ b/src/backends/ibv/comm_instance.h @@ -0,0 +1,34 @@ +#ifndef INFINI_CCL_BACKENDS_IBV_COMM_INSTANCE_H_ +#define INFINI_CCL_BACKENDS_IBV_COMM_INSTANCE_H_ + +#include +#include + +#include "backends/ibv/ibv_common.h" +#include "communicator.h" +#include "return_status_impl.h" + +namespace infini::ccl { + +struct IbvResources; + +struct IbvInstance : public BackendCommInstance { + IbvInstance(); + + ~IbvInstance() override; + + ReturnStatus Connect(const IbvUniqueId &id, int rank); + + ReturnStatus Transfer(void *buffer, size_t bytes, int peer, bool receive, + Device::Type device = Device::Type::kCpu, + void *stream = nullptr); + + void Destroy(); + + private: + std::unique_ptr resources_; +}; + +} // namespace infini::ccl + +#endif // INFINI_CCL_BACKENDS_IBV_COMM_INSTANCE_H_ diff --git a/src/backends/ibv/ibv_common.h b/src/backends/ibv/ibv_common.h new file mode 100644 index 0000000..57ee267 --- /dev/null +++ b/src/backends/ibv/ibv_common.h @@ -0,0 +1,35 @@ +#ifndef INFINI_CCL_BACKENDS_IBV_IBV_COMMON_H_ +#define INFINI_CCL_BACKENDS_IBV_IBV_COMMON_H_ + +#include + +#include "comm.h" + +#define INFINICCL_IBV_ADDRESS_BYTES 64 +#define INFINICCL_IBV_GROUP_ID_BYTES 16 + +namespace infini::ccl { + +static_assert(INFINICCL_UNIQUE_ID_BYTES >= + sizeof(std::uint16_t) + INFINICCL_IBV_ADDRESS_BYTES + + INFINICCL_IBV_GROUP_ID_BYTES + 1, + "The unique ID must hold the IBV endpoint, group ID and " + "reserved space."); + +struct IbvUniqueId { + std::uint16_t port; + + char address[INFINICCL_IBV_ADDRESS_BYTES]; + + char group_id[INFINICCL_IBV_GROUP_ID_BYTES]; + + char reserved[INFINICCL_UNIQUE_ID_BYTES - sizeof(port) - sizeof(address) - + sizeof(group_id)]; +}; + +static_assert(sizeof(IbvUniqueId) == INFINICCL_UNIQUE_ID_BYTES, + "`IbvUniqueId` must fit in `infinicclUniqueId::internal`."); + +} // namespace infini::ccl + +#endif // INFINI_CCL_BACKENDS_IBV_IBV_COMMON_H_ diff --git a/src/backends/ibv/impl/comm_destroy.h b/src/backends/ibv/impl/comm_destroy.h new file mode 100644 index 0000000..de38184 --- /dev/null +++ b/src/backends/ibv/impl/comm_destroy.h @@ -0,0 +1,40 @@ +#ifndef INFINI_CCL_BACKENDS_IBV_IMPL_COMM_DESTROY_H_ +#define INFINI_CCL_BACKENDS_IBV_IMPL_COMM_DESTROY_H_ + +#include "backends/ibv/comm_instance.h" +#include "base/comm_destroy.h" +#include "communicator.h" + +namespace infini::ccl { + +template +class CommDestroyImpl { + public: + static ReturnStatus Apply(void *comm) { + auto *comm_internal = static_cast(comm); + if (!comm_internal) { + return ReturnStatus::kInternalError; + } + if (!comm_internal->inter_comm()) { + return ReturnStatus::kSuccess; + } + if (comm_internal->inter_comm_backend() != BackendType::kIbv) { + return ReturnStatus::kInvalidUsage; + } + + if (auto *inter = + static_cast(comm_internal->inter_comm())) { + inter->Destroy(); + } + comm_internal->set_inter_comm(nullptr); + + return ReturnStatus::kSuccess; + } +}; + +template <> +struct BackendEnabled : std::true_type {}; + +} // namespace infini::ccl + +#endif // INFINI_CCL_BACKENDS_IBV_IMPL_COMM_DESTROY_H_ diff --git a/src/backends/ibv/impl/comm_init_rank.h b/src/backends/ibv/impl/comm_init_rank.h new file mode 100644 index 0000000..434505e --- /dev/null +++ b/src/backends/ibv/impl/comm_init_rank.h @@ -0,0 +1,53 @@ +#ifndef INFINI_CCL_BACKENDS_IBV_IMPL_COMM_INIT_RANK_H_ +#define INFINI_CCL_BACKENDS_IBV_IMPL_COMM_INIT_RANK_H_ + +#include +#include +#include + +#include "backends/ibv/comm_instance.h" +#include "base/comm_init_rank.h" +#include "logging.h" + +namespace infini::ccl { + +template +class CommInitRankImpl { + public: + static ReturnStatus Apply(Communicator *comm, int nranks, + infinicclUniqueId id, int rank) { + if (!comm || rank < 0 || rank >= nranks) { + return ReturnStatus::kInvalidArgument; + } + if (nranks != 2) { + return ReturnStatus::kNotSupported; + } + if (comm->inter_comm()) { + return ReturnStatus::kInvalidUsage; + } + + IbvUniqueId ibv_id{}; + std::memcpy(&ibv_id, id.internal, sizeof(ibv_id)); + if (ibv_id.port == 0 || ibv_id.address[0] == '\0' || + !std::memchr(ibv_id.address, '\0', sizeof(ibv_id.address))) { + LOG("Invalid IBV bootstrap ID for `CommInitRank`."); + return ReturnStatus::kInvalidArgument; + } + auto instance = std::make_unique(); + const auto status = instance->Connect(ibv_id, rank); + if (status != ReturnStatus::kSuccess) { + return status; + } + comm->set_world_info(rank, nranks); + comm->set_local_size(1); + comm->set_inter_comm(std::move(instance)); + return ReturnStatus::kSuccess; + } +}; + +template <> +struct BackendEnabled : std::true_type {}; + +} // namespace infini::ccl + +#endif // INFINI_CCL_BACKENDS_IBV_IMPL_COMM_INIT_RANK_H_ diff --git a/src/backends/ibv/impl/finalize.h b/src/backends/ibv/impl/finalize.h new file mode 100644 index 0000000..0025c9b --- /dev/null +++ b/src/backends/ibv/impl/finalize.h @@ -0,0 +1,19 @@ +#ifndef INFINI_CCL_BACKENDS_IBV_IMPL_FINALIZE_H_ +#define INFINI_CCL_BACKENDS_IBV_IMPL_FINALIZE_H_ + +#include "base/finalize.h" + +namespace infini::ccl { + +template +class FinalizeImpl { + public: + static ReturnStatus Apply() { return ReturnStatus::kSuccess; } +}; + +template <> +struct BackendEnabled : std::true_type {}; + +} // namespace infini::ccl + +#endif // INFINI_CCL_BACKENDS_IBV_IMPL_FINALIZE_H_ diff --git a/src/backends/ibv/impl/get_unique_id.h b/src/backends/ibv/impl/get_unique_id.h new file mode 100644 index 0000000..90259cb --- /dev/null +++ b/src/backends/ibv/impl/get_unique_id.h @@ -0,0 +1,70 @@ +#ifndef INFINI_CCL_BACKENDS_IBV_IMPL_GET_UNIQUE_ID_H_ +#define INFINI_CCL_BACKENDS_IBV_IMPL_GET_UNIQUE_ID_H_ + +#include + +#include +#include +#include + +#include "backends/ibv/ibv_common.h" +#include "base/get_unique_id.h" +#include "logging.h" + +namespace infini::ccl { + +template +class GetUniqueIdImpl { + public: + static ReturnStatus Apply(infinicclUniqueId *id) { + if (!id) { + LOG("Invalid unique ID pointer for `GetUniqueId`."); + return ReturnStatus::kInvalidArgument; + } + + const char *address = std::getenv("INFINICCL_IBV_ADDR"); + if (!address || address[0] == '\0' || + std::strlen(address) >= INFINICCL_IBV_ADDRESS_BYTES) { + LOG("`INFINICCL_IBV_ADDR` must contain a non-empty address that fits " + "in the IBV bootstrap address field."); + return ReturnStatus::kInvalidArgument; + } + + const char *port_string = std::getenv("INFINICCL_IBV_PORT"); + const char *value = port_string ? port_string : "7471"; + char *end = nullptr; + errno = 0; + const unsigned long port = std::strtoul(value, &end, 10); + if (errno || end == value || *end || port == 0 || port > 65535) { + LOG("`INFINICCL_IBV_PORT` must be between 1 and 65535."); + return ReturnStatus::kInvalidArgument; + } + + IbvUniqueId ibv_id{}; + ibv_id.port = static_cast(port); + size_t offset = 0; + while (offset < sizeof(ibv_id.group_id)) { + const ssize_t count = getrandom(ibv_id.group_id + offset, + sizeof(ibv_id.group_id) - offset, 0); + if (count < 0 && errno == EINTR) { + continue; + } + if (count <= 0) { + return ReturnStatus::kSystemError; + } + offset += static_cast(count); + } + std::strncpy(ibv_id.address, address, sizeof(ibv_id.address) - 1); + std::memset(id->internal, 0, sizeof(id->internal)); + std::memcpy(id->internal, &ibv_id, sizeof(ibv_id)); + + return ReturnStatus::kSuccess; + } +}; + +template <> +struct BackendEnabled : std::true_type {}; + +} // namespace infini::ccl + +#endif // INFINI_CCL_BACKENDS_IBV_IMPL_GET_UNIQUE_ID_H_ diff --git a/src/backends/ibv/impl/init.h b/src/backends/ibv/impl/init.h new file mode 100644 index 0000000..ceba499 --- /dev/null +++ b/src/backends/ibv/impl/init.h @@ -0,0 +1,21 @@ +#ifndef INFINI_CCL_BACKENDS_IBV_IMPL_INIT_H_ +#define INFINI_CCL_BACKENDS_IBV_IMPL_INIT_H_ + +#include "base/init.h" + +namespace infini::ccl { + +template +class InitImpl { + public: + static ReturnStatus Apply(int* /*argc*/, char*** /*argv*/) { + return ReturnStatus::kSuccess; + } +}; + +template <> +struct BackendEnabled : std::true_type {}; + +} // namespace infini::ccl + +#endif // INFINI_CCL_BACKENDS_IBV_IMPL_INIT_H_ diff --git a/src/backends/ibv/impl/recv.h b/src/backends/ibv/impl/recv.h new file mode 100644 index 0000000..2b617c7 --- /dev/null +++ b/src/backends/ibv/impl/recv.h @@ -0,0 +1,34 @@ +#ifndef INFINI_CCL_BACKENDS_IBV_IMPL_RECV_H_ +#define INFINI_CCL_BACKENDS_IBV_IMPL_RECV_H_ + +#include + +#include "backends/ibv/comm_instance.h" +#include "base/recv.h" + +namespace infini::ccl { + +template +class RecvImpl { + public: + static ReturnStatus Apply(void *recv_buff, size_t count, DataType data_type, + int peer, Communicator *comm, void *stream) { + if (!comm || comm->inter_comm_backend() != BackendType::kIbv) { + return ReturnStatus::kInvalidUsage; + } + const size_t type_size = kDataTypeToSize.at(data_type); + if (count > std::numeric_limits::max() / type_size) { + return ReturnStatus::kInvalidArgument; + } + auto *instance = static_cast(comm->inter_comm()); + return instance->Transfer(recv_buff, count * type_size, peer, true, + device_type, stream); + } +}; + +template <> +struct BackendEnabled : std::true_type {}; + +} // namespace infini::ccl + +#endif // INFINI_CCL_BACKENDS_IBV_IMPL_RECV_H_ diff --git a/src/backends/ibv/impl/send.h b/src/backends/ibv/impl/send.h new file mode 100644 index 0000000..47c0b0a --- /dev/null +++ b/src/backends/ibv/impl/send.h @@ -0,0 +1,35 @@ +#ifndef INFINI_CCL_BACKENDS_IBV_IMPL_SEND_H_ +#define INFINI_CCL_BACKENDS_IBV_IMPL_SEND_H_ + +#include + +#include "backends/ibv/comm_instance.h" +#include "base/send.h" + +namespace infini::ccl { + +template +class SendImpl { + public: + static ReturnStatus Apply(const void *send_buff, size_t count, + DataType data_type, int peer, Communicator *comm, + void *stream) { + if (!comm || comm->inter_comm_backend() != BackendType::kIbv) { + return ReturnStatus::kInvalidUsage; + } + const size_t type_size = kDataTypeToSize.at(data_type); + if (count > std::numeric_limits::max() / type_size) { + return ReturnStatus::kInvalidArgument; + } + auto *instance = static_cast(comm->inter_comm()); + return instance->Transfer(const_cast(send_buff), count * type_size, + peer, false, device_type, stream); + } +}; + +template <> +struct BackendEnabled : std::true_type {}; + +} // namespace infini::ccl + +#endif // INFINI_CCL_BACKENDS_IBV_IMPL_SEND_H_ diff --git a/src/backends/ibv/memory_adaptor.cc b/src/backends/ibv/memory_adaptor.cc new file mode 100644 index 0000000..a6dc10f --- /dev/null +++ b/src/backends/ibv/memory_adaptor.cc @@ -0,0 +1,207 @@ +#include "backends/ibv/memory_adaptor.h" + +#include + +#include +#include +#include +#include +#include +#include + +#include "devices/cpu/ibv_memory.h" + +#if defined(INFINICCL_WITH_NVIDIA_IBV) +#include "devices/nvidia/ibv_memory.h" +#endif + +#if defined(INFINICCL_WITH_METAX_IBV) +#include "devices/metax/ibv_memory.h" +#endif + +#include "dispatcher.h" +#include "logging.h" + +namespace infini::ccl { + +namespace { + +// Cached registrations are capped so repeated transfers over distinct large +// buffers cannot pin unbounded memory; eviction is least-recently-used. +constexpr size_t kIbvMrCacheLimitBytes = 256 << 20; + +} // namespace + +IbvMemoryRegion::IbvMemoryRegion(IbvMemoryRegion &&other) noexcept + : mr(other.mr), fd(other.fd) { + other.mr = nullptr; + other.fd = -1; +} + +IbvMemoryRegion &IbvMemoryRegion::operator=( + IbvMemoryRegion &&other) noexcept { + if (this != &other) { + mr = other.mr; + fd = other.fd; + other.mr = nullptr; + other.fd = -1; + } + return *this; +} + +IbvMemoryRegion::~IbvMemoryRegion() { + const auto status = Reset(); + if (status != ReturnStatus::kSuccess) { + std::cerr << __FILE__ << ':' << __LINE__ << ' ' << __func__ + << ": Failed to release registered IBV memory safely.\n"; + assert(status == ReturnStatus::kSuccess); + std::abort(); + } +} + +ReturnStatus IbvMemoryRegion::Reset() { + if (mr) { + if (ibv_dereg_mr(mr) != 0) { + std::cerr << __FILE__ << ':' << __LINE__ << ' ' << __func__ + << ": Failed to deregister IBV memory safely.\n"; + assert(false && "IBV memory deregistration failed."); + std::abort(); + } + mr = nullptr; + } + if (fd >= 0) { + const int status = close(fd); + fd = -1; + if (status != 0) { + LOG("Failed to close the DMA-BUF descriptor."); + return ReturnStatus::kSystemError; + } + } + return ReturnStatus::kSuccess; +} + +ReturnStatus RegisterIbvHostMemory(ibv_pd *pd, void *buffer, size_t bytes, + IbvMemoryRegion *region) { + if (!pd || !buffer || bytes == 0 || !region || region->mr || + region->fd >= 0) { + return ReturnStatus::kInvalidArgument; + } + region->mr = ibv_reg_mr(pd, buffer, bytes, IBV_ACCESS_LOCAL_WRITE); + if (!region->mr) { + const int error = errno; + std::cerr << "Host MR registration failed: " << std::strerror(error) << " (" + << error << ").\n"; + return ReturnStatus::kSystemError; + } + return ReturnStatus::kSuccess; +} + +ReturnStatus IbvMrCache::Acquire(ibv_pd *pd, IbvMemoryAdapter *adapter, + void *buffer, size_t bytes, ibv_mr **mr) { + const IbvMemoryKey key = adapter->memory_key(); + std::lock_guard lock(mutex_); + ++acquisitions_; + auto cached = entries_.find(Range(key.base, key.bytes)); + if (cached != entries_.end()) { + if (key.tag == 0 || cached->second.tag == key.tag) { + cached->second.last_used = ++clock_; + *mr = cached->second.region.mr; + return ReturnStatus::kSuccess; + } + // The allocation behind this range was freed and its address reused. + total_bytes_ -= cached->first.second; + entries_.erase(cached); + } + auto status = InsertLocked(key, pd, adapter, buffer, bytes, mr); + if (status != ReturnStatus::kSuccess && !entries_.empty()) { + // Registration can fail once pinning resources are exhausted; free the + // least recently used entry and retry once. + EvictOldestLocked(); + status = InsertLocked(key, pd, adapter, buffer, bytes, mr); + } + if (status == ReturnStatus::kSuccess) { + EvictOverflowLocked(); + } + return status; +} + +ReturnStatus IbvMrCache::InsertLocked(const IbvMemoryKey &key, ibv_pd *pd, + IbvMemoryAdapter *adapter, void *buffer, + size_t bytes, ibv_mr **mr) { + IbvMemoryRegion region; + auto status = adapter->Register(pd, buffer, bytes, ®ion); + if (status != ReturnStatus::kSuccess) { + return status; + } + Entry entry; + entry.tag = key.tag; + entry.last_used = ++clock_; + entry.region = std::move(region); + total_bytes_ += key.bytes; + ++registrations_; + const auto inserted = + entries_.emplace(Range(key.base, key.bytes), std::move(entry)); + *mr = inserted.first->second.region.mr; + return ReturnStatus::kSuccess; +} + +void IbvMrCache::EvictOldestLocked() { + auto oldest = entries_.begin(); + for (auto it = entries_.begin(); it != entries_.end(); ++it) { + if (it->second.last_used < oldest->second.last_used) { + oldest = it; + } + } + total_bytes_ -= oldest->first.second; + entries_.erase(oldest); +} + +void IbvMrCache::EvictOverflowLocked() { + while (total_bytes_ > kIbvMrCacheLimitBytes && entries_.size() > 1) { + EvictOldestLocked(); + } +} + +void IbvMrCache::Reset() { + std::lock_guard lock(mutex_); + for (auto &item : entries_) { + const auto status = item.second.region.Reset(); + if (status != ReturnStatus::kSuccess) { + std::cerr << __FILE__ << ':' << __LINE__ << ' ' << __func__ + << ": Failed to release a cached IBV memory region safely.\n"; + assert(status == ReturnStatus::kSuccess); + std::abort(); + } + } + entries_.clear(); + total_bytes_ = 0; +} + +IbvMrCacheStats IbvMrCache::Stats() const { + std::lock_guard lock(mutex_); + IbvMrCacheStats stats; + stats.registrations = registrations_; + stats.acquisitions = acquisitions_; + stats.entries = entries_.size(); + stats.retained_bytes = total_bytes_; + return stats; +} + +ReturnStatus CreateIbvMemoryAdapter( + Device::Type device, std::unique_ptr *adapter) { + if (!adapter) { + return ReturnStatus::kInvalidArgument; + } + if (device < Device::Type::kCpu || device >= Device::Type::kCount) { + return ReturnStatus::kNotSupported; + } + return DispatchFunc( + device, + [&](auto tag) { + constexpr Device::Type kDevice = decltype(tag)::value; + return MemoryAdapterFactory::Create(adapter); + }, + "CreateIbvMemoryAdapter"); +} + +} // namespace infini::ccl diff --git a/src/backends/ibv/memory_adaptor.h b/src/backends/ibv/memory_adaptor.h new file mode 100644 index 0000000..db9e8f3 --- /dev/null +++ b/src/backends/ibv/memory_adaptor.h @@ -0,0 +1,135 @@ +#ifndef INFINI_CCL_BACKENDS_IBV_MEMORY_ADAPTOR_H_ +#define INFINI_CCL_BACKENDS_IBV_MEMORY_ADAPTOR_H_ + +#include + +#include +#include +#include +#include +#include +#include + +#include "device.h" +#include "return_status_impl.h" + +namespace infini::ccl { + +struct IbvMemoryRegion { + ~IbvMemoryRegion(); + + IbvMemoryRegion() = default; + + IbvMemoryRegion(const IbvMemoryRegion &) = delete; + + IbvMemoryRegion &operator=(const IbvMemoryRegion &) = delete; + + IbvMemoryRegion(IbvMemoryRegion &&other) noexcept; + + IbvMemoryRegion &operator=(IbvMemoryRegion &&other) noexcept; + + ReturnStatus Reset(); + + ibv_mr *mr = nullptr; + + int fd = -1; +}; + +// Identifies the memory allocation a buffer belongs to. Adapters fill it in +// `Prepare`; `tag` carries an allocation identity when the runtime provides +// one and stays zero when only the address range is known. +struct IbvMemoryKey { + uintptr_t base = 0; + + size_t bytes = 0; + + uint64_t tag = 0; +}; + +class IbvMemoryAdapter { + public: + virtual ~IbvMemoryAdapter() = default; + + virtual ReturnStatus Prepare(void *buffer, size_t bytes, void *stream) = 0; + + virtual ReturnStatus Register(ibv_pd *pd, void *buffer, size_t bytes, + IbvMemoryRegion *region) = 0; + + virtual ReturnStatus Complete(bool receive) = 0; + + virtual IbvMemoryKey memory_key() const = 0; +}; + +struct IbvMrCacheStats { + uint64_t registrations = 0; + + uint64_t acquisitions = 0; + + size_t entries = 0; + + size_t retained_bytes = 0; +}; + +// Caches registered memory regions keyed by allocation range so repeated +// transfers on the same buffer reuse one registration instead of paying the +// pinning cost per message. Entries are validated against `tag` to detect +// freed-and-reused allocations and evicted least-recently-used first. +class IbvMrCache { + public: + ReturnStatus Acquire(ibv_pd *pd, IbvMemoryAdapter *adapter, void *buffer, + size_t bytes, ibv_mr **mr); + + // Releases every cached region. Unsafe release aborts the process, + // mirroring `IbvMemoryRegion` teardown semantics. + void Reset(); + + IbvMrCacheStats Stats() const; + + private: + struct Entry { + IbvMemoryRegion region; + + uint64_t tag = 0; + + uint64_t last_used = 0; + }; + + using Range = std::pair; + + ReturnStatus InsertLocked(const IbvMemoryKey &key, ibv_pd *pd, + IbvMemoryAdapter *adapter, void *buffer, + size_t bytes, ibv_mr **mr); + + void EvictOldestLocked(); + + void EvictOverflowLocked(); + + mutable std::mutex mutex_; + + std::map entries_; + + size_t total_bytes_ = 0; + + uint64_t clock_ = 0; + + uint64_t registrations_ = 0; + + uint64_t acquisitions_ = 0; +}; + +template +struct MemoryAdapterFactory { + static ReturnStatus Create(std::unique_ptr * /*adapter*/) { + return ReturnStatus::kNotSupported; + } +}; + +ReturnStatus RegisterIbvHostMemory(ibv_pd *pd, void *buffer, size_t bytes, + IbvMemoryRegion *region); + +ReturnStatus CreateIbvMemoryAdapter( + Device::Type device, std::unique_ptr *adapter); + +} // namespace infini::ccl + +#endif // INFINI_CCL_BACKENDS_IBV_MEMORY_ADAPTOR_H_ diff --git a/src/devices/cpu/ibv_memory.cc b/src/devices/cpu/ibv_memory.cc new file mode 100644 index 0000000..d20f61b --- /dev/null +++ b/src/devices/cpu/ibv_memory.cc @@ -0,0 +1,42 @@ +#include "devices/cpu/ibv_memory.h" + +namespace infini::ccl { +namespace { + +class HostMemoryAdapter : public IbvMemoryAdapter { + public: + ReturnStatus Prepare(void *buffer, size_t bytes, void *stream) override { + if (stream) { + return ReturnStatus::kNotSupported; + } + key_ = IbvMemoryKey{reinterpret_cast(buffer), bytes, 0}; + return ReturnStatus::kSuccess; + } + + ReturnStatus Register(ibv_pd *pd, void *buffer, size_t bytes, + IbvMemoryRegion *region) override { + return RegisterIbvHostMemory(pd, buffer, bytes, region); + } + + ReturnStatus Complete(bool /*receive*/) override { + return ReturnStatus::kSuccess; + } + + IbvMemoryKey memory_key() const override { return key_; } + + private: + IbvMemoryKey key_; +}; + +} // namespace + +ReturnStatus MemoryAdapterFactory::Create( + std::unique_ptr *adapter) { + if (!adapter) { + return ReturnStatus::kInvalidArgument; + } + *adapter = std::make_unique(); + return ReturnStatus::kSuccess; +} + +} // namespace infini::ccl diff --git a/src/devices/cpu/ibv_memory.h b/src/devices/cpu/ibv_memory.h new file mode 100644 index 0000000..36a992d --- /dev/null +++ b/src/devices/cpu/ibv_memory.h @@ -0,0 +1,17 @@ +#ifndef INFINI_CCL_DEVICES_CPU_IBV_MEMORY_H_ +#define INFINI_CCL_DEVICES_CPU_IBV_MEMORY_H_ + +#include + +#include "backends/ibv/memory_adaptor.h" + +namespace infini::ccl { + +template <> +struct MemoryAdapterFactory { + static ReturnStatus Create(std::unique_ptr *adapter); +}; + +} // namespace infini::ccl + +#endif // INFINI_CCL_DEVICES_CPU_IBV_MEMORY_H_ diff --git a/src/devices/metax/ibv_memory.cc b/src/devices/metax/ibv_memory.cc new file mode 100644 index 0000000..7b950b2 --- /dev/null +++ b/src/devices/metax/ibv_memory.cc @@ -0,0 +1,231 @@ +#include "devices/metax/ibv_memory.h" + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace infini::ccl { +namespace { + +struct MetaxAllocation { + void *base = nullptr; + + size_t bytes = 0; + + size_t offset = 0; +}; + +ReturnStatus CheckMaca(mcError_t status, const char *operation) { + if (status != mcSuccess) { + std::cerr << "MACA operation `" << operation + << "` failed: " << mcGetErrorString(status) << ".\n"; + return ReturnStatus::kSystemError; + } + return ReturnStatus::kSuccess; +} + +template +uintptr_t PointerAddress(T pointer) { + if constexpr (std::is_pointer_v) { + return reinterpret_cast(pointer); + } else { + return static_cast(pointer); + } +} + +ReturnStatus ValidateDeviceBuffer(void *buffer, size_t bytes, + int current_device, + MetaxAllocation *allocation) { + int buffer_device = -1; + const auto pointer = reinterpret_cast(buffer); + auto status = CheckMaca( + mcPointerGetAttribute(&buffer_device, mcPointerAttributeDevice, pointer), + "mcPointerGetAttribute(device)"); + if (status != ReturnStatus::kSuccess) { + return status; + } + if (buffer_device != current_device) { + std::cerr + << "The IBV buffer does not belong to the current MACA device.\n"; + return ReturnStatus::kInvalidArgument; + } + mcDeviceptr_t base{}; + size_t allocation_bytes = 0; + status = CheckMaca(mcMemGetAddressRange(&base, &allocation_bytes, pointer), + "mcMemGetAddressRange"); + if (status != ReturnStatus::kSuccess) { + return status; + } + const auto address = reinterpret_cast(buffer); + const auto start = PointerAddress(base); + if (address < start || address - start > allocation_bytes || + bytes > allocation_bytes - (address - start)) { + return ReturnStatus::kInvalidArgument; + } + allocation->base = reinterpret_cast(start); + allocation->bytes = allocation_bytes; + allocation->offset = address - start; + return ReturnStatus::kSuccess; +} + +bool ExperimentalDirectEnabled() { + const char *value = std::getenv("INFINICCL_IBV_METAX_EXPERIMENTAL"); + return value && std::strcmp(value, "1") == 0; +} + +void QueryFlushPolicy(int device, bool *flush) { + static std::once_flag warning_once; + int ordering = 0; + int options = 0; + const auto ordering_status = mcDeviceGetAttribute( + &ordering, mcDeviceAttributeGPUDirectRDMAWritesOrdering, device); + const auto options_status = mcDeviceGetAttribute( + &options, mcDeviceAttributeGPUDirectRDMAFlushWritesOptions, device); + *flush = ordering_status == mcSuccess && options_status == mcSuccess && + ordering < mcFlushGPUDirectRDMAWritesToOwner && + (options & mcFlushGPUDirectRDMAWritesOptionHost); + const bool native_ordering = ordering_status == mcSuccess && + ordering >= mcFlushGPUDirectRDMAWritesToOwner; + std::call_once(warning_once, [flush, native_ordering] { + std::cerr << "Experimental MetaX DeviceDirect: DMA visibility is not yet " + "validated; no Host staging is used. Receive flush: " + << (*flush ? "enabled" + : native_ordering ? "native ordering reported" + : "not reported, visibility unverified") + << ".\n"; + }); +} + +ReturnStatus ExportDeviceMemory(void *buffer, size_t bytes, + IbvMemoryRegion *region, MXuint64 *offset) { + *offset = std::numeric_limits::max(); + const auto status = + mxkwExportDMABufHandle(buffer, bytes, ®ion->fd, offset); + // The target MACA 3.2.1 probe returned zero on a successful export. + if (static_cast(status) != 0 || region->fd < 0 || + *offset > std::numeric_limits::max() - bytes) { + std::cerr << "`mxkwExportDMABufHandle` failed: status=" + << static_cast(status) << ", fd=" << region->fd << ".\n"; + return ReturnStatus::kSystemError; + } + return ReturnStatus::kSuccess; +} + +ReturnStatus RegisterDeviceMemory(ibv_pd *pd, + const MetaxAllocation &allocation, + IbvMemoryRegion *region) { + MXuint64 offset = 0; + auto status = + ExportDeviceMemory(allocation.base, allocation.bytes, region, &offset); + if (status != ReturnStatus::kSuccess) { + return status; + } + const auto iova = reinterpret_cast(allocation.base); + const long page_size = sysconf(_SC_PAGESIZE); + if (page_size <= 0 || offset % page_size != iova % page_size) { + return ReturnStatus::kInvalidArgument; + } + // The whole allocation is registered once so subrange transfers reuse the + // same memory region. + region->mr = ibv_reg_dmabuf_mr(pd, offset, allocation.bytes, iova, + region->fd, IBV_ACCESS_LOCAL_WRITE); + if (!region->mr) { + const int error = errno; + std::cerr << "MetaX DMA-BUF MR registration failed: " + << std::strerror(error) << " (" << error << ").\n"; + return ReturnStatus::kSystemError; + } + return ReturnStatus::kSuccess; +} + +class MetaxMemoryAdapter : public IbvMemoryAdapter { + public: + ReturnStatus Prepare(void *buffer, size_t bytes, void *stream) override; + + ReturnStatus Register(ibv_pd *pd, void *buffer, size_t bytes, + IbvMemoryRegion *region) override { + return device_memory_ ? RegisterDeviceMemory(pd, allocation_, region) + : RegisterIbvHostMemory(pd, buffer, bytes, region); + } + + ReturnStatus Complete(bool receive) override { + if (receive && device_memory_ && flush_) { + return CheckMaca(mcDeviceFlushGPUDirectRDMAWrites( + mcFlushGPUDirectRDMAWritesTargetCurrentDevice, + mcFlushGPUDirectRDMAWritesToOwner), + "mcDeviceFlushGPUDirectRDMAWrites"); + } + return ReturnStatus::kSuccess; + } + + IbvMemoryKey memory_key() const override { return key_; } + + private: + bool device_memory_ = false; + + bool flush_ = false; + + MetaxAllocation allocation_; + + IbvMemoryKey key_; +}; + +ReturnStatus MetaxMemoryAdapter::Prepare(void *buffer, size_t bytes, + void *stream) { + mcPointerAttribute_t attributes{}; + auto status = CheckMaca(mcPointerGetAttributes(&attributes, buffer), + "mcPointerGetAttributes"); + if (status != ReturnStatus::kSuccess) { + return status; + } + device_memory_ = attributes.type == mcMemoryTypeDevice; + if (!device_memory_ && attributes.type != mcMemoryTypeHost && + attributes.type != mcMemoryTypeUnregistered) { + std::cerr << "Managed or array memory is not supported by the MetaX IBV " + "backend.\n"; + return ReturnStatus::kNotSupported; + } + key_ = IbvMemoryKey{reinterpret_cast(buffer), bytes, 0}; + if (device_memory_) { + if (!ExperimentalDirectEnabled()) { + std::cerr << "MetaX DeviceDirect requires explicit experimental opt-in: " + "`INFINICCL_IBV_METAX_EXPERIMENTAL=1`.\n"; + return ReturnStatus::kNotSupported; + } + int device = 0; + status = CheckMaca(mcGetDevice(&device), "mcGetDevice"); + if (status == ReturnStatus::kSuccess) { + status = ValidateDeviceBuffer(buffer, bytes, device, &allocation_); + } + if (status != ReturnStatus::kSuccess) { + return status; + } + key_ = IbvMemoryKey{reinterpret_cast(allocation_.base), + allocation_.bytes, 0}; + QueryFlushPolicy(device, &flush_); + } + return CheckMaca(mcStreamSynchronize(reinterpret_cast(stream)), + "mcStreamSynchronize"); +} + +} // namespace + +ReturnStatus MemoryAdapterFactory::Create( + std::unique_ptr *adapter) { + if (!adapter) { + return ReturnStatus::kInvalidArgument; + } + *adapter = std::make_unique(); + return ReturnStatus::kSuccess; +} + +} // namespace infini::ccl diff --git a/src/devices/metax/ibv_memory.h b/src/devices/metax/ibv_memory.h new file mode 100644 index 0000000..28160a2 --- /dev/null +++ b/src/devices/metax/ibv_memory.h @@ -0,0 +1,17 @@ +#ifndef INFINI_CCL_DEVICES_METAX_IBV_MEMORY_H_ +#define INFINI_CCL_DEVICES_METAX_IBV_MEMORY_H_ + +#include + +#include "backends/ibv/memory_adaptor.h" + +namespace infini::ccl { + +template <> +struct MemoryAdapterFactory { + static ReturnStatus Create(std::unique_ptr *adapter); +}; + +} // namespace infini::ccl + +#endif // INFINI_CCL_DEVICES_METAX_IBV_MEMORY_H_ diff --git a/src/devices/nvidia/ibv_memory.cc b/src/devices/nvidia/ibv_memory.cc new file mode 100644 index 0000000..4c8c1fe --- /dev/null +++ b/src/devices/nvidia/ibv_memory.cc @@ -0,0 +1,208 @@ +#include "devices/nvidia/ibv_memory.h" + +#include +#include + +#include +#include +#include +#include + +namespace infini::ccl { +namespace { + +ReturnStatus CheckCuda(cudaError_t status, const char *operation) { + if (status != cudaSuccess) { + std::cerr << "CUDA operation `" << operation + << "` failed: " << cudaGetErrorString(status) << ".\n"; + return ReturnStatus::kSystemError; + } + return ReturnStatus::kSuccess; +} + +ReturnStatus CheckDriver(CUresult status, const char *operation) { + if (status != CUDA_SUCCESS) { + const char *message = "Unknown CUDA driver error"; + (void)cuGetErrorString(status, &message); + std::cerr << "CUDA operation `" << operation << "` failed: " << message + << ".\n"; + return ReturnStatus::kSystemError; + } + return ReturnStatus::kSuccess; +} + +ReturnStatus ValidateDeviceBuffer(void *buffer, size_t bytes, + IbvMemoryKey *key) { + const auto pointer = reinterpret_cast(buffer); + CUdeviceptr base = 0; + size_t allocation_bytes = 0; + auto status = + CheckDriver(cuMemGetAddressRange(&base, &allocation_bytes, pointer), + "cuMemGetAddressRange"); + if (status != ReturnStatus::kSuccess) { + return status; + } + if (pointer < base || pointer - base > allocation_bytes || + bytes > allocation_bytes - (pointer - base)) { + return ReturnStatus::kInvalidArgument; + } + uint64_t buffer_id = 0; + // A failed identity query only weakens cache validation to range matching. + if (cuPointerGetAttribute(&buffer_id, CU_POINTER_ATTRIBUTE_BUFFER_ID, + pointer) != CUDA_SUCCESS) { + buffer_id = 0; + } + key->base = static_cast(base); + key->bytes = allocation_bytes; + key->tag = buffer_id; + unsigned int sync_memops = 1; + return CheckDriver( + cuPointerSetAttribute(&sync_memops, CU_POINTER_ATTRIBUTE_SYNC_MEMOPS, + pointer), + "cuPointerSetAttribute(SYNC_MEMOPS)"); +} + +ReturnStatus QueryFlushPolicy(int device, bool *flush) { + int supported = 0; + int ordering = 0; + int options = 0; + auto status = + CheckCuda(cudaDeviceGetAttribute( + &supported, cudaDevAttrGPUDirectRDMASupported, device), + "cudaDeviceGetAttribute(GPUDirectRDMASupported)"); + if (status != ReturnStatus::kSuccess) { + return status; + } + if (!supported) { + std::cerr << "The CUDA device does not report GPUDirect RDMA support.\n"; + return ReturnStatus::kNotSupported; + } + status = + CheckCuda(cudaDeviceGetAttribute( + &ordering, cudaDevAttrGPUDirectRDMAWritesOrdering, device), + "cudaDeviceGetAttribute(GPUDirectRDMAWritesOrdering)"); + if (status != ReturnStatus::kSuccess) { + return status; + } + *flush = ordering < cudaFlushGPUDirectRDMAWritesToOwner; + if (!*flush) { + return ReturnStatus::kSuccess; + } + status = CheckCuda( + cudaDeviceGetAttribute( + &options, cudaDevAttrGPUDirectRDMAFlushWritesOptions, device), + "cudaDeviceGetAttribute(GPUDirectRDMAFlushWritesOptions)"); + if (status != ReturnStatus::kSuccess) { + return status; + } + if (!(options & cudaFlushGPUDirectRDMAWritesOptionHost)) { + std::cerr << "The NVIDIA IBV backend requires native owner ordering or " + "Host flush support.\n"; + return ReturnStatus::kNotSupported; + } + return ReturnStatus::kSuccess; +} + +ReturnStatus RegisterDeviceMemory(ibv_pd *pd, const IbvMemoryKey &key, + IbvMemoryRegion *region) { + if (!pd || !region || key.base == 0 || key.bytes == 0 || region->mr || + region->fd >= 0) { + return ReturnStatus::kInvalidArgument; + } + // The whole allocation is registered once so subrange transfers reuse the + // same memory region. + region->mr = ibv_reg_mr(pd, reinterpret_cast(key.base), key.bytes, + IBV_ACCESS_LOCAL_WRITE); + if (!region->mr) { + const int error = errno; + std::cerr << "NVIDIA peer-memory MR registration failed: " + << std::strerror(error) << " (" << error + << "). Check `nvidia-peermem` and GPU/NIC topology; no Host " + "staging is used.\n"; + return ReturnStatus::kSystemError; + } + return ReturnStatus::kSuccess; +} + +class NvidiaMemoryAdapter : public IbvMemoryAdapter { + public: + ReturnStatus Prepare(void *buffer, size_t bytes, void *stream) override; + + ReturnStatus Register(ibv_pd *pd, void *buffer, size_t bytes, + IbvMemoryRegion *region) override { + return device_memory_ ? RegisterDeviceMemory(pd, key_, region) + : RegisterIbvHostMemory(pd, buffer, bytes, region); + } + + ReturnStatus Complete(bool receive) override { + if (receive && device_memory_ && flush_) { + return CheckCuda(cudaDeviceFlushGPUDirectRDMAWrites( + cudaFlushGPUDirectRDMAWritesTargetCurrentDevice, + cudaFlushGPUDirectRDMAWritesToOwner), + "cudaDeviceFlushGPUDirectRDMAWrites"); + } + return ReturnStatus::kSuccess; + } + + IbvMemoryKey memory_key() const override { return key_; } + + private: + bool device_memory_ = false; + + bool flush_ = false; + + IbvMemoryKey key_; +}; + +ReturnStatus NvidiaMemoryAdapter::Prepare(void *buffer, size_t bytes, + void *stream) { + cudaPointerAttributes attributes{}; + auto status = CheckCuda(cudaPointerGetAttributes(&attributes, buffer), + "cudaPointerGetAttributes"); + if (status != ReturnStatus::kSuccess) { + return status; + } + device_memory_ = attributes.type == cudaMemoryTypeDevice; + if (!device_memory_ && attributes.type != cudaMemoryTypeHost && + attributes.type != cudaMemoryTypeUnregistered) { + std::cerr << "Managed or array memory is not supported by the NVIDIA IBV " + "backend.\n"; + return ReturnStatus::kNotSupported; + } + key_ = IbvMemoryKey{reinterpret_cast(buffer), bytes, 0}; + if (device_memory_) { + int device = -1; + status = CheckCuda(cudaGetDevice(&device), "cudaGetDevice"); + if (status != ReturnStatus::kSuccess) { + return status; + } + if (attributes.device != device) { + std::cerr + << "The IBV buffer does not belong to the current CUDA device.\n"; + return ReturnStatus::kInvalidArgument; + } + status = ValidateDeviceBuffer(buffer, bytes, &key_); + if (status == ReturnStatus::kSuccess) { + status = QueryFlushPolicy(device, &flush_); + } + if (status != ReturnStatus::kSuccess) { + return status; + } + } + return CheckCuda( + cudaStreamSynchronize(reinterpret_cast(stream)), + "cudaStreamSynchronize"); +} + +} // namespace + +ReturnStatus MemoryAdapterFactory::Create( + std::unique_ptr *adapter) { + if (!adapter) { + return ReturnStatus::kInvalidArgument; + } + *adapter = std::make_unique(); + return ReturnStatus::kSuccess; +} + +} // namespace infini::ccl diff --git a/src/devices/nvidia/ibv_memory.h b/src/devices/nvidia/ibv_memory.h new file mode 100644 index 0000000..4bf2792 --- /dev/null +++ b/src/devices/nvidia/ibv_memory.h @@ -0,0 +1,17 @@ +#ifndef INFINI_CCL_DEVICES_NVIDIA_IBV_MEMORY_H_ +#define INFINI_CCL_DEVICES_NVIDIA_IBV_MEMORY_H_ + +#include + +#include "backends/ibv/memory_adaptor.h" + +namespace infini::ccl { + +template <> +struct MemoryAdapterFactory { + static ReturnStatus Create(std::unique_ptr *adapter); +}; + +} // namespace infini::ccl + +#endif // INFINI_CCL_DEVICES_NVIDIA_IBV_MEMORY_H_