diff --git a/src/utils/device/device_ops.h b/src/utils/device/device_ops.h index 034c1cc887..f373de4427 100644 --- a/src/utils/device/device_ops.h +++ b/src/utils/device/device_ops.h @@ -26,6 +26,7 @@ namespace nixl { class deviceOps; +class hostPublishedDeviceMem; class mappedHostMem; struct mappedHostMemDeleter { @@ -78,6 +79,19 @@ class deviceOps { [[nodiscard]] nixl_status_t allocMappedHostMem(size_t size, mappedHostMem &out) noexcept; + /** + * @brief Allocate zeroed memory the CPU publishes words into and the GPU reads. + * + * Prefers device memory the CPU writes directly, which keeps GPU polling local, and + * falls back to mapped host memory. + * @param[out] out Owning handle; unchanged on failure. + * @retval NIXL_ERR_INVALID_PARAM size is zero. + * @note Only kernels on the device active at allocation may read it, whatever the backing. + * @note This instance must outlive the returned handle. + */ + [[nodiscard]] nixl_status_t + allocHostPublishedMem(size_t size, std::unique_ptr &out) noexcept; + /** * @brief Copy between host and device memory using the default stream. * @note On success, H2D source storage is reusable; D2H destination data is ready. @@ -125,6 +139,15 @@ class deviceOps { virtual void doFreeMappedHostMem(void *host_ptr) noexcept = 0; + /** + * @brief Allocate zeroed device memory the CPU can publish into directly. + * @note Assigns `out` only on success. Any failure falls back to mapped host memory. + */ + [[nodiscard]] virtual nixl_status_t + doAllocHostPublishedMem(size_t, std::unique_ptr &) noexcept { + return NIXL_ERR_NOT_SUPPORTED; + } + private: friend struct deviceMemDeleter; friend struct mappedHostMemDeleter; diff --git a/src/utils/device/device_ops_cuda.cpp b/src/utils/device/device_ops_cuda.cpp index 4df53a1bf9..ff5cc13328 100644 --- a/src/utils/device/device_ops_cuda.cpp +++ b/src/utils/device/device_ops_cuda.cpp @@ -17,9 +17,12 @@ #include "device/device_ops.h" #include + +#include #include #include "common/nixl_log.h" +#include "device/device_ops_cuda_gdrcopy.h" namespace { @@ -136,6 +139,12 @@ class cudaDeviceOps final : public nixl::deviceOps { setActiveDevice(int device_id) noexcept override { return cudaStatus(cudaSetDevice(device_id), "cudaSetDevice"); } + + nixl_status_t + doAllocHostPublishedMem(size_t size, + std::unique_ptr &out) noexcept override { + return nixl::allocGdrCopyPublishedMem(size, out); + } }; } // namespace diff --git a/src/utils/device/device_ops_cuda_gdrcopy.cpp b/src/utils/device/device_ops_cuda_gdrcopy.cpp new file mode 100644 index 0000000000..2312cbd284 --- /dev/null +++ b/src/utils/device/device_ops_cuda_gdrcopy.cpp @@ -0,0 +1,227 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "device/device_ops_cuda_gdrcopy.h" + +#include +#include + +#include +#include +#include +#include +#include + +#include "common/nixl_log.h" +#include "device/host_published_mem.h" + +namespace nixl { +namespace { + + // GDRCopy ABI, unchanged since 2.0, declared from gdrapi.h + // (Copyright (c) 2014-2021, NVIDIA CORPORATION, MIT). + struct gdr; + using gdr_t = gdr *; + + struct gdr_mh_t { + unsigned long h; + }; + + struct gdrApi { + gdr_t (*open)(); + int (*close)(gdr_t); + int (*pin_buffer)(gdr_t, unsigned long, size_t, uint64_t, uint32_t, gdr_mh_t *); + int (*unpin_buffer)(gdr_t, gdr_mh_t); + int (*map)(gdr_t, gdr_mh_t, void **, size_t); + int (*unmap)(gdr_t, gdr_mh_t, void *, size_t); + int (*copy_to_mapping)(gdr_mh_t, void *, const void *, size_t); + }; + + /** GDRCopy pins and maps whole GPU pages. */ + constexpr size_t kGpuPageSize = size_t{1} << 16; + + template + bool + loadSymbol(void *lib, const char *name, Fn &fn) noexcept { + fn = reinterpret_cast(dlsym(lib, name)); + return fn != nullptr; + } + + std::optional + loadGdrApi() noexcept { + // The versioned name first, as NVSHMEM does: runtime-only packages ship just + // libgdrapi.so.2, and the unversioned name is a development symlink. + void *lib = dlopen("libgdrapi.so.2", RTLD_NOW | RTLD_LOCAL); + if (lib == nullptr) { + lib = dlopen("libgdrapi.so", RTLD_NOW | RTLD_LOCAL); + } + if (lib == nullptr) { + NIXL_INFO << "GDRCopy is unavailable: " << dlerror(); + return std::nullopt; + } + gdrApi api{}; + if (!loadSymbol(lib, "gdr_open", api.open) || !loadSymbol(lib, "gdr_close", api.close) || + !loadSymbol(lib, "gdr_pin_buffer", api.pin_buffer) || + !loadSymbol(lib, "gdr_unpin_buffer", api.unpin_buffer) || + !loadSymbol(lib, "gdr_map", api.map) || !loadSymbol(lib, "gdr_unmap", api.unmap) || + !loadSymbol(lib, "gdr_copy_to_mapping", api.copy_to_mapping)) { + NIXL_WARN << "GDRCopy is unusable: " << dlerror(); + dlclose(lib); + return std::nullopt; + } + // A missing driver fails every gdr_open, so detect it once rather than per allocation. + const gdr_t probe = api.open(); + if (probe == nullptr) { + NIXL_INFO << "GDRCopy is unavailable: gdr_open failed"; + dlclose(lib); + return std::nullopt; + } + api.close(probe); + return api; + } + + /** Loads GDRCopy on first use and keeps it for the process; nullptr when unusable. */ + const gdrApi * + gdrcopy() noexcept { + static const std::optional api = loadGdrApi(); + return api ? &*api : nullptr; + } + + /** + * Device memory the CPU writes through a GDRCopy BAR mapping. + * + * Each instance opens its own GDRCopy handle because libgdrapi does not lock the handle's + * pin and map bookkeeping. + */ + class gdrPublishedMem final : public hostPublishedDeviceMem { + public: + gdrPublishedMem(const gdrApi &api, + void *storage, + void *dev_ptr, + size_t size, + size_t mapped_size) noexcept + : hostPublishedDeviceMem(dev_ptr, size, backing::device), + api_(api), + storage_(storage), + mappedSize_(mapped_size) {} + + ~gdrPublishedMem() override { + if (cpu_ != nullptr) { + api_.unmap(gdr_, mh_, cpu_, mappedSize_); + } + if (pinned_) { + api_.unpin_buffer(gdr_, mh_); + } + if (gdr_ != nullptr) { + api_.close(gdr_); + } + const cudaError_t error = cudaFree(storage_); + if (error != cudaSuccess) { + NIXL_WARN << "cudaFree failed: " << cudaGetErrorString(error); + } + } + + /** @brief Map the storage for CPU writes and zero it. */ + [[nodiscard]] nixl_status_t + map() noexcept { + gdr_ = api_.open(); + if (gdr_ == nullptr) { + NIXL_WARN << "GDRCopy cannot back host-published memory: gdr_open failed"; + return NIXL_ERR_NOT_SUPPORTED; + } + if (api_.pin_buffer(gdr_, + reinterpret_cast(devicePointer()), + mappedSize_, + 0, + 0, + &mh_) != 0) { + NIXL_WARN << "GDRCopy cannot back host-published memory: gdr_pin_buffer failed"; + return NIXL_ERR_NOT_SUPPORTED; + } + pinned_ = true; + void *cpu = nullptr; + if (api_.map(gdr_, mh_, &cpu, mappedSize_) != 0) { + NIXL_WARN << "GDRCopy cannot back host-published memory: gdr_map failed"; + return NIXL_ERR_NOT_SUPPORTED; + } + cpu_ = static_cast(cpu); + + // Zero through the mapping: an asynchronous cudaMemset could land after a later + // publish(). + constexpr uint64_t zero = 0; + for (size_t offset = 0; offset < size(); offset += sizeof(zero)) { + if (api_.copy_to_mapping(mh_, cpu_ + offset, &zero, sizeof(zero)) != 0) { + NIXL_WARN << "GDRCopy cannot back host-published memory: zeroing failed"; + return NIXL_ERR_BACKEND; + } + } + return NIXL_SUCCESS; + } + + private: + nixl_status_t + doPublish(size_t offset, uint64_t value) noexcept override { + // gdr_copy_to_mapping fences only after its store, so order earlier host writes here. + std::atomic_thread_fence(std::memory_order_release); + return api_.copy_to_mapping(mh_, cpu_ + offset, &value, sizeof(value)) == 0 ? + NIXL_SUCCESS : + NIXL_ERR_BACKEND; + } + + const gdrApi &api_; + void *storage_; + size_t mappedSize_; + gdr_t gdr_ = nullptr; + gdr_mh_t mh_{}; + bool pinned_ = false; + uint8_t *cpu_ = nullptr; + }; + +} // namespace + +nixl_status_t +allocGdrCopyPublishedMem(size_t size, std::unique_ptr &out) noexcept { + const gdrApi *api = gdrcopy(); + if (api == nullptr) { + return NIXL_ERR_NOT_SUPPORTED; + } + if (size > std::numeric_limits::max() - 2 * kGpuPageSize) { + return NIXL_ERR_INVALID_PARAM; + } + + // Over-allocate by a page so the mapped range can start on a GPU page boundary. + const size_t mapped_size = (size + kGpuPageSize - 1) & ~(kGpuPageSize - 1); + void *storage; + const cudaError_t error = cudaMalloc(&storage, mapped_size + kGpuPageSize - 1); + if (error != cudaSuccess) { + NIXL_WARN << "GDRCopy cannot back host-published memory: cudaMalloc failed: " + << cudaGetErrorString(error); + return NIXL_ERR_BACKEND; + } + const auto aligned = + (reinterpret_cast(storage) + kGpuPageSize - 1) & ~uintptr_t{kGpuPageSize - 1}; + + auto mem = std::make_unique( + *api, storage, reinterpret_cast(aligned), size, mapped_size); + const nixl_status_t status = mem->map(); + if (status != NIXL_SUCCESS) { + return status; + } + out = std::move(mem); + return NIXL_SUCCESS; +} + +} // namespace nixl diff --git a/src/utils/device/device_ops_cuda_gdrcopy.h b/src/utils/device/device_ops_cuda_gdrcopy.h new file mode 100644 index 0000000000..a0b6b8e9e1 --- /dev/null +++ b/src/utils/device/device_ops_cuda_gdrcopy.h @@ -0,0 +1,41 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef NIXL_SRC_UTILS_DEVICE_DEVICE_OPS_CUDA_GDRCOPY_H +#define NIXL_SRC_UTILS_DEVICE_DEVICE_OPS_CUDA_GDRCOPY_H + +#include +#include + +#include + +namespace nixl { + +class hostPublishedDeviceMem; + +/** + * @brief Allocate zeroed device memory on the active device that the CPU writes through a + * GDRCopy mapping. + * @param[out] out Owning handle; unchanged on failure. + * @retval NIXL_ERR_NOT_SUPPORTED GDRCopy is unavailable or cannot map the memory. + * @note libgdrapi and its driver are probed on first use; the result holds for the process. + */ +[[nodiscard]] nixl_status_t +allocGdrCopyPublishedMem(size_t size, std::unique_ptr &out) noexcept; + +} // namespace nixl + +#endif // NIXL_SRC_UTILS_DEVICE_DEVICE_OPS_CUDA_GDRCOPY_H diff --git a/src/utils/device/host_published_mem.cpp b/src/utils/device/host_published_mem.cpp new file mode 100644 index 0000000000..8e8b0abd63 --- /dev/null +++ b/src/utils/device/host_published_mem.cpp @@ -0,0 +1,69 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "device/host_published_mem.h" + +#include +#include + +#include "common/nixl_log.h" +#include "device/device_ops.h" +#include "nixl_log.h" + +namespace nixl { +namespace { + + class mappedHostPublishedMem final : public hostPublishedDeviceMem { + public: + mappedHostPublishedMem(mappedHostMem mem, size_t size) noexcept + : hostPublishedDeviceMem(mem.devicePointer(), size, backing::mapped_host), + mem_(std::move(mem)) {} + + private: + nixl_status_t + doPublish(size_t offset, uint64_t value) noexcept override { + __atomic_store_n( + mem_.hostPointer() + offset / sizeof(uint64_t), value, __ATOMIC_RELEASE); + return NIXL_SUCCESS; + } + + mappedHostMem mem_; + }; + +} // namespace + +nixl_status_t +deviceOps::allocHostPublishedMem(size_t size, + std::unique_ptr &out) noexcept { + if (size == 0) { + NIXL_ERROR << "Host-published allocation requires nonzero size"; + return NIXL_ERR_INVALID_PARAM; + } + if (doAllocHostPublishedMem(size, out) == NIXL_SUCCESS) { + return NIXL_SUCCESS; + } + + mappedHostMem mem; + const nixl_status_t status = allocMappedHostMem(size, mem); + if (status != NIXL_SUCCESS) { + return status; + } + std::memset(mem.hostPointer(), 0, size); + out = std::make_unique(std::move(mem), size); + return NIXL_SUCCESS; +} + +} // namespace nixl diff --git a/src/utils/device/host_published_mem.h b/src/utils/device/host_published_mem.h new file mode 100644 index 0000000000..70113c3bf5 --- /dev/null +++ b/src/utils/device/host_published_mem.h @@ -0,0 +1,93 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef NIXL_SRC_UTILS_DEVICE_HOST_PUBLISHED_MEM_H +#define NIXL_SRC_UTILS_DEVICE_HOST_PUBLISHED_MEM_H + +#include +#include + +#include + +namespace nixl { + +/** + * @brief Zeroed memory the CPU publishes 64-bit words into and the GPU reads. + * + * One CPU thread writes each word, and the GPU reads it with system-scope acquire loads. Host + * writes made before publish() are visible to a GPU load that observes the published word. + * + * @note The deviceOps that allocated this memory must outlive it. + */ +class hostPublishedDeviceMem { +public: + /** device: device memory the CPU writes directly; mapped_host: the portable fallback. */ + enum class backing { device, mapped_host }; + + virtual ~hostPublishedDeviceMem() = default; + + hostPublishedDeviceMem(const hostPublishedDeviceMem &) = delete; + hostPublishedDeviceMem & + operator=(const hostPublishedDeviceMem &) = delete; + + /** The address the GPU reads. */ + [[nodiscard]] void * + devicePointer() const noexcept { + return devPtr_; + } + + [[nodiscard]] size_t + size() const noexcept { + return size_; + } + + [[nodiscard]] backing + backingKind() const noexcept { + return backing_; + } + + /** + * @brief Publish one 8-byte word at `offset`. + * @retval NIXL_ERR_INVALID_PARAM offset is not word-aligned or the word does not fit. + * @retval NIXL_ERR_BACKEND The write failed. + */ + [[nodiscard]] nixl_status_t + publish(size_t offset, uint64_t value) noexcept { + if (offset % sizeof(uint64_t) != 0 || offset > size_ || size_ - offset < sizeof(uint64_t)) { + return NIXL_ERR_INVALID_PARAM; + } + return doPublish(offset, value); + } + +protected: + hostPublishedDeviceMem(void *dev_ptr, size_t size, backing kind) noexcept + : devPtr_(dev_ptr), + size_(size), + backing_(kind) {} + + /** @brief Release-store `value` at a validated `offset`. */ + [[nodiscard]] virtual nixl_status_t + doPublish(size_t offset, uint64_t value) noexcept = 0; + +private: + void *devPtr_; + size_t size_; + backing backing_; +}; + +} // namespace nixl + +#endif // NIXL_SRC_UTILS_DEVICE_HOST_PUBLISHED_MEM_H diff --git a/src/utils/device/meson.build b/src/utils/device/meson.build index 3220d57374..6357b5f329 100644 --- a/src/utils/device/meson.build +++ b/src/utils/device/meson.build @@ -14,7 +14,8 @@ # limitations under the License. device_utils_lib = shared_library('device_utils', - ['device_ops.cpp', 'device_ops.h'], + ['device_ops.cpp', 'device_ops.h', + 'host_published_mem.cpp', 'host_published_mem.h'], include_directories: [nixl_inc_dirs, utils_inc_dirs], dependencies: [nixl_common_dep, dl_dep], install: true) @@ -23,8 +24,11 @@ device_utils_interface = declare_dependency(link_with: device_utils_lib) if cuda_dep.found() shared_library('nixl_device_ops_cuda', - 'device_ops_cuda.cpp', + ['device_ops_cuda.cpp', + 'device_ops_cuda_gdrcopy.cpp', 'device_ops_cuda_gdrcopy.h'], include_directories: [nixl_inc_dirs, utils_inc_dirs], - dependencies: [cuda_dep, nixl_common_dep], + dependencies: [cuda_dep, nixl_common_dep, dl_dep], install: true) endif + +subdir('proxy') diff --git a/src/utils/device/proxy/README.md b/src/utils/device/proxy/README.md new file mode 100644 index 0000000000..e4e84a0e5f --- /dev/null +++ b/src/utils/device/proxy/README.md @@ -0,0 +1,58 @@ + + +# Device proxy + +The host side of the CPU proxy. Where a transport has no device-callable submission path, GPU +kernels write fixed-layout commands (`proxy_protocol.h`) into per-channel rings, and host threads +turn each command into an ordinary backend transfer through a `nixl::proxyTransport`. The proxy +ignores `nixl::gpu::flags::defer`; a command carries no flags until a consumer exists. + +## Transport contract + +`nixl::proxyTransport` (`proxy_transport.h`) is the interface a backend implements to sit behind +the proxy. It is internal to `libnixl_device_proxy` and the plugins: not installed, not an ABI. + +### Ownership + +- `proxyRuntime::create()` takes ownership of the transport. The runtime calls `shutdown()` and + destroys the transport after its workers have joined. +- Anything the transport references (engine workers, endpoints) must outlive the runtime. The + owning engine shuts the runtime down first in its destructor. + +### Threading + +- `init()` and `shutdown()` run with no worker thread alive. +- `submit()`, `progress()` and `quiesce()` for any ring of channel c, and `checkCompletion()` for + requests submitted on those rings, are made from a single thread at a time. Different channels + may be served concurrently by different threads. +- `resolveDirectPtrs()` runs on an application thread, concurrently with the calls above, and must + not touch per-ring state. +- `submit()`, `checkCompletion()` and `progress()` are the data path: no locks and no atomic + read-modify-write shared across channels. + +### Requests + +- At most `config.ring_depth` requests are outstanding per (channel, peer). +- `submit()` returns `NIXL_IN_PROG` with a non-empty request, or a terminal status with an empty + request (`NIXL_SUCCESS`: complete now; error: never posted). It must not return a transient + error: a transport that cannot post now returns `NIXL_IN_PROG` and posts from `progress()`. +- The runtime polls a ring's requests in submission order and never passes a request again after + `checkCompletion()` has returned a terminal status for it. +- A terminal status releases the handle. It does not promise that the transport has stopped + accessing the operation's memory (UCX under err-mode none cannot abort a put). Only `quiesce()` + promises that. diff --git a/src/utils/device/proxy/meson.build b/src/utils/device/proxy/meson.build new file mode 100644 index 0000000000..3d13c1cdaa --- /dev/null +++ b/src/utils/device/proxy/meson.build @@ -0,0 +1,31 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +device_proxy_lib = library('nixl_device_proxy', + ['proxy_config.cpp', 'proxy_config.h', + 'proxy_control_buffer.cpp', 'proxy_control_buffer.h', + 'proxy_protocol.h', 'proxy_transport.h'], + include_directories: [nixl_inc_dirs, utils_inc_dirs], + dependencies: [nixl_common_dep, device_utils_interface], + install: true) + +if get_option('install_headers') + # Device code includes the wire contract as . + install_headers('proxy_protocol.h', install_dir: prefix_inc + '/device/proxy') +endif + +# The proxy headers hand out nixl::deviceOps, so consumers link it too. +device_proxy_interface = declare_dependency(link_with: device_proxy_lib, + dependencies: [device_utils_interface]) diff --git a/src/utils/device/proxy/proxy_config.cpp b/src/utils/device/proxy/proxy_config.cpp new file mode 100644 index 0000000000..731f040e7d --- /dev/null +++ b/src/utils/device/proxy/proxy_config.cpp @@ -0,0 +1,136 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "proxy_config.h" + +#include +#include +#include + +#include "backend_aux.h" +#include "common/backend.h" +#include "nixl_log.h" + +namespace { + +constexpr std::array kKnownProxyParams = { + nixl::kProxyEnabledParam, + nixl::kProxyChannelCountParam, + nixl::kProxyThreadCountParam, + nixl::kProxyMaxPeersParam, + nixl::kProxyRingDepthParam, +}; + +[[nodiscard]] bool +isPowerOfTwo(uint32_t value) noexcept { + return value != 0 && (value & (value - 1)) == 0; +} + +[[nodiscard]] bool +isProxyParamKey(const std::string &key) noexcept { + return key.starts_with("device_proxy") || key.starts_with("proxy_"); +} + +} // namespace + +namespace nixl { + +nixl_status_t +parseProxyConfig(const nixlBackendInitParams &init_params, proxyConfig &config) noexcept { + const nixl_b_params_t *params = init_params.customParams; + + std::string tuning_key; + if (params != nullptr) { + for (const auto &[key, value] : *params) { + if (!isProxyParamKey(key)) { + continue; + } + if (std::find(kKnownProxyParams.begin(), kKnownProxyParams.end(), key) == + kKnownProxyParams.end()) { + NIXL_ERROR << "Unknown device proxy backend parameter '" << key << "'"; + return NIXL_ERR_INVALID_PARAM; + } + if (key != kProxyEnabledParam && tuning_key.empty()) { + tuning_key = key; + } + } + } + + proxyConfig parsed; + try { + parsed.enabled = + getBackendParamDefaulted(params, std::string(kProxyEnabledParam), false); + const auto channel_count = + getBackendParamOptional(params, std::string(kProxyChannelCountParam)); + const auto thread_count = + getBackendParamOptional(params, std::string(kProxyThreadCountParam)); + const auto max_peers = + getBackendParamOptional(params, std::string(kProxyMaxPeersParam)); + const auto ring_depth = + getBackendParamOptional(params, std::string(kProxyRingDepthParam)); + + parsed.channel_count = channel_count.value_or(kDefaultProxyChannelCount); + parsed.thread_count = thread_count.value_or(parsed.channel_count); + parsed.max_peers = max_peers.value_or(kDefaultProxyMaxPeers); + parsed.ring_depth = ring_depth.value_or(kDefaultProxyRingDepth); + } + catch (const std::exception &e) { + NIXL_ERROR << "Failed to parse device proxy backend parameters: " << e.what(); + return NIXL_ERR_INVALID_PARAM; + } + + if (!parsed.enabled) { + if (!tuning_key.empty()) { + NIXL_ERROR << "Device proxy parameter '" << tuning_key << "' given without " + << kProxyEnabledParam << "=true"; + return NIXL_ERR_INVALID_PARAM; + } + config = parsed; + return NIXL_SUCCESS; + } + + if (parsed.channel_count == 0 || parsed.thread_count == 0 || parsed.max_peers == 0) { + NIXL_ERROR << "Device proxy counts must be positive: " << kProxyChannelCountParam << "=" + << parsed.channel_count << " " << kProxyThreadCountParam << "=" + << parsed.thread_count << " " << kProxyMaxPeersParam << "=" << parsed.max_peers; + return NIXL_ERR_INVALID_PARAM; + } + + if (!isPowerOfTwo(parsed.ring_depth)) { + NIXL_ERROR << "Device proxy " << kProxyRingDepthParam + << " must be a non-zero power of two: " << parsed.ring_depth; + return NIXL_ERR_INVALID_PARAM; + } + + if (init_params.enableProgTh) { + NIXL_ERROR << "Device proxy progress threads own the backend workers; the backend " + "progress thread (enableProgTh) is not allowed with " + << kProxyEnabledParam << "=true"; + return NIXL_ERR_NOT_ALLOWED; + } + + if (parsed.thread_count > parsed.channel_count) { + NIXL_INFO << "Device proxy " << kProxyThreadCountParam << "=" << parsed.thread_count + << " exceeds " << kProxyChannelCountParam << "=" << parsed.channel_count + << "; only " << parsed.effectiveThreadCount() + << " thread(s) will be started (channels are striped across threads)"; + } + + config = parsed; + return NIXL_SUCCESS; +} + +} // namespace nixl diff --git a/src/utils/device/proxy/proxy_config.h b/src/utils/device/proxy/proxy_config.h new file mode 100644 index 0000000000..937f3918ed --- /dev/null +++ b/src/utils/device/proxy/proxy_config.h @@ -0,0 +1,77 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef NIXL_SRC_UTILS_DEVICE_PROXY_PROXY_CONFIG_H +#define NIXL_SRC_UTILS_DEVICE_PROXY_PROXY_CONFIG_H + +#include +#include +#include +#include + +#include + +class nixlBackendInitParams; + +namespace nixl { + +/** Backend-param keys controlling the device proxy. */ +inline constexpr std::string_view kProxyEnabledParam = "device_proxy"; +inline constexpr std::string_view kProxyChannelCountParam = "proxy_channel_count"; +inline constexpr std::string_view kProxyThreadCountParam = "proxy_thread_count"; +inline constexpr std::string_view kProxyMaxPeersParam = "proxy_max_peers"; +inline constexpr std::string_view kProxyRingDepthParam = "proxy_ring_depth"; + +inline constexpr uint32_t kDefaultProxyChannelCount = 4; +/** Deliberately small: each peer costs a ring per channel; pass the real peer capacity. */ +inline constexpr uint32_t kDefaultProxyMaxPeers = 8; +/** Work-ring slots per (channel, peer); the GPU masks indices, so a power of two. */ +inline constexpr uint32_t kDefaultProxyRingDepth = 256; + +struct proxyConfig { + bool enabled = false; + uint32_t channel_count = kDefaultProxyChannelCount; + /** Number of proxy CPU progress threads; defaults to channel_count. */ + uint32_t thread_count = kDefaultProxyChannelCount; + uint32_t max_peers = kDefaultProxyMaxPeers; + /** Work-ring depth per (channel, peer) slot; power of two. */ + uint32_t ring_depth = kDefaultProxyRingDepth; + + [[nodiscard]] size_t + ringCount() const noexcept { + return static_cast(channel_count) * max_peers; + } + + /** Threads beyond channel_count would own no channels. */ + [[nodiscard]] uint32_t + effectiveThreadCount() const noexcept { + return std::min(thread_count, channel_count); + } +}; + +/** + * @brief Parse the device proxy backend parameters. + * @param[out] config Parsed configuration; unchanged on failure. + * @retval NIXL_ERR_INVALID_PARAM Unknown proxy key, invalid value, or tuning without + * device_proxy=true. + * @retval NIXL_ERR_NOT_ALLOWED device_proxy=true with the backend progress thread. + */ +[[nodiscard]] nixl_status_t +parseProxyConfig(const nixlBackendInitParams &init_params, proxyConfig &config) noexcept; + +} // namespace nixl + +#endif // NIXL_SRC_UTILS_DEVICE_PROXY_PROXY_CONFIG_H diff --git a/src/utils/device/proxy/proxy_control_buffer.cpp b/src/utils/device/proxy/proxy_control_buffer.cpp new file mode 100644 index 0000000000..1c6dac5417 --- /dev/null +++ b/src/utils/device/proxy/proxy_control_buffer.cpp @@ -0,0 +1,68 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include "proxy_control_buffer.h" + +#include +#include + +#include "nixl_log.h" + +namespace nixl { + +proxyControlBuffer::proxyControlBuffer(std::unique_ptr mem) noexcept + : mem_(std::move(mem)) {} + +nixl_status_t +proxyControlBuffer::create(deviceOps &ops, + size_t ring_count, + std::unique_ptr &out) { + if (ring_count > std::numeric_limits::max() / sizeof(uint64_t) - ringSlot(0)) { + NIXL_ERROR << "Invalid proxy control buffer size: " << ring_count << " ring(s)"; + return NIXL_ERR_INVALID_PARAM; + } + + std::unique_ptr mem; + const nixl_status_t status = + ops.allocHostPublishedMem(sizeof(uint64_t) * ringSlot(ring_count), mem); + if (status != NIXL_SUCCESS) { + return status; + } + out.reset(new proxyControlBuffer(std::move(mem))); + return NIXL_SUCCESS; +} + +nixl_status_t +proxyControlBuffer::publishShutdown(nixl_proxy_control_state_t state) noexcept { + return mem_->publish(sizeof(uint64_t) * shutdownSlot(), static_cast(state)); +} + +nixl_status_t +proxyControlBuffer::publishConsumerIdx(size_t ring_index, uint64_t value) noexcept { + if (ring_index >= mem_->size() / sizeof(uint64_t) - ringSlot(0)) { + return NIXL_ERR_INVALID_PARAM; + } + return mem_->publish(sizeof(uint64_t) * ringSlot(ring_index), value); +} + +uint64_t * +proxyControlBuffer::devicePointer(size_t slot) const noexcept { + return slot < mem_->size() / sizeof(uint64_t) ? + static_cast(mem_->devicePointer()) + slot : + nullptr; +} + +} // namespace nixl diff --git a/src/utils/device/proxy/proxy_control_buffer.h b/src/utils/device/proxy/proxy_control_buffer.h new file mode 100644 index 0000000000..f1517017a4 --- /dev/null +++ b/src/utils/device/proxy/proxy_control_buffer.h @@ -0,0 +1,80 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef NIXL_SRC_UTILS_DEVICE_PROXY_PROXY_CONTROL_BUFFER_H +#define NIXL_SRC_UTILS_DEVICE_PROXY_PROXY_CONTROL_BUFFER_H + +#include +#include +#include + +#include "device/device_ops.h" +#include "device/host_published_mem.h" +#include "nixl_types.h" +#include "proxy_protocol.h" + +namespace nixl { + +/** + * GPU-visible words the CPU publishes cheaply: the shutdown state and one + * consumer index per (channel, peer) ring, laid out as 64-bit slots over one + * hostPublishedDeviceMem. + */ +class proxyControlBuffer { +public: + static constexpr size_t + shutdownSlot() noexcept { + return 0; + } + + static constexpr size_t + ringSlot(size_t ring_index) noexcept { + return 1 + ring_index; + } + + /** + * @brief Create a zeroed buffer holding the shutdown slot and `ring_count` ring slots. + * @param[out] out Owning handle; unchanged on failure. + * @retval NIXL_ERR_INVALID_PARAM ring_count is too large. + * @retval NIXL_ERR_BACKEND Neither backing could be allocated. + * @note `ops` must outlive the buffer. + */ + [[nodiscard]] static nixl_status_t + create(deviceOps &ops, size_t ring_count, std::unique_ptr &out); + + proxyControlBuffer(const proxyControlBuffer &) = delete; + proxyControlBuffer & + operator=(const proxyControlBuffer &) = delete; + + [[nodiscard]] nixl_status_t + publishShutdown(nixl_proxy_control_state_t state) noexcept; + + [[nodiscard]] nixl_status_t + publishConsumerIdx(size_t ring_index, uint64_t value) noexcept; + + /** Device address of `slot`, or nullptr when out of range. */ + [[nodiscard]] uint64_t * + devicePointer(size_t slot) const noexcept; + +private: + explicit proxyControlBuffer(std::unique_ptr mem) noexcept; + + std::unique_ptr mem_; +}; + +} // namespace nixl + +#endif // NIXL_SRC_UTILS_DEVICE_PROXY_PROXY_CONTROL_BUFFER_H diff --git a/src/utils/device/proxy/proxy_protocol.h b/src/utils/device/proxy/proxy_protocol.h new file mode 100644 index 0000000000..9dffe6d634 --- /dev/null +++ b/src/utils/device/proxy/proxy_protocol.h @@ -0,0 +1,175 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef NIXL_SRC_UTILS_DEVICE_PROXY_PROXY_PROTOCOL_H +#define NIXL_SRC_UTILS_DEVICE_PROXY_PROXY_PROTOCOL_H + +#include +#include + +#include + +// The accessors below have to be callable from device code, but this header +// must not include a CUDA header to say so. +#ifdef __CUDACC__ +#define NIXL_PROXY_PROTO_FN __host__ __device__ inline +#else +#define NIXL_PROXY_PROTO_FN inline +#endif + +enum class nixl_proxy_opcode_t : uint8_t { + PUT = 0, + ATOMIC_ADD = 1, +}; + +enum class nixl_proxy_control_state_t : uint32_t { + RUNNING = 0, + SHUTDOWN = 1, +}; + +struct nixlProxyDeviceContextData; + +/** A prepared memory view as device code sees it; `direct_ptr_count` pointers follow it. */ +struct nixlProxyDeviceMemView { + uint64_t host_view = 0; + const nixlProxyDeviceContextData *context = nullptr; + uint32_t direct_ptr_count = 0; + uint32_t reserved = 0; +}; + +NIXL_PROXY_PROTO_FN void ** +nixlProxyDeviceMemViewDirectPtrs(nixlProxyDeviceMemView *view) { + return reinterpret_cast(view + 1); +} + +NIXL_PROXY_PROTO_FN void *const * +nixlProxyDeviceMemViewDirectPtrs(const nixlProxyDeviceMemView *view) { + return reinterpret_cast(view + 1); +} + +/** Bytes to allocate for a view carrying `count` direct pointers. */ +NIXL_PROXY_PROTO_FN size_t +nixlProxyDeviceMemViewBytes(size_t count) { + return sizeof(nixlProxyDeviceMemView) + count * sizeof(void *); +} + +/** + * A GPU-submitted PUT or atomic-add operation for the CPU proxy to execute. + * + * What each field means, by opcode: + * + * | field | PUT | ATOMIC_ADD | + * |------------|-------------------------|---------------------| + * | operand | source offset | value to add | + * | dst_offset | destination offset | counter offset | + * | size | bytes | unused | + * | src_view | source view token | unused | + * | src_index | source descriptor | unused | + * | dst_view | destination view token | counter view token | + * | dst_index | destination descriptor | counter descriptor | + * + * The destination descriptor index is also the peer slot the command goes to. + * The ring the command is written into implies its channel. + * For ATOMIC_ADD the size field is unused and the host uses 8 bytes. + */ +struct alignas(64) nixlProxyCommand { + uint64_t op_idx = 0; + uint64_t operand = 0; // PUT: source offset; ATOMIC_ADD: value. + uint64_t dst_offset = 0; + uint64_t size = 0; + uint64_t src_view = 0; + uint64_t dst_view = 0; + uint32_t src_index = 0; + uint32_t dst_index = 0; + nixl_proxy_opcode_t opcode = nixl_proxy_opcode_t::PUT; + /** Reserved. Keeps the command 64 bytes. */ + uint8_t reserved[7] = {}; + + /** PUT: byte offset into the source descriptor. */ + NIXL_PROXY_PROTO_FN uint64_t + sourceOffset() const { + return operand; + } + + /** ATOMIC_ADD: the value to add to the counter. */ + NIXL_PROXY_PROTO_FN uint64_t + atomicValue() const { + return operand; + } + + /** The peer slot the command goes to. */ + NIXL_PROXY_PROTO_FN uint32_t + peerIndex() const { + return dst_index; + } +}; + +struct nixlProxyWorkRing { + /** Mapped host commands: GPU writes via device alias; CPU worker reads host alias. */ + nixlProxyCommand *commands = nullptr; + /** Device-resident producer index; only the GPU updates it. */ + uint64_t *producer_idx = nullptr; + /** Authoritative consumer index. The CPU publishes it through host-published device memory. */ + uint64_t *consumer_idx = nullptr; + /** Device-resident cached consumer index; GPU refreshes from consumer_idx only when full. */ + uint64_t *consumer_idx_cache = nullptr; + /** The depth of the work ring. */ + uint32_t depth = 0; +}; + +struct alignas(16) nixlProxyCompletionSlot { + uint64_t completed_idx = 0; + /** Status of the op at completed_idx; an error stays latched. */ + nixl_status_t completion_status = NIXL_IN_PROG; +}; + +struct nixlProxyRingDesc { + nixlProxyWorkRing *work_ring = nullptr; + /** Mapped pinned host memory (device alias); host writes via host pointer with atomics. */ + nixlProxyCompletionSlot *completion_slot = nullptr; +}; + +struct nixlProxyDeviceContextData { + nixlProxyRingDesc *rings = nullptr; + uint32_t max_peers = 0; + uint32_t num_channels = 0; + uint64_t *shutdown_word = nullptr; +}; + +static_assert(sizeof(nixlProxyCommand) == 64, "nixlProxyCommand must be 64 bytes"); +static_assert(offsetof(nixlProxyCommand, op_idx) == 0, + "op_idx must be the first word because it publishes command readiness"); +static_assert(alignof(nixlProxyCommand) == 64, "nixlProxyCommand must be cache-line aligned"); + +static_assert(sizeof(nixlProxyDeviceMemView) == 24, "nixlProxyDeviceMemView layout changed"); +static_assert(offsetof(nixlProxyDeviceMemView, host_view) == 0, + "nixlProxyDeviceMemView layout changed"); +static_assert(sizeof(nixlProxyDeviceMemView) % alignof(void *) == 0, + "the trailing direct-pointer run must start aligned"); + +static_assert(sizeof(nixlProxyWorkRing) == 40, "nixlProxyWorkRing layout changed"); +static_assert(sizeof(nixlProxyCompletionSlot) == 16, "nixlProxyCompletionSlot layout changed"); +static_assert(offsetof(nixlProxyCompletionSlot, completed_idx) == 0, + "nixlProxyCompletionSlot layout changed"); +static_assert(sizeof(nixl_status_t) == 4, "nixl_status_t must be 4 bytes in a completion slot"); +static_assert(sizeof(nixlProxyRingDesc) == 16, "nixlProxyRingDesc layout changed"); +static_assert(sizeof(nixlProxyDeviceContextData) == 24, + "nixlProxyDeviceContextData layout changed"); +static_assert(offsetof(nixlProxyDeviceContextData, rings) == 0, + "nixlProxyDeviceContextData layout changed"); + +#endif // NIXL_SRC_UTILS_DEVICE_PROXY_PROXY_PROTOCOL_H diff --git a/src/utils/device/proxy/proxy_transport.h b/src/utils/device/proxy/proxy_transport.h new file mode 100644 index 0000000000..973a1df4f1 --- /dev/null +++ b/src/utils/device/proxy/proxy_transport.h @@ -0,0 +1,109 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef NIXL_SRC_UTILS_DEVICE_PROXY_PROXY_TRANSPORT_H +#define NIXL_SRC_UTILS_DEVICE_PROXY_PROXY_TRANSPORT_H + +#include +#include +#include + +#include +#include "backend_aux.h" +#include "proxy_config.h" +#include "proxy_protocol.h" + +namespace nixl { + +/** A ring command with its view tokens resolved into transport descriptors. */ +struct proxyBackendSubmission { + uint64_t op_idx = 0; + nixl_proxy_opcode_t opcode = nixl_proxy_opcode_t::PUT; + uint32_t channel_id = 0; + uint32_t peer_index = 0; + + /** nixlMetaDesc() leaves addr, len and devId unset, so zero them explicitly. */ + nixlMetaDesc local{0, 0, 0, nullptr}; + nixlMetaDesc remote{0, 0, 0, nullptr}; + + size_t size = 0; + uint64_t value = 0; +}; + +/** One in-flight transfer, named by a single token. */ +struct proxyBackendRequest { + uint64_t token = 0; + + explicit + operator bool() const noexcept { + return token != 0; + } +}; + +/** + * The transport a proxyRuntime drives. Internal to libnixl_device_proxy and the plugins; not + * installed, not an ABI. Ownership, threading and request rules: README.md in this directory. + */ +class proxyTransport { +public: + virtual ~proxyTransport() = default; + + /** + * Called once by proxyRuntime::create() before any ring exists. On failure nothing else is + * called. + */ + [[nodiscard]] virtual nixl_status_t + init(const proxyConfig &config) = 0; + + /** NIXL_IN_PROG with a non-empty request, or a terminal status with an empty one; never a + * transient error (post from progress() instead). */ + [[nodiscard]] virtual nixl_status_t + submit(const proxyBackendSubmission &submission, proxyBackendRequest &request) = 0; + + /** Polled in submission order per ring. `channel` and `peer` select that ring. A terminal + * status releases the request, which is not passed again. */ + [[nodiscard]] virtual nixl_status_t + checkCompletion(uint32_t channel, uint32_t peer, const proxyBackendRequest &request) = 0; + + /** Once per ring per worker pass, busy or idle; an idle ring should return quickly. + * Transfer errors surface through checkCompletion(). */ + virtual void + progress(uint32_t channel, uint32_t peer) noexcept = 0; + + /** On the owning thread, once the ring has no outstanding request. On success every operation + * submitted on the ring is remotely visible and no longer references local or remote memory. + * A failure is fatal to the process. */ + [[nodiscard]] virtual nixl_status_t + quiesce(uint32_t channel, uint32_t peer) = 0; + + /** Once, after a successful init(), with workers joined and every ring drained. */ + [[nodiscard]] virtual nixl_status_t + shutdown() = 0; + + /** + * Optional: leave direct_ptrs empty (no direct access) or fill one entry per descriptor, + * nullptr where unavailable. Any error is a real error. + */ + [[nodiscard]] virtual nixl_status_t + resolveDirectPtrs(const nixl_remote_meta_dlist_t &, std::vector &direct_ptrs) { + direct_ptrs.clear(); + return NIXL_SUCCESS; + } +}; + +} // namespace nixl + +#endif // NIXL_SRC_UTILS_DEVICE_PROXY_PROXY_TRANSPORT_H diff --git a/test/gtest/unit/device_ops/host_published_mem.cpp b/test/gtest/unit/device_ops/host_published_mem.cpp new file mode 100644 index 0000000000..f52bf145be --- /dev/null +++ b/test/gtest/unit/device_ops/host_published_mem.cpp @@ -0,0 +1,229 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include + +#include +#include +#include +#include + +#include "device/device_ops.h" +#include "device/host_published_mem.h" +#include "gpu_utils.h" + +namespace gtest { +namespace host_published_mem { + + using nixl::deviceOps; + using nixl::hostPublishedDeviceMem; + using backing = hostPublishedDeviceMem::backing; + + /** Stands in for a backend's device-resident backing. */ + class fakeDevicePublishedMem final : public hostPublishedDeviceMem { + public: + explicit fakeDevicePublishedMem(size_t size) + : hostPublishedDeviceMem(&word_, size, backing::device) {} + + private: + nixl_status_t + doPublish(size_t, uint64_t value) noexcept override { + word_ = value; + return NIXL_SUCCESS; + } + + uint64_t word_ = 0; + }; + + /** Host-only deviceOps whose mapped memory is plain heap memory. */ + class fakeOps : public deviceOps { + public: + /** Result of the backend allocation; NIXL_ERR_NOT_SUPPORTED mimics the default. */ + nixl_status_t backend_status = NIXL_ERR_NOT_SUPPORTED; + bool fail_mapped = false; + int mapped_frees = 0; + + nixl_status_t + doAllocDeviceMem(void *&, size_t) noexcept override { + return NIXL_ERR_NOT_SUPPORTED; + } + + void + doFreeDeviceMem(void *) noexcept override {} + + nixl_status_t + doAllocMappedHostMem(void *&host_ptr, void *&dev_ptr, size_t size) noexcept override { + if (fail_mapped) { + return NIXL_ERR_BACKEND; + } + // Poisoned so the test sees that allocHostPublishedMem zeroes it. + host_ptr = std::malloc(size); + std::memset(host_ptr, 0xA5, size); + dev_ptr = host_ptr; + return NIXL_SUCCESS; + } + + void + doFreeMappedHostMem(void *host_ptr) noexcept override { + std::free(host_ptr); + ++mapped_frees; + } + + nixl_status_t + doAllocHostPublishedMem(size_t size, + std::unique_ptr &out) noexcept override { + if (backend_status == NIXL_SUCCESS) { + out = std::make_unique(size); + } + return backend_status; + } + + nixl_status_t + copy(void *, const void *, size_t, copyDirection) noexcept override { + return NIXL_ERR_NOT_SUPPORTED; + } + + nixl_status_t + memsetDeviceMem(void *, int, size_t) noexcept override { + return NIXL_ERR_NOT_SUPPORTED; + } + + nixl_status_t + synchronize() noexcept override { + return NIXL_SUCCESS; + } + + nixl_status_t + getActiveDevice(int &device_id) noexcept override { + device_id = 0; + return NIXL_SUCCESS; + } + + nixl_status_t + setActiveDevice(int) noexcept override { + return NIXL_SUCCESS; + } + }; + + TEST(hostPublishedMem, ZeroSizeLeavesOutputUnchanged) { + fakeOps ops; + std::unique_ptr mem; + EXPECT_EQ(ops.allocHostPublishedMem(0, mem), NIXL_ERR_INVALID_PARAM); + EXPECT_FALSE(mem); + + ASSERT_EQ(ops.allocHostPublishedMem(8, mem), NIXL_SUCCESS); + hostPublishedDeviceMem *const kept = mem.get(); + EXPECT_EQ(ops.allocHostPublishedMem(0, mem), NIXL_ERR_INVALID_PARAM); + EXPECT_EQ(mem.get(), kept); + } + + TEST(hostPublishedMem, MappedHostIsZeroedAndPublishesWholeWords) { + fakeOps ops; + std::unique_ptr mem; + ASSERT_EQ(ops.allocHostPublishedMem(16, mem), NIXL_SUCCESS); + EXPECT_EQ(mem->backingKind(), backing::mapped_host); + EXPECT_EQ(mem->size(), 16u); + + auto *words = static_cast(mem->devicePointer()); + EXPECT_EQ(words[0], 0u); + EXPECT_EQ(words[1], 0u); + + ASSERT_EQ(mem->publish(0, 0xffffffff00000000ull), NIXL_SUCCESS); + EXPECT_EQ(words[0], 0xffffffff00000000ull); + ASSERT_EQ(mem->publish(8, 1), NIXL_SUCCESS); + EXPECT_EQ(words[1], 1u); + + EXPECT_EQ(mem->publish(1, 2), NIXL_ERR_INVALID_PARAM); + EXPECT_EQ(mem->publish(16, 2), NIXL_ERR_INVALID_PARAM); + EXPECT_EQ(mem->publish(SIZE_MAX - 7, 2), NIXL_ERR_INVALID_PARAM); + EXPECT_EQ(words[1], 1u); + } + + TEST(hostPublishedMem, PrefersTheBackendBacking) { + fakeOps ops; + ops.backend_status = NIXL_SUCCESS; + std::unique_ptr mem; + ASSERT_EQ(ops.allocHostPublishedMem(8, mem), NIXL_SUCCESS); + EXPECT_EQ(mem->backingKind(), backing::device); + ASSERT_EQ(mem->publish(0, 7), NIXL_SUCCESS); + EXPECT_EQ(*static_cast(mem->devicePointer()), 7u); + mem.reset(); + EXPECT_EQ(ops.mapped_frees, 0); + } + + TEST(hostPublishedMem, BackendFailureFallsBackToMappedHost) { + fakeOps ops; + ops.backend_status = NIXL_ERR_BACKEND; + std::unique_ptr mem; + ASSERT_EQ(ops.allocHostPublishedMem(8, mem), NIXL_SUCCESS); + EXPECT_EQ(mem->backingKind(), backing::mapped_host); + } + + TEST(hostPublishedMem, MappedFailureLeavesOutputUnchanged) { + fakeOps ops; + ops.fail_mapped = true; + std::unique_ptr mem; + EXPECT_EQ(ops.allocHostPublishedMem(8, mem), NIXL_ERR_BACKEND); + EXPECT_FALSE(mem); + } + + TEST(hostPublishedMem, DestroyingMappedHostFreesIt) { + fakeOps ops; + { + std::unique_ptr mem; + ASSERT_EQ(ops.allocHostPublishedMem(8, mem), NIXL_SUCCESS); + } + EXPECT_EQ(ops.mapped_frees, 1); + } + + TEST(hostPublishedMemGpu, IsZeroedAndPublishesToTheDevice) { + int count = 0; + gpuGetDeviceCount(&count, "Probing GPU devices"); + if (count < 1) { + GTEST_SKIP() << "No GPU is available."; + } + deviceOps *ops = nixl::getDeviceOps(); + if (ops == nullptr) { + GTEST_SKIP() << "No device operations implementation is available."; + } + + constexpr size_t kWords = 3; + std::unique_ptr mem; + ASSERT_EQ(ops->allocHostPublishedMem(kWords * sizeof(uint64_t), mem), NIXL_SUCCESS); + RecordProperty("backing", mem->backingKind() == backing::device ? "device" : "mapped_host"); + + uint64_t got[kWords] = {1, 1, 1}; + ASSERT_EQ( + ops->copy( + got, mem->devicePointer(), sizeof(got), deviceOps::copyDirection::DeviceToHost), + NIXL_SUCCESS); + EXPECT_EQ(got[0], 0u); + EXPECT_EQ(got[1], 0u); + EXPECT_EQ(got[2], 0u); + + ASSERT_EQ(mem->publish(sizeof(uint64_t), 0x123456789abcdef0ull), NIXL_SUCCESS); + ASSERT_EQ( + ops->copy( + got, mem->devicePointer(), sizeof(got), deviceOps::copyDirection::DeviceToHost), + NIXL_SUCCESS); + EXPECT_EQ(got[0], 0u); + EXPECT_EQ(got[1], 0x123456789abcdef0ull); + EXPECT_EQ(got[2], 0u); + } + +} // namespace host_published_mem +} // namespace gtest diff --git a/test/gtest/unit/device_ops/meson.build b/test/gtest/unit/device_ops/meson.build index d55f34928f..e97d650b59 100644 --- a/test/gtest/unit/device_ops/meson.build +++ b/test/gtest/unit/device_ops/meson.build @@ -14,7 +14,7 @@ # limitations under the License. device_ops_unit_test_dep = declare_dependency( - sources: ['device_ops.cpp'], + sources: ['device_ops.cpp', 'host_published_mem.cpp'], include_directories: [nixl_inc_dirs, utils_inc_dirs, gtest_inc_dirs], dependencies: [nixl_common_dep, device_utils_interface, gpu_dependencies], )