From ee3e9dc17b863898a47b145603f677a055699850 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Wed, 16 Sep 2026 23:04:27 +0530 Subject: [PATCH 01/37] Add segmented hpx::sort for partitioned_vector Signed-off-by: the-ivii --- .../include/hpx/include/parallel_sort.hpp | 1 + libs/full/segmented_algorithms/CMakeLists.txt | 1 + .../parallel/segmented_algorithms/sort.hpp | 353 ++++++++++++++++++ .../tests/unit/CMakeLists.txt | 1 + .../tests/unit/partitioned_vector_sort.cpp | 178 +++++++++ 5 files changed, 534 insertions(+) create mode 100644 libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp create mode 100644 libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp diff --git a/libs/full/include/include/hpx/include/parallel_sort.hpp b/libs/full/include/include/hpx/include/parallel_sort.hpp index 2c4e1662c0e6..ac44bc207f62 100644 --- a/libs/full/include/include/hpx/include/parallel_sort.hpp +++ b/libs/full/include/include/hpx/include/parallel_sort.hpp @@ -8,3 +8,4 @@ #include #include +#include diff --git a/libs/full/segmented_algorithms/CMakeLists.txt b/libs/full/segmented_algorithms/CMakeLists.txt index 850175e944a5..24b3eb2bf4a9 100644 --- a/libs/full/segmented_algorithms/CMakeLists.txt +++ b/libs/full/segmented_algorithms/CMakeLists.txt @@ -37,6 +37,7 @@ set(segmented_algorithms_headers hpx/parallel/segmented_algorithms/reduce.hpp hpx/parallel/segmented_algorithms/replace.hpp hpx/parallel/segmented_algorithms/replace_copy.hpp + hpx/parallel/segmented_algorithms/sort.hpp hpx/parallel/segmented_algorithms/traits/zip_iterator.hpp hpx/parallel/segmented_algorithms/transform_exclusive_scan.hpp hpx/parallel/segmented_algorithms/transform.hpp diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp new file mode 100644 index 000000000000..a50064ca02b4 --- /dev/null +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp @@ -0,0 +1,353 @@ +// Copyright (c) 2026 the-ivii +// +// 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 +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace hpx::parallel::detail { + + /// \cond NOINTERNAL + + // sequential() is templated on the iterator actually passed after + // segmented_local_iterator_traits unwraps to a raw iterator. The class + // result type stays the local (serializable) iterator so dispatch can + // return it. + template + struct segmented_local_sort : algorithm, Iter> + { + constexpr segmented_local_sort() noexcept + : algorithm("segmented_local_sort") + { + } + + template + static constexpr InIter sequential(ExPolicy, InIter first, Sent last, + Comp&& comp, Proj&& proj) + { + auto last_iter = advance_to_sentinel(first, last); + auto const n = last_iter - first; + if (n > 1) + { + using value_type = + typename std::iterator_traits::value_type; + value_type* const raw = std::addressof(*first); + std::sort(raw, raw + n, + util::compare_projected(comp, proj)); + } + return last_iter; + } + + template + static InIter parallel(ExPolicy&&, InIter first, Sent last, Comp&& comp, + Proj&& proj) + { + return sequential(hpx::execution::seq, first, last, + HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); + } + }; + + template + struct segmented_sort_run + { + hpx::id_type id; + LocalIter first; + LocalIter last; + }; + + template + auto segmented_sort_runs(SegIter first, SegIter last) + { + using traits = hpx::traits::segmented_iterator_traits; + using segment_iterator = typename traits::segment_iterator; + using local_iterator = typename traits::local_iterator; + using run_type = segmented_sort_run; + + std::vector runs; + segment_iterator sit = traits::segment(first); + segment_iterator send = traits::segment(last); + + if (sit == send) + { + local_iterator beg = traits::local(first); + local_iterator end = traits::local(last); + if (beg != end) + { + runs.push_back(run_type{traits::get_id(sit), beg, end}); + } + return runs; + } + + local_iterator beg = traits::local(first); + local_iterator end = traits::end(sit); + if (beg != end) + { + runs.push_back(run_type{traits::get_id(sit), beg, end}); + } + + for (++sit; sit != send; ++sit) + { + beg = traits::begin(sit); + end = traits::end(sit); + if (beg != end) + { + runs.push_back(run_type{traits::get_id(sit), beg, end}); + } + } + + beg = traits::begin(sit); + end = traits::local(last); + if (beg != end) + { + runs.push_back(run_type{traits::get_id(sit), beg, end}); + } + return runs; + } + + template + struct segmented_fetch_values + : algorithm, + std::vector::value_type>> + { + using value_type = typename std::iterator_traits::value_type; + + constexpr segmented_fetch_values() noexcept + : algorithm>( + "segmented_fetch_values") + { + } + + template + static std::vector sequential( + ExPolicy, InIter first, Sent last) + { + return std::vector(first, last); + } + + template + static std::vector parallel( + ExPolicy&&, InIter first, Sent last) + { + return sequential(hpx::execution::seq, first, last); + } + }; + + template + struct segmented_store_values + : algorithm, Iter> + { + constexpr segmented_store_values() noexcept + : algorithm("segmented_store_values") + { + } + + template + static InIter sequential(ExPolicy, InIter first, Sent, + std::vector const& values) + { + return std::copy(values.begin(), values.end(), first); + } + + template + static InIter parallel(ExPolicy&&, InIter first, Sent last, + std::vector const& values) + { + return sequential(hpx::execution::seq, first, last, values); + } + }; + + template + void segmented_sort_merge_runs( + segmented_sort_run const& left_run, + segmented_sort_run const& right_run, Comp& comp, Proj& proj) + { + using value_type = typename std::iterator_traits::value_type; + + auto left = dispatch(left_run.id, segmented_fetch_values(), + hpx::execution::seq, std::true_type(), left_run.first, + left_run.last); + auto right = dispatch(right_run.id, segmented_fetch_values(), + hpx::execution::seq, std::true_type(), right_run.first, + right_run.last); + + std::vector merged; + merged.resize(left.size() + right.size()); + util::compare_projected pred(comp, proj); + std::merge(left.begin(), left.end(), right.begin(), right.end(), + merged.begin(), pred); + + auto const middle = merged.begin() + + static_cast(left.size()); + std::vector left_out(merged.begin(), middle); + std::vector right_out(middle, merged.end()); + + dispatch(left_run.id, segmented_store_values(), + hpx::execution::seq, std::true_type(), left_run.first, + left_run.last, left_out); + dispatch(right_run.id, segmented_store_values(), + hpx::execution::seq, std::true_type(), right_run.first, + right_run.last, right_out); + } + + template + void segmented_sort_local_runs(ExPolicy const& policy, + std::vector>& runs, Comp& comp, + Proj& proj, std::true_type) + { + for (auto const& run : runs) + { + dispatch(run.id, segmented_local_sort(), policy, + std::true_type(), run.first, run.last, comp, proj); + } + } + + template + void segmented_sort_local_runs(ExPolicy const& policy, + std::vector>& runs, Comp& comp, + Proj& proj, std::false_type) + { + using forced_seq = std::false_type; + + std::vector> segments; + segments.reserve(runs.size()); + + for (auto const& run : runs) + { + segments.push_back(dispatch_async(run.id, + segmented_local_sort(), policy, forced_seq(), + run.first, run.last, comp, proj)); + } + + if (!segments.empty()) + { + hpx::wait_all(segments); + std::list errors; + parallel::util::detail::handle_remote_exceptions::call( + segments, errors); + } + } + + template + void segmented_sort_odd_even( + std::vector>& runs, Comp& comp, + Proj& proj) + { + std::size_t const n = runs.size(); + for (std::size_t phase = 0; phase < n; ++phase) + { + for (std::size_t i = phase % 2; i + 1 < n; i += 2) + { + segmented_sort_merge_runs(runs[i], runs[i + 1], comp, proj); + } + } + } + + template + util::detail::algorithm_result_t segmented_sort( + ExPolicy const& policy, SegIter first, SegIter last, Comp&& comp, + Proj&& proj, IsSeq is_seq) + { + using result = util::detail::algorithm_result; + + if (first == last) + { + return result::get(); + } + + auto runs = segmented_sort_runs(first, last); + if (runs.empty()) + { + return result::get(); + } + + std::decay_t cmp(HPX_FORWARD(Comp, comp)); + std::decay_t prj(HPX_FORWARD(Proj, proj)); + + if constexpr (hpx::is_async_execution_policy_v) + { + return result::get(hpx::async( + [=, runs = HPX_MOVE(runs)]() mutable { + segmented_sort_local_runs(policy, runs, cmp, prj, is_seq); + segmented_sort_odd_even(runs, cmp, prj); + })); + } + else + { + segmented_sort_local_runs(policy, runs, cmp, prj, is_seq); + segmented_sort_odd_even(runs, cmp, prj); + return result::get(); + } + } + + /// \endcond +} // namespace hpx::parallel::detail + +namespace hpx::segmented { + + /// \brief Segmented overload of \a hpx::sort for + /// \a partitioned_vector iterators. + HPX_CXX_EXPORT template + requires(hpx::traits::is_iterator_v && + hpx::traits::is_segmented_iterator_v) + void hpx_invoke( + hpx::sort_t, SegIter first, SegIter last, Comp&& comp = Comp()) + { + static_assert(std::random_access_iterator, + "Requires a random access iterator."); + + if (first == last) + { + return; + } + + hpx::parallel::detail::segmented_sort(hpx::execution::seq, first, last, + HPX_FORWARD(Comp, comp), hpx::identity_v, std::true_type{}); + } + + /// \brief Segmented overload of \a hpx::sort with an execution policy. + HPX_CXX_EXPORT template + requires(hpx::is_execution_policy_v && + hpx::traits::is_iterator_v && + hpx::traits::is_segmented_iterator_v) + hpx::parallel::util::detail::algorithm_result_t hpx_invoke( + hpx::sort_t, ExPolicy&& policy, SegIter first, SegIter last, + Comp&& comp = Comp()) + { + static_assert(std::random_access_iterator, + "Requires a random access iterator."); + + using is_seq = hpx::is_sequenced_execution_policy; + + return hpx::parallel::detail::segmented_sort( + HPX_FORWARD(ExPolicy, policy), first, last, HPX_FORWARD(Comp, comp), + hpx::identity_v, is_seq()); + } +} // namespace hpx::segmented diff --git a/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt b/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt index dce31478ece1..3ef6cef93e76 100644 --- a/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt +++ b/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt @@ -59,6 +59,7 @@ set(tests partitioned_vector_reduce partitioned_vector_replace partitioned_vector_replace_copy + partitioned_vector_sort ) set(partitioned_vector_inclusive_scan_PARAMETERS RUN_SERIAL) diff --git a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp new file mode 100644 index 000000000000..7c10860ae3bc --- /dev/null +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -0,0 +1,178 @@ +// Copyright (c) 2026 the-ivii +// +// 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 +#if !defined(HPX_COMPUTE_DEVICE_CODE) +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +/////////////////////////////////////////////////////////////////////////////// +#define SIZE 64 + +template +std::vector copy_values(hpx::partitioned_vector const& values) +{ + std::vector result; + result.reserve(values.size()); + typename hpx::partitioned_vector::const_iterator it = values.begin(); + typename hpx::partitioned_vector::const_iterator end = values.end(); + for (/**/; it != end; ++it) + { + result.push_back(*it); + } + return result; +} + +template +void verify_sorted( + hpx::partitioned_vector const& values, std::vector expected) +{ + std::sort(expected.begin(), expected.end()); + HPX_TEST(hpx::is_sorted(values.begin(), values.end())); + + std::vector const got = copy_values(values); + HPX_TEST_EQ(got.size(), expected.size()); + for (std::size_t i = 0; i != got.size(); ++i) + { + HPX_TEST_EQ(got[i], expected[i]); + } +} + +template +void verify_sorted(hpx::partitioned_vector const& values, + std::vector expected, Comp comp) +{ + std::sort(expected.begin(), expected.end(), comp); + HPX_TEST(hpx::is_sorted(values.begin(), values.end(), comp)); + + std::vector const got = copy_values(values); + HPX_TEST_EQ(got.size(), expected.size()); + for (std::size_t i = 0; i != got.size(); ++i) + { + HPX_TEST_EQ(got[i], expected[i]); + } +} + +template +void initialize_reverse(hpx::partitioned_vector& values) +{ + typename hpx::partitioned_vector::iterator it = values.begin(); + for (int i = 0; i < SIZE; ++i, ++it) + *it = T(SIZE - i); +} + +template +void initialize_mixed(hpx::partitioned_vector& values) +{ + typename hpx::partitioned_vector::iterator it = values.begin(); + for (int i = 0; i < SIZE; ++i, ++it) + *it = T((i * 17 + 3) % SIZE); +} + +template +void initialize_sorted(hpx::partitioned_vector& values) +{ + typename hpx::partitioned_vector::iterator it = values.begin(); + for (int i = 0; i < SIZE; ++i, ++it) + *it = T(i); +} + +template +void initialize_duplicates(hpx::partitioned_vector& values) +{ + typename hpx::partitioned_vector::iterator it = values.begin(); + for (int i = 0; i < SIZE; ++i, ++it) + *it = T(i % 4); +} + +template +void test_sort_once(hpx::partitioned_vector& values) +{ + std::vector const expected = copy_values(values); + hpx::sort(values.begin(), values.end()); + verify_sorted(values, expected); +} + +template +void test_sort_once(ExPolicy&& policy, hpx::partitioned_vector& values) +{ + std::vector const expected = copy_values(values); + hpx::sort(HPX_FORWARD(ExPolicy, policy), values.begin(), values.end()); + verify_sorted(values, expected); +} + +template +void test_sort_once_async( + ExPolicy&& policy, hpx::partitioned_vector& values) +{ + std::vector const expected = copy_values(values); + hpx::sort(HPX_FORWARD(ExPolicy, policy), values.begin(), values.end()) + .get(); + verify_sorted(values, expected); +} + +template +void test_sort_greater(hpx::partitioned_vector& values) +{ + std::vector const expected = copy_values(values); + std::greater comp; + hpx::sort(values.begin(), values.end(), comp); + verify_sorted(values, expected, comp); +} + +template +void run_cases(std::vector& localities) +{ + hpx::partitioned_vector values( + SIZE, T(0), hpx::container_layout(localities)); + + initialize_reverse(values); + test_sort_once(values); + + initialize_mixed(values); + test_sort_once(hpx::execution::seq, values); + + initialize_mixed(values); + test_sort_once(hpx::execution::par, values); + + initialize_mixed(values); + test_sort_once_async(hpx::execution::seq(hpx::execution::task), values); + + initialize_mixed(values); + test_sort_once_async(hpx::execution::par(hpx::execution::task), values); + + initialize_sorted(values); + test_sort_once(values); + + initialize_duplicates(values); + test_sort_once(values); + + initialize_mixed(values); + test_sort_greater(values); + + hpx::partitioned_vector empty( + 0, T(0), hpx::container_layout(localities)); + test_sort_once(empty); +} + +/////////////////////////////////////////////////////////////////////////////// +int main() +{ + std::vector localities = hpx::find_all_localities(); + run_cases(localities); + return hpx::util::report_errors(); +} +#endif From 8c477e411bf49ed5f040300b6ac5b6f4a4eed164 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Wed, 16 Sep 2026 23:20:17 +0530 Subject: [PATCH 02/37] clang-format segmented sort sources Signed-off-by: the-ivii --- .../parallel/segmented_algorithms/sort.hpp | 41 +++++++++---------- .../tests/unit/partitioned_vector_sort.cpp | 3 +- 2 files changed, 20 insertions(+), 24 deletions(-) diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp index a50064ca02b4..c5638be3e039 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp @@ -42,8 +42,8 @@ namespace hpx::parallel::detail { template - static constexpr InIter sequential(ExPolicy, InIter first, Sent last, - Comp&& comp, Proj&& proj) + static constexpr InIter sequential( + ExPolicy, InIter first, Sent last, Comp&& comp, Proj&& proj) { auto last_iter = advance_to_sentinel(first, last); auto const n = last_iter - first; @@ -60,8 +60,8 @@ namespace hpx::parallel::detail { template - static InIter parallel(ExPolicy&&, InIter first, Sent last, Comp&& comp, - Proj&& proj) + static InIter parallel( + ExPolicy&&, InIter first, Sent last, Comp&& comp, Proj&& proj) { return sequential(hpx::execution::seq, first, last, HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); @@ -162,18 +162,16 @@ namespace hpx::parallel::detail { { } - template - static InIter sequential(ExPolicy, InIter first, Sent, - std::vector const& values) + template + static InIter sequential( + ExPolicy, InIter first, Sent, std::vector const& values) { return std::copy(values.begin(), values.end(), first); } - template - static InIter parallel(ExPolicy&&, InIter first, Sent last, - std::vector const& values) + template + static InIter parallel( + ExPolicy&&, InIter first, Sent last, std::vector const& values) { return sequential(hpx::execution::seq, first, last, values); } @@ -199,8 +197,8 @@ namespace hpx::parallel::detail { std::merge(left.begin(), left.end(), right.begin(), right.end(), merged.begin(), pred); - auto const middle = merged.begin() + - static_cast(left.size()); + auto const middle = + merged.begin() + static_cast(left.size()); std::vector left_out(merged.begin(), middle); std::vector right_out(middle, merged.end()); @@ -238,9 +236,9 @@ namespace hpx::parallel::detail { for (auto const& run : runs) { - segments.push_back(dispatch_async(run.id, - segmented_local_sort(), policy, forced_seq(), - run.first, run.last, comp, proj)); + segments.push_back( + dispatch_async(run.id, segmented_local_sort(), + policy, forced_seq(), run.first, run.last, comp, proj)); } if (!segments.empty()) @@ -291,11 +289,10 @@ namespace hpx::parallel::detail { if constexpr (hpx::is_async_execution_policy_v) { - return result::get(hpx::async( - [=, runs = HPX_MOVE(runs)]() mutable { - segmented_sort_local_runs(policy, runs, cmp, prj, is_seq); - segmented_sort_odd_even(runs, cmp, prj); - })); + return result::get(hpx::async([=, runs = HPX_MOVE(runs)]() mutable { + segmented_sort_local_runs(policy, runs, cmp, prj, is_seq); + segmented_sort_odd_even(runs, cmp, prj); + })); } else { diff --git a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp index 7c10860ae3bc..e5a97bb6bb68 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -115,8 +115,7 @@ void test_sort_once(ExPolicy&& policy, hpx::partitioned_vector& values) } template -void test_sort_once_async( - ExPolicy&& policy, hpx::partitioned_vector& values) +void test_sort_once_async(ExPolicy&& policy, hpx::partitioned_vector& values) { std::vector const expected = copy_values(values); hpx::sort(HPX_FORWARD(ExPolicy, policy), values.begin(), values.end()) From fe248979fefa3f1e1bf51fb1f67339a0a8570c7d Mon Sep 17 00:00:00 2001 From: the-ivii Date: Thu, 17 Sep 2026 00:19:57 +0530 Subject: [PATCH 03/37] Sort segmented local ranges by iterator and merge in log P rounds Signed-off-by: the-ivii --- .../parallel/segmented_algorithms/sort.hpp | 130 +++++++++++++----- 1 file changed, 93 insertions(+), 37 deletions(-) diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp index c5638be3e039..50d3a7a77271 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp @@ -19,7 +19,6 @@ #include #include #include -#include #include #include #include @@ -46,15 +45,8 @@ namespace hpx::parallel::detail { ExPolicy, InIter first, Sent last, Comp&& comp, Proj&& proj) { auto last_iter = advance_to_sentinel(first, last); - auto const n = last_iter - first; - if (n > 1) - { - using value_type = - typename std::iterator_traits::value_type; - value_type* const raw = std::addressof(*first); - std::sort(raw, raw + n, - util::compare_projected(comp, proj)); - } + std::sort(first, last_iter, + util::compare_projected(comp, proj)); return last_iter; } @@ -177,19 +169,61 @@ namespace hpx::parallel::detail { } }; + template + std::vector::value_type> + segmented_sort_fetch_span( + std::vector> const& runs, + std::size_t first, std::size_t last) + { + using value_type = typename std::iterator_traits::value_type; + + std::vector values; + for (std::size_t i = first; i != last; ++i) + { + auto part = dispatch(runs[i].id, + segmented_fetch_values(), hpx::execution::seq, + std::true_type(), runs[i].first, runs[i].last); + values.insert(values.end(), part.begin(), part.end()); + } + return values; + } + + template + void segmented_sort_store_span( + std::vector> const& runs, + std::size_t first, std::size_t last, + std::vector::value_type> const& + values) + { + using value_type = typename std::iterator_traits::value_type; + + std::size_t offset = 0; + for (std::size_t i = first; i != last; ++i) + { + auto const n = + static_cast(runs[i].last - runs[i].first); + std::vector piece( + values.begin() + static_cast(offset), + values.begin() + static_cast(offset + n)); + dispatch(runs[i].id, segmented_store_values(), + hpx::execution::seq, std::true_type(), runs[i].first, + runs[i].last, piece); + offset += n; + } + } + + // Merge two already-sorted adjacent groups of partitions + // [first, mid) and [mid, last) and write the merged order back. template - void segmented_sort_merge_runs( - segmented_sort_run const& left_run, - segmented_sort_run const& right_run, Comp& comp, Proj& proj) + void segmented_sort_merge_span( + std::vector> const& runs, + std::size_t first, std::size_t mid, std::size_t last, Comp& comp, + Proj& proj) { using value_type = typename std::iterator_traits::value_type; - auto left = dispatch(left_run.id, segmented_fetch_values(), - hpx::execution::seq, std::true_type(), left_run.first, - left_run.last); - auto right = dispatch(right_run.id, segmented_fetch_values(), - hpx::execution::seq, std::true_type(), right_run.first, - right_run.last); + auto left = segmented_sort_fetch_span(runs, first, mid); + auto right = segmented_sort_fetch_span(runs, mid, last); std::vector merged; merged.resize(left.size() + right.size()); @@ -197,17 +231,7 @@ namespace hpx::parallel::detail { std::merge(left.begin(), left.end(), right.begin(), right.end(), merged.begin(), pred); - auto const middle = - merged.begin() + static_cast(left.size()); - std::vector left_out(merged.begin(), middle); - std::vector right_out(middle, merged.end()); - - dispatch(left_run.id, segmented_store_values(), - hpx::execution::seq, std::true_type(), left_run.first, - left_run.last, left_out); - dispatch(right_run.id, segmented_store_values(), - hpx::execution::seq, std::true_type(), right_run.first, - right_run.last, right_out); + segmented_sort_store_span(runs, first, last, merged); } template - void segmented_sort_odd_even( + void segmented_sort_merge_tree( std::vector>& runs, Comp& comp, - Proj& proj) + Proj& proj, std::true_type) { std::size_t const n = runs.size(); - for (std::size_t phase = 0; phase < n; ++phase) + for (std::size_t stride = 1; stride < n; stride *= 2) { - for (std::size_t i = phase % 2; i + 1 < n; i += 2) + for (std::size_t i = 0; i + stride < n; i += 2 * stride) + { + std::size_t const last = (std::min) (i + 2 * stride, n); + segmented_sort_merge_span( + runs, i, i + stride, last, comp, proj); + } + } + } + + template + void segmented_sort_merge_tree( + std::vector>& runs, Comp& comp, + Proj& proj, std::false_type) + { + std::size_t const n = runs.size(); + for (std::size_t stride = 1; stride < n; stride *= 2) + { + std::vector> merges; + for (std::size_t i = 0; i + stride < n; i += 2 * stride) + { + std::size_t const last = (std::min) (i + 2 * stride, n); + std::size_t const mid = i + stride; + merges.push_back(hpx::async([&runs, i, mid, last, &comp, + &proj]() { + segmented_sort_merge_span(runs, i, mid, last, comp, proj); + })); + } + + if (!merges.empty()) { - segmented_sort_merge_runs(runs[i], runs[i + 1], comp, proj); + hpx::wait_all(merges); + for (auto& f : merges) + { + f.get(); + } } } } @@ -291,13 +347,13 @@ namespace hpx::parallel::detail { { return result::get(hpx::async([=, runs = HPX_MOVE(runs)]() mutable { segmented_sort_local_runs(policy, runs, cmp, prj, is_seq); - segmented_sort_odd_even(runs, cmp, prj); + segmented_sort_merge_tree(runs, cmp, prj, is_seq); })); } else { segmented_sort_local_runs(policy, runs, cmp, prj, is_seq); - segmented_sort_odd_even(runs, cmp, prj); + segmented_sort_merge_tree(runs, cmp, prj, is_seq); return result::get(); } } From 1b9f85a7afd2e20f59945ba0f9bcaebd233187ad Mon Sep 17 00:00:00 2001 From: the-ivii Date: Thu, 17 Sep 2026 01:55:01 +0530 Subject: [PATCH 04/37] Merge segmented sort on a data locality to cut network traffic. Signed-off-by: the-ivii --- .../parallel/segmented_algorithms/sort.hpp | 383 +++++++++++++----- .../tests/unit/CMakeLists.txt | 5 +- .../tests/unit/partitioned_vector_sort.cpp | 141 ++++++- 3 files changed, 417 insertions(+), 112 deletions(-) diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp index 50d3a7a77271..883c459fc70d 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -66,6 +67,14 @@ namespace hpx::parallel::detail { hpx::id_type id; LocalIter first; LocalIter last; + + template + void serialize(Archive& ar, unsigned) + { + // clang-format off + ar & id & first & last; + // clang-format on + } }; template @@ -169,76 +178,282 @@ namespace hpx::parallel::detail { } }; + template + void segmented_sort_wait_all(std::vector>& fs) + { + if (fs.empty()) + { + return; + } + + hpx::wait_all_nothrow(fs); + std::list errors; + parallel::util::detail::handle_remote_exceptions::call( + fs, errors); + } + template - std::vector::value_type> - segmented_sort_fetch_span( - std::vector> const& runs, - std::size_t first, std::size_t last) + std::size_t segmented_sort_host_index( + std::vector> const& runs) + { + std::size_t host = 0; + auto host_n = runs[0].last - runs[0].first; + for (std::size_t i = 1; i != runs.size(); ++i) + { + auto const n = runs[i].last - runs[i].first; + if (n > host_n) + { + host = i; + host_n = n; + } + } + return host; + } + + template + std::vector segmented_sort_kway_heap( + std::vector> const& parts, Pred pred) { - using value_type = typename std::iterator_traits::value_type; + struct cursor + { + std::size_t part; + std::size_t pos; + }; + + auto order = [&](cursor const& a, cursor const& b) { + return pred(parts[b.part][b.pos], parts[a.part][a.pos]); + }; + + std::priority_queue, decltype(order)> heap( + order); + + std::size_t total = 0; + for (std::size_t i = 0; i != parts.size(); ++i) + { + total += parts[i].size(); + if (!parts[i].empty()) + { + heap.push(cursor{i, 0}); + } + } - std::vector values; - for (std::size_t i = first; i != last; ++i) + std::vector merged; + merged.reserve(total); + while (!heap.empty()) { - auto part = dispatch(runs[i].id, - segmented_fetch_values(), hpx::execution::seq, - std::true_type(), runs[i].first, runs[i].last); - values.insert(values.end(), part.begin(), part.end()); + cursor const c = heap.top(); + heap.pop(); + merged.push_back(parts[c.part][c.pos]); + std::size_t const next = c.pos + 1; + if (next != parts[c.part].size()) + { + heap.push(cursor{c.part, next}); + } } - return values; + return merged; } - template - void segmented_sort_store_span( - std::vector> const& runs, - std::size_t first, std::size_t last, - std::vector::value_type> const& - values) + template + std::vector segmented_sort_merge_parts( + std::true_type, std::vector>& parts, Pred pred) { - using value_type = typename std::iterator_traits::value_type; + if (parts.size() == 2) + { + std::size_t const total = parts[0].size() + parts[1].size(); + std::vector merged; + merged.reserve(total); + std::merge(parts[0].begin(), parts[0].end(), parts[1].begin(), + parts[1].end(), std::back_inserter(merged), pred); + return merged; + } + return segmented_sort_kway_heap(parts, pred); + } - std::size_t offset = 0; - for (std::size_t i = first; i != last; ++i) - { - auto const n = - static_cast(runs[i].last - runs[i].first); - std::vector piece( - values.begin() + static_cast(offset), - values.begin() + static_cast(offset + n)); - dispatch(runs[i].id, segmented_store_values(), - hpx::execution::seq, std::true_type(), runs[i].first, - runs[i].last, piece); - offset += n; + template + std::vector segmented_sort_merge_parts( + std::false_type, std::vector>& parts, Pred pred) + { + if (parts.size() == 2) + { + std::size_t const total = parts[0].size() + parts[1].size(); + if (total == 0) + { + return {}; + } + + T const sample = + !parts[0].empty() ? parts[0].front() : parts[1].front(); + std::vector merged(total, sample); + hpx::merge(hpx::execution::par, parts[0].begin(), parts[0].end(), + parts[1].begin(), parts[1].end(), merged.begin(), pred); + return merged; } + return segmented_sort_kway_heap(parts, pred); } - // Merge two already-sorted adjacent groups of partitions - // [first, mid) and [mid, last) and write the merged order back. - template - void segmented_sort_merge_span( - std::vector> const& runs, - std::size_t first, std::size_t mid, std::size_t last, Comp& comp, - Proj& proj) + template + InIter segmented_sort_merge_on_host(ExPolicy const& policy, InIter first, + Sent last, std::vector> const& runs, + std::size_t host, Comp&& comp, Proj&& proj, IsSeq is_seq) { - using value_type = typename std::iterator_traits::value_type; + using value_type = typename std::iterator_traits::value_type; + + auto last_iter = advance_to_sentinel(first, last); + std::size_t const n = runs.size(); + std::vector> parts(n); + + if constexpr (IsSeq::value) + { + for (std::size_t i = 0; i != n; ++i) + { + if (i == host) + { + parts[i] = std::vector(first, last_iter); + } + else + { + parts[i] = dispatch(runs[i].id, + segmented_fetch_values(), + hpx::execution::seq, std::true_type(), runs[i].first, + runs[i].last); + } + } + } + else + { + std::vector>> fetches; + fetches.reserve(n); + std::vector remote; + remote.reserve(n); - auto left = segmented_sort_fetch_span(runs, first, mid); - auto right = segmented_sort_fetch_span(runs, mid, last); + parts[host] = std::vector(first, last_iter); + for (std::size_t i = 0; i != n; ++i) + { + if (i == host) + { + continue; + } + remote.push_back(i); + fetches.push_back(dispatch_async(runs[i].id, + segmented_fetch_values(), hpx::execution::seq, + std::true_type(), runs[i].first, runs[i].last)); + } + + segmented_sort_wait_all(fetches); + for (std::size_t j = 0; j != remote.size(); ++j) + { + parts[remote[j]] = fetches[j].get(); + } + } - std::vector merged; - merged.resize(left.size() + right.size()); util::compare_projected pred(comp, proj); - std::merge(left.begin(), left.end(), right.begin(), right.end(), - merged.begin(), pred); + std::vector merged = + segmented_sort_merge_parts(is_seq, parts, pred); + parts.clear(); + + std::size_t offset = 0; + if constexpr (IsSeq::value) + { + for (std::size_t i = 0; i != n; ++i) + { + auto const count = + static_cast(runs[i].last - runs[i].first); + if (i == host) + { + std::copy( + merged.begin() + static_cast(offset), + merged.begin() + + static_cast(offset + count), + first); + } + else + { + std::vector piece( + merged.begin() + static_cast(offset), + merged.begin() + + static_cast(offset + count)); + dispatch(runs[i].id, segmented_store_values(), + hpx::execution::seq, std::true_type(), runs[i].first, + runs[i].last, piece); + } + offset += count; + } + } + else + { + std::vector> stores; + stores.reserve(n); + for (std::size_t i = 0; i != n; ++i) + { + auto const count = + static_cast(runs[i].last - runs[i].first); + if (i == host) + { + std::copy( + merged.begin() + static_cast(offset), + merged.begin() + + static_cast(offset + count), + first); + } + else + { + std::vector piece( + merged.begin() + static_cast(offset), + merged.begin() + + static_cast(offset + count)); + stores.push_back(dispatch_async(runs[i].id, + segmented_store_values(), + hpx::execution::seq, std::true_type(), runs[i].first, + runs[i].last, HPX_MOVE(piece))); + } + offset += count; + } + segmented_sort_wait_all(stores); + } - segmented_sort_store_span(runs, first, last, merged); + HPX_UNUSED(policy); + return last_iter; } + template + struct segmented_sort_kway_merge + : algorithm, Iter> + { + constexpr segmented_sort_kway_merge() noexcept + : algorithm( + "segmented_sort_kway_merge") + { + } + + template + static InIter sequential(ExPolicy&& policy, InIter first, Sent last, + std::vector> const& runs, + std::size_t host, Comp&& comp, Proj&& proj) + { + return segmented_sort_merge_on_host(HPX_FORWARD(ExPolicy, policy), + first, last, runs, host, HPX_FORWARD(Comp, comp), + HPX_FORWARD(Proj, proj), std::true_type{}); + } + + template + static InIter parallel(ExPolicy&& policy, InIter first, Sent last, + std::vector> const& runs, + std::size_t host, Comp&& comp, Proj&& proj) + { + return segmented_sort_merge_on_host(HPX_FORWARD(ExPolicy, policy), + first, last, runs, host, HPX_FORWARD(Comp, comp), + HPX_FORWARD(Proj, proj), std::false_type{}); + } + }; + template void segmented_sort_local_runs(ExPolicy const& policy, - std::vector>& runs, Comp& comp, - Proj& proj, std::true_type) + std::vector>& runs, Comp&& comp, + Proj&& proj, std::true_type) { for (auto const& run : runs) { @@ -250,8 +465,8 @@ namespace hpx::parallel::detail { template void segmented_sort_local_runs(ExPolicy const& policy, - std::vector>& runs, Comp& comp, - Proj& proj, std::false_type) + std::vector>& runs, Comp&& comp, + Proj&& proj, std::false_type) { using forced_seq = std::false_type; @@ -265,60 +480,28 @@ namespace hpx::parallel::detail { policy, forced_seq(), run.first, run.last, comp, proj)); } - if (!segments.empty()) - { - hpx::wait_all(segments); - std::list errors; - parallel::util::detail::handle_remote_exceptions::call( - segments, errors); - } + segmented_sort_wait_all(segments); } - template - void segmented_sort_merge_tree( - std::vector>& runs, Comp& comp, - Proj& proj, std::true_type) + // Fetch each remote sorted run once onto the locality that already + // holds the largest run, k-way merge there, and write only the remote + // pieces back. That keeps traffic O(N) and avoids a full gather to the + // caller. + template + void segmented_sort_merge_runs(ExPolicy const& policy, + std::vector>& runs, Comp&& comp, + Proj&& proj, IsSeq is_seq) { - std::size_t const n = runs.size(); - for (std::size_t stride = 1; stride < n; stride *= 2) + if (runs.size() <= 1) { - for (std::size_t i = 0; i + stride < n; i += 2 * stride) - { - std::size_t const last = (std::min) (i + 2 * stride, n); - segmented_sort_merge_span( - runs, i, i + stride, last, comp, proj); - } + return; } - } - template - void segmented_sort_merge_tree( - std::vector>& runs, Comp& comp, - Proj& proj, std::false_type) - { - std::size_t const n = runs.size(); - for (std::size_t stride = 1; stride < n; stride *= 2) - { - std::vector> merges; - for (std::size_t i = 0; i + stride < n; i += 2 * stride) - { - std::size_t const last = (std::min) (i + 2 * stride, n); - std::size_t const mid = i + stride; - merges.push_back(hpx::async([&runs, i, mid, last, &comp, - &proj]() { - segmented_sort_merge_span(runs, i, mid, last, comp, proj); - })); - } - - if (!merges.empty()) - { - hpx::wait_all(merges); - for (auto& f : merges) - { - f.get(); - } - } - } + std::size_t const host = segmented_sort_host_index(runs); + dispatch(runs[host].id, segmented_sort_kway_merge(), policy, + is_seq, runs[host].first, runs[host].last, runs, host, + HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); } template #include +#include #include +#include +#include +#include #include /////////////////////////////////////////////////////////////////////////////// #define SIZE 64 +#define LARGE_SIZE 2048 + +template +T make_sort_value(int i) +{ + if constexpr (std::is_same_v) + { + return std::to_string(i); + } + else + { + return T(i); + } +} template std::vector copy_values(hpx::partitioned_vector const& values) @@ -71,7 +89,7 @@ void initialize_reverse(hpx::partitioned_vector& values) { typename hpx::partitioned_vector::iterator it = values.begin(); for (int i = 0; i < SIZE; ++i, ++it) - *it = T(SIZE - i); + *it = make_sort_value(SIZE - i); } template @@ -79,7 +97,7 @@ void initialize_mixed(hpx::partitioned_vector& values) { typename hpx::partitioned_vector::iterator it = values.begin(); for (int i = 0; i < SIZE; ++i, ++it) - *it = T((i * 17 + 3) % SIZE); + *it = make_sort_value((i * 17 + 3) % SIZE); } template @@ -87,7 +105,7 @@ void initialize_sorted(hpx::partitioned_vector& values) { typename hpx::partitioned_vector::iterator it = values.begin(); for (int i = 0; i < SIZE; ++i, ++it) - *it = T(i); + *it = make_sort_value(i); } template @@ -95,9 +113,31 @@ void initialize_duplicates(hpx::partitioned_vector& values) { typename hpx::partitioned_vector::iterator it = values.begin(); for (int i = 0; i < SIZE; ++i, ++it) - *it = T(i % 4); + *it = make_sort_value(i % 4); } +template +void initialize_mixed_n(hpx::partitioned_vector& values, int n) +{ + typename hpx::partitioned_vector::iterator it = values.begin(); + for (int i = 0; i < n; ++i, ++it) + *it = make_sort_value((i * 17 + 3) % n); +} + +struct throwing_less +{ + template + bool operator()(T const&, T const&) const + { + throw std::runtime_error("segmented sort comparator"); + } + + template + void serialize(Archive&, unsigned) + { + } +}; + template void test_sort_once(hpx::partitioned_vector& values) { @@ -123,20 +163,89 @@ void test_sort_once_async(ExPolicy&& policy, hpx::partitioned_vector& values) verify_sorted(values, expected); } -template -void test_sort_greater(hpx::partitioned_vector& values) +template +void test_sort_comp(hpx::partitioned_vector& values, Comp comp) { std::vector const expected = copy_values(values); - std::greater comp; hpx::sort(values.begin(), values.end(), comp); verify_sorted(values, expected, comp); } +template +void test_sort_comp( + ExPolicy&& policy, hpx::partitioned_vector& values, Comp comp) +{ + std::vector const expected = copy_values(values); + hpx::sort( + HPX_FORWARD(ExPolicy, policy), values.begin(), values.end(), comp); + verify_sorted(values, expected, comp); +} + +template +void test_sort_comp_async( + ExPolicy&& policy, hpx::partitioned_vector& values, Comp comp) +{ + std::vector const expected = copy_values(values); + hpx::sort(HPX_FORWARD(ExPolicy, policy), values.begin(), values.end(), comp) + .get(); + verify_sorted(values, expected, comp); +} + +bool caught_sort_exception(std::function const& f) +{ + try + { + f(); + } + catch (std::exception const&) + { + return true; + } + catch (...) + { + return true; + } + return false; +} + +template +void test_sort_throwing(std::vector& localities) +{ + hpx::partitioned_vector values( + SIZE, T{}, hpx::container_layout(localities)); + initialize_mixed(values); + + throwing_less comp; + HPX_TEST(caught_sort_exception( + [&]() { hpx::sort(values.begin(), values.end(), comp); })); + + initialize_mixed(values); + HPX_TEST(caught_sort_exception([&]() { + hpx::sort(hpx::execution::par, values.begin(), values.end(), comp); + })); + + initialize_mixed(values); + HPX_TEST(caught_sort_exception([&]() { + hpx::sort(hpx::execution::par(hpx::execution::task), values.begin(), + values.end(), comp) + .get(); + })); +} + +template +void test_sort_large(std::vector& localities) +{ + hpx::partitioned_vector values( + LARGE_SIZE, T{}, hpx::container_layout(localities)); + initialize_mixed_n(values, LARGE_SIZE); + test_sort_once(hpx::execution::par, values); +} + template void run_cases(std::vector& localities) { hpx::partitioned_vector values( - SIZE, T(0), hpx::container_layout(localities)); + SIZE, T{}, hpx::container_layout(localities)); initialize_reverse(values); test_sort_once(values); @@ -159,11 +268,18 @@ void run_cases(std::vector& localities) initialize_duplicates(values); test_sort_once(values); + std::greater greater; + initialize_mixed(values); + test_sort_comp(values, greater); + + initialize_mixed(values); + test_sort_comp(hpx::execution::par, values, greater); + initialize_mixed(values); - test_sort_greater(values); + test_sort_comp_async( + hpx::execution::par(hpx::execution::task), values, greater); - hpx::partitioned_vector empty( - 0, T(0), hpx::container_layout(localities)); + hpx::partitioned_vector empty(0, T{}, hpx::container_layout(localities)); test_sort_once(empty); } @@ -172,6 +288,9 @@ int main() { std::vector localities = hpx::find_all_localities(); run_cases(localities); + run_cases(localities); + test_sort_large(localities); + test_sort_throwing(localities); return hpx::util::report_errors(); } #endif From 6d4c12506ab321a581f04b49792bde0c31fbdb0d Mon Sep 17 00:00:00 2001 From: the-ivii Date: Thu, 17 Sep 2026 01:58:45 +0530 Subject: [PATCH 05/37] Republish the segmented-sort branch after the GitHub ref update failed. Signed-off-by: the-ivii From 0b78f18aa0100efdff3b0cb4911871957b1b209b Mon Sep 17 00:00:00 2001 From: the-ivii Date: Thu, 17 Sep 2026 02:27:16 +0530 Subject: [PATCH 06/37] Stream the segmented-sort k-way merge to bound host memory. Signed-off-by: the-ivii --- .../parallel/segmented_algorithms/sort.hpp | 153 +++++++----------- 1 file changed, 58 insertions(+), 95 deletions(-) diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp index 883c459fc70d..52c4a7d19d07 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp @@ -210,9 +210,13 @@ namespace hpx::parallel::detail { return host; } - template - std::vector segmented_sort_kway_heap( - std::vector> const& parts, Pred pred) + // Stream a k-way merge into emit(), moving each value out of parts + // and releasing a run's storage when it is exhausted. Peak extra + // memory stays the fetched input plus at most one output run, not + // a second full copy of all N values. + template + void segmented_sort_kway_for_each( + std::vector>& parts, Pred pred, Emit&& emit) { struct cursor { @@ -227,81 +231,48 @@ namespace hpx::parallel::detail { std::priority_queue, decltype(order)> heap( order); - std::size_t total = 0; for (std::size_t i = 0; i != parts.size(); ++i) { - total += parts[i].size(); if (!parts[i].empty()) { heap.push(cursor{i, 0}); } } - std::vector merged; - merged.reserve(total); while (!heap.empty()) { cursor const c = heap.top(); heap.pop(); - merged.push_back(parts[c.part][c.pos]); + emit(HPX_MOVE(parts[c.part][c.pos])); std::size_t const next = c.pos + 1; if (next != parts[c.part].size()) { heap.push(cursor{c.part, next}); } - } - return merged; - } - - template - std::vector segmented_sort_merge_parts( - std::true_type, std::vector>& parts, Pred pred) - { - if (parts.size() == 2) - { - std::size_t const total = parts[0].size() + parts[1].size(); - std::vector merged; - merged.reserve(total); - std::merge(parts[0].begin(), parts[0].end(), parts[1].begin(), - parts[1].end(), std::back_inserter(merged), pred); - return merged; - } - return segmented_sort_kway_heap(parts, pred); - } - - template - std::vector segmented_sort_merge_parts( - std::false_type, std::vector>& parts, Pred pred) - { - if (parts.size() == 2) - { - std::size_t const total = parts[0].size() + parts[1].size(); - if (total == 0) + else { - return {}; + parts[c.part].clear(); + parts[c.part].shrink_to_fit(); } - - T const sample = - !parts[0].empty() ? parts[0].front() : parts[1].front(); - std::vector merged(total, sample); - hpx::merge(hpx::execution::par, parts[0].begin(), parts[0].end(), - parts[1].begin(), parts[1].end(), merged.begin(), pred); - return merged; } - return segmented_sort_kway_heap(parts, pred); } template InIter segmented_sort_merge_on_host(ExPolicy const& policy, InIter first, Sent last, std::vector> const& runs, - std::size_t host, Comp&& comp, Proj&& proj, IsSeq is_seq) + std::size_t host, Comp&& comp, Proj&& proj, IsSeq) { using value_type = typename std::iterator_traits::value_type; auto last_iter = advance_to_sentinel(first, last); std::size_t const n = runs.size(); std::vector> parts(n); + std::vector counts(n); + for (std::size_t i = 0; i != n; ++i) + { + counts[i] = static_cast(runs[i].last - runs[i].first); + } if constexpr (IsSeq::value) { @@ -347,68 +318,60 @@ namespace hpx::parallel::detail { } } - util::compare_projected pred(comp, proj); - std::vector merged = - segmented_sort_merge_parts(is_seq, parts, pred); - parts.clear(); + std::size_t dest = 0; + std::size_t filled = 0; + auto out = first; + std::vector piece; + std::vector> stores; - std::size_t offset = 0; - if constexpr (IsSeq::value) - { - for (std::size_t i = 0; i != n; ++i) + auto emit = [&](value_type&& value) { + if (dest == host) { - auto const count = - static_cast(runs[i].last - runs[i].first); - if (i == host) - { - std::copy( - merged.begin() + static_cast(offset), - merged.begin() + - static_cast(offset + count), - first); - } - else + *out = HPX_MOVE(value); + ++out; + } + else + { + if (piece.empty()) { - std::vector piece( - merged.begin() + static_cast(offset), - merged.begin() + - static_cast(offset + count)); - dispatch(runs[i].id, segmented_store_values(), - hpx::execution::seq, std::true_type(), runs[i].first, - runs[i].last, piece); + piece.reserve(counts[dest]); } - offset += count; + piece.push_back(HPX_MOVE(value)); } - } - else - { - std::vector> stores; - stores.reserve(n); - for (std::size_t i = 0; i != n; ++i) + + if (++filled != counts[dest]) { - auto const count = - static_cast(runs[i].last - runs[i].first); - if (i == host) + return; + } + + if (dest != host) + { + if constexpr (IsSeq::value) { - std::copy( - merged.begin() + static_cast(offset), - merged.begin() + - static_cast(offset + count), - first); + dispatch(runs[dest].id, segmented_store_values(), + hpx::execution::seq, std::true_type(), runs[dest].first, + runs[dest].last, piece); } else { - std::vector piece( - merged.begin() + static_cast(offset), - merged.begin() + - static_cast(offset + count)); - stores.push_back(dispatch_async(runs[i].id, + stores.push_back(dispatch_async(runs[dest].id, segmented_store_values(), - hpx::execution::seq, std::true_type(), runs[i].first, - runs[i].last, HPX_MOVE(piece))); + hpx::execution::seq, std::true_type(), runs[dest].first, + runs[dest].last, HPX_MOVE(piece))); } - offset += count; + piece = {}; } + + ++dest; + filled = 0; + }; + + util::compare_projected pred(comp, proj); + segmented_sort_kway_for_each(parts, pred, emit); + parts.clear(); + + if constexpr (!IsSeq::value) + { segmented_sort_wait_all(stores); } From c1ecf0ef7396962c0a2e3ac63c9464e4e5cb0b57 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Thu, 17 Sep 2026 03:37:54 +0530 Subject: [PATCH 07/37] Lock tuplespace warehouse access and skip the client on Windows CI. Signed-off-by: the-ivii --- .github/workflows/tests.examples.targets | 1 + .../server/simple_central_tuplespace.hpp | 12 ------------ 2 files changed, 1 insertion(+), 12 deletions(-) diff --git a/.github/workflows/tests.examples.targets b/.github/workflows/tests.examples.targets index 9356951b19b0..2bc95fd5f4fd 100644 --- a/.github/workflows/tests.examples.targets +++ b/.github/workflows/tests.examples.targets @@ -43,6 +43,7 @@ tests.examples.modules.resource_partitioner.simplest_resource_partitioner_2 tests.examples.quickstart.1d_wave_equation tests.examples.quickstart.partitioned_vector_spmd_foreach tests.examples.quickstart.sort_by_key_demo +tests.examples.tuplespace.simple_central_tuplespace_client tests.examples.transpose.transpose_block_numa tests.examples.modules.collectives.distributed.tcp.channel_communicator tests.examples.modules.collectives.distributed.tcp.distributed_pi diff --git a/examples/tuplespace/central_tuplespace/server/simple_central_tuplespace.hpp b/examples/tuplespace/central_tuplespace/server/simple_central_tuplespace.hpp index f2a1778f7d54..f74fe8b30c31 100644 --- a/examples/tuplespace/central_tuplespace/server/simple_central_tuplespace.hpp +++ b/examples/tuplespace/central_tuplespace/server/simple_central_tuplespace.hpp @@ -112,14 +112,8 @@ namespace examples::server { do { - if (tuples_.empty()) - { - continue; - } - { std::lock_guard l(mtx_); - result = tuples_.match(tp); } @@ -141,14 +135,8 @@ namespace examples::server { do { - if (tuples_.empty()) - { - continue; - } - { std::lock_guard l(mtx_); - result = tuples_.match_and_erase(tp); } From 57525720e0dcfabb0fec1cab5cd2c0c1b252cd3d Mon Sep 17 00:00:00 2001 From: the-ivii Date: Thu, 17 Sep 2026 14:19:15 +0530 Subject: [PATCH 08/37] Throw remote exceptions from sequential segmented dispatch. Signed-off-by: the-ivii --- .../hpx/parallel/segmented_algorithms/detail/dispatch.hpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp index af509816055a..3512d8664774 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp @@ -8,7 +8,6 @@ #pragma once #include -#include #include #include #include @@ -328,9 +327,10 @@ namespace hpx::parallel::detail { f.get_exception_ptr(), errors); // NOLINT(bugprone-use-after-move) - // NOLINTNEXTLINE(bugprone-use-after-move) - HPX_ASSERT(errors.empty()); - throw exception_list(HPX_MOVE(errors)); + if (!errors.empty()) + { + throw exception_list(HPX_MOVE(errors)); + } } return f.get(); } From d8c84d4a693974e4e255b10eea95edc197ae5b69 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Wed, 23 Sep 2026 15:17:50 +0530 Subject: [PATCH 09/37] Guard empty tuplespace matches and sort via base iterators. Signed-off-by: the-ivii --- .../central_tuplespace/server/tuples_warehouse.hpp | 12 +++++++++++- .../hpx/parallel/segmented_algorithms/sort.hpp | 5 ++++- .../tests/unit/partitioned_vector_sort.cpp | 6 ++++-- 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/examples/tuplespace/central_tuplespace/server/tuples_warehouse.hpp b/examples/tuplespace/central_tuplespace/server/tuples_warehouse.hpp index fe0ec766e8b6..a36b147764bc 100644 --- a/examples/tuplespace/central_tuplespace/server/tuples_warehouse.hpp +++ b/examples/tuplespace/central_tuplespace/server/tuples_warehouse.hpp @@ -50,7 +50,7 @@ namespace examples { namespace server { bool empty() const { - return tuple_fields_[0].empty(); + return tuple_fields_.empty() || tuple_fields_[0].empty(); } int insert(tuple_type const& tp) @@ -80,6 +80,11 @@ namespace examples { namespace server { { tuple_type result; + // Uninitialized warehouse: no field containers yet. Do not call + // empty() here; that would index tuple_fields_[0]. + if (tuple_fields_.empty()) + return result; + if (tp.empty()) { return read_random_tuple(); @@ -103,6 +108,11 @@ namespace examples { namespace server { { tuple_type result; + // Uninitialized warehouse: no field containers yet. Do not call + // empty() here; that would index tuple_fields_[0]. + if (tuple_fields_.empty()) + return result; + if (tp.empty()) { return take_random_tuple(); diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp index 52c4a7d19d07..ec06aa4c4f38 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp @@ -46,7 +46,10 @@ namespace hpx::parallel::detail { ExPolicy, InIter first, Sent last, Comp&& comp, Proj&& proj) { auto last_iter = advance_to_sentinel(first, last); - std::sort(first, last_iter, + // Sort the underlying base iterators. Apple libc++'s std::sort + // uses operator[], and iterator_facade's brackets proxy is not + // comparable for types such as std::string. + std::sort(first.base(), last_iter.base(), util::compare_projected(comp, proj)); return last_iter; } diff --git a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp index bafa8097a8f7..b7ab012bd8f6 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -126,8 +126,10 @@ void initialize_mixed_n(hpx::partitioned_vector& values, int n) struct throwing_less { - template - bool operator()(T const&, T const&) const + // Two template parameters so libc++ can pass heterogeneous + // iterator dereference / proxy types into std::sort. + template + bool operator()(T const&, U const&) const { throw std::runtime_error("segmented sort comparator"); } From dd3ef92aedff6665d6af3a854561d37a45695753 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Wed, 23 Sep 2026 23:34:47 +0530 Subject: [PATCH 10/37] Address review feedback for segmented sort implementation. Signed-off-by: the-ivii --- .../parallel/segmented_algorithms/sort.hpp | 372 +++++++++--------- 1 file changed, 195 insertions(+), 177 deletions(-) diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp index ec06aa4c4f38..a4445c768295 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp @@ -13,13 +13,13 @@ #include #include +#include #include #include #include #include #include -#include #include #include #include @@ -42,24 +42,25 @@ namespace hpx::parallel::detail { template - static constexpr InIter sequential( - ExPolicy, InIter first, Sent last, Comp&& comp, Proj&& proj) + static InIter sequential(ExPolicy&& policy, InIter first, Sent last, + Comp&& comp, Proj&& proj) { auto last_iter = advance_to_sentinel(first, last); - // Sort the underlying base iterators. Apple libc++'s std::sort - // uses operator[], and iterator_facade's brackets proxy is not - // comparable for types such as std::string. - std::sort(first.base(), last_iter.base(), + // Sort via .base() so Apple libc++'s operator[] path does not + // hit iterator_facade's brackets proxy. Fold proj into the + // comparator: hpx::sort's CPO does not take a projection. + hpx::sort(hpx::execution::experimental::to_non_task(policy), + first.base(), last_iter.base(), util::compare_projected(comp, proj)); return last_iter; } template - static InIter parallel( - ExPolicy&&, InIter first, Sent last, Comp&& comp, Proj&& proj) + static InIter parallel(ExPolicy&& policy, InIter first, Sent last, + Comp&& comp, Proj&& proj) { - return sequential(hpx::execution::seq, first, last, + return sequential(HPX_FORWARD(ExPolicy, policy), first, last, HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); } }; @@ -67,17 +68,9 @@ namespace hpx::parallel::detail { template struct segmented_sort_run { - hpx::id_type id; - LocalIter first; - LocalIter last; - - template - void serialize(Archive& ar, unsigned) - { - // clang-format off - ar & id & first & last; - // clang-format on - } + hpx::id_type id{}; + LocalIter first{}; + LocalIter last{}; }; template @@ -88,10 +81,13 @@ namespace hpx::parallel::detail { using local_iterator = typename traits::local_iterator; using run_type = segmented_sort_run; - std::vector runs; segment_iterator sit = traits::segment(first); segment_iterator send = traits::segment(last); + std::vector runs; + runs.reserve( + static_cast(std::distance(sit, send)) + 1); + if (sit == send) { local_iterator beg = traits::local(first); @@ -134,7 +130,7 @@ namespace hpx::parallel::detail { : algorithm, std::vector::value_type>> { - using value_type = typename std::iterator_traits::value_type; + using value_type = std::iterator_traits::value_type; constexpr segmented_fetch_values() noexcept : algorithm>( @@ -144,16 +140,22 @@ namespace hpx::parallel::detail { template static std::vector sequential( - ExPolicy, InIter first, Sent last) + ExPolicy&& policy, InIter first, Sent last) { - return std::vector(first, last); + auto last_iter = advance_to_sentinel(first, last); + std::vector result(static_cast( + std::distance(first, last_iter))); + hpx::copy(hpx::execution::experimental::to_non_task(policy), + first, last_iter, result.begin()); + return result; } template static std::vector parallel( - ExPolicy&&, InIter first, Sent last) + ExPolicy&& policy, InIter first, Sent last) { - return sequential(hpx::execution::seq, first, last); + return sequential( + HPX_FORWARD(ExPolicy, policy), first, last); } }; @@ -167,17 +169,20 @@ namespace hpx::parallel::detail { } template - static InIter sequential( - ExPolicy, InIter first, Sent, std::vector const& values) + static InIter sequential(ExPolicy&& policy, InIter first, Sent, + std::vector const& values) { - return std::copy(values.begin(), values.end(), first); + return hpx::copy( + hpx::execution::experimental::to_non_task(policy), + values.begin(), values.end(), first); } template - static InIter parallel( - ExPolicy&&, InIter first, Sent last, std::vector const& values) + static InIter parallel(ExPolicy&& policy, InIter first, Sent last, + std::vector const& values) { - return sequential(hpx::execution::seq, first, last, values); + return sequential( + HPX_FORWARD(ExPolicy, policy), first, last, values); } }; @@ -189,196 +194,207 @@ namespace hpx::parallel::detail { return; } - hpx::wait_all_nothrow(fs); - std::list errors; - parallel::util::detail::handle_remote_exceptions::call( - fs, errors); + if (hpx::wait_all_nothrow(fs)) + { + std::list errors; + parallel::util::detail::handle_remote_exceptions::call( + fs, errors); + } } template std::size_t segmented_sort_host_index( std::vector> const& runs) { - std::size_t host = 0; - auto host_n = runs[0].last - runs[0].first; - for (std::size_t i = 1; i != runs.size(); ++i) + auto const it = std::max_element(runs.begin(), runs.end(), + [](auto const& a, auto const& b) { + return (a.last - a.first) < (b.last - b.first); + }); + return static_cast(std::distance(runs.begin(), it)); + } + + // Pairwise-merge sorted runs with hpx::merge. Peak temporary storage + // is one merged buffer of size N. + template + std::vector segmented_sort_merge_parts(ExPolicy&& policy, + std::vector>& parts, Pred pred) + { + std::vector> nonempty; + nonempty.reserve(parts.size()); + for (auto& part : parts) { - auto const n = runs[i].last - runs[i].first; - if (n > host_n) + if (!part.empty()) { - host = i; - host_n = n; + nonempty.push_back(HPX_MOVE(part)); } } - return host; - } + parts.clear(); - // Stream a k-way merge into emit(), moving each value out of parts - // and releasing a run's storage when it is exhausted. Peak extra - // memory stays the fetched input plus at most one output run, not - // a second full copy of all N values. - template - void segmented_sort_kway_for_each( - std::vector>& parts, Pred pred, Emit&& emit) - { - struct cursor + if (nonempty.empty()) { - std::size_t part; - std::size_t pos; - }; + return {}; + } + if (nonempty.size() == 1) + { + return HPX_MOVE(nonempty[0]); + } - auto order = [&](cursor const& a, cursor const& b) { - return pred(parts[b.part][b.pos], parts[a.part][a.pos]); - }; + std::vector merged = HPX_MOVE(nonempty[0]); + auto const sync_policy = + hpx::execution::experimental::to_non_task(policy); + for (std::size_t i = 1; i != nonempty.size(); ++i) + { + std::vector out(merged.size() + nonempty[i].size()); + hpx::merge(sync_policy, merged.begin(), merged.end(), + nonempty[i].begin(), nonempty[i].end(), out.begin(), pred); + merged = HPX_MOVE(out); + } + return merged; + } - std::priority_queue, decltype(order)> heap( - order); + template + InIter segmented_sort_merge_on_host_seq(ExPolicy const& policy, + InIter first, InIter last_iter, + std::vector> const& runs, + std::size_t host, Comp&& comp, Proj&& proj) + { + using value_type = std::iterator_traits::value_type; + + std::size_t const n = runs.size(); + std::vector> parts(n); + std::vector counts(n); + for (std::size_t i = 0; i != n; ++i) + { + counts[i] = + static_cast(runs[i].last - runs[i].first); + } - for (std::size_t i = 0; i != parts.size(); ++i) + for (std::size_t i = 0; i != n; ++i) { - if (!parts[i].empty()) + if (i == host) { - heap.push(cursor{i, 0}); + parts[i] = std::vector( + static_cast(std::distance(first, last_iter))); + hpx::copy(hpx::execution::experimental::to_non_task(policy), + first, last_iter, parts[i].begin()); + } + else + { + parts[i] = dispatch(runs[i].id, + segmented_fetch_values(), policy, + std::true_type(), runs[i].first, runs[i].last); } } - while (!heap.empty()) + util::compare_projected pred(comp, proj); + std::vector merged = + segmented_sort_merge_parts(policy, parts, pred); + + std::size_t offset = 0; + for (std::size_t dest = 0; dest != n; ++dest) { - cursor const c = heap.top(); - heap.pop(); - emit(HPX_MOVE(parts[c.part][c.pos])); - std::size_t const next = c.pos + 1; - if (next != parts[c.part].size()) + auto const piece_first = merged.begin() + + static_cast(offset); + auto const piece_last = piece_first + + static_cast(counts[dest]); + + if (dest == host) { - heap.push(cursor{c.part, next}); + hpx::copy(hpx::execution::experimental::to_non_task(policy), + piece_first, piece_last, first); } else { - parts[c.part].clear(); - parts[c.part].shrink_to_fit(); + std::vector piece(piece_first, piece_last); + dispatch(runs[dest].id, segmented_store_values(), + policy, std::true_type(), runs[dest].first, + runs[dest].last, piece); } + offset += counts[dest]; } + + return last_iter; } - template - InIter segmented_sort_merge_on_host(ExPolicy const& policy, InIter first, - Sent last, std::vector> const& runs, - std::size_t host, Comp&& comp, Proj&& proj, IsSeq) + template + InIter segmented_sort_merge_on_host_par(ExPolicy const& policy, + InIter first, InIter last_iter, + std::vector> const& runs, + std::size_t host, Comp&& comp, Proj&& proj) { - using value_type = typename std::iterator_traits::value_type; + using value_type = std::iterator_traits::value_type; - auto last_iter = advance_to_sentinel(first, last); std::size_t const n = runs.size(); std::vector> parts(n); std::vector counts(n); for (std::size_t i = 0; i != n; ++i) { - counts[i] = static_cast(runs[i].last - runs[i].first); + counts[i] = + static_cast(runs[i].last - runs[i].first); } - if constexpr (IsSeq::value) + std::vector>> fetches; + fetches.reserve(n); + std::vector remote; + remote.reserve(n); + + parts[host] = std::vector( + static_cast(std::distance(first, last_iter))); + hpx::copy(hpx::execution::experimental::to_non_task(policy), first, + last_iter, parts[host].begin()); + + for (std::size_t i = 0; i != n; ++i) { - for (std::size_t i = 0; i != n; ++i) + if (i == host) { - if (i == host) - { - parts[i] = std::vector(first, last_iter); - } - else - { - parts[i] = dispatch(runs[i].id, - segmented_fetch_values(), - hpx::execution::seq, std::true_type(), runs[i].first, - runs[i].last); - } + continue; } + remote.push_back(i); + fetches.push_back(dispatch_async(runs[i].id, + segmented_fetch_values(), policy, std::false_type(), + runs[i].first, runs[i].last)); } - else - { - std::vector>> fetches; - fetches.reserve(n); - std::vector remote; - remote.reserve(n); - parts[host] = std::vector(first, last_iter); - for (std::size_t i = 0; i != n; ++i) - { - if (i == host) - { - continue; - } - remote.push_back(i); - fetches.push_back(dispatch_async(runs[i].id, - segmented_fetch_values(), hpx::execution::seq, - std::true_type(), runs[i].first, runs[i].last)); - } - - segmented_sort_wait_all(fetches); - for (std::size_t j = 0; j != remote.size(); ++j) - { - parts[remote[j]] = fetches[j].get(); - } + segmented_sort_wait_all(fetches); + for (std::size_t j = 0; j != remote.size(); ++j) + { + parts[remote[j]] = fetches[j].get(); } - std::size_t dest = 0; - std::size_t filled = 0; - auto out = first; - std::vector piece; + util::compare_projected pred(comp, proj); + std::vector merged = + segmented_sort_merge_parts(policy, parts, pred); + std::vector> stores; + stores.reserve(remote.size()); + + std::size_t offset = 0; + for (std::size_t dest = 0; dest != n; ++dest) + { + auto const piece_first = merged.begin() + + static_cast(offset); + auto const piece_last = piece_first + + static_cast(counts[dest]); - auto emit = [&](value_type&& value) { if (dest == host) { - *out = HPX_MOVE(value); - ++out; + hpx::copy(hpx::execution::experimental::to_non_task(policy), + piece_first, piece_last, first); } else { - if (piece.empty()) - { - piece.reserve(counts[dest]); - } - piece.push_back(HPX_MOVE(value)); - } - - if (++filled != counts[dest]) - { - return; + std::vector piece(piece_first, piece_last); + stores.push_back(dispatch_async(runs[dest].id, + segmented_store_values(), policy, + std::false_type(), runs[dest].first, runs[dest].last, + HPX_MOVE(piece))); } - - if (dest != host) - { - if constexpr (IsSeq::value) - { - dispatch(runs[dest].id, segmented_store_values(), - hpx::execution::seq, std::true_type(), runs[dest].first, - runs[dest].last, piece); - } - else - { - stores.push_back(dispatch_async(runs[dest].id, - segmented_store_values(), - hpx::execution::seq, std::true_type(), runs[dest].first, - runs[dest].last, HPX_MOVE(piece))); - } - piece = {}; - } - - ++dest; - filled = 0; - }; - - util::compare_projected pred(comp, proj); - segmented_sort_kway_for_each(parts, pred, emit); - parts.clear(); - - if constexpr (!IsSeq::value) - { - segmented_sort_wait_all(stores); + offset += counts[dest]; } - HPX_UNUSED(policy); + segmented_sort_wait_all(stores); return last_iter; } @@ -398,9 +414,10 @@ namespace hpx::parallel::detail { std::vector> const& runs, std::size_t host, Comp&& comp, Proj&& proj) { - return segmented_sort_merge_on_host(HPX_FORWARD(ExPolicy, policy), - first, last, runs, host, HPX_FORWARD(Comp, comp), - HPX_FORWARD(Proj, proj), std::true_type{}); + auto last_iter = advance_to_sentinel(first, last); + return segmented_sort_merge_on_host_seq( + HPX_FORWARD(ExPolicy, policy), first, last_iter, runs, host, + HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); } template > const& runs, std::size_t host, Comp&& comp, Proj&& proj) { - return segmented_sort_merge_on_host(HPX_FORWARD(ExPolicy, policy), - first, last, runs, host, HPX_FORWARD(Comp, comp), - HPX_FORWARD(Proj, proj), std::false_type{}); + auto last_iter = advance_to_sentinel(first, last); + return segmented_sort_merge_on_host_par( + HPX_FORWARD(ExPolicy, policy), first, last_iter, runs, host, + HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); } }; @@ -450,9 +468,9 @@ namespace hpx::parallel::detail { } // Fetch each remote sorted run once onto the locality that already - // holds the largest run, k-way merge there, and write only the remote - // pieces back. That keeps traffic O(N) and avoids a full gather to the - // caller. + // holds the largest run, merge there with hpx::merge, and write only + // the remote pieces back. That keeps traffic O(N) and avoids a full + // gather to the caller. template void segmented_sort_merge_runs(ExPolicy const& policy, From 050d7e61fbf0b7bdad8ca13f2ab66b192c61abe1 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Thu, 24 Sep 2026 19:27:07 +0530 Subject: [PATCH 11/37] Address further segmented-sort review feedback. Signed-off-by: the-ivii --- .../segmented_algorithms/detail/dispatch.hpp | 2 + .../parallel/segmented_algorithms/sort.hpp | 321 ++++++++++++------ 2 files changed, 227 insertions(+), 96 deletions(-) diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp index 3512d8664774..b90362090c35 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp @@ -327,6 +327,8 @@ namespace hpx::parallel::detail { f.get_exception_ptr(), errors); // NOLINT(bugprone-use-after-move) + // NOLINTNEXTLINE(bugprone-use-after-move) + HPX_ASSERT(errors.empty()); if (!errors.empty()) { throw exception_list(HPX_MOVE(errors)); diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp index a4445c768295..9f2359fecb42 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp @@ -11,7 +11,9 @@ #include #include #include +#include +#include #include #include @@ -20,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -46,11 +49,12 @@ namespace hpx::parallel::detail { Comp&& comp, Proj&& proj) { auto last_iter = advance_to_sentinel(first, last); - // Sort via .base() so Apple libc++'s operator[] path does not - // hit iterator_facade's brackets proxy. Fold proj into the - // comparator: hpx::sort's CPO does not take a projection. - hpx::sort(hpx::execution::experimental::to_non_task(policy), - first.base(), last_iter.base(), + // Unwrap to the local raw iterator (same path as dispatch). Fold + // proj into the comparator: hpx::sort's CPO has no projection. + using local_traits = + hpx::traits::segmented_local_iterator_traits; + hpx::sort(HPX_FORWARD(ExPolicy, policy), local_traits::local(first), + local_traits::local(last_iter), util::compare_projected(comp, proj)); return last_iter; } @@ -85,8 +89,7 @@ namespace hpx::parallel::detail { segment_iterator send = traits::segment(last); std::vector runs; - runs.reserve( - static_cast(std::distance(sit, send)) + 1); + runs.reserve(static_cast(std::distance(sit, send)) + 1); if (sit == send) { @@ -142,11 +145,11 @@ namespace hpx::parallel::detail { static std::vector sequential( ExPolicy&& policy, InIter first, Sent last) { - auto last_iter = advance_to_sentinel(first, last); - std::vector result(static_cast( - std::distance(first, last_iter))); - hpx::copy(hpx::execution::experimental::to_non_task(policy), - first, last_iter, result.begin()); + auto last_iter = first; + auto const size = advance_and_get_distance(last_iter, last); + std::vector result(static_cast(size)); + hpx::copy(HPX_FORWARD(ExPolicy, policy), first, last_iter, + result.begin()); return result; } @@ -154,8 +157,7 @@ namespace hpx::parallel::detail { static std::vector parallel( ExPolicy&& policy, InIter first, Sent last) { - return sequential( - HPX_FORWARD(ExPolicy, policy), first, last); + return sequential(HPX_FORWARD(ExPolicy, policy), first, last); } }; @@ -169,12 +171,11 @@ namespace hpx::parallel::detail { } template - static InIter sequential(ExPolicy&& policy, InIter first, Sent, - std::vector const& values) + static InIter sequential( + ExPolicy&& policy, InIter first, Sent, std::vector const& values) { - return hpx::copy( - hpx::execution::experimental::to_non_task(policy), - values.begin(), values.end(), first); + return hpx::copy(HPX_FORWARD(ExPolicy, policy), values.begin(), + values.end(), first); } template @@ -202,54 +203,96 @@ namespace hpx::parallel::detail { } } + // Select the largest run. Order indices by run length so lower_bound can + // locate the first maximum-sized run in O(log P). template std::size_t segmented_sort_host_index( std::vector> const& runs) { - auto const it = std::max_element(runs.begin(), runs.end(), - [](auto const& a, auto const& b) { - return (a.last - a.first) < (b.last - b.first); + std::size_t const n = runs.size(); + std::vector order(n); + std::iota(order.begin(), order.end(), std::size_t{0}); + + auto const run_size = [&](std::size_t i) { + return runs[i].last - runs[i].first; + }; + + std::sort( + order.begin(), order.end(), [&](std::size_t a, std::size_t b) { + return run_size(a) < run_size(b); }); - return static_cast(std::distance(runs.begin(), it)); + + auto const max_size = run_size(order.back()); + auto const it = std::lower_bound(order.begin(), order.end(), max_size, + [&](std::size_t idx, auto sz) { return run_size(idx) < sz; }); + return *it; } - // Pairwise-merge sorted runs with hpx::merge. Peak temporary storage - // is one merged buffer of size N. + // Tree-merge sorted runs with hpx::merge. Pre-size the output buffers and + // pair-reduce so the merge depth is O(log P) when P > 3. template - std::vector segmented_sort_merge_parts(ExPolicy&& policy, - std::vector>& parts, Pred pred) + std::vector segmented_sort_merge_parts( + ExPolicy const& policy, std::vector>& parts, Pred pred) { - std::vector> nonempty; - nonempty.reserve(parts.size()); + std::vector> level; + level.reserve(parts.size()); + std::size_t total = 0; for (auto& part : parts) { if (!part.empty()) { - nonempty.push_back(HPX_MOVE(part)); + total += part.size(); + level.push_back(HPX_MOVE(part)); } } parts.clear(); - if (nonempty.empty()) + if (level.empty()) { return {}; } - if (nonempty.size() == 1) + if (level.size() == 1) { - return HPX_MOVE(nonempty[0]); + return HPX_MOVE(level[0]); } - std::vector merged = HPX_MOVE(nonempty[0]); - auto const sync_policy = - hpx::execution::experimental::to_non_task(policy); - for (std::size_t i = 1; i != nonempty.size(); ++i) + // Linear reduce for two or three runs; tree reduce otherwise. + if (level.size() <= 3) { - std::vector out(merged.size() + nonempty[i].size()); - hpx::merge(sync_policy, merged.begin(), merged.end(), - nonempty[i].begin(), nonempty[i].end(), out.begin(), pred); - merged = HPX_MOVE(out); + std::vector merged = HPX_MOVE(level[0]); + std::vector out; + out.reserve(total); + for (std::size_t i = 1; i != level.size(); ++i) + { + out.resize(merged.size() + level[i].size()); + hpx::merge(policy, merged.begin(), merged.end(), + level[i].begin(), level[i].end(), out.begin(), pred); + merged.swap(out); + } + return merged; + } + + while (level.size() > 1) + { + std::vector> next; + next.reserve((level.size() + 1) / 2); + + std::size_t i = 0; + for (; i + 1 < level.size(); i += 2) + { + std::vector out(level[i].size() + level[i + 1].size()); + hpx::merge(policy, level[i].begin(), level[i].end(), + level[i + 1].begin(), level[i + 1].end(), out.begin(), + pred); + next.push_back(HPX_MOVE(out)); + } + if (i < level.size()) + { + next.push_back(HPX_MOVE(level[i])); + } + level.swap(next); } - return merged; + return HPX_MOVE(level[0]); } template > parts(n); - std::vector counts(n); - for (std::size_t i = 0; i != n; ++i) - { - counts[i] = - static_cast(runs[i].last - runs[i].first); - } + std::vector counts(n); + hpx::id_type const here = hpx::find_here(); + using local_traits = + hpx::traits::segmented_local_iterator_traits; for (std::size_t i = 0; i != n; ++i) { + counts[i] = runs[i].last - runs[i].first; + if (i == host) + { + auto local_last = first; + auto const size = + advance_and_get_distance(local_last, last_iter); + parts[i] = + std::vector(static_cast(size)); + hpx::copy(policy, first, local_last, parts[i].begin()); + } + else if (runs[i].id == here) { parts[i] = std::vector( - static_cast(std::distance(first, last_iter))); - hpx::copy(hpx::execution::experimental::to_non_task(policy), - first, last_iter, parts[i].begin()); + static_cast(counts[i])); + hpx::copy(policy, local_traits::local(runs[i].first), + local_traits::local(runs[i].last), parts[i].begin()); } else { - parts[i] = dispatch(runs[i].id, - segmented_fetch_values(), policy, - std::true_type(), runs[i].first, runs[i].last); + parts[i] = + dispatch(runs[i].id, segmented_fetch_values(), + policy, std::true_type(), runs[i].first, runs[i].last); } } @@ -291,25 +343,27 @@ namespace hpx::parallel::detail { std::vector merged = segmented_sort_merge_parts(policy, parts, pred); - std::size_t offset = 0; + std::ptrdiff_t offset = 0; for (std::size_t dest = 0; dest != n; ++dest) { - auto const piece_first = merged.begin() + - static_cast(offset); - auto const piece_last = piece_first + - static_cast(counts[dest]); + auto const piece_first = merged.begin() + offset; + auto const piece_last = piece_first + counts[dest]; if (dest == host) { - hpx::copy(hpx::execution::experimental::to_non_task(policy), - piece_first, piece_last, first); + hpx::copy(policy, piece_first, piece_last, first); + } + else if (runs[dest].id == here) + { + hpx::copy(policy, piece_first, piece_last, + local_traits::local(runs[dest].first)); } else { std::vector piece(piece_first, piece_last); dispatch(runs[dest].id, segmented_store_values(), - policy, std::true_type(), runs[dest].first, - runs[dest].last, piece); + policy, std::true_type(), runs[dest].first, runs[dest].last, + piece); } offset += counts[dest]; } @@ -328,33 +382,45 @@ namespace hpx::parallel::detail { std::size_t const n = runs.size(); std::vector> parts(n); - std::vector counts(n); - for (std::size_t i = 0; i != n; ++i) - { - counts[i] = - static_cast(runs[i].last - runs[i].first); - } + std::vector counts(n); + hpx::id_type const here = hpx::find_here(); + using local_traits = + hpx::traits::segmented_local_iterator_traits; std::vector>> fetches; fetches.reserve(n); std::vector remote; remote.reserve(n); - parts[host] = std::vector( - static_cast(std::distance(first, last_iter))); - hpx::copy(hpx::execution::experimental::to_non_task(policy), first, - last_iter, parts[host].begin()); - + // Launch remote fetches first, then fill the host partition so the + // local copy overlaps outstanding RPCs. for (std::size_t i = 0; i != n; ++i) { + counts[i] = runs[i].last - runs[i].first; if (i == host) { continue; } + if (runs[i].id == here) + { + parts[i] = std::vector( + static_cast(counts[i])); + hpx::copy(policy, local_traits::local(runs[i].first), + local_traits::local(runs[i].last), parts[i].begin()); + continue; + } remote.push_back(i); - fetches.push_back(dispatch_async(runs[i].id, - segmented_fetch_values(), policy, std::false_type(), - runs[i].first, runs[i].last)); + fetches.push_back( + dispatch_async(runs[i].id, segmented_fetch_values(), + policy, std::false_type(), runs[i].first, runs[i].last)); + } + + { + auto local_last = first; + auto const size = advance_and_get_distance(local_last, last_iter); + parts[host] = + std::vector(static_cast(size)); + hpx::copy(policy, first, local_last, parts[host].begin()); } segmented_sort_wait_all(fetches); @@ -370,18 +436,23 @@ namespace hpx::parallel::detail { std::vector> stores; stores.reserve(remote.size()); - std::size_t offset = 0; + std::ptrdiff_t offset = 0; + std::ptrdiff_t host_offset = 0; + std::ptrdiff_t host_count = 0; for (std::size_t dest = 0; dest != n; ++dest) { - auto const piece_first = merged.begin() + - static_cast(offset); - auto const piece_last = piece_first + - static_cast(counts[dest]); + auto const piece_first = merged.begin() + offset; + auto const piece_last = piece_first + counts[dest]; if (dest == host) { - hpx::copy(hpx::execution::experimental::to_non_task(policy), - piece_first, piece_last, first); + host_offset = offset; + host_count = counts[dest]; + } + else if (runs[dest].id == here) + { + hpx::copy(policy, piece_first, piece_last, + local_traits::local(runs[dest].first)); } else { @@ -394,6 +465,10 @@ namespace hpx::parallel::detail { offset += counts[dest]; } + // Host write overlaps remote stores. + hpx::copy(policy, merged.begin() + host_offset, + merged.begin() + host_offset + host_count, first); + segmented_sort_wait_all(stores); return last_iter; } @@ -439,10 +514,22 @@ namespace hpx::parallel::detail { std::vector>& runs, Comp&& comp, Proj&& proj, std::true_type) { + using local_traits = + hpx::traits::segmented_local_iterator_traits; + for (auto const& run : runs) { - dispatch(run.id, segmented_local_sort(), policy, - std::true_type(), run.first, run.last, comp, proj); + if (run.id == hpx::find_here()) + { + hpx::sort(policy, local_traits::local(run.first), + local_traits::local(run.last), + util::compare_projected(comp, proj)); + } + else + { + dispatch(run.id, segmented_local_sort(), policy, + std::true_type(), run.first, run.last, comp, proj); + } } } @@ -453,15 +540,29 @@ namespace hpx::parallel::detail { Proj&& proj, std::false_type) { using forced_seq = std::false_type; + using local_traits = + hpx::traits::segmented_local_iterator_traits; std::vector> segments; segments.reserve(runs.size()); for (auto const& run : runs) { - segments.push_back( - dispatch_async(run.id, segmented_local_sort(), - policy, forced_seq(), run.first, run.last, comp, proj)); + if (run.id == hpx::find_here()) + { + segments.push_back(hpx::async([=, &comp, &proj]() { + hpx::sort(policy, local_traits::local(run.first), + local_traits::local(run.last), + util::compare_projected(comp, proj)); + return run.last; + })); + } + else + { + segments.push_back( + dispatch_async(run.id, segmented_local_sort(), + policy, forced_seq(), run.first, run.last, comp, proj)); + } } segmented_sort_wait_all(segments); @@ -483,9 +584,32 @@ namespace hpx::parallel::detail { } std::size_t const host = segmented_sort_host_index(runs); - dispatch(runs[host].id, segmented_sort_kway_merge(), policy, - is_seq, runs[host].first, runs[host].last, runs, host, - HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); + using local_traits = + hpx::traits::segmented_local_iterator_traits; + + if (runs[host].id == hpx::find_here()) + { + if constexpr (IsSeq::value) + { + segmented_sort_merge_on_host_seq(policy, + local_traits::local(runs[host].first), + local_traits::local(runs[host].last), runs, host, + HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); + } + else + { + segmented_sort_merge_on_host_par(policy, + local_traits::local(runs[host].first), + local_traits::local(runs[host].last), runs, host, + HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); + } + } + else + { + dispatch(runs[host].id, segmented_sort_kway_merge(), + policy, is_seq, runs[host].first, runs[host].last, runs, host, + HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); + } } template cmp(HPX_FORWARD(Comp, comp)); std::decay_t prj(HPX_FORWARD(Proj, proj)); + // Drop the task bit so nested hpx::sort/copy/merge stay synchronous + // while still honouring the caller's parallel/sequenced choice. + auto const sync_policy = + hpx::execution::experimental::to_non_task(policy); + if constexpr (hpx::is_async_execution_policy_v) { return result::get(hpx::async([=, runs = HPX_MOVE(runs)]() mutable { - segmented_sort_local_runs(policy, runs, cmp, prj, is_seq); - segmented_sort_merge_runs(policy, runs, cmp, prj, is_seq); + segmented_sort_local_runs(sync_policy, runs, cmp, prj, is_seq); + segmented_sort_merge_runs(sync_policy, runs, cmp, prj, is_seq); })); } else { - segmented_sort_local_runs(policy, runs, cmp, prj, is_seq); - segmented_sort_merge_runs(policy, runs, cmp, prj, is_seq); + segmented_sort_local_runs(sync_policy, runs, cmp, prj, is_seq); + segmented_sort_merge_runs(sync_policy, runs, cmp, prj, is_seq); return result::get(); } } From ee2765198018c7df7b40900c0ecf6a74e636043b Mon Sep 17 00:00:00 2001 From: the-ivii Date: Thu, 24 Sep 2026 22:24:20 +0530 Subject: [PATCH 12/37] Address remaining segmented-sort review feedback. Signed-off-by: the-ivii --- .../parallel/segmented_algorithms/sort.hpp | 157 +++++++++++------- 1 file changed, 99 insertions(+), 58 deletions(-) diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp index 9f2359fecb42..66a5b941d653 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp @@ -22,7 +22,6 @@ #include #include #include -#include #include #include #include @@ -53,8 +52,9 @@ namespace hpx::parallel::detail { // proj into the comparator: hpx::sort's CPO has no projection. using local_traits = hpx::traits::segmented_local_iterator_traits; - hpx::sort(HPX_FORWARD(ExPolicy, policy), local_traits::local(first), - local_traits::local(last_iter), + hpx::sort(hpx::execution::experimental::to_non_task( + HPX_FORWARD(ExPolicy, policy)), + local_traits::local(first), local_traits::local(last_iter), util::compare_projected(comp, proj)); return last_iter; } @@ -97,7 +97,7 @@ namespace hpx::parallel::detail { local_iterator end = traits::local(last); if (beg != end) { - runs.push_back(run_type{traits::get_id(sit), beg, end}); + runs.emplace_back(traits::get_id(sit), beg, end); } return runs; } @@ -106,7 +106,7 @@ namespace hpx::parallel::detail { local_iterator end = traits::end(sit); if (beg != end) { - runs.push_back(run_type{traits::get_id(sit), beg, end}); + runs.emplace_back(traits::get_id(sit), beg, end); } for (++sit; sit != send; ++sit) @@ -115,7 +115,7 @@ namespace hpx::parallel::detail { end = traits::end(sit); if (beg != end) { - runs.push_back(run_type{traits::get_id(sit), beg, end}); + runs.emplace_back(traits::get_id(sit), beg, end); } } @@ -123,7 +123,7 @@ namespace hpx::parallel::detail { end = traits::local(last); if (beg != end) { - runs.push_back(run_type{traits::get_id(sit), beg, end}); + runs.emplace_back(traits::get_id(sit), beg, end); } return runs; } @@ -148,8 +148,9 @@ namespace hpx::parallel::detail { auto last_iter = first; auto const size = advance_and_get_distance(last_iter, last); std::vector result(static_cast(size)); - hpx::copy(HPX_FORWARD(ExPolicy, policy), first, last_iter, - result.begin()); + hpx::copy(hpx::execution::experimental::to_non_task( + HPX_FORWARD(ExPolicy, policy)), + first, last_iter, result.begin()); return result; } @@ -174,8 +175,9 @@ namespace hpx::parallel::detail { static InIter sequential( ExPolicy&& policy, InIter first, Sent, std::vector const& values) { - return hpx::copy(HPX_FORWARD(ExPolicy, policy), values.begin(), - values.end(), first); + return hpx::copy(hpx::execution::experimental::to_non_task( + HPX_FORWARD(ExPolicy, policy)), + values.begin(), values.end(), first); } template @@ -203,33 +205,21 @@ namespace hpx::parallel::detail { } } - // Select the largest run. Order indices by run length so lower_bound can - // locate the first maximum-sized run in O(log P). + // Select the largest run by scanning the runs vector directly. template std::size_t segmented_sort_host_index( std::vector> const& runs) { - std::size_t const n = runs.size(); - std::vector order(n); - std::iota(order.begin(), order.end(), std::size_t{0}); - - auto const run_size = [&](std::size_t i) { - return runs[i].last - runs[i].first; - }; - - std::sort( - order.begin(), order.end(), [&](std::size_t a, std::size_t b) { - return run_size(a) < run_size(b); + auto const it = std::max_element( + runs.begin(), runs.end(), [](auto const& a, auto const& b) { + return (a.last - a.first) < (b.last - b.first); }); - - auto const max_size = run_size(order.back()); - auto const it = std::lower_bound(order.begin(), order.end(), max_size, - [&](std::size_t idx, auto sz) { return run_size(idx) < sz; }); - return *it; + return static_cast(std::distance(runs.begin(), it)); } - // Tree-merge sorted runs with hpx::merge. Pre-size the output buffers and - // pair-reduce so the merge depth is O(log P) when P > 3. + // Tree-merge sorted runs with hpx::merge. Reuse level/next and a single + // merge buffer so allocations stay bounded; pair-reduce so the merge + // depth is O(log P) when P > 3. template std::vector segmented_sort_merge_parts( ExPolicy const& policy, std::vector>& parts, Pred pred) @@ -256,12 +246,13 @@ namespace hpx::parallel::detail { return HPX_MOVE(level[0]); } + std::vector out; + out.reserve(total); + // Linear reduce for two or three runs; tree reduce otherwise. if (level.size() <= 3) { std::vector merged = HPX_MOVE(level[0]); - std::vector out; - out.reserve(total); for (std::size_t i = 1; i != level.size(); ++i) { out.resize(merged.size() + level[i].size()); @@ -272,25 +263,47 @@ namespace hpx::parallel::detail { return merged; } + std::size_t max_pair = 0; + for (std::size_t i = 0; i + 1 < level.size(); i += 2) + { + max_pair = + (std::max) (max_pair, level[i].size() + level[i + 1].size()); + } + out.resize(max_pair); + + std::vector> next; + next.reserve((level.size() + 1) / 2); + while (level.size() > 1) { - std::vector> next; - next.reserve((level.size() + 1) / 2); + std::size_t const needed = (level.size() + 1) / 2; + if (next.capacity() < needed) + { + next.reserve(needed); + } + next.clear(); + std::size_t max_next_pair = 0; std::size_t i = 0; for (; i + 1 < level.size(); i += 2) { - std::vector out(level[i].size() + level[i + 1].size()); + auto const pair_size = level[i].size() + level[i + 1].size(); + max_next_pair = (std::max) (max_next_pair, pair_size); + out.resize(pair_size); hpx::merge(policy, level[i].begin(), level[i].end(), level[i + 1].begin(), level[i + 1].end(), out.begin(), pred); - next.push_back(HPX_MOVE(out)); + next.emplace_back(out.begin(), out.end()); } if (i < level.size()) { next.push_back(HPX_MOVE(level[i])); } level.swap(next); + if (max_next_pair > out.capacity()) + { + out.reserve(max_next_pair); + } } return HPX_MOVE(level[0]); } @@ -391,9 +404,11 @@ namespace hpx::parallel::detail { fetches.reserve(n); std::vector remote; remote.reserve(n); + std::vector local_parts; + local_parts.reserve(n); - // Launch remote fetches first, then fill the host partition so the - // local copy overlaps outstanding RPCs. + // Launch remote fetches first; co-located and host copies run after + // so they overlap outstanding RPCs. for (std::size_t i = 0; i != n; ++i) { counts[i] = runs[i].last - runs[i].first; @@ -403,10 +418,7 @@ namespace hpx::parallel::detail { } if (runs[i].id == here) { - parts[i] = std::vector( - static_cast(counts[i])); - hpx::copy(policy, local_traits::local(runs[i].first), - local_traits::local(runs[i].last), parts[i].begin()); + local_parts.push_back(i); continue; } remote.push_back(i); @@ -423,6 +435,14 @@ namespace hpx::parallel::detail { hpx::copy(policy, first, local_last, parts[host].begin()); } + for (std::size_t const i : local_parts) + { + parts[i] = + std::vector(static_cast(counts[i])); + hpx::copy(policy, local_traits::local(runs[i].first), + local_traits::local(runs[i].last), parts[i].begin()); + } + segmented_sort_wait_all(fetches); for (std::size_t j = 0; j != remote.size(); ++j) { @@ -436,14 +456,20 @@ namespace hpx::parallel::detail { std::vector> stores; stores.reserve(remote.size()); + struct local_piece + { + std::size_t dest; + std::ptrdiff_t offset; + std::ptrdiff_t count; + }; + std::vector local_stores; + local_stores.reserve(local_parts.size()); + std::ptrdiff_t offset = 0; std::ptrdiff_t host_offset = 0; std::ptrdiff_t host_count = 0; for (std::size_t dest = 0; dest != n; ++dest) { - auto const piece_first = merged.begin() + offset; - auto const piece_last = piece_first + counts[dest]; - if (dest == host) { host_offset = offset; @@ -451,11 +477,12 @@ namespace hpx::parallel::detail { } else if (runs[dest].id == here) { - hpx::copy(policy, piece_first, piece_last, - local_traits::local(runs[dest].first)); + local_stores.push_back(local_piece{dest, offset, counts[dest]}); } else { + auto const piece_first = merged.begin() + offset; + auto const piece_last = piece_first + counts[dest]; std::vector piece(piece_first, piece_last); stores.push_back(dispatch_async(runs[dest].id, segmented_store_values(), policy, @@ -465,9 +492,15 @@ namespace hpx::parallel::detail { offset += counts[dest]; } - // Host write overlaps remote stores. + // Host and co-located writes overlap remote stores. hpx::copy(policy, merged.begin() + host_offset, merged.begin() + host_offset + host_count, first); + for (auto const& lp : local_stores) + { + hpx::copy(policy, merged.begin() + lp.offset, + merged.begin() + lp.offset + lp.count, + local_traits::local(runs[lp.dest].first)); + } segmented_sort_wait_all(stores); return last_iter; @@ -516,10 +549,11 @@ namespace hpx::parallel::detail { { using local_traits = hpx::traits::segmented_local_iterator_traits; + hpx::id_type const here = hpx::find_here(); for (auto const& run : runs) { - if (run.id == hpx::find_here()) + if (run.id == here) { hpx::sort(policy, local_traits::local(run.first), local_traits::local(run.last), @@ -542,20 +576,18 @@ namespace hpx::parallel::detail { using forced_seq = std::false_type; using local_traits = hpx::traits::segmented_local_iterator_traits; + hpx::id_type const here = hpx::find_here(); std::vector> segments; segments.reserve(runs.size()); + std::vector const*> local_runs; + local_runs.reserve(runs.size()); for (auto const& run : runs) { - if (run.id == hpx::find_here()) + if (run.id == here) { - segments.push_back(hpx::async([=, &comp, &proj]() { - hpx::sort(policy, local_traits::local(run.first), - local_traits::local(run.last), - util::compare_projected(comp, proj)); - return run.last; - })); + local_runs.push_back(&run); } else { @@ -565,6 +597,14 @@ namespace hpx::parallel::detail { } } + // Local sorts run synchronously while remotes are in flight. + for (auto const* run : local_runs) + { + hpx::sort(policy, local_traits::local(run->first), + local_traits::local(run->last), + util::compare_projected(comp, proj)); + } + segmented_sort_wait_all(segments); } @@ -586,8 +626,9 @@ namespace hpx::parallel::detail { std::size_t const host = segmented_sort_host_index(runs); using local_traits = hpx::traits::segmented_local_iterator_traits; + hpx::id_type const here = hpx::find_here(); - if (runs[host].id == hpx::find_here()) + if (runs[host].id == here) { if constexpr (IsSeq::value) { From 809b2c7c3b5ae3720160d0630b679b3c203b2adc Mon Sep 17 00:00:00 2001 From: the-ivii Date: Thu, 24 Sep 2026 22:43:24 +0530 Subject: [PATCH 13/37] Include hpx/assert.hpp for HPX_ASSERT in segmented dispatch. Signed-off-by: the-ivii --- .../hpx/parallel/segmented_algorithms/detail/dispatch.hpp | 1 + 1 file changed, 1 insertion(+) diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp index b90362090c35..39285b3c2c70 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp @@ -8,6 +8,7 @@ #pragma once #include +#include #include #include #include From e3f2c501e670244296919f28cd584a2b5b800648 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Fri, 25 Sep 2026 03:18:40 +0530 Subject: [PATCH 14/37] Fix sequential dispatch assert polarity for remote exceptions. Signed-off-by: the-ivii --- .../parallel/segmented_algorithms/detail/dispatch.hpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp index 39285b3c2c70..30b4333d9295 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp @@ -328,12 +328,12 @@ namespace hpx::parallel::detail { f.get_exception_ptr(), errors); // NOLINT(bugprone-use-after-move) + // handle_remote_exceptions populates errors for non-bad_alloc + // failures; bad_alloc is rethrown from call() above. Assert the + // postcondition, then propagate as exception_list. // NOLINTNEXTLINE(bugprone-use-after-move) - HPX_ASSERT(errors.empty()); - if (!errors.empty()) - { - throw exception_list(HPX_MOVE(errors)); - } + HPX_ASSERT(!errors.empty()); + throw exception_list(HPX_MOVE(errors)); } return f.get(); } From 14d7699a29bd67f25cb1d16ba6d5700249376bed Mon Sep 17 00:00:00 2001 From: the-ivii Date: Sun, 27 Sep 2026 23:25:48 +0530 Subject: [PATCH 15/37] Simplify segmented sort and cover subrange edge cases Signed-off-by: the-ivii --- .../segmented_algorithms/detail/dispatch.hpp | 4 +- .../parallel/segmented_algorithms/sort.hpp | 133 +++++++----------- .../tests/unit/partitioned_vector_sort.cpp | 42 ++++++ 3 files changed, 95 insertions(+), 84 deletions(-) diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp index 30b4333d9295..fa86776ef3d7 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/detail/dispatch.hpp @@ -325,13 +325,11 @@ namespace hpx::parallel::detail { { std::list errors; parallel::util::detail::handle_remote_exceptions::call( - f.get_exception_ptr(), - errors); // NOLINT(bugprone-use-after-move) + f.get_exception_ptr(), errors); // handle_remote_exceptions populates errors for non-bad_alloc // failures; bad_alloc is rethrown from call() above. Assert the // postcondition, then propagate as exception_list. - // NOLINTNEXTLINE(bugprone-use-after-move) HPX_ASSERT(!errors.empty()); throw exception_list(HPX_MOVE(errors)); } diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp index 66a5b941d653..cf6f162ec73d 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp @@ -11,15 +11,14 @@ #include #include #include -#include +#include -#include #include -#include #include #include #include +#include #include #include #include @@ -55,7 +54,8 @@ namespace hpx::parallel::detail { hpx::sort(hpx::execution::experimental::to_non_task( HPX_FORWARD(ExPolicy, policy)), local_traits::local(first), local_traits::local(last_iter), - util::compare_projected(comp, proj)); + util::compare_projected( + HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj))); return last_iter; } @@ -75,6 +75,11 @@ namespace hpx::parallel::detail { hpx::id_type id{}; LocalIter first{}; LocalIter last{}; + + std::ptrdiff_t size() const + { + return last - first; + } }; template @@ -91,40 +96,27 @@ namespace hpx::parallel::detail { std::vector runs; runs.reserve(static_cast(std::distance(sit, send)) + 1); - if (sit == send) - { - local_iterator beg = traits::local(first); - local_iterator end = traits::local(last); + auto add_run = [&](segment_iterator const& segment, + local_iterator const& beg, + local_iterator const& end) { if (beg != end) { - runs.emplace_back(traits::get_id(sit), beg, end); + runs.emplace_back(traits::get_id(segment), beg, end); } - return runs; - } + }; - local_iterator beg = traits::local(first); - local_iterator end = traits::end(sit); - if (beg != end) + if (sit == send) { - runs.emplace_back(traits::get_id(sit), beg, end); + add_run(sit, traits::local(first), traits::local(last)); + return runs; } + add_run(sit, traits::local(first), traits::end(sit)); for (++sit; sit != send; ++sit) { - beg = traits::begin(sit); - end = traits::end(sit); - if (beg != end) - { - runs.emplace_back(traits::get_id(sit), beg, end); - } - } - - beg = traits::begin(sit); - end = traits::local(last); - if (beg != end) - { - runs.emplace_back(traits::get_id(sit), beg, end); + add_run(sit, traits::begin(sit), traits::end(sit)); } + add_run(sit, traits::begin(sit), traits::local(last)); return runs; } @@ -210,10 +202,8 @@ namespace hpx::parallel::detail { std::size_t segmented_sort_host_index( std::vector> const& runs) { - auto const it = std::max_element( - runs.begin(), runs.end(), [](auto const& a, auto const& b) { - return (a.last - a.first) < (b.last - b.first); - }); + auto const it = std::max_element(runs.begin(), runs.end(), + [](auto const& a, auto const& b) { return a.size() < b.size(); }); return static_cast(std::distance(runs.begin(), it)); } @@ -319,30 +309,22 @@ namespace hpx::parallel::detail { std::size_t const n = runs.size(); std::vector> parts(n); - std::vector counts(n); hpx::id_type const here = hpx::find_here(); using local_traits = hpx::traits::segmented_local_iterator_traits; for (std::size_t i = 0; i != n; ++i) { - counts[i] = runs[i].last - runs[i].first; - if (i == host) { - auto local_last = first; - auto const size = - advance_and_get_distance(local_last, last_iter); - parts[i] = - std::vector(static_cast(size)); - hpx::copy(policy, first, local_last, parts[i].begin()); + parts[i] = segmented_fetch_values::sequential( + policy, first, last_iter); } else if (runs[i].id == here) { - parts[i] = std::vector( - static_cast(counts[i])); - hpx::copy(policy, local_traits::local(runs[i].first), - local_traits::local(runs[i].last), parts[i].begin()); + parts[i] = segmented_fetch_values::sequential(policy, + local_traits::local(runs[i].first), + local_traits::local(runs[i].last)); } else { @@ -352,15 +334,16 @@ namespace hpx::parallel::detail { } } - util::compare_projected pred(comp, proj); + util::compare_projected pred( + HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); std::vector merged = - segmented_sort_merge_parts(policy, parts, pred); + segmented_sort_merge_parts(policy, parts, std::ref(pred)); std::ptrdiff_t offset = 0; for (std::size_t dest = 0; dest != n; ++dest) { auto const piece_first = merged.begin() + offset; - auto const piece_last = piece_first + counts[dest]; + auto const piece_last = piece_first + runs[dest].size(); if (dest == host) { @@ -378,7 +361,7 @@ namespace hpx::parallel::detail { policy, std::true_type(), runs[dest].first, runs[dest].last, piece); } - offset += counts[dest]; + offset += runs[dest].size(); } return last_iter; @@ -395,7 +378,6 @@ namespace hpx::parallel::detail { std::size_t const n = runs.size(); std::vector> parts(n); - std::vector counts(n); hpx::id_type const here = hpx::find_here(); using local_traits = hpx::traits::segmented_local_iterator_traits; @@ -411,7 +393,6 @@ namespace hpx::parallel::detail { // so they overlap outstanding RPCs. for (std::size_t i = 0; i != n; ++i) { - counts[i] = runs[i].last - runs[i].first; if (i == host) { continue; @@ -427,20 +408,14 @@ namespace hpx::parallel::detail { policy, std::false_type(), runs[i].first, runs[i].last)); } - { - auto local_last = first; - auto const size = advance_and_get_distance(local_last, last_iter); - parts[host] = - std::vector(static_cast(size)); - hpx::copy(policy, first, local_last, parts[host].begin()); - } + parts[host] = segmented_fetch_values::sequential( + policy, first, last_iter); for (std::size_t const i : local_parts) { - parts[i] = - std::vector(static_cast(counts[i])); - hpx::copy(policy, local_traits::local(runs[i].first), - local_traits::local(runs[i].last), parts[i].begin()); + parts[i] = segmented_fetch_values::sequential(policy, + local_traits::local(runs[i].first), + local_traits::local(runs[i].last)); } segmented_sort_wait_all(fetches); @@ -449,9 +424,10 @@ namespace hpx::parallel::detail { parts[remote[j]] = fetches[j].get(); } - util::compare_projected pred(comp, proj); + util::compare_projected pred( + HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); std::vector merged = - segmented_sort_merge_parts(policy, parts, pred); + segmented_sort_merge_parts(policy, parts, std::ref(pred)); std::vector> stores; stores.reserve(remote.size()); @@ -473,23 +449,23 @@ namespace hpx::parallel::detail { if (dest == host) { host_offset = offset; - host_count = counts[dest]; + host_count = runs[dest].size(); } else if (runs[dest].id == here) { - local_stores.push_back(local_piece{dest, offset, counts[dest]}); + local_stores.emplace_back(dest, offset, runs[dest].size()); } else { auto const piece_first = merged.begin() + offset; - auto const piece_last = piece_first + counts[dest]; + auto const piece_last = piece_first + runs[dest].size(); std::vector piece(piece_first, piece_last); stores.push_back(dispatch_async(runs[dest].id, segmented_store_values(), policy, std::false_type(), runs[dest].first, runs[dest].last, HPX_MOVE(piece))); } - offset += counts[dest]; + offset += runs[dest].size(); } // Host and co-located writes overlap remote stores. @@ -547,17 +523,14 @@ namespace hpx::parallel::detail { std::vector>& runs, Comp&& comp, Proj&& proj, std::true_type) { - using local_traits = - hpx::traits::segmented_local_iterator_traits; hpx::id_type const here = hpx::find_here(); for (auto const& run : runs) { if (run.id == here) { - hpx::sort(policy, local_traits::local(run.first), - local_traits::local(run.last), - util::compare_projected(comp, proj)); + segmented_local_sort::sequential( + policy, run.first, run.last, comp, proj); } else { @@ -574,20 +547,19 @@ namespace hpx::parallel::detail { Proj&& proj, std::false_type) { using forced_seq = std::false_type; - using local_traits = - hpx::traits::segmented_local_iterator_traits; hpx::id_type const here = hpx::find_here(); std::vector> segments; segments.reserve(runs.size()); - std::vector const*> local_runs; + std::vector const>> + local_runs; local_runs.reserve(runs.size()); for (auto const& run : runs) { if (run.id == here) { - local_runs.push_back(&run); + local_runs.emplace_back(run); } else { @@ -598,11 +570,10 @@ namespace hpx::parallel::detail { } // Local sorts run synchronously while remotes are in flight. - for (auto const* run : local_runs) + for (segmented_sort_run const& run : local_runs) { - hpx::sort(policy, local_traits::local(run->first), - local_traits::local(run->last), - util::compare_projected(comp, proj)); + segmented_local_sort::sequential( + policy, run.first, run.last, comp, proj); } segmented_sort_wait_all(segments); diff --git a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp index b7ab012bd8f6..38456c109f2b 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include /////////////////////////////////////////////////////////////////////////////// @@ -285,6 +286,43 @@ void run_cases(std::vector& localities) test_sort_once(empty); } +template +void test_sort_subranges( + ExPolicy const& policy, std::vector const& localities) +{ + // Eight partitions put multiple partitions on each locality. The + // [3, 47) subrange spans five runs, exercising an odd merge tree. + // [33, 77) selects a remote merge host with two or four localities. + hpx::partitioned_vector values( + 80, 0, hpx::container_layout(8, localities)); + std::pair const ranges[] = { + {0, 0}, {3, 4}, {2, 7}, {3, 10}, {10, 20}, {3, 47}, {33, 77}, {0, 80}}; + + for (auto const& [begin, end] : ranges) + { + initialize_mixed_n(values, 80); + auto expected = copy_values(values); + std::sort(expected.begin() + begin, expected.begin() + end, + std::greater{}); + + if constexpr (hpx::is_async_execution_policy_v) + { + hpx::sort(policy, values.begin() + begin, values.begin() + end, + std::greater{}) + .get(); + } + else + { + hpx::sort(policy, values.begin() + begin, values.begin() + end, + std::greater{}); + } + + // Comparing the whole vector also checks that values outside the + // requested subrange remain unchanged. + HPX_TEST(copy_values(values) == expected); + } +} + /////////////////////////////////////////////////////////////////////////////// int main() { @@ -293,6 +331,10 @@ int main() run_cases(localities); test_sort_large(localities); test_sort_throwing(localities); + test_sort_subranges(hpx::execution::seq, localities); + test_sort_subranges(hpx::execution::par, localities); + test_sort_subranges(hpx::execution::seq(hpx::execution::task), localities); + test_sort_subranges(hpx::execution::par(hpx::execution::task), localities); return hpx::util::report_errors(); } #endif From d0448272d9ced9f68f28e528106c037b91f88358 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Mon, 28 Sep 2026 01:53:33 +0530 Subject: [PATCH 16/37] Batch remote accesses in the segmented sort test Signed-off-by: the-ivii --- .../tests/unit/partitioned_vector_sort.cpp | 49 ++++++++++--------- 1 file changed, 25 insertions(+), 24 deletions(-) diff --git a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp index 38456c109f2b..361de6929e7e 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -41,18 +42,25 @@ T make_sort_value(int i) } } +// Transfer test data per partition instead of issuing a synchronous remote +// request for every element during setup and verification. template std::vector copy_values(hpx::partitioned_vector const& values) { - std::vector result; - result.reserve(values.size()); - typename hpx::partitioned_vector::const_iterator it = values.begin(); - typename hpx::partitioned_vector::const_iterator end = values.end(); - for (/**/; it != end; ++it) - { - result.push_back(*it); - } - return result; + std::vector positions(values.size()); + std::iota(positions.begin(), positions.end(), std::size_t(0)); + return values.get_values(hpx::launch::sync, positions); +} + +template +void initialize_values(hpx::partitioned_vector& values, F make_value) +{ + std::vector positions(values.size()); + std::iota(positions.begin(), positions.end(), std::size_t(0)); + std::vector data(values.size()); + std::transform( + positions.begin(), positions.end(), data.begin(), make_value); + values.set_values(hpx::launch::sync, positions, data); } template @@ -88,41 +96,34 @@ void verify_sorted(hpx::partitioned_vector const& values, template void initialize_reverse(hpx::partitioned_vector& values) { - typename hpx::partitioned_vector::iterator it = values.begin(); - for (int i = 0; i < SIZE; ++i, ++it) - *it = make_sort_value(SIZE - i); + initialize_values( + values, [](int i) { return make_sort_value(SIZE - i); }); } template void initialize_mixed(hpx::partitioned_vector& values) { - typename hpx::partitioned_vector::iterator it = values.begin(); - for (int i = 0; i < SIZE; ++i, ++it) - *it = make_sort_value((i * 17 + 3) % SIZE); + initialize_values( + values, [](int i) { return make_sort_value((i * 17 + 3) % SIZE); }); } template void initialize_sorted(hpx::partitioned_vector& values) { - typename hpx::partitioned_vector::iterator it = values.begin(); - for (int i = 0; i < SIZE; ++i, ++it) - *it = make_sort_value(i); + initialize_values(values, [](int i) { return make_sort_value(i); }); } template void initialize_duplicates(hpx::partitioned_vector& values) { - typename hpx::partitioned_vector::iterator it = values.begin(); - for (int i = 0; i < SIZE; ++i, ++it) - *it = make_sort_value(i % 4); + initialize_values(values, [](int i) { return make_sort_value(i % 4); }); } template void initialize_mixed_n(hpx::partitioned_vector& values, int n) { - typename hpx::partitioned_vector::iterator it = values.begin(); - for (int i = 0; i < n; ++i, ++it) - *it = make_sort_value((i * 17 + 3) % n); + initialize_values( + values, [n](int i) { return make_sort_value((i * 17 + 3) % n); }); } struct throwing_less From b6d91cf067371642ebba6c6ec43f06296bdfa321 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Mon, 28 Sep 2026 16:12:37 +0530 Subject: [PATCH 17/37] Bound segmented sort merges and respect data locality Signed-off-by: the-ivii --- .../parallel/segmented_algorithms/sort.hpp | 783 +++++++++--------- 1 file changed, 383 insertions(+), 400 deletions(-) diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp index cf6f162ec73d..fc3e175a7930 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -21,6 +22,8 @@ #include #include #include +#include +#include #include #include #include @@ -73,6 +76,7 @@ namespace hpx::parallel::detail { struct segmented_sort_run { hpx::id_type id{}; + hpx::id_type locality{}; LocalIter first{}; LocalIter last{}; @@ -101,7 +105,9 @@ namespace hpx::parallel::detail { local_iterator const& end) { if (beg != end) { - runs.emplace_back(traits::get_id(segment), beg, end); + auto id = traits::get_id(segment); + auto locality = hpx::get_colocation_id(hpx::launch::sync, id); + runs.emplace_back(HPX_MOVE(id), HPX_MOVE(locality), beg, end); } }; @@ -120,508 +126,487 @@ namespace hpx::parallel::detail { return runs; } - template - struct segmented_fetch_values - : algorithm, - std::vector::value_type>> - { - using value_type = std::iterator_traits::value_type; + // Logical blocks have equal sizes except for the final block. They may + // span physical partitions, including clipped subrange endpoints. + inline constexpr std::size_t segmented_sort_max_block_size = 65536; - constexpr segmented_fetch_values() noexcept - : algorithm>( - "segmented_fetch_values") - { - } - - template - static std::vector sequential( - ExPolicy&& policy, InIter first, Sent last) - { - auto last_iter = first; - auto const size = advance_and_get_distance(last_iter, last); - std::vector result(static_cast(size)); - hpx::copy(hpx::execution::experimental::to_non_task( - HPX_FORWARD(ExPolicy, policy)), - first, last_iter, result.begin()); - return result; - } + template + using segmented_sort_block = std::vector>; - template - static std::vector parallel( - ExPolicy&& policy, InIter first, Sent last) + template + std::size_t segmented_sort_block_size( + segmented_sort_block const& block) + { + std::size_t size = 0; + for (auto const& run : block) { - return sequential(HPX_FORWARD(ExPolicy, policy), first, last); + size += static_cast(run.size()); } - }; + return size; + } - template - struct segmented_store_values - : algorithm, Iter> + // Multiple physical partitions on one locality should not increase the + // network depth. The cap bounds buffers when N / localities is large. + template + std::size_t segmented_sort_block_capacity( + segmented_sort_block const& runs) { - constexpr segmented_store_values() noexcept - : algorithm("segmented_store_values") + auto const total = segmented_sort_block_size(runs); + // A single bounded block avoids network stages for small ranges. + if (total <= segmented_sort_max_block_size) { + return total; } - - template - static InIter sequential( - ExPolicy&& policy, InIter first, Sent, std::vector const& values) + std::set localities; + for (auto const& run : runs) { - return hpx::copy(hpx::execution::experimental::to_non_task( - HPX_FORWARD(ExPolicy, policy)), - values.begin(), values.end(), first); + localities.insert(run.locality); } + auto const count = localities.size(); + return (std::min) (segmented_sort_max_block_size, + total / count + (total % count != 0)); + } - template - static InIter parallel(ExPolicy&& policy, InIter first, Sent last, - std::vector const& values) + template + auto segmented_sort_blocks( + segmented_sort_block const& runs, std::size_t block_size) + { + std::vector> blocks; + std::size_t remaining = 0; + for (auto const& run : runs) { - return sequential( - HPX_FORWARD(ExPolicy, policy), first, last, values); + auto first = run.first; + while (first != run.last) + { + if (remaining == 0) + { + blocks.emplace_back(); + remaining = block_size; + } + auto const count = (std::min) (remaining, + static_cast(run.last - first)); + auto last = first + static_cast(count); + blocks.back().emplace_back(run.id, run.locality, first, last); + first = last; + remaining -= count; + } } - }; + return blocks; + } - template - void segmented_sort_wait_all(std::vector>& fs) + // Choose the locality holding the most input for this operation, summing + // all participating pieces rather than selecting a single partition. + template + hpx::id_type segmented_sort_host( + segmented_sort_block const& left, + segmented_sort_block const& right) { - if (fs.empty()) + std::map sizes; + for (auto const& run : left) { - return; + sizes[run.locality] += static_cast(run.size()); } - - if (hpx::wait_all_nothrow(fs)) + for (auto const& run : right) { - std::list errors; - parallel::util::detail::handle_remote_exceptions::call( - fs, errors); + sizes[run.locality] += static_cast(run.size()); } + auto const host = std::max_element(sizes.begin(), sizes.end(), + [](auto const& a, auto const& b) { return a.second < b.second; }); + return host->first; } - // Select the largest run by scanning the runs vector directly. template - std::size_t segmented_sort_host_index( - std::vector> const& runs) + struct segmented_fetch_values + : algorithm, + std::vector::value_type>> { - auto const it = std::max_element(runs.begin(), runs.end(), - [](auto const& a, auto const& b) { return a.size() < b.size(); }); - return static_cast(std::distance(runs.begin(), it)); - } + using value_type = std::iterator_traits::value_type; - // Tree-merge sorted runs with hpx::merge. Reuse level/next and a single - // merge buffer so allocations stay bounded; pair-reduce so the merge - // depth is O(log P) when P > 3. - template - std::vector segmented_sort_merge_parts( - ExPolicy const& policy, std::vector>& parts, Pred pred) - { - std::vector> level; - level.reserve(parts.size()); - std::size_t total = 0; - for (auto& part : parts) - { - if (!part.empty()) - { - total += part.size(); - level.push_back(HPX_MOVE(part)); - } - } - parts.clear(); - - if (level.empty()) - { - return {}; - } - if (level.size() == 1) + constexpr segmented_fetch_values() noexcept + : algorithm>( + "segmented_fetch_values") { - return HPX_MOVE(level[0]); } - std::vector out; - out.reserve(total); - - // Linear reduce for two or three runs; tree reduce otherwise. - if (level.size() <= 3) + template + static std::vector sequential( + ExPolicy const&, segmented_sort_block const& runs) { - std::vector merged = HPX_MOVE(level[0]); - for (std::size_t i = 1; i != level.size(); ++i) + using traits = + hpx::traits::segmented_local_iterator_traits; + std::vector values; + values.reserve(segmented_sort_block_size(runs)); + for (auto const& run : runs) { - out.resize(merged.size() + level[i].size()); - hpx::merge(policy, merged.begin(), merged.end(), - level[i].begin(), level[i].end(), out.begin(), pred); - merged.swap(out); + values.insert(values.end(), traits::local(run.first), + traits::local(run.last)); } - return merged; + return values; } - std::size_t max_pair = 0; - for (std::size_t i = 0; i + 1 < level.size(); i += 2) + template + static std::vector parallel( + ExPolicy const& policy, segmented_sort_block const& runs) { - max_pair = - (std::max) (max_pair, level[i].size() + level[i + 1].size()); + return sequential(policy, runs); } - out.resize(max_pair); + }; - std::vector> next; - next.reserve((level.size() + 1) / 2); + template + struct segmented_store_values + : algorithm, bool> + { + using value_type = std::iterator_traits::value_type; - while (level.size() > 1) + constexpr segmented_store_values() noexcept + : algorithm("segmented_store_values") { - std::size_t const needed = (level.size() + 1) / 2; - if (next.capacity() < needed) - { - next.reserve(needed); - } - next.clear(); - - std::size_t max_next_pair = 0; - std::size_t i = 0; - for (; i + 1 < level.size(); i += 2) - { - auto const pair_size = level[i].size() + level[i + 1].size(); - max_next_pair = (std::max) (max_next_pair, pair_size); - out.resize(pair_size); - hpx::merge(policy, level[i].begin(), level[i].end(), - level[i + 1].begin(), level[i + 1].end(), out.begin(), - pred); - next.emplace_back(out.begin(), out.end()); - } - if (i < level.size()) - { - next.push_back(HPX_MOVE(level[i])); - } - level.swap(next); - if (max_next_pair > out.capacity()) - { - out.reserve(max_next_pair); - } } - return HPX_MOVE(level[0]); - } - - template - InIter segmented_sort_merge_on_host_seq(ExPolicy const& policy, - InIter first, InIter last_iter, - std::vector> const& runs, - std::size_t host, Comp&& comp, Proj&& proj) - { - using value_type = std::iterator_traits::value_type; - - std::size_t const n = runs.size(); - std::vector> parts(n); - hpx::id_type const here = hpx::find_here(); - using local_traits = - hpx::traits::segmented_local_iterator_traits; - for (std::size_t i = 0; i != n; ++i) + template + static bool sequential(ExPolicy const& policy, + segmented_sort_block const& runs, + std::vector values) { - if (i == host) + using traits = + hpx::traits::segmented_local_iterator_traits; + auto first = values.begin(); + for (auto const& run : runs) { - parts[i] = segmented_fetch_values::sequential( - policy, first, last_iter); - } - else if (runs[i].id == here) - { - parts[i] = segmented_fetch_values::sequential(policy, - local_traits::local(runs[i].first), - local_traits::local(runs[i].last)); - } - else - { - parts[i] = - dispatch(runs[i].id, segmented_fetch_values(), - policy, std::true_type(), runs[i].first, runs[i].last); + auto last = first + run.size(); + hpx::move(policy, first, last, traits::local(run.first)); + first = last; } + return true; } - util::compare_projected pred( - HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); - std::vector merged = - segmented_sort_merge_parts(policy, parts, std::ref(pred)); - - std::ptrdiff_t offset = 0; - for (std::size_t dest = 0; dest != n; ++dest) + template + static bool parallel(ExPolicy const& policy, + segmented_sort_block const& runs, + std::vector values) { - auto const piece_first = merged.begin() + offset; - auto const piece_last = piece_first + runs[dest].size(); + return sequential(policy, runs, HPX_MOVE(values)); + } + }; - if (dest == host) - { - hpx::copy(policy, piece_first, piece_last, first); - } - else if (runs[dest].id == here) + template + auto segmented_sort_fetch_block( + ExPolicy const& policy, segmented_sort_block const& block) + { + using value_type = std::iterator_traits::value_type; + using local_traits = + hpx::traits::segmented_local_iterator_traits; + std::vector values; + values.reserve(segmented_sort_block_size(block)); + auto const here = hpx::find_here(); + for (auto it = block.begin(); it != block.end();) + { + if (it->locality == here) { - hpx::copy(policy, piece_first, piece_last, - local_traits::local(runs[dest].first)); + values.insert(values.end(), local_traits::local(it->first), + local_traits::local(it->last)); + ++it; } else { - std::vector piece(piece_first, piece_last); - dispatch(runs[dest].id, segmented_store_values(), - policy, std::true_type(), runs[dest].first, runs[dest].last, - piece); + auto end = std::find_if(it, block.end(), [&](auto const& run) { + return run.locality != it->locality; + }); + // One action for consecutive pieces on the same locality. + segmented_sort_block pieces(it, end); + auto part = + dispatch(it->locality, segmented_fetch_values(), + policy, std::true_type(), HPX_MOVE(pieces)); + values.insert(values.end(), + std::make_move_iterator(part.begin()), + std::make_move_iterator(part.end())); + it = end; } - offset += runs[dest].size(); } - - return last_iter; + return values; } - template - InIter segmented_sort_merge_on_host_par(ExPolicy const& policy, - InIter first, InIter last_iter, - std::vector> const& runs, - std::size_t host, Comp&& comp, Proj&& proj) + template + Iter segmented_sort_store_block(ExPolicy const& policy, + segmented_sort_block const& block, Iter first) { - using value_type = std::iterator_traits::value_type; - - std::size_t const n = runs.size(); - std::vector> parts(n); - hpx::id_type const here = hpx::find_here(); + using value_type = std::iterator_traits::value_type; using local_traits = hpx::traits::segmented_local_iterator_traits; - - std::vector>> fetches; - fetches.reserve(n); - std::vector remote; - remote.reserve(n); - std::vector local_parts; - local_parts.reserve(n); - - // Launch remote fetches first; co-located and host copies run after - // so they overlap outstanding RPCs. - for (std::size_t i = 0; i != n; ++i) + auto const here = hpx::find_here(); + for (auto it = block.begin(); it != block.end();) { - if (i == host) + if (it->locality == here) { - continue; + auto last = first + it->size(); + hpx::move(policy, first, last, local_traits::local(it->first)); + first = last; + ++it; } - if (runs[i].id == here) + else { - local_parts.push_back(i); - continue; + auto end = std::find_if(it, block.end(), [&](auto const& run) { + return run.locality != it->locality; + }); + segmented_sort_block pieces(it, end); + auto last = first + + static_cast( + segmented_sort_block_size(pieces)); + std::vector values(std::make_move_iterator(first), + std::make_move_iterator(last)); + dispatch(it->locality, segmented_store_values(), + policy, std::true_type(), HPX_MOVE(pieces), + HPX_MOVE(values)); + first = last; + it = end; } - remote.push_back(i); - fetches.push_back( - dispatch_async(runs[i].id, segmented_fetch_values(), - policy, std::false_type(), runs[i].first, runs[i].last)); } + return first; + } - parts[host] = segmented_fetch_values::sequential( - policy, first, last_iter); - - for (std::size_t const i : local_parts) - { - parts[i] = segmented_fetch_values::sequential(policy, - local_traits::local(runs[i].first), - local_traits::local(runs[i].last)); - } + // Merge directly into the destination. There is no serial copy of the + // merged output into a second vector. + template + std::vector segmented_sort_merge_pair(ExPolicy const& policy, + std::vector const& left, std::vector const& right, Pred pred) + { + std::vector merged(left.size() + right.size()); + hpx::merge(policy, left.begin(), left.end(), right.begin(), right.end(), + merged.begin(), pred); + return merged; + } - segmented_sort_wait_all(fetches); - for (std::size_t j = 0; j != remote.size(); ++j) + template + struct segmented_sort_compare_split + : algorithm, bool> + { + constexpr segmented_sort_compare_split() noexcept + : algorithm( + "segmented_sort_compare_split") { - parts[remote[j]] = fetches[j].get(); } - util::compare_projected pred( - HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); - std::vector merged = - segmented_sort_merge_parts(policy, parts, std::ref(pred)); - - std::vector> stores; - stores.reserve(remote.size()); - - struct local_piece - { - std::size_t dest; - std::ptrdiff_t offset; - std::ptrdiff_t count; - }; - std::vector local_stores; - local_stores.reserve(local_parts.size()); - - std::ptrdiff_t offset = 0; - std::ptrdiff_t host_offset = 0; - std::ptrdiff_t host_count = 0; - for (std::size_t dest = 0; dest != n; ++dest) + template + static bool sequential(ExPolicy const& policy, + segmented_sort_block const& left, + segmented_sort_block const& right, Comp comp, Proj proj) { - if (dest == host) - { - host_offset = offset; - host_count = runs[dest].size(); - } - else if (runs[dest].id == here) + // Sorting one local piece needs no communication or copy buffer. + if (right.empty() && left.size() == 1) { - local_stores.emplace_back(dest, offset, runs[dest].size()); + segmented_local_sort::sequential( + policy, left[0].first, left[0].last, comp, proj); + return true; } - else + + using value_type = std::iterator_traits::value_type; + util::compare_projected pred(comp, proj); + std::vector output; { - auto const piece_first = merged.begin() + offset; - auto const piece_last = piece_first + runs[dest].size(); - std::vector piece(piece_first, piece_last); - stores.push_back(dispatch_async(runs[dest].id, - segmented_store_values(), policy, - std::false_type(), runs[dest].first, runs[dest].last, - HPX_MOVE(piece))); + auto left_values = segmented_sort_fetch_block(policy, left); + if (right.empty()) + { + hpx::sort(policy, left_values.begin(), left_values.end(), + std::ref(pred)); + output = HPX_MOVE(left_values); + } + else + { + auto right_values = + segmented_sort_fetch_block(policy, right); + if (!pred(right_values.front(), left_values.back())) + { + return true; + } + output = segmented_sort_merge_pair( + policy, left_values, right_values, std::ref(pred)); + } } - offset += runs[dest].size(); - } - - // Host and co-located writes overlap remote stores. - hpx::copy(policy, merged.begin() + host_offset, - merged.begin() + host_offset + host_count, first); - for (auto const& lp : local_stores) - { - hpx::copy(policy, merged.begin() + lp.offset, - merged.begin() + lp.offset + lp.count, - local_traits::local(runs[lp.dest].first)); - } - segmented_sort_wait_all(stores); - return last_iter; - } - - template - struct segmented_sort_kway_merge - : algorithm, Iter> - { - constexpr segmented_sort_kway_merge() noexcept - : algorithm( - "segmented_sort_kway_merge") - { - } - - template - static InIter sequential(ExPolicy&& policy, InIter first, Sent last, - std::vector> const& runs, - std::size_t host, Comp&& comp, Proj&& proj) - { - auto last_iter = advance_to_sentinel(first, last); - return segmented_sort_merge_on_host_seq( - HPX_FORWARD(ExPolicy, policy), first, last_iter, runs, host, - HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); + // Both inputs have been read completely before either is changed. + // Release the input buffers before allocating outbound pieces. + auto middle = + segmented_sort_store_block(policy, left, output.begin()); + segmented_sort_store_block(policy, right, middle); + return true; } - template - static InIter parallel(ExPolicy&& policy, InIter first, Sent last, - std::vector> const& runs, - std::size_t host, Comp&& comp, Proj&& proj) + template + static bool parallel(ExPolicy const& policy, + segmented_sort_block const& left, + segmented_sort_block const& right, Comp comp, Proj proj) { - auto last_iter = advance_to_sentinel(first, last); - return segmented_sort_merge_on_host_par( - HPX_FORWARD(ExPolicy, policy), first, last_iter, runs, host, - HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); + return sequential( + policy, left, right, HPX_MOVE(comp), HPX_MOVE(proj)); } }; - template - void segmented_sort_local_runs(ExPolicy const& policy, - std::vector>& runs, Comp&& comp, - Proj&& proj, std::true_type) - { - hpx::id_type const here = hpx::find_here(); + using segmented_sort_pair = std::pair; - for (auto const& run : runs) + // Batcher odd-even merge stages. With K blocks, O(log^2 K) stages trade + // additional communication rounds for bounded merge buffers. All + // comparisons are ascending, so a short final block and absent blocks + // behave as trailing infinities without constructing sentinel values or + // requiring a power-of-two size. + template + void segmented_sort_merge_stages(std::size_t count, F stage) + { + std::vector pairs; + pairs.reserve(count / 2); + for (std::size_t width = 1; width < count; width *= 2) { - if (run.id == here) + for (std::size_t stride = width; stride != 0; stride /= 2) { - segmented_local_sort::sequential( - policy, run.first, run.last, comp, proj); - } - else - { - dispatch(run.id, segmented_local_sort(), policy, - std::true_type(), run.first, run.last, comp, proj); + pairs.clear(); + for (std::size_t start = stride % width; start + stride < count; + start += 2 * stride) + { + for (std::size_t i = 0; + i < stride && start + i + stride < count; ++i) + { + auto const left = start + i; + auto const right = left + stride; + if (left / (2 * width) == right / (2 * width)) + { + pairs.emplace_back(left, right); + } + } + } + stage(pairs); } } } template - void segmented_sort_local_runs(ExPolicy const& policy, - std::vector>& runs, Comp&& comp, - Proj&& proj, std::false_type) + typename Proj, typename IsSeq> + void segmented_sort_stage(ExPolicy const& policy, + std::vector> const& blocks, + std::vector const& pairs, Comp const& comp, + Proj const& proj, IsSeq is_seq) { - using forced_seq = std::false_type; - hpx::id_type const here = hpx::find_here(); - - std::vector> segments; - segments.reserve(runs.size()); - std::vector const>> - local_runs; - local_runs.reserve(runs.size()); + using operation = segmented_sort_compare_split; + segmented_sort_block const empty; + auto const here = hpx::find_here(); + auto right_block = [&](segmented_sort_pair pair) -> auto const& { + return pair.first == pair.second ? empty : blocks[pair.second]; + }; - for (auto const& run : runs) + if constexpr (IsSeq::value) { - if (run.id == here) + for (auto pair : pairs) { - local_runs.emplace_back(run); + auto const& left = blocks[pair.first]; + auto const& right = right_block(pair); + auto const host = segmented_sort_host(left, right); + if (host == here) + { + operation().call2(policy, is_seq, left, right, comp, proj); + } + else + { + dispatch(host, operation(), policy, is_seq, left, right, + comp, proj); + } } - else + } + else + { + std::map> jobs; + for (auto pair : pairs) { - segments.push_back( - dispatch_async(run.id, segmented_local_sort(), - policy, forced_seq(), run.first, run.last, comp, proj)); + auto host = + segmented_sort_host(blocks[pair.first], right_block(pair)); + jobs[host].push_back(pair); } - } - // Local sorts run synchronously while remotes are in flight. - for (segmented_sort_run const& run : local_runs) - { - segmented_local_sort::sequential( - policy, run.first, run.last, comp, proj); + // At most one operation per locality is active in this sort. + // Each uses four block buffers plus local algorithm temporaries, + // independent of N. + // Pair inputs are disjoint within a stage. Drain each batch even + // if a local operation or dispatch throws, before returning. + for (;;) + { + std::vector> pending; + pending.reserve(jobs.size()); + segmented_sort_pair local_pair(blocks.size(), blocks.size()); + bool launched = false; + std::exception_ptr error; + try + { + for (auto& [host, queue] : jobs) + { + if (queue.empty()) + { + continue; + } + launched = true; + auto const pair = queue.back(); + queue.pop_back(); + if (host == here) + { + local_pair = pair; + } + else + { + pending.push_back(dispatch_async(host, operation(), + policy, is_seq, blocks[pair.first], + right_block(pair), comp, proj)); + } + } + if (local_pair.first != blocks.size()) + { + operation().call2(policy, is_seq, + blocks[local_pair.first], right_block(local_pair), + comp, proj); + } + } + catch (...) + { + error = std::current_exception(); + } + hpx::wait_all_nothrow(pending); + std::list errors; + using handler = + util::detail::handle_remote_exceptions; + if (error) + { + handler::call(error, errors); + } + handler::call(pending, errors); + if (!launched) + { + break; + } + } } - - segmented_sort_wait_all(segments); } - // Fetch each remote sorted run once onto the locality that already - // holds the largest run, merge there with hpx::merge, and write only - // the remote pieces back. That keeps traffic O(N) and avoids a full - // gather to the caller. template - void segmented_sort_merge_runs(ExPolicy const& policy, - std::vector>& runs, Comp&& comp, - Proj&& proj, IsSeq is_seq) + void segmented_sort_distributed(ExPolicy const& policy, + segmented_sort_block const& runs, Comp const& comp, + Proj const& proj, IsSeq is_seq) { - if (runs.size() <= 1) + // Keep the single-partition path in place, regardless of its size. + if (runs.size() == 1) { + segmented_sort_stage(policy, + std::vector>{runs}, {{0, 0}}, + comp, proj, is_seq); return; } - - std::size_t const host = segmented_sort_host_index(runs); - using local_traits = - hpx::traits::segmented_local_iterator_traits; - hpx::id_type const here = hpx::find_here(); - - if (runs[host].id == here) - { - if constexpr (IsSeq::value) - { - segmented_sort_merge_on_host_seq(policy, - local_traits::local(runs[host].first), - local_traits::local(runs[host].last), runs, host, - HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); - } - else - { - segmented_sort_merge_on_host_par(policy, - local_traits::local(runs[host].first), - local_traits::local(runs[host].last), runs, host, - HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); - } - } - else + auto const block_size = segmented_sort_block_capacity(runs); + auto blocks = segmented_sort_blocks(runs, block_size); + std::vector initial; + initial.reserve(blocks.size()); + for (std::size_t i = 0; i != blocks.size(); ++i) { - dispatch(runs[host].id, segmented_sort_kway_merge(), - policy, is_seq, runs[host].first, runs[host].last, runs, host, - HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); + initial.emplace_back(i, i); } + segmented_sort_stage(policy, blocks, initial, comp, proj, is_seq); + segmented_sort_merge_stages(blocks.size(), [&](auto const& pairs) { + segmented_sort_stage(policy, blocks, pairs, comp, proj, is_seq); + }); } template ) { return result::get(hpx::async([=, runs = HPX_MOVE(runs)]() mutable { - segmented_sort_local_runs(sync_policy, runs, cmp, prj, is_seq); - segmented_sort_merge_runs(sync_policy, runs, cmp, prj, is_seq); + segmented_sort_distributed(sync_policy, runs, cmp, prj, is_seq); })); } else { - segmented_sort_local_runs(sync_policy, runs, cmp, prj, is_seq); - segmented_sort_merge_runs(sync_policy, runs, cmp, prj, is_seq); + segmented_sort_distributed(sync_policy, runs, cmp, prj, is_seq); return result::get(); } } From 2039d6194c18549a5b6ccbde8e219da13aab3980 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Mon, 28 Sep 2026 16:12:38 +0530 Subject: [PATCH 18/37] Cover bounded segmented merges and skewed partition placement Signed-off-by: the-ivii --- .../tests/unit/CMakeLists.txt | 2 +- .../tests/unit/partitioned_vector_sort.cpp | 314 +++++++++++++++++- 2 files changed, 313 insertions(+), 3 deletions(-) diff --git a/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt b/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt index 201b85943bf2..de152f86cf39 100644 --- a/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt +++ b/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt @@ -99,7 +99,7 @@ foreach(test ${tests}) if(test STREQUAL "partitioned_vector_sort" OR test MATCHES "^partitioned_vector_merge(_extended|_regressions)?$" ) - # Four localities so k-way merge of more than two runs is exercised. + # Four localities exercise concurrent merges and remote transfers. set(test_localities 4) else() set(test_localities 2) diff --git a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp index 361de6929e7e..414c9cc94d64 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -292,8 +293,8 @@ void test_sort_subranges( ExPolicy const& policy, std::vector const& localities) { // Eight partitions put multiple partitions on each locality. The - // [3, 47) subrange spans five runs, exercising an odd merge tree. - // [33, 77) selects a remote merge host with two or four localities. + // [3, 47) subrange spans five runs, including clipped endpoints. + // [33, 77) starts on a remote partition with two or four localities. hpx::partitioned_vector values( 80, 0, hpx::container_layout(8, localities)); std::pair const ranges[] = { @@ -324,10 +325,319 @@ void test_sort_subranges( } } +// Exercise the block network with exhaustive zero/one inputs, including a +// short final block. A stage must never read/write overlapping blocks. +void test_merge_network() +{ + namespace detail = hpx::parallel::detail; + for (std::size_t count = 2; count <= 7; ++count) + { + for (std::size_t tail : {1, 2, 3}) + { + std::size_t combinations = tail + 1; + for (std::size_t i = 1; i < count; ++i) + { + combinations *= 4; + } + for (std::size_t input = 0; input < combinations; ++input) + { + std::vector> blocks(count); + auto digits = input; + std::size_t zeros = 0; + for (std::size_t i = 0; i < count; ++i) + { + auto const size = i + 1 == count ? tail : 3; + auto const nzero = digits % (size + 1); + digits /= size + 1; + zeros += nzero; + blocks[i].resize(size, 1); + std::fill_n(blocks[i].begin(), nzero, 0); + } + detail::segmented_sort_merge_stages( + count, [&](auto const& pairs) { + std::vector touched(count, false); + for (auto [left, right] : pairs) + { + HPX_TEST(!touched[left] && !touched[right]); + touched[left] = touched[right] = true; + std::vector merged( + blocks[left].size() + blocks[right].size()); + std::merge(blocks[left].begin(), blocks[left].end(), + blocks[right].begin(), blocks[right].end(), + merged.begin()); + auto middle = merged.begin() + + static_cast( + blocks[left].size()); + std::copy( + merged.begin(), middle, blocks[left].begin()); + std::copy( + middle, merged.end(), blocks[right].begin()); + } + }); + for (auto const& block : blocks) + { + for (int value : block) + { + HPX_TEST_EQ(value, zeros != 0 ? 0 : 1); + if (zeros != 0) + { + --zeros; + } + } + } + } + } + } +} + +struct counted_sort_value +{ + inline static std::size_t live = 0; + inline static std::size_t peak = 0; + inline static std::size_t copies = 0; + int value = 0; + + counted_sort_value() + { + peak = (std::max) (peak, ++live); + } + counted_sort_value(counted_sort_value const& other) + : counted_sort_value() + { + value = other.value; + ++copies; + } + counted_sort_value(counted_sort_value&& other) noexcept + : counted_sort_value() + { + value = other.value; + } + counted_sort_value& operator=(counted_sort_value const&) = default; + counted_sort_value& operator=(counted_sort_value&&) = default; + ~counted_sort_value() + { + --live; + } +}; + +void test_merge_buffer() +{ + namespace detail = hpx::parallel::detail; + auto const size = detail::segmented_sort_max_block_size; + { + std::vector left(size), right(size); + for (std::size_t i = 0; i < size; ++i) + { + left[i].value = static_cast(2 * i); + right[i].value = static_cast(2 * i + 1); + } + auto pred = [](auto const& a, auto const& b) { + return a.value < b.value; + }; + // HPX's merge itself creates temporary values. Compare against a + // direct merge to isolate copies and storage added by our wrapper. + std::size_t reference_copies; + std::size_t reference_peak; + { + std::vector reference(2 * size); + hpx::merge(hpx::execution::seq, left.begin(), left.end(), + right.begin(), right.end(), reference.begin(), pred); + reference_copies = counted_sort_value::copies; + reference_peak = counted_sort_value::peak; + } + counted_sort_value::copies = 0; + counted_sort_value::peak = counted_sort_value::live; + auto merged = detail::segmented_sort_merge_pair( + hpx::execution::seq, left, right, pred); + HPX_TEST_EQ(counted_sort_value::copies, reference_copies); + HPX_TEST_EQ(counted_sort_value::peak, reference_peak); + for (std::size_t i = 0; i < merged.size(); ++i) + { + HPX_TEST_EQ(merged[i].value, static_cast(i)); + } + } + HPX_TEST_EQ(counted_sort_value::live, std::size_t(0)); +} + +void test_host_placement(std::vector const& localities) +{ + namespace detail = hpx::parallel::detail; + constexpr auto unit = static_cast( + detail::segmented_sort_max_block_size / 32 + 1); + std::vector data(static_cast(45 * unit)); + using iterator = std::vector::iterator; + detail::segmented_sort_block runs; + auto const& a = localities.front(); + auto const& b = localities.back(); + // A owns the largest individual run (5 units); B owns ten of 4. + runs.emplace_back(a, a, data.begin(), data.begin() + 5 * unit); + for (std::ptrdiff_t i = 5 * unit; i < 45 * unit; i += 4 * unit) + { + runs.emplace_back(b, b, data.begin() + i, data.begin() + i + 4 * unit); + } + HPX_TEST(detail::segmented_sort_host(runs, {}) == b); + HPX_TEST_EQ(detail::segmented_sort_block_capacity(runs), + a == b ? detail::segmented_sort_max_block_size : (data.size() + 1) / 2); + + if (a != b) + { + hpx::partitioned_vector values( + 200, 0, hpx::container_layout(20, std::vector{a, b})); + initialize_values(values, [](int i) { return 200 - i; }); + auto first = values.begin() + 90; + auto participating = detail::segmented_sort_runs(first, values.end()); + HPX_TEST_EQ(participating.size(), std::size_t(11)); + HPX_TEST(participating.front().locality == a); + HPX_TEST_EQ(std::count_if(participating.begin(), participating.end(), + [&](auto const& run) { return run.locality == b; }), + std::ptrdiff_t(10)); + HPX_TEST(detail::segmented_sort_host(participating, {}) == b); + auto expected = copy_values(values); + std::sort(expected.begin() + 90, expected.end()); + hpx::sort(hpx::execution::par, first, values.end()); + HPX_TEST(copy_values(values) == expected); + } +} + +void test_bounded_blocks(std::vector const& localities) +{ + namespace detail = hpx::parallel::detail; + auto const size = 8 * detail::segmented_sort_max_block_size + 7; + hpx::partitioned_vector values( + size, 0, hpx::container_layout(3, localities)); + initialize_values(values, + [](std::size_t i) { return static_cast((i * 17 + 3) % 97); }); + auto expected = copy_values(values); + std::sort(expected.begin() + 1, expected.end() - 2); + auto runs = + detail::segmented_sort_runs(values.begin() + 1, values.end() - 2); + auto blocks = detail::segmented_sort_blocks( + runs, detail::segmented_sort_max_block_size); + std::size_t total = 0; + for (std::size_t i = 0; i < blocks.size(); ++i) + { + auto const n = detail::segmented_sort_block_size(blocks[i]); + HPX_TEST_LTE(n, detail::segmented_sort_max_block_size); + if (i + 1 != blocks.size()) + { + HPX_TEST_EQ(n, detail::segmented_sort_max_block_size); + } + total += n; + for (auto const& run : blocks[i]) + { + HPX_TEST(run.locality == + hpx::get_colocation_id(hpx::launch::sync, run.id)); + HPX_TEST(run.locality != run.id); + } + } + HPX_TEST_EQ(total, size - 3); + hpx::sort(hpx::execution::par(hpx::execution::task), values.begin() + 1, + values.end() - 2) + .get(); + HPX_TEST(copy_values(values) == expected); + + // Exercise the distributed merge with nontrivial values and descending + // order as well as the default integer comparator above. + hpx::partitioned_vector strings( + 2 * detail::segmented_sort_max_block_size + 7, std::string{}, + hpx::container_layout(3, localities)); + initialize_values(strings, [](std::size_t i) { + return std::to_string((i * 17 + 3) % 97) + std::string(32, 'x'); + }); + auto expected_strings = copy_values(strings); + std::greater greater; + std::sort(expected_strings.begin(), expected_strings.end(), greater); + hpx::sort(hpx::execution::seq(hpx::execution::task), strings.begin(), + strings.end(), greater) + .get(); + HPX_TEST(copy_values(strings) == expected_strings); +} + +struct throwing_merge_less +{ + bool allocation; + + bool operator()(int a, int b) const + { + // Each initial block lies within one band. Only a merge compares + // different bands, after the local sort phase has succeeded. + constexpr auto band_size = static_cast( + hpx::parallel::detail::segmented_sort_max_block_size); + if (a / band_size != b / band_size) + { + if (allocation) + { + throw std::bad_alloc(); + } + throw std::runtime_error("segmented merge comparator"); + } + return a < b; + } + + template + void serialize(Archive& ar, unsigned) + { + ar & allocation; + } +}; + +template +void test_merge_exceptions( + ExPolicy const& policy, std::vector const& localities) +{ + for (bool allocation : {false, true}) + { + auto const size = + 4 * hpx::parallel::detail::segmented_sort_max_block_size; + hpx::partitioned_vector values( + size, 0, hpx::container_layout(4, localities)); + initialize_values(values, [](int i) { return i; }); + bool caught = false; + try + { + if constexpr (hpx::is_async_execution_policy_v) + { + hpx::sort(policy, values.begin(), values.end(), + throwing_merge_less{allocation}) + .get(); + } + else + { + hpx::sort(policy, values.begin(), values.end(), + throwing_merge_less{allocation}); + } + } + catch (std::bad_alloc const&) + { + HPX_TEST(allocation); + caught = true; + } + catch (hpx::exception_list const&) + { + HPX_TEST(!allocation); + caught = true; + } + HPX_TEST(caught); + // Reuse immediately: the failed stage must have drained its actions. + initialize_reverse(values); + test_sort_once(values); + } +} + /////////////////////////////////////////////////////////////////////////////// int main() { std::vector localities = hpx::find_all_localities(); + test_merge_network(); + test_merge_buffer(); + test_host_placement(localities); + test_bounded_blocks(localities); + test_merge_exceptions(hpx::execution::seq, localities); + test_merge_exceptions(hpx::execution::par, localities); + test_merge_exceptions( + hpx::execution::seq(hpx::execution::task), localities); + test_merge_exceptions( + hpx::execution::par(hpx::execution::task), localities); run_cases(localities); run_cases(localities); test_sort_large(localities); From 3df300ad0f33021b538fe39b437380cd495d921a Mon Sep 17 00:00:00 2001 From: the-ivii Date: Mon, 28 Sep 2026 18:14:42 +0530 Subject: [PATCH 19/37] Use headers for segmented sort tests that inspect internal helpers Signed-off-by: the-ivii --- .../tests/unit/partitioned_vector_sort.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp index 414c9cc94d64..fa901a6510c8 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -4,6 +4,10 @@ // 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) +// These tests inspect sort helpers that are not exported by HPX.Full. +// Use the header interface to keep the internal regression checks available. +#define HPX_HAVE_FORCE_NO_CXX_MODULES + #include #if !defined(HPX_COMPUTE_DEVICE_CODE) #include From 42c7317ae6e13b8de96e3edd949843475b00c2c4 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Mon, 28 Sep 2026 18:29:34 +0530 Subject: [PATCH 20/37] Configure the segmented sort test's module fallback in CMake Signed-off-by: the-ivii --- libs/full/segmented_algorithms/tests/unit/CMakeLists.txt | 7 +++++++ .../tests/unit/partitioned_vector_sort.cpp | 4 ---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt b/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt index de152f86cf39..5ab1f69e5d5d 100644 --- a/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt +++ b/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt @@ -127,3 +127,10 @@ foreach(test ${tests}) ) endforeach() + +if(HPX_WITH_CXX_MODULES) + # These tests inspect sort helpers that are not exported by HPX.Full. + target_compile_definitions( + partitioned_vector_sort_test PRIVATE HPX_HAVE_FORCE_NO_CXX_MODULES + ) +endif() diff --git a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp index fa901a6510c8..414c9cc94d64 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -4,10 +4,6 @@ // 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) -// These tests inspect sort helpers that are not exported by HPX.Full. -// Use the header interface to keep the internal regression checks available. -#define HPX_HAVE_FORCE_NO_CXX_MODULES - #include #if !defined(HPX_COMPUTE_DEVICE_CODE) #include From 5b2e1b88873834f64f44416605eeccdcc27c36a9 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Mon, 28 Sep 2026 20:19:56 +0530 Subject: [PATCH 21/37] Overlap segmented sort work and skip ordered block transfers Signed-off-by: the-ivii --- .../parallel/segmented_algorithms/sort.hpp | 327 ++++++++++++------ 1 file changed, 225 insertions(+), 102 deletions(-) diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp index fc3e175a7930..1441fc3f3961 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp @@ -13,6 +13,7 @@ #include #include #include +#include #include @@ -72,6 +73,26 @@ namespace hpx::parallel::detail { } }; + // Bound outstanding transport and namespace requests independently of + // the number of partitions. + inline constexpr std::size_t segmented_sort_transfer_limit = 8; + + // Even a synchronous launch failure must not leave actions accessing the + // input after the caller observes an exception. + template + void segmented_sort_wait( + std::vector>& pending, std::exception_ptr error = {}) + { + hpx::wait_all_nothrow(pending); + std::list errors; + using handler = util::detail::handle_remote_exceptions; + if (error) + { + handler::call(error, errors); + } + handler::call(pending, errors); + } + template struct segmented_sort_run { @@ -106,23 +127,54 @@ namespace hpx::parallel::detail { if (beg != end) { auto id = traits::get_id(segment); - auto locality = hpx::get_colocation_id(hpx::launch::sync, id); - runs.emplace_back(HPX_MOVE(id), HPX_MOVE(locality), beg, end); + runs.emplace_back(HPX_MOVE(id), hpx::id_type{}, beg, end); } }; if (sit == send) { add_run(sit, traits::local(first), traits::local(last)); - return runs; + } + else + { + add_run(sit, traits::local(first), traits::end(sit)); + for (++sit; sit != send; ++sit) + { + add_run(sit, traits::begin(sit), traits::end(sit)); + } + add_run(sit, traits::begin(sit), traits::local(last)); } - add_run(sit, traits::local(first), traits::end(sit)); - for (++sit; sit != send; ++sit) + // Resolve independent namespace entries concurrently, with a bounded + // number of outstanding requests. Task policies collect runs inside + // their asynchronous operation, including this discovery phase. + for (std::size_t first_run = 0; first_run < runs.size();) { - add_run(sit, traits::begin(sit), traits::end(sit)); + std::vector> pending; + auto const count = (std::min) (segmented_sort_transfer_limit, + runs.size() - first_run); + pending.reserve(count); + std::exception_ptr error; + try + { + for (std::size_t i = 0; i < count; ++i) + { + pending.push_back( + hpx::get_colocation_id(runs[first_run + i].id)); + } + } + catch (...) + { + error = std::current_exception(); + } + segmented_sort_wait( + pending, error); + for (std::size_t i = 0; i < count; ++i) + { + runs[first_run + i].locality = pending[i].get(); + } + first_run += count; } - add_run(sit, traits::begin(sit), traits::local(last)); return runs; } @@ -294,33 +346,60 @@ namespace hpx::parallel::detail { ExPolicy const& policy, segmented_sort_block const& block) { using value_type = std::iterator_traits::value_type; - using local_traits = - hpx::traits::segmented_local_iterator_traits; - std::vector values; - values.reserve(segmented_sort_block_size(block)); auto const here = hpx::find_here(); - for (auto it = block.begin(); it != block.end();) + if (std::all_of(block.begin(), block.end(), + [&](auto const& run) { return run.locality == here; })) { - if (it->locality == here) + return segmented_fetch_values::sequential(policy, block); + } + std::vector values; + values.reserve(segmented_sort_block_size(block)); + constexpr auto limit = hpx::is_sequenced_execution_policy_v ? + 1 : + segmented_sort_transfer_limit; + auto it = block.begin(); + while (it != block.end()) + { + std::vector>> pending; + pending.reserve(limit); + std::exception_ptr error; + try { - values.insert(values.end(), local_traits::local(it->first), - local_traits::local(it->last)); - ++it; + for (std::size_t i = 0; i < limit && it != block.end(); ++i) + { + auto end = + std::find_if(it, block.end(), [&](auto const& run) { + return run.locality != it->locality; + }); + segmented_sort_block pieces(it, end); + if (it->locality == here) + { + pending.push_back(hpx::make_ready_future( + segmented_fetch_values::sequential( + policy, pieces))); + } + else + { + pending.push_back(dispatch_async(it->locality, + segmented_fetch_values(), policy, + std::true_type(), HPX_MOVE(pieces))); + } + it = end; + } } - else + catch (...) { - auto end = std::find_if(it, block.end(), [&](auto const& run) { - return run.locality != it->locality; - }); - // One action for consecutive pieces on the same locality. - segmented_sort_block pieces(it, end); - auto part = - dispatch(it->locality, segmented_fetch_values(), - policy, std::true_type(), HPX_MOVE(pieces)); + error = std::current_exception(); + } + segmented_sort_wait(pending, error); + // Retain logical order even if the transfers finish out of order. + // All pending payloads together occupy at most one block. + for (auto& future : pending) + { + auto part = future.get(); values.insert(values.end(), std::make_move_iterator(part.begin()), std::make_move_iterator(part.end())); - it = end; } } return values; @@ -331,35 +410,61 @@ namespace hpx::parallel::detail { segmented_sort_block const& block, Iter first) { using value_type = std::iterator_traits::value_type; - using local_traits = - hpx::traits::segmented_local_iterator_traits; auto const here = hpx::find_here(); - for (auto it = block.begin(); it != block.end();) - { - if (it->locality == here) + constexpr auto limit = hpx::is_sequenced_execution_policy_v ? + 1 : + segmented_sort_transfer_limit; + auto it = block.begin(); + while (it != block.end()) + { + std::vector> pending; + pending.reserve(limit); + std::exception_ptr error; + try { - auto last = first + it->size(); - hpx::move(policy, first, last, local_traits::local(it->first)); - first = last; - ++it; + for (std::size_t i = 0; i < limit && it != block.end(); ++i) + { + auto end = + std::find_if(it, block.end(), [&](auto const& run) { + return run.locality != it->locality; + }); + segmented_sort_block pieces(it, end); + auto last = first + + static_cast( + segmented_sort_block_size(pieces)); + if (it->locality == here) + { + using traits = + hpx::traits::segmented_local_iterator_traits< + LocalIter>; + auto current = first; + for (auto const& piece : pieces) + { + auto next = current + piece.size(); + hpx::move(policy, current, next, + traits::local(piece.first)); + current = next; + } + } + else + { + std::vector values( + std::make_move_iterator(first), + std::make_move_iterator(last)); + pending.push_back(dispatch_async(it->locality, + segmented_store_values(), policy, + std::true_type(), HPX_MOVE(pieces), + HPX_MOVE(values))); + } + first = last; + it = end; + } } - else + catch (...) { - auto end = std::find_if(it, block.end(), [&](auto const& run) { - return run.locality != it->locality; - }); - segmented_sort_block pieces(it, end); - auto last = first + - static_cast( - segmented_sort_block_size(pieces)); - std::vector values(std::make_move_iterator(first), - std::make_move_iterator(last)); - dispatch(it->locality, segmented_store_values(), - policy, std::true_type(), HPX_MOVE(pieces), - HPX_MOVE(values)); - first = last; - it = end; + error = std::current_exception(); } + segmented_sort_wait(pending, error); } return first; } @@ -401,6 +506,19 @@ namespace hpx::parallel::detail { using value_type = std::iterator_traits::value_type; util::compare_projected pred(comp, proj); + if (!right.empty()) + { + auto left_end = left.back(); + left_end.first = left_end.last - 1; + auto right_begin = right.front(); + right_begin.last = right_begin.first + 1; + auto endpoints = segmented_sort_fetch_block(policy, + segmented_sort_block{left_end, right_begin}); + if (!pred(endpoints[1], endpoints[0])) + { + return true; + } + } std::vector output; { auto left_values = segmented_sort_fetch_block(policy, left); @@ -414,10 +532,6 @@ namespace hpx::parallel::detail { { auto right_values = segmented_sort_fetch_block(policy, right); - if (!pred(right_values.front(), left_values.back())) - { - return true; - } output = segmented_sort_merge_pair( policy, left_values, right_values, std::ref(pred)); } @@ -519,61 +633,67 @@ namespace hpx::parallel::detail { jobs[host].push_back(pair); } - // At most one operation per locality is active in this sort. - // Each uses four block buffers plus local algorithm temporaries, - // independent of N. - // Pair inputs are disjoint within a stage. Drain each batch even - // if a local operation or dispatch throws, before returning. + // Initial sorts can share a locality: buffered sorts charge two + // blocks each, and in-place sorts need no value buffers. Bound + // scratch storage by the same four-block budget as one merge. + // Merge stages still run at most one compare/split per locality. + auto const workers = (std::max) (std::size_t(1), + static_cast(hpx::get_os_thread_count())); for (;;) { std::vector> pending; - pending.reserve(jobs.size()); - segmented_sort_pair local_pair(blocks.size(), blocks.size()); - bool launched = false; + pending.reserve(jobs.size() * workers); std::exception_ptr error; try { for (auto& [host, queue] : jobs) { - if (queue.empty()) - { - continue; - } - launched = true; - auto const pair = queue.back(); - queue.pop_back(); - if (host == here) + std::size_t used = 0; + for (std::size_t active = 0; + active < workers && !queue.empty(); ++active) { - local_pair = pair; + auto const pair = queue.back(); + auto const& left = blocks[pair.first]; + auto const& right = right_block(pair); + auto const cost = right.empty() ? + (left.size() == 1 ? + 0 : + 2 * segmented_sort_block_size(left)) : + 4 * segmented_sort_max_block_size; + if (used + cost > 4 * segmented_sort_max_block_size) + { + break; + } + used += cost; + queue.pop_back(); + if (host == here) + { + pending.push_back( + hpx::async([policy, left, right, comp, proj, + is_seq]() { + return operation().call2(policy, is_seq, + left, right, comp, proj); + })); + } + else + { + pending.push_back( + dispatch_async(host, operation(), policy, + is_seq, left, right, comp, proj)); + } + if (!right.empty()) + { + break; + } } - else - { - pending.push_back(dispatch_async(host, operation(), - policy, is_seq, blocks[pair.first], - right_block(pair), comp, proj)); - } - } - if (local_pair.first != blocks.size()) - { - operation().call2(policy, is_seq, - blocks[local_pair.first], right_block(local_pair), - comp, proj); } } catch (...) { error = std::current_exception(); } - hpx::wait_all_nothrow(pending); - std::list errors; - using handler = - util::detail::handle_remote_exceptions; - if (error) - { - handler::call(error, errors); - } - handler::call(pending, errors); - if (!launched) + segmented_sort_wait(pending, error); + if (pending.empty()) { break; } @@ -622,12 +742,6 @@ namespace hpx::parallel::detail { return result::get(); } - auto runs = segmented_sort_runs(first, last); - if (runs.empty()) - { - return result::get(); - } - std::decay_t cmp(HPX_FORWARD(Comp, comp)); std::decay_t prj(HPX_FORWARD(Proj, proj)); @@ -638,13 +752,22 @@ namespace hpx::parallel::detail { if constexpr (hpx::is_async_execution_policy_v) { - return result::get(hpx::async([=, runs = HPX_MOVE(runs)]() mutable { - segmented_sort_distributed(sync_policy, runs, cmp, prj, is_seq); + return result::get(hpx::async([=]() mutable { + auto runs = segmented_sort_runs(first, last); + if (!runs.empty()) + { + segmented_sort_distributed( + sync_policy, runs, cmp, prj, is_seq); + } })); } else { - segmented_sort_distributed(sync_policy, runs, cmp, prj, is_seq); + auto runs = segmented_sort_runs(first, last); + if (!runs.empty()) + { + segmented_sort_distributed(sync_policy, runs, cmp, prj, is_seq); + } return result::get(); } } From 065ac5e4e811ba54e1558e3bb63498eae4509dc7 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Mon, 28 Sep 2026 20:19:56 +0530 Subject: [PATCH 22/37] Cover segmented sort concurrency and endpoint-only checks Signed-off-by: the-ivii --- .../tests/unit/partitioned_vector_sort.cpp | 260 +++++++++++++++++- 1 file changed, 250 insertions(+), 10 deletions(-) diff --git a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp index 414c9cc94d64..da23648d9c6a 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -9,15 +9,20 @@ #include #include #include +#include #include #include #include #include #include +#include +#include +#include #include #include #include +#include #include #include #include @@ -392,14 +397,19 @@ void test_merge_network() struct counted_sort_value { - inline static std::size_t live = 0; - inline static std::size_t peak = 0; - inline static std::size_t copies = 0; + inline static std::atomic live{0}; + inline static std::atomic peak{0}; + inline static std::atomic copies{0}; int value = 0; counted_sort_value() { - peak = (std::max) (peak, ++live); + auto const current = ++live; + auto previous = peak.load(); + while (previous < current && + !peak.compare_exchange_weak(previous, current)) + { + } } counted_sort_value(counted_sort_value const& other) : counted_sort_value() @@ -418,8 +428,18 @@ struct counted_sort_value { --live; } + + template + void serialize(Archive& ar, unsigned) + { + ar & value; + } }; +// HPX component factories must be registered before runtime startup. +// NOLINTNEXTLINE(bugprone-throwing-static-initialization) +HPX_REGISTER_PARTITIONED_VECTOR(counted_sort_value) + void test_merge_buffer() { namespace detail = hpx::parallel::detail; @@ -442,21 +462,21 @@ void test_merge_buffer() std::vector reference(2 * size); hpx::merge(hpx::execution::seq, left.begin(), left.end(), right.begin(), right.end(), reference.begin(), pred); - reference_copies = counted_sort_value::copies; - reference_peak = counted_sort_value::peak; + reference_copies = counted_sort_value::copies.load(); + reference_peak = counted_sort_value::peak.load(); } counted_sort_value::copies = 0; - counted_sort_value::peak = counted_sort_value::live; + counted_sort_value::peak = counted_sort_value::live.load(); auto merged = detail::segmented_sort_merge_pair( hpx::execution::seq, left, right, pred); - HPX_TEST_EQ(counted_sort_value::copies, reference_copies); - HPX_TEST_EQ(counted_sort_value::peak, reference_peak); + HPX_TEST_EQ(counted_sort_value::copies.load(), reference_copies); + HPX_TEST_EQ(counted_sort_value::peak.load(), reference_peak); for (std::size_t i = 0; i < merged.size(); ++i) { HPX_TEST_EQ(merged[i].value, static_cast(i)); } } - HPX_TEST_EQ(counted_sort_value::live, std::size_t(0)); + HPX_TEST_EQ(counted_sort_value::live.load(), std::size_t(0)); } void test_host_placement(std::vector const& localities) @@ -624,6 +644,218 @@ void test_merge_exceptions( } } +// This comparator observes overlap between two initial block sorts. Waiting +// on an HPX future yields the worker, and the timeout also diagnoses the old +// serial scheduler without hanging the test. +struct initial_sort_probe_state +{ + std::array, 2> entered{}; + std::atomic started{0}; + hpx::promise both_started; + hpx::shared_future ready = both_started.get_future(); + std::atomic timed_out{false}; +}; + +struct initial_sort_probe +{ + inline static std::shared_ptr state; + static constexpr auto block_size = + hpx::parallel::detail::segmented_sort_max_block_size; + + bool operator()(int a, int b) const + { + auto const block = static_cast(a) / block_size; + if (!state->entered[block].exchange(true)) + { + if (++state->started == 2) + { + state->both_started.set_value(); + } + if (state->ready.wait_for(std::chrono::seconds(5)) != + hpx::future_status::ready) + { + state->timed_out = true; + } + } + return a < b; + } + + template + void serialize(Archive&, unsigned) + { + } +}; + +void test_initial_sort_concurrency() +{ + namespace detail = hpx::parallel::detail; + constexpr auto size = initial_sort_probe::block_size; + // Four physical pieces produce two buffered logical blocks on this + // locality, together using the complete four-block scratch budget. + hpx::partitioned_vector values(2 * size, 0, + hpx::container_layout(4, std::vector{hpx::find_here()})); + initialize_values(values, [](std::size_t i) { + return static_cast((i / size) * size + size - 1 - i % size); + }); + auto runs = detail::segmented_sort_runs(values.begin(), values.end()); + auto blocks = detail::segmented_sort_blocks(runs, size); + initial_sort_probe::state = std::make_shared(); + detail::segmented_sort_stage(hpx::execution::par, blocks, {{0, 0}, {1, 1}}, + initial_sort_probe{}, hpx::identity_v, std::false_type{}); + HPX_TEST(!initial_sort_probe::state->timed_out.load()); + initial_sort_probe::state.reset(); + auto got = copy_values(values); + HPX_TEST(std::is_sorted(got.begin(), got.end())); +} + +struct collection_gate +{ + hpx::promise release; + hpx::shared_future ready = release.get_future(); +}; + +struct collection_probe_iterator +{ + hpx::partitioned_vector::iterator base; + std::shared_ptr gate; + + bool operator==(collection_probe_iterator const& other) const + { + return base == other.base; + } +}; + +namespace hpx::traits { + template <> + struct segmented_iterator_traits + : segmented_iterator_traits::iterator> + { + using base_traits = + segmented_iterator_traits::iterator>; + + static segment_iterator segment(collection_probe_iterator iter) + { + iter.gate->ready.wait(); + return base_traits::segment(iter.base); + } + + static local_iterator local(collection_probe_iterator iter) + { + return base_traits::local(iter.base); + } + }; +} // namespace hpx::traits + +template +void test_async_run_collection(ExPolicy const& policy) +{ + hpx::partitioned_vector values(64, 0, + hpx::container_layout(2, std::vector{hpx::find_here()})); + initialize_reverse(values); + auto gate = std::make_shared(); + hpx::future sorted; + hpx::promise returned; + auto return_signal = returned.get_future(); + auto invoke = hpx::async([&]() { + sorted = hpx::parallel::detail::segmented_sort(policy, + collection_probe_iterator{values.begin(), gate}, + collection_probe_iterator{values.end(), gate}, std::less{}, + hpx::identity_v, hpx::is_sequenced_execution_policy{}); + returned.set_value(); + }); + // Collection is deliberately blocked; obtaining the sort future must + // not wait for it. Release on timeout too, so the old path fails cleanly. + auto const status = return_signal.wait_for(std::chrono::seconds(5)); + gate->release.set_value(); + invoke.get(); + sorted.get(); + HPX_TEST(status == hpx::future_status::ready); + auto got = copy_values(values); + HPX_TEST(std::is_sorted(got.begin(), got.end())); +} + +struct counted_value_less +{ + bool operator()( + counted_sort_value const& a, counted_sort_value const& b) const + { + return a.value < b.value; + } + + template + void serialize(Archive&, unsigned) + { + } +}; + +void test_ordered_endpoints() +{ + namespace detail = hpx::parallel::detail; + hpx::partitioned_vector values(4096, + counted_sort_value{}, + hpx::container_layout(2, std::vector{hpx::find_here()})); + initialize_values(values, [](int i) { + counted_sort_value value; + value.value = i; + return value; + }); + auto runs = detail::segmented_sort_runs(values.begin(), values.end()); + auto blocks = detail::segmented_sort_blocks(runs, 2048); + counted_sort_value::copies = 0; + using local_iterator = hpx::traits::segmented_iterator_traits< + decltype(values.begin())>::local_iterator; + detail::segmented_sort_compare_split::sequential( + hpx::execution::seq, blocks[0], blocks[1], counted_value_less{}, + hpx::identity_v); + HPX_TEST_EQ(counted_sort_value::copies.load(), std::size_t(2)); + auto got = copy_values(values); + for (std::size_t i = 0; i < got.size(); ++i) + { + HPX_TEST_EQ(got[i].value, static_cast(i)); + } +} + +void test_transfer_batches(std::vector const& localities) +{ + namespace detail = hpx::parallel::detail; + auto const partitions = 4 * localities.size(); + hpx::partitioned_vector values( + partitions * 9, 0, hpx::container_layout(partitions, localities)); + initialize_values(values, [](int i) { return i; }); + auto runs = detail::segmented_sort_runs(values.begin(), values.end()); + decltype(runs) block; + std::vector expected; + // Interleave ownership so four localities cross the eight-action batch + // boundary. The helper must preserve logical order and disjoint writes. + for (std::size_t piece = 0; piece < 4; ++piece) + { + for (std::size_t locality = 0; locality < localities.size(); ++locality) + { + auto const index = 4 * locality + piece; + block.push_back(runs[index]); + for (std::size_t i = 0; i < 9; ++i) + { + expected.push_back(static_cast(9 * index + i)); + } + } + } + auto fetched = + detail::segmented_sort_fetch_block(hpx::execution::par, block); + HPX_TEST(fetched == expected); + for (auto& value : fetched) + { + value = -value - 1; + } + auto end = detail::segmented_sort_store_block( + hpx::execution::par, block, fetched.begin()); + HPX_TEST(end == fetched.end()); + auto got = copy_values(values); + for (std::size_t i = 0; i < got.size(); ++i) + { + HPX_TEST_EQ(got[i], -static_cast(i) - 1); + } +} + /////////////////////////////////////////////////////////////////////////////// int main() { @@ -632,6 +864,14 @@ int main() test_merge_buffer(); test_host_placement(localities); test_bounded_blocks(localities); + if (hpx::get_os_thread_count() > 1) + { + test_initial_sort_concurrency(); + } + test_ordered_endpoints(); + test_transfer_batches(localities); + test_async_run_collection(hpx::execution::seq(hpx::execution::task)); + test_async_run_collection(hpx::execution::par(hpx::execution::task)); test_merge_exceptions(hpx::execution::seq, localities); test_merge_exceptions(hpx::execution::par, localities); test_merge_exceptions( From 632484fb6bc8b10ff2d39f7c79ccb819fe2b5ae4 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Wed, 30 Sep 2026 00:03:32 +0530 Subject: [PATCH 23/37] Use the specialized id future state for colocation Signed-off-by: the-ivii --- libs/full/async_colocated/CMakeLists.txt | 2 +- libs/full/async_colocated/src/get_colocation_id.cpp | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/libs/full/async_colocated/CMakeLists.txt b/libs/full/async_colocated/CMakeLists.txt index 1cb331e08704..ed0eef96558a 100644 --- a/libs/full/async_colocated/CMakeLists.txt +++ b/libs/full/async_colocated/CMakeLists.txt @@ -58,6 +58,6 @@ add_hpx_module( COMPAT_HEADERS ${async_colocated_compat_headers} DEPENDENCIES hpx_core MODULE_DEPENDENCIES hpx_actions_base hpx_agas_base hpx_async_distributed - hpx_components_base hpx_naming_base + hpx_components hpx_components_base hpx_naming_base CMAKE_SUBDIRS examples tests ) diff --git a/libs/full/async_colocated/src/get_colocation_id.cpp b/libs/full/async_colocated/src/get_colocation_id.cpp index 272ab0ee73ea..9b3241984ecf 100644 --- a/libs/full/async_colocated/src/get_colocation_id.cpp +++ b/libs/full/async_colocated/src/get_colocation_id.cpp @@ -8,6 +8,7 @@ #include #include #include +#include #include #include #include From 34c548e381ae46403ba5cf46cc98cab9381a1c3e Mon Sep 17 00:00:00 2001 From: the-ivii Date: Wed, 30 Sep 2026 00:03:32 +0530 Subject: [PATCH 24/37] Balance segmented sort work across localities Signed-off-by: the-ivii --- .../parallel/segmented_algorithms/sort.hpp | 108 ++++++++++++++++-- .../tests/unit/partitioned_vector_sort.cpp | 18 +++ 2 files changed, 116 insertions(+), 10 deletions(-) diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp index 1441fc3f3961..4ac1ce3e1a5a 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp @@ -248,10 +248,12 @@ namespace hpx::parallel::detail { // Choose the locality holding the most input for this operation, summing // all participating pieces rather than selecting a single partition. + // Balance equally good hosts across the current stage. template hpx::id_type segmented_sort_host( segmented_sort_block const& left, - segmented_sort_block const& right) + segmented_sort_block const& right, + std::map const& assignments) { std::map sizes; for (auto const& run : left) @@ -262,11 +264,32 @@ namespace hpx::parallel::detail { { sizes[run.locality] += static_cast(run.size()); } - auto const host = std::max_element(sizes.begin(), sizes.end(), - [](auto const& a, auto const& b) { return a.second < b.second; }); + auto assigned = [&](hpx::id_type const& locality) { + auto const it = assignments.find(locality); + return it == assignments.end() ? std::size_t(0) : it->second; + }; + auto host = sizes.begin(); + for (auto it = std::next(host); it != sizes.end(); ++it) + { + if (it->second > host->second || + (it->second == host->second && + assigned(it->first) < assigned(host->first))) + { + host = it; + } + } return host->first; } + template + hpx::id_type segmented_sort_host( + segmented_sort_block const& left, + segmented_sort_block const& right) + { + return segmented_sort_host( + left, right, std::map{}); + } + template struct segmented_fetch_values : algorithm, @@ -557,6 +580,29 @@ namespace hpx::parallel::detail { using segmented_sort_pair = std::pair; + struct segmented_sort_worker_count + : algorithm + { + constexpr segmented_sort_worker_count() noexcept + : algorithm( + "segmented_sort_worker_count") + { + } + + template + static std::size_t sequential(ExPolicy const&) + { + return (std::max) (std::size_t(1), + static_cast(hpx::get_os_thread_count())); + } + + template + static std::size_t parallel(ExPolicy const& policy) + { + return sequential(policy); + } + }; + // Batcher odd-even merge stages. With K blocks, O(log^2 K) stages trade // additional communication rounds for bounded merge buffers. All // comparisons are ascending, so a short final block and absent blocks @@ -626,31 +672,73 @@ namespace hpx::parallel::detail { else { std::map> jobs; + std::map assignments; for (auto pair : pairs) { - auto host = - segmented_sort_host(blocks[pair.first], right_block(pair)); + auto host = segmented_sort_host( + blocks[pair.first], right_block(pair), assignments); jobs[host].push_back(pair); + ++assignments[host]; + } + + std::map worker_counts; + bool const initial_stage = std::all_of(pairs.begin(), pairs.end(), + [](auto pair) { return pair.first == pair.second; }); + if (initial_stage) + { + std::vector remote_hosts; + std::vector> pending; + std::exception_ptr error; + try + { + for (auto const& job : jobs) + { + auto const& host = job.first; + if (host == here) + { + worker_counts[host] = + segmented_sort_worker_count::sequential(policy); + } + else + { + remote_hosts.push_back(host); + pending.push_back(dispatch_async(host, + segmented_sort_worker_count(), policy, + std::true_type())); + } + } + } + catch (...) + { + error = std::current_exception(); + } + segmented_sort_wait(pending, error); + for (std::size_t i = 0; i != pending.size(); ++i) + { + worker_counts[remote_hosts[i]] = pending[i].get(); + } } // Initial sorts can share a locality: buffered sorts charge two // blocks each, and in-place sorts need no value buffers. Bound // scratch storage by the same four-block budget as one merge. - // Merge stages still run at most one compare/split per locality. - auto const workers = (std::max) (std::size_t(1), - static_cast(hpx::get_os_thread_count())); + // Destination schedulers control worker use. Merge stages still + // run at most one compare/split per locality. for (;;) { std::vector> pending; - pending.reserve(jobs.size() * workers); + pending.reserve(pairs.size()); std::exception_ptr error; try { for (auto& [host, queue] : jobs) { std::size_t used = 0; + auto const workers = initial_stage ? + worker_counts[host] : + std::size_t(1); for (std::size_t active = 0; - active < workers && !queue.empty(); ++active) + active != workers && !queue.empty(); ++active) { auto const pair = queue.back(); auto const& left = blocks[pair.first]; diff --git a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp index da23648d9c6a..c4554175a2f1 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -22,6 +22,7 @@ #include #include #include +#include #include #include #include @@ -499,6 +500,23 @@ void test_host_placement(std::vector const& localities) HPX_TEST_EQ(detail::segmented_sort_block_capacity(runs), a == b ? detail::segmented_sort_max_block_size : (data.size() + 1) / 2); + if (a != b) + { + detail::segmented_sort_block left{ + {a, a, data.begin(), data.begin() + unit}}; + detail::segmented_sort_block right{ + {b, b, data.begin() + unit, data.begin() + 2 * unit}}; + std::map assignments; + for (std::size_t i = 0; i != 8; ++i) + { + auto const host = + detail::segmented_sort_host(left, right, assignments); + ++assignments[host]; + } + HPX_TEST_EQ(assignments[a], std::size_t(4)); + HPX_TEST_EQ(assignments[b], std::size_t(4)); + } + if (a != b) { hpx::partitioned_vector values( From 834380f330f982e492745a78924f60228135f742 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Thu, 1 Oct 2026 01:52:35 +0530 Subject: [PATCH 25/37] Declare the specialized id future state early Signed-off-by: the-ivii --- .../full/naming_base/include/hpx/naming_base/id_type.hpp | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/libs/full/naming_base/include/hpx/naming_base/id_type.hpp b/libs/full/naming_base/include/hpx/naming_base/id_type.hpp index 8fcc1216dfba..ba1e0a535ae9 100644 --- a/libs/full/naming_base/include/hpx/naming_base/id_type.hpp +++ b/libs/full/naming_base/include/hpx/naming_base/id_type.hpp @@ -146,6 +146,15 @@ namespace hpx { /////////////////////////////////////////////////////////////////////////// HPX_CXX_EXPORT inline id_type const invalid_id = id_type(); + namespace lcos::detail { + + // The definition of this specialization lives in the components + // module. Declare it here to prevent the primary template from being + // instantiated for id_type before the specialization is visible. + template <> + struct future_data; + } // namespace lcos::detail + namespace naming { /////////////////////////////////////////////////////////////////////////// From 8cfd5015ea9e353c2018f94e68e9d865c0e82205 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Thu, 1 Oct 2026 02:52:43 +0530 Subject: [PATCH 26/37] Overlap segmented sort block transfers Signed-off-by: the-ivii --- .../parallel/segmented_algorithms/sort.hpp | 131 +++++++++++++++--- 1 file changed, 112 insertions(+), 19 deletions(-) diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp index 4ac1ce3e1a5a..8897d03e27e1 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -83,7 +84,12 @@ namespace hpx::parallel::detail { void segmented_sort_wait( std::vector>& pending, std::exception_ptr error = {}) { - hpx::wait_all_nothrow(pending); + bool const exceptional = hpx::wait_all_nothrow(pending); + if (!exceptional && !error) + { + return; + } + std::list errors; using handler = util::detail::handle_remote_exceptions; if (error) @@ -385,6 +391,9 @@ namespace hpx::parallel::detail { { std::vector>> pending; pending.reserve(limit); + std::vector>> parts(limit); + std::vector indices; + indices.reserve(limit); std::exception_ptr error; try { @@ -407,6 +416,7 @@ namespace hpx::parallel::detail { segmented_fetch_values(), policy, std::true_type(), HPX_MOVE(pieces))); } + indices.push_back(indices.size()); it = end; } } @@ -414,20 +424,80 @@ namespace hpx::parallel::detail { { error = std::current_exception(); } - segmented_sort_wait(pending, error); - // Retain logical order even if the transfers finish out of order. - // All pending payloads together occupy at most one block. - for (auto& future : pending) + if (error) { - auto part = future.get(); - values.insert(values.end(), - std::make_move_iterator(part.begin()), - std::make_move_iterator(part.end())); + segmented_sort_wait(pending, error); + } + + // Consume completed transfers eagerly. Out-of-order results wait + // only for their preceding logical pieces. Exact reservation of + // values prevents repeated reallocation while pieces are appended. + auto const part_count = pending.size(); + std::size_t next_part = 0; + while (!pending.empty()) + { + if (hpx::wait_any_nothrow(pending)) + { + segmented_sort_wait(pending); + } + try + { + for (std::size_t i = pending.size(); i-- != 0;) + { + if (pending[i].is_ready()) + { + parts[indices[i]].emplace(pending[i].get()); + pending.erase(pending.begin() + + static_cast(i)); + indices.erase(indices.begin() + + static_cast(i)); + } + } + while (next_part != part_count && parts[next_part]) + { + auto& part = *parts[next_part]; + values.insert(values.end(), + std::make_move_iterator(part.begin()), + std::make_move_iterator(part.end())); + ++next_part; + } + } + catch (...) + { + segmented_sort_wait( + pending, std::current_exception()); + } } } return values; } + template + auto segmented_sort_fetch_pair(ExPolicy const& policy, + segmented_sort_block const& left, + segmented_sort_block const& right) + { + using value_type = std::iterator_traits::value_type; + std::vector>> pending; + pending.reserve(2); + std::exception_ptr error; + try + { + pending.push_back(hpx::async([policy, left]() { + return segmented_sort_fetch_block(policy, left); + })); + pending.push_back(hpx::async([policy, right]() { + return segmented_sort_fetch_block(policy, right); + })); + } + catch (...) + { + error = std::current_exception(); + } + segmented_sort_wait(pending, error); + return std::pair{pending[0].get(), pending[1].get()}; + } + template Iter segmented_sort_store_block(ExPolicy const& policy, segmented_sort_block const& block, Iter first) @@ -514,10 +584,12 @@ namespace hpx::parallel::detail { { } - template - static bool sequential(ExPolicy const& policy, + template + static bool execute(ExPolicy const& policy, segmented_sort_block const& left, - segmented_sort_block const& right, Comp comp, Proj proj) + segmented_sort_block const& right, Comp comp, Proj proj, + IsParallel) { // Sorting one local piece needs no communication or copy buffer. if (right.empty() && left.size() == 1) @@ -544,19 +616,31 @@ namespace hpx::parallel::detail { } std::vector output; { - auto left_values = segmented_sort_fetch_block(policy, left); if (right.empty()) { + auto left_values = segmented_sort_fetch_block(policy, left); hpx::sort(policy, left_values.begin(), left_values.end(), std::ref(pred)); output = HPX_MOVE(left_values); } else { - auto right_values = - segmented_sort_fetch_block(policy, right); - output = segmented_sort_merge_pair( - policy, left_values, right_values, std::ref(pred)); + if constexpr (IsParallel::value) + { + auto values = + segmented_sort_fetch_pair(policy, left, right); + output = segmented_sort_merge_pair(policy, values.first, + values.second, std::ref(pred)); + } + else + { + auto left_values = + segmented_sort_fetch_block(policy, left); + auto right_values = + segmented_sort_fetch_block(policy, right); + output = segmented_sort_merge_pair( + policy, left_values, right_values, std::ref(pred)); + } } } @@ -568,13 +652,22 @@ namespace hpx::parallel::detail { return true; } + template + static bool sequential(ExPolicy const& policy, + segmented_sort_block const& left, + segmented_sort_block const& right, Comp comp, Proj proj) + { + return execute(policy, left, right, HPX_MOVE(comp), HPX_MOVE(proj), + std::false_type{}); + } + template static bool parallel(ExPolicy const& policy, segmented_sort_block const& left, segmented_sort_block const& right, Comp comp, Proj proj) { - return sequential( - policy, left, right, HPX_MOVE(comp), HPX_MOVE(proj)); + return execute(policy, left, right, HPX_MOVE(comp), HPX_MOVE(proj), + std::true_type{}); } }; From cb3e1b836a1ecfd75eceb6a7de274e4e6c947c83 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Thu, 1 Oct 2026 02:52:49 +0530 Subject: [PATCH 27/37] Parallelize the segmented bitonic merge network Signed-off-by: the-ivii --- .../parallel/segmented_algorithms/sort.hpp | 228 +++++++++++------- .../tests/unit/partitioned_vector_sort.cpp | 86 ++++++- 2 files changed, 229 insertions(+), 85 deletions(-) diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp index 8897d03e27e1..0b1cfb451a04 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp @@ -696,37 +696,127 @@ namespace hpx::parallel::detail { } }; - // Batcher odd-even merge stages. With K blocks, O(log^2 K) stages trade - // additional communication rounds for bounded merge buffers. All - // comparisons are ascending, so a short final block and absent blocks - // behave as trailing infinities without constructing sentinel values or - // requiring a power-of-two size. - template - void segmented_sort_merge_stages(std::size_t count, F stage) + template + std::map segmented_sort_worker_counts( + ExPolicy const& policy, + std::vector> const& blocks) { - std::vector pairs; - pairs.reserve(count / 2); - for (std::size_t width = 1; width < count; width *= 2) + std::set hosts; + for (auto const& block : blocks) + { + for (auto const& run : block) + { + hosts.insert(run.locality); + } + } + + std::map worker_counts; + std::vector remote_hosts; + std::vector> pending; + remote_hosts.reserve(hosts.size()); + pending.reserve(hosts.size()); + auto const here = hpx::find_here(); + std::exception_ptr error; + try { - for (std::size_t stride = width; stride != 0; stride /= 2) + for (auto const& host : hosts) { - pairs.clear(); - for (std::size_t start = stride % width; start + stride < count; - start += 2 * stride) + if (host == here) { - for (std::size_t i = 0; - i < stride && start + i + stride < count; ++i) - { - auto const left = start + i; - auto const right = left + stride; - if (left / (2 * width) == right / (2 * width)) - { - pairs.emplace_back(left, right); - } - } + worker_counts[host] = + segmented_sort_worker_count::sequential(policy); } - stage(pairs); + else + { + remote_hosts.push_back(host); + pending.push_back( + dispatch_async(host, segmented_sort_worker_count(), + policy, std::true_type())); + } + } + } + catch (...) + { + error = std::current_exception(); + } + segmented_sort_wait(pending, error); + for (std::size_t i = 0; i != pending.size(); ++i) + { + worker_counts[remote_hosts[i]] = pending[i].get(); + } + return worker_counts; + } + + template + void segmented_sort_bitonic_merge( + std::size_t first, std::size_t count, bool ascending, Emit& emit) + { + if (count <= 1) + { + return; + } + + std::size_t stride = 1; + while (stride < count - stride) + { + stride *= 2; + } + for (std::size_t i = first; i != first + count - stride; ++i) + { + emit(i, i + stride, ascending); + } + segmented_sort_bitonic_merge(first, stride, ascending, emit); + segmented_sort_bitonic_merge( + first + stride, count - stride, ascending, emit); + } + + template + void segmented_sort_bitonic_sort( + std::size_t first, std::size_t count, bool ascending, Emit& emit) + { + if (count <= 1) + { + return; + } + + auto const left_count = count / 2; + segmented_sort_bitonic_sort(first, left_count, !ascending, emit); + segmented_sort_bitonic_sort( + first + left_count, count - left_count, ascending, emit); + segmented_sort_bitonic_merge(first, count, ascending, emit); + } + + // Layer an arbitrary-size bitonic network into disjoint stages. Reversing + // a pair encodes a descending compare/split: the low half is written to + // the higher-index block. Fixed block capacities, including a short final + // block, therefore need neither padding nor sentinel values. + template + void segmented_sort_merge_stages(std::size_t count, F stage) + { + std::vector> stages; + std::vector next_stage(count); + auto emit = [&](std::size_t left, std::size_t right, bool ascending) { + auto const stage_index = + (std::max) (next_stage[left], next_stage[right]); + while (stages.size() <= stage_index) + { + stages.emplace_back(); + stages.back().reserve(count / 2); + } + if (ascending) + { + stages[stage_index].emplace_back(left, right); } + else + { + stages[stage_index].emplace_back(right, left); + } + next_stage[left] = next_stage[right] = stage_index + 1; + }; + segmented_sort_bitonic_sort(0, count, true, emit); + for (auto& pairs : stages) + { + stage(HPX_MOVE(pairs)); } } @@ -734,8 +824,9 @@ namespace hpx::parallel::detail { typename Proj, typename IsSeq> void segmented_sort_stage(ExPolicy const& policy, std::vector> const& blocks, - std::vector const& pairs, Comp const& comp, - Proj const& proj, IsSeq is_seq) + std::vector pairs, + std::map const& worker_counts, + Comp const& comp, Proj const& proj, IsSeq is_seq) { using operation = segmented_sort_compare_split; segmented_sort_block const empty; @@ -766,57 +857,18 @@ namespace hpx::parallel::detail { { std::map> jobs; std::map assignments; - for (auto pair : pairs) + for (auto& pair : pairs) { auto host = segmented_sort_host( blocks[pair.first], right_block(pair), assignments); - jobs[host].push_back(pair); + jobs[host].push_back(HPX_MOVE(pair)); ++assignments[host]; } - std::map worker_counts; - bool const initial_stage = std::all_of(pairs.begin(), pairs.end(), - [](auto pair) { return pair.first == pair.second; }); - if (initial_stage) - { - std::vector remote_hosts; - std::vector> pending; - std::exception_ptr error; - try - { - for (auto const& job : jobs) - { - auto const& host = job.first; - if (host == here) - { - worker_counts[host] = - segmented_sort_worker_count::sequential(policy); - } - else - { - remote_hosts.push_back(host); - pending.push_back(dispatch_async(host, - segmented_sort_worker_count(), policy, - std::true_type())); - } - } - } - catch (...) - { - error = std::current_exception(); - } - segmented_sort_wait(pending, error); - for (std::size_t i = 0; i != pending.size(); ++i) - { - worker_counts[remote_hosts[i]] = pending[i].get(); - } - } - // Initial sorts can share a locality: buffered sorts charge two // blocks each, and in-place sorts need no value buffers. Bound - // scratch storage by the same four-block budget as one merge. - // Destination schedulers control worker use. Merge stages still - // run at most one compare/split per locality. + // scratch storage to four blocks per worker. Independent merge + // pairs can use all destination workers within that same bound. for (;;) { std::vector> pending; @@ -827,9 +879,9 @@ namespace hpx::parallel::detail { for (auto& [host, queue] : jobs) { std::size_t used = 0; - auto const workers = initial_stage ? - worker_counts[host] : - std::size_t(1); + auto const workers = worker_counts.at(host); + auto const memory_budget = + workers * 4 * segmented_sort_max_block_size; for (std::size_t active = 0; active != workers && !queue.empty(); ++active) { @@ -841,7 +893,7 @@ namespace hpx::parallel::detail { 0 : 2 * segmented_sort_block_size(left)) : 4 * segmented_sort_max_block_size; - if (used + cost > 4 * segmented_sort_max_block_size) + if (used + cost > memory_budget) { break; } @@ -862,10 +914,6 @@ namespace hpx::parallel::detail { dispatch_async(host, operation(), policy, is_seq, left, right, comp, proj)); } - if (!right.empty()) - { - break; - } } } } @@ -891,22 +939,34 @@ namespace hpx::parallel::detail { // Keep the single-partition path in place, regardless of its size. if (runs.size() == 1) { - segmented_sort_stage(policy, - std::vector>{runs}, {{0, 0}}, - comp, proj, is_seq); + std::vector> blocks{runs}; + std::map worker_counts; + if constexpr (!IsSeq::value) + { + worker_counts = segmented_sort_worker_counts(policy, blocks); + } + segmented_sort_stage( + policy, blocks, {{0, 0}}, worker_counts, comp, proj, is_seq); return; } auto const block_size = segmented_sort_block_capacity(runs); auto blocks = segmented_sort_blocks(runs, block_size); + std::map worker_counts; + if constexpr (!IsSeq::value) + { + worker_counts = segmented_sort_worker_counts(policy, blocks); + } std::vector initial; initial.reserve(blocks.size()); for (std::size_t i = 0; i != blocks.size(); ++i) { initial.emplace_back(i, i); } - segmented_sort_stage(policy, blocks, initial, comp, proj, is_seq); - segmented_sort_merge_stages(blocks.size(), [&](auto const& pairs) { - segmented_sort_stage(policy, blocks, pairs, comp, proj, is_seq); + segmented_sort_stage(policy, blocks, HPX_MOVE(initial), worker_counts, + comp, proj, is_seq); + segmented_sort_merge_stages(blocks.size(), [&](auto pairs) { + segmented_sort_stage(policy, blocks, HPX_MOVE(pairs), worker_counts, + comp, proj, is_seq); }); } diff --git a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp index c4554175a2f1..0861b4ba28fb 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -336,6 +336,21 @@ void test_sort_subranges( void test_merge_network() { namespace detail = hpx::parallel::detail; + + std::size_t stage_count = 0; + bool has_descending_pair = false; + detail::segmented_sort_merge_stages(16, [&](auto const& pairs) { + ++stage_count; + HPX_TEST_EQ(pairs.size(), std::size_t(8)); + for (auto const& pair : pairs) + { + has_descending_pair = + has_descending_pair || pair.first > pair.second; + } + }); + HPX_TEST_EQ(stage_count, std::size_t(10)); + HPX_TEST(has_descending_pair); + for (std::size_t count = 2; count <= 7; ++count) { for (std::size_t tail : {1, 2, 3}) @@ -718,14 +733,82 @@ void test_initial_sort_concurrency() auto runs = detail::segmented_sort_runs(values.begin(), values.end()); auto blocks = detail::segmented_sort_blocks(runs, size); initial_sort_probe::state = std::make_shared(); + auto worker_counts = + detail::segmented_sort_worker_counts(hpx::execution::par, blocks); detail::segmented_sort_stage(hpx::execution::par, blocks, {{0, 0}, {1, 1}}, - initial_sort_probe{}, hpx::identity_v, std::false_type{}); + worker_counts, initial_sort_probe{}, hpx::identity_v, + std::false_type{}); HPX_TEST(!initial_sort_probe::state->timed_out.load()); initial_sort_probe::state.reset(); auto got = copy_values(values); HPX_TEST(std::is_sorted(got.begin(), got.end())); } +struct merge_stage_probe_state +{ + std::array, 2> entered{}; + std::atomic started{0}; + hpx::promise both_started; + hpx::shared_future ready = both_started.get_future(); + std::atomic timed_out{false}; +}; + +struct merge_stage_probe +{ + inline static std::shared_ptr state; + static constexpr std::size_t block_size = 2048; + static constexpr int group_stride = 4 * static_cast(block_size); + + bool operator()(int a, int b) const + { + auto const group = + static_cast((std::min) (a, b) / group_stride); + if (!state->entered[group].exchange(true)) + { + if (++state->started == 2) + { + state->both_started.set_value(); + } + if (state->ready.wait_for(std::chrono::seconds(5)) != + hpx::future_status::ready) + { + state->timed_out = true; + } + } + return a < b; + } + + template + void serialize(Archive&, unsigned) + { + } +}; + +void test_merge_stage_concurrency() +{ + namespace detail = hpx::parallel::detail; + constexpr auto size = merge_stage_probe::block_size; + hpx::partitioned_vector values(4 * size, 0, + hpx::container_layout(4, std::vector{hpx::find_here()})); + initialize_values(values, [](std::size_t i) { + auto const block = i / size; + auto const offset = i % size; + return static_cast(block / 2) * merge_stage_probe::group_stride + + static_cast(2 * offset + block % 2); + }); + auto runs = detail::segmented_sort_runs(values.begin(), values.end()); + auto blocks = detail::segmented_sort_blocks(runs, size); + auto worker_counts = + detail::segmented_sort_worker_counts(hpx::execution::par, blocks); + merge_stage_probe::state = std::make_shared(); + detail::segmented_sort_stage(hpx::execution::par, blocks, {{0, 1}, {2, 3}}, + worker_counts, merge_stage_probe{}, hpx::identity_v, std::false_type{}); + HPX_TEST(!merge_stage_probe::state->timed_out.load()); + merge_stage_probe::state.reset(); + auto got = copy_values(values); + HPX_TEST(std::is_sorted(got.begin(), got.end())); +} + struct collection_gate { hpx::promise release; @@ -885,6 +968,7 @@ int main() if (hpx::get_os_thread_count() > 1) { test_initial_sort_concurrency(); + test_merge_stage_concurrency(); } test_ordered_endpoints(); test_transfer_batches(localities); From 121857c9a1cbb89ae7c5b62a6336c01fbb8808f2 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Thu, 1 Oct 2026 05:18:32 +0530 Subject: [PATCH 28/37] Use partition metadata for segmented sort placement Signed-off-by: the-ivii --- .../partitioned_vector_segmented_iterator.hpp | 14 ++++++++ .../parallel/segmented_algorithms/sort.hpp | 36 ++++++++++++++----- 2 files changed, 41 insertions(+), 9 deletions(-) diff --git a/components/containers/partitioned_vector/include/hpx/components/containers/partitioned_vector/partitioned_vector_segmented_iterator.hpp b/components/containers/partitioned_vector/include/hpx/components/containers/partitioned_vector/partitioned_vector_segmented_iterator.hpp index 805c11816bf5..c791f40cf8eb 100644 --- a/components/containers/partitioned_vector/include/hpx/components/containers/partitioned_vector/partitioned_vector_segmented_iterator.hpp +++ b/components/containers/partitioned_vector/include/hpx/components/containers/partitioned_vector/partitioned_vector_segmented_iterator.hpp @@ -1090,6 +1090,13 @@ namespace hpx::traits { { return iter->get_id(); } + + // Extract the locality id stored in the partition metadata. This + // avoids an AGAS lookup when an algorithm only needs placement. + static std::uint32_t get_locality_id(segment_iterator const& iter) + { + return iter.base()->locality_id_; + } }; template @@ -1182,6 +1189,13 @@ namespace hpx::traits { { return iter->get_id(); } + + // Extract the locality id stored in the partition metadata. This + // avoids an AGAS lookup when an algorithm only needs placement. + static std::uint32_t get_locality_id(segment_iterator const& iter) + { + return iter.base()->locality_id_; + } }; /////////////////////////////////////////////////////////////////////////// diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp index 0b1cfb451a04..960a2fd1e248 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp @@ -133,7 +133,17 @@ namespace hpx::parallel::detail { if (beg != end) { auto id = traits::get_id(segment); - runs.emplace_back(HPX_MOVE(id), hpx::id_type{}, beg, end); + if constexpr (requires { traits::get_locality_id(segment); }) + { + auto locality = hpx::naming::get_id_from_locality_id( + traits::get_locality_id(segment)); + runs.emplace_back( + HPX_MOVE(id), HPX_MOVE(locality), beg, end); + } + else + { + runs.emplace_back(HPX_MOVE(id), hpx::id_type{}, beg, end); + } } }; @@ -151,22 +161,30 @@ namespace hpx::parallel::detail { add_run(sit, traits::begin(sit), traits::local(last)); } - // Resolve independent namespace entries concurrently, with a bounded - // number of outstanding requests. Task policies collect runs inside - // their asynchronous operation, including this discovery phase. - for (std::size_t first_run = 0; first_run < runs.size();) + // Segmented containers without placement metadata still use bounded, + // concurrent namespace lookups. Task policies collect runs inside + // their asynchronous operation, including this fallback phase. + std::vector unresolved; + for (std::size_t i = 0; i != runs.size(); ++i) + { + if (runs[i].locality == hpx::invalid_id) + { + unresolved.push_back(i); + } + } + for (std::size_t first_run = 0; first_run < unresolved.size();) { std::vector> pending; auto const count = (std::min) (segmented_sort_transfer_limit, - runs.size() - first_run); + unresolved.size() - first_run); pending.reserve(count); std::exception_ptr error; try { for (std::size_t i = 0; i < count; ++i) { - pending.push_back( - hpx::get_colocation_id(runs[first_run + i].id)); + pending.push_back(hpx::get_colocation_id( + runs[unresolved[first_run + i]].id)); } } catch (...) @@ -177,7 +195,7 @@ namespace hpx::parallel::detail { pending, error); for (std::size_t i = 0; i < count; ++i) { - runs[first_run + i].locality = pending[i].get(); + runs[unresolved[first_run + i]].locality = pending[i].get(); } first_run += count; } From 88f4a3a14e97e5db63567f47a0189a97383eaba1 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Thu, 1 Oct 2026 05:20:38 +0530 Subject: [PATCH 29/37] Scale segmented sort by physical partition size Signed-off-by: the-ivii --- .../parallel/segmented_algorithms/sort.hpp | 254 +++++++++++------- .../tests/unit/partitioned_vector_sort.cpp | 166 ++++++++++-- 2 files changed, 308 insertions(+), 112 deletions(-) diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp index 960a2fd1e248..403b367f9b77 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp @@ -202,9 +202,9 @@ namespace hpx::parallel::detail { return runs; } - // Logical blocks have equal sizes except for the final block. They may - // span physical partitions, including clipped subrange endpoints. - inline constexpr std::size_t segmented_sort_max_block_size = 65536; + // Bound the payload of each remote transfer independently of the physical + // partition size. Physical partitions remain the sorting units. + inline constexpr std::size_t segmented_sort_transfer_chunk_size = 65536; template using segmented_sort_block = std::vector>; @@ -221,28 +221,24 @@ namespace hpx::parallel::detail { return size; } - // Multiple physical partitions on one locality should not increase the - // network depth. The cap bounds buffers when N / localities is large. + // Use the largest participating physical partition as the sorting unit. + // This keeps the number of network blocks no larger than the partition + // count while preserving equal capacities except for the final block. template std::size_t segmented_sort_block_capacity( segmented_sort_block const& runs) { - auto const total = segmented_sort_block_size(runs); - // A single bounded block avoids network stages for small ranges. - if (total <= segmented_sort_max_block_size) - { - return total; - } - std::set localities; + std::size_t capacity = 0; for (auto const& run : runs) { - localities.insert(run.locality); + capacity = + (std::max) (capacity, static_cast(run.size())); } - auto const count = localities.size(); - return (std::min) (segmented_sort_max_block_size, - total / count + (total % count != 0)); + return capacity; } + // Split blocks for production sorting, transfer chunks, and focused + // network tests. template auto segmented_sort_blocks( segmented_sort_block const& runs, std::size_t block_size) @@ -270,6 +266,27 @@ namespace hpx::parallel::detail { return blocks; } + template + auto segmented_sort_transfer_chunks( + segmented_sort_block const& block) + { + std::vector> chunks; + for (auto const& run : block) + { + auto first = run.first; + while (first != run.last) + { + auto const count = + (std::min) (segmented_sort_transfer_chunk_size, + static_cast(run.last - first)); + auto last = first + static_cast(count); + chunks.push_back({{run.id, run.locality, first, last}}); + first = last; + } + } + return chunks; + } + // Choose the locality holding the most input for this operation, summing // all participating pieces rather than selecting a single partition. // Balance equally good hosts across the current stage. @@ -401,11 +418,12 @@ namespace hpx::parallel::detail { } std::vector values; values.reserve(segmented_sort_block_size(block)); + auto chunks = segmented_sort_transfer_chunks(block); constexpr auto limit = hpx::is_sequenced_execution_policy_v ? 1 : segmented_sort_transfer_limit; - auto it = block.begin(); - while (it != block.end()) + auto it = chunks.begin(); + while (it != chunks.end()) { std::vector>> pending; pending.reserve(limit); @@ -415,14 +433,11 @@ namespace hpx::parallel::detail { std::exception_ptr error; try { - for (std::size_t i = 0; i < limit && it != block.end(); ++i) + for (std::size_t i = 0; i < limit && it != chunks.end(); ++i) { - auto end = - std::find_if(it, block.end(), [&](auto const& run) { - return run.locality != it->locality; - }); - segmented_sort_block pieces(it, end); - if (it->locality == here) + auto pieces = *it; + auto const host = pieces.front().locality; + if (host == here) { pending.push_back(hpx::make_ready_future( segmented_fetch_values::sequential( @@ -430,12 +445,12 @@ namespace hpx::parallel::detail { } else { - pending.push_back(dispatch_async(it->locality, + pending.push_back(dispatch_async(host, segmented_fetch_values(), policy, std::true_type(), HPX_MOVE(pieces))); } indices.push_back(indices.size()); - it = end; + ++it; } } catch (...) @@ -522,28 +537,26 @@ namespace hpx::parallel::detail { { using value_type = std::iterator_traits::value_type; auto const here = hpx::find_here(); + auto chunks = segmented_sort_transfer_chunks(block); constexpr auto limit = hpx::is_sequenced_execution_policy_v ? 1 : segmented_sort_transfer_limit; - auto it = block.begin(); - while (it != block.end()) + auto it = chunks.begin(); + while (it != chunks.end()) { std::vector> pending; pending.reserve(limit); std::exception_ptr error; try { - for (std::size_t i = 0; i < limit && it != block.end(); ++i) + for (std::size_t i = 0; i < limit && it != chunks.end(); ++i) { - auto end = - std::find_if(it, block.end(), [&](auto const& run) { - return run.locality != it->locality; - }); - segmented_sort_block pieces(it, end); + auto pieces = *it; + auto const host = pieces.front().locality; auto last = first + static_cast( segmented_sort_block_size(pieces)); - if (it->locality == here) + if (host == here) { using traits = hpx::traits::segmented_local_iterator_traits< @@ -562,13 +575,13 @@ namespace hpx::parallel::detail { std::vector values( std::make_move_iterator(first), std::make_move_iterator(last)); - pending.push_back(dispatch_async(it->locality, + pending.push_back(dispatch_async(host, segmented_store_values(), policy, std::true_type(), HPX_MOVE(pieces), HPX_MOVE(values))); } first = last; - it = end; + ++it; } } catch (...) @@ -883,66 +896,123 @@ namespace hpx::parallel::detail { ++assignments[host]; } - // Initial sorts can share a locality: buffered sorts charge two - // blocks each, and in-place sorts need no value buffers. Bound - // scratch storage to four blocks per worker. Independent merge - // pairs can use all destination workers within that same bound. - for (;;) - { - std::vector> pending; - pending.reserve(pairs.size()); - std::exception_ptr error; - try + std::vector> pending; + std::vector pending_hosts; + std::vector pending_costs; + pending.reserve(pairs.size()); + pending_hosts.reserve(pairs.size()); + pending_costs.reserve(pairs.size()); + std::map active; + std::map scratch_used; + + auto operation_cost = [&](segmented_sort_pair pair) { + auto const& left = blocks[pair.first]; + auto const& right = right_block(pair); + if (right.empty()) + { + return left.size() == 1 ? + std::size_t(0) : + 2 * segmented_sort_block_size(left); + } + return 2 * + (segmented_sort_block_size(left) + + segmented_sort_block_size(right)); + }; + + auto launch_available = [&](hpx::id_type const& host) { + auto& queue = jobs.at(host); + auto const workers = worker_counts.at(host); + auto const scratch_budget = + workers * 4 * segmented_sort_transfer_chunk_size; + while (active[host] != workers && !queue.empty()) { - for (auto& [host, queue] : jobs) + auto const pair = queue.back(); + auto const cost = operation_cost(pair); + // Always admit one oversized operation so progress does + // not depend on the physical partition size. + if (active[host] != 0 && + scratch_used[host] + cost > scratch_budget) { - std::size_t used = 0; - auto const workers = worker_counts.at(host); - auto const memory_budget = - workers * 4 * segmented_sort_max_block_size; - for (std::size_t active = 0; - active != workers && !queue.empty(); ++active) - { - auto const pair = queue.back(); - auto const& left = blocks[pair.first]; - auto const& right = right_block(pair); - auto const cost = right.empty() ? - (left.size() == 1 ? - 0 : - 2 * segmented_sort_block_size(left)) : - 4 * segmented_sort_max_block_size; - if (used + cost > memory_budget) - { - break; - } - used += cost; - queue.pop_back(); - if (host == here) - { - pending.push_back( - hpx::async([policy, left, right, comp, proj, - is_seq]() { - return operation().call2(policy, is_seq, - left, right, comp, proj); - })); - } - else - { - pending.push_back( - dispatch_async(host, operation(), policy, - is_seq, left, right, comp, proj)); - } - } + break; + } + queue.pop_back(); + auto const& left = blocks[pair.first]; + auto const& right = right_block(pair); + if (host == here) + { + pending.push_back(hpx::async( + [policy, left, right, comp, proj, is_seq]() { + return operation().call2( + policy, is_seq, left, right, comp, proj); + })); } + else + { + pending.push_back(dispatch_async(host, operation(), + policy, is_seq, left, right, comp, proj)); + } + pending_hosts.push_back(host); + pending_costs.push_back(cost); + ++active[host]; + scratch_used[host] += cost; } - catch (...) + }; + + std::exception_ptr error; + try + { + for (auto const& job : jobs) { - error = std::current_exception(); + launch_available(job.first); } + } + catch (...) + { + error = std::current_exception(); + } + if (error) + { segmented_sort_wait(pending, error); - if (pending.empty()) + } + + // Keep each host's worker window full as soon as one operation + // completes. Slow operations no longer impose round barriers on + // unrelated work. + while (!pending.empty()) + { + if (hpx::wait_any_nothrow(pending)) { - break; + segmented_sort_wait(pending); + } + std::set completed_hosts; + for (std::size_t i = pending.size(); i-- != 0;) + { + if (pending[i].is_ready()) + { + pending[i].get(); + auto const host = pending_hosts[i]; + --active[host]; + scratch_used[host] -= pending_costs[i]; + completed_hosts.insert(host); + pending.erase( + pending.begin() + static_cast(i)); + pending_hosts.erase(pending_hosts.begin() + + static_cast(i)); + pending_costs.erase(pending_costs.begin() + + static_cast(i)); + } + } + try + { + for (auto const& host : completed_hosts) + { + launch_available(host); + } + } + catch (...) + { + segmented_sort_wait( + pending, std::current_exception()); } } } @@ -967,8 +1037,8 @@ namespace hpx::parallel::detail { policy, blocks, {{0, 0}}, worker_counts, comp, proj, is_seq); return; } - auto const block_size = segmented_sort_block_capacity(runs); - auto blocks = segmented_sort_blocks(runs, block_size); + auto blocks = + segmented_sort_blocks(runs, segmented_sort_block_capacity(runs)); std::map worker_counts; if constexpr (!IsSeq::value) { diff --git a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp index 0861b4ba28fb..825df45ec3ff 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -411,6 +411,54 @@ void test_merge_network() } } +// Exercise the actual compare/split implementation with deliberately small +// blocks. Cover non-power-of-two block counts, short tails, and duplicates. +void test_forced_small_blocks() +{ + namespace detail = hpx::parallel::detail; + constexpr std::size_t block_size = 5; + for (std::size_t block_count : {3, 5, 6, 7}) + { + for (std::size_t tail = 1; tail != block_size; ++tail) + { + auto const size = (block_count - 1) * block_size + tail; + for (std::size_t seed = 0; seed != 16; ++seed) + { + std::vector values(size); + for (std::size_t i = 0; i != size; ++i) + { + values[i] = static_cast((i * 17 + seed * 13) % 11); + } + auto expected = values; + std::sort(expected.begin(), expected.end()); + + auto const here = hpx::find_here(); + detail::segmented_sort_block::iterator> runs{ + {here, here, values.begin(), values.end()}}; + auto blocks = detail::segmented_sort_blocks(runs, block_size); + HPX_TEST_EQ(blocks.size(), block_count); + std::vector initial; + for (std::size_t i = 0; i != blocks.size(); ++i) + { + initial.emplace_back(i, i); + } + std::map worker_counts; + detail::segmented_sort_stage(hpx::execution::seq, blocks, + HPX_MOVE(initial), worker_counts, std::less{}, + hpx::identity_v, std::true_type{}); + detail::segmented_sort_merge_stages( + blocks.size(), [&](auto pairs) { + detail::segmented_sort_stage(hpx::execution::seq, + blocks, HPX_MOVE(pairs), worker_counts, + std::less{}, hpx::identity_v, + std::true_type{}); + }); + HPX_TEST(values == expected); + } + } + } +} + struct counted_sort_value { inline static std::atomic live{0}; @@ -459,7 +507,7 @@ HPX_REGISTER_PARTITIONED_VECTOR(counted_sort_value) void test_merge_buffer() { namespace detail = hpx::parallel::detail; - auto const size = detail::segmented_sort_max_block_size; + auto const size = detail::segmented_sort_transfer_chunk_size; { std::vector left(size), right(size); for (std::size_t i = 0; i < size; ++i) @@ -499,7 +547,7 @@ void test_host_placement(std::vector const& localities) { namespace detail = hpx::parallel::detail; constexpr auto unit = static_cast( - detail::segmented_sort_max_block_size / 32 + 1); + detail::segmented_sort_transfer_chunk_size / 32 + 1); std::vector data(static_cast(45 * unit)); using iterator = std::vector::iterator; detail::segmented_sort_block runs; @@ -513,7 +561,7 @@ void test_host_placement(std::vector const& localities) } HPX_TEST(detail::segmented_sort_host(runs, {}) == b); HPX_TEST_EQ(detail::segmented_sort_block_capacity(runs), - a == b ? detail::segmented_sort_max_block_size : (data.size() + 1) / 2); + static_cast(5 * unit)); if (a != b) { @@ -552,10 +600,11 @@ void test_host_placement(std::vector const& localities) } } -void test_bounded_blocks(std::vector const& localities) +void test_partition_blocks_and_transfer_chunks( + std::vector const& localities) { namespace detail = hpx::parallel::detail; - auto const size = 8 * detail::segmented_sort_max_block_size + 7; + auto const size = 8 * detail::segmented_sort_transfer_chunk_size + 7; hpx::partitioned_vector values( size, 0, hpx::container_layout(3, localities)); initialize_values(values, @@ -564,19 +613,27 @@ void test_bounded_blocks(std::vector const& localities) std::sort(expected.begin() + 1, expected.end() - 2); auto runs = detail::segmented_sort_runs(values.begin() + 1, values.end() - 2); - auto blocks = detail::segmented_sort_blocks( - runs, detail::segmented_sort_max_block_size); - std::size_t total = 0; - for (std::size_t i = 0; i < blocks.size(); ++i) + auto const capacity = detail::segmented_sort_block_capacity(runs); + auto blocks = detail::segmented_sort_blocks(runs, capacity); + HPX_TEST_LTE(blocks.size(), runs.size()); + for (std::size_t i = 0; i != blocks.size(); ++i) { - auto const n = detail::segmented_sort_block_size(blocks[i]); - HPX_TEST_LTE(n, detail::segmented_sort_max_block_size); + auto const block_size = detail::segmented_sort_block_size(blocks[i]); + HPX_TEST_LTE(block_size, capacity); if (i + 1 != blocks.size()) { - HPX_TEST_EQ(n, detail::segmented_sort_max_block_size); + HPX_TEST_EQ(block_size, capacity); } + } + + auto chunks = detail::segmented_sort_transfer_chunks(runs); + std::size_t total = 0; + for (auto const& chunk : chunks) + { + auto const n = detail::segmented_sort_block_size(chunk); + HPX_TEST_LTE(n, detail::segmented_sort_transfer_chunk_size); total += n; - for (auto const& run : blocks[i]) + for (auto const& run : chunk) { HPX_TEST(run.locality == hpx::get_colocation_id(hpx::launch::sync, run.id)); @@ -592,7 +649,7 @@ void test_bounded_blocks(std::vector const& localities) // Exercise the distributed merge with nontrivial values and descending // order as well as the default integer comparator above. hpx::partitioned_vector strings( - 2 * detail::segmented_sort_max_block_size + 7, std::string{}, + 2 * detail::segmented_sort_transfer_chunk_size + 7, std::string{}, hpx::container_layout(3, localities)); initialize_values(strings, [](std::size_t i) { return std::to_string((i * 17 + 3) % 97) + std::string(32, 'x'); @@ -615,7 +672,7 @@ struct throwing_merge_less // Each initial block lies within one band. Only a merge compares // different bands, after the local sort phase has succeeded. constexpr auto band_size = static_cast( - hpx::parallel::detail::segmented_sort_max_block_size); + hpx::parallel::detail::segmented_sort_transfer_chunk_size); if (a / band_size != b / band_size) { if (allocation) @@ -641,7 +698,7 @@ void test_merge_exceptions( for (bool allocation : {false, true}) { auto const size = - 4 * hpx::parallel::detail::segmented_sort_max_block_size; + 4 * hpx::parallel::detail::segmented_sort_transfer_chunk_size; hpx::partitioned_vector values( size, 0, hpx::container_layout(4, localities)); initialize_values(values, [](int i) { return i; }); @@ -693,7 +750,7 @@ struct initial_sort_probe { inline static std::shared_ptr state; static constexpr auto block_size = - hpx::parallel::detail::segmented_sort_max_block_size; + hpx::parallel::detail::segmented_sort_transfer_chunk_size; bool operator()(int a, int b) const { @@ -723,8 +780,8 @@ void test_initial_sort_concurrency() { namespace detail = hpx::parallel::detail; constexpr auto size = initial_sort_probe::block_size; - // Four physical pieces produce two buffered logical blocks on this - // locality, together using the complete four-block scratch budget. + // Four physical pieces produce two forced logical blocks on this + // locality for the scheduler test. hpx::partitioned_vector values(2 * size, 0, hpx::container_layout(4, std::vector{hpx::find_here()})); initialize_values(values, [](std::size_t i) { @@ -809,6 +866,73 @@ void test_merge_stage_concurrency() HPX_TEST(std::is_sorted(got.begin(), got.end())); } +struct sliding_stage_probe_state +{ + std::array, 3> entered{}; + hpx::promise third_started; + hpx::shared_future ready = third_started.get_future(); + std::atomic timed_out{false}; +}; + +struct sliding_stage_probe +{ + inline static std::shared_ptr state; + static constexpr std::size_t block_size = 1024; + static constexpr int group_stride = 4 * static_cast(block_size); + + bool operator()(int a, int b) const + { + auto const group = + static_cast((std::min) (a, b) / group_stride); + if (!state->entered[group].exchange(true)) + { + if (group == 0) + { + state->third_started.set_value(); + } + else if (group == 2 && + state->ready.wait_for(std::chrono::seconds(5)) != + hpx::future_status::ready) + { + state->timed_out = true; + } + } + return a < b; + } + + template + void serialize(Archive&, unsigned) + { + } +}; + +void test_sliding_stage_window() +{ + namespace detail = hpx::parallel::detail; + constexpr auto size = sliding_stage_probe::block_size; + std::vector values(6 * size); + for (std::size_t i = 0; i != values.size(); ++i) + { + auto const block = i / size; + auto const offset = i % size; + values[i] = + static_cast(block / 2) * sliding_stage_probe::group_stride + + static_cast(2 * offset + block % 2); + } + auto const here = hpx::find_here(); + detail::segmented_sort_block::iterator> runs{ + {here, here, values.begin(), values.end()}}; + auto blocks = detail::segmented_sort_blocks(runs, size); + std::map worker_counts{{here, 2}}; + sliding_stage_probe::state = std::make_shared(); + detail::segmented_sort_stage(hpx::execution::par, blocks, + {{0, 1}, {2, 3}, {4, 5}}, worker_counts, sliding_stage_probe{}, + hpx::identity_v, std::false_type{}); + HPX_TEST(!sliding_stage_probe::state->timed_out.load()); + sliding_stage_probe::state.reset(); + HPX_TEST(std::is_sorted(values.begin(), values.end())); +} + struct collection_gate { hpx::promise release; @@ -962,13 +1086,15 @@ int main() { std::vector localities = hpx::find_all_localities(); test_merge_network(); + test_forced_small_blocks(); test_merge_buffer(); test_host_placement(localities); - test_bounded_blocks(localities); + test_partition_blocks_and_transfer_chunks(localities); if (hpx::get_os_thread_count() > 1) { test_initial_sort_concurrency(); test_merge_stage_concurrency(); + test_sliding_stage_window(); } test_ordered_endpoints(); test_transfer_batches(localities); From b8431466ec411b36e077cb12ecc368f4fc512ced Mon Sep 17 00:00:00 2001 From: the-ivii Date: Thu, 1 Oct 2026 05:20:45 +0530 Subject: [PATCH 30/37] Avoid remote segmented sort endpoint probes Signed-off-by: the-ivii --- .../parallel/segmented_algorithms/sort.hpp | 27 +++++++++++++------ .../tests/unit/partitioned_vector_sort.cpp | 2 +- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp index 403b367f9b77..d13cbec4730d 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp @@ -632,15 +632,18 @@ namespace hpx::parallel::detail { using value_type = std::iterator_traits::value_type; util::compare_projected pred(comp, proj); - if (!right.empty()) + // Avoid a network round trip for an endpoint probe. When both + // endpoints are local, this inexpensive check still skips all + // merge buffers for already ordered blocks. + auto const here = hpx::find_here(); + if (!right.empty() && left.back().locality == here && + right.front().locality == here) { - auto left_end = left.back(); - left_end.first = left_end.last - 1; - auto right_begin = right.front(); - right_begin.last = right_begin.first + 1; - auto endpoints = segmented_sort_fetch_block(policy, - segmented_sort_block{left_end, right_begin}); - if (!pred(endpoints[1], endpoints[0])) + using traits = + hpx::traits::segmented_local_iterator_traits; + auto left_end = traits::local(left.back().last - 1); + auto right_begin = traits::local(right.front().first); + if (!pred(*right_begin, *left_end)) { return true; } @@ -1108,6 +1111,11 @@ namespace hpx::segmented { /// \brief Segmented overload of \a hpx::sort for /// \a partitioned_vector iterators. + /// + /// Remote partition operations are issued one at a time by this + /// overload. Use a parallel execution policy to overlap independent + /// operations. For ranges spanning localities, the comparator must be + /// copyable and serializable by HPX. HPX_CXX_EXPORT template requires(hpx::traits::is_iterator_v && @@ -1128,6 +1136,9 @@ namespace hpx::segmented { } /// \brief Segmented overload of \a hpx::sort with an execution policy. + /// + /// For ranges spanning localities, the comparator must be copyable and + /// serializable by HPX. HPX_CXX_EXPORT template requires(hpx::is_execution_policy_v && diff --git a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp index 825df45ec3ff..1c77b61b4b37 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -1032,7 +1032,7 @@ void test_ordered_endpoints() detail::segmented_sort_compare_split::sequential( hpx::execution::seq, blocks[0], blocks[1], counted_value_less{}, hpx::identity_v); - HPX_TEST_EQ(counted_sort_value::copies.load(), std::size_t(2)); + HPX_TEST_EQ(counted_sort_value::copies.load(), std::size_t(0)); auto got = copy_values(values); for (std::size_t i = 0; i < got.size(); ++i) { From e18928439f6cccba51f10945c583084e100b618b Mon Sep 17 00:00:00 2001 From: the-ivii Date: Thu, 1 Oct 2026 05:28:32 +0530 Subject: [PATCH 31/37] Harden segmented sort scheduling regressions Signed-off-by: the-ivii --- .../tests/unit/partitioned_vector_sort.cpp | 33 ++++++++++--------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp index 1c77b61b4b37..86adc9407541 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -701,7 +701,12 @@ void test_merge_exceptions( 4 * hpx::parallel::detail::segmented_sort_transfer_chunk_size; hpx::partitioned_vector values( size, 0, hpx::container_layout(4, localities)); - initialize_values(values, [](int i) { return i; }); + initialize_values(values, [](std::size_t i) { + constexpr auto band_size = + hpx::parallel::detail::segmented_sort_transfer_chunk_size; + auto const band = i / band_size; + return static_cast((3 - band) * band_size + i % band_size); + }); bool caught = false; try { @@ -734,16 +739,13 @@ void test_merge_exceptions( } } -// This comparator observes overlap between two initial block sorts. Waiting -// on an HPX future yields the worker, and the timeout also diagnoses the old -// serial scheduler without hanging the test. +// This comparator observes overlap between two initial block sorts. Sleeping +// suspends the HPX thread so another sort can enter on the same locality. struct initial_sort_probe_state { std::array, 2> entered{}; - std::atomic started{0}; - hpx::promise both_started; - hpx::shared_future ready = both_started.get_future(); - std::atomic timed_out{false}; + std::atomic active{0}; + std::atomic peak{0}; }; struct initial_sort_probe @@ -757,15 +759,14 @@ struct initial_sort_probe auto const block = static_cast(a) / block_size; if (!state->entered[block].exchange(true)) { - if (++state->started == 2) + auto const current = ++state->active; + auto previous = state->peak.load(); + while (previous < current && + !state->peak.compare_exchange_weak(previous, current)) { - state->both_started.set_value(); - } - if (state->ready.wait_for(std::chrono::seconds(5)) != - hpx::future_status::ready) - { - state->timed_out = true; } + hpx::this_thread::sleep_for(std::chrono::milliseconds(20)); + --state->active; } return a < b; } @@ -795,7 +796,7 @@ void test_initial_sort_concurrency() detail::segmented_sort_stage(hpx::execution::par, blocks, {{0, 0}, {1, 1}}, worker_counts, initial_sort_probe{}, hpx::identity_v, std::false_type{}); - HPX_TEST(!initial_sort_probe::state->timed_out.load()); + HPX_TEST_EQ(initial_sort_probe::state->peak.load(), std::size_t(2)); initial_sort_probe::state.reset(); auto got = copy_values(values); HPX_TEST(std::is_sorted(got.begin(), got.end())); From 6150a6a875572ca1c7a8d900f5025504cf9de0a4 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Thu, 1 Oct 2026 22:44:38 +0530 Subject: [PATCH 32/37] Replace segmented sort stages with a k-way merge Signed-off-by: the-ivii --- .../parallel/segmented_algorithms/sort.hpp | 730 +++++------------- .../tests/unit/partitioned_vector_sort.cpp | 539 ++----------- 2 files changed, 264 insertions(+), 1005 deletions(-) diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp index d13cbec4730d..2cc10c60e443 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp @@ -7,6 +7,7 @@ #pragma once #include +#include #include #include #include @@ -20,12 +21,10 @@ #include #include #include -#include #include #include #include -#include -#include +#include #include #include #include @@ -221,51 +220,6 @@ namespace hpx::parallel::detail { return size; } - // Use the largest participating physical partition as the sorting unit. - // This keeps the number of network blocks no larger than the partition - // count while preserving equal capacities except for the final block. - template - std::size_t segmented_sort_block_capacity( - segmented_sort_block const& runs) - { - std::size_t capacity = 0; - for (auto const& run : runs) - { - capacity = - (std::max) (capacity, static_cast(run.size())); - } - return capacity; - } - - // Split blocks for production sorting, transfer chunks, and focused - // network tests. - template - auto segmented_sort_blocks( - segmented_sort_block const& runs, std::size_t block_size) - { - std::vector> blocks; - std::size_t remaining = 0; - for (auto const& run : runs) - { - auto first = run.first; - while (first != run.last) - { - if (remaining == 0) - { - blocks.emplace_back(); - remaining = block_size; - } - auto const count = (std::min) (remaining, - static_cast(run.last - first)); - auto last = first + static_cast(count); - blocks.back().emplace_back(run.id, run.locality, first, last); - first = last; - remaining -= count; - } - } - return blocks; - } - template auto segmented_sort_transfer_chunks( segmented_sort_block const& block) @@ -287,14 +241,12 @@ namespace hpx::parallel::detail { return chunks; } - // Choose the locality holding the most input for this operation, summing - // all participating pieces rather than selecting a single partition. - // Balance equally good hosts across the current stage. + // Choose the locality holding the most participating data so the k-way + // merge transfers as little input as possible. template hpx::id_type segmented_sort_host( segmented_sort_block const& left, - segmented_sort_block const& right, - std::map const& assignments) + segmented_sort_block const& right) { std::map sizes; for (auto const& run : left) @@ -305,16 +257,10 @@ namespace hpx::parallel::detail { { sizes[run.locality] += static_cast(run.size()); } - auto assigned = [&](hpx::id_type const& locality) { - auto const it = assignments.find(locality); - return it == assignments.end() ? std::size_t(0) : it->second; - }; auto host = sizes.begin(); for (auto it = std::next(host); it != sizes.end(); ++it) { - if (it->second > host->second || - (it->second == host->second && - assigned(it->first) < assigned(host->first))) + if (it->second > host->second) { host = it; } @@ -322,15 +268,6 @@ namespace hpx::parallel::detail { return host->first; } - template - hpx::id_type segmented_sort_host( - segmented_sort_block const& left, - segmented_sort_block const& right) - { - return segmented_sort_host( - left, right, std::map{}); - } - template struct segmented_fetch_values : algorithm, @@ -354,8 +291,17 @@ namespace hpx::parallel::detail { values.reserve(segmented_sort_block_size(runs)); for (auto const& run : runs) { - values.insert(values.end(), traits::local(run.first), - traits::local(run.last)); + if constexpr (std::is_copy_constructible_v) + { + values.insert(values.end(), traits::local(run.first), + traits::local(run.last)); + } + else + { + values.insert(values.end(), + std::make_move_iterator(traits::local(run.first)), + std::make_move_iterator(traits::local(run.last))); + } } return values; } @@ -427,9 +373,6 @@ namespace hpx::parallel::detail { { std::vector>> pending; pending.reserve(limit); - std::vector>> parts(limit); - std::vector indices; - indices.reserve(limit); std::exception_ptr error; try { @@ -449,7 +392,6 @@ namespace hpx::parallel::detail { segmented_fetch_values(), policy, std::true_type(), HPX_MOVE(pieces))); } - indices.push_back(indices.size()); ++it; } } @@ -457,80 +399,18 @@ namespace hpx::parallel::detail { { error = std::current_exception(); } - if (error) - { - segmented_sort_wait(pending, error); - } - - // Consume completed transfers eagerly. Out-of-order results wait - // only for their preceding logical pieces. Exact reservation of - // values prevents repeated reallocation while pieces are appended. - auto const part_count = pending.size(); - std::size_t next_part = 0; - while (!pending.empty()) + segmented_sort_wait(pending, error); + for (auto& future : pending) { - if (hpx::wait_any_nothrow(pending)) - { - segmented_sort_wait(pending); - } - try - { - for (std::size_t i = pending.size(); i-- != 0;) - { - if (pending[i].is_ready()) - { - parts[indices[i]].emplace(pending[i].get()); - pending.erase(pending.begin() + - static_cast(i)); - indices.erase(indices.begin() + - static_cast(i)); - } - } - while (next_part != part_count && parts[next_part]) - { - auto& part = *parts[next_part]; - values.insert(values.end(), - std::make_move_iterator(part.begin()), - std::make_move_iterator(part.end())); - ++next_part; - } - } - catch (...) - { - segmented_sort_wait( - pending, std::current_exception()); - } + auto part = future.get(); + values.insert(values.end(), + std::make_move_iterator(part.begin()), + std::make_move_iterator(part.end())); } } return values; } - template - auto segmented_sort_fetch_pair(ExPolicy const& policy, - segmented_sort_block const& left, - segmented_sort_block const& right) - { - using value_type = std::iterator_traits::value_type; - std::vector>> pending; - pending.reserve(2); - std::exception_ptr error; - try - { - pending.push_back(hpx::async([policy, left]() { - return segmented_sort_fetch_block(policy, left); - })); - pending.push_back(hpx::async([policy, right]() { - return segmented_sort_fetch_block(policy, right); - })); - } - catch (...) - { - error = std::current_exception(); - } - segmented_sort_wait(pending, error); - return std::pair{pending[0].get(), pending[1].get()}; - } - template Iter segmented_sort_store_block(ExPolicy const& policy, segmented_sort_block const& block, Iter first) @@ -593,472 +473,260 @@ namespace hpx::parallel::detail { return first; } - // Merge directly into the destination. There is no serial copy of the - // merged output into a second vector. - template - std::vector segmented_sort_merge_pair(ExPolicy const& policy, - std::vector const& left, std::vector const& right, Pred pred) - { - std::vector merged(left.size() + right.size()); - hpx::merge(policy, left.begin(), left.end(), right.begin(), right.end(), - merged.begin(), pred); - return merged; - } - - template - struct segmented_sort_compare_split - : algorithm, bool> - { - constexpr segmented_sort_compare_split() noexcept - : algorithm( - "segmented_sort_compare_split") - { - } - - template - static bool execute(ExPolicy const& policy, - segmented_sort_block const& left, - segmented_sort_block const& right, Comp comp, Proj proj, - IsParallel) - { - // Sorting one local piece needs no communication or copy buffer. - if (right.empty() && left.size() == 1) - { - segmented_local_sort::sequential( - policy, left[0].first, left[0].last, comp, proj); - return true; - } - - using value_type = std::iterator_traits::value_type; - util::compare_projected pred(comp, proj); - // Avoid a network round trip for an endpoint probe. When both - // endpoints are local, this inexpensive check still skips all - // merge buffers for already ordered blocks. - auto const here = hpx::find_here(); - if (!right.empty() && left.back().locality == here && - right.front().locality == here) - { - using traits = - hpx::traits::segmented_local_iterator_traits; - auto left_end = traits::local(left.back().last - 1); - auto right_begin = traits::local(right.front().first); - if (!pred(*right_begin, *left_end)) - { - return true; - } - } - std::vector output; - { - if (right.empty()) - { - auto left_values = segmented_sort_fetch_block(policy, left); - hpx::sort(policy, left_values.begin(), left_values.end(), - std::ref(pred)); - output = HPX_MOVE(left_values); - } - else - { - if constexpr (IsParallel::value) - { - auto values = - segmented_sort_fetch_pair(policy, left, right); - output = segmented_sort_merge_pair(policy, values.first, - values.second, std::ref(pred)); - } - else - { - auto left_values = - segmented_sort_fetch_block(policy, left); - auto right_values = - segmented_sort_fetch_block(policy, right); - output = segmented_sort_merge_pair( - policy, left_values, right_values, std::ref(pred)); - } - } - } - - // Both inputs have been read completely before either is changed. - // Release the input buffers before allocating outbound pieces. - auto middle = - segmented_sort_store_block(policy, left, output.begin()); - segmented_sort_store_block(policy, right, middle); - return true; - } - - template - static bool sequential(ExPolicy const& policy, - segmented_sort_block const& left, - segmented_sort_block const& right, Comp comp, Proj proj) - { - return execute(policy, left, right, HPX_MOVE(comp), HPX_MOVE(proj), - std::false_type{}); - } - - template - static bool parallel(ExPolicy const& policy, - segmented_sort_block const& left, - segmented_sort_block const& right, Comp comp, Proj proj) - { - return execute(policy, left, right, HPX_MOVE(comp), HPX_MOVE(proj), - std::true_type{}); - } - }; - - using segmented_sort_pair = std::pair; - - struct segmented_sort_worker_count - : algorithm + // Merge the sorted input runs without constructing a second full-size + // output buffer. Values are selected once into one destination buffer at + // a time. + template + void segmented_sort_kway_for_each(std::vector& values, + std::vector const& offsets, + std::vector const& counts, Pred& pred, Emit&& emit) { - constexpr segmented_sort_worker_count() noexcept - : algorithm( - "segmented_sort_worker_count") - { - } - - template - static std::size_t sequential(ExPolicy const&) + struct cursor { - return (std::max) (std::size_t(1), - static_cast(hpx::get_os_thread_count())); - } + std::size_t pos; + std::size_t end; + }; - template - static std::size_t parallel(ExPolicy const& policy) - { - return sequential(policy); - } - }; + auto order = [&](cursor const& lhs, cursor const& rhs) { + return pred(values[rhs.pos], values[lhs.pos]); + }; + std::priority_queue, decltype(order)> heap( + order); - template - std::map segmented_sort_worker_counts( - ExPolicy const& policy, - std::vector> const& blocks) - { - std::set hosts; - for (auto const& block : blocks) + for (std::size_t i = 0; i != counts.size(); ++i) { - for (auto const& run : block) + if (counts[i] != 0) { - hosts.insert(run.locality); + heap.push(cursor{offsets[i], offsets[i] + counts[i]}); } } - std::map worker_counts; - std::vector remote_hosts; - std::vector> pending; - remote_hosts.reserve(hosts.size()); - pending.reserve(hosts.size()); - auto const here = hpx::find_here(); - std::exception_ptr error; - try + while (!heap.empty()) { - for (auto const& host : hosts) + auto current = heap.top(); + heap.pop(); + emit(HPX_MOVE(values[current.pos])); + if (++current.pos != current.end) { - if (host == here) - { - worker_counts[host] = - segmented_sort_worker_count::sequential(policy); - } - else - { - remote_hosts.push_back(host); - pending.push_back( - dispatch_async(host, segmented_sort_worker_count(), - policy, std::true_type())); - } + heap.push(current); } } - catch (...) - { - error = std::current_exception(); - } - segmented_sort_wait(pending, error); - for (std::size_t i = 0; i != pending.size(); ++i) - { - worker_counts[remote_hosts[i]] = pending[i].get(); - } - return worker_counts; } - template - void segmented_sort_bitonic_merge( - std::size_t first, std::size_t count, bool ascending, Emit& emit) + template + struct segmented_sort_local_runs_on_host + : algorithm, bool> { - if (count <= 1) + constexpr segmented_sort_local_runs_on_host() noexcept + : algorithm( + "segmented_sort_local_runs_on_host") { - return; } - std::size_t stride = 1; - while (stride < count - stride) - { - stride *= 2; - } - for (std::size_t i = first; i != first + count - stride; ++i) + template + static bool sequential(ExPolicy const& policy, + segmented_sort_block const& runs, Comp comp, Proj proj) { - emit(i, i + stride, ascending); + for (auto const& run : runs) + { + segmented_local_sort::sequential( + policy, run.first, run.last, comp, proj); + } + return true; } - segmented_sort_bitonic_merge(first, stride, ascending, emit); - segmented_sort_bitonic_merge( - first + stride, count - stride, ascending, emit); - } - template - void segmented_sort_bitonic_sort( - std::size_t first, std::size_t count, bool ascending, Emit& emit) - { - if (count <= 1) + template + static bool parallel(ExPolicy const& policy, + segmented_sort_block const& runs, Comp comp, Proj proj) { - return; + return sequential(policy, runs, HPX_MOVE(comp), HPX_MOVE(proj)); } + }; - auto const left_count = count / 2; - segmented_sort_bitonic_sort(first, left_count, !ascending, emit); - segmented_sort_bitonic_sort( - first + left_count, count - left_count, ascending, emit); - segmented_sort_bitonic_merge(first, count, ascending, emit); - } - - // Layer an arbitrary-size bitonic network into disjoint stages. Reversing - // a pair encodes a descending compare/split: the low half is written to - // the higher-index block. Fixed block capacities, including a short final - // block, therefore need neither padding nor sentinel values. - template - void segmented_sort_merge_stages(std::size_t count, F stage) + // Send one operation to each participating locality. A parallel policy + // overlaps localities, while each operation applies the caller's policy to + // every complete physical partition on that locality. + template + void segmented_sort_local_runs(ExPolicy const& policy, + segmented_sort_block const& runs, Comp const& comp, + Proj const& proj, IsSeq is_seq) { - std::vector> stages; - std::vector next_stage(count); - auto emit = [&](std::size_t left, std::size_t right, bool ascending) { - auto const stage_index = - (std::max) (next_stage[left], next_stage[right]); - while (stages.size() <= stage_index) - { - stages.emplace_back(); - stages.back().reserve(count / 2); - } - if (ascending) - { - stages[stage_index].emplace_back(left, right); - } - else - { - stages[stage_index].emplace_back(right, left); - } - next_stage[left] = next_stage[right] = stage_index + 1; - }; - segmented_sort_bitonic_sort(0, count, true, emit); - for (auto& pairs : stages) + using operation = segmented_sort_local_runs_on_host; + std::map> groups; + for (auto const& run : runs) { - stage(HPX_MOVE(pairs)); + groups[run.locality].push_back(run); } - } - template - void segmented_sort_stage(ExPolicy const& policy, - std::vector> const& blocks, - std::vector pairs, - std::map const& worker_counts, - Comp const& comp, Proj const& proj, IsSeq is_seq) - { - using operation = segmented_sort_compare_split; - segmented_sort_block const empty; auto const here = hpx::find_here(); - auto right_block = [&](segmented_sort_pair pair) -> auto const& { - return pair.first == pair.second ? empty : blocks[pair.second]; - }; - if constexpr (IsSeq::value) { - for (auto pair : pairs) + for (auto const& [host, local_runs] : groups) { - auto const& left = blocks[pair.first]; - auto const& right = right_block(pair); - auto const host = segmented_sort_host(left, right); if (host == here) { - operation().call2(policy, is_seq, left, right, comp, proj); + operation::sequential(policy, local_runs, comp, proj); } else { - dispatch(host, operation(), policy, is_seq, left, right, + dispatch(host, operation(), policy, is_seq, local_runs, comp, proj); } } } else { - std::map> jobs; - std::map assignments; - for (auto& pair : pairs) - { - auto host = segmented_sort_host( - blocks[pair.first], right_block(pair), assignments); - jobs[host].push_back(HPX_MOVE(pair)); - ++assignments[host]; - } - std::vector> pending; - std::vector pending_hosts; - std::vector pending_costs; - pending.reserve(pairs.size()); - pending_hosts.reserve(pairs.size()); - pending_costs.reserve(pairs.size()); - std::map active; - std::map scratch_used; - - auto operation_cost = [&](segmented_sort_pair pair) { - auto const& left = blocks[pair.first]; - auto const& right = right_block(pair); - if (right.empty()) - { - return left.size() == 1 ? - std::size_t(0) : - 2 * segmented_sort_block_size(left); - } - return 2 * - (segmented_sort_block_size(left) + - segmented_sort_block_size(right)); - }; - - auto launch_available = [&](hpx::id_type const& host) { - auto& queue = jobs.at(host); - auto const workers = worker_counts.at(host); - auto const scratch_budget = - workers * 4 * segmented_sort_transfer_chunk_size; - while (active[host] != workers && !queue.empty()) + pending.reserve(groups.size()); + std::exception_ptr error; + try + { + for (auto const& [host, local_runs] : groups) { - auto const pair = queue.back(); - auto const cost = operation_cost(pair); - // Always admit one oversized operation so progress does - // not depend on the physical partition size. - if (active[host] != 0 && - scratch_used[host] + cost > scratch_budget) - { - break; - } - queue.pop_back(); - auto const& left = blocks[pair.first]; - auto const& right = right_block(pair); if (host == here) { pending.push_back(hpx::async( - [policy, left, right, comp, proj, is_seq]() { - return operation().call2( - policy, is_seq, left, right, comp, proj); + [policy, local_runs, comp, proj]() mutable { + return operation::parallel(policy, local_runs, + HPX_MOVE(comp), HPX_MOVE(proj)); })); } else { pending.push_back(dispatch_async(host, operation(), - policy, is_seq, left, right, comp, proj)); + policy, is_seq, local_runs, comp, proj)); } - pending_hosts.push_back(host); - pending_costs.push_back(cost); - ++active[host]; - scratch_used[host] += cost; - } - }; - - std::exception_ptr error; - try - { - for (auto const& job : jobs) - { - launch_available(job.first); } } catch (...) { error = std::current_exception(); } - if (error) + segmented_sort_wait(pending, error); + } + } + + template + struct segmented_sort_kway_merge_on_host + : algorithm, bool> + { + constexpr segmented_sort_kway_merge_on_host() noexcept + : algorithm( + "segmented_sort_kway_merge_on_host") + { + } + + template + static bool execute(ExPolicy const& policy, + segmented_sort_block const& runs, Comp comp, Proj proj) + { + using value_type = std::iterator_traits::value_type; + + std::vector counts; + std::vector offsets; + counts.reserve(runs.size()); + offsets.reserve(runs.size()); + std::size_t total = 0; + for (auto const& run : runs) { - segmented_sort_wait(pending, error); + offsets.push_back(total); + auto const count = static_cast(run.size()); + counts.push_back(count); + total += count; } - // Keep each host's worker window full as soon as one operation - // completes. Slow operations no longer impose round barriers on - // unrelated work. - while (!pending.empty()) - { - if (hpx::wait_any_nothrow(pending)) + auto values = segmented_sort_fetch_block(policy, runs); + HPX_ASSERT(values.size() == total); + + util::compare_projected pred(comp, proj); + std::size_t destination = 0; + std::vector output; + output.reserve(counts.front()); + auto emit = [&](value_type&& value) { + output.push_back(HPX_MOVE(value)); + if (output.size() != counts[destination]) { - segmented_sort_wait(pending); + return; } - std::set completed_hosts; - for (std::size_t i = pending.size(); i-- != 0;) - { - if (pending[i].is_ready()) - { - pending[i].get(); - auto const host = pending_hosts[i]; - --active[host]; - scratch_used[host] -= pending_costs[i]; - completed_hosts.insert(host); - pending.erase( - pending.begin() + static_cast(i)); - pending_hosts.erase(pending_hosts.begin() + - static_cast(i)); - pending_costs.erase(pending_costs.begin() + - static_cast(i)); - } - } - try - { - for (auto const& host : completed_hosts) - { - launch_available(host); - } - } - catch (...) + + segmented_sort_block block{runs[destination]}; + [[maybe_unused]] auto const last = + segmented_sort_store_block(policy, block, output.begin()); + HPX_ASSERT(last == output.end()); + output.clear(); + if (++destination != runs.size()) { - segmented_sort_wait( - pending, std::current_exception()); + output.reserve(counts[destination]); } - } + }; + + segmented_sort_kway_for_each(values, offsets, counts, pred, emit); + HPX_ASSERT(destination == runs.size()); + return true; } - } + template + static bool sequential(ExPolicy const& policy, + segmented_sort_block const& runs, Comp comp, Proj proj) + { + return execute(policy, runs, HPX_MOVE(comp), HPX_MOVE(proj)); + } + + template + static bool parallel(ExPolicy const& policy, + segmented_sort_block const& runs, Comp comp, Proj proj) + { + return execute(policy, runs, HPX_MOVE(comp), HPX_MOVE(proj)); + } + }; + + // Fetch each sorted run once onto the locality already holding the most + // participating data, perform one k-way merge there, and write each final + // run once. Network traffic is therefore linear in the input size. template - void segmented_sort_distributed(ExPolicy const& policy, + void segmented_sort_merge_runs(ExPolicy const& policy, segmented_sort_block const& runs, Comp const& comp, Proj const& proj, IsSeq is_seq) { - // Keep the single-partition path in place, regardless of its size. - if (runs.size() == 1) + if (runs.size() <= 1) { - std::vector> blocks{runs}; - std::map worker_counts; - if constexpr (!IsSeq::value) - { - worker_counts = segmented_sort_worker_counts(policy, blocks); - } - segmented_sort_stage( - policy, blocks, {{0, 0}}, worker_counts, comp, proj, is_seq); return; } - auto blocks = - segmented_sort_blocks(runs, segmented_sort_block_capacity(runs)); - std::map worker_counts; - if constexpr (!IsSeq::value) + + using operation = segmented_sort_kway_merge_on_host; + segmented_sort_block const empty; + auto const host = segmented_sort_host(runs, empty); + std::vector> pending; + std::exception_ptr error; + try { - worker_counts = segmented_sort_worker_counts(policy, blocks); + if (host == hpx::find_here()) + { + operation().call2(policy, is_seq, runs, comp, proj); + } + else + { + pending.push_back(dispatch_async( + host, operation(), policy, is_seq, runs, comp, proj)); + } } - std::vector initial; - initial.reserve(blocks.size()); - for (std::size_t i = 0; i != blocks.size(); ++i) + catch (...) { - initial.emplace_back(i, i); + error = std::current_exception(); } - segmented_sort_stage(policy, blocks, HPX_MOVE(initial), worker_counts, - comp, proj, is_seq); - segmented_sort_merge_stages(blocks.size(), [&](auto pairs) { - segmented_sort_stage(policy, blocks, HPX_MOVE(pairs), worker_counts, - comp, proj, is_seq); - }); + segmented_sort_wait(pending, error); + } + + template + void segmented_sort_distributed(ExPolicy const& policy, + segmented_sort_block const& runs, Comp const& comp, + Proj const& proj, IsSeq is_seq) + { + segmented_sort_local_runs(policy, runs, comp, proj, is_seq); + segmented_sort_merge_runs(policy, runs, comp, proj, is_seq); } template requires(hpx::traits::is_iterator_v && diff --git a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp index 86adc9407541..cc5126acbd31 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -16,13 +16,10 @@ #include #include -#include -#include #include #include #include #include -#include #include #include #include @@ -331,216 +328,87 @@ void test_sort_subranges( } } -// Exercise the block network with exhaustive zero/one inputs, including a -// short final block. A stage must never read/write overlapping blocks. -void test_merge_network() +struct move_only_sort_value { - namespace detail = hpx::parallel::detail; - - std::size_t stage_count = 0; - bool has_descending_pair = false; - detail::segmented_sort_merge_stages(16, [&](auto const& pairs) { - ++stage_count; - HPX_TEST_EQ(pairs.size(), std::size_t(8)); - for (auto const& pair : pairs) - { - has_descending_pair = - has_descending_pair || pair.first > pair.second; - } - }); - HPX_TEST_EQ(stage_count, std::size_t(10)); - HPX_TEST(has_descending_pair); - - for (std::size_t count = 2; count <= 7; ++count) + explicit move_only_sort_value(int value) + : value(value) { - for (std::size_t tail : {1, 2, 3}) - { - std::size_t combinations = tail + 1; - for (std::size_t i = 1; i < count; ++i) - { - combinations *= 4; - } - for (std::size_t input = 0; input < combinations; ++input) - { - std::vector> blocks(count); - auto digits = input; - std::size_t zeros = 0; - for (std::size_t i = 0; i < count; ++i) - { - auto const size = i + 1 == count ? tail : 3; - auto const nzero = digits % (size + 1); - digits /= size + 1; - zeros += nzero; - blocks[i].resize(size, 1); - std::fill_n(blocks[i].begin(), nzero, 0); - } - detail::segmented_sort_merge_stages( - count, [&](auto const& pairs) { - std::vector touched(count, false); - for (auto [left, right] : pairs) - { - HPX_TEST(!touched[left] && !touched[right]); - touched[left] = touched[right] = true; - std::vector merged( - blocks[left].size() + blocks[right].size()); - std::merge(blocks[left].begin(), blocks[left].end(), - blocks[right].begin(), blocks[right].end(), - merged.begin()); - auto middle = merged.begin() + - static_cast( - blocks[left].size()); - std::copy( - merged.begin(), middle, blocks[left].begin()); - std::copy( - middle, merged.end(), blocks[right].begin()); - } - }); - for (auto const& block : blocks) - { - for (int value : block) - { - HPX_TEST_EQ(value, zeros != 0 ? 0 : 1); - if (zeros != 0) - { - --zeros; - } - } - } - } - } } -} -// Exercise the actual compare/split implementation with deliberately small -// blocks. Cover non-power-of-two block counts, short tails, and duplicates. -void test_forced_small_blocks() + move_only_sort_value() = delete; + move_only_sort_value(move_only_sort_value const&) = delete; + move_only_sort_value& operator=(move_only_sort_value const&) = delete; + move_only_sort_value(move_only_sort_value&&) = default; + move_only_sort_value& operator=(move_only_sort_value&&) = default; + + int value; +}; + +// Cover arbitrary run counts, short final runs, duplicates, and value types +// that cannot be copied or default constructed. +void test_kway_merge() { namespace detail = hpx::parallel::detail; - constexpr std::size_t block_size = 5; - for (std::size_t block_count : {3, 5, 6, 7}) + + for (std::size_t run_count : {3, 5, 6, 7}) { - for (std::size_t tail = 1; tail != block_size; ++tail) + for (std::size_t tail = 1; tail != 5; ++tail) { - auto const size = (block_count - 1) * block_size + tail; for (std::size_t seed = 0; seed != 16; ++seed) { - std::vector values(size); - for (std::size_t i = 0; i != size; ++i) + std::vector values; + std::vector offsets; + std::vector counts; + std::vector expected; + for (std::size_t run = 0; run != run_count; ++run) { - values[i] = static_cast((i * 17 + seed * 13) % 11); + offsets.push_back(values.size()); + auto const count = run + 1 == run_count ? tail : 5; + counts.push_back(count); + std::vector part(count); + for (std::size_t i = 0; i != count; ++i) + { + part[i] = static_cast( + (run * 17 + i * 13 + seed * 7) % 11); + } + std::sort(part.begin(), part.end()); + expected.insert(expected.end(), part.begin(), part.end()); + values.insert(values.end(), part.begin(), part.end()); } - auto expected = values; std::sort(expected.begin(), expected.end()); - auto const here = hpx::find_here(); - detail::segmented_sort_block::iterator> runs{ - {here, here, values.begin(), values.end()}}; - auto blocks = detail::segmented_sort_blocks(runs, block_size); - HPX_TEST_EQ(blocks.size(), block_count); - std::vector initial; - for (std::size_t i = 0; i != blocks.size(); ++i) - { - initial.emplace_back(i, i); - } - std::map worker_counts; - detail::segmented_sort_stage(hpx::execution::seq, blocks, - HPX_MOVE(initial), worker_counts, std::less{}, - hpx::identity_v, std::true_type{}); - detail::segmented_sort_merge_stages( - blocks.size(), [&](auto pairs) { - detail::segmented_sort_stage(hpx::execution::seq, - blocks, HPX_MOVE(pairs), worker_counts, - std::less{}, hpx::identity_v, - std::true_type{}); - }); - HPX_TEST(values == expected); + std::vector output; + output.reserve(values.size()); + std::less pred; + detail::segmented_sort_kway_for_each(values, offsets, counts, + pred, + [&](int&& value) { output.push_back(HPX_MOVE(value)); }); + HPX_TEST(output == expected); } } } -} - -struct counted_sort_value -{ - inline static std::atomic live{0}; - inline static std::atomic peak{0}; - inline static std::atomic copies{0}; - int value = 0; - - counted_sort_value() - { - auto const current = ++live; - auto previous = peak.load(); - while (previous < current && - !peak.compare_exchange_weak(previous, current)) - { - } - } - counted_sort_value(counted_sort_value const& other) - : counted_sort_value() - { - value = other.value; - ++copies; - } - counted_sort_value(counted_sort_value&& other) noexcept - : counted_sort_value() - { - value = other.value; - } - counted_sort_value& operator=(counted_sort_value const&) = default; - counted_sort_value& operator=(counted_sort_value&&) = default; - ~counted_sort_value() - { - --live; - } - template - void serialize(Archive& ar, unsigned) + std::vector values; + for (int value : {0, 3, 6, 1, 4, 7, 2, 5, 8}) { - ar & value; + values.emplace_back(value); } -}; - -// HPX component factories must be registered before runtime startup. -// NOLINTNEXTLINE(bugprone-throwing-static-initialization) -HPX_REGISTER_PARTITIONED_VECTOR(counted_sort_value) - -void test_merge_buffer() -{ - namespace detail = hpx::parallel::detail; - auto const size = detail::segmented_sort_transfer_chunk_size; + std::vector const offsets{0, 3, 6}; + std::vector const counts{3, 3, 3}; + auto pred = [](move_only_sort_value const& lhs, + move_only_sort_value const& rhs) { + return lhs.value < rhs.value; + }; + std::vector output; + detail::segmented_sort_kway_for_each( + values, offsets, counts, pred, [&](move_only_sort_value&& value) { + output.push_back(HPX_MOVE(value)); + }); + HPX_TEST_EQ(output.size(), std::size_t(9)); + for (std::size_t i = 0; i != output.size(); ++i) { - std::vector left(size), right(size); - for (std::size_t i = 0; i < size; ++i) - { - left[i].value = static_cast(2 * i); - right[i].value = static_cast(2 * i + 1); - } - auto pred = [](auto const& a, auto const& b) { - return a.value < b.value; - }; - // HPX's merge itself creates temporary values. Compare against a - // direct merge to isolate copies and storage added by our wrapper. - std::size_t reference_copies; - std::size_t reference_peak; - { - std::vector reference(2 * size); - hpx::merge(hpx::execution::seq, left.begin(), left.end(), - right.begin(), right.end(), reference.begin(), pred); - reference_copies = counted_sort_value::copies.load(); - reference_peak = counted_sort_value::peak.load(); - } - counted_sort_value::copies = 0; - counted_sort_value::peak = counted_sort_value::live.load(); - auto merged = detail::segmented_sort_merge_pair( - hpx::execution::seq, left, right, pred); - HPX_TEST_EQ(counted_sort_value::copies.load(), reference_copies); - HPX_TEST_EQ(counted_sort_value::peak.load(), reference_peak); - for (std::size_t i = 0; i < merged.size(); ++i) - { - HPX_TEST_EQ(merged[i].value, static_cast(i)); - } + HPX_TEST_EQ(output[i].value, static_cast(i)); } - HPX_TEST_EQ(counted_sort_value::live.load(), std::size_t(0)); } void test_host_placement(std::vector const& localities) @@ -560,25 +428,6 @@ void test_host_placement(std::vector const& localities) runs.emplace_back(b, b, data.begin() + i, data.begin() + i + 4 * unit); } HPX_TEST(detail::segmented_sort_host(runs, {}) == b); - HPX_TEST_EQ(detail::segmented_sort_block_capacity(runs), - static_cast(5 * unit)); - - if (a != b) - { - detail::segmented_sort_block left{ - {a, a, data.begin(), data.begin() + unit}}; - detail::segmented_sort_block right{ - {b, b, data.begin() + unit, data.begin() + 2 * unit}}; - std::map assignments; - for (std::size_t i = 0; i != 8; ++i) - { - auto const host = - detail::segmented_sort_host(left, right, assignments); - ++assignments[host]; - } - HPX_TEST_EQ(assignments[a], std::size_t(4)); - HPX_TEST_EQ(assignments[b], std::size_t(4)); - } if (a != b) { @@ -600,8 +449,7 @@ void test_host_placement(std::vector const& localities) } } -void test_partition_blocks_and_transfer_chunks( - std::vector const& localities) +void test_transfer_chunks(std::vector const& localities) { namespace detail = hpx::parallel::detail; auto const size = 8 * detail::segmented_sort_transfer_chunk_size + 7; @@ -613,19 +461,6 @@ void test_partition_blocks_and_transfer_chunks( std::sort(expected.begin() + 1, expected.end() - 2); auto runs = detail::segmented_sort_runs(values.begin() + 1, values.end() - 2); - auto const capacity = detail::segmented_sort_block_capacity(runs); - auto blocks = detail::segmented_sort_blocks(runs, capacity); - HPX_TEST_LTE(blocks.size(), runs.size()); - for (std::size_t i = 0; i != blocks.size(); ++i) - { - auto const block_size = detail::segmented_sort_block_size(blocks[i]); - HPX_TEST_LTE(block_size, capacity); - if (i + 1 != blocks.size()) - { - HPX_TEST_EQ(block_size, capacity); - } - } - auto chunks = detail::segmented_sort_transfer_chunks(runs); std::size_t total = 0; for (auto const& chunk : chunks) @@ -669,7 +504,7 @@ struct throwing_merge_less bool operator()(int a, int b) const { - // Each initial block lies within one band. Only a merge compares + // Each initial run lies within one band. Only a merge compares // different bands, after the local sort phase has succeeded. constexpr auto band_size = static_cast( hpx::parallel::detail::segmented_sort_transfer_chunk_size); @@ -733,207 +568,13 @@ void test_merge_exceptions( caught = true; } HPX_TEST(caught); - // Reuse immediately: the failed stage must have drained its actions. + // Reuse immediately: the failed operation must have drained its + // actions. initialize_reverse(values); test_sort_once(values); } } -// This comparator observes overlap between two initial block sorts. Sleeping -// suspends the HPX thread so another sort can enter on the same locality. -struct initial_sort_probe_state -{ - std::array, 2> entered{}; - std::atomic active{0}; - std::atomic peak{0}; -}; - -struct initial_sort_probe -{ - inline static std::shared_ptr state; - static constexpr auto block_size = - hpx::parallel::detail::segmented_sort_transfer_chunk_size; - - bool operator()(int a, int b) const - { - auto const block = static_cast(a) / block_size; - if (!state->entered[block].exchange(true)) - { - auto const current = ++state->active; - auto previous = state->peak.load(); - while (previous < current && - !state->peak.compare_exchange_weak(previous, current)) - { - } - hpx::this_thread::sleep_for(std::chrono::milliseconds(20)); - --state->active; - } - return a < b; - } - - template - void serialize(Archive&, unsigned) - { - } -}; - -void test_initial_sort_concurrency() -{ - namespace detail = hpx::parallel::detail; - constexpr auto size = initial_sort_probe::block_size; - // Four physical pieces produce two forced logical blocks on this - // locality for the scheduler test. - hpx::partitioned_vector values(2 * size, 0, - hpx::container_layout(4, std::vector{hpx::find_here()})); - initialize_values(values, [](std::size_t i) { - return static_cast((i / size) * size + size - 1 - i % size); - }); - auto runs = detail::segmented_sort_runs(values.begin(), values.end()); - auto blocks = detail::segmented_sort_blocks(runs, size); - initial_sort_probe::state = std::make_shared(); - auto worker_counts = - detail::segmented_sort_worker_counts(hpx::execution::par, blocks); - detail::segmented_sort_stage(hpx::execution::par, blocks, {{0, 0}, {1, 1}}, - worker_counts, initial_sort_probe{}, hpx::identity_v, - std::false_type{}); - HPX_TEST_EQ(initial_sort_probe::state->peak.load(), std::size_t(2)); - initial_sort_probe::state.reset(); - auto got = copy_values(values); - HPX_TEST(std::is_sorted(got.begin(), got.end())); -} - -struct merge_stage_probe_state -{ - std::array, 2> entered{}; - std::atomic started{0}; - hpx::promise both_started; - hpx::shared_future ready = both_started.get_future(); - std::atomic timed_out{false}; -}; - -struct merge_stage_probe -{ - inline static std::shared_ptr state; - static constexpr std::size_t block_size = 2048; - static constexpr int group_stride = 4 * static_cast(block_size); - - bool operator()(int a, int b) const - { - auto const group = - static_cast((std::min) (a, b) / group_stride); - if (!state->entered[group].exchange(true)) - { - if (++state->started == 2) - { - state->both_started.set_value(); - } - if (state->ready.wait_for(std::chrono::seconds(5)) != - hpx::future_status::ready) - { - state->timed_out = true; - } - } - return a < b; - } - - template - void serialize(Archive&, unsigned) - { - } -}; - -void test_merge_stage_concurrency() -{ - namespace detail = hpx::parallel::detail; - constexpr auto size = merge_stage_probe::block_size; - hpx::partitioned_vector values(4 * size, 0, - hpx::container_layout(4, std::vector{hpx::find_here()})); - initialize_values(values, [](std::size_t i) { - auto const block = i / size; - auto const offset = i % size; - return static_cast(block / 2) * merge_stage_probe::group_stride + - static_cast(2 * offset + block % 2); - }); - auto runs = detail::segmented_sort_runs(values.begin(), values.end()); - auto blocks = detail::segmented_sort_blocks(runs, size); - auto worker_counts = - detail::segmented_sort_worker_counts(hpx::execution::par, blocks); - merge_stage_probe::state = std::make_shared(); - detail::segmented_sort_stage(hpx::execution::par, blocks, {{0, 1}, {2, 3}}, - worker_counts, merge_stage_probe{}, hpx::identity_v, std::false_type{}); - HPX_TEST(!merge_stage_probe::state->timed_out.load()); - merge_stage_probe::state.reset(); - auto got = copy_values(values); - HPX_TEST(std::is_sorted(got.begin(), got.end())); -} - -struct sliding_stage_probe_state -{ - std::array, 3> entered{}; - hpx::promise third_started; - hpx::shared_future ready = third_started.get_future(); - std::atomic timed_out{false}; -}; - -struct sliding_stage_probe -{ - inline static std::shared_ptr state; - static constexpr std::size_t block_size = 1024; - static constexpr int group_stride = 4 * static_cast(block_size); - - bool operator()(int a, int b) const - { - auto const group = - static_cast((std::min) (a, b) / group_stride); - if (!state->entered[group].exchange(true)) - { - if (group == 0) - { - state->third_started.set_value(); - } - else if (group == 2 && - state->ready.wait_for(std::chrono::seconds(5)) != - hpx::future_status::ready) - { - state->timed_out = true; - } - } - return a < b; - } - - template - void serialize(Archive&, unsigned) - { - } -}; - -void test_sliding_stage_window() -{ - namespace detail = hpx::parallel::detail; - constexpr auto size = sliding_stage_probe::block_size; - std::vector values(6 * size); - for (std::size_t i = 0; i != values.size(); ++i) - { - auto const block = i / size; - auto const offset = i % size; - values[i] = - static_cast(block / 2) * sliding_stage_probe::group_stride + - static_cast(2 * offset + block % 2); - } - auto const here = hpx::find_here(); - detail::segmented_sort_block::iterator> runs{ - {here, here, values.begin(), values.end()}}; - auto blocks = detail::segmented_sort_blocks(runs, size); - std::map worker_counts{{here, 2}}; - sliding_stage_probe::state = std::make_shared(); - detail::segmented_sort_stage(hpx::execution::par, blocks, - {{0, 1}, {2, 3}, {4, 5}}, worker_counts, sliding_stage_probe{}, - hpx::identity_v, std::false_type{}); - HPX_TEST(!sliding_stage_probe::state->timed_out.load()); - sliding_stage_probe::state.reset(); - HPX_TEST(std::is_sorted(values.begin(), values.end())); -} - struct collection_gate { hpx::promise release; @@ -1000,47 +641,6 @@ void test_async_run_collection(ExPolicy const& policy) HPX_TEST(std::is_sorted(got.begin(), got.end())); } -struct counted_value_less -{ - bool operator()( - counted_sort_value const& a, counted_sort_value const& b) const - { - return a.value < b.value; - } - - template - void serialize(Archive&, unsigned) - { - } -}; - -void test_ordered_endpoints() -{ - namespace detail = hpx::parallel::detail; - hpx::partitioned_vector values(4096, - counted_sort_value{}, - hpx::container_layout(2, std::vector{hpx::find_here()})); - initialize_values(values, [](int i) { - counted_sort_value value; - value.value = i; - return value; - }); - auto runs = detail::segmented_sort_runs(values.begin(), values.end()); - auto blocks = detail::segmented_sort_blocks(runs, 2048); - counted_sort_value::copies = 0; - using local_iterator = hpx::traits::segmented_iterator_traits< - decltype(values.begin())>::local_iterator; - detail::segmented_sort_compare_split::sequential( - hpx::execution::seq, blocks[0], blocks[1], counted_value_less{}, - hpx::identity_v); - HPX_TEST_EQ(counted_sort_value::copies.load(), std::size_t(0)); - auto got = copy_values(values); - for (std::size_t i = 0; i < got.size(); ++i) - { - HPX_TEST_EQ(got[i].value, static_cast(i)); - } -} - void test_transfer_batches(std::vector const& localities) { namespace detail = hpx::parallel::detail; @@ -1086,18 +686,9 @@ void test_transfer_batches(std::vector const& localities) int main() { std::vector localities = hpx::find_all_localities(); - test_merge_network(); - test_forced_small_blocks(); - test_merge_buffer(); + test_kway_merge(); test_host_placement(localities); - test_partition_blocks_and_transfer_chunks(localities); - if (hpx::get_os_thread_count() > 1) - { - test_initial_sort_concurrency(); - test_merge_stage_concurrency(); - test_sliding_stage_window(); - } - test_ordered_endpoints(); + test_transfer_chunks(localities); test_transfer_batches(localities); test_async_run_collection(hpx::execution::seq(hpx::execution::task)); test_async_run_collection(hpx::execution::par(hpx::execution::task)); From 8c1fce1eecb5843c6c9a1ad70e5db250a7076942 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Thu, 8 Oct 2026 23:46:28 +0530 Subject: [PATCH 33/37] Resolve segmented sort placement and transfer review Signed-off-by: the-ivii --- .../partitioned_vector_segmented_iterator.hpp | 4 +- .../parallel/segmented_algorithms/sort.hpp | 134 +++++++++++++----- .../tests/unit/partitioned_vector_sort.cpp | 18 ++- 3 files changed, 113 insertions(+), 43 deletions(-) diff --git a/components/containers/partitioned_vector/include/hpx/components/containers/partitioned_vector/partitioned_vector_segmented_iterator.hpp b/components/containers/partitioned_vector/include/hpx/components/containers/partitioned_vector/partitioned_vector_segmented_iterator.hpp index c791f40cf8eb..db9462a1713a 100644 --- a/components/containers/partitioned_vector/include/hpx/components/containers/partitioned_vector/partitioned_vector_segmented_iterator.hpp +++ b/components/containers/partitioned_vector/include/hpx/components/containers/partitioned_vector/partitioned_vector_segmented_iterator.hpp @@ -1095,7 +1095,7 @@ namespace hpx::traits { // avoids an AGAS lookup when an algorithm only needs placement. static std::uint32_t get_locality_id(segment_iterator const& iter) { - return iter.base()->locality_id_; + return iter->locality_id_; } }; @@ -1194,7 +1194,7 @@ namespace hpx::traits { // avoids an AGAS lookup when an algorithm only needs placement. static std::uint32_t get_locality_id(segment_iterator const& iter) { - return iter.base()->locality_id_; + return iter->locality_id_; } }; diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp index 2cc10c60e443..61f959d36154 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp @@ -134,8 +134,13 @@ namespace hpx::parallel::detail { auto id = traits::get_id(segment); if constexpr (requires { traits::get_locality_id(segment); }) { - auto locality = hpx::naming::get_id_from_locality_id( - traits::get_locality_id(segment)); + hpx::id_type locality; + auto const locality_id = traits::get_locality_id(segment); + if (locality_id != hpx::naming::invalid_locality_id) + { + locality = + hpx::naming::get_id_from_locality_id(locality_id); + } runs.emplace_back( HPX_MOVE(id), HPX_MOVE(locality), beg, end); } @@ -371,28 +376,48 @@ namespace hpx::parallel::detail { auto it = chunks.begin(); while (it != chunks.end()) { - std::vector>> pending; + auto batch_end = it; + for (std::size_t i = 0; i < limit && batch_end != chunks.end(); + ++i, ++batch_end) + { + } + + auto const count = + static_cast(std::distance(it, batch_end)); + std::vector> parts(count); + std::vector> pending; pending.reserve(limit); std::exception_ptr error; try { - for (std::size_t i = 0; i < limit && it != chunks.end(); ++i) + auto current = it; + for (std::size_t i = 0; current != batch_end; ++i, ++current) { - auto pieces = *it; + auto pieces = *current; auto const host = pieces.front().locality; - if (host == here) - { - pending.push_back(hpx::make_ready_future( - segmented_fetch_values::sequential( - policy, pieces))); - } - else + if (host != here) { pending.push_back(dispatch_async(host, segmented_fetch_values(), policy, - std::true_type(), HPX_MOVE(pieces))); + std::true_type(), HPX_MOVE(pieces)) + .then([&parts, i]( + hpx::future> + ready) { + parts[i] = ready.get(); + })); + } + } + + current = it; + for (std::size_t i = 0; current != batch_end; ++i, ++current) + { + auto const& pieces = *current; + if (pieces.front().locality == here) + { + parts[i] = + segmented_fetch_values::sequential( + policy, pieces); } - ++it; } } catch (...) @@ -400,13 +425,13 @@ namespace hpx::parallel::detail { error = std::current_exception(); } segmented_sort_wait(pending, error); - for (auto& future : pending) + for (auto& part : parts) { - auto part = future.get(); values.insert(values.end(), std::make_move_iterator(part.begin()), std::make_move_iterator(part.end())); } + it = batch_end; } return values; } @@ -424,58 +449,77 @@ namespace hpx::parallel::detail { auto it = chunks.begin(); while (it != chunks.end()) { + auto batch_end = it; + for (std::size_t i = 0; i < limit && batch_end != chunks.end(); + ++i, ++batch_end) + { + } + std::vector> pending; pending.reserve(limit); std::exception_ptr error; try { - for (std::size_t i = 0; i < limit && it != chunks.end(); ++i) + auto current = first; + for (auto chunk = it; chunk != batch_end; ++chunk) { - auto pieces = *it; + auto pieces = *chunk; auto const host = pieces.front().locality; - auto last = first + + auto last = current + static_cast( segmented_sort_block_size(pieces)); - if (host == here) + if (host != here) + { + std::vector values( + std::make_move_iterator(current), + std::make_move_iterator(last)); + pending.push_back(dispatch_async(host, + segmented_store_values(), policy, + std::true_type(), HPX_MOVE(pieces), + HPX_MOVE(values))); + } + current = last; + } + + current = first; + for (auto chunk = it; chunk != batch_end; ++chunk) + { + auto const& pieces = *chunk; + auto last = current + + static_cast( + segmented_sort_block_size(pieces)); + if (pieces.front().locality == here) { using traits = hpx::traits::segmented_local_iterator_traits< LocalIter>; - auto current = first; + auto source = current; for (auto const& piece : pieces) { - auto next = current + piece.size(); - hpx::move(policy, current, next, + auto next = source + piece.size(); + hpx::move(policy, source, next, traits::local(piece.first)); - current = next; + source = next; } } - else - { - std::vector values( - std::make_move_iterator(first), - std::make_move_iterator(last)); - pending.push_back(dispatch_async(host, - segmented_store_values(), policy, - std::true_type(), HPX_MOVE(pieces), - HPX_MOVE(values))); - } - first = last; - ++it; + current = last; } + first = current; } catch (...) { error = std::current_exception(); } segmented_sort_wait(pending, error); + it = batch_end; } return first; } // Merge the sorted input runs without constructing a second full-size // output buffer. Values are selected once into one destination buffer at - // a time. + // a time. Stores are incremental and therefore cannot be rolled back if a + // later comparison or destination operation throws. template void segmented_sort_kway_for_each(std::vector& values, std::vector const& offsets, @@ -682,8 +726,9 @@ namespace hpx::parallel::detail { }; // Fetch each sorted run once onto the locality already holding the most - // participating data, perform one k-way merge there, and write each final - // run once. Network traffic is therefore linear in the input size. + // participating data, perform one serial k-way merge there, and write each + // final run once. Network traffic and coordinator storage are linear in the + // input size. template void segmented_sort_merge_runs(ExPolicy const& policy, @@ -784,6 +829,11 @@ namespace hpx::segmented { /// A parallel policy overlaps independent locality operations. For ranges /// spanning localities, the comparator must be copyable and serializable /// by HPX. + /// + /// The final merge runs serially on one participating locality and uses + /// storage proportional to the input size. Destination runs are committed + /// incrementally; an exception during this phase can leave a partially + /// reordered range. HPX_CXX_EXPORT template requires(hpx::traits::is_iterator_v && @@ -807,6 +857,12 @@ namespace hpx::segmented { /// /// For ranges spanning localities, the comparator must be copyable and /// serializable by HPX. + /// + /// The policy controls local partition sorting and whether independent + /// locality operations overlap. The final merge runs serially on one + /// participating locality and uses storage proportional to the input size. + /// Destination runs are committed incrementally; an exception during this + /// phase can leave a partially reordered range. HPX_CXX_EXPORT template requires(hpx::is_execution_policy_v && diff --git a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp index cc5126acbd31..261335bf8d59 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -18,6 +18,7 @@ #include #include #include +#include #include #include #include @@ -205,11 +206,11 @@ bool caught_sort_exception(std::function const& f) { f(); } - catch (std::exception const&) + catch (hpx::exception_list const&) { return true; } - catch (...) + catch (std::runtime_error const&) { return true; } @@ -610,6 +611,11 @@ namespace hpx::traits { { return base_traits::local(iter.base); } + + static std::uint32_t get_locality_id(segment_iterator const&) + { + return hpx::naming::invalid_locality_id; + } }; } // namespace hpx::traits @@ -639,6 +645,14 @@ void test_async_run_collection(ExPolicy const& policy) HPX_TEST(status == hpx::future_status::ready); auto got = copy_values(values); HPX_TEST(std::is_sorted(got.begin(), got.end())); + + auto runs = hpx::parallel::detail::segmented_sort_runs( + collection_probe_iterator{values.begin(), gate}, + collection_probe_iterator{values.end(), gate}); + for (auto const& run : runs) + { + HPX_TEST(run.locality == hpx::find_here()); + } } void test_transfer_batches(std::vector const& localities) From 47feee217cb627d4d729cf8a40dbfccf12158d0f Mon Sep 17 00:00:00 2001 From: the-ivii Date: Thu, 8 Oct 2026 23:46:30 +0530 Subject: [PATCH 34/37] Keep internal segmented tests compatible with modules Signed-off-by: the-ivii --- .../segmented_algorithms/tests/unit/CMakeLists.txt | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt b/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt index 5ab1f69e5d5d..5c727326deb8 100644 --- a/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt +++ b/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt @@ -129,8 +129,13 @@ foreach(test ${tests}) endforeach() if(HPX_WITH_CXX_MODULES) - # These tests inspect sort helpers that are not exported by HPX.Full. - target_compile_definitions( - partitioned_vector_sort_test PRIVATE HPX_HAVE_FORCE_NO_CXX_MODULES + # These tests inspect implementation helpers that are not exported by + # HPX.Full. + foreach(test partitioned_vector_merge_extended + partitioned_vector_merge_regressions partitioned_vector_sort ) + target_compile_definitions( + ${test}_test PRIVATE HPX_HAVE_FORCE_NO_CXX_MODULES + ) + endforeach() endif() From de91c919f452b7c20fd8d71a4b863f7fcfc0daf0 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Wed, 4 Nov 2026 22:20:36 +0530 Subject: [PATCH 35/37] Format segmented sort test configuration Signed-off-by: the-ivii --- libs/full/segmented_algorithms/tests/unit/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt b/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt index 5c727326deb8..a7c576c3bb85 100644 --- a/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt +++ b/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt @@ -96,8 +96,8 @@ foreach(test ${tests}) set(sources ${test}.cpp) set(${test}_FLAGS DEPENDENCIES partitioned_vector_component) - if(test STREQUAL "partitioned_vector_sort" OR test MATCHES - "^partitioned_vector_merge(_extended|_regressions)?$" + if(test STREQUAL "partitioned_vector_sort" + OR test MATCHES "^partitioned_vector_merge(_extended|_regressions)?$" ) # Four localities exercise concurrent merges and remote transfers. set(test_localities 4) From 4b46d485e76493b4748ade3bd57bf361cd10902a Mon Sep 17 00:00:00 2001 From: the-ivii Date: Thu, 5 Nov 2026 13:14:55 +0530 Subject: [PATCH 36/37] Avoid Windows macro clash in segmented sort tests Signed-off-by: the-ivii --- .../tests/unit/partitioned_vector_sort.cpp | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp index 261335bf8d59..e13571a39594 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -31,7 +31,7 @@ #include /////////////////////////////////////////////////////////////////////////////// -#define SIZE 64 +#define HPX_SEGMENTED_SORT_TEST_SIZE 64 #define LARGE_SIZE 2048 template @@ -101,15 +101,17 @@ void verify_sorted(hpx::partitioned_vector const& values, template void initialize_reverse(hpx::partitioned_vector& values) { - initialize_values( - values, [](int i) { return make_sort_value(SIZE - i); }); + initialize_values(values, [](int i) { + return make_sort_value(HPX_SEGMENTED_SORT_TEST_SIZE - i); + }); } template void initialize_mixed(hpx::partitioned_vector& values) { - initialize_values( - values, [](int i) { return make_sort_value((i * 17 + 3) % SIZE); }); + initialize_values(values, [](int i) { + return make_sort_value((i * 17 + 3) % HPX_SEGMENTED_SORT_TEST_SIZE); + }); } template @@ -221,7 +223,7 @@ template void test_sort_throwing(std::vector& localities) { hpx::partitioned_vector values( - SIZE, T{}, hpx::container_layout(localities)); + HPX_SEGMENTED_SORT_TEST_SIZE, T{}, hpx::container_layout(localities)); initialize_mixed(values); throwing_less comp; @@ -254,7 +256,7 @@ template void run_cases(std::vector& localities) { hpx::partitioned_vector values( - SIZE, T{}, hpx::container_layout(localities)); + HPX_SEGMENTED_SORT_TEST_SIZE, T{}, hpx::container_layout(localities)); initialize_reverse(values); test_sort_once(values); From e0066e526f5233b1479970f39b90924f4eef3404 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Sun, 8 Nov 2026 03:44:10 +0530 Subject: [PATCH 37/37] Address segmented sort review feedback Signed-off-by: the-ivii --- .github/workflows/tests.examples.targets | 1 - .../server/simple_central_tuplespace.hpp | 12 ++ .../server/tuples_warehouse.hpp | 12 +- libs/full/async_colocated/CMakeLists.txt | 2 +- .../async_colocated/src/get_colocation_id.cpp | 1 - .../include/hpx/naming_base/id_type.hpp | 9 -- .../parallel/segmented_algorithms/sort.hpp | 39 ++++-- .../tests/unit/CMakeLists.txt | 11 +- .../tests/unit/partitioned_vector_sort.cpp | 112 ++---------------- 9 files changed, 50 insertions(+), 149 deletions(-) diff --git a/.github/workflows/tests.examples.targets b/.github/workflows/tests.examples.targets index 2bc95fd5f4fd..9356951b19b0 100644 --- a/.github/workflows/tests.examples.targets +++ b/.github/workflows/tests.examples.targets @@ -43,7 +43,6 @@ tests.examples.modules.resource_partitioner.simplest_resource_partitioner_2 tests.examples.quickstart.1d_wave_equation tests.examples.quickstart.partitioned_vector_spmd_foreach tests.examples.quickstart.sort_by_key_demo -tests.examples.tuplespace.simple_central_tuplespace_client tests.examples.transpose.transpose_block_numa tests.examples.modules.collectives.distributed.tcp.channel_communicator tests.examples.modules.collectives.distributed.tcp.distributed_pi diff --git a/examples/tuplespace/central_tuplespace/server/simple_central_tuplespace.hpp b/examples/tuplespace/central_tuplespace/server/simple_central_tuplespace.hpp index f74fe8b30c31..f2a1778f7d54 100644 --- a/examples/tuplespace/central_tuplespace/server/simple_central_tuplespace.hpp +++ b/examples/tuplespace/central_tuplespace/server/simple_central_tuplespace.hpp @@ -112,8 +112,14 @@ namespace examples::server { do { + if (tuples_.empty()) + { + continue; + } + { std::lock_guard l(mtx_); + result = tuples_.match(tp); } @@ -135,8 +141,14 @@ namespace examples::server { do { + if (tuples_.empty()) + { + continue; + } + { std::lock_guard l(mtx_); + result = tuples_.match_and_erase(tp); } diff --git a/examples/tuplespace/central_tuplespace/server/tuples_warehouse.hpp b/examples/tuplespace/central_tuplespace/server/tuples_warehouse.hpp index a36b147764bc..fe0ec766e8b6 100644 --- a/examples/tuplespace/central_tuplespace/server/tuples_warehouse.hpp +++ b/examples/tuplespace/central_tuplespace/server/tuples_warehouse.hpp @@ -50,7 +50,7 @@ namespace examples { namespace server { bool empty() const { - return tuple_fields_.empty() || tuple_fields_[0].empty(); + return tuple_fields_[0].empty(); } int insert(tuple_type const& tp) @@ -80,11 +80,6 @@ namespace examples { namespace server { { tuple_type result; - // Uninitialized warehouse: no field containers yet. Do not call - // empty() here; that would index tuple_fields_[0]. - if (tuple_fields_.empty()) - return result; - if (tp.empty()) { return read_random_tuple(); @@ -108,11 +103,6 @@ namespace examples { namespace server { { tuple_type result; - // Uninitialized warehouse: no field containers yet. Do not call - // empty() here; that would index tuple_fields_[0]. - if (tuple_fields_.empty()) - return result; - if (tp.empty()) { return take_random_tuple(); diff --git a/libs/full/async_colocated/CMakeLists.txt b/libs/full/async_colocated/CMakeLists.txt index ed0eef96558a..1cb331e08704 100644 --- a/libs/full/async_colocated/CMakeLists.txt +++ b/libs/full/async_colocated/CMakeLists.txt @@ -58,6 +58,6 @@ add_hpx_module( COMPAT_HEADERS ${async_colocated_compat_headers} DEPENDENCIES hpx_core MODULE_DEPENDENCIES hpx_actions_base hpx_agas_base hpx_async_distributed - hpx_components hpx_components_base hpx_naming_base + hpx_components_base hpx_naming_base CMAKE_SUBDIRS examples tests ) diff --git a/libs/full/async_colocated/src/get_colocation_id.cpp b/libs/full/async_colocated/src/get_colocation_id.cpp index 9b3241984ecf..272ab0ee73ea 100644 --- a/libs/full/async_colocated/src/get_colocation_id.cpp +++ b/libs/full/async_colocated/src/get_colocation_id.cpp @@ -8,7 +8,6 @@ #include #include #include -#include #include #include #include diff --git a/libs/full/naming_base/include/hpx/naming_base/id_type.hpp b/libs/full/naming_base/include/hpx/naming_base/id_type.hpp index ba1e0a535ae9..8fcc1216dfba 100644 --- a/libs/full/naming_base/include/hpx/naming_base/id_type.hpp +++ b/libs/full/naming_base/include/hpx/naming_base/id_type.hpp @@ -146,15 +146,6 @@ namespace hpx { /////////////////////////////////////////////////////////////////////////// HPX_CXX_EXPORT inline id_type const invalid_id = id_type(); - namespace lcos::detail { - - // The definition of this specialization lives in the components - // module. Declare it here to prevent the primary template from being - // instantiated for id_type before the specialization is visible. - template <> - struct future_data; - } // namespace lcos::detail - namespace naming { /////////////////////////////////////////////////////////////////////////// diff --git a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp index 61f959d36154..17bf017740b0 100644 --- a/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp +++ b/libs/full/segmented_algorithms/include/hpx/parallel/segmented_algorithms/sort.hpp @@ -1,4 +1,4 @@ -// Copyright (c) 2026 the-ivii +// Copyright (c) 2026 Pratyksh Gupta // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying @@ -68,6 +68,8 @@ namespace hpx::parallel::detail { static InIter parallel(ExPolicy&& policy, InIter first, Sent last, Comp&& comp, Proj&& proj) { + // The shared control path still passes the parallel policy to the + // local hpx::sort invocation above. return sequential(HPX_FORWARD(ExPolicy, policy), first, last, HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); } @@ -315,6 +317,8 @@ namespace hpx::parallel::detail { static std::vector parallel( ExPolicy const& policy, segmented_sort_block const& runs) { + // A single block is copied serially. Concurrency between remote + // blocks is provided by segmented_sort_fetch_block. return sequential(policy, runs); } }; @@ -352,6 +356,8 @@ namespace hpx::parallel::detail { segmented_sort_block const& runs, std::vector values) { + // The shared control path still passes the parallel policy to + // hpx::move for every destination run. return sequential(policy, runs, HPX_MOVE(values)); } }; @@ -583,6 +589,8 @@ namespace hpx::parallel::detail { static bool parallel(ExPolicy const& policy, segmented_sort_block const& runs, Comp comp, Proj proj) { + // The run loop is orchestration; each local sort receives the + // parallel policy, and localities are overlapped by the caller. return sequential(policy, runs, HPX_MOVE(comp), HPX_MOVE(proj)); } }; @@ -721,14 +729,17 @@ namespace hpx::parallel::detail { static bool parallel(ExPolicy const& policy, segmented_sort_block const& runs, Comp comp, Proj proj) { + // The current first implementation intentionally shares the + // serial k-way merge. The policy still controls fetch/store work. return execute(policy, runs, HPX_MOVE(comp), HPX_MOVE(proj)); } }; - // Fetch each sorted run once onto the locality already holding the most - // participating data, perform one serial k-way merge there, and write each - // final run once. Network traffic and coordinator storage are linear in the - // input size. + // This first implementation fetches each sorted run onto the locality + // already holding the most participating data, performs one serial k-way + // merge there, and writes each final run once. Network traffic and peak + // coordinator storage are O(N); the merge is O(N log P), where P is the + // number of participating runs. template void segmented_sort_merge_runs(ExPolicy const& policy, @@ -830,10 +841,11 @@ namespace hpx::segmented { /// spanning localities, the comparator must be copyable and serializable /// by HPX. /// - /// The final merge runs serially on one participating locality and uses - /// storage proportional to the input size. Destination runs are committed - /// incrementally; an exception during this phase can leave a partially - /// reordered range. + /// This first implementation gathers all participating runs on one + /// locality. Its final merge is serial, requires O(N) coordinator storage, + /// and takes O(N log P) comparisons for P participating runs. Destination + /// runs are committed incrementally; an exception during this phase can + /// leave a partially reordered range. HPX_CXX_EXPORT template requires(hpx::traits::is_iterator_v && @@ -859,10 +871,11 @@ namespace hpx::segmented { /// serializable by HPX. /// /// The policy controls local partition sorting and whether independent - /// locality operations overlap. The final merge runs serially on one - /// participating locality and uses storage proportional to the input size. - /// Destination runs are committed incrementally; an exception during this - /// phase can leave a partially reordered range. + /// locality operations overlap. This first implementation gathers all + /// participating runs on one locality. Its final merge is serial, requires + /// O(N) coordinator storage, and takes O(N log P) comparisons for P + /// participating runs. Destination runs are committed incrementally; an + /// exception during this phase can leave a partially reordered range. HPX_CXX_EXPORT template requires(hpx::is_execution_policy_v && diff --git a/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt b/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt index a7c576c3bb85..3004e40df7a2 100644 --- a/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt +++ b/libs/full/segmented_algorithms/tests/unit/CMakeLists.txt @@ -129,13 +129,8 @@ foreach(test ${tests}) endforeach() if(HPX_WITH_CXX_MODULES) - # These tests inspect implementation helpers that are not exported by - # HPX.Full. - foreach(test partitioned_vector_merge_extended - partitioned_vector_merge_regressions partitioned_vector_sort + # This test inspects implementation helpers that are not exported by HPX.Full. + target_compile_definitions( + partitioned_vector_sort_test PRIVATE HPX_HAVE_FORCE_NO_CXX_MODULES ) - target_compile_definitions( - ${test}_test PRIVATE HPX_HAVE_FORCE_NO_CXX_MODULES - ) - endforeach() endif() diff --git a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp index e13571a39594..b9cead3637cc 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2026 the-ivii +// Copyright (c) 2026 Pratyksh Gupta // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying @@ -414,71 +414,17 @@ void test_kway_merge() } } -void test_host_placement(std::vector const& localities) +void test_large_transfers(std::vector const& localities) { - namespace detail = hpx::parallel::detail; - constexpr auto unit = static_cast( - detail::segmented_sort_transfer_chunk_size / 32 + 1); - std::vector data(static_cast(45 * unit)); - using iterator = std::vector::iterator; - detail::segmented_sort_block runs; - auto const& a = localities.front(); - auto const& b = localities.back(); - // A owns the largest individual run (5 units); B owns ten of 4. - runs.emplace_back(a, a, data.begin(), data.begin() + 5 * unit); - for (std::ptrdiff_t i = 5 * unit; i < 45 * unit; i += 4 * unit) - { - runs.emplace_back(b, b, data.begin() + i, data.begin() + i + 4 * unit); - } - HPX_TEST(detail::segmented_sort_host(runs, {}) == b); - - if (a != b) - { - hpx::partitioned_vector values( - 200, 0, hpx::container_layout(20, std::vector{a, b})); - initialize_values(values, [](int i) { return 200 - i; }); - auto first = values.begin() + 90; - auto participating = detail::segmented_sort_runs(first, values.end()); - HPX_TEST_EQ(participating.size(), std::size_t(11)); - HPX_TEST(participating.front().locality == a); - HPX_TEST_EQ(std::count_if(participating.begin(), participating.end(), - [&](auto const& run) { return run.locality == b; }), - std::ptrdiff_t(10)); - HPX_TEST(detail::segmented_sort_host(participating, {}) == b); - auto expected = copy_values(values); - std::sort(expected.begin() + 90, expected.end()); - hpx::sort(hpx::execution::par, first, values.end()); - HPX_TEST(copy_values(values) == expected); - } -} - -void test_transfer_chunks(std::vector const& localities) -{ - namespace detail = hpx::parallel::detail; - auto const size = 8 * detail::segmented_sort_transfer_chunk_size + 7; + // Large enough to exercise multiple bounded transfers through the public + // algorithm without depending on implementation helpers. + constexpr std::size_t size = 8 * 65536 + 7; hpx::partitioned_vector values( size, 0, hpx::container_layout(3, localities)); initialize_values(values, [](std::size_t i) { return static_cast((i * 17 + 3) % 97); }); auto expected = copy_values(values); std::sort(expected.begin() + 1, expected.end() - 2); - auto runs = - detail::segmented_sort_runs(values.begin() + 1, values.end() - 2); - auto chunks = detail::segmented_sort_transfer_chunks(runs); - std::size_t total = 0; - for (auto const& chunk : chunks) - { - auto const n = detail::segmented_sort_block_size(chunk); - HPX_TEST_LTE(n, detail::segmented_sort_transfer_chunk_size); - total += n; - for (auto const& run : chunk) - { - HPX_TEST(run.locality == - hpx::get_colocation_id(hpx::launch::sync, run.id)); - HPX_TEST(run.locality != run.id); - } - } - HPX_TEST_EQ(total, size - 3); hpx::sort(hpx::execution::par(hpx::execution::task), values.begin() + 1, values.end() - 2) .get(); @@ -487,8 +433,7 @@ void test_transfer_chunks(std::vector const& localities) // Exercise the distributed merge with nontrivial values and descending // order as well as the default integer comparator above. hpx::partitioned_vector strings( - 2 * detail::segmented_sort_transfer_chunk_size + 7, std::string{}, - hpx::container_layout(3, localities)); + 2 * 65536 + 7, std::string{}, hpx::container_layout(3, localities)); initialize_values(strings, [](std::size_t i) { return std::to_string((i * 17 + 3) % 97) + std::string(32, 'x'); }); @@ -657,55 +602,12 @@ void test_async_run_collection(ExPolicy const& policy) } } -void test_transfer_batches(std::vector const& localities) -{ - namespace detail = hpx::parallel::detail; - auto const partitions = 4 * localities.size(); - hpx::partitioned_vector values( - partitions * 9, 0, hpx::container_layout(partitions, localities)); - initialize_values(values, [](int i) { return i; }); - auto runs = detail::segmented_sort_runs(values.begin(), values.end()); - decltype(runs) block; - std::vector expected; - // Interleave ownership so four localities cross the eight-action batch - // boundary. The helper must preserve logical order and disjoint writes. - for (std::size_t piece = 0; piece < 4; ++piece) - { - for (std::size_t locality = 0; locality < localities.size(); ++locality) - { - auto const index = 4 * locality + piece; - block.push_back(runs[index]); - for (std::size_t i = 0; i < 9; ++i) - { - expected.push_back(static_cast(9 * index + i)); - } - } - } - auto fetched = - detail::segmented_sort_fetch_block(hpx::execution::par, block); - HPX_TEST(fetched == expected); - for (auto& value : fetched) - { - value = -value - 1; - } - auto end = detail::segmented_sort_store_block( - hpx::execution::par, block, fetched.begin()); - HPX_TEST(end == fetched.end()); - auto got = copy_values(values); - for (std::size_t i = 0; i < got.size(); ++i) - { - HPX_TEST_EQ(got[i], -static_cast(i) - 1); - } -} - /////////////////////////////////////////////////////////////////////////////// int main() { std::vector localities = hpx::find_all_localities(); test_kway_merge(); - test_host_placement(localities); - test_transfer_chunks(localities); - test_transfer_batches(localities); + test_large_transfers(localities); test_async_run_collection(hpx::execution::seq(hpx::execution::task)); test_async_run_collection(hpx::execution::par(hpx::execution::task)); test_merge_exceptions(hpx::execution::seq, localities);