From 366b37649b9ef964f26c0878b5b3ea7ea8e56873 Mon Sep 17 00:00:00 2001 From: Hartmut Kaiser Date: Wed, 25 Nov 2026 12:38:06 -0600 Subject: [PATCH 1/6] Let a received parcel wait only for the steps of the parcels whose objects it uses A parcel de-serialized from a message waited for the post-receive steps (zero-copy and device chunk transfers) of all parcels before it in the same message, since objects shared through tracked pointers are loaded only by the first parcel referring to them. This can deadlock when a later parcel is needed to finish an earlier one's transfer, for instance a device conduit's control message sent together with the parcels whose data it moves. The input archive now records the keys of the tracked objects loaded so far and the back-references a parcel loads. A parcel waits for the steps of the earlier parcels only if it refers to an object one of them has loaded; otherwise it waits for its own steps only. Errors propagate the same way. Signed-off-by: Hartmut Kaiser --- .../hpx/serialization/detail/pointer.hpp | 26 ++++++ .../detail/post_receive_actions.hpp | 62 +++++++++++-- .../src/detail/post_receive_actions.cpp | 36 +++++++- .../unit/serialization_post_receive_steps.cpp | 91 +++++++++++++++---- libs/full/parcelset/src/parcel.cpp | 14 +-- 5 files changed, 198 insertions(+), 31 deletions(-) diff --git a/libs/core/serialization/include/hpx/serialization/detail/pointer.hpp b/libs/core/serialization/include/hpx/serialization/detail/pointer.hpp index 3ea33fb7984..be697505ae4 100644 --- a/libs/core/serialization/include/hpx/serialization/detail/pointer.hpp +++ b/libs/core/serialization/include/hpx/serialization/detail/pointer.hpp @@ -17,6 +17,7 @@ #include #include #include +#include #include #include #include @@ -408,6 +409,29 @@ namespace hpx::serialization { } } + // The steps a received parcel waits for depend on whether it uses + // objects that earlier parcels of the message have loaded (see + // post_receive_actions::take_parcel_steps). + template + void note_object_loaded(Archive& ar, std::uint64_t const pos) + { + if (auto* actions = + ar.template try_get_extra_data()) + { + actions->object_loaded(pos); + } + } + + template + void note_back_reference(Archive& ar, std::uint64_t const pos) + { + if (auto* actions = + ar.template try_get_extra_data()) + { + actions->back_reference(pos); + } + } + // forwarded serialize pointer functions template HPX_FORCEINLINE void serialize_pointer_tracked( @@ -453,6 +477,7 @@ namespace hpx::serialization { Pointer temp = detail::pointer_input_dispatcher::type::call( ar); + note_object_loaded(ar, pos); register_pointer(ar, pos, ptr_helper_ptr( //-V824 new detail::erase_ptr_helper( @@ -460,6 +485,7 @@ namespace hpx::serialization { } else { + note_back_reference(ar, pos); auto& tracked = tracked_pointer(ar, pos); if (tracked.type() != typeid(Pointer)) { diff --git a/libs/core/serialization/include/hpx/serialization/detail/post_receive_actions.hpp b/libs/core/serialization/include/hpx/serialization/detail/post_receive_actions.hpp index e9445b058ba..4b134774799 100644 --- a/libs/core/serialization/include/hpx/serialization/detail/post_receive_actions.hpp +++ b/libs/core/serialization/include/hpx/serialization/detail/post_receive_actions.hpp @@ -10,6 +10,7 @@ #include #include +#include #include #include #include @@ -22,8 +23,8 @@ namespace hpx::serialization::detail { - // The completion of a parcel's steps and of those of the parcels before - // it in the same archive. + // The completion of a parcel's steps, and of those of the parcels before + // it in the same archive if it uses objects they have loaded. HPX_CXX_CORE_EXPORT class HPX_CORE_EXPORT receive_completion { public: @@ -31,6 +32,12 @@ namespace hpx::serialization::detail { static std::shared_ptr create( std::shared_ptr previous, std::size_t steps); + // complete once both 'first' and 'second' are (neither is null), + // with the first error of the two + static std::shared_ptr join( + std::shared_ptr const& first, + std::shared_ptr const& second); + explicit receive_completion(std::size_t pending) noexcept : pending_(pending) { @@ -126,17 +133,45 @@ namespace hpx::serialization::detail { return actions_.empty() && transfers_.empty(); } + // An object shared through a tracked pointer was loaded; 'key' is + // its position in the archive as the sender wrote it (keys grow + // through a message, the objects of a parcel have larger keys than + // those of the parcels before it). + void object_loaded(std::uint64_t const key) noexcept + { + if (!any_object_ || key > last_key_) + { + last_key_ = key; + any_object_ = true; + } + } + + // A back-reference to the object loaded with 'key' was loaded: the + // parcel uses it, and if an earlier parcel of the message has loaded + // it, the steps that complete it (see take_parcel_steps). + void back_reference(std::uint64_t const key) noexcept + { + if (earlier_objects_ && key <= earlier_last_key_) + { + uses_earlier_objects_ = true; + } + } + // hand the actions to the parcel that was just de-serialized [[nodiscard]] actions_type move_actions() noexcept { return HPX_MOVE(actions_); } - // What a parcel just de-serialized waits for: its own steps, and the - // steps registered for the parcels de-serialized before it from the - // same archive. Objects shared through pointers are loaded once, by + // What a parcel just de-serialized waits for: its own steps, and, if + // it uses objects the parcels de-serialized before it from the same + // archive have loaded (back_reference), the steps registered for + // those parcels. Objects shared through pointers are loaded once, by // the first parcel referring to them, but the later ones use them as - // well. 'completion' is null if there's nothing to wait for; the + // well. A parcel that doesn't waits for its own steps only: it must + // not wait for transfers that may depend on it (e.g. a device + // conduit's control message sent with the parcels whose data it + // moves). 'completion' is null if there's nothing to wait for; the // parcel starts 'actions', each calls completion->step_done() when // it has finished. struct parcel_steps @@ -152,12 +187,27 @@ namespace hpx::serialization::detail { actions_.clear(); transfers_.clear(); last_.reset(); + any_object_ = false; + earlier_objects_ = false; + uses_earlier_objects_ = false; } private: actions_type actions_; actions_type transfers_; + + // the completion of all steps registered so far std::shared_ptr last_; + + // the largest key of the objects loaded so far, and of those the + // parcels before the current one have loaded + std::uint64_t last_key_ = 0; + std::uint64_t earlier_last_key_ = 0; + bool any_object_ = false; + bool earlier_objects_ = false; + + // the current parcel uses an object an earlier one has loaded + bool uses_earlier_objects_ = false; }; } // namespace hpx::serialization::detail diff --git a/libs/core/serialization/src/detail/post_receive_actions.cpp b/libs/core/serialization/src/detail/post_receive_actions.cpp index ce707fedc61..c153efb3317 100644 --- a/libs/core/serialization/src/detail/post_receive_actions.cpp +++ b/libs/core/serialization/src/detail/post_receive_actions.cpp @@ -151,17 +151,47 @@ namespace hpx::serialization::detail { }); } + // the parcel waits for the steps of the earlier parcels only if it + // uses objects they have loaded; the objects it has loaded itself + // count as earlier ones for the parcels after it + std::shared_ptr previous = + uses_earlier_objects_ ? last_ : nullptr; + uses_earlier_objects_ = false; + earlier_last_key_ = last_key_; + earlier_objects_ = any_object_; + if (actions_.empty()) { // only the steps of earlier parcels, if any - return {{}, last_}; + return {{}, HPX_MOVE(previous)}; } - auto completion = receive_completion::create(last_, actions_.size()); - last_ = completion; + auto completion = receive_completion::create(previous, actions_.size()); + + // a later parcel using an object loaded so far waits for all steps + // registered so far + if (previous || !last_) + { + last_ = completion; + } + else + { + last_ = receive_completion::join(last_, completion); + } return {HPX_MOVE(actions_), HPX_MOVE(completion)}; } + std::shared_ptr receive_completion::join( + std::shared_ptr const& first, + std::shared_ptr const& second) + { + // 'first' counts as one step (see create), 'second' as the other + auto result = create(first, 1); + second->when_done( + [result, s = second.get()]() { result->step_done(s->error()); }); + return result; + } + std::shared_ptr receive_completion::create( std::shared_ptr previous, std::size_t const steps) { diff --git a/libs/core/serialization/tests/unit/serialization_post_receive_steps.cpp b/libs/core/serialization/tests/unit/serialization_post_receive_steps.cpp index 85f73a186cf..76716297fb9 100644 --- a/libs/core/serialization/tests/unit/serialization_post_receive_steps.cpp +++ b/libs/core/serialization/tests/unit/serialization_post_receive_steps.cpp @@ -6,9 +6,10 @@ // The steps de-serialization defers until zero-copy chunk data has arrived // (post_receive_actions), as the parcels de-serialized one after the other -// from an archive take them: a parcel completes once its own steps and those -// of the parcels before it have finished, since objects shared through -// pointers are loaded only by the first parcel referring to them. +// from an archive take them: a parcel completes once its own steps have +// finished, and if it uses objects that parcels before it have loaded (shared +// through pointers, loaded only by the first parcel referring to them), once +// the steps of those parcels have finished as well. #include #include @@ -107,86 +108,121 @@ namespace { // the first parcel loads an object and defers completing it controlled_step s1; + actions.object_loaded(10); actions.add(s1.action()); parcel p1(actions); // the second refers to the same object, it isn't loaded again + actions.back_reference(10); parcel p2(actions); // the third loads another object, completed by a step of its own controlled_step s3; + actions.object_loaded(20); actions.add(s3.action()); parcel p3(actions); + // the fourth refers to the third one's object + actions.back_reference(20); + parcel p4(actions); + HPX_TEST_EQ(p1.steps.actions.size(), std::size_t(1)); HPX_TEST(p2.steps.actions.empty()); HPX_TEST_EQ(p3.steps.actions.size(), std::size_t(1)); + HPX_TEST(p4.steps.actions.empty()); HPX_TEST(p2.steps.completion == p1.steps.completion); HPX_TEST(p3.steps.completion != p1.steps.completion); p1.start(); p2.start(); p3.start(); + p4.start(); HPX_TEST(!p1.complete); HPX_TEST(!p2.complete); HPX_TEST(!p3.complete); + HPX_TEST(!p4.complete); - // the third parcel's own step: it still waits for the first one + // the third parcel doesn't use the first one's object; the fourth + // waits for all steps before it s3.finish(); HPX_TEST(!p1.complete); HPX_TEST(!p2.complete); - HPX_TEST(!p3.complete); + HPX_TEST(p3.complete); + HPX_TEST(!p4.complete); s1.finish(); HPX_TEST(p1.complete); HPX_TEST(p2.complete); - HPX_TEST(p3.complete); + HPX_TEST(p4.complete); // waiting for completed steps calls right away bool called = false; - p3.steps.completion->when_done([&called]() { called = true; }); + p4.steps.completion->when_done([&called]() { called = true; }); HPX_TEST(called); } - void test_steps_finished_in_order() + // Parcels that don't use each other's objects complete independently: + // a later one must not wait for transfers that may depend on it. + void test_independent_parcels() { post_receive_actions actions; controlled_step s1; + actions.object_loaded(10); actions.add(s1.action()); parcel p1(actions); - controlled_step s2; - actions.add(s2.action()); + // no steps, no shared objects: complete right away parcel p2(actions); + HPX_TEST(!p2.steps.completion); + + // an object of its own, referred to twice in the same parcel + controlled_step s3; + actions.object_loaded(30); + actions.back_reference(30); + actions.add(s3.action()); + parcel p3(actions); p1.start(); p2.start(); + p3.start(); + HPX_TEST(p2.complete); + + s3.finish(); + HPX_TEST(p3.complete); + HPX_TEST(!p1.complete); s1.finish(); HPX_TEST(p1.complete); - HPX_TEST(!p2.complete); - - s2.finish(); - HPX_TEST(p2.complete); } // A failed step completes its parcel with the error, and the parcels - // after it (which may use the same objects) as well. + // after it that use the same objects as well. void test_failed_step() { post_receive_actions actions; controlled_step s1; + actions.object_loaded(10); actions.add(s1.action()); parcel p1(actions); + controlled_step s2; + actions.back_reference(10); actions.add(s2.action()); parcel p2(actions); + controlled_step s3; + actions.add(s3.action()); + parcel p3(actions); + p1.start(); p2.start(); + p3.start(); s2.finish(); + s3.finish(); HPX_TEST(!p2.complete); + HPX_TEST(p3.complete); + HPX_TEST(!p3.failed); s1.fail(); HPX_TEST(p1.complete); @@ -195,6 +231,28 @@ namespace { HPX_TEST(p2.failed); } + // a new message: the objects of the last one don't count + void test_reset() + { + post_receive_actions actions; + controlled_step s1; + actions.object_loaded(10); + actions.add(s1.action()); + parcel p1(actions); + + actions.reset(); + actions.back_reference(10); + parcel p2(actions); + HPX_TEST(!p2.steps.completion); + + p1.start(); + p2.start(); + HPX_TEST(p2.complete); + HPX_TEST(!p1.complete); + s1.finish(); + HPX_TEST(p1.complete); + } + // All waiters run when the last step finishes, also if one throws; the // exception is passed on afterwards. void test_throwing_waiter() @@ -303,8 +361,9 @@ int main() { test_no_steps(); test_shared_steps(); - test_steps_finished_in_order(); + test_independent_parcels(); test_failed_step(); + test_reset(); test_throwing_waiter(); test_transfers_first(); test_transfers_only(); diff --git a/libs/full/parcelset/src/parcel.cpp b/libs/full/parcelset/src/parcel.cpp index ff1f85a8be4..0d0e550cbc2 100644 --- a/libs/full/parcelset/src/parcel.cpp +++ b/libs/full/parcelset/src/parcel.cpp @@ -582,8 +582,9 @@ namespace hpx::parcelset::detail { void parcel::take_post_receive_actions(serialization::input_archive& ar) { - // also without steps of its own: the parcel may use data that the - // steps of an earlier parcel in the same archive complete + // also without steps of its own: the parcel may use objects that an + // earlier parcel in the same archive has loaded and whose data that + // parcel's steps complete (see take_parcel_steps) auto* actions = ar.try_get_extra_data< serialization::detail::post_receive_actions>(); if (actions != nullptr) @@ -607,10 +608,11 @@ namespace hpx::parcelset::detail { return; } - // f is called once the steps of this parcel and of the parcels - // before it have finished, by the thread that finished the last one; - // if one of them failed, the arguments are incomplete and the action - // isn't scheduled (the waiter is called by 'completion') + // f is called once the steps of this parcel (and of the parcels + // before it whose objects it uses) have finished, by the thread that + // finished the last one; if one of them failed, the arguments are + // incomplete and the action isn't scheduled (the waiter is called by + // 'completion') // // All steps finish (the parcels after this one wait for them), also // if the waiter can't be set up or a waiter that runs while a step is From 237714c480447b4b856f126146215036ec879e97 Mon Sep 17 00:00:00 2001 From: Hartmut Kaiser Date: Wed, 25 Nov 2026 12:38:07 -0600 Subject: [PATCH 2/6] Add an NCCL/RCCL based device conduit The conduit moves device chunks of parcels with NCCL (RCCL in HIP builds), enabled with HPX_WITH_DEVICE_CONDUIT_NCCL=ON and selected at runtime with hpx.parcel.device_conduit=nccl. It works over any parcelport. Each direction between two localities uses its own non-blocking 2-rank communicator (the receiver is rank 0 and creates the unique id). Since NCCL matches sends and receives by issue order, the receiver forms numbered rounds of the chunks it has been asked to receive and tells the sender about each one; both sides issue a round as one NCCL group. Progress is made by polling the communicator state and a CUDA event per round in the conduit's background work. NCCL's helper threads inherit the affinity of the thread creating them; the calls that create them run with the CPUs of the process, otherwise they share the single core of an HPX worker thread and transfers take about 12 ms. Device memory must not be freed with cudaFree while transfers are in flight (it waits for NCCL kernels which wait for the peer); the module's documentation describes this. Signed-off-by: Hartmut Kaiser --- CMakeLists.txt | 15 + cmake/FindNCCL.cmake | 71 ++ cmake/HPX_SetupNCCL.cmake | 44 + cmake/templates/HPXConfig.cmake.in | 8 + libs/full/CMakeLists.txt | 1 + libs/full/device_conduit_nccl/CMakeLists.txt | 39 + libs/full/device_conduit_nccl/docs/index.rst | 59 + .../hpx/device_conduit_nccl/nccl_conduit.hpp | 133 ++ .../device_conduit_nccl/src/nccl_conduit.cpp | 1093 +++++++++++++++++ .../device_conduit_nccl/tests/CMakeLists.txt | 13 + .../tests/unit/CMakeLists.txt | 28 + .../tests/unit/device_memory.cpp | 326 +++++ 12 files changed, 1830 insertions(+) create mode 100644 cmake/FindNCCL.cmake create mode 100644 cmake/HPX_SetupNCCL.cmake create mode 100644 libs/full/device_conduit_nccl/CMakeLists.txt create mode 100644 libs/full/device_conduit_nccl/docs/index.rst create mode 100644 libs/full/device_conduit_nccl/include/hpx/device_conduit_nccl/nccl_conduit.hpp create mode 100644 libs/full/device_conduit_nccl/src/nccl_conduit.cpp create mode 100644 libs/full/device_conduit_nccl/tests/CMakeLists.txt create mode 100644 libs/full/device_conduit_nccl/tests/unit/CMakeLists.txt create mode 100644 libs/full/device_conduit_nccl/tests/unit/device_memory.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 97531b18704..0d9c8f9bec5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1541,6 +1541,21 @@ if(HPX_WITH_NETWORKING) if(HPX_WITH_DEVICE_CONDUIT_UCX) hpx_add_config_define(HPX_HAVE_DEVICE_CONDUIT_UCX) endif() + hpx_option( + HPX_WITH_DEVICE_CONDUIT_NCCL + BOOL + "Enable the NCCL based device conduit (NCCL with CUDA, RCCL with HIP; set NCCL_ROOT or RCCL_ROOT if they aren't found)." + OFF + CATEGORY "Parcelport" + ) + if(HPX_WITH_DEVICE_CONDUIT_NCCL) + if(NOT (HPX_WITH_CUDA OR HPX_WITH_HIP)) + hpx_error( + "HPX_WITH_DEVICE_CONDUIT_NCCL=ON requires HPX_WITH_CUDA=ON or HPX_WITH_HIP=ON" + ) + endif() + hpx_add_config_define(HPX_HAVE_DEVICE_CONDUIT_NCCL) + endif() hpx_option( HPX_WITH_PARCELPORT_COUNTERS BOOL "Enable performance counters reporting parcelport statistics." OFF diff --git a/cmake/FindNCCL.cmake b/cmake/FindNCCL.cmake new file mode 100644 index 00000000000..7feb51d860d --- /dev/null +++ b/cmake/FindNCCL.cmake @@ -0,0 +1,71 @@ +# Copyright (c) 2026 Hartmut Kaiser +# +# SPDX-License-Identifier: BSL-1.0 +# Distributed under the Boost Software License, Version 1.0. (See accompanying +# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +# Find NVIDIA's NCCL library. Hints: NCCL_ROOT, NCCL_DIR, the environment +# variables NCCL_ROOT and NCCL_HOME, and the CUDA toolkit directory. Sets +# NCCL_FOUND, NCCL_VERSION (from nccl.h), NCCL_INCLUDE_DIR, NCCL_LIBRARY and +# defines the imported target NCCL::nccl. + +if(NOT TARGET NCCL::nccl) + + find_path( + NCCL_INCLUDE_DIR nccl.h + HINTS ${NCCL_ROOT} + ${NCCL_DIR} + ENV + NCCL_ROOT + ENV + NCCL_HOME + ${CUDAToolkit_INCLUDE_DIRS} + PATH_SUFFIXES include + ) + + find_library( + NCCL_LIBRARY + NAMES nccl + HINTS ${NCCL_ROOT} + ${NCCL_DIR} + ENV + NCCL_ROOT + ENV + NCCL_HOME + ${CUDAToolkit_LIBRARY_DIR} + PATH_SUFFIXES lib lib64 + ) + + if(NCCL_INCLUDE_DIR AND EXISTS "${NCCL_INCLUDE_DIR}/nccl.h") + file(STRINGS "${NCCL_INCLUDE_DIR}/nccl.h" _nccl_version_lines + REGEX "#define NCCL_(MAJOR|MINOR|PATCH)[ \t]+[0-9]+" + ) + foreach(_part MAJOR MINOR PATCH) + string(REGEX MATCH "NCCL_${_part}[ \t]+([0-9]+)" _match + "${_nccl_version_lines}" + ) + set(NCCL_VERSION_${_part} "${CMAKE_MATCH_1}") + endforeach() + set(NCCL_VERSION + "${NCCL_VERSION_MAJOR}.${NCCL_VERSION_MINOR}.${NCCL_VERSION_PATCH}" + ) + unset(_nccl_version_lines) + unset(_match) + endif() + + include(FindPackageHandleStandardArgs) + find_package_handle_standard_args( + NCCL + REQUIRED_VARS NCCL_LIBRARY NCCL_INCLUDE_DIR + VERSION_VAR NCCL_VERSION + ) + + if(NCCL_FOUND) + add_library(NCCL::nccl INTERFACE IMPORTED GLOBAL) + target_include_directories(NCCL::nccl SYSTEM INTERFACE ${NCCL_INCLUDE_DIR}) + target_link_libraries(NCCL::nccl INTERFACE ${NCCL_LIBRARY}) + endif() + + mark_as_advanced(NCCL_INCLUDE_DIR NCCL_LIBRARY) + +endif() diff --git a/cmake/HPX_SetupNCCL.cmake b/cmake/HPX_SetupNCCL.cmake new file mode 100644 index 00000000000..db8b8bc15a2 --- /dev/null +++ b/cmake/HPX_SetupNCCL.cmake @@ -0,0 +1,44 @@ +# Copyright (c) 2026 Hartmut Kaiser +# +# SPDX-License-Identifier: BSL-1.0 +# Distributed under the Boost Software License, Version 1.0. (See accompanying +# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +include(HPX_Message) + +# Finds the library of the NCCL device conduit: NCCL with CUDA, RCCL (the same +# API) with HIP, and defines HPX::nccl for it. Non-blocking communicators and +# ncclGetLastError need NCCL 2.14 or newer (RCCL of ROCm 5.4 or newer). +macro(hpx_setup_nccl) + if(NOT TARGET HPX::nccl) + if(HPX_WITH_HIP) + # RCCL_ROOT (the module of the CI stack sets it) or the ROCm directory + find_package( + rccl + REQUIRED + CONFIG + HINTS + ${RCCL_ROOT} + $ENV{RCCL_ROOT} + ${ROCM_PATH} + $ENV{ROCM_PATH} + /opt/rocm + ) + add_library(HPX::nccl INTERFACE IMPORTED GLOBAL) + target_link_libraries(HPX::nccl INTERFACE roc::rccl) + hpx_info(" RCCL ${rccl_VERSION} for the device conduit") + elseif(HPX_WITH_CUDA) + find_package(CUDAToolkit REQUIRED) + find_package(NCCL 2.14 REQUIRED) + add_library(HPX::nccl INTERFACE IMPORTED GLOBAL) + target_link_libraries(HPX::nccl INTERFACE NCCL::nccl CUDA::cudart) + hpx_info( + " NCCL ${NCCL_VERSION} for the device conduit: ${NCCL_LIBRARY}" + ) + else() + hpx_error( + "The NCCL device conduit requires CUDA or HIP (HPX_WITH_CUDA=ON or HPX_WITH_HIP=ON)" + ) + endif() + endif() +endmacro() diff --git a/cmake/templates/HPXConfig.cmake.in b/cmake/templates/HPXConfig.cmake.in index e42db681400..b9beb8a3413 100644 --- a/cmake/templates/HPXConfig.cmake.in +++ b/cmake/templates/HPXConfig.cmake.in @@ -80,6 +80,14 @@ if(HPX_WITH_NETWORKING AND HPX_WITH_DEVICE_CONDUIT_UCX) hpx_setup_ucx() endif() +# NCCL or RCCL (device conduit) +if(HPX_WITH_NETWORKING AND HPX_WITH_DEVICE_CONDUIT_NCCL) + set(NCCL_ROOT "@NCCL_ROOT@") + set(RCCL_ROOT "@RCCL_ROOT@") + include(HPX_SetupNCCL) + hpx_setup_nccl() +endif() + # LCW if(HPX_WITH_NETWORKING AND HPX_WITH_PARCELPORT_LCW) if(HPX_WITH_FETCH_LCW) diff --git a/libs/full/CMakeLists.txt b/libs/full/CMakeLists.txt index 8c418d57151..59d2072b1de 100644 --- a/libs/full/CMakeLists.txt +++ b/libs/full/CMakeLists.txt @@ -23,6 +23,7 @@ set(_hpx_full_modules components components_base compute + device_conduit_nccl device_conduit_ucx distribution_policies execution_distributed diff --git a/libs/full/device_conduit_nccl/CMakeLists.txt b/libs/full/device_conduit_nccl/CMakeLists.txt new file mode 100644 index 00000000000..14e407c59ff --- /dev/null +++ b/libs/full/device_conduit_nccl/CMakeLists.txt @@ -0,0 +1,39 @@ +# Copyright (c) 2026 Hartmut Kaiser +# +# SPDX-License-Identifier: BSL-1.0 +# Distributed under the Boost Software License, Version 1.0. (See accompanying +# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +if(NOT (HPX_WITH_NETWORKING AND HPX_WITH_DEVICE_CONDUIT_NCCL)) + return() +endif() + +# NCCL with CUDA, RCCL with HIP (HPX::nccl) +include(HPX_SetupNCCL) +hpx_setup_nccl() + +set(device_conduit_nccl_headers hpx/device_conduit_nccl/nccl_conduit.hpp) +set(device_conduit_nccl_sources nccl_conduit.cpp) + +include(HPX_AddModule) +add_hpx_module( + full device_conduit_nccl + GLOBAL_HEADER_GEN OFF + SOURCES ${device_conduit_nccl_sources} + HEADERS ${device_conduit_nccl_headers} + DEPENDENCIES hpx_core HPX::nccl + MODULE_DEPENDENCIES + hpx_actions + hpx_actions_base + hpx_async_distributed + hpx_naming_base + hpx_parcelset + hpx_parcelset_base + hpx_plugin_factories + CMAKE_SUBDIRS tests +) + +set(HPX_STATIC_DEVICE_CONDUIT_PLUGINS + ${HPX_STATIC_DEVICE_CONDUIT_PLUGINS} nccl + CACHE INTERNAL "" FORCE +) diff --git a/libs/full/device_conduit_nccl/docs/index.rst b/libs/full/device_conduit_nccl/docs/index.rst new file mode 100644 index 00000000000..b60e08d4594 --- /dev/null +++ b/libs/full/device_conduit_nccl/docs/index.rst @@ -0,0 +1,59 @@ +.. + Copyright (c) 2026 The STE||AR-Group + + SPDX-License-Identifier: BSL-1.0 + Distributed under the Boost Software License, Version 1.0. (See accompanying + file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +.. _modules_device_conduit_nccl: + +=================== +device_conduit_nccl +=================== + +A device conduit (``hpx::parcelset::device_conduit``) based on NCCL, or on +RCCL in HIP builds (the same API): it moves the zero-copy chunks of device +memory of parcels between localities with NCCL point-to-point operations, +below the parcelport, which sends the rest of the parcels. NCCL chooses the +path: NVLink or PCIe peer access within a node, GPUDirect RDMA between nodes, +staging through host memory where neither is available, and several network +ports at once where a node has them. + +Enable it with ``HPX_WITH_DEVICE_CONDUIT_NCCL=ON`` (it requires +``HPX_WITH_CUDA=ON`` or ``HPX_WITH_HIP=ON``) and select it at runtime with +``hpx.parcel.device_conduit=nccl``. It finds NCCL through ``NCCL_ROOT`` (or +the environment variables ``NCCL_ROOT`` and ``NCCL_HOME``) and RCCL through +``RCCL_ROOT`` or the ROCm installation. NCCL reads its own configuration from +the ``NCCL_`` environment variables (e.g. ``NCCL_DMABUF_ENABLE=1``, which +GPUDirect RDMA with ROCm needs where it is available only through DMA-BUF). + +NCCL matches the sends and receives between two ranks by the order they are +issued in, and its communicators are not thread safe. The conduit uses one +communicator of two ranks for each direction between two localities, created +when the first device data goes that way (the receiving locality creates its +identifier and sends it with its first request). The receiving locality +decides the order: it collects the receives of the chunks it has decoded into +numbered rounds, posts them as one group, and asks the sending locality for the +chunks of each round, which it sends in that order. Each transfer therefore +costs a small control message from the receiver to the sender in addition to +NCCL's own latency (tens of microseconds per operation); the conduit pays off +for large transfers on systems where NCCL is faster than the alternatives, +for instance nodes with several network ports. + +The communicators are non-blocking: no thread waits in NCCL, the conduit +polls the communicators and the CUDA events of the rounds in its background +work. A channel uses the GPU of the first chunk it moves: the conduit supports +one GPU per locality, and localities on the same node need different GPUs +(NCCL does not allow two ranks of a communicator on the same GPU). + +NCCL moves data with kernels that wait on the GPU until the other locality +has started its part of the transfer. Functions that wait for all work on the +GPU, such as ``cudaFree`` and ``cudaDeviceSynchronize``, therefore must not be +called while transfers are in flight: if both localities do, each waits for a +transfer the other cannot start, and both hang. Use memory that is allocated +once, such as the pooled allocator of ``hpx::thrust`` (the default for +``thrust::device_vector`` sent in parcels), or stream-ordered allocation +(``cudaMallocAsync`` and ``cudaFreeAsync``). + +See the :ref:`API reference ` of this module +for more details. diff --git a/libs/full/device_conduit_nccl/include/hpx/device_conduit_nccl/nccl_conduit.hpp b/libs/full/device_conduit_nccl/include/hpx/device_conduit_nccl/nccl_conduit.hpp new file mode 100644 index 00000000000..0d598b2407b --- /dev/null +++ b/libs/full/device_conduit_nccl/include/hpx/device_conduit_nccl/nccl_conduit.hpp @@ -0,0 +1,133 @@ +// Copyright (c) 2026 Hartmut Kaiser +// +// SPDX-License-Identifier: BSL-1.0 +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +#pragma once + +#include + +#if defined(HPX_HAVE_NETWORKING) && defined(HPX_HAVE_DEVICE_CONDUIT_NCCL) +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace hpx::parcelset::device_conduits { + + /// What the receiver of device chunks tells their sender: the receives + /// of round 'round' are (or will be) posted, in the order of 'tags', + /// with the sizes in 'sizes'. The sender posts the matching sends in the + /// same order, rounds strictly by number. 'id' is the ncclUniqueId of + /// the communicator of the two (with the first round only). + struct nccl_conduit_round + { + std::uint64_t round = 0; + std::vector tags; + std::vector sizes; + std::vector id; + + template + void serialize(Archive& ar, unsigned) + { + // clang-format off + ar & round & tags & sizes & id; + // clang-format on + } + }; + + /// A device conduit moving the zero-copy chunks of device memory of + /// parcels with NCCL (or RCCL, in HIP builds) point-to-point operations. + /// + /// NCCL matches sends and receives between two ranks by the order they + /// are issued in (it has no tags), its communicators aren't thread safe, + /// and HPX decodes several parcels at once. So the conduit uses one + /// communicator of two ranks per direction of a pair of localities (a + /// channel), and lets the receiver decide the order: it collects the + /// receives of the chunks it has decoded into numbered rounds, sends the + /// sender the tags of each round (an action), and posts the receives of + /// the round as one NCCL group. The sender holds its chunks until their + /// round arrives and posts the matching sends as one group, rounds by + /// number. The receiver creates the communicator (it is rank 0) when it + /// forms its first round, which carries the ncclUniqueId to the sender. + /// + /// The communicators are non-blocking: no thread waits in NCCL, the + /// conduit polls the state of the communicators and the CUDA events of + /// the rounds in its background work. A channel uses the GPU of the + /// first chunk it moves (one GPU per locality). + class HPX_EXPORT nccl_conduit : public device_conduit_impl + { + public: + explicit nccl_conduit(util::runtime_configuration const& cfg); + ~nccl_conduit() override; + + nccl_conduit(nccl_conduit const&) = delete; + nccl_conduit& operator=(nccl_conduit const&) = delete; + + [[nodiscard]] static std::string name_impl() + { + return "nccl"; + } + + [[nodiscard]] bool can_reach_impl(std::uint32_t) const noexcept + { + return true; + } + + void send_impl(std::uint32_t locality_id, + serialization::detail::device_chunk_descriptor const& d, + void const* p, std::size_t size, + hpx::move_only_function sent); + + void recv_impl(serialization::detail::device_chunk_descriptor const& d, + void* p, std::size_t size, + std::function done); + + bool background_work_impl(); + + /// Fails what is held for a locality that was disconnected + /// ('forced'); for a locality that has left, finishes the rounds it + /// has asked for first. Its channels are destroyed once idle. + void locality_removed_impl( + std::uint32_t locality_id, bool forced) noexcept; + + /// The receiver 'receiver' has formed a round of the chunks this + /// locality sent it (what the action calls). + void round_ready(std::uint32_t receiver, nccl_conduit_round round); + + struct channel; + + private: + // the channel for sending to (or receiving from) 'locality_id', + // created the first time + std::shared_ptr get_channel( + std::uint32_t locality_id, bool sending); + + // the channel for sending to 'locality_id' (also if the locality was + // removed), nullptr if there is none + std::shared_ptr find_sender(std::uint32_t locality_id); + + // makes progress on one channel, returns whether it did anything + bool progress(channel& c); + + hpx::spinlock channels_mtx_; + std::map> senders_; + std::map> receivers_; + + // the channels of removed localities, until they are idle + std::vector> removed_; + }; +} // namespace hpx::parcelset::device_conduits + +#endif diff --git a/libs/full/device_conduit_nccl/src/nccl_conduit.cpp b/libs/full/device_conduit_nccl/src/nccl_conduit.cpp new file mode 100644 index 00000000000..93473f7ea6e --- /dev/null +++ b/libs/full/device_conduit_nccl/src/nccl_conduit.cpp @@ -0,0 +1,1093 @@ +// Copyright (c) 2026 Hartmut Kaiser +// +// SPDX-License-Identifier: BSL-1.0 +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +#include +#include + +#if defined(HPX_HAVE_NETWORKING) && defined(HPX_HAVE_DEVICE_CONDUIT_NCCL) +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +// cuda* names for HIP in HIP builds +#include + +#if defined(HPX_HAVE_HIP) +#include +#if !defined(cudaMemoryTypeDevice) +#define cudaMemoryTypeDevice hipMemoryTypeDevice +#endif +#else +#include +#endif + +#if defined(__linux__) +#include +#include +#include +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace hpx::parcelset::device_conduits { + + namespace { + + // the functions the errors name + constexpr char const conduit_send[] = + "hpx::parcelset::device_conduits::nccl_conduit::send_impl"; + constexpr char const conduit_recv[] = + "hpx::parcelset::device_conduits::nccl_conduit::recv_impl"; + constexpr char const conduit_progress[] = + "hpx::parcelset::device_conduits::nccl_conduit::progress"; + constexpr char const conduit_round[] = + "hpx::parcelset::device_conduits::nccl_conduit::round_ready"; + + std::exception_ptr make_error(char const* function, std::string msg) + { + return std::make_exception_ptr(hpx::exception( + hpx::error::network_error, std::string(function) + ": " + msg)); + } + + std::exception_ptr nccl_error(char const* function, char const* what, + ncclResult_t const result, ncclComm_t const comm = nullptr) + { + std::string msg = + std::string(what) + " failed: " + ncclGetErrorString(result); + if (char const* last = ncclGetLastError(comm); + last != nullptr && *last != '\0') + { + msg += " ("; + msg += last; + msg += ")"; + } + return make_error(function, HPX_MOVE(msg)); + } + + std::exception_ptr cuda_error( + char const* function, char const* what, cudaError_t const error) + { + return make_error(function, + std::string(what) + " failed: " + cudaGetErrorString(error)); + } + + // the GPU of the device memory at 'p', -1 if it isn't device memory + int device_of(void const* p) noexcept + { + cudaPointerAttributes attributes; + std::memset(&attributes, 0, sizeof(attributes)); + if (cudaPointerGetAttributes(&attributes, p) != cudaSuccess) + { + (void) cudaGetLastError(); + return -1; + } + return attributes.type == cudaMemoryTypeDevice ? attributes.device : + -1; + } + + // makes 'device' current on this OS thread, restores the previous + // one at the end of the scope (HPX threads of other tasks may rely + // on it) + class device_guard + { + public: + explicit device_guard(int const device) noexcept + { + if (device >= 0 && cudaGetDevice(&previous_) == cudaSuccess && + previous_ != device) + { + if (cudaSetDevice(device) == cudaSuccess) + { + restore_ = true; + } + else + { + (void) cudaGetLastError(); + } + } + } + + device_guard(device_guard const&) = delete; + device_guard& operator=(device_guard const&) = delete; + + ~device_guard() + { + if (restore_ && cudaSetDevice(previous_) != cudaSuccess) + { + (void) cudaGetLastError(); + } + } + + private: + int previous_ = -1; + bool restore_ = false; + }; + +#if defined(__linux__) + // The CPUs of the process (of its main thread, which HPX doesn't + // bind), read once. + cpu_set_t const* process_cpus() noexcept + { + static cpu_set_t cpus; + static bool const valid = [] { + CPU_ZERO(&cpus); + return sched_getaffinity(getpid(), sizeof(cpus), &cpus) == 0; + }(); + return valid ? &cpus : nullptr; + } +#endif + + // NCCL creates threads in some calls (its proxy threads when a + // communicator is created, a thread launching each group of a + // non-blocking communicator), which inherit the CPUs of the calling + // thread. An HPX worker thread is bound to one core, which it keeps + // busy: NCCL's threads would run only when the scheduler preempts it, + // after milliseconds. The calling thread uses all CPUs of the process + // while it makes these calls (NCCL binds its proxy threads to the + // CPUs near the GPU among these). + template + decltype(auto) with_process_cpus(F&& f) + { +#if defined(__linux__) + cpu_set_t const* const cpus = process_cpus(); + cpu_set_t own; + CPU_ZERO(&own); + pthread_t const self = pthread_self(); + bool const widened = cpus != nullptr && + pthread_getaffinity_np(self, sizeof(own), &own) == 0 && + !CPU_EQUAL(&own, cpus) && + pthread_setaffinity_np(self, sizeof(*cpus), cpus) == 0; + auto const restore = hpx::experimental::scope_exit([&] { + if (widened) + { + (void) pthread_setaffinity_np(self, sizeof(own), &own); + } + }); +#endif + return HPX_FORWARD(F, f)(); + } + + using completion_type = + hpx::move_only_function; + + // the conduit of this locality, if it is the NCCL conduit + nccl_conduit* this_conduit() + { + device_conduit* conduit = get_device_conduit(); + if (conduit == nullptr || + conduit->name() != nccl_conduit::name_impl()) + { + HPX_THROW_EXCEPTION(hpx::error::invalid_status, conduit_round, + "the NCCL device conduit isn't used here (see " + "hpx.parcel.device_conduit)"); + } + return static_cast(conduit); + } + } // namespace + + // the receiver 'receiver' has formed a round of chunks this locality + // sent it + void nccl_conduit_round_ready( + std::uint32_t const receiver, nccl_conduit_round round) + { + this_conduit()->round_ready(receiver, HPX_MOVE(round)); + } +} // namespace hpx::parcelset::device_conduits + +HPX_PLAIN_ACTION(hpx::parcelset::device_conduits::nccl_conduit_round_ready, + nccl_conduit_round_ready_action) + +namespace hpx::parcelset::device_conduits { + + /////////////////////////////////////////////////////////////////////////// + // One direction between this locality and another one: a communicator of + // two ranks (the receiver is rank 0), a stream, and the chunks on their + // way through the rounds. + struct nccl_conduit::channel + { + // one chunk: a send or a receive + struct operation + { + std::uint64_t tag = 0; + void* p = nullptr; + std::size_t size = 0; + int device = -1; + completion_type done; + }; + + // the operations of one round, issued as one NCCL group, finished + // when 'event' (recorded on the stream after them) has completed + struct round_type + { + std::vector operations; + cudaEvent_t event = nullptr; + }; + + channel(std::uint32_t const peer, bool const sending) noexcept + : peer(peer) + , sending(sending) + { + } + + channel(channel const&) = delete; + channel& operator=(channel const&) = delete; + + ~channel() + { + // the conduit is going away (after draining it) or the channel + // is idle: anything still here can't finish any more + std::exception_ptr const error = make_error(conduit_progress, + "the NCCL device conduit was destroyed with transfers to or " + "from locality " + + std::to_string(peer) + " in flight"); + for (auto& completion : take_completions()) + { + completion(error); + } + release_nccl(); + } + + // all completions of operations not finished yet (with mtx and + // comm_mtx held, or when no other thread uses the channel) + std::vector take_completions() + { + std::vector result; + auto const take = [&](std::vector& operations) { + for (auto& op : operations) + { + if (op.done) + { + result.push_back(HPX_MOVE(op.done)); + } + } + operations.clear(); + }; + take(pending); + for (auto& [tag, op] : held) + { + if (op.done) + { + result.push_back(HPX_MOVE(op.done)); + } + } + held.clear(); + ready.clear(); + for (auto& r : formed) + { + take(r.operations); + } + formed.clear(); + for (auto& r : in_flight) + { + take(r.operations); + if (r.event != nullptr) + { + device_guard const g(device); + (void) cudaEventDestroy(r.event); + r.event = nullptr; + } + } + in_flight.clear(); + group_pending = false; + return result; + } + + // aborts the communicator, destroys the stream (with comm_mtx held) + void release_nccl() noexcept + { + device_guard const g(device); + if (comm != nullptr) + { + // nothing waits for the peer: the operations have finished, + // or they fail + (void) ncclCommAbort(comm); + comm = nullptr; + } + comm_ready = false; + if (stream != nullptr) + { + (void) cudaStreamDestroy(stream); + stream = nullptr; + } + } + + // whether nothing is left to do (with mtx and comm_mtx held) + [[nodiscard]] bool idle() const noexcept + { + return pending.empty() && held.empty() && ready.empty() && + formed.empty() && in_flight.empty() && !group_pending; + } + + std::uint32_t const peer; + bool const sending; + + // guards the queues (held for short times only) + hpx::spinlock mtx; + + // receiving: the receives not in a round yet + std::vector pending; + + // sending: the chunks waiting for their round, by tag + std::map held; + + // sending: the rounds the receiver has formed, by number + std::map ready; + + // the rounds formed (receiving) or ready with their chunks (sending) + // but not issued yet, in order + std::deque formed; + + // receiving: the number of the next round to form; sending: of the + // next round to issue + std::uint64_t next_round = 0; + + // the ncclUniqueId of the communicator (receiving: created with the + // first round; sending: the one of the first round) + std::vector id; + + // the channel has failed: all its transfers fail + std::exception_ptr error; + + // guards the NCCL and CUDA state below; NCCL communicators aren't + // thread safe (one issuer at a time, others leave the work to it) + hpx::spinlock comm_mtx; + + ncclComm_t comm = nullptr; + + // the communicator has been initialized (non-blocking) + bool comm_ready = false; + + // the last group returned ncclInProgress: the communicator must + // become ready again before the next NCCL call and the event of the + // round can be recorded + bool group_pending = false; + + int device = -1; + cudaStream_t stream = nullptr; + + // the rounds issued, in order + std::deque in_flight; + }; + + /////////////////////////////////////////////////////////////////////////// + nccl_conduit::nccl_conduit(util::runtime_configuration const&) {} + + nccl_conduit::~nccl_conduit() + { + // destroyed after drain(): the channels abort their communicators + // (the peers may have shut down already); anything still in flight + // fails (the base logs it) + std::map> senders; + std::map> receivers; + std::vector> removed; + { + std::lock_guard l(channels_mtx_); + senders.swap(senders_); + receivers.swap(receivers_); + removed.swap(removed_); + } + } + + std::shared_ptr nccl_conduit::get_channel( + std::uint32_t const locality_id, bool const sending) + { + std::lock_guard l(channels_mtx_); + auto& channels = sending ? senders_ : receivers_; + auto it = channels.find(locality_id); + if (it == channels.end()) + { + it = channels + .emplace(locality_id, + std::make_shared(locality_id, sending)) + .first; + } + return it->second; + } + + std::shared_ptr nccl_conduit::find_sender( + std::uint32_t const locality_id) + { + std::lock_guard l(channels_mtx_); + if (auto const it = senders_.find(locality_id); it != senders_.end()) + { + return it->second; + } + + // a locality that has left still asks for what was sent to it + for (auto const& c : removed_) + { + if (c->sending && c->peer == locality_id) + { + return c; + } + } + return nullptr; + } + + /////////////////////////////////////////////////////////////////////////// + void nccl_conduit::send_impl(std::uint32_t const locality_id, + serialization::detail::device_chunk_descriptor const& d, void const* p, + std::size_t const size, + hpx::move_only_function sent) + { + int const device = device_of(p); + if (device < 0) + { + // the receiver will ask for the chunk; the error stops the + // runtime (the parcel has left) + sent(make_error(conduit_send, + "the NCCL device conduit moves device memory only")); + return; + } + + std::shared_ptr const c = get_channel(locality_id, true); + std::exception_ptr error; + { + std::lock_guard l(c->mtx); + if (c->error) + { + error = c->error; + } + else + { + // held until the receiver has formed its round + c->held.emplace(d.tag, + channel::operation{d.tag, const_cast(p), size, + device, HPX_MOVE(sent)}); + } + } + if (error) + { + sent(HPX_MOVE(error)); + } + } + + void nccl_conduit::recv_impl( + serialization::detail::device_chunk_descriptor const& d, void* p, + std::size_t const size, std::function done) + { + int const device = device_of(p); + if (device < 0) + { + done(make_error(conduit_recv, + "the NCCL device conduit moves device memory only")); + return; + } + + std::shared_ptr const c = + get_channel(static_cast(d.source), false); + std::exception_ptr error; + { + std::lock_guard l(c->mtx); + if (c->error) + { + error = c->error; + } + else + { + c->pending.push_back( + channel::operation{d.tag, p, size, device, HPX_MOVE(done)}); + } + } + if (error) + { + done(HPX_MOVE(error)); + return; + } + + // forms the round now (a short wait for the next receives would make + // larger rounds, but delay this one) + progress(*c); + } + + void nccl_conduit::round_ready( + std::uint32_t const receiver, nccl_conduit_round round) + { + std::shared_ptr const c = find_sender(receiver); + if (c == nullptr) + { + // nothing was sent to it (or it was removed and is gone) + LPT_(warning).format("nccl_conduit: locality {} asks for round {} " + "of chunks this locality doesn't hold", + receiver, round.round); + return; + } + + { + std::lock_guard l(c->mtx); + if (c->error) + { + return; + } + if (round.round == 0) + { + c->id = HPX_MOVE(round.id); + } + std::uint64_t const number = round.round; + c->ready.emplace(number, HPX_MOVE(round)); + } + progress(*c); + } + + /////////////////////////////////////////////////////////////////////////// + namespace { + + // fails the channel (with mtx not held, comm_mtx held): returns the + // completions to call with the error + std::vector fail_channel( + nccl_conduit::channel& c, std::exception_ptr const& error) + { + std::vector completions; + { + std::lock_guard l(c.mtx); + if (!c.error) + { + c.error = error; + } + completions = c.take_completions(); + } + c.release_nccl(); + return completions; + } + } // namespace + + bool nccl_conduit::progress(channel& c) + { + bool did_work = false; + + // what to do once no lock is held: the rounds to tell the sender + // about, the completions to call (and their error) + std::vector rounds; + std::vector completions; + std::vector failed; + std::exception_ptr error; + + // form the rounds + { + std::lock_guard l(c.mtx); + if (c.error) + { + return false; + } + + if (!c.sending && !c.pending.empty()) + { + nccl_conduit_round r; + r.round = c.next_round++; + if (r.round == 0) + { + // the communicator's id, for the sender (rank 1) + ncclUniqueId id; + if (ncclResult_t const result = ncclGetUniqueId(&id); + result != ncclSuccess) + { + error = nccl_error( + conduit_progress, "ncclGetUniqueId", result); + } + else + { + auto const* begin = reinterpret_cast(&id); + c.id.assign(begin, begin + sizeof(id)); + r.id = c.id; + } + } + if (!error) + { + channel::round_type formed; + formed.operations.swap(c.pending); + r.tags.reserve(formed.operations.size()); + r.sizes.reserve(formed.operations.size()); + for (auto const& op : formed.operations) + { + r.tags.push_back(op.tag); + r.sizes.push_back(op.size); + } + c.formed.push_back(HPX_MOVE(formed)); + rounds.push_back(HPX_MOVE(r)); + did_work = true; + } + } + + // the sender issues the rounds strictly by number, the chunks in + // the order the receiver gave + while (c.sending && !error) + { + auto const it = c.ready.find(c.next_round); + if (it == c.ready.end()) + { + break; + } + nccl_conduit_round const& r = it->second; + channel::round_type formed; + formed.operations.reserve(r.tags.size()); + for (std::size_t i = 0; i != r.tags.size(); ++i) + { + auto const op = c.held.find(r.tags[i]); + if (op == c.held.end() || op->second.size != r.sizes[i]) + { + // the order of the channel is lost + error = make_error(conduit_progress, + "locality " + std::to_string(c.peer) + + " asks for a chunk this locality doesn't " + "hold (tag " + + std::to_string(r.tags[i]) + ")"); + break; + } + formed.operations.push_back(HPX_MOVE(op->second)); + c.held.erase(op); + } + if (error) + { + // the chunks taken already fail with the channel + for (auto& op : formed.operations) + { + failed.push_back(HPX_MOVE(op.done)); + } + break; + } + c.ready.erase(it); + ++c.next_round; + c.formed.push_back(HPX_MOVE(formed)); + did_work = true; + } + } + + // tell the senders about the new rounds (outside the locks: this + // sends a parcel) + for (auto& r : rounds) + { + try + { + hpx::id_type const dest = + naming::get_id_from_locality_id(c.peer); + std::uint32_t const here = hpx::get_locality_id(); + if (threads::get_self_ptr() != nullptr) + { + hpx::post(nccl_conduit_round_ready_action(), dest, here, + HPX_MOVE(r)); + } + else + { + // the background work of an OS thread + hpx::post([dest, here, r = HPX_MOVE(r)]() mutable { + hpx::post(nccl_conduit_round_ready_action(), dest, here, + HPX_MOVE(r)); + }); + } + } + catch (...) + { + if (!error) + { + error = std::current_exception(); + } + } + } + + // issue the rounds, poll the communicator and the rounds in flight; + // the thread holding the lock does it for all + std::unique_lock cl(c.comm_mtx, std::try_to_lock); + if (!cl.owns_lock()) + { + if (error) + { + // fail it once the lock is free (rare) + cl.lock(); + } + else + { + return did_work; + } + } + + while (!error) + { + // create the communicator once the id is there and the GPU is + // known (from the first round) + if (c.comm == nullptr) + { + int device = -1; + { + std::lock_guard l(c.mtx); + if (c.id.size() != sizeof(ncclUniqueId) || + c.formed.empty() || c.formed.front().operations.empty()) + { + break; + } + device = c.formed.front().operations.front().device; + } + + ncclUniqueId id; + std::memcpy(&id, c.id.data(), sizeof(id)); + + c.device = device; + device_guard const g(device); + if (cudaError_t const e = cudaStreamCreateWithFlags( + &c.stream, cudaStreamNonBlocking); + e != cudaSuccess) + { + (void) cudaGetLastError(); + error = cuda_error( + conduit_progress, "cudaStreamCreateWithFlags", e); + break; + } + + ncclConfig_t config = NCCL_CONFIG_INITIALIZER; + config.blocking = 0; + ncclResult_t const result = with_process_cpus([&] { + return ncclCommInitRankConfig( + &c.comm, 2, id, c.sending ? 1 : 0, &config); + }); + if (result != ncclSuccess && result != ncclInProgress) + { + error = nccl_error( + conduit_progress, "ncclCommInitRankConfig", result); + break; + } + did_work = true; + } + + // a non-blocking communicator must be ready before the next + // call (after its creation and after a group in progress) + if (!c.comm_ready || c.group_pending) + { + ncclResult_t state = ncclSuccess; + if (ncclResult_t const result = + ncclCommGetAsyncError(c.comm, &state); + result != ncclSuccess) + { + error = nccl_error(conduit_progress, + "ncclCommGetAsyncError", result, c.comm); + break; + } + if (state == ncclInProgress) + { + break; + } + if (state != ncclSuccess) + { + error = nccl_error( + conduit_progress, "the communicator", state, c.comm); + break; + } + did_work = true; + c.comm_ready = true; + if (c.group_pending) + { + // the round's operations are on the stream now + c.group_pending = false; + device_guard const g(c.device); + auto& r = c.in_flight.back(); + if (cudaError_t const e = cudaEventCreateWithFlags( + &r.event, cudaEventDisableTiming); + e != cudaSuccess) + { + (void) cudaGetLastError(); + r.event = nullptr; + error = cuda_error( + conduit_progress, "cudaEventCreateWithFlags", e); + break; + } + if (cudaError_t const e = + cudaEventRecord(r.event, c.stream); + e != cudaSuccess) + { + (void) cudaGetLastError(); + error = + cuda_error(conduit_progress, "cudaEventRecord", e); + break; + } + } + } + + // issue the next round as one group + channel::round_type r; + { + std::lock_guard l(c.mtx); + if (c.formed.empty()) + { + break; + } + r = HPX_MOVE(c.formed.front()); + c.formed.pop_front(); + } + + device_guard const g(c.device); + for (auto const& op : r.operations) + { + if (op.device != c.device) + { + error = make_error(conduit_progress, + "the NCCL device conduit moves the chunks of one GPU " + "per locality (the channel to or from locality " + + std::to_string(c.peer) + " uses GPU " + + std::to_string(c.device) + ", a chunk is on GPU " + + std::to_string(op.device) + ")"); + break; + } + } + if (error) + { + for (auto& op : r.operations) + { + failed.push_back(HPX_MOVE(op.done)); + } + break; + } + + ncclResult_t result = ncclGroupStart(); + if (result == ncclSuccess) + { + for (auto const& op : r.operations) + { + // the receiver is rank 0, the sender rank 1 + result = c.sending ? + ncclSend(op.p, op.size, ncclInt8, 0, c.comm, c.stream) : + ncclRecv(op.p, op.size, ncclInt8, 1, c.comm, c.stream); + if (result != ncclSuccess && result != ncclInProgress) + { + break; + } + } + ncclResult_t const end = + with_process_cpus([] { return ncclGroupEnd(); }); + if (result == ncclSuccess || result == ncclInProgress) + { + result = end; + } + } + if (result != ncclSuccess && result != ncclInProgress) + { + for (auto& op : r.operations) + { + failed.push_back(HPX_MOVE(op.done)); + } + error = nccl_error(conduit_progress, + c.sending ? "ncclSend" : "ncclRecv", result, c.comm); + break; + } + did_work = true; + + c.in_flight.push_back(HPX_MOVE(r)); + if (result == ncclInProgress) + { + // the event is recorded once the communicator is ready + c.group_pending = true; + c.comm_ready = false; + continue; + } + + auto& issued = c.in_flight.back(); + if (cudaError_t const e = cudaEventCreateWithFlags( + &issued.event, cudaEventDisableTiming); + e != cudaSuccess) + { + (void) cudaGetLastError(); + issued.event = nullptr; + error = + cuda_error(conduit_progress, "cudaEventCreateWithFlags", e); + break; + } + if (cudaError_t const e = cudaEventRecord(issued.event, c.stream); + e != cudaSuccess) + { + (void) cudaGetLastError(); + error = cuda_error(conduit_progress, "cudaEventRecord", e); + break; + } + } + + // the rounds that have finished, in order + while (!error && !c.in_flight.empty() && + c.in_flight.front().event != nullptr) + { + auto& r = c.in_flight.front(); + device_guard const g(c.device); + cudaError_t const e = cudaEventQuery(r.event); + if (e == cudaErrorNotReady) + { + (void) cudaGetLastError(); + break; + } + if (e != cudaSuccess) + { + (void) cudaGetLastError(); + error = cuda_error(conduit_progress, "cudaEventQuery", e); + break; + } + (void) cudaEventDestroy(r.event); + for (auto& op : r.operations) + { + completions.push_back(HPX_MOVE(op.done)); + } + c.in_flight.pop_front(); + did_work = true; + } + + // an NCCL error is reported by the communicator too (the peer + // failed or left) + if (!error && c.comm != nullptr && c.comm_ready) + { + ncclResult_t state = ncclSuccess; + if (ncclCommGetAsyncError(c.comm, &state) == ncclSuccess && + state != ncclSuccess && state != ncclInProgress) + { + error = nccl_error( + conduit_progress, "the communicator", state, c.comm); + } + } + + if (error) + { + auto rest = fail_channel(c, error); + for (auto& done : rest) + { + failed.push_back(HPX_MOVE(done)); + } + did_work = true; + } + cl.unlock(); + + for (auto& done : completions) + { + done(nullptr); + } + for (auto& done : failed) + { + done(error); + } + return did_work; + } + + bool nccl_conduit::background_work_impl() + { + std::vector> channels; + { + std::unique_lock l(channels_mtx_, std::try_to_lock); + if (!l.owns_lock()) + { + return false; + } + channels.reserve( + senders_.size() + receivers_.size() + removed_.size()); + for (auto const& [locality_id, c] : senders_) + { + channels.push_back(c); + } + for (auto const& [locality_id, c] : receivers_) + { + channels.push_back(c); + } + for (auto const& c : removed_) + { + channels.push_back(c); + } + } + + bool did_work = false; + for (auto const& c : channels) + { + did_work = progress(*c) || did_work; + } + + // destroy the channels of removed localities once idle + std::unique_lock l(channels_mtx_, std::try_to_lock); + if (l.owns_lock()) + { + std::vector> idle; + std::erase_if(removed_, [&](std::shared_ptr const& c) { + std::unique_lock cl( + c->comm_mtx, std::try_to_lock); + if (!cl.owns_lock()) + { + return false; + } + std::lock_guard ll(c->mtx); + if (!c->idle()) + { + return false; + } + idle.push_back(c); + return true; + }); + l.unlock(); + + // the last references (destroyed without locks held) + did_work = !idle.empty() || did_work; + } + return did_work; + } + + void nccl_conduit::locality_removed_impl( + std::uint32_t const locality_id, bool const forced) noexcept + { + // new transfers to the locality use new channels (and fail like + // parcels to it); the old ones finish what the locality has asked + // for, unless it was disconnected + std::vector> channels; + { + std::lock_guard l(channels_mtx_); + for (auto* map : {&senders_, &receivers_}) + { + if (auto const it = map->find(locality_id); it != map->end()) + { + channels.push_back(HPX_MOVE(it->second)); + map->erase(it); + } + } + for (auto const& c : channels) + { + removed_.push_back(c); + } + } + + if (!forced) + { + return; + } + for (auto const& c : channels) + { + std::exception_ptr const error = make_error(conduit_progress, + "locality " + std::to_string(locality_id) + + " was disconnected"); + std::vector completions; + { + std::lock_guard cl(c->comm_mtx); + completions = fail_channel(*c, error); + } + for (auto& done : completions) + { + done(error); + } + } + } +} // namespace hpx::parcelset::device_conduits + +HPX_REGISTER_DEVICE_CONDUIT(hpx::parcelset::device_conduits::nccl_conduit, nccl) + +#endif diff --git a/libs/full/device_conduit_nccl/tests/CMakeLists.txt b/libs/full/device_conduit_nccl/tests/CMakeLists.txt new file mode 100644 index 00000000000..4c1b32954de --- /dev/null +++ b/libs/full/device_conduit_nccl/tests/CMakeLists.txt @@ -0,0 +1,13 @@ +# Copyright (c) 2026 Hartmut Kaiser +# +# SPDX-License-Identifier: BSL-1.0 +# Distributed under the Boost Software License, Version 1.0. (See accompanying +# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +if(HPX_WITH_TESTS AND HPX_WITH_TESTS_UNIT) + add_hpx_pseudo_target(tests.unit.modules.device_conduit_nccl) + add_hpx_pseudo_dependencies( + tests.unit.modules tests.unit.modules.device_conduit_nccl + ) + add_subdirectory(unit) +endif() diff --git a/libs/full/device_conduit_nccl/tests/unit/CMakeLists.txt b/libs/full/device_conduit_nccl/tests/unit/CMakeLists.txt new file mode 100644 index 00000000000..e05c9caaa62 --- /dev/null +++ b/libs/full/device_conduit_nccl/tests/unit/CMakeLists.txt @@ -0,0 +1,28 @@ +# Copyright (c) 2026 Hartmut Kaiser +# +# SPDX-License-Identifier: BSL-1.0 +# Distributed under the Boost Software License, Version 1.0. (See accompanying +# file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +set(tests device_memory) + +set(device_memory_PARAMETERS LOCALITIES 2 THREADS_PER_LOCALITY 4 RUN_SERIAL) + +foreach(test ${tests}) + set(sources ${test}.cpp) + + source_group("Source Files" FILES ${sources}) + + add_hpx_executable( + ${test}_test INTERNAL_FLAGS + SOURCES ${sources} + EXCLUDE_FROM_ALL + HPX_PREFIX ${HPX_BUILD_PREFIX} + FOLDER "Tests/Unit/Modules/Full/DeviceConduitNCCL" + ) + + # the CUDA (or HIP) runtime for the device memory of the test + target_link_libraries(${test}_test PRIVATE HPX::nccl) + + add_hpx_unit_test("modules.device_conduit_nccl" ${test} ${${test}_PARAMETERS}) +endforeach() diff --git a/libs/full/device_conduit_nccl/tests/unit/device_memory.cpp b/libs/full/device_conduit_nccl/tests/unit/device_memory.cpp new file mode 100644 index 00000000000..c421966e29e --- /dev/null +++ b/libs/full/device_conduit_nccl/tests/unit/device_memory.cpp @@ -0,0 +1,326 @@ +// Copyright (c) 2026 Hartmut Kaiser +// +// SPDX-License-Identifier: BSL-1.0 +// Distributed under the Boost Software License, Version 1.0. (See accompanying +// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) + +// The NCCL device conduit moves the zero-copy chunks of device memory of +// parcels: single chunks of several sizes, parcels with two device chunks, +// empty chunks, and many parcels in flight at once in both directions (the +// receivers form rounds of several chunks, in an order the senders don't +// know). The data is GPU memory (NCCL moves nothing else); the test checks it +// on the host. NCCL needs a GPU of its own for each locality: localities on +// the same node use different GPUs, the test is skipped where a node has +// fewer GPUs than localities. +// +// The test allocates and frees its device memory stream ordered: cudaFree +// waits for all work on the GPU, including NCCL kernels waiting for the other +// locality, which may itself wait in cudaFree (a deadlock). + +#include + +#if !defined(HPX_COMPUTE_DEVICE_CODE) +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#if !defined(HPX_WINDOWS) +#include +#endif + +#if defined(HPX_HAVE_HIP) +#define cudaMallocAsync hipMallocAsync +#define cudaFreeAsync hipFreeAsync +#endif + +namespace detail = hpx::serialization::detail; + +/////////////////////////////////////////////////////////////////////////////// +// the GPU of this locality +int device() +{ + int count = 0; + HPX_TEST_EQ(cudaGetDeviceCount(&count), cudaSuccess); + return count == 0 ? 0 : static_cast(hpx::get_locality_id()) % count; +} + +// the stream of the allocations of this locality +cudaStream_t allocation_stream() +{ + static cudaStream_t const stream = [] { + HPX_TEST_EQ(cudaSetDevice(device()), cudaSuccess); + cudaStream_t s = nullptr; + HPX_TEST_EQ( + cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), cudaSuccess); + return s; + }(); + return stream; +} + +// the node of this locality and its number of GPUs +std::pair node_info() +{ + std::string host = "unknown"; +#if !defined(HPX_WINDOWS) + char name[256] = {}; + if (gethostname(name, sizeof(name) - 1) == 0) + { + host = name; + } +#endif + int count = 0; + if (cudaGetDeviceCount(&count) != cudaSuccess) + { + count = 0; + } + return {host, count}; +} +HPX_PLAIN_ACTION(node_info) + +/////////////////////////////////////////////////////////////////////////////// +// device memory, sent as a zero-copy chunk of device memory +struct device_buffer +{ + device_buffer() = default; + + explicit device_buffer(std::size_t size) + : size(size) + { + if (size != 0) + { + // on this locality's GPU (from any worker thread) + HPX_TEST_EQ(cudaSetDevice(device()), cudaSuccess); + cudaStream_t const stream = allocation_stream(); + void* p = nullptr; + HPX_TEST_EQ(cudaMallocAsync(&p, size, stream), cudaSuccess); + HPX_TEST_EQ(cudaStreamSynchronize(stream), cudaSuccess); + data = std::shared_ptr(static_cast(p), + [stream](char* q) { (void) cudaFreeAsync(q, stream); }); + } + } + + // device memory holding 'host' + static device_buffer from_host(std::vector const& host) + { + device_buffer b(host.size()); + if (!host.empty()) + { + cudaError_t const e = cudaMemcpy( + b.data.get(), host.data(), host.size(), cudaMemcpyHostToDevice); + HPX_TEST_MSG(e == cudaSuccess, cudaGetErrorString(e)); + } + return b; + } + + [[nodiscard]] std::vector to_host() const + { + std::vector host(size); + if (size != 0) + { + HPX_TEST_EQ(cudaSetDevice(device()), cudaSuccess); + cudaError_t const e = cudaMemcpy( + host.data(), data.get(), size, cudaMemcpyDeviceToHost); + HPX_TEST_MSG(e == cudaSuccess, cudaGetErrorString(e)); + } + return host; + } + + template + void save(Archive& ar, unsigned) const + { + ar << size; + ar.save_binary_chunk(detail::fundamental_types::none, data.get(), size, + hpx::serialization::chunk_memory::device); + } + + template + void load(Archive& ar, unsigned) + { + std::size_t n = 0; + ar >> n; + *this = device_buffer(n); + if (n == 0) + { + // the archive has no chunk for empty data + return; + } + + // the conduit moves the data (asked first, as device_vector does) + HPX_TEST(ar.next_chunk_from_transport()); + ar.load_binary_chunk(detail::fundamental_types::none, data.get(), n, + true, hpx::serialization::chunk_memory::device); + } + + HPX_SERIALIZATION_SPLIT_MEMBER() + + std::size_t size = 0; + std::shared_ptr data; +}; + +std::vector pattern(std::size_t size, char first) +{ + std::vector v(size); + for (std::size_t i = 0; i != size; ++i) + { + v[i] = static_cast(first + static_cast(i % 61)); + } + return v; +} + +/////////////////////////////////////////////////////////////////////////////// +// checks its arguments (the data has arrived when the action runs) and +// returns device data +device_buffer exchange(device_buffer const& d, std::size_t size, char first) +{ + HPX_TEST(d.to_host() == pattern(size, first)); + return device_buffer::from_host( + pattern(size, static_cast(first + 1))); +} +HPX_PLAIN_ACTION(exchange) + +// two device chunks in one parcel +std::pair exchange_two( + device_buffer const& a, device_buffer const& b, std::size_t size) +{ + HPX_TEST(a.to_host() == pattern(size, 'a')); + HPX_TEST(b.to_host() == pattern(size / 2, 'b')); + return {device_buffer::from_host(pattern(size / 3, 'c')), + device_buffer::from_host(pattern(size, 'd'))}; +} +HPX_PLAIN_ACTION(exchange_two) + +// many exchanges at once from 'source' with the localities in 'targets' +// (both directions are busy when all localities run it) +void exchange_many(std::vector const& targets, std::size_t count) +{ + std::vector> results; + std::vector sizes; + for (std::size_t i = 0; i != count; ++i) + { + for (hpx::id_type const& id : targets) + { + std::size_t const size = (std::size_t(1) << (i % 21)) + i; + char const first = static_cast('A' + (i % 20)); + sizes.push_back(size); + results.push_back(hpx::async(id, + device_buffer::from_host(pattern(size, first)), size, first)); + } + } + + std::size_t k = 0; + for (std::size_t i = 0; i != count; ++i) + { + for (std::size_t j = 0; j != targets.size(); ++j, ++k) + { + char const first = static_cast('A' + (i % 20) + 1); + HPX_TEST(results[k].get().to_host() == pattern(sizes[k], first)); + } + } +} +HPX_PLAIN_ACTION(exchange_many) + +/////////////////////////////////////////////////////////////////////////////// +int hpx_main() +{ + hpx::parcelset::device_conduit const* conduit = + hpx::parcelset::get_device_conduit(); + HPX_TEST(conduit != nullptr); + if (conduit == nullptr) + { + return hpx::finalize(); + } + HPX_TEST_EQ(conduit->name(), std::string("nccl")); + + // a GPU for each locality + { + std::map> nodes; + for (hpx::id_type const& id : hpx::find_all_localities()) + { + auto const [host, count] = node_info_action()(id); + auto& [localities, gpus] = nodes[host]; + ++localities; + gpus = count; + } + for (auto const& [host, n] : nodes) + { + if (n.second < n.first) + { + std::cout << "skipped: node " << host << " has " << n.second + << " GPUs for " << n.first << " localities\n"; + return hpx::finalize(); + } + } + } + + std::vector const remotes = hpx::find_remote_localities(); + for (hpx::id_type const& id : remotes) + { + // single chunks, from small to larger than NCCL's buffers + for (std::size_t size : + {std::size_t(1), std::size_t(16), std::size_t(4000), + std::size_t(1) << 20, (std::size_t(8) << 20) + 3}) + { + device_buffer const result = exchange_action()( + id, device_buffer::from_host(pattern(size, 'a')), size, 'a'); + HPX_TEST(result.to_host() == pattern(size, 'b')); + } + + // empty data has no chunk + device_buffer const empty = + exchange_action()(id, device_buffer(0), 0, 'a'); + HPX_TEST_EQ(empty.size, std::size_t(0)); + + // two chunks in a parcel + std::size_t const size = std::size_t(3) << 16; + auto const [c, d] = exchange_two_action()(id, + device_buffer::from_host(pattern(size, 'a')), + device_buffer::from_host(pattern(size / 2, 'b')), size); + HPX_TEST(c.to_host() == pattern(size / 3, 'c')); + HPX_TEST(d.to_host() == pattern(size, 'd')); + } + + // many parcels in flight, all localities sending to all others + std::vector> busy; + for (hpx::id_type const& id : hpx::find_all_localities()) + { + std::vector targets; + for (hpx::id_type const& other : hpx::find_all_localities()) + { + if (other != id) + { + targets.push_back(other); + } + } + busy.push_back(hpx::async(id, targets, 64)); + } + hpx::wait_all(busy); + for (auto& f : busy) + { + HPX_TEST(!f.has_exception()); + } + + return hpx::finalize(); +} + +int main(int argc, char* argv[]) +{ + hpx::init_params params; + params.cfg = {"hpx.parcel.device_conduit=nccl"}; + HPX_TEST_EQ(hpx::init(argc, argv, params), 0); + return hpx::util::report_errors(); +} +#endif From c58ee85172d0f8d47738c4054c1313a25de2b2a6 Mon Sep 17 00:00:00 2001 From: Hartmut Kaiser Date: Wed, 25 Nov 2026 14:20:57 -0600 Subject: [PATCH 3/6] Use blocking communicators with RCCL, document HIP's stream hazard RCCL (2.22.3) fails when the non-blocking initializations of two communicators overlap in a process (hangs, crashes), which happens with the conduit's communicator per direction. With RCCL the communicators are blocking now, and their calls that may wait for the peer (initialization, issuing a group) run on a thread of each channel; the progress polls their results as it polls a non-blocking communicator with NCCL. NCCL keeps the non-blocking path. HIP runs the streams of a GPU on a few in-order hardware queues, and RCCL creates several streams of its own, so waiting for any stream may wait for an RCCL kernel that waits for the other locality. The test allocates with hipMalloc and reuses its buffers in HIP builds, and the module documentation describes the rule. The HIP names the conduit needs (cudaMallocAsync, cudaFreeAsync, cudaMemoryTypeDevice) are now mapped in custom_gpu_api.hpp. Signed-off-by: Hartmut Kaiser --- .../include/hpx/async_cuda/custom_gpu_api.hpp | 2 + libs/full/device_conduit_nccl/docs/index.rst | 16 + .../device_conduit_nccl/src/nccl_conduit.cpp | 273 +++++++++++++++++- .../tests/unit/device_memory.cpp | 52 +++- 4 files changed, 333 insertions(+), 10 deletions(-) diff --git a/libs/core/async_cuda/include/hpx/async_cuda/custom_gpu_api.hpp b/libs/core/async_cuda/include/hpx/async_cuda/custom_gpu_api.hpp index a244d6d4dfc..e4ee2e2fe24 100644 --- a/libs/core/async_cuda/include/hpx/async_cuda/custom_gpu_api.hpp +++ b/libs/core/async_cuda/include/hpx/async_cuda/custom_gpu_api.hpp @@ -43,6 +43,7 @@ #define cudaEventRecord hipEventRecord #define cudaEventSynchronize hipEventSynchronize #define cudaFree hipFree +#define cudaFreeAsync hipFreeAsync #define cudaFreeHost hipHostFree #define cudaGetDevice hipGetDevice #define cudaGetDeviceCount hipGetDeviceCount @@ -53,6 +54,7 @@ #define cudaLaunchDevice hipLaunchDevice #define cudaLaunchKernel hipLaunchKernel #define cudaMalloc hipMalloc +#define cudaMallocAsync hipMallocAsync #define cudaMallocHost hipHostMalloc #define cudaMemcpy hipMemcpy #define cudaMemcpyAsync hipMemcpyAsync diff --git a/libs/full/device_conduit_nccl/docs/index.rst b/libs/full/device_conduit_nccl/docs/index.rst index b60e08d4594..e6006060fa1 100644 --- a/libs/full/device_conduit_nccl/docs/index.rst +++ b/libs/full/device_conduit_nccl/docs/index.rst @@ -46,6 +46,14 @@ work. A channel uses the GPU of the first chunk it moves: the conduit supports one GPU per locality, and localities on the same node need different GPUs (NCCL does not allow two ranks of a communicator on the same GPU). +With RCCL the communicators are blocking instead: RCCL (2.22) hangs or +crashes when the non-blocking initializations of two communicators overlap in +a process, which happens here with a communicator per direction. The calls +that may wait for the other locality, the initialization of a communicator and +issuing a group, run on a thread of the channel, one at a time; the conduit +polls their results in its background work as it polls a non-blocking +communicator with NCCL. + NCCL moves data with kernels that wait on the GPU until the other locality has started its part of the transfer. Functions that wait for all work on the GPU, such as ``cudaFree`` and ``cudaDeviceSynchronize``, therefore must not be @@ -55,5 +63,13 @@ once, such as the pooled allocator of ``hpx::thrust`` (the default for ``thrust::device_vector`` sent in parcels), or stream-ordered allocation (``cudaMallocAsync`` and ``cudaFreeAsync``). +With HIP the rule is broader: HIP runs the streams of a GPU on a few in-order +hardware queues (``GPU_MAX_HW_QUEUES``), and RCCL creates several streams of +its own, so waiting for any stream may wait for an RCCL kernel queued before +it on the same hardware queue. This includes stream-ordered allocation +followed by ``hipStreamSynchronize``, and the work ``hipFreeAsync`` queues. +Allocate the device memory of transfers once and reuse it (``hipMalloc`` does +not wait for the GPU), and synchronize only the streams whose work is needed. + See the :ref:`API reference ` of this module for more details. diff --git a/libs/full/device_conduit_nccl/src/nccl_conduit.cpp b/libs/full/device_conduit_nccl/src/nccl_conduit.cpp index 93473f7ea6e..29a17f350d9 100644 --- a/libs/full/device_conduit_nccl/src/nccl_conduit.cpp +++ b/libs/full/device_conduit_nccl/src/nccl_conduit.cpp @@ -28,9 +28,6 @@ #if defined(HPX_HAVE_HIP) #include -#if !defined(cudaMemoryTypeDevice) -#define cudaMemoryTypeDevice hipMemoryTypeDevice -#endif #else #include #endif @@ -41,6 +38,8 @@ #include #endif +#include +#include #include #include #include @@ -51,6 +50,7 @@ #include #include #include +#include #include #include @@ -192,6 +192,169 @@ namespace hpx::parcelset::device_conduits { return HPX_FORWARD(F, f)(); } +#if defined(HPX_HAVE_HIP) + // RCCL (2.22) fails when the non-blocking initializations of two + // communicators overlap in a process (it hangs or crashes), which + // happens here with a communicator per direction. With RCCL, the + // communicators are blocking, and their calls that may wait for the + // peer (the initialization, issuing a group) run on a thread of the + // channel, one at a time; the progress polls their result as it polls + // a non-blocking communicator. + class blocking_calls + { + struct state + { + std::mutex mtx; + std::condition_variable cv; + std::function task; + bool stop = false; + std::atomic result{ncclSuccess}; + + // the communicator an initialization has created (until the + // channel takes it), or the one handed back by release + ncclComm_t comm = nullptr; + + // handed back by release + cudaStream_t stream = nullptr; + int device = -1; + }; + + public: + blocking_calls() = default; + blocking_calls(blocking_calls const&) = delete; + blocking_calls& operator=(blocking_calls const&) = delete; + + ~blocking_calls() + { + release(nullptr, nullptr, -1); + } + + // runs 'task' on the thread (no other one is running); the task + // gets the communicator to create (for an initialization) + void start(std::function task) + { + if (!thread_.joinable()) + { + // the thread, and the threads RCCL creates from it, use + // all CPUs of the process (see with_process_cpus) + try + { + thread_ = with_process_cpus( + [s = state_] { return std::thread(&run, s); }); + } + catch (...) + { + // the channel fails as with an error of RCCL + state_->result.store( + ncclSystemError, std::memory_order_release); + return; + } + } + { + std::lock_guard l(state_->mtx); + state_->result.store( + ncclInProgress, std::memory_order_relaxed); + state_->task = HPX_MOVE(task); + } + state_->cv.notify_one(); + } + + // the result of the last task, ncclInProgress while it runs + [[nodiscard]] ncclResult_t result() const noexcept + { + return state_->result.load(std::memory_order_acquire); + } + + // the communicator the last initialization has created (once + // its result is there) + [[nodiscard]] ncclComm_t take_comm() noexcept + { + std::lock_guard l(state_->mtx); + return std::exchange(state_->comm, nullptr); + } + + // stops the thread: it aborts 'comm' and destroys 'stream' (and + // a communicator an initialization still running creates) once + // its current call has returned, which may wait for the peer + void release( + ncclComm_t const comm, cudaStream_t const stream, int device) + { + if (!thread_.joinable()) + { + return; + } + { + std::lock_guard l(state_->mtx); + if (comm != nullptr) + { + state_->comm = comm; + } + state_->stream = stream; + state_->device = device; + state_->stop = true; + } + state_->cv.notify_one(); + if (result() == ncclInProgress) + { + thread_.detach(); + } + else + { + thread_.join(); + } + } + + private: + static void run(std::shared_ptr const s) + { + std::unique_lock l(s->mtx); + for (;;) + { + s->cv.wait(l, [&] { return s->task || s->stop; }); + if (s->stop) + { + // released: a task not started yet is dropped + break; + } + auto task = HPX_MOVE(s->task); + s->task = nullptr; + l.unlock(); + + // only the channel's initialization sets the + // communicator; the channel reads it after the result + ncclComm_t comm = nullptr; + ncclResult_t const result = task(comm); + + l.lock(); + if (comm != nullptr) + { + s->comm = comm; + } + s->result.store(result, std::memory_order_release); + } + + // released + if (s->comm != nullptr) + { + (void) ncclCommAbort(s->comm); + s->comm = nullptr; + } + if (s->stream != nullptr) + { + if (s->device >= 0) + { + (void) cudaSetDevice(s->device); + } + (void) cudaStreamDestroy(s->stream); + s->stream = nullptr; + } + } + + std::shared_ptr state_ = std::make_shared(); + std::thread thread_; + }; +#endif + using completion_type = hpx::move_only_function; @@ -320,6 +483,16 @@ namespace hpx::parcelset::device_conduits { // aborts the communicator, destroys the stream (with comm_mtx held) void release_nccl() noexcept { +#if defined(HPX_HAVE_HIP) + // RCCL: a call of the channel's thread may still use them (and + // wait for the peer), so they can't be released here as NCCL's + // non-blocking communicator is (ncclCommAbort stops what is in + // progress); the thread releases them when the call has returned + calls.release(comm, stream, device); + comm = nullptr; + stream = nullptr; + initializing = false; +#endif device_guard const g(device); if (comm != nullptr) { @@ -382,6 +555,14 @@ namespace hpx::parcelset::device_conduits { // the communicator has been initialized (non-blocking) bool comm_ready = false; +#if defined(HPX_HAVE_HIP) + // RCCL: the thread making the blocking calls (NCCL's non-blocking + // communicator needs none), and whether it is creating the + // communicator + blocking_calls calls; + bool initializing = false; +#endif + // the last group returned ncclInProgress: the communicator must // become ready again before the next NCCL call and the event of the // round can be recorded @@ -729,7 +910,14 @@ namespace hpx::parcelset::device_conduits { { // create the communicator once the id is there and the GPU is // known (from the first round) +#if defined(HPX_HAVE_HIP) + // RCCL: the communicator exists only once the channel's thread + // has created it (NCCL's non-blocking initialization sets it + // right away and finishes in the background) + if (c.comm == nullptr && !c.initializing) +#else if (c.comm == nullptr) +#endif { int device = -1; { @@ -757,6 +945,22 @@ namespace hpx::parcelset::device_conduits { break; } +#if defined(HPX_HAVE_HIP) + // RCCL: a blocking initialization (it waits for the peer to + // initialize its side), made by the channel's thread instead + // of a non-blocking one made here, since RCCL fails when the + // non-blocking initializations of two communicators overlap + // (see blocking_calls). The thread was created with the CPUs + // of the process, so with_process_cpus isn't needed. + c.calls.start([id, device, rank = c.sending ? 1 : 0]( + ncclComm_t& comm) { + (void) cudaSetDevice(device); + ncclConfig_t config = NCCL_CONFIG_INITIALIZER; + config.blocking = 1; + return ncclCommInitRankConfig(&comm, 2, id, rank, &config); + }); + c.initializing = true; +#else ncclConfig_t config = NCCL_CONFIG_INITIALIZER; config.blocking = 0; ncclResult_t const result = with_process_cpus([&] { @@ -769,6 +973,7 @@ namespace hpx::parcelset::device_conduits { conduit_progress, "ncclCommInitRankConfig", result); break; } +#endif did_work = true; } @@ -777,6 +982,28 @@ namespace hpx::parcelset::device_conduits { if (!c.comm_ready || c.group_pending) { ncclResult_t state = ncclSuccess; +#if defined(HPX_HAVE_HIP) + // RCCL: the communicator is blocking, there is nothing to + // poll in it; the initialization or group is done once the + // call of the channel's thread has returned, its result is + // what ncclCommGetAsyncError reports for NCCL + state = c.calls.result(); + if (state == ncclInProgress) + { + break; + } + if (c.initializing) + { + c.initializing = false; + c.comm = c.calls.take_comm(); + if (state != ncclSuccess) + { + error = nccl_error(conduit_progress, + "ncclCommInitRankConfig", state, c.comm); + break; + } + } +#else if (ncclResult_t const result = ncclCommGetAsyncError(c.comm, &state); result != ncclSuccess) @@ -789,6 +1016,7 @@ namespace hpx::parcelset::device_conduits { { break; } +#endif if (state != ncclSuccess) { error = nccl_error( @@ -860,6 +1088,44 @@ namespace hpx::parcelset::device_conduits { break; } +#if defined(HPX_HAVE_HIP) + // RCCL: the communicator is blocking, so ncclGroupEnd may wait + // (for the peer, when the connection is set up with the first + // group). Unlike NCCL's non-blocking group, which returns + // ncclInProgress and finishes on a thread of NCCL, the group is + // issued by the channel's thread, and the result is polled the + // same way (as if ncclGroupEnd had returned ncclInProgress). + std::vector> chunks; + chunks.reserve(r.operations.size()); + for (auto const& op : r.operations) + { + chunks.emplace_back(op.p, op.size); + } + c.calls.start( + [chunks = HPX_MOVE(chunks), sending = c.sending, comm = c.comm, + stream = c.stream, device = c.device](ncclComm_t&) { + (void) cudaSetDevice(device); + ncclResult_t result = ncclGroupStart(); + if (result != ncclSuccess) + { + return result; + } + for (auto const& [p, size] : chunks) + { + // the receiver is rank 0, the sender rank 1 + result = sending ? + ncclSend(p, size, ncclInt8, 0, comm, stream) : + ncclRecv(p, size, ncclInt8, 1, comm, stream); + if (result != ncclSuccess) + { + break; + } + } + ncclResult_t const end = ncclGroupEnd(); + return result == ncclSuccess ? end : result; + }); + ncclResult_t const result = ncclInProgress; +#else ncclResult_t result = ncclGroupStart(); if (result == ncclSuccess) { @@ -881,6 +1147,7 @@ namespace hpx::parcelset::device_conduits { result = end; } } +#endif if (result != ncclSuccess && result != ncclInProgress) { for (auto& op : r.operations) diff --git a/libs/full/device_conduit_nccl/tests/unit/device_memory.cpp b/libs/full/device_conduit_nccl/tests/unit/device_memory.cpp index c421966e29e..279e4672603 100644 --- a/libs/full/device_conduit_nccl/tests/unit/device_memory.cpp +++ b/libs/full/device_conduit_nccl/tests/unit/device_memory.cpp @@ -15,7 +15,12 @@ // // The test allocates and frees its device memory stream ordered: cudaFree // waits for all work on the GPU, including NCCL kernels waiting for the other -// locality, which may itself wait in cudaFree (a deadlock). +// locality, which may itself wait in cudaFree (a deadlock). With HIP, it +// allocates with hipMalloc and reuses the memory instead of freeing it: HIP +// runs the streams of a GPU on a few in-order hardware queues, so waiting for +// a stream (also the one of stream-ordered allocations) may wait for an RCCL +// kernel queued before it on the same hardware queue, which waits for the +// other locality. #include @@ -34,6 +39,7 @@ #include #include #include +#include #include #include #include @@ -42,11 +48,6 @@ #include #endif -#if defined(HPX_HAVE_HIP) -#define cudaMallocAsync hipMallocAsync -#define cudaFreeAsync hipFreeAsync -#endif - namespace detail = hpx::serialization::detail; /////////////////////////////////////////////////////////////////////////////// @@ -58,6 +59,21 @@ int device() return count == 0 ? 0 : static_cast(hpx::get_locality_id()) % count; } +#if defined(HPX_HAVE_HIP) +// the device memory released by the test, by size, for reuse (never freed, +// see above) +std::map>& released_memory() +{ + static std::map> memory; + return memory; +} + +std::mutex& released_memory_mutex() +{ + static std::mutex mtx; + return mtx; +} +#else // the stream of the allocations of this locality cudaStream_t allocation_stream() { @@ -70,6 +86,7 @@ cudaStream_t allocation_stream() }(); return stream; } +#endif // the node of this locality and its number of GPUs std::pair node_info() @@ -104,12 +121,33 @@ struct device_buffer { // on this locality's GPU (from any worker thread) HPX_TEST_EQ(cudaSetDevice(device()), cudaSuccess); - cudaStream_t const stream = allocation_stream(); void* p = nullptr; +#if defined(HPX_HAVE_HIP) + { + std::lock_guard l(released_memory_mutex()); + auto& released = released_memory()[size]; + if (!released.empty()) + { + p = released.back(); + released.pop_back(); + } + } + if (p == nullptr) + { + HPX_TEST_EQ(cudaMalloc(&p, size), cudaSuccess); + } + data = + std::shared_ptr(static_cast(p), [size](char* q) { + std::lock_guard l(released_memory_mutex()); + released_memory()[size].push_back(q); + }); +#else + cudaStream_t const stream = allocation_stream(); HPX_TEST_EQ(cudaMallocAsync(&p, size, stream), cudaSuccess); HPX_TEST_EQ(cudaStreamSynchronize(stream), cudaSuccess); data = std::shared_ptr(static_cast(p), [stream](char* q) { (void) cudaFreeAsync(q, stream); }); +#endif } } From 9f48f31c92f35383af79f6a7321ddae986b8320d Mon Sep 17 00:00:00 2001 From: Hartmut Kaiser Date: Wed, 25 Nov 2026 14:51:57 -0600 Subject: [PATCH 4/6] Add a field the conduit defines to the device chunk descriptor A device chunk's descriptor held the sending locality and a tag. It now also holds 'extra', which the archive carries with the other two and whose meaning the conduit defines: send_impl may take the descriptor by non-const reference and set it, the receiver gets it in recv_impl. The NCCL conduit uses it for the GPU of the sent data. Signed-off-by: Hartmut Kaiser --- .../serialization/detail/device_chunk_transport.hpp | 4 +++- .../include/hpx/serialization/input_archive.hpp | 1 + .../include/hpx/serialization/output_archive.hpp | 1 + .../parcelset/include/hpx/parcelset/device_conduit.hpp | 10 +++++++--- 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/libs/core/serialization/include/hpx/serialization/detail/device_chunk_transport.hpp b/libs/core/serialization/include/hpx/serialization/detail/device_chunk_transport.hpp index ef2d9fc839b..750f41cdd1e 100644 --- a/libs/core/serialization/include/hpx/serialization/detail/device_chunk_transport.hpp +++ b/libs/core/serialization/include/hpx/serialization/detail/device_chunk_transport.hpp @@ -19,11 +19,13 @@ namespace hpx::serialization::detail { // What an archive stores in place of a chunk of device memory that a // transport moves (see device_chunk_transport); the transport defines - // the meaning of the two values (e.g. the sending locality and a tag). + // the meaning of the values (e.g. the sending locality and a tag, and + // in 'extra' what else the receiver needs, such as the sending GPU). HPX_CXX_CORE_EXPORT struct device_chunk_descriptor { std::uint64_t source = 0; std::uint64_t tag = 0; + std::uint64_t extra = 0; }; // Moves the data of zero-copy chunks of device memory between the two diff --git a/libs/core/serialization/include/hpx/serialization/input_archive.hpp b/libs/core/serialization/include/hpx/serialization/input_archive.hpp index f9f83b5cbb4..01df4fd1def 100644 --- a/libs/core/serialization/include/hpx/serialization/input_archive.hpp +++ b/libs/core/serialization/include/hpx/serialization/input_archive.hpp @@ -426,6 +426,7 @@ namespace hpx::serialization { detail::device_chunk_descriptor descriptor; load(descriptor.source); load(descriptor.tag); + load(descriptor.extra); auto const* transport = try_get_extra_data(); diff --git a/libs/core/serialization/include/hpx/serialization/output_archive.hpp b/libs/core/serialization/include/hpx/serialization/output_archive.hpp index 47a6e09a58f..284a635642a 100644 --- a/libs/core/serialization/include/hpx/serialization/output_archive.hpp +++ b/libs/core/serialization/include/hpx/serialization/output_archive.hpp @@ -471,6 +471,7 @@ namespace hpx::serialization { } save(descriptor.source); save(descriptor.tag); + save(descriptor.extra); return true; } diff --git a/libs/full/parcelset/include/hpx/parcelset/device_conduit.hpp b/libs/full/parcelset/include/hpx/parcelset/device_conduit.hpp index 94dab411354..7445ef6f32e 100644 --- a/libs/full/parcelset/include/hpx/parcelset/device_conduit.hpp +++ b/libs/full/parcelset/include/hpx/parcelset/device_conduit.hpp @@ -45,6 +45,8 @@ namespace hpx::parcelset { /// serialization::detail::device_chunk_descriptor const& d, /// void const* p, std::size_t size, /// hpx::move_only_function sent) + /// (or taking 'd' by non-const reference to set d.extra, which the + /// receiver gets with the descriptor, e.g. the sending GPU) /// starts sending the data, calls 'sent' once the memory may be /// reused (the message's objects are kept alive until then), with /// the error if the data couldn't be sent: the parcel has left @@ -69,8 +71,9 @@ namespace hpx::parcelset { /// - static void config_defaults(std::vector& ini) /// adds the defaults of its configuration entries /// - /// The descriptor of a chunk holds the sending locality and a tag unique - /// for it. Conduits are registered with HPX_REGISTER_DEVICE_CONDUIT + /// The descriptor of a chunk holds the sending locality, a tag unique + /// for it, and what the conduit's send_impl sets in 'extra' (0 if it + /// sets nothing). Conduits are registered with HPX_REGISTER_DEVICE_CONDUIT /// (compiled into HPX) or a static hpx::plugins::device_conduit_factory<> /// object (e.g. in the application). HPX_CXX_EXPORT template @@ -202,7 +205,8 @@ namespace hpx::parcelset { void const* p, std::size_t const size) override { device_conduit_impl& b = base(conduit_); - serialization::detail::device_chunk_descriptor const d{ + // send_impl may set d.extra + serialization::detail::device_chunk_descriptor d{ hpx::get_locality_id(), b.next_tag_.fetch_add(1, std::memory_order_relaxed)}; From 8695b62ac90b546eee836e52e0be7b1e0244fc7a Mon Sep 17 00:00:00 2001 From: Hartmut Kaiser Date: Wed, 25 Nov 2026 14:51:57 -0600 Subject: [PATCH 5/6] Support several GPUs per locality in the NCCL conduit An NCCL rank belongs to one GPU, so a channel is now a direction between two localities and a pair of GPUs: the GPU of the sent data, which the sender puts into the chunk's descriptor, and the GPU of the memory receiving it (device data is received on the GPU of the parcel's destination). Each channel has its own communicator and rounds; the rounds name their pair of GPUs. Chunks waiting for their round are held per destination until a round of one of its channels asks for them. Communicators are created for the pairs of GPUs used only. The test sets the default target of each locality to its own GPU (results of remote calls are received there) and, where each locality has two GPUs, sends from each GPU of a locality to a component on each GPU of the others, which checks that the data arrived on its GPU. Signed-off-by: Hartmut Kaiser --- libs/full/device_conduit_nccl/docs/index.rst | 21 +- .../hpx/device_conduit_nccl/nccl_conduit.hpp | 68 ++- .../device_conduit_nccl/src/nccl_conduit.cpp | 425 +++++++++++++----- .../tests/unit/device_memory.cpp | 248 ++++++++-- 4 files changed, 590 insertions(+), 172 deletions(-) diff --git a/libs/full/device_conduit_nccl/docs/index.rst b/libs/full/device_conduit_nccl/docs/index.rst index e6006060fa1..74f22fb7f3f 100644 --- a/libs/full/device_conduit_nccl/docs/index.rst +++ b/libs/full/device_conduit_nccl/docs/index.rst @@ -29,8 +29,8 @@ GPUDirect RDMA with ROCm needs where it is available only through DMA-BUF). NCCL matches the sends and receives between two ranks by the order they are issued in, and its communicators are not thread safe. The conduit uses one -communicator of two ranks for each direction between two localities, created -when the first device data goes that way (the receiving locality creates its +communicator of two ranks for each direction between two localities (and +pair of GPUs, see below), created when the first device data goes that way (the receiving locality creates its identifier and sends it with its first request). The receiving locality decides the order: it collects the receives of the chunks it has decoded into numbered rounds, posts them as one group, and asks the sending locality for the @@ -42,9 +42,20 @@ for instance nodes with several network ports. The communicators are non-blocking: no thread waits in NCCL, the conduit polls the communicators and the CUDA events of the rounds in its background -work. A channel uses the GPU of the first chunk it moves: the conduit supports -one GPU per locality, and localities on the same node need different GPUs -(NCCL does not allow two ranks of a communicator on the same GPU). +work. + +A rank of an NCCL communicator belongs to one GPU, so a channel is a +direction between two localities and a pair of GPUs: the GPU of the sent data +and the GPU of the memory it is received into. The sender puts its GPU into +the chunk's descriptor, the receiver chooses its GPU by allocating the memory +(device data in a parcel is received on the GPU of the parcel's destination, +see the ``thrust`` module). Communicators are created for the pairs of GPUs +that are used only; each costs some GPU memory and its setup. Localities on +the same node must not use the same GPU for one channel (NCCL does not allow +two ranks of a communicator on the same GPU). The results of remote calls are +received on the GPU of the default target +(``hpx::cuda::experimental::get_default_target()``, GPU 0 unless set): where +several localities share a node, set it to a different GPU in each. With RCCL the communicators are blocking instead: RCCL (2.22) hangs or crashes when the non-blocking initializations of two communicators overlap in diff --git a/libs/full/device_conduit_nccl/include/hpx/device_conduit_nccl/nccl_conduit.hpp b/libs/full/device_conduit_nccl/include/hpx/device_conduit_nccl/nccl_conduit.hpp index 0d598b2407b..5881452c5af 100644 --- a/libs/full/device_conduit_nccl/include/hpx/device_conduit_nccl/nccl_conduit.hpp +++ b/libs/full/device_conduit_nccl/include/hpx/device_conduit_nccl/nccl_conduit.hpp @@ -22,18 +22,23 @@ #include #include #include +#include #include namespace hpx::parcelset::device_conduits { /// What the receiver of device chunks tells their sender: the receives - /// of round 'round' are (or will be) posted, in the order of 'tags', - /// with the sizes in 'sizes'. The sender posts the matching sends in the - /// same order, rounds strictly by number. 'id' is the ncclUniqueId of - /// the communicator of the two (with the first round only). + /// of round 'round' of the channel from GPU 'sender_device' of the + /// sender to GPU 'receiver_device' of the receiver are (or will be) + /// posted, in the order of 'tags', with the sizes in 'sizes'. The sender + /// posts the matching sends in the same order, rounds strictly by + /// number. 'id' is the ncclUniqueId of the channel's communicator (with + /// the first round only). struct nccl_conduit_round { std::uint64_t round = 0; + std::int32_t sender_device = -1; + std::int32_t receiver_device = -1; std::vector tags; std::vector sizes; std::vector id; @@ -42,7 +47,7 @@ namespace hpx::parcelset::device_conduits { void serialize(Archive& ar, unsigned) { // clang-format off - ar & round & tags & sizes & id; + ar & round & sender_device & receiver_device & tags & sizes & id; // clang-format on } }; @@ -51,10 +56,13 @@ namespace hpx::parcelset::device_conduits { /// parcels with NCCL (or RCCL, in HIP builds) point-to-point operations. /// /// NCCL matches sends and receives between two ranks by the order they - /// are issued in (it has no tags), its communicators aren't thread safe, - /// and HPX decodes several parcels at once. So the conduit uses one - /// communicator of two ranks per direction of a pair of localities (a - /// channel), and lets the receiver decide the order: it collects the + /// are issued in (it has no tags), a rank belongs to one GPU, its + /// communicators aren't thread safe, and HPX decodes several parcels at + /// once. So the conduit uses one communicator of two ranks per direction + /// of a pair of localities and pair of GPUs (a channel: the GPU of the + /// sent data and the one of the memory receiving it; the sender puts its + /// GPU into the chunk's descriptor), and lets the receiver decide the + /// order: it collects the /// receives of the chunks it has decoded into numbered rounds, sends the /// sender the tags of each round (an action), and posts the receives of /// the round as one NCCL group. The sender holds its chunks until their @@ -64,8 +72,11 @@ namespace hpx::parcelset::device_conduits { /// /// The communicators are non-blocking: no thread waits in NCCL, the /// conduit polls the state of the communicators and the CUDA events of - /// the rounds in its background work. A channel uses the GPU of the - /// first chunk it moves (one GPU per locality). + /// the rounds in its background work. With RCCL they are blocking, their + /// blocking calls run on a thread of each channel. Communicators are + /// created for the pairs of GPUs used only; localities on the same node + /// must not use the same GPU (two ranks of a communicator can't share + /// one). class HPX_EXPORT nccl_conduit : public device_conduit_impl { public: @@ -85,9 +96,10 @@ namespace hpx::parcelset::device_conduits { return true; } + // sets d.extra to the GPU of the data void send_impl(std::uint32_t locality_id, - serialization::detail::device_chunk_descriptor const& d, - void const* p, std::size_t size, + serialization::detail::device_chunk_descriptor& d, void const* p, + std::size_t size, hpx::move_only_function sent); void recv_impl(serialization::detail::device_chunk_descriptor const& d, @@ -107,26 +119,36 @@ namespace hpx::parcelset::device_conduits { void round_ready(std::uint32_t receiver, nccl_conduit_round round); struct channel; + struct outbox; private: - // the channel for sending to (or receiving from) 'locality_id', - // created the first time - std::shared_ptr get_channel( - std::uint32_t locality_id, bool sending); + // a channel: the other locality, the GPU here, the GPU there + using channel_key = std::tuple; - // the channel for sending to 'locality_id' (also if the locality was - // removed), nullptr if there is none - std::shared_ptr find_sender(std::uint32_t locality_id); + // the channel receiving from 'key', created the first time + std::shared_ptr get_receiver(channel_key const& key); + + // the chunks held for sending to 'locality_id', created the first + // time + std::shared_ptr get_outbox(std::uint32_t locality_id); + + // the channel sending to 'key', created the first time if chunks + // were sent to the locality (also if it was removed since), nullptr + // otherwise + std::shared_ptr find_sender(channel_key const& key); // makes progress on one channel, returns whether it did anything bool progress(channel& c); hpx::spinlock channels_mtx_; - std::map> senders_; - std::map> receivers_; + std::map> senders_; + std::map> receivers_; + std::map> outboxes_; - // the channels of removed localities, until they are idle + // the channels and outboxes of removed localities, until they are + // idle std::vector> removed_; + std::vector> removed_outboxes_; }; } // namespace hpx::parcelset::device_conduits diff --git a/libs/full/device_conduit_nccl/src/nccl_conduit.cpp b/libs/full/device_conduit_nccl/src/nccl_conduit.cpp index 29a17f350d9..0d6fe3e0ad6 100644 --- a/libs/full/device_conduit_nccl/src/nccl_conduit.cpp +++ b/libs/full/device_conduit_nccl/src/nccl_conduit.cpp @@ -411,9 +411,14 @@ namespace hpx::parcelset::device_conduits { cudaEvent_t event = nullptr; }; - channel(std::uint32_t const peer, bool const sending) noexcept + channel(std::uint32_t const peer, bool const sending, + int const local_device, int const remote_device, + std::shared_ptr box) noexcept : peer(peer) , sending(sending) + , remote_device(remote_device) + , box(HPX_MOVE(box)) + , device(local_device) { } @@ -437,48 +442,7 @@ namespace hpx::parcelset::device_conduits { // all completions of operations not finished yet (with mtx and // comm_mtx held, or when no other thread uses the channel) - std::vector take_completions() - { - std::vector result; - auto const take = [&](std::vector& operations) { - for (auto& op : operations) - { - if (op.done) - { - result.push_back(HPX_MOVE(op.done)); - } - } - operations.clear(); - }; - take(pending); - for (auto& [tag, op] : held) - { - if (op.done) - { - result.push_back(HPX_MOVE(op.done)); - } - } - held.clear(); - ready.clear(); - for (auto& r : formed) - { - take(r.operations); - } - formed.clear(); - for (auto& r : in_flight) - { - take(r.operations); - if (r.event != nullptr) - { - device_guard const g(device); - (void) cudaEventDestroy(r.event); - r.event = nullptr; - } - } - in_flight.clear(); - group_pending = false; - return result; - } + std::vector take_completions(); // aborts the communicator, destroys the stream (with comm_mtx held) void release_nccl() noexcept @@ -512,22 +476,25 @@ namespace hpx::parcelset::device_conduits { // whether nothing is left to do (with mtx and comm_mtx held) [[nodiscard]] bool idle() const noexcept { - return pending.empty() && held.empty() && ready.empty() && - formed.empty() && in_flight.empty() && !group_pending; + return pending.empty() && ready.empty() && formed.empty() && + in_flight.empty() && !group_pending; } std::uint32_t const peer; bool const sending; + // the GPU of the other end (the one here is 'device') + int const remote_device; + + // sending: the chunks held for the peer (shared by its channels) + std::shared_ptr const box; + // guards the queues (held for short times only) hpx::spinlock mtx; // receiving: the receives not in a round yet std::vector pending; - // sending: the chunks waiting for their round, by tag - std::map held; - // sending: the rounds the receiver has formed, by number std::map ready; @@ -575,6 +542,124 @@ namespace hpx::parcelset::device_conduits { std::deque in_flight; }; + /////////////////////////////////////////////////////////////////////////// + // The chunks sent to one locality that wait for their round, by tag. They + // are shared by the channels to that locality (one per pair of GPUs): + // the round a receiver forms names the channel, and its tags the chunks. + struct nccl_conduit::outbox + { + explicit outbox(std::uint32_t const peer) noexcept + : peer(peer) + { + } + + outbox(outbox const&) = delete; + outbox& operator=(outbox const&) = delete; + + ~outbox() + { + // the conduit is going away (after draining it): anything still + // here can't be sent any more + std::exception_ptr const error = make_error(conduit_progress, + "the NCCL device conduit was destroyed with chunks for " + "locality " + + std::to_string(peer) + " not sent"); + for (auto& done : take(nullptr)) + { + done(error); + } + } + + // the completions of the chunks 'tags' (of all if null), which are + // removed (with mtx held, or when no other thread uses the outbox) + std::vector take( + std::vector const* tags) + { + std::vector result; + auto const take_one = [&](auto it) { + if (it->second.done) + { + result.push_back(HPX_MOVE(it->second.done)); + } + return held.erase(it); + }; + if (tags == nullptr) + { + for (auto it = held.begin(); it != held.end();) + { + it = take_one(it); + } + } + else + { + for (std::uint64_t const tag : *tags) + { + if (auto const it = held.find(tag); it != held.end()) + { + take_one(it); + } + } + } + return result; + } + + std::uint32_t const peer; + + // guards 'held' and 'error' (after a channel's mtx, if both) + hpx::spinlock mtx; + std::map held; + + // the locality was disconnected: new chunks for it fail + std::exception_ptr error; + }; + + std::vector nccl_conduit::channel::take_completions() + { + std::vector result; + auto const take = [&](std::vector& operations) { + for (auto& op : operations) + { + if (op.done) + { + result.push_back(HPX_MOVE(op.done)); + } + } + operations.clear(); + }; + take(pending); + if (box != nullptr && !ready.empty()) + { + // the chunks of the rounds asked for but not formed yet + std::lock_guard lb(box->mtx); + for (auto& [number, r] : ready) + { + for (auto& done : box->take(&r.tags)) + { + result.push_back(HPX_MOVE(done)); + } + } + } + ready.clear(); + for (auto& r : formed) + { + take(r.operations); + } + formed.clear(); + for (auto& r : in_flight) + { + take(r.operations); + if (r.event != nullptr) + { + device_guard const g(device); + (void) cudaEventDestroy(r.event); + r.event = nullptr; + } + } + in_flight.clear(); + group_pending = false; + return result; + } + /////////////////////////////////////////////////////////////////////////// nccl_conduit::nccl_conduit(util::runtime_configuration const&) {} @@ -582,39 +667,60 @@ namespace hpx::parcelset::device_conduits { { // destroyed after drain(): the channels abort their communicators // (the peers may have shut down already); anything still in flight - // fails (the base logs it) - std::map> senders; - std::map> receivers; + // or held fails (the base logs it) + std::map> senders; + std::map> receivers; + std::map> outboxes; std::vector> removed; + std::vector> removed_outboxes; { std::lock_guard l(channels_mtx_); senders.swap(senders_); receivers.swap(receivers_); + outboxes.swap(outboxes_); removed.swap(removed_); + removed_outboxes.swap(removed_outboxes_); } } - std::shared_ptr nccl_conduit::get_channel( - std::uint32_t const locality_id, bool const sending) + std::shared_ptr nccl_conduit::get_receiver( + channel_key const& key) { std::lock_guard l(channels_mtx_); - auto& channels = sending ? senders_ : receivers_; - auto it = channels.find(locality_id); - if (it == channels.end()) + auto it = receivers_.find(key); + if (it == receivers_.end()) { - it = channels - .emplace(locality_id, - std::make_shared(locality_id, sending)) + auto const& [peer, here, there] = key; + it = receivers_ + .emplace(key, + std::make_shared( + peer, false, here, there, nullptr)) .first; } return it->second; } - std::shared_ptr nccl_conduit::find_sender( + std::shared_ptr nccl_conduit::get_outbox( std::uint32_t const locality_id) { std::lock_guard l(channels_mtx_); - if (auto const it = senders_.find(locality_id); it != senders_.end()) + auto it = outboxes_.find(locality_id); + if (it == outboxes_.end()) + { + it = + outboxes_ + .emplace(locality_id, std::make_shared(locality_id)) + .first; + } + return it->second; + } + + std::shared_ptr nccl_conduit::find_sender( + channel_key const& key) + { + auto const& [peer, here, there] = key; + std::lock_guard l(channels_mtx_); + if (auto const it = senders_.find(key); it != senders_.end()) { return it->second; } @@ -622,17 +728,38 @@ namespace hpx::parcelset::device_conduits { // a locality that has left still asks for what was sent to it for (auto const& c : removed_) { - if (c->sending && c->peer == locality_id) + if (c->sending && c->peer == peer && c->device == here && + c->remote_device == there) { return c; } } + + // the first round of this pair of GPUs + if (auto const it = outboxes_.find(peer); it != outboxes_.end()) + { + return senders_ + .emplace(key, + std::make_shared( + peer, true, here, there, it->second)) + .first->second; + } + for (auto const& box : removed_outboxes_) + { + if (box->peer == peer) + { + auto c = + std::make_shared(peer, true, here, there, box); + removed_.push_back(c); + return c; + } + } return nullptr; } /////////////////////////////////////////////////////////////////////////// void nccl_conduit::send_impl(std::uint32_t const locality_id, - serialization::detail::device_chunk_descriptor const& d, void const* p, + serialization::detail::device_chunk_descriptor& d, void const* p, std::size_t const size, hpx::move_only_function sent) { @@ -646,18 +773,21 @@ namespace hpx::parcelset::device_conduits { return; } - std::shared_ptr const c = get_channel(locality_id, true); + // the receiver uses the channel from this GPU + d.extra = static_cast(device); + + std::shared_ptr const box = get_outbox(locality_id); std::exception_ptr error; { - std::lock_guard l(c->mtx); - if (c->error) + std::lock_guard l(box->mtx); + if (box->error) { - error = c->error; + error = box->error; } else { // held until the receiver has formed its round - c->held.emplace(d.tag, + box->held.emplace(d.tag, channel::operation{d.tag, const_cast(p), size, device, HPX_MOVE(sent)}); } @@ -680,8 +810,11 @@ namespace hpx::parcelset::device_conduits { return; } + // the channel from the sender's GPU (d.extra, see send_impl) to the + // one of the memory here std::shared_ptr const c = - get_channel(static_cast(d.source), false); + get_receiver({static_cast(d.source), device, + static_cast(d.extra)}); std::exception_ptr error; { std::lock_guard l(c->mtx); @@ -709,7 +842,9 @@ namespace hpx::parcelset::device_conduits { void nccl_conduit::round_ready( std::uint32_t const receiver, nccl_conduit_round round) { - std::shared_ptr const c = find_sender(receiver); + std::shared_ptr const c = + find_sender({receiver, static_cast(round.sender_device), + static_cast(round.receiver_device)}); if (c == nullptr) { // nothing was sent to it (or it was removed and is gone) @@ -719,18 +854,34 @@ namespace hpx::parcelset::device_conduits { return; } + std::exception_ptr error; + std::vector failed; { std::lock_guard l(c->mtx); if (c->error) { - return; + // the round's chunks can't be sent any more + error = c->error; + std::lock_guard lb(c->box->mtx); + failed = c->box->take(&round.tags); + } + else + { + if (round.round == 0) + { + c->id = HPX_MOVE(round.id); + } + std::uint64_t const number = round.round; + c->ready.emplace(number, HPX_MOVE(round)); } - if (round.round == 0) + } + if (error) + { + for (auto& done : failed) { - c->id = HPX_MOVE(round.id); + done(error); } - std::uint64_t const number = round.round; - c->ready.emplace(number, HPX_MOVE(round)); + return; } progress(*c); } @@ -780,6 +931,8 @@ namespace hpx::parcelset::device_conduits { { nccl_conduit_round r; r.round = c.next_round++; + r.sender_device = c.remote_device; + r.receiver_device = c.device; if (r.round == 0) { // the communicator's id, for the sender (rank 1) @@ -826,21 +979,29 @@ namespace hpx::parcelset::device_conduits { nccl_conduit_round const& r = it->second; channel::round_type formed; formed.operations.reserve(r.tags.size()); - for (std::size_t i = 0; i != r.tags.size(); ++i) { - auto const op = c.held.find(r.tags[i]); - if (op == c.held.end() || op->second.size != r.sizes[i]) + // the chunks of the round, from the ones held for the + // peer (on this channel's GPU) + std::lock_guard lb(c.box->mtx); + for (std::size_t i = 0; i != r.tags.size(); ++i) { - // the order of the channel is lost - error = make_error(conduit_progress, - "locality " + std::to_string(c.peer) + - " asks for a chunk this locality doesn't " - "hold (tag " + - std::to_string(r.tags[i]) + ")"); - break; + auto const op = c.box->held.find(r.tags[i]); + if (op == c.box->held.end() || + op->second.size != r.sizes[i] || + op->second.device != c.device) + { + // the order of the channel is lost + error = make_error(conduit_progress, + "locality " + std::to_string(c.peer) + + " asks for a chunk this locality doesn't " + "hold on GPU " + + std::to_string(c.device) + " (tag " + + std::to_string(r.tags[i]) + ")"); + break; + } + formed.operations.push_back(HPX_MOVE(op->second)); + c.box->held.erase(op); } - formed.operations.push_back(HPX_MOVE(op->second)); - c.held.erase(op); } if (error) { @@ -919,21 +1080,19 @@ namespace hpx::parcelset::device_conduits { if (c.comm == nullptr) #endif { - int device = -1; { std::lock_guard l(c.mtx); - if (c.id.size() != sizeof(ncclUniqueId) || - c.formed.empty() || c.formed.front().operations.empty()) + if (c.id.size() != sizeof(ncclUniqueId) || c.formed.empty()) { break; } - device = c.formed.front().operations.front().device; } ncclUniqueId id; std::memcpy(&id, c.id.data(), sizeof(id)); - c.device = device; + // the GPU of the channel (from its key) + int const device = c.device; device_guard const g(device); if (cudaError_t const e = cudaStreamCreateWithFlags( &c.stream, cudaStreamNonBlocking); @@ -1066,27 +1225,13 @@ namespace hpx::parcelset::device_conduits { } device_guard const g(c.device); +#if defined(HPX_DEBUG) + // the channels are per GPU (see recv_impl and the outbox) for (auto const& op : r.operations) { - if (op.device != c.device) - { - error = make_error(conduit_progress, - "the NCCL device conduit moves the chunks of one GPU " - "per locality (the channel to or from locality " + - std::to_string(c.peer) + " uses GPU " + - std::to_string(c.device) + ", a chunk is on GPU " + - std::to_string(op.device) + ")"); - break; - } - } - if (error) - { - for (auto& op : r.operations) - { - failed.push_back(HPX_MOVE(op.done)); - } - break; + HPX_ASSERT(op.device == c.device); } +#endif #if defined(HPX_HAVE_HIP) // RCCL: the communicator is blocking, so ncclGroupEnd may wait @@ -1262,11 +1407,11 @@ namespace hpx::parcelset::device_conduits { } channels.reserve( senders_.size() + receivers_.size() + removed_.size()); - for (auto const& [locality_id, c] : senders_) + for (auto const& [key, c] : senders_) { channels.push_back(c); } - for (auto const& [locality_id, c] : receivers_) + for (auto const& [key, c] : receivers_) { channels.push_back(c); } @@ -1302,10 +1447,24 @@ namespace hpx::parcelset::device_conduits { idle.push_back(c); return true; }); + + // and their outboxes once empty (nothing left to ask for) + std::vector> empty; + std::erase_if( + removed_outboxes_, [&](std::shared_ptr const& box) { + std::unique_lock lb( + box->mtx, std::try_to_lock); + if (!lb.owns_lock() || !box->held.empty()) + { + return false; + } + empty.push_back(box); + return true; + }); l.unlock(); // the last references (destroyed without locks held) - did_work = !idle.empty() || did_work; + did_work = !idle.empty() || !empty.empty() || did_work; } return did_work; } @@ -1317,26 +1476,60 @@ namespace hpx::parcelset::device_conduits { // parcels to it); the old ones finish what the locality has asked // for, unless it was disconnected std::vector> channels; + std::shared_ptr box; { std::lock_guard l(channels_mtx_); for (auto* map : {&senders_, &receivers_}) { - if (auto const it = map->find(locality_id); it != map->end()) + // all pairs of GPUs + for (auto it = map->begin(); it != map->end();) { - channels.push_back(HPX_MOVE(it->second)); - map->erase(it); + if (std::get<0>(it->first) == locality_id) + { + channels.push_back(HPX_MOVE(it->second)); + it = map->erase(it); + } + else + { + ++it; + } } } for (auto const& c : channels) { removed_.push_back(c); } + if (auto const it = outboxes_.find(locality_id); + it != outboxes_.end()) + { + box = HPX_MOVE(it->second); + outboxes_.erase(it); + removed_outboxes_.push_back(box); + } } if (!forced) { return; } + + // the chunks not asked for yet fail too + if (box != nullptr) + { + std::exception_ptr const error = make_error(conduit_progress, + "locality " + std::to_string(locality_id) + + " was disconnected"); + std::vector completions; + { + std::lock_guard lb(box->mtx); + box->error = error; + completions = box->take(nullptr); + } + for (auto& done : completions) + { + done(error); + } + } for (auto const& c : channels) { std::exception_ptr const error = make_error(conduit_progress, diff --git a/libs/full/device_conduit_nccl/tests/unit/device_memory.cpp b/libs/full/device_conduit_nccl/tests/unit/device_memory.cpp index 279e4672603..72bd621b662 100644 --- a/libs/full/device_conduit_nccl/tests/unit/device_memory.cpp +++ b/libs/full/device_conduit_nccl/tests/unit/device_memory.cpp @@ -6,9 +6,11 @@ // The NCCL device conduit moves the zero-copy chunks of device memory of // parcels: single chunks of several sizes, parcels with two device chunks, -// empty chunks, and many parcels in flight at once in both directions (the +// empty chunks, many parcels in flight at once in both directions (the // receivers form rounds of several chunks, in an order the senders don't -// know). The data is GPU memory (NCCL moves nothing else); the test checks it +// know), and, where each locality has two GPUs, data from each GPU of a +// locality to each GPU of the others (a component per GPU names it as its +// target, the data is received there). The data is GPU memory (NCCL moves nothing else); the test checks it // on the host. NCCL needs a GPU of its own for each locality: localities on // the same node use different GPUs, the test is skipped where a node has // fewer GPUs than localities. @@ -27,13 +29,17 @@ #if !defined(HPX_COMPUTE_DEVICE_CODE) #include #include +#include #include +#include #include #include #include #include +#include + #include #include #include @@ -59,12 +65,25 @@ int device() return count == 0 ? 0 : static_cast(hpx::get_locality_id()) % count; } +// the GPU of the device memory at 'p', -1 if it isn't device memory +int gpu_of(void const* p) +{ + cudaPointerAttributes attributes{}; + if (cudaPointerGetAttributes(&attributes, p) != cudaSuccess || + attributes.type != cudaMemoryTypeDevice) + { + (void) cudaGetLastError(); + return -1; + } + return attributes.device; +} + #if defined(HPX_HAVE_HIP) -// the device memory released by the test, by size, for reuse (never freed, -// see above) -std::map>& released_memory() +// the device memory released by the test, by GPU and size, for reuse (never +// freed, see above) +std::map, std::vector>& released_memory() { - static std::map> memory; + static std::map, std::vector> memory; return memory; } @@ -74,17 +93,20 @@ std::mutex& released_memory_mutex() return mtx; } #else -// the stream of the allocations of this locality -cudaStream_t allocation_stream() +// the stream of the allocations on 'gpu' (the GPU is current) +cudaStream_t allocation_stream(int const gpu) { - static cudaStream_t const stream = [] { - HPX_TEST_EQ(cudaSetDevice(device()), cudaSuccess); - cudaStream_t s = nullptr; + static std::mutex mtx; + static std::map streams; + + std::lock_guard l(mtx); + cudaStream_t& s = streams[gpu]; + if (s == nullptr) + { HPX_TEST_EQ( cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking), cudaSuccess); - return s; - }(); - return stream; + } + return s; } #endif @@ -108,24 +130,35 @@ std::pair node_info() } HPX_PLAIN_ACTION(node_info) +// results of remote calls are received on the GPU of the default target: +// this locality's GPU (localities on one node must not share one) +void use_own_gpu() +{ + hpx::cuda::experimental::get_default_target() = + hpx::cuda::experimental::target(device()); +} +HPX_PLAIN_ACTION(use_own_gpu) + /////////////////////////////////////////////////////////////////////////////// // device memory, sent as a zero-copy chunk of device memory struct device_buffer { device_buffer() = default; - explicit device_buffer(std::size_t size) + // on 'gpu', the locality's GPU by default + explicit device_buffer(std::size_t size, int const gpu = device()) : size(size) + , gpu(gpu) { if (size != 0) { - // on this locality's GPU (from any worker thread) - HPX_TEST_EQ(cudaSetDevice(device()), cudaSuccess); + // from any worker thread + HPX_TEST_EQ(cudaSetDevice(gpu), cudaSuccess); void* p = nullptr; #if defined(HPX_HAVE_HIP) { std::lock_guard l(released_memory_mutex()); - auto& released = released_memory()[size]; + auto& released = released_memory()[{gpu, size}]; if (!released.empty()) { p = released.back(); @@ -136,13 +169,13 @@ struct device_buffer { HPX_TEST_EQ(cudaMalloc(&p, size), cudaSuccess); } - data = - std::shared_ptr(static_cast(p), [size](char* q) { + data = std::shared_ptr( + static_cast(p), [gpu, size](char* q) { std::lock_guard l(released_memory_mutex()); - released_memory()[size].push_back(q); + released_memory()[{gpu, size}].push_back(q); }); #else - cudaStream_t const stream = allocation_stream(); + cudaStream_t const stream = allocation_stream(gpu); HPX_TEST_EQ(cudaMallocAsync(&p, size, stream), cudaSuccess); HPX_TEST_EQ(cudaStreamSynchronize(stream), cudaSuccess); data = std::shared_ptr(static_cast(p), @@ -151,10 +184,11 @@ struct device_buffer } } - // device memory holding 'host' - static device_buffer from_host(std::vector const& host) + // device memory on 'gpu' holding 'host' + static device_buffer from_host( + std::vector const& host, int const gpu = device()) { - device_buffer b(host.size()); + device_buffer b(host.size(), gpu); if (!host.empty()) { cudaError_t const e = cudaMemcpy( @@ -169,7 +203,7 @@ struct device_buffer std::vector host(size); if (size != 0) { - HPX_TEST_EQ(cudaSetDevice(device()), cudaSuccess); + HPX_TEST_EQ(cudaSetDevice(gpu), cudaSuccess); cudaError_t const e = cudaMemcpy( host.data(), data.get(), size, cudaMemcpyDeviceToHost); HPX_TEST_MSG(e == cudaSuccess, cudaGetErrorString(e)); @@ -190,7 +224,13 @@ struct device_buffer { std::size_t n = 0; ar >> n; - *this = device_buffer(n); + + // on the GPU of the parcel's destination, if it names one + auto const* receive = + ar.template try_get_extra_data(); + *this = device_buffer(n, + receive != nullptr && receive->device >= 0 ? receive->device : + device()); if (n == 0) { // the archive has no chunk for empty data @@ -206,9 +246,16 @@ struct device_buffer HPX_SERIALIZATION_SPLIT_MEMBER() std::size_t size = 0; + int gpu = -1; std::shared_ptr data; }; +// it is told the GPU of the parcel's destination (receive_device) +template <> +struct hpx::traits::has_device_data : std::true_type +{ +}; + std::vector pattern(std::size_t size, char first) { std::vector v(size); @@ -271,6 +318,126 @@ void exchange_many(std::vector const& targets, std::size_t count) } HPX_PLAIN_ACTION(exchange_many) +/////////////////////////////////////////////////////////////////////////////// +// Several GPUs per locality: a component per GPU names it as its target (the +// way hpx::cuda::experimental::target does), its argument's device data is +// received on that GPU. +struct gpu_target +{ + struct native_handle_type + { + int device = -1; + + [[nodiscard]] int get_device() const noexcept + { + return device; + } + }; + + [[nodiscard]] native_handle_type const& native_handle() const noexcept + { + return handle; + } + + native_handle_type handle; +}; + +struct on_gpu : hpx::components::component_base +{ + on_gpu() = default; + explicit on_gpu(int const gpu) + : target{{gpu}} + { + } + + [[nodiscard]] gpu_target const& get_target() const noexcept + { + return target; + } + + // the data has arrived on this component's GPU + void check(device_buffer const& d, std::size_t const size, char const first) + { + HPX_TEST_EQ(d.gpu, target.handle.device); + HPX_TEST_EQ(gpu_of(d.data.get()), target.handle.device); + HPX_TEST(d.to_host() == pattern(size, first)); + } + + HPX_DEFINE_COMPONENT_ACTION(on_gpu, check) + + gpu_target target; +}; + +using on_gpu_type = hpx::components::component; +HPX_REGISTER_COMPONENT(on_gpu_type, on_gpu) +HPX_REGISTER_ACTION(on_gpu::check_action, on_gpu_check_action) + +// sends data from each of the GPUs 'first_gpu' .. 'first_gpu + count - 1' of +// this locality to each of the components 'targets' (on the other +// localities, one per GPU) +void exchange_gpus(std::vector const& targets, + int const first_gpu, int const count) +{ + std::vector> checks; + for (int gpu = first_gpu; gpu != first_gpu + count; ++gpu) + { + for (std::size_t i = 0; i != targets.size(); ++i) + { + for (std::size_t size : {std::size_t(1000), std::size_t(1) << 20}) + { + char const first = + static_cast('a' + (gpu + static_cast(i)) % 20); + checks.push_back(hpx::async(targets[i], + device_buffer::from_host(pattern(size, first), gpu), size, + first)); + } + } + } + hpx::wait_all(checks); + for (auto& f : checks) + { + HPX_TEST(!f.has_exception()); + } +} +HPX_PLAIN_ACTION(exchange_gpus) + +// each locality uses 'per_locality' GPUs of its node, disjoint from the +// other localities on the node (NCCL doesn't allow two ranks of a +// communicator on one GPU): data from each of them to each GPU of the other +// localities, all localities at once +void test_several_gpus( + std::map const& first_gpus, int const per_locality) +{ + std::map> components; + for (auto const& [id, first] : first_gpus) + { + for (int gpu = first; gpu != first + per_locality; ++gpu) + { + components[id].push_back(hpx::new_(id, gpu).get()); + } + } + + std::vector> busy; + for (auto const& [id, first] : first_gpus) + { + std::vector targets; + for (auto const& [other, ids] : components) + { + if (other != id) + { + targets.insert(targets.end(), ids.begin(), ids.end()); + } + } + busy.push_back( + hpx::async(id, targets, first, per_locality)); + } + hpx::wait_all(busy); + for (auto& f : busy) + { + HPX_TEST(!f.has_exception()); + } +} + /////////////////////////////////////////////////////////////////////////////// int hpx_main() { @@ -283,13 +450,18 @@ int hpx_main() } HPX_TEST_EQ(conduit->name(), std::string("nccl")); - // a GPU for each locality + // a GPU for each locality; the GPUs of each locality for the test of + // several GPUs per locality (at most two each, the first ones of its + // share of the node's GPUs) + std::map first_gpus; + int per_locality = 2; { std::map> nodes; for (hpx::id_type const& id : hpx::find_all_localities()) { auto const [host, count] = node_info_action()(id); auto& [localities, gpus] = nodes[host]; + first_gpus[id] = localities; // its index on the node, for now ++localities; gpus = count; } @@ -301,7 +473,17 @@ int hpx_main() << " GPUs for " << n.first << " localities\n"; return hpx::finalize(); } + per_locality = (std::min) (per_locality, n.second / n.first); } + for (auto& [id, first] : first_gpus) + { + first *= per_locality; + } + } + + for (hpx::id_type const& id : hpx::find_all_localities()) + { + use_own_gpu_action()(id); } std::vector const remotes = hpx::find_remote_localities(); @@ -351,6 +533,16 @@ int hpx_main() HPX_TEST(!f.has_exception()); } + if (per_locality >= 2) + { + test_several_gpus(first_gpus, per_locality); + } + else + { + std::cout << "several GPUs per locality: skipped (a node has fewer " + "than two GPUs per locality)\n"; + } + return hpx::finalize(); } From f4e82aef9dc850095fedf6e6868b839db15775a1 Mon Sep 17 00:00:00 2001 From: Hartmut Kaiser Date: Wed, 25 Nov 2026 17:13:44 -0600 Subject: [PATCH 6/6] Fix the inspect findings in the NCCL conduit test Rewrap the description at the top of the test, and rename the component action 'check' to 'arrived' (check clashes with a macro on Apple platforms). Also drop a clang-format off/on pair that clang-format 20 doesn't need. Signed-off-by: Hartmut Kaiser --- .../hpx/device_conduit_nccl/nccl_conduit.hpp | 2 -- .../tests/unit/device_memory.cpp | 17 +++++++++-------- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/libs/full/device_conduit_nccl/include/hpx/device_conduit_nccl/nccl_conduit.hpp b/libs/full/device_conduit_nccl/include/hpx/device_conduit_nccl/nccl_conduit.hpp index 5881452c5af..8c1cc7c25ab 100644 --- a/libs/full/device_conduit_nccl/include/hpx/device_conduit_nccl/nccl_conduit.hpp +++ b/libs/full/device_conduit_nccl/include/hpx/device_conduit_nccl/nccl_conduit.hpp @@ -46,9 +46,7 @@ namespace hpx::parcelset::device_conduits { template void serialize(Archive& ar, unsigned) { - // clang-format off ar & round & sender_device & receiver_device & tags & sizes & id; - // clang-format on } }; diff --git a/libs/full/device_conduit_nccl/tests/unit/device_memory.cpp b/libs/full/device_conduit_nccl/tests/unit/device_memory.cpp index 72bd621b662..db7565849e2 100644 --- a/libs/full/device_conduit_nccl/tests/unit/device_memory.cpp +++ b/libs/full/device_conduit_nccl/tests/unit/device_memory.cpp @@ -10,10 +10,10 @@ // receivers form rounds of several chunks, in an order the senders don't // know), and, where each locality has two GPUs, data from each GPU of a // locality to each GPU of the others (a component per GPU names it as its -// target, the data is received there). The data is GPU memory (NCCL moves nothing else); the test checks it -// on the host. NCCL needs a GPU of its own for each locality: localities on -// the same node use different GPUs, the test is skipped where a node has -// fewer GPUs than localities. +// target, the data is received there). The data is GPU memory (NCCL moves +// nothing else); the test checks it on the host. NCCL needs a GPU of its +// own for each locality: localities on the same node use different GPUs, the +// test is skipped where a node has fewer GPUs than localities. // // The test allocates and frees its device memory stream ordered: cudaFree // waits for all work on the GPU, including NCCL kernels waiting for the other @@ -356,21 +356,22 @@ struct on_gpu : hpx::components::component_base } // the data has arrived on this component's GPU - void check(device_buffer const& d, std::size_t const size, char const first) + void arrived( + device_buffer const& d, std::size_t const size, char const first) { HPX_TEST_EQ(d.gpu, target.handle.device); HPX_TEST_EQ(gpu_of(d.data.get()), target.handle.device); HPX_TEST(d.to_host() == pattern(size, first)); } - HPX_DEFINE_COMPONENT_ACTION(on_gpu, check) + HPX_DEFINE_COMPONENT_ACTION(on_gpu, arrived) gpu_target target; }; using on_gpu_type = hpx::components::component; HPX_REGISTER_COMPONENT(on_gpu_type, on_gpu) -HPX_REGISTER_ACTION(on_gpu::check_action, on_gpu_check_action) +HPX_REGISTER_ACTION(on_gpu::arrived_action, on_gpu_arrived_action) // sends data from each of the GPUs 'first_gpu' .. 'first_gpu + count - 1' of // this locality to each of the components 'targets' (on the other @@ -387,7 +388,7 @@ void exchange_gpus(std::vector const& targets, { char const first = static_cast('a' + (gpu + static_cast(i)) % 20); - checks.push_back(hpx::async(targets[i], + checks.push_back(hpx::async(targets[i], device_buffer::from_host(pattern(size, first), gpu), size, first)); }