diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index 0241ca0a468..446aa543b86 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -26,6 +26,13 @@ jobs: container: stellargroup/build_env:19 base-targets: hpx_core core components shards: 25 + # UCX for the UCX device conduit; the tests run with it, and the TCP + # parcelport sends large host chunks through it + setup: | + apt-get update && apt-get install -y --no-install-recommends libucx-dev + echo "HPX_PARCEL_DEVICE_CONDUIT=ucx" >> "$GITHUB_ENV" + echo "HPX_PARCEL_CONDUIT_HOST_CHUNKS=1" >> "$GITHUB_ENV" + echo "HPX_PARCEL_CONDUIT_HOST_THRESHOLD=8192" >> "$GITHUB_ENV" configure: | mkdir -p "$GITHUB_WORKSPACE/build" cd "$GITHUB_WORKSPACE/build" @@ -74,7 +81,8 @@ jobs: -DHPX_WITH_TESTS_MAX_THREADS_PER_LOCALITY=2 \ -DHPX_WITH_SUPERVISION=On \ -DHPX_WITH_DATAPAR=On \ - -DHPX_WITH_DATAPAR_BACKEND=EMULATE + -DHPX_WITH_DATAPAR_BACKEND=EMULATE \ + -DHPX_WITH_DEVICE_CONDUIT_UCX=On # Disable logging for now as otherwise we run out of diskspace on the # github runner instance 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/docs/sphinx/manual/launching_and_configuring_hpx_applications.rst b/docs/sphinx/manual/launching_and_configuring_hpx_applications.rst index 7aef3354945..aaea9bfc3e4 100644 --- a/docs/sphinx/manual/launching_and_configuring_hpx_applications.rst +++ b/docs/sphinx/manual/launching_and_configuring_hpx_applications.rst @@ -760,6 +760,9 @@ The ``hpx.parcel`` configuration section zero_copy_receive_optimization = ${HPX_PARCEL_ZERO_COPY_RECEIVE_OPTIMIZATION:$[hpx.parcel.array_optimization]} async_serialization = ${HPX_PARCEL_ASYNC_SERIALIZATION:1} message_handlers = ${HPX_PARCEL_MESSAGE_HANDLERS:0} + device_conduit = ${HPX_PARCEL_DEVICE_CONDUIT:none} + conduit_host_chunks = ${HPX_PARCEL_CONDUIT_HOST_CHUNKS:0} + conduit_host_threshold = ${HPX_PARCEL_CONDUIT_HOST_THRESHOLD:1048576} .. _ini_hpx_parcel: @@ -827,6 +830,32 @@ The ``hpx.parcel`` configuration section * This property defines whether this :term:`locality` is allowed to spawn a new thread for serialization (this is both for encoding and decoding parcels). The default is ``1``. + * * ``hpx.parcel.device_conduit`` + * This property selects the device conduit that moves the zero-copy chunks + of device memory of :term:`parcel`\ s between localities below the + parcelports (for instance ``ucx`` or ``nccl``, if compiled in), or + ``none``. Each :term:`locality` publishes the name of its conduit with + its endpoints; device data goes through the conduit only to localities + that use the same one, otherwise through the parcelport. The default is + ``none``. + * * ``hpx.parcel.conduit_host_chunks`` + * This property defines whether the device conduit also moves zero-copy + chunks of host memory of at least ``hpx.parcel.conduit_host_threshold`` + bytes, for objects that accept their data after their de-serialization + (arrays, for instance ``std::vector`` and ``serialize_buffer`` of + bitwise serializable types), if the conduit moves host memory (``ucx`` + does). It is set per parcelport with + ``hpx.parcel..conduit_host_chunks`` (defaulting to this + value) and published with the parcelport's endpoint: a sender uses the + conduit for host chunks only to destinations whose endpoint for the same + parcelport says they receive them that way, and once the conduit has + found that it reaches the destination (until then, and if it doesn't, + the parcelport moves them). Useful for the TCP parcelport + on networks the conduit can use directly (RDMA). The default is ``0``. + * * ``hpx.parcel.conduit_host_threshold`` + * This property defines the smallest chunk of host memory (in bytes) the + device conduit moves if ``hpx.parcel.conduit_host_chunks`` is set; the + same for all parcelports. The default is ``1048576``. * * ``hpx.parcel.message_handlers`` * This property defines whether message handlers are loaded. The default is ``0``. 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/core/serialization/include/hpx/serialization/array.hpp b/libs/core/serialization/include/hpx/serialization/array.hpp index 10884da0c87..09728d2108c 100644 --- a/libs/core/serialization/include/hpx/serialization/array.hpp +++ b/libs/core/serialization/include/hpx/serialization/array.hpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -80,15 +81,18 @@ namespace hpx::serialization { ar.template try_get_extra_data< detail::allow_zero_copy_receive>() != nullptr; + // an array doesn't use its elements while it is loaded: + // a device transport may deliver them afterwards ar.load_binary_chunk( detail::array_of_fundamental_type_v, m_t, - m_element_count * sizeof(T), allow_zero_copy_receive); + m_element_count * sizeof(T), allow_zero_copy_receive, + chunk_memory::host, true); } else { ar.save_binary_chunk( detail::array_of_fundamental_type_v, m_t, - m_element_count * sizeof(T)); + m_element_count * sizeof(T), chunk_memory::host, true); } } else diff --git a/libs/core/serialization/include/hpx/serialization/basic_archive.hpp b/libs/core/serialization/include/hpx/serialization/basic_archive.hpp index ea453b0b396..42e87ea47c9 100644 --- a/libs/core/serialization/include/hpx/serialization/basic_archive.hpp +++ b/libs/core/serialization/include/hpx/serialization/basic_archive.hpp @@ -50,7 +50,16 @@ namespace hpx::serialization { // detail::device_chunk_transport, the archive carries a marker for // each zero-copy chunk and a descriptor for each of those enable_device_transport = 0x00800000, - all_archive_flags = 0x00efe000 // all of the above + // with enable_device_transport: the transport also moves the data + // of large zero-copy chunks of host memory whose objects allow it + // (see detail::host_transport_threshold) + enable_host_transport = 0x01000000, + // with enable_device_transport: the transport would move large + // zero-copy chunks of host memory, but isn't ready to yet; the + // output archive tells it when it has one (see + // detail::device_chunk_transport::host_chunk_waiting) + host_transport_pending = 0x02000000, + all_archive_flags = 0x03efe000 // all of the above }; HPX_CXX_CORE_EXPORT constexpr archive_flags operator|( @@ -309,6 +318,22 @@ namespace hpx::serialization { flags_ & archive_flags::enable_device_transport); } + // The transport also moves large chunks of host memory (with + // enable_device_transport). + [[nodiscard]] constexpr bool enable_host_transport() const noexcept + { + return static_cast( + flags_ & archive_flags::enable_host_transport); + } + + // The transport would move large chunks of host memory once it is + // ready to (with enable_device_transport). + [[nodiscard]] constexpr bool host_transport_pending() const noexcept + { + return static_cast( + flags_ & archive_flags::host_transport_pending); + } + [[nodiscard]] constexpr std::uint32_t flags() const noexcept { return flags_; 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..6088f51a7a0 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 @@ -51,6 +53,13 @@ namespace hpx::serialization::detail { [[nodiscard]] virtual device_chunk_descriptor send( void const* p, std::size_t size) = 0; + // Sending side: the archive has a chunk of host memory the transport + // would move if it were ready to for the destination + // (archive_flags::host_transport_pending); called once per archive. + // The transport may get ready (e.g. check that it reaches the + // destination), the chunk goes with the archive meanwhile. + virtual void host_chunk_waiting() {} + // Receiving side: receives the data described by 'descriptor' into // 'size' bytes of memory at 'p' and calls 'done' once it has arrived // (with the error if it failed). It is started as one of the steps of @@ -61,6 +70,17 @@ namespace hpx::serialization::detail { std::size_t size, std::function done) = 0; }; + // The smallest chunk of host memory a transport moves in archives with + // archive_flags::enable_host_transport (for objects that allow it, see + // output_archive::save_binary_chunk), the same in all archives of a + // process (the preprocessing pass and the serialization of a parcel must + // decide alike). Set by the parcel layer at startup; by default no host + // chunk is moved. + HPX_CXX_CORE_EXPORT HPX_CORE_EXPORT std::size_t + host_transport_threshold() noexcept; + HPX_CXX_CORE_EXPORT HPX_CORE_EXPORT void set_host_transport_threshold( + std::size_t threshold) noexcept; + // The transport of an archive (extra data); none if 'transport' is // empty. HPX_CXX_CORE_EXPORT struct device_transport 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/include/hpx/serialization/input_archive.hpp b/libs/core/serialization/include/hpx/serialization/input_archive.hpp index f9f83b5cbb4..b512fed1fd3 100644 --- a/libs/core/serialization/include/hpx/serialization/input_archive.hpp +++ b/libs/core/serialization/include/hpx/serialization/input_archive.hpp @@ -338,10 +338,15 @@ namespace hpx::serialization { /// \param memory Whether \a address refers to device memory: the /// networking layer receives into it then (see /// serialization_chunk::is_device_memory). + /// \param may_arrive_later Whether the data may arrive after the + /// de-serialization if a device transport moves it, + /// also without zero-copy receive (as passed to + /// output_archive::save_binary_chunk by the sender). void load_binary_chunk(detail::fundamental_types expected, void* address, std::size_t const count, bool const allow_zero_copy_receive, - chunk_memory const memory = chunk_memory::host) + chunk_memory const memory = chunk_memory::host, + bool const may_arrive_later = false) { if (HPX_UNLIKELY(count == 0)) return; @@ -352,8 +357,8 @@ namespace hpx::serialization { } if (HPX_UNLIKELY(enable_device_transport()) && - load_with_device_transport( - address, count, allow_zero_copy_receive)) + load_with_device_transport(address, count, + allow_zero_copy_receive || may_arrive_later)) { return; } @@ -426,6 +431,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..b2fbe502879 100644 --- a/libs/core/serialization/include/hpx/serialization/output_archive.hpp +++ b/libs/core/serialization/include/hpx/serialization/output_archive.hpp @@ -412,9 +412,16 @@ namespace hpx::serialization { /// \param memory Whether \a address refers to device memory: the /// chunk is marked (see /// serialization_chunk::is_device_memory). + /// \param may_arrive_later Whether the receiving object accepts the + /// data after its de-serialization, also where the + /// receiver doesn't use zero-copy receive (it loads the + /// chunk with the same argument): a device transport + /// may then move a large chunk of host memory (see + /// archive_flags::enable_host_transport). void save_binary_chunk(detail::fundamental_types t, void const* address, std::size_t const count, - chunk_memory const memory = chunk_memory::host) + chunk_memory const memory = chunk_memory::host, + bool const may_arrive_later = false) { if (HPX_UNLIKELY(count == 0)) return; @@ -425,7 +432,8 @@ namespace hpx::serialization { } if (HPX_UNLIKELY(enable_device_transport()) && - save_with_device_transport(address, count, memory)) + save_with_device_transport( + address, count, memory, may_arrive_later)) { return; } @@ -449,11 +457,26 @@ namespace hpx::serialization { // holds the transport's descriptor instead of the chunk, 0 for a // chunk as usual. Returns whether the transport moves the data. bool save_with_device_transport(void const* address, - std::size_t const count, chunk_memory const memory) + std::size_t const count, chunk_memory const memory, + bool const may_arrive_later) { auto const* transport = try_get_extra_data(); - bool const use_transport = memory == chunk_memory::device && + bool const host_candidate = memory == chunk_memory::host && + may_arrive_later && count >= detail::host_transport_threshold(); + bool const moved = memory == chunk_memory::device || + (host_candidate && enable_host_transport()); + + // the transport isn't ready for host chunks to this destination + // yet: tell it there is one (once) + if (host_candidate && !moved && host_transport_pending() && + !host_chunk_reported_ && !is_preprocessing() && + transport != nullptr && transport->transport) + { + host_chunk_reported_ = true; + transport->transport->host_chunk_waiting(); + } + bool const use_transport = moved && (is_preprocessing() || (transport != nullptr && transport->transport)); @@ -471,11 +494,15 @@ namespace hpx::serialization { } save(descriptor.source); save(descriptor.tag); + save(descriptor.extra); return true; } std::unique_ptr buffer_; bool filtered_ = false; + + // a host chunk was reported to the transport (host_chunk_waiting) + bool host_chunk_reported_ = false; }; } // namespace hpx::serialization diff --git a/libs/core/serialization/src/detail/device_chunk_transport.cpp b/libs/core/serialization/src/detail/device_chunk_transport.cpp index 75750fc1005..87124110bbb 100644 --- a/libs/core/serialization/src/detail/device_chunk_transport.cpp +++ b/libs/core/serialization/src/detail/device_chunk_transport.cpp @@ -8,6 +8,33 @@ #include #include +#include +#include +#include + +namespace hpx::serialization::detail { + + namespace { + + std::atomic& host_threshold() noexcept + { + static std::atomic threshold{ + (std::numeric_limits::max)()}; + return threshold; + } + } // namespace + + std::size_t host_transport_threshold() noexcept + { + return host_threshold().load(std::memory_order_relaxed); + } + + void set_host_transport_threshold(std::size_t const threshold) noexcept + { + host_threshold().store(threshold, std::memory_order_relaxed); + } +} // namespace hpx::serialization::detail + namespace hpx::util { // This is explicitly instantiated to ensure that the id is stable across 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/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..74f22fb7f3f --- /dev/null +++ b/libs/full/device_conduit_nccl/docs/index.rst @@ -0,0 +1,86 @@ +.. + 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 (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 +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 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 +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 +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``). + +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/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..8c1cc7c25ab --- /dev/null +++ b/libs/full/device_conduit_nccl/include/hpx/device_conduit_nccl/nccl_conduit.hpp @@ -0,0 +1,153 @@ +// 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 +#include + +namespace hpx::parcelset::device_conduits { + + /// What the receiver of device chunks tells their sender: the receives + /// 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; + + template + void serialize(Archive& ar, unsigned) + { + ar & round & sender_device & receiver_device & tags & sizes & id; + } + }; + + /// 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), 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 + /// 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. 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: + 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; + } + + // sets d.extra to the GPU of the data + void send_impl(std::uint32_t locality_id, + 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, + 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; + struct outbox; + + private: + // a channel: the other locality, the GPU here, the GPU there + using channel_key = std::tuple; + + // 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> outboxes_; + + // the channels and outboxes of removed localities, until they are + // idle + std::vector> removed_; + std::vector> removed_outboxes_; + }; +} // 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..0d6fe3e0ad6 --- /dev/null +++ b/libs/full/device_conduit_nccl/src/nccl_conduit.cpp @@ -0,0 +1,1553 @@ +// 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 +#else +#include +#endif + +#if defined(__linux__) +#include +#include +#include +#endif + +#include +#include +#include +#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)(); + } + +#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; + + // 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, + 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) + { + } + + 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(); + + // 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) + { + // 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() && 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 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; + +#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 + bool group_pending = false; + + int device = -1; + cudaStream_t stream = nullptr; + + // the rounds issued, in order + 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&) {} + + nccl_conduit::~nccl_conduit() + { + // destroyed after drain(): the channels abort their communicators + // (the peers may have shut down already); anything still in flight + // 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_receiver( + channel_key const& key) + { + std::lock_guard l(channels_mtx_); + auto it = receivers_.find(key); + if (it == receivers_.end()) + { + 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::get_outbox( + std::uint32_t const locality_id) + { + std::lock_guard l(channels_mtx_); + 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; + } + + // a locality that has left still asks for what was sent to it + for (auto const& c : removed_) + { + 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& 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; + } + + // 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(box->mtx); + if (box->error) + { + error = box->error; + } + else + { + // held until the receiver has formed its round + box->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; + } + + // 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_receiver({static_cast(d.source), device, + static_cast(d.extra)}); + 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, 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) + LPT_(warning).format("nccl_conduit: locality {} asks for round {} " + "of chunks this locality doesn't hold", + receiver, round.round); + return; + } + + std::exception_ptr error; + std::vector failed; + { + std::lock_guard l(c->mtx); + if (c->error) + { + // 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 (error) + { + for (auto& done : failed) + { + done(error); + } + return; + } + 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++; + r.sender_device = c.remote_device; + r.receiver_device = c.device; + 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()); + { + // 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) + { + 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); + } + } + 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 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 + { + { + std::lock_guard l(c.mtx); + if (c.id.size() != sizeof(ncclUniqueId) || c.formed.empty()) + { + break; + } + } + + ncclUniqueId id; + std::memcpy(&id, c.id.data(), sizeof(id)); + + // 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); + e != cudaSuccess) + { + (void) cudaGetLastError(); + error = cuda_error( + conduit_progress, "cudaStreamCreateWithFlags", e); + 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([&] { + return ncclCommInitRankConfig( + &c.comm, 2, id, c.sending ? 1 : 0, &config); + }); + if (result != ncclSuccess && result != ncclInProgress) + { + error = nccl_error( + conduit_progress, "ncclCommInitRankConfig", result); + break; + } +#endif + 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 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) + { + error = nccl_error(conduit_progress, + "ncclCommGetAsyncError", result, c.comm); + break; + } + if (state == ncclInProgress) + { + break; + } +#endif + 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); +#if defined(HPX_DEBUG) + // the channels are per GPU (see recv_impl and the outbox) + for (auto const& op : r.operations) + { + HPX_ASSERT(op.device == c.device); + } +#endif + +#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) + { + 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; + } + } +#endif + 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& [key, c] : senders_) + { + channels.push_back(c); + } + for (auto const& [key, 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; + }); + + // 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() || !empty.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::shared_ptr box; + { + std::lock_guard l(channels_mtx_); + for (auto* map : {&senders_, &receivers_}) + { + // all pairs of GPUs + for (auto it = map->begin(); it != map->end();) + { + 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, + "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..db7565849e2 --- /dev/null +++ b/libs/full/device_conduit_nccl/tests/unit/device_memory.cpp @@ -0,0 +1,557 @@ +// 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, many parcels in flight at once in both directions (the +// 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. +// +// 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). 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 + +#if !defined(HPX_COMPUTE_DEVICE_CODE) +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if !defined(HPX_WINDOWS) +#include +#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 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 GPU and size, for reuse (never +// freed, see above) +std::map, std::vector>& released_memory() +{ + static std::map, std::vector> memory; + return memory; +} + +std::mutex& released_memory_mutex() +{ + static std::mutex mtx; + return mtx; +} +#else +// the stream of the allocations on 'gpu' (the GPU is current) +cudaStream_t allocation_stream(int const gpu) +{ + 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; +} +#endif + +// 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) + +// 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; + + // 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) + { + // 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()[{gpu, 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), [gpu, size](char* q) { + std::lock_guard l(released_memory_mutex()); + released_memory()[{gpu, size}].push_back(q); + }); +#else + 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), + [stream](char* q) { (void) cudaFreeAsync(q, stream); }); +#endif + } + } + + // device memory on 'gpu' holding 'host' + static device_buffer from_host( + std::vector const& host, int const gpu = device()) + { + device_buffer b(host.size(), gpu); + 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(gpu), 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; + + // 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 + 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; + 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); + 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) + +/////////////////////////////////////////////////////////////////////////////// +// 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 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, arrived) + + gpu_target target; +}; + +using on_gpu_type = hpx::components::component; +HPX_REGISTER_COMPONENT(on_gpu_type, on_gpu) +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 +// 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() +{ + 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; 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; + } + 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(); + } + 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(); + 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()); + } + + 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(); +} + +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 diff --git a/libs/full/device_conduit_ucx/docs/index.rst b/libs/full/device_conduit_ucx/docs/index.rst index 189c47772ab..f3cded5c205 100644 --- a/libs/full/device_conduit_ucx/docs/index.rst +++ b/libs/full/device_conduit_ucx/docs/index.rst @@ -57,5 +57,30 @@ endpoints at shutdown waits for the peers. Use ``none`` only where no locality leaves before the others (no localities connecting and disconnecting dynamically). +The conduit also moves host memory: with ``hpx.parcel.conduit_host_chunks=1`` +(per parcelport: ``hpx.parcel..conduit_host_chunks``) it moves the +zero-copy chunks of host memory of at least ``hpx.parcel.conduit_host_threshold`` +bytes (default 1 MiB) of arrays such as ``std::vector`` and +``serialize_buffer``, to localities whose endpoint for the parcelport says +they receive them that way. With the TCP parcelport on an RDMA network, large +arguments then move as fast as with the MPI parcelport (on V100 nodes with +ConnectX-3, 1.3 to 1.7 times faster than through TCP for 1 to 64 MiB). The +error handling ``peer`` costs nothing for host memory. Endpoints are created +when the first data goes to a locality, so localities connecting later are +reached the same way, and a locality that leaves has its endpoint closed. + +Two localities that both use the UCX conduit may still not reach each other +through UCX (for instance on different networks, or with transports +restricted by ``HPX_DEVICE_CONDUIT_UCX_TLS``). Host chunks therefore go to a +locality through the conduit only once its endpoint has been created and +flushed successfully, which the conduit starts when a message to the locality +first has a host chunk to move; until then, and for good if that fails (a +warning is logged), the parcelport moves them. Device data doesn't fall back this way: a +parcelport may not be able to move device memory. + +The conduit runs the completions of its transfers after UCX's progress has +returned, never inside UCX's callbacks: UCX calls them with its worker lock +held, and a completion may suspend its HPX thread. + See the :ref:`API reference ` of this module for more details. diff --git a/libs/full/device_conduit_ucx/include/hpx/device_conduit_ucx/ucx_conduit.hpp b/libs/full/device_conduit_ucx/include/hpx/device_conduit_ucx/ucx_conduit.hpp index e3d0980db3c..129c0c1d9b4 100644 --- a/libs/full/device_conduit_ucx/include/hpx/device_conduit_ucx/ucx_conduit.hpp +++ b/libs/full/device_conduit_ucx/include/hpx/device_conduit_ucx/ucx_conduit.hpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include @@ -60,6 +61,12 @@ namespace hpx::parcelset::device_conduits { return true; } + // UCX finds the memory type of each buffer itself + [[nodiscard]] static constexpr bool moves_host_memory_impl() 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, @@ -109,6 +116,36 @@ namespace hpx::parcelset::device_conduits { // progress void note_device(void const* p) noexcept; + public: + // A completion of a send or receive, run outside of UCX (see + // run_completions): UCX calls the callbacks of requests while it + // holds its worker lock, and a completion may suspend its HPX thread + // (it may send parcels, e.g. when the sent parcels are released), + // which would leave the lock taken. + void defer(hpx::move_only_function completion); + + // Host chunks go to 'locality_id' through the conduit only once + // its endpoint has been flushed successfully (UCX may not reach a + // locality that also uses the UCX conduit, e.g. on another fabric): + // until then, and for good if it fails, the parcelport moves them. + bool host_chunks_ready_impl(std::uint32_t locality_id) noexcept; + + // a message to 'locality_id' has a host chunk: starts the check + // (the first time) + void prepare_host_chunks_impl(std::uint32_t locality_id) noexcept; + + // the check of 'locality_id' has finished + void host_check_done( + std::uint32_t locality_id, bool reachable) noexcept; + + private: + // creates and flushes the endpoint to 'locality_id' (on an HPX + // thread) + void check_host_reach(std::uint32_t locality_id); + + // runs the deferred completions (no lock held) + bool run_completions(); + // sends unless the endpoint was closed since (its locality was // removed) void start_send(std::uint32_t locality_id, std::uint64_t generation, @@ -138,6 +175,22 @@ namespace hpx::parcelset::device_conduits { // one thread at a time makes progress hpx::spinlock progress_mtx_; + + // the deferred completions (a lock that never suspends: taken in + // UCX's callbacks) + std::mutex completions_mtx_; + std::vector> completions_; + + // the checks of the destinations of host chunks (see + // host_chunks_ready_impl) + enum class host_reach : std::uint8_t + { + checking, + reachable, + unreachable + }; + std::mutex host_checks_mtx_; + std::map host_checks_; }; } // namespace hpx::parcelset::device_conduits diff --git a/libs/full/device_conduit_ucx/src/ucx_conduit.cpp b/libs/full/device_conduit_ucx/src/ucx_conduit.cpp index 737d92c94ff..362fcb76956 100644 --- a/libs/full/device_conduit_ucx/src/ucx_conduit.cpp +++ b/libs/full/device_conduit_ucx/src/ucx_conduit.cpp @@ -10,6 +10,7 @@ #if defined(HPX_HAVE_NETWORKING) && defined(HPX_HAVE_DEVICE_CONDUIT_UCX) #include #include +#include #include #include #include @@ -109,11 +110,13 @@ namespace hpx::parcelset::device_conduits { struct send_state { hpx::move_only_function sent; + ucx_conduit* conduit = nullptr; }; struct recv_state { std::function done; + ucx_conduit* conduit = nullptr; }; void send_callback( @@ -123,13 +126,19 @@ namespace hpx::parcelset::device_conduits { // completed, the conduit may be destroyed auto* state = static_cast(user_data); auto sent = HPX_MOVE(state->sent); + ucx_conduit* conduit = state->conduit; delete state; ucp_request_free(request); - // a failed send is reported (its parcel has left already) - sent(status == UCS_OK ? - nullptr : - make_error(status, "ucp_tag_send_nbx", conduit_send)); + // a failed send is reported (its parcel has left already); run + // outside of UCX (see ucx_conduit::defer) + std::exception_ptr error = status == UCS_OK ? + nullptr : + make_error(status, "ucp_tag_send_nbx", conduit_send); + conduit->defer( + [sent = HPX_MOVE(sent), error = HPX_MOVE(error)]() mutable { + sent(HPX_MOVE(error)); + }); } void recv_callback(void* request, ucs_status_t const status, @@ -138,13 +147,19 @@ namespace hpx::parcelset::device_conduits { // done with UCX before the completion (see send_callback) auto* state = static_cast(user_data); auto done = HPX_MOVE(state->done); + ucx_conduit* conduit = state->conduit; delete state; ucp_request_free(request); - // a failed receive fails the parcel (it isn't run) - done(status == UCS_OK ? - nullptr : - make_error(status, "ucp_tag_recv_nbx", conduit_recv)); + // a failed receive fails the parcel (it isn't run); run outside + // of UCX (see ucx_conduit::defer) + std::exception_ptr error = status == UCS_OK ? + nullptr : + make_error(status, "ucp_tag_recv_nbx", conduit_recv); + conduit->defer( + [done = HPX_MOVE(done), error = HPX_MOVE(error)]() mutable { + done(HPX_MOVE(error)); + }); } // a peer failed (with UCP_ERR_HANDLING_MODE_PEER): the transfers to @@ -368,10 +383,179 @@ namespace hpx::parcelset::device_conduits { closing_.clear(); endpoints_.clear(); + // what closing the endpoints has completed + run_completions(); + ucp_worker_destroy(worker_); ucp_cleanup(context_); } + /////////////////////////////////////////////////////////////////////////// + namespace { + + // the flush checking that the conduit reaches a locality + struct host_check_state + { + ucx_conduit* conduit = nullptr; + std::uint32_t locality_id = 0; + }; + + void host_check_callback( + void* request, ucs_status_t const status, void* user_data) + { + auto* state = static_cast(user_data); + ucx_conduit* conduit = state->conduit; + std::uint32_t const locality_id = state->locality_id; + delete state; + ucp_request_free(request); + + conduit->defer([conduit, locality_id, status]() { + if (status != UCS_OK) + { + LPT_(warning).format( + "ucx_conduit: host chunks to locality {} go through " + "the parcelport: the conduit doesn't reach it ({})", + locality_id, ucs_status_string(status)); + } + conduit->host_check_done(locality_id, status == UCS_OK); + }); + } + } // namespace + + bool ucx_conduit::host_chunks_ready_impl( + std::uint32_t const locality_id) noexcept + { + std::lock_guard l(host_checks_mtx_); + auto const it = host_checks_.find(locality_id); + return it != host_checks_.end() && it->second == host_reach::reachable; + } + + void ucx_conduit::prepare_host_chunks_impl( + std::uint32_t const locality_id) noexcept + { + { + std::lock_guard l(host_checks_mtx_); + if (host_checks_.contains(locality_id)) + { + return; // checked or being checked + } + + // the endpoint is created by an action: not before the runtime + // runs + if (!hpx::is_running()) + { + return; + } + try + { + host_checks_.emplace(locality_id, host_reach::checking); + } + catch (...) + { + return; // asked again with the next host chunk + } + } + + // check it (the first time a message to it has a host chunk, so the + // locality runs): host chunks go through the parcelport meanwhile + try + { + hpx::post([this, locality_id] { check_host_reach(locality_id); }); + } + catch (...) + { + host_check_done(locality_id, false); + } + } + + void ucx_conduit::check_host_reach(std::uint32_t const locality_id) + { + ucp_ep* ep = nullptr; + std::uint64_t generation = 0; + try + { + endpoint_entry const entry = endpoint(locality_id); + generation = entry.generation; + ep = entry.ep.get(); + } + catch (...) + { + LPT_(warning).format( + "ucx_conduit: host chunks to locality {} go through the " + "parcelport: the conduit doesn't reach it ({})", + locality_id, hpx::get_error_what(std::current_exception())); + host_check_done(locality_id, false); + return; + } + + // a flush finishes once the endpoint is connected (or fails if the + // peer can't be reached) + auto* state = new host_check_state{this, locality_id}; + ucp_request_param_t param; + std::memset(¶m, 0, sizeof(param)); + param.op_attr_mask = + UCP_OP_ATTR_FIELD_CALLBACK | UCP_OP_ATTR_FIELD_USER_DATA; + param.cb.send = &host_check_callback; + param.user_data = state; + + // the endpoint is valid while it is in endpoints_ (see start_send) + bool removed = true; + ucs_status_ptr_t request = nullptr; + { + std::lock_guard l(endpoints_mtx_); + if (auto const it = endpoints_.find(locality_id); + it != endpoints_.end() && it->second.generation == generation) + { + removed = false; + request = ucp_ep_flush_nbx(ep, ¶m); + } + } + + if (removed || UCS_PTR_IS_ERR(request)) + { + delete state; + host_check_done(locality_id, false); + } + else if (request == nullptr) + { + // flushed right away, the callback isn't called + delete state; + host_check_done(locality_id, true); + } + } + + void ucx_conduit::host_check_done( + std::uint32_t const locality_id, bool const reachable) noexcept + { + std::lock_guard l(host_checks_mtx_); + if (auto const it = host_checks_.find(locality_id); + it != host_checks_.end() && it->second == host_reach::checking) + { + it->second = + reachable ? host_reach::reachable : host_reach::unreachable; + } + } + + void ucx_conduit::defer(hpx::move_only_function completion) + { + std::lock_guard l(completions_mtx_); + completions_.push_back(HPX_MOVE(completion)); + } + + bool ucx_conduit::run_completions() + { + std::vector> completions; + { + std::lock_guard l(completions_mtx_); + completions.swap(completions_); + } + for (auto& completion : completions) + { + completion(); + } + return !completions.empty(); + } + /////////////////////////////////////////////////////////////////////////// ucx_conduit::endpoint_entry ucx_conduit::endpoint( std::uint32_t const locality_id) @@ -484,6 +668,13 @@ namespace hpx::parcelset::device_conduits { // disconnected with hpx::force_disconnect doesn't need them, and may // be gone: they are cancelled (with peer error handling). bool const force = forced && peer_errors_; + + // a locality connecting later with the same id is checked again + { + std::lock_guard l(host_checks_mtx_); + host_checks_.erase(locality_id); + } + hpx::shared_future ep; { std::lock_guard l(endpoints_mtx_); @@ -544,7 +735,7 @@ namespace hpx::parcelset::device_conduits { { note_device(p); - auto* state = new send_state{HPX_MOVE(sent)}; + auto* state = new send_state{HPX_MOVE(sent), this}; ucp_request_param_t param; std::memset(¶m, 0, sizeof(param)); @@ -647,7 +838,7 @@ namespace hpx::parcelset::device_conduits { note_device(p); - auto* state = new recv_state{HPX_MOVE(done)}; + auto* state = new recv_state{HPX_MOVE(done), this}; ucp_request_param_t param; std::memset(¶m, 0, sizeof(param)); @@ -679,12 +870,18 @@ namespace hpx::parcelset::device_conduits { std::unique_lock l(progress_mtx_, std::try_to_lock); if (!l.owns_lock()) { - return false; + // the completions of others' progress can be run here + return run_completions(); } // progress registers the memory of rendezvous messages ensure_context(device_.load(std::memory_order_relaxed)); - bool const did_work = ucp_worker_progress(worker_) != 0; + bool did_work = ucp_worker_progress(worker_) != 0; + l.unlock(); + + // the completions progress has found, without a lock held (they may + // suspend this thread) + did_work = run_completions() || did_work; // release the endpoints of removed localities once closed (not // urgent: skip it if sends hold the lock) diff --git a/libs/full/device_conduit_ucx/tests/unit/CMakeLists.txt b/libs/full/device_conduit_ucx/tests/unit/CMakeLists.txt index aa4546a91f4..8ca6083155d 100644 --- a/libs/full/device_conduit_ucx/tests/unit/CMakeLists.txt +++ b/libs/full/device_conduit_ucx/tests/unit/CMakeLists.txt @@ -46,3 +46,21 @@ if(HPX_WITH_DEVICE_CONDUIT_UCX locality_removed_worker ) endif() + +# host chunks through the conduit, over every parcelport the test runs with +if(HPX_WITH_DEVICE_CONDUIT_UCX) + add_hpx_executable( + host_chunks_test INTERNAL_FLAGS + SOURCES host_chunks.cpp + EXCLUDE_FROM_ALL + HPX_PREFIX ${HPX_BUILD_PREFIX} + FOLDER "Tests/Unit/Modules/Full/DeviceConduitUCX" + ) + + add_hpx_unit_test( + "modules.device_conduit_ucx" host_chunks + LOCALITIES 2 + THREADS_PER_LOCALITY 4 + RUN_SERIAL + ) +endif() diff --git a/libs/full/device_conduit_ucx/tests/unit/host_chunks.cpp b/libs/full/device_conduit_ucx/tests/unit/host_chunks.cpp new file mode 100644 index 00000000000..9d9a52a6be2 --- /dev/null +++ b/libs/full/device_conduit_ucx/tests/unit/host_chunks.cpp @@ -0,0 +1,227 @@ +// 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) + +// Host chunks through the UCX device conduit: with +// hpx.parcel.conduit_host_chunks=1 the conduit also moves the zero-copy +// chunks of host memory of at least hpx.parcel.conduit_host_threshold bytes +// whose objects accept the data after their de-serialization (arrays: here +// std::vector and serialize_buffer), between localities whose endpoints say +// they receive them that way. Smaller chunks go through the parcelport. The +// test checks the data of arguments and results, many calls in flight in +// both directions, and the conduit's statistics on both sides. + +#include + +#if !defined(HPX_COMPUTE_DEVICE_CODE) +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +constexpr std::size_t threshold = 65536; + +/////////////////////////////////////////////////////////////////////////////// +std::vector pattern(std::size_t const count, int const first) +{ + std::vector v(count); + std::iota(v.begin(), v.end(), first); + return v; +} + +// checks its argument (the data has arrived when the action runs), returns +// data of the same size +std::vector echo(std::vector const& v, std::size_t count, int first) +{ + HPX_TEST(v == pattern(count, first)); + return pattern(count, first + 1); +} +HPX_PLAIN_ACTION(echo) + +using buffer_type = hpx::serialization::serialize_buffer; + +buffer_type echo_buffer(buffer_type const& b, std::size_t size, char first) +{ + HPX_TEST_EQ(b.size(), size); + bool ok = true; + for (std::size_t i = 0; i != b.size(); ++i) + { + ok = ok && b[i] == static_cast(first + i % 61); + } + HPX_TEST(ok); + + buffer_type result(size); + for (std::size_t i = 0; i != size; ++i) + { + result[i] = static_cast(first + 1 + i % 61); + } + return result; +} +HPX_PLAIN_ACTION(echo_buffer) + +// the conduit's statistics on this locality +std::pair conduit_chunks() +{ + auto const* conduit = hpx::parcelset::get_device_conduit(); + if (conduit == nullptr) + { + return {0, 0}; + } + auto const s = conduit->statistics(); + return {s.chunks_sent, s.chunks_received}; +} +HPX_PLAIN_ACTION(conduit_chunks) + +// host chunks go to 'locality_id' through the conduit once it has checked +// that it reaches it, which it starts when a message has one (they go +// through the parcelport until then) +bool wait_for_host_chunks(std::uint32_t const locality_id) +{ + auto* conduit = hpx::parcelset::get_device_conduit(); + hpx::id_type const id = hpx::naming::get_id_from_locality_id(locality_id); + std::size_t const count = threshold / sizeof(int); + auto const deadline = + std::chrono::steady_clock::now() + std::chrono::seconds(10); + while (!conduit->host_chunks_ready(locality_id)) + { + if (std::chrono::steady_clock::now() >= deadline) + { + return false; + } + HPX_TEST(echo_action()(id, pattern(count, 3), count, 3) == + pattern(count, 4)); + hpx::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + return true; +} +HPX_PLAIN_ACTION(wait_for_host_chunks) + +// many calls with large vectors to 'target' at once +void echo_many(hpx::id_type const& target, std::size_t const calls) +{ + std::vector>> results; + for (std::size_t i = 0; i != calls; ++i) + { + std::size_t const count = threshold / sizeof(int) + i * 1000; + results.push_back(hpx::async(target, + pattern(count, static_cast(i)), count, static_cast(i))); + } + for (std::size_t i = 0; i != calls; ++i) + { + std::size_t const count = threshold / sizeof(int) + i * 1000; + HPX_TEST(results[i].get() == pattern(count, static_cast(i) + 1)); + } +} +HPX_PLAIN_ACTION(echo_many) + +/////////////////////////////////////////////////////////////////////////////// +int hpx_main() +{ + auto const* conduit = hpx::parcelset::get_device_conduit(); + HPX_TEST(conduit != nullptr); + if (conduit == nullptr) + { + return hpx::finalize(); + } + HPX_TEST_EQ(conduit->name(), std::string("ucx")); + HPX_TEST(conduit->moves_host_memory()); + + std::vector const remotes = hpx::find_remote_localities(); + for (hpx::id_type const& id : remotes) + { + // both ways checked (the first host chunks go through the + // parcelport meanwhile) + HPX_TEST( + wait_for_host_chunks(hpx::naming::get_locality_id_from_id(id))); + HPX_TEST(wait_for_host_chunks_action()(id, hpx::get_locality_id())); + + // below the threshold: through the parcelport + auto const before = conduit_chunks(); + auto const remote_before = conduit_chunks_action()(id); + { + std::size_t const count = threshold / sizeof(int) / 4; + HPX_TEST(echo_action()(id, pattern(count, 7), count, 7) == + pattern(count, 8)); + } + HPX_TEST(conduit_chunks() == before); + HPX_TEST(conduit_chunks_action()(id) == remote_before); + + // at or above it: through the conduit, the argument and the result + for (std::size_t count : + {threshold / sizeof(int), (std::size_t(8) << 20) / sizeof(int) + 3}) + { + HPX_TEST(echo_action()(id, pattern(count, 1), count, 1) == + pattern(count, 2)); + } + { + std::size_t const size = std::size_t(1) << 20; + buffer_type b(size); + for (std::size_t i = 0; i != size; ++i) + { + b[i] = static_cast('a' + i % 61); + } + buffer_type const r = echo_buffer_action()(id, b, size, 'a'); + HPX_TEST_EQ(r.size(), size); + bool ok = true; + for (std::size_t i = 0; i != size; ++i) + { + ok = ok && r[i] == static_cast('b' + i % 61); + } + HPX_TEST(ok); + } + + // three arguments sent and three results received here, the other + // way round there + auto const after = conduit_chunks(); + auto const remote_after = conduit_chunks_action()(id); + HPX_TEST_EQ(after.first - before.first, std::uint64_t(3)); + HPX_TEST_EQ(after.second - before.second, std::uint64_t(3)); + HPX_TEST_EQ(remote_after.first - remote_before.first, std::uint64_t(3)); + HPX_TEST_EQ( + remote_after.second - remote_before.second, std::uint64_t(3)); + } + + // many calls in flight, all localities calling all others + std::vector> busy; + for (hpx::id_type const& from : hpx::find_all_localities()) + { + for (hpx::id_type const& to : hpx::find_all_localities()) + { + if (from != to) + { + busy.push_back(hpx::async(from, to, 32)); + } + } + } + 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=ucx", + "hpx.parcel.conduit_host_chunks=1", + "hpx.parcel.conduit_host_threshold=" + std::to_string(threshold)}; + HPX_TEST_EQ(hpx::init(argc, argv, params), 0); + return hpx::util::report_errors(); +} +#endif diff --git a/libs/full/device_conduit_ucx/tests/unit/locality_removed.cpp b/libs/full/device_conduit_ucx/tests/unit/locality_removed.cpp index 50bac6571bb..385f9d1c207 100644 --- a/libs/full/device_conduit_ucx/tests/unit/locality_removed.cpp +++ b/libs/full/device_conduit_ucx/tests/unit/locality_removed.cpp @@ -16,10 +16,11 @@ // The conduit is told (device_conduit::locality_removed) and closes its // endpoint to the locality. A failed device send to a removed locality must // not stop the application, and the calls with device data in flight must -// not report wrong data (HPX doesn't guarantee that they finish). Afterwards, -// device data still reaches the other localities, a locality connecting -// later is reached through a new endpoint, and the test shuts down in time -// (the conduit doesn't wait for the localities that went away). +// not report wrong data (HPX doesn't guarantee that they finish). Large host +// data (hpx.parcel.conduit_host_chunks) goes through the conduit too. +// Afterwards, device data still reaches the other localities, a locality +// connecting later is reached through a new endpoint, and the test shuts +// down in time (the conduit doesn't wait for the localities that went away). #include @@ -27,6 +28,7 @@ #include #include #include +#include #include #include #include @@ -76,9 +78,13 @@ void wait_for_worker_startup(hpx::id_type const& id) "worker did not finish runtime startup"); } -// launches a worker and returns it with the locality it registered as -std::pair launch_worker( - fs::path const& exe, std::uint64_t const spawn_id) +// launches a worker (with 'extra_args' after the common ones, and the +// environment variables 'env') and returns it with the locality it +// registered as +std::pair launch_worker(fs::path const& exe, + std::uint64_t const spawn_id, + std::vector const& extra_args = {}, + std::vector const& env = {}) { std::unordered_set before; for (hpx::id_type const& id : hpx::find_all_localities()) @@ -86,8 +92,10 @@ std::pair launch_worker( before.insert(id); } + std::vector args = worker_args; + args.insert(args.end(), extra_args.begin(), extra_args.end()); process::child worker = process::launch_connecting_locality( - fs::to_string(exe), worker_args, {}, spawn_id); + fs::to_string(exe), args, env, spawn_id); worker.wait(); HPX_TEST(worker); @@ -108,20 +116,45 @@ std::pair launch_worker( return std::make_pair(HPX_MOVE(worker), new_locality); } -// device data reaches 'id' intact, through the conduit +// host chunks go to 'id' through the conduit once it has checked that it +// reaches it, which it starts when a message has one (they go through the +// parcelport until then) +bool wait_for_host_chunks(hpx::id_type const& id) +{ + hpx::parcelset::device_conduit* conduit = + hpx::parcelset::get_device_conduit(); + std::uint32_t const locality_id = hpx::naming::get_locality_id_from_id(id); + auto const deadline = + std::chrono::steady_clock::now() + std::chrono::seconds(10); + while (!conduit->host_chunks_ready(locality_id)) + { + if (std::chrono::steady_clock::now() >= deadline) + { + return false; + } + hpx::async(put_host_data_action(), id, pattern(small_size, 'w')).get(); + hpx::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + return true; +} + +// device data and large host data reach 'id' intact, through the conduit void test_device_data(hpx::id_type const& id) { hpx::parcelset::device_conduit const* conduit = hpx::parcelset::get_device_conduit(); + HPX_TEST(wait_for_host_chunks(id)); std::uint64_t const before = conduit->statistics().chunks_sent; constexpr std::size_t count = 4; std::vector> results; - for (std::size_t i = 0; i != count; ++i) + for (std::size_t i = 0; i != count / 2; ++i) { char const first = static_cast('a' + i); results.push_back(hpx::async(check_device_data_action(), id, device_like{pattern(small_size, first)}, first)); + results.push_back(hpx::async( + check_host_data_action(), id, pattern(small_size, first), first)); } for (hpx::future& f : results) { @@ -139,14 +172,43 @@ void test_device_data(hpx::id_type const& id) HPX_TEST_LTE(before + count, conduit->statistics().chunks_sent); } -// device data to 'id' that is still being moved when it goes away +// large host data reaches 'id' intact through the parcelport: the conduit +// doesn't reach it (also once it has had the time to check) +void test_host_data_without_conduit(hpx::id_type const& id) +{ + hpx::parcelset::device_conduit const* conduit = + hpx::parcelset::get_device_conduit(); + std::uint64_t const before = conduit->statistics().chunks_sent; + for (int round = 0; round != 2; ++round) + { + std::vector> results; + for (std::size_t i = 0; i != 4; ++i) + { + char const first = static_cast('a' + i); + results.push_back(hpx::async(check_host_data_action(), id, + pattern(small_size, first), first)); + } + for (hpx::future& f : results) + { + HPX_TEST(f.get()); + } + + // the conduit's check (if it started one) has finished by now + hpx::this_thread::sleep_for(std::chrono::seconds(2)); + } + HPX_TEST_EQ(conduit->statistics().chunks_sent, before); +} + +// device and host data to 'id' that is still being moved when it goes away std::vector> start_transfers(hpx::id_type const& id) { std::vector> results; - for (std::size_t i = 0; i != transfers_in_flight; ++i) + for (std::size_t i = 0; i != transfers_in_flight / 2; ++i) { results.push_back(hpx::async(check_device_data_action(), id, device_like{pattern(large_size, 'x')}, 'x')); + results.push_back(hpx::async( + check_host_data_action(), id, pattern(large_size, 'x'), 'x')); } return results; } @@ -216,6 +278,8 @@ int hpx_main(hpx::program_options::variables_map& vm) "--hpx:ini=hpx.parcel.conduit.ucx.error_handling=" + hpx::get_config_entry( "hpx.parcel.conduit.ucx.error_handling", "peer"), + "--hpx:ini=hpx.parcel.conduit_host_chunks=1", + "--hpx:ini=hpx.parcel.conduit_host_threshold=65536", "--hpx:ini=hpx.parcel.bootstrap=tcp", "--hpx:ini=hpx.parcel.tcp.priority=1000"}; @@ -259,10 +323,11 @@ int hpx_main(hpx::program_options::variables_map& vm) // the parcels aren't waited for: the process is gone, only the // conduit's sends are left - for (std::size_t i = 0; i != transfers_in_flight; ++i) + for (std::size_t i = 0; i != transfers_in_flight / 2; ++i) { hpx::post( id, device_like{pattern(large_size, 'k')}); + hpx::post(id, pattern(large_size, 'k')); } worker.terminate(hpx::launch::sync); @@ -289,6 +354,32 @@ int hpx_main(hpx::program_options::variables_map& vm) HPX_TEST_EQ(worker.wait_for_exit(hpx::launch::sync), 0); } + std::cout << "Localities the conduit doesn't move host chunks to.\n"; + { + // one without a conduit (its endpoints say so) + auto [plain_worker, plain] = + launch_worker(exe, 6, {"--hpx:ini=hpx.parcel.device_conduit=none"}); + test_host_data_without_conduit(plain); + + // one with the UCX conduit that no other process reaches (UCX may + // only use its loopback transport there) + auto [isolated_worker, isolated] = + launch_worker(exe, 7, {}, {"HPX_DEVICE_CONDUIT_UCX_TLS=self"}); + test_host_data_without_conduit(isolated); + + for (auto const& id : {plain, isolated}) + { + hpx::error_code ec(hpx::throwmode::lightweight); + HPX_TEST_EQ(hpx::force_disconnect(id, ec), 0); + HPX_TEST(!ec); + } + HPX_TEST_EQ(plain_worker.wait_for_exit(hpx::launch::sync), 0); + HPX_TEST_EQ(isolated_worker.wait_for_exit(hpx::launch::sync), 0); + + // the others are reached as before + test_device_data(control); + } + { hpx::error_code ec(hpx::throwmode::lightweight); HPX_TEST_EQ(hpx::force_disconnect(control, ec), 0); @@ -315,7 +406,8 @@ int main(int argc, char* argv[]) hpx::init_params params; params.desc_cmdline = desc_commandline; params.cfg = {"hpx.expect_connecting_localities!=1", - "hpx.parcel.device_conduit!=ucx"}; + "hpx.parcel.device_conduit!=ucx", "hpx.parcel.conduit_host_chunks!=1", + "hpx.parcel.conduit_host_threshold!=65536"}; HPX_TEST_EQ(hpx::init(argc, argv, params), 0); diff --git a/libs/full/device_conduit_ucx/tests/unit/locality_removed.hpp b/libs/full/device_conduit_ucx/tests/unit/locality_removed.hpp index a57519b5e46..fa9a505f1bd 100644 --- a/libs/full/device_conduit_ucx/tests/unit/locality_removed.hpp +++ b/libs/full/device_conduit_ucx/tests/unit/locality_removed.hpp @@ -77,6 +77,16 @@ HPX_PLAIN_ACTION(check_device_data, check_device_data_action) inline void put_device_data(device_like const&) {} HPX_PLAIN_ACTION(put_device_data, put_device_data_action) +// host data, moved by the conduit as well (hpx.parcel.conduit_host_chunks) +inline bool check_host_data(std::vector const& d, char const first) +{ + return d == pattern(d.size(), first); +} +HPX_PLAIN_ACTION(check_host_data, check_host_data_action) + +inline void put_host_data(std::vector const&) {} +HPX_PLAIN_ACTION(put_host_data, put_host_data_action) + inline bool worker_is_running() { return hpx::is_running(); diff --git a/libs/full/parcelset/include/hpx/parcelset/device_conduit.hpp b/libs/full/parcelset/include/hpx/parcelset/device_conduit.hpp index 94dab411354..afb3e611094 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 @@ -60,6 +62,15 @@ namespace hpx::parcelset { /// /// and optionally (this base implements them doing nothing) /// + /// - static constexpr bool moves_host_memory_impl() + /// whether the conduit also moves host memory (false) + /// - bool host_chunks_ready_impl(std::uint32_t locality_id) + /// whether host chunks may go to 'locality_id' through the conduit + /// now, e.g. once it has checked that it reaches it (true) + /// - void prepare_host_chunks_impl(std::uint32_t locality_id) + /// a message to 'locality_id' has a host chunk the conduit would + /// move once ready (does nothing) + /// /// - bool background_work_impl() /// makes progress, called with the parcelports' background work /// - void locality_removed_impl( @@ -69,8 +80,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 @@ -88,6 +100,17 @@ namespace hpx::parcelset { return derived().can_reach_impl(locality_id); } + [[nodiscard]] bool moves_host_memory() const override + { + return Derived::moves_host_memory_impl(); + } + + [[nodiscard]] bool host_chunks_ready( + std::uint32_t const locality_id) override + { + return derived().host_chunks_ready_impl(locality_id); + } + [[nodiscard]] std::shared_ptr< serialization::detail::device_chunk_transport> sender(std::uint32_t const locality_id, @@ -163,6 +186,18 @@ namespace hpx::parcelset { // its own) static void config_defaults(std::vector&) noexcept {} + [[nodiscard]] static constexpr bool moves_host_memory_impl() noexcept + { + return false; + } + + [[nodiscard]] bool host_chunks_ready_impl(std::uint32_t) noexcept + { + return true; + } + + void prepare_host_chunks_impl(std::uint32_t) noexcept {} + bool background_work_impl() noexcept { return false; @@ -202,7 +237,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)}; @@ -277,6 +313,11 @@ namespace hpx::parcelset { return d; } + void host_chunk_waiting() override + { + conduit_.prepare_host_chunks_impl(locality_id_); + } + void recv(serialization::detail::device_chunk_descriptor const&, void*, std::size_t, std::function) override @@ -410,12 +451,31 @@ namespace hpx::parcelset { std::vector& get_device_conduit_factories(); - /// The archive flags to add to the parcelport's flags for a message - /// to 'locality_id': enable_device_transport and enable_device_chunks - /// if the conduit reaches the destination, none otherwise. The - /// preprocessing pass of a parcel and its real serialization must use - /// the same flags. + /// The archive flags to add to the flags of the parcelport 'pp' for + /// a message to 'locality_id': enable_device_transport and + /// enable_device_chunks if the conduit reaches the destination and + /// it uses the same conduit, also enable_host_transport if the + /// conduit moves host memory, 'pp' lets it and the destination + /// receives host chunks that way, none otherwise. What the + /// destination does comes from its endpoint for 'pp' (see + /// locality_capabilities), as recorded by + /// record_destination_capabilities. The preprocessing pass of a + /// parcel and its real serialization must use the same flags, except + /// enable_host_transport, which may become set in between (when the + /// conduit has found that it reaches the destination): that changes + /// only the size the preprocessing pass estimates. HPX_CXX_EXPORT HPX_EXPORT std::uint32_t device_conduit_flags( + parcelport const& pp, std::uint32_t locality_id) noexcept; + + /// Records what the endpoints of 'locality_id' (as AGAS resolved + /// them) can do, for device_conduit_flags; once per locality. The + /// locality objects the parcelports keep for a destination may have + /// been created before (e.g. from the configuration), without it. + HPX_CXX_EXPORT HPX_EXPORT void record_destination_capabilities( + std::uint32_t locality_id, endpoints_type const& endpoints); + + /// Forgets what was recorded for 'locality_id' (it was removed). + HPX_CXX_EXPORT HPX_EXPORT void forget_destination_capabilities( std::uint32_t locality_id) noexcept; /// Attaches the sending transport for a message to 'locality_id' to diff --git a/libs/full/parcelset/include/hpx/parcelset/encode_parcels.hpp b/libs/full/parcelset/include/hpx/parcelset/encode_parcels.hpp index 8be9477e8ae..908f4a6b8be 100644 --- a/libs/full/parcelset/include/hpx/parcelset/encode_parcels.hpp +++ b/libs/full/parcelset/include/hpx/parcelset/encode_parcels.hpp @@ -202,11 +202,14 @@ namespace hpx::parcelset { buffer.chunks_.reserve(num_chunks); // a device conduit moves the device memory of the parcels if - // it reaches their destination (the same for all of them) + // it reaches their destination (the same for all of them), + // and their large host chunks if the destination receives + // them that way std::uint32_t const destination = ps[0].destination_locality_id(); archive_flags = archive_flags | - static_cast(detail::device_conduit_flags(destination)); + static_cast( + detail::device_conduit_flags(pp, destination)); // mark start of serialization #if defined(HPX_HAVE_PARCELPORT_COUNTERS) diff --git a/libs/full/parcelset/include/hpx/parcelset/parcelport_impl.hpp b/libs/full/parcelset/include/hpx/parcelset/parcelport_impl.hpp index 861e96b05c0..887819bf0f8 100644 --- a/libs/full/parcelset/include/hpx/parcelset/parcelport_impl.hpp +++ b/libs/full/parcelset/include/hpx/parcelset/parcelport_impl.hpp @@ -354,7 +354,8 @@ namespace hpx::parcelset { // of the 'this' pointer. // the same flags as for the real serialization (encode_parcels) std::uint32_t const flags = archive_flags_ | - detail::device_conduit_flags(p.destination_locality_id()); + detail::device_conduit_flags( + *this, p.destination_locality_id()); detail::parcel_await_apply( HPX_MOVE(p), HPX_MOVE(f), flags, [this, dest](parcel&& p, write_handler_type&& f) { @@ -418,7 +419,7 @@ namespace hpx::parcelset { // the same flags as for the real serialization (encode_parcels) std::uint32_t const flags = archive_flags_ | detail::device_conduit_flags( - parcels[0].destination_locality_id()); + *this, parcels[0].destination_locality_id()); detail::parcels_await_apply( HPX_MOVE(parcels), HPX_MOVE(handlers), flags, [this, dest](std::vector&& parcels, diff --git a/libs/full/parcelset/src/device_conduit.cpp b/libs/full/parcelset/src/device_conduit.cpp index 00c73af9bbd..4f68fc14fb0 100644 --- a/libs/full/parcelset/src/device_conduit.cpp +++ b/libs/full/parcelset/src/device_conduit.cpp @@ -18,8 +18,12 @@ #include #include +#include #include +#include #include +#include +#include #include #include #include @@ -87,6 +91,15 @@ namespace hpx::parcelset { HPX_ASSERT(!conduit); conduit = factory->create(cfg); current_conduit.store(conduit.get(), std::memory_order_release); + + // the smallest host chunk the conduit moves (where enabled) + if (conduit->moves_host_memory()) + { + serialization::detail::set_host_transport_threshold( + hpx::util::get_entry_as(cfg, + "hpx.parcel.conduit_host_threshold", + std::size_t(1) << 20)); + } } void reset_device_conduit() noexcept @@ -111,17 +124,105 @@ namespace hpx::parcelset { conduit.reset(); } - std::uint32_t device_conduit_flags( + namespace { + + // what the endpoints of the destinations can do, by locality and + // parcelport (see record_destination_capabilities) + struct destination_capabilities + { + std::shared_mutex mtx; + std::map, + locality_capabilities> + entries; + }; + + destination_capabilities& destinations() + { + static destination_capabilities d; + return d; + } + } // namespace + + void record_destination_capabilities( + std::uint32_t const locality_id, endpoints_type const& endpoints) + { + if (get_device_conduit() == nullptr || endpoints.empty()) + { + return; + } + + auto& d = destinations(); + { + std::shared_lock l(d.mtx); + if (d.entries.contains({locality_id, endpoints.begin()->first})) + { + return; + } + } + + std::unique_lock l(d.mtx); + for (auto const& [type, endpoint] : endpoints) + { + d.entries.insert_or_assign( + {locality_id, type}, endpoint.capabilities()); + } + } + + void forget_destination_capabilities( std::uint32_t const locality_id) noexcept { - device_conduit const* c = get_device_conduit(); + auto& d = destinations(); + std::unique_lock l(d.mtx); + std::erase_if(d.entries, [&](auto const& entry) { + return entry.first.first == locality_id; + }); + } + + std::uint32_t device_conduit_flags( + parcelport const& pp, std::uint32_t const locality_id) noexcept + { + device_conduit* c = get_device_conduit(); if (c == nullptr || !c->can_reach(locality_id)) { return 0; } - return static_cast( - serialization::archive_flags::enable_device_transport | - serialization::archive_flags::enable_device_chunks); + + // the destination uses the same conduit (its endpoint names it); + // otherwise, or if it isn't known (yet), the parcelport moves the + // data + bool host_chunks = false; + { + auto& d = destinations(); + std::shared_lock l(d.mtx); + auto const it = d.entries.find({locality_id, pp.type()}); + if (it == d.entries.end() || it->second.conduit != c->name()) + { + return 0; + } + host_chunks = + it->second.has(locality_capabilities::conduit_host_chunks); + } + + auto flags = serialization::archive_flags::enable_device_transport | + serialization::archive_flags::enable_device_chunks; + + // and large host chunks, if this parcelport lets the conduit + // move them, the destination receives them that way, and the + // conduit is ready to move them there; if it isn't (it may check + // first that it reaches the destination), it is told when a + // message has such a chunk, which goes with the message + // meanwhile + if (host_chunks && c->moves_host_memory() && + pp.conduit_host_chunks()) + { + flags = flags | + (c->host_chunks_ready(locality_id) ? + serialization::archive_flags:: + enable_host_transport : + serialization::archive_flags:: + host_transport_pending); + } + return static_cast(flags); } void attach_device_conduit_sender( 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 diff --git a/libs/full/parcelset/src/parcelhandler.cpp b/libs/full/parcelset/src/parcelhandler.cpp index 1bfa7168dce..bdd3a2035cb 100644 --- a/libs/full/parcelset/src/parcelhandler.cpp +++ b/libs/full/parcelset/src/parcelhandler.cpp @@ -71,6 +71,30 @@ namespace hpx::parcelset { namespace { + // the endpoint of 'pp' with what its parcelport can do (published + // with it, see locality_capabilities) + locality endpoint_of(parcelport const& pp) + { + locality l = pp.here(); + + locality_capabilities caps; + if (pp.allow_zero_copy_receive_optimizations()) + { + caps.flags |= locality_capabilities::zero_copy_receive; + } + if (device_conduit const* conduit = get_device_conduit(); + conduit != nullptr) + { + caps.conduit = conduit->name(); + if (conduit->moves_host_memory() && pp.conduit_host_chunks()) + { + caps.flags |= locality_capabilities::conduit_host_chunks; + } + } + l.set_capabilities(HPX_MOVE(caps)); + return l; + } + /////////////////////////////////////////////////////////////////////////// // these are the errors a send reports if the destination went away bool is_peer_gone_error(std::error_code const& ec) @@ -247,6 +271,9 @@ namespace hpx::parcelset { // the conduit moving device memory below the parcelports detail::init_device_conduit(cfg); + + // the endpoints name the conduit and what it receives + update_endpoints(); } } @@ -510,7 +537,7 @@ namespace hpx::parcelset { // add the endpoint of the new parcelport HPX_ASSERT(pp->type() == pp->here().type()); if (priority > 0) - endpoints_[pp->type()] = pp->here(); + endpoints_[pp->type()] = endpoint_of(*pp); } void parcelhandler::update_endpoints() @@ -520,7 +547,7 @@ namespace hpx::parcelset { if (pp.first > 0 && pp.second) { HPX_ASSERT(pp.second->type() == pp.second->here().type()); - endpoints_[pp.second->type()] = pp.second->here(); + endpoints_[pp.second->type()] = endpoint_of(*pp.second); } } } @@ -588,6 +615,8 @@ namespace hpx::parcelset { { conduit->locality_removed( naming::get_locality_id_from_gid(gid), forced); + detail::forget_destination_capabilities( + naming::get_locality_id_from_gid(gid)); } agas::remove_resolved_locality(gid); @@ -727,6 +756,10 @@ namespace hpx::parcelset { { endpoints_type const& dest_endpoints = agas::resolve_locality(dest_gid); + // what the destination's endpoints can do, for the device conduit + detail::record_destination_capabilities( + naming::get_locality_id_from_gid(dest_gid), dest_endpoints); + for (auto& [idx, pp] : pports_) { if (idx > 0) @@ -1739,6 +1772,13 @@ namespace hpx::parcelset { // hpx::parcelset::device_conduit ini_defs.emplace_back( "device_conduit = ${HPX_PARCEL_DEVICE_CONDUIT:none}"); + // also host chunks of at least 'conduit_host_threshold' bytes go + // through a device conduit that moves host memory (per parcelport, + // see hpx::parcelset::locality_capabilities) + ini_defs.emplace_back( + "conduit_host_chunks = ${HPX_PARCEL_CONDUIT_HOST_CHUNKS:0}"); + ini_defs.emplace_back("conduit_host_threshold = " + "${HPX_PARCEL_CONDUIT_HOST_THRESHOLD:1048576}"); ini_defs.emplace_back( "zero_copy_optimization = ${HPX_PARCEL_ZERO_COPY_OPTIMIZATION:" "$[hpx.parcel.array_optimization]}"); diff --git a/libs/full/parcelset_base/include/hpx/parcelset_base/device_conduit.hpp b/libs/full/parcelset_base/include/hpx/parcelset_base/device_conduit.hpp index fb6b7a02507..4373f445342 100644 --- a/libs/full/parcelset_base/include/hpx/parcelset_base/device_conduit.hpp +++ b/libs/full/parcelset_base/include/hpx/parcelset_base/device_conduit.hpp @@ -57,6 +57,23 @@ namespace hpx::parcelset { [[nodiscard]] virtual bool can_reach( std::uint32_t locality_id) const = 0; + /// Whether the conduit also moves host memory (the parcel layer + /// then lets it move large host chunks, where the parcelports are + /// configured to, see locality_capabilities::conduit_host_chunks). + [[nodiscard]] virtual bool moves_host_memory() const = 0; + + /// Whether the conduit may move host chunks to 'locality_id' now + /// (moves_host_memory is true): a conduit may first check that it + /// can reach the destination (it starts the check when a message + /// to it has a host chunk, see + /// serialization::detail::device_chunk_transport:: + /// host_chunk_waiting), host chunks go through the parcelport until + /// then, and for good if it can't. Called for every message to a + /// destination that receives host chunks through the conduit, from + /// any thread. + [[nodiscard]] virtual bool host_chunks_ready( + std::uint32_t locality_id) = 0; + /// The transport for one message to 'locality_id' (can_reach is /// true). It keeps 'keep_alive' (the objects the message refers to, /// e.g. its parcels) until it has sent all data handed to it, which diff --git a/libs/full/parcelset_base/include/hpx/parcelset_base/locality.hpp b/libs/full/parcelset_base/include/hpx/parcelset_base/locality.hpp index 7c0b420ce99..a7c7d86451a 100644 --- a/libs/full/parcelset_base/include/hpx/parcelset_base/locality.hpp +++ b/libs/full/parcelset_base/include/hpx/parcelset_base/locality.hpp @@ -17,6 +17,7 @@ #include +#include #include #include #include @@ -28,6 +29,38 @@ /////////////////////////////////////////////////////////////////////////////// namespace hpx::parcelset { + /// What the parcelport behind an endpoint can do, besides being reached. + /// The parcel handler sets it for the endpoints of its locality; it + /// travels with them to the other localities (registration, AGAS), also + /// to localities connecting later, so a sender knows it for every + /// destination. + HPX_CXX_EXPORT struct locality_capabilities + { + /// The parcelport receives the zero-copy chunks of a parcel after + /// decoding it, into the memory of the de-serialized objects. + static constexpr std::uint32_t zero_copy_receive = 0x1; + + /// The locality receives host chunks through its device conduit + /// ('conduit') when they come through this parcelport. + static constexpr std::uint32_t conduit_host_chunks = 0x2; + + std::uint32_t flags = 0; + + /// The name of the locality's device conduit, empty if it has none. + std::string conduit; + + [[nodiscard]] bool has(std::uint32_t const f) const noexcept + { + return (flags & f) == f; + } + + template + void serialize(Archive& ar, unsigned) + { + ar & flags & conduit; + } + }; + ////////////////////////////////////////////////////////////////////////// HPX_CXX_EXPORT class locality { @@ -107,6 +140,18 @@ namespace hpx::parcelset { return impl_->get(); } + /// What the parcelport behind this endpoint can do (not part of the + /// endpoint's identity: comparisons ignore it). + [[nodiscard]] locality_capabilities const& capabilities() const noexcept + { + return capabilities_; + } + + void set_capabilities(locality_capabilities caps) + { + capabilities_ = HPX_MOVE(caps); + } + private: friend HPX_EXPORT bool operator==( locality const& lhs, locality const& rhs); @@ -131,6 +176,7 @@ namespace hpx::parcelset { HPX_SERIALIZATION_SPLIT_MEMBER() std::unique_ptr impl_; + locality_capabilities capabilities_; template class impl : public impl_base diff --git a/libs/full/parcelset_base/include/hpx/parcelset_base/parcelport.hpp b/libs/full/parcelset_base/include/hpx/parcelset_base/parcelport.hpp index 512cf251a70..255e868fb68 100644 --- a/libs/full/parcelset_base/include/hpx/parcelset_base/parcelport.hpp +++ b/libs/full/parcelset_base/include/hpx/parcelset_base/parcelport.hpp @@ -348,6 +348,13 @@ namespace hpx::parcelset { /// receiving end bool allow_zero_copy_receive_optimizations() const noexcept; + /// Return whether host chunks of at least + /// hpx.parcel.conduit_host_threshold bytes may go through the device + /// conduit (to destinations whose endpoint for this parcelport + /// receives them that way, see + /// locality_capabilities::conduit_host_chunks) + bool conduit_host_chunks() const noexcept; + bool async_serialization() const noexcept; // callback while bootstrap the parcel layer @@ -399,6 +406,7 @@ namespace hpx::parcelset { bool allow_array_optimizations_; bool allow_zero_copy_optimizations_; bool allow_zero_copy_receive_optimizations_; + bool conduit_host_chunks_ = false; /// async serialization of parcels bool async_serialization_; diff --git a/libs/full/parcelset_base/src/locality.cpp b/libs/full/parcelset_base/src/locality.cpp index cdc94c15d73..2f7f3517a16 100644 --- a/libs/full/parcelset_base/src/locality.cpp +++ b/libs/full/parcelset_base/src/locality.cpp @@ -23,11 +23,13 @@ namespace hpx::parcelset { locality::locality(locality const& other) : impl_(other.impl_ ? other.impl_->clone() : nullptr) + , capabilities_(other.capabilities_) { } locality::locality(locality&& other) noexcept : impl_(other.impl_ ? other.impl_->move() : nullptr) + , capabilities_(HPX_MOVE(other.capabilities_)) { } @@ -43,6 +45,7 @@ namespace hpx::parcelset { { impl_.reset(); } + capabilities_ = other.capabilities_; } return *this; } @@ -59,6 +62,7 @@ namespace hpx::parcelset { { impl_.reset(); } + capabilities_ = HPX_MOVE(other.capabilities_); } return *this; } @@ -117,6 +121,7 @@ namespace hpx::parcelset { } impl_->save(ar); + ar << capabilities_; #else HPX_THROW_EXCEPTION(hpx::error::invalid_status, "locality::save", "this shouldn't be called if networking is disabled"); @@ -137,6 +142,7 @@ namespace hpx::parcelset { impl_ = HPX_MOVE(create_locality(t).impl_); impl_->load(ar); HPX_ASSERT(impl_->valid()); + ar >> capabilities_; #else HPX_THROW_EXCEPTION(hpx::error::invalid_status, "locality::load", "this shouldn't be called if networking is disabled"); diff --git a/libs/full/parcelset_base/src/parcelport.cpp b/libs/full/parcelset_base/src/parcelport.cpp index 94c3c9688bc..bef4b1ff345 100644 --- a/libs/full/parcelset_base/src/parcelport.cpp +++ b/libs/full/parcelset_base/src/parcelport.cpp @@ -84,6 +84,11 @@ namespace hpx::parcelset { { async_serialization_ = true; } + + // host chunks through the device conduit need the chunks + conduit_host_chunks_ = allow_zero_copy_optimizations_ && + hpx::util::get_entry_as( + ini, key + ".conduit_host_chunks", 0) != 0; } int parcelport::priority() const noexcept @@ -419,6 +424,11 @@ namespace hpx::parcelset { return allow_zero_copy_receive_optimizations_; } + bool parcelport::conduit_host_chunks() const noexcept + { + return conduit_host_chunks_; + } + bool parcelport::async_serialization() const noexcept { return async_serialization_; diff --git a/libs/full/plugin_factories/include/hpx/plugin_factories/parcelport_factory.hpp b/libs/full/plugin_factories/include/hpx/plugin_factories/parcelport_factory.hpp index 909053830a9..97f892e9d33 100644 --- a/libs/full/plugin_factories/include/hpx/plugin_factories/parcelport_factory.hpp +++ b/libs/full/plugin_factories/include/hpx/plugin_factories/parcelport_factory.hpp @@ -123,6 +123,11 @@ namespace hpx::plugins { "zero_copy_receive_optimization = ${HPX_PARCEL_" + name_uc + "_ZERO_COPY_RECEIVE_OPTIMIZATION:" "$[hpx.parcel.zero_copy_receive_optimization]}"); + // host chunks through the device conduit (see + // parcelset::locality_capabilities::conduit_host_chunks) + fillini.emplace_back("conduit_host_chunks = ${HPX_PARCEL_" + + name_uc + + "_CONDUIT_HOST_CHUNKS:$[hpx.parcel.conduit_host_chunks]}"); fillini.emplace_back( "zero_copy_serialization_threshold = ${HPX_PARCEL_" + name_uc + "_ZERO_COPY_SERIALIZATION_THRESHOLD:"