From 72e0e0eeb3152c6e009666907f1afcc2016d8854 Mon Sep 17 00:00:00 2001 From: fergus barratt Date: Mon, 15 Jun 2026 09:05:39 +0000 Subject: [PATCH 1/5] p2p: add CXI transport backend --- p2p/Makefile | 26 +- p2p/README.md | 19 +- p2p/cxi/cxi_endpoint.cc | 716 ++++++++++++++++++++++++++++++++++++++ p2p/cxi/cxi_endpoint.h | 153 ++++++++ p2p/cxi/fabric_dl.cc | 44 +++ p2p/cxi/fabric_dl.h | 45 +++ p2p/endpoint_wrapper.h | 37 +- p2p/engine.cc | 137 ++++++-- p2p/engine.h | 18 +- p2p/util/common.h | 1 + p2p/util/transport_type.h | 7 +- 11 files changed, 1162 insertions(+), 41 deletions(-) create mode 100644 p2p/cxi/cxi_endpoint.cc create mode 100644 p2p/cxi/cxi_endpoint.h create mode 100644 p2p/cxi/fabric_dl.cc create mode 100644 p2p/cxi/fabric_dl.h diff --git a/p2p/Makefile b/p2p/Makefile index 4dc3e05d8..ae6282f7b 100644 --- a/p2p/Makefile +++ b/p2p/Makefile @@ -1,19 +1,27 @@ # Makefile for UCCL P2P Engine nanobind project (stable ABI) # # Single binary, runtime transport selection via UCCL_P2P_TRANSPORT env var. -# libibverbs, libnccl, and libefa are loaded dynamically at runtime via -# dlopen/dlsym (see *_dl.h). No transport libraries are linked. +# libibverbs, libnccl, libefa, and optional libfabric/CXI are loaded +# dynamically at runtime via dlopen/dlsym (see *_dl.h). # -# Runtime: UCCL_P2P_TRANSPORT=rdma|nccl|efa (default: rdma) +# Runtime: UCCL_P2P_TRANSPORT=rdma|nccl|efa|cxi (default: rdma) # DietGPU optional integration USE_DIETGPU ?= $(shell echo $${USE_DIETGPU:-0}) +USE_CXI ?= $(shell echo $${USE_CXI:-0}) # Compiler and flags CUDA_HOME ?= /usr/local/cuda CUDA_INC := $(CUDA_HOME)/include CUDA_LIB := $(CUDA_HOME)/lib64 EFA_HOME ?= /opt/amazon/efa +LIBFABRIC_HOME ?= /opt/libfabric + +CXI_CXXFLAGS := +CXI_LDFLAGS := +ifeq ($(USE_CXI),1) + CXI_CXXFLAGS := -DUSE_CXI -I./cxi -I$(LIBFABRIC_HOME)/include +endif # Building with the following settings: # NOTE: -libverbs, -lnccl, -lefa are NOT linked at compile time. @@ -27,6 +35,7 @@ CXXFLAGS := -O3 -shared -std=c++17 -fPIC \ -MMD -MP \ -Wno-pointer-arith -Wno-sign-compare -Wno-unused-variable \ -Wl,-rpath=/usr/lib/x86_64-linux-gnu +CXXFLAGS += $(CXI_CXXFLAGS) # ---------------- DietGPU ---------------- DIETGPU_ROOT := ../thirdparty/dietgpu @@ -75,9 +84,9 @@ PREFIX ?= /usr/local LIBDIR ?= $(PREFIX)/lib INCDIR ?= $(PREFIX)/include -# NO transport libraries linked (-libverbs, -lnccl, -lefa). -# All ibv_* / nccl* / efadv_* symbols are provided by the dlsym wrappers -# in rdma/ibverbs_dl.cc, nccl/nccl_dl.cc, rdma/efadv_dl.cc. +# No transport libraries are linked (-libverbs, -lnccl, -lefa, -lfabric). +# All ibv_* / nccl* / efadv_* / fi_* symbols are provided by dlsym wrappers in +# rdma/ibverbs_dl.cc, nccl/nccl_dl.cc, rdma/efadv_dl.cc, and cxi/fabric_dl.cc. # The --wrap flags redirect compat-layer calls from verbs.h to our wrappers. IBV_WRAP_FLAGS := -Wl,--wrap=ibv_get_device_list \ -Wl,--wrap=ibv_query_port \ @@ -88,7 +97,7 @@ IBV_WRAP_FLAGS := -Wl,--wrap=ibv_get_device_list \ -Wl,--wrap=ibv_qp_to_qp_ex LDFLAGS = -L$(CUDA_LIB) -lcudart -lcuda -Wl,-rpath,$(CUDA_LIB) \ -lz -lelf -lpthread -ldl -Wl,-Bsymbolic-functions \ - $(IBV_WRAP_FLAGS) $(DIETGPU_LIBS) + $(IBV_WRAP_FLAGS) $(DIETGPU_LIBS) $(CXI_LDFLAGS) # Target and source files - always compile ALL sources P2P_PYTHON_EXT := p2p$(PYEXT) @@ -115,6 +124,9 @@ P2P_IMPL_SOURCES := \ util/seq_num.cc \ rdma/providers/efa_data_channel_impl.cc \ rdma/providers/ib_data_channel_impl.cc +ifeq ($(USE_CXI),1) + P2P_IMPL_SOURCES += cxi/cxi_endpoint.cc cxi/fabric_dl.cc +endif P2P_IMPL_OBJECTS := $(P2P_IMPL_SOURCES:.cc=.o) SOURCES := engine.cc engine_api.cc nccl/nccl_endpoint.cc $(P2P_IMPL_SOURCES) CORE_OBJECT := engine.o nccl/nccl_endpoint.o $(P2P_IMPL_OBJECTS) $(DL_OBJECTS) diff --git a/p2p/README.md b/p2p/README.md index 4b759f29f..01a2c268e 100644 --- a/p2p/README.md +++ b/p2p/README.md @@ -64,6 +64,12 @@ To enable AWS EFA support, you can do the same as above, and specify `UCCL_P2P_T To enable GCP TCPX support, you can refer to [NIXL_plugin_readme.md](./NIXL_plugin_readme.md). +To enable HPE Slingshot/CXI support, build with libfabric headers and select the `cxi` transport at runtime: +```bash +USE_CXI=1 LIBFABRIC_HOME=/path/to/libfabric make -j install +UCCL_P2P_TRANSPORT=cxi UCCL_P2P_DISABLE_IPC=1 torchrun ... +``` + To build with DietGPU float compression support, you can: ```bash USE_DIETGPU=1 make -j install @@ -92,7 +98,7 @@ torchrun --nnodes=2 --nproc_per_node=1 --node-rank=1 --master_addr= ben Notes: * You may consider exporting `GLOO_SOCKET_IFNAME=xxx NCCL_SOCKET_IFNAME=xxx` if triggering Gloo connectFullMesh failure. * You may consider exporting `UCCL_P2P_RDMA_GID_INDEX` if your cluster requires it for NCCL to run (usually 1, or 3 in some testbed). -* You can specify `UCCL_P2P_TRANSPORT=ib|efa|nccl|tcp|tcpx` at runtime to choose different network backends. The default is `ib` that works for NVIDIA, Broadcom, AMD, and Intel RDMA NICs. +* You can specify `UCCL_P2P_TRANSPORT=ib|efa|nccl|tcp|tcpx|cxi` at runtime to choose different network backends. The default is `ib` that works for NVIDIA, Broadcom, AMD, and Intel RDMA NICs. * **You must first import `torch` before importing `uccl.p2p` for AMD GPUs**, otherwise, `RuntimeError: No HIP GPUs are available` will occur. We guess this is because torch does some extra init for AMD GPUs, in order for Pybind-C++ code to work. * One-sided network write is the default in `benchmark_uccl.py`; use `--mode read` for RDMA read. * To benchmark one-sided IPC write (GPU-to-GPU or CPU-to-GPU), `torchrun --nproc_per_node=2 benchmarks/benchmark_uccl.py --write-ipc`. Use `--device cpu --pinned` for CPU source buffers. @@ -107,7 +113,16 @@ Notes: | UCCL_P2P_RDMA_SL | Service level in RDMA network | 8/3 (EFA/IB) | | UCCL_P2P_RDMA_TC | Traffic class in RDMA network | 104 (IB) | | UCCL_P2P_RDMA_DEV | RDMA devices forced to use (instead of auto-selecting based on PCIe affinity) | none (eg, `irdma-mkp0,irdma-mkp1`) | -| UCCL_P2P_TRANSPORT | Network backend to use at runtime | ib (others: efa/nccl/tcp/tcpx) | +| UCCL_P2P_TRANSPORT | Network backend to use at runtime | ib (others: efa/nccl/tcp/tcpx/cxi) | +| UCCL_CXI_DOMAIN | CXI/libfabric domain to use when `UCCL_P2P_TRANSPORT=cxi` | auto from GPU index, eg `cxi0` | +| UCCL_CXI_DEVICE_INDEX | CXI device index used for automatic domain selection | GPU index modulo 4 | +| UCCL_CXI_THREADING | libfabric threading hint for the CXI domain | endpoint | +| UCCL_CXI_TX_QUEUE_SIZE | CXI transmit queue size | 4096 | +| UCCL_CXI_RX_QUEUE_SIZE | CXI receive queue size | 4096 | +| UCCL_CXI_CQ_SIZE | CXI completion queue size | 8192 | +| UCCL_CXI_DELIVERY_COMPLETE | Request FI_DELIVERY_COMPLETE for CXI sends when set to `1` | unset | +| UCCL_P2P_MAX_INFLIGHT_OPS | Maximum one-sided in-flight operations; CXI defaults lower than RDMA | 32 for CXI, otherwise internal maximum | +| UCCL_LIBFABRIC_SO | Override libfabric shared-library path for the CXI dlsym wrapper | auto-detect `libfabric.so` / `libfabric.so.1` | | UCCL_P2P_COMPRESS_STRATEGY | DietGPU compression strategy (requires `USE_DIETGPU=1` build) | none | | UCCL_RDMA_ADAPTIVE_SLEEP | Enable adaptive sleeping on proxy threads, by putting the proxy threads into a sleeping state if there have been no new work requests / RDMA completion events after 120s. | null | diff --git a/p2p/cxi/cxi_endpoint.cc b/p2p/cxi/cxi_endpoint.cc new file mode 100644 index 000000000..45ea7f292 --- /dev/null +++ b/p2p/cxi/cxi_endpoint.cc @@ -0,0 +1,716 @@ +#ifdef USE_CXI + +#include "cxi_endpoint.h" +#include "engine.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr uint32_t kCxiEndpointInfoMagic = 0x43584950; // "CXIP" +constexpr uint32_t kCxiEndpointInfoVersion = 1; + +struct CxiEndpointInfoHeader { + uint32_t magic = kCxiEndpointInfoMagic; + uint32_t version = kCxiEndpointInfoVersion; + int32_t gpu_index = -1; + uint16_t oob_port = 0; + uint16_t ep_name_size = 0; +}; + +void check_fi(char const* what, int ret) { + if (ret != 0) { + throw std::runtime_error(std::string(what) + ": " + fi_strerror(-ret)); + } +} + +fi_threading threading_hint() { + char const* value = std::getenv("UCCL_CXI_THREADING"); + if (!value || std::strcmp(value, "endpoint") == 0) return FI_THREAD_ENDPOINT; + if (std::strcmp(value, "completion") == 0) return FI_THREAD_COMPLETION; + if (std::strcmp(value, "domain") == 0) return FI_THREAD_DOMAIN; + if (std::strcmp(value, "fid") == 0) return FI_THREAD_FID; + if (std::strcmp(value, "safe") == 0) return FI_THREAD_SAFE; + if (std::strcmp(value, "unspec") == 0) return FI_THREAD_UNSPEC; + throw std::runtime_error(std::string("Invalid UCCL_CXI_THREADING=") + value); +} + +int cxi_device_index_for_gpu(int gpu_index) { + char const* value = std::getenv("UCCL_CXI_DEVICE_INDEX"); + if (value && value[0] != '\0') return std::atoi(value); + if (gpu_index < 0 || static_cast(gpu_index) == INVALID_GPU) { + return -1; + } + return gpu_index % 4; +} + +std::string cxi_domain_name_for_gpu(int gpu_index) { + char const* domain = std::getenv("UCCL_CXI_DOMAIN"); + if (domain && domain[0] != '\0') return domain; + + int const device_index = cxi_device_index_for_gpu(gpu_index); + if (device_index < 0) return ""; + + std::ostringstream os; + os << "cxi" << device_index; + return os.str(); +} + +size_t cxi_size_env(char const* name, size_t fallback) { + char const* value = std::getenv(name); + if (!value || value[0] == '\0') return fallback; + char* end = nullptr; + unsigned long parsed = std::strtoul(value, &end, 10); + if (end == value || parsed == 0) return fallback; + return static_cast(parsed); +} + +bool is_cuda_pointer(void* ptr, int& cuda_device) { + cudaPointerAttributes attrs{}; + cudaError_t err = cudaPointerGetAttributes(&attrs, ptr); + if (err != cudaSuccess) { + cudaGetLastError(); + return false; + } + if (attrs.type == cudaMemoryTypeDevice || attrs.type == cudaMemoryTypeManaged) { + cuda_device = attrs.device; + return true; + } + return false; +} + +std::string cq_error_string(fid_cq* cq, fi_cq_err_entry const& err) { + char buf[256]; + char const* msg = + fi_cq_strerror(cq, err.prov_errno, err.err_data, buf, sizeof(buf)); + if (msg) return msg; + return fi_strerror(err.err); +} + +} // namespace + +CxiEndpoint::CxiEndpoint(int gpu_index, uint64_t port) + : gpu_index_(gpu_index) { + if (gpu_index != INVALID_GPU) { + initialize_rdma_ctx_for_gpu(gpu_index); + } + + oob_server_ = std::make_shared( + static_cast(port), + [this](std::string const& input, std::string& output, + std::string const& ip, int client_port) { + this->process_meta(input, output, ip, client_port); + }); + oob_client_ = std::make_shared(); + + if (!oob_server_->start()) { + UCCL_LOG(ERROR) << "Failed to start CXI OOB server"; + throw std::runtime_error("Failed to start CXI OOB server"); + } + if (!oob_client_->start()) { + UCCL_LOG(ERROR) << "Failed to start CXI OOB client"; + throw std::runtime_error("Failed to start CXI OOB client"); + } +} + +CxiEndpoint::~CxiEndpoint() { + if (oob_client_) oob_client_->stop(); + if (oob_server_) oob_server_->stop(); + + { + std::lock_guard lock(op_mutex_); + inflight_ops_.clear(); + } + + if (av_) fi_close(&av_->fid); + if (cq_) fi_close(&cq_->fid); + if (ep_) fi_close(&ep_->fid); + if (domain_) fi_close(&domain_->fid); + if (fabric_) fi_close(&fabric_->fid); + if (info_) fi_freeinfo(info_); +} + +bool CxiEndpoint::initialize_rdma_ctx_for_gpu( + int gpu_index, std::vector const& device_ids) { + (void)device_ids; + gpu_index_ = gpu_index; + if (fabric_initialized_) return true; + + init_fabric(gpu_index); + fabric_initialized_ = true; + UCCL_LOG(INFO) << "CxiEndpoint initialized for GPU " << gpu_index + << " on domain " << cxi_domain_name_for_gpu(gpu_index); + return true; +} + +void CxiEndpoint::init_fabric(int gpu_index) { + fi_info* hints = fi_allocinfo(); + if (!hints) throw std::runtime_error("fi_allocinfo failed"); + + hints->fabric_attr->prov_name = strdup("cxi"); + std::string domain_name = cxi_domain_name_for_gpu(gpu_index); + if (!domain_name.empty()) { + hints->domain_attr->name = strdup(domain_name.c_str()); + } + hints->ep_attr->type = FI_EP_RDM; + hints->caps = FI_TAGGED | FI_MSG | FI_HMEM | FI_RMA | FI_READ | FI_WRITE | + FI_REMOTE_WRITE | FI_REMOTE_READ | FI_LOCAL_COMM | + FI_REMOTE_COMM; + hints->mode = FI_CONTEXT | FI_CONTEXT2; + hints->domain_attr->threading = threading_hint(); + hints->domain_attr->control_progress = FI_PROGRESS_UNSPEC; + hints->domain_attr->data_progress = FI_PROGRESS_UNSPEC; + hints->domain_attr->mr_mode = FI_MR_LOCAL | FI_MR_HMEM | FI_MR_ENDPOINT | + FI_MR_VIRT_ADDR | FI_MR_ALLOCATED | + FI_MR_PROV_KEY; + hints->domain_attr->mr_key_size = 2; + hints->tx_attr->size = cxi_size_env("UCCL_CXI_TX_QUEUE_SIZE", 4096); + hints->rx_attr->size = cxi_size_env("UCCL_CXI_RX_QUEUE_SIZE", 4096); + hints->tx_attr->msg_order = FI_ORDER_SAS; + hints->rx_attr->msg_order = FI_ORDER_SAS; + + try { + check_fi("fi_getinfo(cxi)", fi_getinfo(FI_VERSION(1, 18), nullptr, nullptr, + 0, hints, &info_)); + char const* dc = std::getenv("UCCL_CXI_DELIVERY_COMPLETE"); + if (dc && dc[0] == '1') { + info_->tx_attr->op_flags |= FI_DELIVERY_COMPLETE; + UCCL_LOG(INFO) << "CXI FI_DELIVERY_COMPLETE enabled"; + } + + check_fi("fi_fabric", fi_fabric(info_->fabric_attr, &fabric_, nullptr)); + check_fi("fi_domain", fi_domain(fabric_, info_, &domain_, nullptr)); + check_fi("fi_endpoint", fi_endpoint(domain_, info_, &ep_, nullptr)); + + fi_cq_attr cq_attr{}; + cq_attr.format = FI_CQ_FORMAT_CONTEXT; + cq_attr.size = cxi_size_env("UCCL_CXI_CQ_SIZE", 8192); + check_fi("fi_cq_open", fi_cq_open(domain_, &cq_attr, &cq_, nullptr)); + check_fi("fi_ep_bind(cq)", + fi_ep_bind(ep_, &cq_->fid, FI_TRANSMIT | FI_RECV)); + + fi_av_attr av_attr{}; + av_attr.type = FI_AV_TABLE; + check_fi("fi_av_open", fi_av_open(domain_, &av_attr, &av_, nullptr)); + check_fi("fi_ep_bind(av)", fi_ep_bind(ep_, &av_->fid, 0)); + +#ifdef FI_OPT_CUDA_API_PERMITTED + bool cuda_api_permitted = false; + check_fi("fi_setopt(FI_OPT_CUDA_API_PERMITTED)", + fi_setopt(&ep_->fid, FI_OPT_ENDPOINT, + FI_OPT_CUDA_API_PERMITTED, &cuda_api_permitted, + sizeof(cuda_api_permitted))); +#endif + + check_fi("fi_enable", fi_enable(ep_)); + } catch (...) { + fi_freeinfo(hints); + throw; + } + + fi_freeinfo(hints); +} + +uint16_t CxiEndpoint::get_p2p_listen_port() { + return oob_server_ ? oob_server_->get_port() : 0; +} + +int CxiEndpoint::get_p2p_listen_fd() { + return oob_server_ ? oob_server_->get_listen_fd() : -1; +} + +std::shared_ptr CxiEndpoint::get_oob_client() { + return oob_client_; +} + +std::string CxiEndpoint::get_oob_conn_key(uint64_t peer_id) const { + std::shared_lock lock(peer_oob_conn_keys_mutex_); + auto it = peer_oob_conn_keys_.find(peer_id); + return it == peer_oob_conn_keys_.end() ? "" : it->second; +} + +CxiEndpoint::EndpointInfo CxiEndpoint::local_endpoint_info() const { + if (!fabric_initialized_ || !ep_) { + throw std::runtime_error("CXI endpoint not initialized"); + } + + EndpointInfo info; + info.oob_port = oob_server_ ? oob_server_->get_port() : 0; + info.gpu_index = gpu_index_; + info.ep_name.resize(512); + size_t len = info.ep_name.size(); + check_fi("fi_getname", fi_getname(&ep_->fid, info.ep_name.data(), &len)); + info.ep_name.resize(len); + return info; +} + +std::string CxiEndpoint::serialize_endpoint_info(EndpointInfo const& info) const { + if (info.ep_name.size() > std::numeric_limits::max()) { + throw std::runtime_error("CXI endpoint name too large"); + } + + CxiEndpointInfoHeader header; + header.gpu_index = info.gpu_index; + header.oob_port = info.oob_port; + header.ep_name_size = static_cast(info.ep_name.size()); + + std::string bytes(sizeof(header) + info.ep_name.size(), '\0'); + std::memcpy(bytes.data(), &header, sizeof(header)); + if (!info.ep_name.empty()) { + std::memcpy(bytes.data() + sizeof(header), info.ep_name.data(), + info.ep_name.size()); + } + return bytes; +} + +CxiEndpoint::EndpointInfo CxiEndpoint::deserialize_endpoint_info( + std::string const& bytes) const { + if (bytes.size() < sizeof(CxiEndpointInfoHeader)) { + throw std::runtime_error("CXI endpoint metadata too short"); + } + + CxiEndpointInfoHeader header{}; + std::memcpy(&header, bytes.data(), sizeof(header)); + if (header.magic != kCxiEndpointInfoMagic || + header.version != kCxiEndpointInfoVersion) { + throw std::runtime_error("Invalid CXI endpoint metadata"); + } + if (bytes.size() != sizeof(header) + header.ep_name_size) { + throw std::runtime_error("CXI endpoint metadata length mismatch"); + } + + EndpointInfo info; + info.oob_port = header.oob_port; + info.gpu_index = header.gpu_index; + info.ep_name.resize(header.ep_name_size); + if (header.ep_name_size > 0) { + std::memcpy(info.ep_name.data(), bytes.data() + sizeof(header), + header.ep_name_size); + } + return info; +} + +fi_addr_t CxiEndpoint::insert_peer(EndpointInfo const& info) { + if (!av_) throw std::runtime_error("CXI AV missing"); + if (info.ep_name.empty()) { + throw std::runtime_error("CXI peer endpoint name is empty"); + } + + fi_addr_t addr = FI_ADDR_UNSPEC; + int ret = fi_av_insert(av_, info.ep_name.data(), 1, &addr, 0, nullptr); + if (ret != 1) check_fi("fi_av_insert", ret < 0 ? ret : -FI_EINVAL); + return addr; +} + +ConnID CxiEndpoint::uccl_connect(int remote_gpuidx, std::string remote_ip, + uint16_t remote_port) { + int32_t peer_id = + next_send_peer_id_.fetch_add(1, std::memory_order_relaxed); + + std::string conn_key; + while (conn_key.empty()) { + conn_key = oob_client_->connect_to_server(remote_ip, remote_port); + if (conn_key.empty()) std::this_thread::sleep_for(std::chrono::seconds(1)); + } + { + std::unique_lock lock(peer_oob_conn_keys_mutex_); + peer_oob_conn_keys_[peer_id] = conn_key; + } + + EndpointInfo local_info = local_endpoint_info(); + std::string payload = serialize_endpoint_info(local_info); + + auto promise = std::make_shared>(); + std::future future = promise->get_future(); + bool sent = oob_client_->send_meta( + conn_key, payload, + [this, promise](std::string const& response) { + promise->set_value(deserialize_endpoint_info(response)); + }); + if (!sent) { + UCCL_LOG(ERROR) << "Failed to send CXI endpoint metadata"; + return ConnID{nullptr, -1, -1, UINT64_MAX}; + } + + auto const timeout_ms = std::chrono::milliseconds(10000); + if (future.wait_for(timeout_ms) == std::future_status::timeout) { + UCCL_LOG(ERROR) << "Timeout waiting for CXI endpoint handshake"; + return ConnID{nullptr, -1, -1, UINT64_MAX}; + } + + EndpointInfo remote_info = future.get(); + fi_addr_t addr = insert_peer(remote_info); + { + std::unique_lock lock(peer_mutex_); + peers_[peer_id] = Peer{addr, remote_ip, remote_port, remote_gpuidx}; + } + + ConnID conn_id; + conn_id.context = reinterpret_cast(static_cast(peer_id)); + conn_id.sock_fd = 0; + conn_id.dev = gpu_index_; + conn_id.peer_id = peer_id; + return conn_id; +} + +ConnID CxiEndpoint::uccl_accept(std::string& remote_ip, int* remote_gpuidx) { + AcceptedMeta accepted; + uint64_t peer_id = UINT64_MAX; + + while (!stop_accept_.load(std::memory_order_acquire)) { + { + std::unique_lock lock(accepted_meta_mutex_); + if (!accepted_meta_.empty()) { + auto it = accepted_meta_.begin(); + peer_id = it->first; + accepted = it->second; + accepted_meta_.erase(it); + break; + } + } + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + + if (peer_id == UINT64_MAX) { + return ConnID{nullptr, -1, -1, UINT64_MAX}; + } + + remote_ip = accepted.ip; + if (remote_gpuidx) *remote_gpuidx = accepted.gpu_id; + + ConnID conn_id; + conn_id.context = reinterpret_cast(static_cast(peer_id)); + conn_id.sock_fd = 0; + conn_id.dev = gpu_index_; + conn_id.peer_id = peer_id; + return conn_id; +} + +void CxiEndpoint::stop_accept() { + stop_accept_.store(true, std::memory_order_release); +} + +void CxiEndpoint::process_meta(std::string const& input, std::string& output, + std::string const& client_ip, + int client_port) { + if (input.size() >= sizeof(NotifyMsg)) { + NotifyMsg const* notify_msg = + reinterpret_cast(input.data()); + if (notify_msg->magic == NOTIFY_MSG_MAGIC) { + std::lock_guard lock(notify_mutex); + notify_list.push_back(*notify_msg); + output = ""; + return; + } + } + + EndpointInfo peer_info = deserialize_endpoint_info(input); + fi_addr_t addr = insert_peer(peer_info); + uint64_t peer_id = + next_recv_peer_id_.fetch_add(1, std::memory_order_relaxed); + + { + std::unique_lock lock(peer_mutex_); + peers_[peer_id] = + Peer{addr, client_ip, static_cast(client_port), + peer_info.gpu_index}; + } + + { + std::unique_lock lock(accepted_meta_mutex_); + AcceptedMeta accepted; + accepted.ip = client_ip; + accepted.port = static_cast(client_port); + accepted.gpu_id = peer_info.gpu_index; + accepted.peer_id = peer_id; + accepted_meta_[peer_id] = accepted; + } + + if (peer_info.oob_port > 0) { + std::string reverse_key = + oob_client_->connect_to_server(client_ip, peer_info.oob_port); + if (!reverse_key.empty()) { + std::unique_lock lock(peer_oob_conn_keys_mutex_); + peer_oob_conn_keys_[peer_id] = reverse_key; + } + } + + output = serialize_endpoint_info(local_endpoint_info()); +} + +int CxiEndpoint::uccl_regmr(void* data, size_t len, + std::shared_ptr& region) { + if (!fabric_initialized_) { + UCCL_LOG(ERROR) << "CXI endpoint not initialized before memory registration"; + return -1; + } + if (!data || len == 0) { + UCCL_LOG(ERROR) << "Invalid CXI memory registration"; + return -1; + } + + auto out = std::make_shared(); + out->addr = data; + out->len = len; + + int cuda_device = -1; + if (is_cuda_pointer(data, cuda_device)) { + iovec iov{}; + iov.iov_base = data; + iov.iov_len = len; + + fi_mr_attr mr_attr{}; + mr_attr.mr_iov = &iov; + mr_attr.iov_count = 1; + mr_attr.access = FI_SEND | FI_RECV | FI_READ | FI_WRITE | + FI_REMOTE_WRITE | FI_REMOTE_READ; + mr_attr.iface = FI_HMEM_CUDA; + mr_attr.device.cuda = cuda_device; + + int ret = fi_mr_regattr(domain_, &mr_attr, 0, &out->mr); + if (ret != 0) { + UCCL_LOG(ERROR) << "fi_mr_regattr(cuda) failed: " + << fi_strerror(-ret); + return -1; + } + } else { + int ret = fi_mr_reg(domain_, data, len, + FI_SEND | FI_RECV | FI_READ | FI_WRITE | + FI_REMOTE_WRITE | FI_REMOTE_READ, + 0, 0, 0, &out->mr, nullptr); + if (ret != 0) { + UCCL_LOG(ERROR) << "fi_mr_reg(host) failed: " << fi_strerror(-ret); + return -1; + } + } + + if (info_->domain_attr->mr_mode & FI_MR_ENDPOINT) { + int ret = fi_mr_bind(out->mr, &ep_->fid, 0); + if (ret != 0) { + UCCL_LOG(ERROR) << "fi_mr_bind(ep) failed: " << fi_strerror(-ret); + fi_close(&out->mr->fid); + return -1; + } + ret = fi_mr_enable(out->mr); + if (ret != 0) { + UCCL_LOG(ERROR) << "fi_mr_enable failed: " << fi_strerror(-ret); + fi_close(&out->mr->fid); + return -1; + } + } + + out->key = fi_mr_key(out->mr); + region = out; + return 0; +} + +void CxiEndpoint::uccl_deregmr( + std::shared_ptr const& region) { + if (!region || !region->mr) return; + fi_close(®ion->mr->fid); +} + +int CxiEndpoint::uccl_read_async( + ConnID const& conn, std::shared_ptr const& local_mr, + void* dst, size_t size, FifoItem const& fifo_item, UcclRequest* ureq) { + return post_rma(true, conn, local_mr, dst, size, fifo_item, ureq); +} + +int CxiEndpoint::uccl_write_async( + ConnID const& conn, std::shared_ptr const& local_mr, + void* src, size_t size, FifoItem const& fifo_item, UcclRequest* ureq) { + return post_rma(false, conn, local_mr, src, size, fifo_item, ureq); +} + +int CxiEndpoint::post_rma(bool is_read, ConnID const& conn, + std::shared_ptr const& local_mr, + void* local, size_t size, + FifoItem const& fifo_item, UcclRequest* ureq) { + if (!local_mr || !local_mr->mr || !local || !ureq) return -1; + + CxiFifoMetadata metadata; + if (!decode_cxi_fifo_metadata(fifo_item, metadata)) { + UCCL_LOG(ERROR) << "Invalid CXI FIFO metadata"; + return -1; + } + + uintptr_t const local_addr = reinterpret_cast(local); + uintptr_t const local_base = reinterpret_cast(local_mr->addr); + if (local_addr < local_base || + local_addr + size > local_base + local_mr->len) { + UCCL_LOG(ERROR) << "CXI local range is outside registered MR"; + return -1; + } + if (fifo_item.addr < metadata.base || + fifo_item.addr + size > metadata.base + metadata.len) { + UCCL_LOG(ERROR) << "CXI remote range is outside advertised MR"; + return -1; + } + + Peer peer; + { + std::shared_lock lock(peer_mutex_); + auto it = peers_.find(conn.peer_id); + if (it == peers_.end()) { + UCCL_LOG(ERROR) << "Unknown CXI peer_id " << conn.peer_id; + return -1; + } + peer = it->second; + } + + auto op = std::make_unique(); + op->id = static_cast( + next_request_id_.fetch_add(1, std::memory_order_relaxed)); + uint64_t const remote_offset = fifo_item.addr - metadata.base; + + ssize_t rc; + { + std::lock_guard fabric_lock(fabric_mutex_); + if (is_read) { + rc = fi_read(ep_, local, size, fi_mr_desc(local_mr->mr), peer.addr, + remote_offset, metadata.key, &op->ctx); + } else { + rc = fi_write(ep_, local, size, fi_mr_desc(local_mr->mr), peer.addr, + remote_offset, metadata.key, &op->ctx); + } + + if (rc == -FI_EAGAIN || rc == -FI_EIO) { + poll_cq_locked(); + std::this_thread::yield(); + return UCCL_POST_TRANSIENT; + } + } + if (rc != 0) { + std::ostringstream os; + os << (is_read ? "fi_read" : "fi_write") << " failed: " + << fi_strerror(-rc) << " rc=" << rc << " peer_id=" << conn.peer_id + << " peer_gpu=" << peer.gpu_index << " size=" << size + << " local=0x" << std::hex << local_addr << " local_base=0x" + << local_base << " local_len=0x" << local_mr->len + << " remote=0x" << fifo_item.addr << " remote_base=0x" + << metadata.base << " remote_len=0x" << metadata.len + << " remote_offset=0x" << remote_offset << " key=0x" << metadata.key + << std::dec; + UCCL_LOG(ERROR) << os.str(); + return -1; + } + + uint32_t const request_id = static_cast(op->id); + { + std::lock_guard lock(op_mutex_); + inflight_ops_[request_id] = std::move(op); + } + + ureq->type = is_read ? ReqType::ReqRead : ReqType::ReqWrite; + ureq->peer_id = conn.peer_id; + ureq->engine_idx = request_id; + return static_cast(request_id); +} + +void CxiEndpoint::poll_cq() { + std::lock_guard fabric_lock(fabric_mutex_); + poll_cq_locked(); +} + +void CxiEndpoint::poll_cq_locked() { + if (!cq_) return; + + for (;;) { + fi_cq_entry entries[16]{}; + ssize_t rc = fi_cq_read(cq_, entries, 16); + if (rc > 0) { + std::lock_guard lock(op_mutex_); + for (ssize_t i = 0; i < rc; ++i) { + auto* ctx = reinterpret_cast(entries[i].op_context); + if (ctx) ctx->done = true; + } + continue; + } + if (rc == -FI_EAGAIN) return; + if (rc == -FI_EAVAIL) { + fi_cq_err_entry err{}; + ssize_t err_rc = fi_cq_readerr(cq_, &err, 0); + std::string error_message = + err_rc >= 0 ? cq_error_string(cq_, err) + : std::string("fi_cq_readerr failed: ") + + fi_strerror(-err_rc); + { + std::lock_guard lock(op_mutex_); + auto* ctx = reinterpret_cast(err.op_context); + if (ctx) { + ctx->done = true; + ctx->failed = true; + ctx->err = err.err; + ctx->prov_errno = err.prov_errno; + ctx->error_message = error_message; + } + } + UCCL_LOG(ERROR) << "CXI CQ error: " << error_message; + continue; + } + + UCCL_LOG(ERROR) << "fi_cq_read failed: " << fi_strerror(-rc); + return; + } +} + +bool CxiEndpoint::check_send_complete_once(uint64_t peer_id, + int64_t request_id) { + (void)peer_id; + poll_cq(); + + std::lock_guard lock(op_mutex_); + auto it = inflight_ops_.find(request_id); + if (it == inflight_ops_.end()) return true; + if (!it->second->done) return false; + if (it->second->failed) { + UCCL_LOG(ERROR) << "CXI transfer failed: request_id=" << request_id + << " peer_id=" << peer_id << " err=" << it->second->err + << " prov_errno=" << it->second->prov_errno << " " + << it->second->error_message; + std::abort(); + } + inflight_ops_.erase(it); + return true; +} + +void CxiEndpoint::send_routine() { poll_cq(); } + +void CxiEndpoint::recv_routine() { poll_cq(); } + +int CxiEndpoint::send_notification(uint64_t peer_id, + NotifyMsg const& notification) const { + std::string conn_key = get_oob_conn_key(peer_id); + if (conn_key.empty() || !oob_client_) return -1; + + std::string payload(reinterpret_cast(¬ification), + sizeof(NotifyMsg)); + return oob_client_->send_meta(conn_key, payload) ? sizeof(NotifyMsg) : -1; +} + +void encode_cxi_fifo_metadata(CxiMemoryRegion const& region, FifoItem& item) { + CxiFifoMetadata metadata; + metadata.base = reinterpret_cast(region.addr); + metadata.key = region.key; + metadata.len = region.len; + std::memset(item.padding, 0, sizeof(item.padding)); + std::memcpy(item.padding, &metadata, sizeof(metadata)); +} + +bool decode_cxi_fifo_metadata(FifoItem const& item, + CxiFifoMetadata& metadata) { + std::memcpy(&metadata, item.padding, sizeof(metadata)); + return metadata.base != 0 && metadata.len != 0; +} + +#endif // USE_CXI diff --git a/p2p/cxi/cxi_endpoint.h b/p2p/cxi/cxi_endpoint.h new file mode 100644 index 000000000..eaa7b125f --- /dev/null +++ b/p2p/cxi/cxi_endpoint.h @@ -0,0 +1,153 @@ +#pragma once + +#ifdef USE_CXI + +#include "common.h" +#include "epoll_client.h" +#include "epoll_server.h" +#include "util/debug.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct CxiMemoryRegion { + void* addr = nullptr; + size_t len = 0; + fid_mr* mr = nullptr; + uint64_t key = 0; +}; + +struct CxiFifoMetadata { + uint64_t base = 0; + uint64_t key = 0; + uint64_t len = 0; +}; + +static_assert(sizeof(CxiFifoMetadata) <= sizeof(FifoItem::padding), + "CXI FIFO metadata must fit in FifoItem padding"); + +struct UcclRequest; + +class CxiEndpoint { + public: + explicit CxiEndpoint(int gpu_index = INVALID_GPU, uint64_t port = 0); + ~CxiEndpoint(); + + bool initialize_rdma_ctx_for_gpu( + int gpu_index, + std::vector const& device_ids = std::vector()); + void create_unified_p2p_socket() {} + + int gpu_index() const { return gpu_index_; } + uint16_t get_p2p_listen_port(); + int get_p2p_listen_fd(); + std::shared_ptr get_oob_client(); + std::string get_oob_conn_key(uint64_t peer_id) const; + + ConnID uccl_connect(int remote_gpuidx, std::string remote_ip, + uint16_t remote_port); + ConnID uccl_accept(std::string& remote_ip, int* remote_gpuidx); + void stop_accept(); + + int uccl_regmr(void* data, size_t len, + std::shared_ptr& region); + void uccl_deregmr(std::shared_ptr const& region); + + int uccl_read_async(ConnID const& conn, + std::shared_ptr const& local_mr, + void* dst, size_t size, FifoItem const& fifo_item, + UcclRequest* ureq); + int uccl_write_async(ConnID const& conn, + std::shared_ptr const& local_mr, + void* src, size_t size, FifoItem const& fifo_item, + UcclRequest* ureq); + + bool check_send_complete_once(uint64_t peer_id, int64_t request_id); + void send_routine(); + void recv_routine(); + void flush_all_sends() {} + + int send_notification(uint64_t peer_id, NotifyMsg const& notification) const; + + private: + struct Peer { + fi_addr_t addr = FI_ADDR_UNSPEC; + std::string ip; + uint16_t port = 0; + int gpu_index = -1; + }; + + struct OpContext { + fi_context2 ctx{}; + int64_t id = -1; + bool done = false; + bool failed = false; + int err = 0; + int prov_errno = 0; + std::string error_message; + }; + + struct EndpointInfo { + std::vector ep_name; + uint16_t oob_port = 0; + int gpu_index = -1; + }; + + void init_fabric(int gpu_index); + EndpointInfo local_endpoint_info() const; + fi_addr_t insert_peer(EndpointInfo const& info); + void process_meta(std::string const& input, std::string& output, + std::string const& client_ip, int client_port); + std::string serialize_endpoint_info(EndpointInfo const& info) const; + EndpointInfo deserialize_endpoint_info(std::string const& bytes) const; + int post_rma(bool is_read, ConnID const& conn, + std::shared_ptr const& local_mr, void* local, + size_t size, FifoItem const& fifo_item, UcclRequest* ureq); + void poll_cq(); + void poll_cq_locked(); + + int gpu_index_ = INVALID_GPU; + bool fabric_initialized_ = false; + std::atomic stop_accept_{false}; + std::atomic next_send_peer_id_{0}; + std::atomic next_recv_peer_id_{0}; + std::atomic next_request_id_{0}; + + fi_info* info_ = nullptr; + fid_fabric* fabric_ = nullptr; + fid_domain* domain_ = nullptr; + fid_ep* ep_ = nullptr; + fid_cq* cq_ = nullptr; + fid_av* av_ = nullptr; + + std::shared_ptr oob_client_; + std::shared_ptr oob_server_; + + mutable std::shared_mutex peer_mutex_; + std::unordered_map peers_; + mutable std::shared_mutex peer_oob_conn_keys_mutex_; + std::unordered_map peer_oob_conn_keys_; + + mutable std::shared_mutex accepted_meta_mutex_; + std::unordered_map accepted_meta_; + + mutable std::mutex fabric_mutex_; + std::mutex op_mutex_; + std::unordered_map> inflight_ops_; +}; + +void encode_cxi_fifo_metadata(CxiMemoryRegion const& region, FifoItem& item); +bool decode_cxi_fifo_metadata(FifoItem const& item, CxiFifoMetadata& metadata); + +#endif // USE_CXI diff --git a/p2p/cxi/fabric_dl.cc b/p2p/cxi/fabric_dl.cc new file mode 100644 index 000000000..07e5f2a58 --- /dev/null +++ b/p2p/cxi/fabric_dl.cc @@ -0,0 +1,44 @@ +// Linker-level dlsym wrappers for libfabric functions. +// Provides exported fi_* symbols via dlopen/dlsym instead of linking -lfabric. + +#include "fabric_dl.h" + +static void* fabric_resolve(char const* name) { + return fabric_dl::resolve(name); +} + +extern "C" { + +int fi_getinfo(uint32_t version, char const* node, char const* service, + uint64_t flags, fi_info const* hints, fi_info** info) { + using FnType = int (*)(uint32_t, char const*, char const*, uint64_t, + fi_info const*, fi_info**); + static FnType fn = reinterpret_cast(fabric_resolve("fi_getinfo")); + return fn(version, node, service, flags, hints, info); +} + +void fi_freeinfo(fi_info* info) { + using FnType = void (*)(fi_info*); + static FnType fn = reinterpret_cast(fabric_resolve("fi_freeinfo")); + return fn(info); +} + +fi_info* fi_dupinfo(fi_info const* info) { + using FnType = fi_info* (*)(fi_info const*); + static FnType fn = reinterpret_cast(fabric_resolve("fi_dupinfo")); + return fn(info); +} + +int fi_fabric(fi_fabric_attr* attr, fid_fabric** fabric, void* context) { + using FnType = int (*)(fi_fabric_attr*, fid_fabric**, void*); + static FnType fn = reinterpret_cast(fabric_resolve("fi_fabric")); + return fn(attr, fabric, context); +} + +char const* fi_strerror(int errnum) { + using FnType = char const* (*)(int); + static FnType fn = reinterpret_cast(fabric_resolve("fi_strerror")); + return fn(errnum); +} + +} // extern "C" diff --git a/p2p/cxi/fabric_dl.h b/p2p/cxi/fabric_dl.h new file mode 100644 index 000000000..3a0b41f8d --- /dev/null +++ b/p2p/cxi/fabric_dl.h @@ -0,0 +1,45 @@ +#pragma once +// Runtime dlsym wrapper for libfabric. +// Keeps for types while avoiding a hard -lfabric link. +// Custom library path: set UCCL_LIBFABRIC_SO. + +#include +#include +#include +#include + +namespace fabric_dl { + +inline void* get_handle() { + static void* h = [] { + char const* custom = std::getenv("UCCL_LIBFABRIC_SO"); + void* handle = custom ? dlopen(custom, RTLD_NOW | RTLD_GLOBAL) : nullptr; + if (!handle) handle = dlopen("libfabric.so", RTLD_NOW | RTLD_GLOBAL); + if (!handle) handle = dlopen("libfabric.so.1", RTLD_NOW | RTLD_GLOBAL); + if (!handle) { + std::fprintf(stderr, "UCCL P2P: failed to load libfabric.so: %s\n", + dlerror()); + } + return handle; + }(); + return h; +} + +inline bool is_available() { return get_handle() != nullptr; } + +inline void* resolve(char const* name) { + void* handle = get_handle(); + if (!handle) { + std::fprintf(stderr, "UCCL P2P: cannot resolve %s without libfabric\n", + name); + std::abort(); + } + void* sym = dlsym(handle, name); + if (!sym) { + std::fprintf(stderr, "UCCL P2P: dlsym(%s) failed: %s\n", name, dlerror()); + std::abort(); + } + return sym; +} + +} // namespace fabric_dl diff --git a/p2p/endpoint_wrapper.h b/p2p/endpoint_wrapper.h index b09305d21..c22774abe 100644 --- a/p2p/endpoint_wrapper.h +++ b/p2p/endpoint_wrapper.h @@ -198,6 +198,10 @@ inline bool uccl_regmr(GenericEndpoint const& ep, void* data, size_t len, (void)len; (void)mhandle; return true; +#ifdef USE_CXI + } else if constexpr (std::is_same_v) { + return s->uccl_regmr(data, len, mhandle->cxi_region) >= 0; +#endif } else { return s->uccl_regmr(data, len, mhandle->mr_array, mhandle->cache_refs, mhandle->compress_ctx) >= 0; @@ -264,7 +268,7 @@ inline SendConnection* uccl_resolve_send_group(GenericEndpoint const& ep, std::visit( [&](auto const& s) { using T = std::decay_t; - if constexpr (!std::is_same_v) { + if constexpr (std::is_same_v) { result = s->get_send_group_raw(peer_id); } }, @@ -332,6 +336,12 @@ inline int uccl_read_async(GenericEndpoint const& ep, Conn* conn, dst, size, nccl_item, &nreq); from_nccl_req(nreq, ureq); return ret; +#ifdef USE_CXI + } else if constexpr (std::is_same_v) { + ureq->type = ReqType::ReqRead; + return s->uccl_read_async(conn->uccl_conn_id_, local_mh->cxi_region, + dst, size, slot_item, ureq); +#endif } else { ureq->type = ReqType::ReqRead; return set_request(s, conn, local_mh, dst, size, slot_item, ureq); @@ -360,6 +370,12 @@ inline int uccl_write_async(GenericEndpoint const& ep, Conn* conn, src, size, nccl_item, &nreq); from_nccl_req(nreq, ureq); return ret; +#ifdef USE_CXI + } else if constexpr (std::is_same_v) { + ureq->type = ReqType::ReqWrite; + return s->uccl_write_async(conn->uccl_conn_id_, local_mh->cxi_region, + src, size, slot_item, ureq); +#endif } else { ureq->type = ReqType::ReqWrite; return set_request(s, conn, local_mh, src, size, slot_item, ureq); @@ -397,6 +413,21 @@ inline int prepare_fifo_metadata(GenericEndpoint const& ep, P2PMhandle* mhandle, (void)mhandle; return s->prepare_fifo_metadata(nullptr, nullptr, data, size, out_buf); +#ifdef USE_CXI + } else if constexpr (std::is_same_v) { + (void)s; + if (!mhandle->cxi_region) return -1; + FifoItem remote_mem_info; + remote_mem_info.addr = reinterpret_cast(data); + remote_mem_info.size = size; + remote_mem_info.rkey = 0; + remote_mem_info.nmsgs = 0; + remote_mem_info.rid = 0; + remote_mem_info.idx = 0; + encode_cxi_fifo_metadata(*mhandle->cxi_region, remote_mem_info); + serialize_fifo_item(remote_mem_info, out_buf); + return 0; +#endif } else { FifoItem remote_mem_info; remote_mem_info.addr = reinterpret_cast(data); @@ -417,6 +448,10 @@ inline void uccl_deregmr(GenericEndpoint const& ep, P2PMhandle* mhandle) { using T = std::decay_t; if constexpr (std::is_same_v) { (void)mhandle; +#ifdef USE_CXI + } else if constexpr (std::is_same_v) { + s->uccl_deregmr(mhandle->cxi_region); +#endif } else { s->uccl_deregmr(mhandle->cache_refs); } diff --git a/p2p/engine.cc b/p2p/engine.cc index 2cd849933..c568e5906 100644 --- a/p2p/engine.cc +++ b/p2p/engine.cc @@ -143,6 +143,27 @@ static inline size_t max_iov_bytes(std::vector const& size_v, return max_bytes; } +static inline bool retryable_post_rc(int rc) { + return rc == -1 || rc == UCCL_POST_TRANSIENT; +} + +size_t Endpoint::max_one_sided_inflight_ops() { + size_t limit = kMaxInflightOps; +#ifdef USE_CXI + if (is_cxi_transport()) limit = 32; +#endif + + char const* env = std::getenv("UCCL_P2P_MAX_INFLIGHT_OPS"); + if (env && env[0] != '\0') { + char* end = nullptr; + unsigned long requested = std::strtoul(env, &end, 10); + if (end != env && requested > 0) { + limit = std::min(requested, kMaxInflightOps); + } + } + return std::max(1, limit); +} + // ShmChannel helper function static inline std::string shm_ring_name(std::string const& from_bdf, std::string const& to_bdf) { @@ -228,6 +249,15 @@ Endpoint::Endpoint(uint32_t const gpu_idx) : passive_accept_(false) { if (is_nccl_transport()) { ep_ = std::make_shared(local_gpu_idx_, 0); numa_node_ = get_numa_node_from_iface(); +#ifdef USE_CXI + } else if (is_cxi_transport()) { + ep_ = std::make_shared(local_gpu_idx_, 0); + numa_node_ = get_numa_node_from_iface(); +#else + } else if (is_cxi_transport()) { + throw std::runtime_error( + "UCCL_P2P_TRANSPORT=cxi requires building p2p with USE_CXI=1"); +#endif } else { ep_ = std::shared_ptr(new RDMAEndpoint(local_gpu_idx_, 0)); } @@ -240,7 +270,7 @@ Endpoint::Endpoint(uint32_t const gpu_idx) : passive_accept_(false) { recv_unified_task_ring_ = uccl::create_ring(sizeof(UnifiedTask*), kTaskRingSize); - if (!is_nccl_transport()) { + if (!is_nccl_transport() && !is_cxi_transport()) { numa_node_ = RdmaDeviceManager::instance().get_numa_node( RdmaDeviceManager::instance().get_best_dev_idx(local_gpu_idx_)[0]); } @@ -301,6 +331,14 @@ Endpoint::Endpoint() : local_gpu_idx_(INVALID_GPU), passive_accept_(false) { if (is_nccl_transport()) { ep_ = std::make_shared(local_gpu_idx_, 0); +#ifdef USE_CXI + } else if (is_cxi_transport()) { + ep_ = std::make_shared(INVALID_GPU, 0); +#else + } else if (is_cxi_transport()) { + throw std::runtime_error( + "UCCL_P2P_TRANSPORT=cxi requires building p2p with USE_CXI=1"); +#endif } else { ep_ = std::shared_ptr(new RDMAEndpoint(INVALID_GPU, 0)); } @@ -670,8 +708,8 @@ bool Endpoint::read(uint64_t conn_id, uint64_t mr_id, void* dst, size_t size, FifoItem curr_slot_item = slot_item; curr_slot_item.size = size; - while (uccl_read_async(ep_, conn, mhandle, dst, size, curr_slot_item, - &ureq) == -1) + while (retryable_post_rc(uccl_read_async(ep_, conn, mhandle, dst, size, + curr_slot_item, &ureq))) ; bool done = false; @@ -705,8 +743,8 @@ bool Endpoint::read_async(uint64_t conn_id, uint64_t mr_id, void* dst, UcclRequest ureq = {}; FifoItem curr_slot_item = slot_item; curr_slot_item.size = size; - while (uccl_read_async(ep_, conn, mhandle, dst, size, curr_slot_item, - &ureq) == -1) { + while (retryable_post_rc(uccl_read_async(ep_, conn, mhandle, dst, size, + curr_slot_item, &ureq))) { } auto* status = new TransferStatus(); @@ -778,13 +816,14 @@ bool Endpoint::readv(uint64_t conn_id, std::vector const& mr_id_v, UcclRequest ureq[kMaxInflightOps] = {}; bool active[kMaxInflightOps] = {false}; + size_t const max_inflight_ops = max_one_sided_inflight_ops(); size_t next_iov = 0; size_t num_completed = 0; size_t num_inflight = 0; while (num_completed < num_iovs) { - while (next_iov < num_iovs && num_inflight < kMaxInflightOps) { + while (next_iov < num_iovs && num_inflight < max_inflight_ops) { size_t slot = 0; while (slot < kMaxInflightOps && active[slot]) { slot++; @@ -799,7 +838,21 @@ bool Endpoint::readv(uint64_t conn_id, std::vector const& mr_id_v, : uccl_read_async(ep_, conn, mhandle_v[next_iov], dst_v[next_iov], size_v[next_iov], slot_item_v[next_iov], &ureq[slot]); - if (rc == -1) break; + if (rc == UCCL_POST_TRANSIENT) { + if (num_inflight > 0) break; + uccl_drive_send(ep_); + uccl_drive_recv(ep_); + std::this_thread::yield(); + continue; + } + if (rc == -1) { + if (num_inflight == 0) { + UCCL_LOG(ERROR) << "readv failed to post iov " << next_iov + << " with no in-flight requests"; + return false; + } + break; + } active[slot] = true; next_iov++; num_inflight++; @@ -877,15 +930,16 @@ bool Endpoint::run_raw_one_sided_pipeline( }; std::array pending_waits{}; + size_t const max_inflight_ops = max_one_sided_inflight_ops(); size_t next_iov = 0; size_t num_completed = 0; size_t num_inflight = 0; auto post_raw_window = [&]() -> bool { - if (next_iov >= num_iovs || num_inflight >= kMaxInflightOps) return true; + if (next_iov >= num_iovs || num_inflight >= max_inflight_ops) return true; size_t const batch_iovs = - std::min(kMaxInflightOps - num_inflight, num_iovs - next_iov); + std::min(max_inflight_ops - num_inflight, num_iovs - next_iov); std::array ops{}; int64_t wr_ids[kMaxInflightOps] = {}; std::array waits{}; @@ -924,7 +978,7 @@ bool Endpoint::run_raw_one_sided_pipeline( }; while (num_completed < num_iovs) { - while (next_iov < num_iovs && num_inflight < kMaxInflightOps) { + while (next_iov < num_iovs && num_inflight < max_inflight_ops) { if (!post_raw_window()) return false; } @@ -965,11 +1019,12 @@ bool Endpoint::write(uint64_t conn_id, uint64_t mr_id, void* src, size_t size, FifoItem curr_slot_item = slot_item; curr_slot_item.size = size; - while ((send_group != nullptr - ? uccl_write_async_on_group(send_group, conn, mhandle, src, size, - curr_slot_item, &ureq) - : uccl_write_async(ep_, conn, mhandle, src, size, curr_slot_item, - &ureq)) == -1) + while (retryable_post_rc( + send_group != nullptr + ? uccl_write_async_on_group(send_group, conn, mhandle, src, size, + curr_slot_item, &ureq) + : uccl_write_async(ep_, conn, mhandle, src, size, curr_slot_item, + &ureq))) ; bool done = false; @@ -1002,8 +1057,8 @@ bool Endpoint::write_async(uint64_t conn_id, uint64_t mr_id, void* src, UcclRequest ureq = {}; FifoItem curr_slot_item = slot_item; curr_slot_item.size = size; - while (uccl_write_async(ep_, conn, mhandle, src, size, curr_slot_item, - &ureq) == -1) { + while (retryable_post_rc(uccl_write_async(ep_, conn, mhandle, src, size, + curr_slot_item, &ureq))) { } auto* status = new TransferStatus(); @@ -1077,13 +1132,14 @@ bool Endpoint::writev(uint64_t conn_id, std::vector const& mr_id_v, UcclRequest ureq[kMaxInflightOps] = {}; bool active[kMaxInflightOps] = {false}; + size_t const max_inflight_ops = max_one_sided_inflight_ops(); size_t next_iov = 0; size_t num_completed = 0; size_t num_inflight = 0; while (num_completed < num_iovs) { - while (next_iov < num_iovs && num_inflight < kMaxInflightOps) { + while (next_iov < num_iovs && num_inflight < max_inflight_ops) { size_t slot = 0; while (slot < kMaxInflightOps && active[slot]) { slot++; @@ -1098,7 +1154,21 @@ bool Endpoint::writev(uint64_t conn_id, std::vector const& mr_id_v, : uccl_write_async(ep_, conn, mhandle_v[next_iov], src_v[next_iov], size_v[next_iov], slot_item_v[next_iov], &ureq[slot]); - if (rc == -1) break; + if (rc == UCCL_POST_TRANSIENT) { + if (num_inflight > 0) break; + uccl_drive_send(ep_); + uccl_drive_recv(ep_); + std::this_thread::yield(); + continue; + } + if (rc == -1) { + if (num_inflight == 0) { + UCCL_LOG(ERROR) << "writev failed to post iov " << next_iov + << " with no in-flight requests"; + return false; + } + break; + } active[slot] = true; next_iov++; num_inflight++; @@ -2072,11 +2142,6 @@ std::string Endpoint::get_oob_conn_key(uint64_t conn_id) const { int Endpoint::send_notification(uint64_t conn_id, NotifyMsg const& notification) const { - if (!is_nccl_transport()) { - (void)conn_id; - (void)notification; - return -1; - } Conn* conn = get_conn(conn_id); if (conn == nullptr) { return -1; @@ -2085,9 +2150,19 @@ int Endpoint::send_notification(uint64_t conn_id, if (peer_id == UINT64_MAX) { return -1; } - auto* nccl_ep = std::get_if>(&ep_); - if (!nccl_ep || !*nccl_ep) return -1; - return (*nccl_ep)->send_notification(peer_id, notification); + if (is_nccl_transport()) { + auto* nccl_ep = std::get_if>(&ep_); + if (!nccl_ep || !*nccl_ep) return -1; + return (*nccl_ep)->send_notification(peer_id, notification); + } +#ifdef USE_CXI + if (is_cxi_transport()) { + auto* cxi_ep = std::get_if>(&ep_); + if (!cxi_ep || !*cxi_ep) return -1; + return (*cxi_ep)->send_notification(peer_id, notification); + } +#endif + return -1; } MR* Endpoint::get_mr(uint64_t mr_id) const { @@ -2124,6 +2199,14 @@ void Endpoint::initialize_engine() { if (is_nccl_transport()) { numa_node_ = get_numa_node_from_iface(); +#ifdef USE_CXI + } else if (is_cxi_transport()) { + numa_node_ = get_numa_node_from_iface(); +#else + } else if (is_cxi_transport()) { + throw std::runtime_error( + "UCCL_P2P_TRANSPORT=cxi requires building p2p with USE_CXI=1"); +#endif } else { numa_node_ = RdmaDeviceManager::instance().get_numa_node( RdmaDeviceManager::instance().get_best_dev_idx(local_gpu_idx_)[0]); diff --git a/p2p/engine.h b/p2p/engine.h index c523dace6..623dbb77a 100644 --- a/p2p/engine.h +++ b/p2p/engine.h @@ -2,6 +2,9 @@ #include "adaptive_sleeper.h" #include "common.h" +#ifdef USE_CXI +#include "cxi_endpoint.h" +#endif #include "nccl_endpoint.h" #include "rdma_endpoint.h" #include "transport_type.h" @@ -26,9 +29,14 @@ extern thread_local bool inside_python; -// Runtime-polymorphic endpoint: holds either RDMA or NCCL endpoint. -using GenericEndpoint = - std::variant, std::shared_ptr>; +// Runtime-polymorphic endpoint. +using GenericEndpoint = std::variant, + std::shared_ptr +#ifdef USE_CXI + , + std::shared_ptr +#endif + >; // Use the RDMA-native request types as the common currency. // The NCCL shim functions in endpoint_wrapper.h convert as needed. @@ -48,6 +56,9 @@ struct P2PMhandle { MRArray mr_array; CompressCtx compress_ctx; std::vector cache_refs; +#ifdef USE_CXI + std::shared_ptr cxi_region; +#endif }; struct MR { @@ -248,6 +259,7 @@ class Endpoint { static constexpr size_t kDirectAsyncNetThreshold = 256 * 1024; static uccl::UCCLLogLevel parse_log_level_from_env(); + static size_t max_one_sided_inflight_ops(); public: /* Create engine threads running in background for a single interface. It also diff --git a/p2p/util/common.h b/p2p/util/common.h index faf489654..65c9b631a 100644 --- a/p2p/util/common.h +++ b/p2p/util/common.h @@ -56,6 +56,7 @@ typedef struct AcceptedMeta { // Notifications static constexpr uint32_t NOTIFY_MSG_MAGIC = 0xDEADDEAD; static constexpr size_t NOTIFY_MSG_SIZE = 256; +static constexpr int UCCL_POST_TRANSIENT = -2; struct NotifyMsg { uint32_t magic; diff --git a/p2p/util/transport_type.h b/p2p/util/transport_type.h index defb7bab7..47ed214fe 100644 --- a/p2p/util/transport_type.h +++ b/p2p/util/transport_type.h @@ -5,7 +5,7 @@ #include #include -enum class TransportType { RDMA, NCCL, EFA }; +enum class TransportType { RDMA, NCCL, EFA, CXI }; inline TransportType get_transport_type() { static TransportType t = [] { @@ -15,6 +15,7 @@ inline TransportType get_transport_type() { std::strcmp(env, "tcpx") == 0) return TransportType::NCCL; if (std::strcmp(env, "efa") == 0) return TransportType::EFA; + if (std::strcmp(env, "cxi") == 0) return TransportType::CXI; return TransportType::RDMA; }(); return t; @@ -27,3 +28,7 @@ inline bool is_nccl_transport() { inline bool is_efa_transport() { return get_transport_type() == TransportType::EFA; } + +inline bool is_cxi_transport() { + return get_transport_type() == TransportType::CXI; +} From 7088689b5e00f1e3e34de0bdf7a9837c2960cd89 Mon Sep 17 00:00:00 2001 From: fergus barratt Date: Tue, 16 Jun 2026 11:50:21 +0100 Subject: [PATCH 2/5] p2p: fail direct posts on hard errors --- p2p/cxi/cxi_endpoint.cc | 6 +++++ p2p/engine.cc | 53 +++++++++++++++++++++++++++-------------- 2 files changed, 41 insertions(+), 18 deletions(-) diff --git a/p2p/cxi/cxi_endpoint.cc b/p2p/cxi/cxi_endpoint.cc index 45ea7f292..6cc5c909c 100644 --- a/p2p/cxi/cxi_endpoint.cc +++ b/p2p/cxi/cxi_endpoint.cc @@ -326,6 +326,10 @@ ConnID CxiEndpoint::uccl_connect(int remote_gpuidx, std::string remote_ip, std::unique_lock lock(peer_oob_conn_keys_mutex_); peer_oob_conn_keys_[peer_id] = conn_key; } + auto erase_oob_conn_key = [this, peer_id] { + std::unique_lock lock(peer_oob_conn_keys_mutex_); + peer_oob_conn_keys_.erase(peer_id); + }; EndpointInfo local_info = local_endpoint_info(); std::string payload = serialize_endpoint_info(local_info); @@ -339,12 +343,14 @@ ConnID CxiEndpoint::uccl_connect(int remote_gpuidx, std::string remote_ip, }); if (!sent) { UCCL_LOG(ERROR) << "Failed to send CXI endpoint metadata"; + erase_oob_conn_key(); return ConnID{nullptr, -1, -1, UINT64_MAX}; } auto const timeout_ms = std::chrono::milliseconds(10000); if (future.wait_for(timeout_ms) == std::future_status::timeout) { UCCL_LOG(ERROR) << "Timeout waiting for CXI endpoint handshake"; + erase_oob_conn_key(); return ConnID{nullptr, -1, -1, UINT64_MAX}; } diff --git a/p2p/engine.cc b/p2p/engine.cc index c568e5906..88461a7d2 100644 --- a/p2p/engine.cc +++ b/p2p/engine.cc @@ -143,10 +143,6 @@ static inline size_t max_iov_bytes(std::vector const& size_v, return max_bytes; } -static inline bool retryable_post_rc(int rc) { - return rc == -1 || rc == UCCL_POST_TRANSIENT; -} - size_t Endpoint::max_one_sided_inflight_ops() { size_t limit = kMaxInflightOps; #ifdef USE_CXI @@ -708,9 +704,14 @@ bool Endpoint::read(uint64_t conn_id, uint64_t mr_id, void* dst, size_t size, FifoItem curr_slot_item = slot_item; curr_slot_item.size = size; - while (retryable_post_rc(uccl_read_async(ep_, conn, mhandle, dst, size, - curr_slot_item, &ureq))) - ; + int rc = UCCL_POST_TRANSIENT; + while (rc == UCCL_POST_TRANSIENT) { + rc = uccl_read_async(ep_, conn, mhandle, dst, size, curr_slot_item, &ureq); + } + if (rc < 0) { + UCCL_LOG(ERROR) << "read failed to post: rc=" << rc; + return false; + } bool done = false; while (!done) { @@ -743,8 +744,13 @@ bool Endpoint::read_async(uint64_t conn_id, uint64_t mr_id, void* dst, UcclRequest ureq = {}; FifoItem curr_slot_item = slot_item; curr_slot_item.size = size; - while (retryable_post_rc(uccl_read_async(ep_, conn, mhandle, dst, size, - curr_slot_item, &ureq))) { + int rc = UCCL_POST_TRANSIENT; + while (rc == UCCL_POST_TRANSIENT) { + rc = uccl_read_async(ep_, conn, mhandle, dst, size, curr_slot_item, &ureq); + } + if (rc < 0) { + UCCL_LOG(ERROR) << "read_async failed to post: rc=" << rc; + return false; } auto* status = new TransferStatus(); @@ -1019,13 +1025,18 @@ bool Endpoint::write(uint64_t conn_id, uint64_t mr_id, void* src, size_t size, FifoItem curr_slot_item = slot_item; curr_slot_item.size = size; - while (retryable_post_rc( - send_group != nullptr - ? uccl_write_async_on_group(send_group, conn, mhandle, src, size, - curr_slot_item, &ureq) - : uccl_write_async(ep_, conn, mhandle, src, size, curr_slot_item, - &ureq))) - ; + int rc = UCCL_POST_TRANSIENT; + while (rc == UCCL_POST_TRANSIENT) { + rc = send_group != nullptr + ? uccl_write_async_on_group(send_group, conn, mhandle, src, size, + curr_slot_item, &ureq) + : uccl_write_async(ep_, conn, mhandle, src, size, curr_slot_item, + &ureq); + } + if (rc < 0) { + UCCL_LOG(ERROR) << "write failed to post: rc=" << rc; + return false; + } bool done = false; while (!done) { @@ -1057,8 +1068,14 @@ bool Endpoint::write_async(uint64_t conn_id, uint64_t mr_id, void* src, UcclRequest ureq = {}; FifoItem curr_slot_item = slot_item; curr_slot_item.size = size; - while (retryable_post_rc(uccl_write_async(ep_, conn, mhandle, src, size, - curr_slot_item, &ureq))) { + int rc = UCCL_POST_TRANSIENT; + while (rc == UCCL_POST_TRANSIENT) { + rc = + uccl_write_async(ep_, conn, mhandle, src, size, curr_slot_item, &ureq); + } + if (rc < 0) { + UCCL_LOG(ERROR) << "write_async failed to post: rc=" << rc; + return false; } auto* status = new TransferStatus(); From 276f517f71e440fc8f9520a3e93af2d05fa96816 Mon Sep 17 00:00:00 2001 From: fergus barratt Date: Tue, 16 Jun 2026 12:44:10 +0100 Subject: [PATCH 3/5] p2p: harden CXI completion contexts --- p2p/cxi/cxi_endpoint.cc | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/p2p/cxi/cxi_endpoint.cc b/p2p/cxi/cxi_endpoint.cc index 6cc5c909c..754a70e1c 100644 --- a/p2p/cxi/cxi_endpoint.cc +++ b/p2p/cxi/cxi_endpoint.cc @@ -89,6 +89,16 @@ bool is_cuda_pointer(void* ptr, int& cuda_device) { return false; } +void set_fi_context_owner(fi_context2& ctx, void* owner) { + ctx = fi_context2{}; + ctx.internal[0] = owner; +} + +void* get_fi_context_owner(void* context) { + auto* fi_ctx = static_cast(context); + return fi_ctx ? fi_ctx->internal[0] : nullptr; +} + std::string cq_error_string(fid_cq* cq, fi_cq_err_entry const& err) { char buf[256]; char const* msg = @@ -523,7 +533,14 @@ int CxiEndpoint::uccl_regmr(void* data, size_t len, void CxiEndpoint::uccl_deregmr( std::shared_ptr const& region) { if (!region || !region->mr) return; - fi_close(®ion->mr->fid); + fid_mr* mr = region->mr; + int ret = fi_close(&mr->fid); + if (ret != 0) { + UCCL_LOG(ERROR) << "fi_close(mr) failed: " << fi_strerror(-ret); + return; + } + region->mr = nullptr; + region->key = 0; } int CxiEndpoint::uccl_read_async( @@ -577,6 +594,7 @@ int CxiEndpoint::post_rma(bool is_read, ConnID const& conn, auto op = std::make_unique(); op->id = static_cast( next_request_id_.fetch_add(1, std::memory_order_relaxed)); + set_fi_context_owner(op->ctx, op.get()); uint64_t const remote_offset = fifo_item.addr - metadata.base; ssize_t rc; @@ -637,7 +655,8 @@ void CxiEndpoint::poll_cq_locked() { if (rc > 0) { std::lock_guard lock(op_mutex_); for (ssize_t i = 0; i < rc; ++i) { - auto* ctx = reinterpret_cast(entries[i].op_context); + auto* ctx = + static_cast(get_fi_context_owner(entries[i].op_context)); if (ctx) ctx->done = true; } continue; @@ -652,7 +671,8 @@ void CxiEndpoint::poll_cq_locked() { fi_strerror(-err_rc); { std::lock_guard lock(op_mutex_); - auto* ctx = reinterpret_cast(err.op_context); + auto* ctx = + static_cast(get_fi_context_owner(err.op_context)); if (ctx) { ctx->done = true; ctx->failed = true; From b0a84d915bbe5c97911aab6cba1554b46cd7cd6a Mon Sep 17 00:00:00 2001 From: fergus barratt Date: Tue, 16 Jun 2026 16:05:34 +0100 Subject: [PATCH 4/5] p2p: avoid spinning on transient vector posts --- p2p/engine.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/p2p/engine.cc b/p2p/engine.cc index 88461a7d2..11ae10fbe 100644 --- a/p2p/engine.cc +++ b/p2p/engine.cc @@ -849,7 +849,7 @@ bool Endpoint::readv(uint64_t conn_id, std::vector const& mr_id_v, uccl_drive_send(ep_); uccl_drive_recv(ep_); std::this_thread::yield(); - continue; + return false; } if (rc == -1) { if (num_inflight == 0) { @@ -1176,7 +1176,7 @@ bool Endpoint::writev(uint64_t conn_id, std::vector const& mr_id_v, uccl_drive_send(ep_); uccl_drive_recv(ep_); std::this_thread::yield(); - continue; + return false; } if (rc == -1) { if (num_inflight == 0) { From c728050453a8d00bd55d50dcbbd72334d8b9948d Mon Sep 17 00:00:00 2001 From: fergus barratt Date: Wed, 17 Jun 2026 11:17:37 +0100 Subject: [PATCH 5/5] p2p: always request CXI delivery completion --- p2p/README.md | 1 - p2p/cxi/cxi_endpoint.cc | 7 ++----- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/p2p/README.md b/p2p/README.md index 01a2c268e..dea72d344 100644 --- a/p2p/README.md +++ b/p2p/README.md @@ -120,7 +120,6 @@ Notes: | UCCL_CXI_TX_QUEUE_SIZE | CXI transmit queue size | 4096 | | UCCL_CXI_RX_QUEUE_SIZE | CXI receive queue size | 4096 | | UCCL_CXI_CQ_SIZE | CXI completion queue size | 8192 | -| UCCL_CXI_DELIVERY_COMPLETE | Request FI_DELIVERY_COMPLETE for CXI sends when set to `1` | unset | | UCCL_P2P_MAX_INFLIGHT_OPS | Maximum one-sided in-flight operations; CXI defaults lower than RDMA | 32 for CXI, otherwise internal maximum | | UCCL_LIBFABRIC_SO | Override libfabric shared-library path for the CXI dlsym wrapper | auto-detect `libfabric.so` / `libfabric.so.1` | | UCCL_P2P_COMPRESS_STRATEGY | DietGPU compression strategy (requires `USE_DIETGPU=1` build) | none | diff --git a/p2p/cxi/cxi_endpoint.cc b/p2p/cxi/cxi_endpoint.cc index 754a70e1c..fe708a5b6 100644 --- a/p2p/cxi/cxi_endpoint.cc +++ b/p2p/cxi/cxi_endpoint.cc @@ -192,11 +192,8 @@ void CxiEndpoint::init_fabric(int gpu_index) { try { check_fi("fi_getinfo(cxi)", fi_getinfo(FI_VERSION(1, 18), nullptr, nullptr, 0, hints, &info_)); - char const* dc = std::getenv("UCCL_CXI_DELIVERY_COMPLETE"); - if (dc && dc[0] == '1') { - info_->tx_attr->op_flags |= FI_DELIVERY_COMPLETE; - UCCL_LOG(INFO) << "CXI FI_DELIVERY_COMPLETE enabled"; - } + info_->tx_attr->op_flags |= FI_DELIVERY_COMPLETE; + UCCL_LOG(INFO) << "CXI FI_DELIVERY_COMPLETE enabled"; check_fi("fi_fabric", fi_fabric(info_->fabric_attr, &fabric_, nullptr)); check_fi("fi_domain", fi_domain(fabric_, info_, &domain_, nullptr));