From aee5b3e2d364f932844eb365518e72155188c77c Mon Sep 17 00:00:00 2001 From: the-ivii Date: Tue, 10 Nov 2026 03:03:41 +0530 Subject: [PATCH 01/10] Distribute the segmented sort merge Signed-off-by: the-ivii --- .../parallel/segmented_algorithms/sort.hpp | 229 ++++++++---------- .../tests/unit/partitioned_vector_sort.cpp | 95 ++------ 2 files changed, 122 insertions(+), 202 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 17bf017740b0..9d9d244ab4bd 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,7 +24,6 @@ #include #include #include -#include #include #include #include @@ -248,8 +247,8 @@ namespace hpx::parallel::detail { return chunks; } - // Choose the locality holding the most participating data so the k-way - // merge transfers as little input as possible. + // Choose the locality holding the most participating data so a compare- + // split transfers as little input as possible. template hpx::id_type segmented_sort_host( segmented_sort_block const& left, @@ -522,47 +521,6 @@ namespace hpx::parallel::detail { 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. 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, - std::vector const& counts, Pred& pred, Emit&& emit) - { - struct cursor - { - std::size_t pos; - std::size_t end; - }; - - auto order = [&](cursor const& lhs, cursor const& rhs) { - return pred(values[rhs.pos], values[lhs.pos]); - }; - std::priority_queue, decltype(order)> heap( - order); - - for (std::size_t i = 0; i != counts.size(); ++i) - { - if (counts[i] != 0) - { - heap.push(cursor{offsets[i], offsets[i] + counts[i]}); - } - } - - while (!heap.empty()) - { - auto current = heap.top(); - heap.pop(); - emit(HPX_MOVE(values[current.pos])); - if (++current.pos != current.end) - { - heap.push(current); - } - } - } - template struct segmented_sort_local_runs_on_host : algorithm, bool> @@ -660,86 +618,71 @@ namespace hpx::parallel::detail { } template - struct segmented_sort_kway_merge_on_host - : algorithm, bool> + struct segmented_sort_compare_split_on_host + : algorithm, bool> { - constexpr segmented_sort_kway_merge_on_host() noexcept - : algorithm( - "segmented_sort_kway_merge_on_host") + constexpr segmented_sort_compare_split_on_host() noexcept + : algorithm( + "segmented_sort_compare_split_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; + segmented_sort_run const& left, + segmented_sort_run const& right, Comp comp, Proj proj) + { + segmented_sort_block const pair{left, right}; + auto values = segmented_sort_fetch_block(policy, pair); + auto const left_size = static_cast(left.size()); + HPX_ASSERT(values.size() == + left_size + static_cast(right.size())); + + auto middle = values.begin() + + static_cast( + left_size); + util::compare_projected pred(comp, proj); - std::vector counts; - std::vector offsets; - counts.reserve(runs.size()); - offsets.reserve(runs.size()); - std::size_t total = 0; - for (auto const& run : runs) + // Avoid rewriting an already ordered pair. The full pair has + // already been fetched, but no destination is modified. + if (middle == values.end() || !pred(*middle, *(std::prev(middle)))) { - offsets.push_back(total); - auto const count = static_cast(run.size()); - counts.push_back(count); - total += count; + return false; } - 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]) - { - return; - } - - 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()) - { - output.reserve(counts[destination]); - } - }; - - segmented_sort_kway_for_each(values, offsets, counts, pred, emit); - HPX_ASSERT(destination == runs.size()); + hpx::inplace_merge( + policy, values.begin(), middle, values.end(), pred); + [[maybe_unused]] auto const last = + segmented_sort_store_block(policy, pair, values.begin()); + HPX_ASSERT(last == values.end()); return true; } template static bool sequential(ExPolicy const& policy, - segmented_sort_block const& runs, Comp comp, Proj proj) + segmented_sort_run const& left, + segmented_sort_run const& right, Comp comp, Proj proj) { - return execute(policy, runs, HPX_MOVE(comp), HPX_MOVE(proj)); + return execute(policy, left, right, HPX_MOVE(comp), HPX_MOVE(proj)); } template static bool parallel(ExPolicy const& policy, - segmented_sort_block const& runs, Comp comp, Proj proj) + segmented_sort_run const& left, + segmented_sort_run const& right, 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)); + // Disjoint pairs are overlapped by segmented_sort_merge_runs; the + // policy is also used by the local merge and stores. + return execute(policy, left, right, HPX_MOVE(comp), HPX_MOVE(proj)); } }; - // 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. + // Odd-even compare-split phases keep the data distributed. Each operation + // temporarily holds only two adjacent runs, keeps the lower part in the + // left run and the upper part in the right run, and uses bounded transfers. + // After P phases all P runs are globally ordered. Parallel policies overlap + // the disjoint pairs in each phase. Temporary storage is bounded by the + // largest adjacent pair, although values can move in multiple phases. template void segmented_sort_merge_runs(ExPolicy const& policy, @@ -751,28 +694,57 @@ namespace hpx::parallel::detail { return; } - 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 + using operation = segmented_sort_compare_split_on_host; + auto const here = hpx::find_here(); + for (std::size_t phase = 0; phase != runs.size(); ++phase) { - if (host == hpx::find_here()) + std::vector> pending; + pending.reserve(runs.size() / 2); + std::exception_ptr error; + try { - operation().call2(policy, is_seq, runs, comp, proj); + for (std::size_t i = phase % 2; i + 1 < runs.size(); i += 2) + { + segmented_sort_block const left{runs[i]}; + segmented_sort_block const right{runs[i + 1]}; + auto const host = segmented_sort_host(left, right); + if constexpr (IsSeq::value) + { + if (host == here) + { + operation().call2(policy, is_seq, runs[i], + runs[i + 1], comp, proj); + } + else + { + dispatch(host, operation(), policy, is_seq, runs[i], + runs[i + 1], comp, proj); + } + } + else if (host == here) + { + auto left_run = runs[i]; + auto right_run = runs[i + 1]; + pending.push_back( + hpx::async([policy, left_run, right_run, comp, + proj]() mutable { + return operation::parallel(policy, left_run, + right_run, HPX_MOVE(comp), HPX_MOVE(proj)); + })); + } + else + { + pending.push_back(dispatch_async(host, operation(), + policy, is_seq, runs[i], runs[i + 1], comp, proj)); + } + } } - else + catch (...) { - pending.push_back(dispatch_async( - host, operation(), policy, is_seq, runs, comp, proj)); + error = std::current_exception(); } + segmented_sort_wait(pending, error); } - catch (...) - { - error = std::current_exception(); - } - segmented_sort_wait(pending, error); } template requires(hpx::traits::is_iterator_v && @@ -871,11 +845,14 @@ namespace hpx::segmented { /// serializable by HPX. /// /// The policy controls local partition sorting and whether independent - /// 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. + /// compare-splits overlap. The final merge uses P odd-even phases for P + /// participating runs. Each operation temporarily gathers only two + /// adjacent runs, keeps their original sizes, and writes the lower and + /// upper results back to their respective owners. No locality gathers the + /// full input; peak temporary storage is proportional to the largest + /// adjacent pair, and a value can be transferred in multiple phases. An + /// exception after a compare-split stores data 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 3d1120c1bc2f..c6fdcfe328a1 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -341,87 +341,27 @@ void test_sort_subranges( } } -struct move_only_sort_value -{ - explicit move_only_sort_value(int value) - : value(value) - { - } - - 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() +template +void test_uneven_merge_split( + ExPolicy const& policy, std::vector const& localities) { - namespace detail = hpx::parallel::detail; - - for (std::size_t run_count : {3, 5, 6, 7}) - { - for (std::size_t tail = 1; tail != 5; ++tail) - { - for (std::size_t seed = 0; seed != 16; ++seed) - { - std::vector values; - std::vector offsets; - std::vector counts; - std::vector expected; - for (std::size_t run = 0; run != run_count; ++run) - { - 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()); - } - std::sort(expected.begin(), expected.end()); - - 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); - } - } - } + // Eleven physical partitions across four localities exercise both parities + // of the compare-split network, unequal run sizes, and duplicate values. + hpx::partitioned_vector values( + 257, 0, hpx::container_layout(11, localities)); + initialize_values(values, + [](std::size_t i) { return static_cast((i * 37 + 11) % 23); }); + auto const expected = copy_values(values); - std::vector values; - for (int value : {0, 3, 6, 1, 4, 7, 2, 5, 8}) + if constexpr (hpx::is_async_execution_policy_v) { - values.emplace_back(value); + hpx::sort(policy, values.begin(), values.end()).get(); } - 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) + else { - HPX_TEST_EQ(output[i].value, static_cast(i)); + hpx::sort(policy, values.begin(), values.end()); } + verify_sorted(values, expected); } void test_large_transfers(std::vector const& localities) @@ -616,7 +556,10 @@ void test_async_run_collection(ExPolicy const& policy) int main() { std::vector localities = hpx::find_all_localities(); - test_kway_merge(); + test_uneven_merge_split(hpx::execution::seq, localities); + test_uneven_merge_split(hpx::execution::par, localities); + test_uneven_merge_split( + hpx::execution::par(hpx::execution::task), 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)); From cc3b3d9636f57c7df50d60a9245a2b899d5c3c8e Mon Sep 17 00:00:00 2001 From: the-ivii Date: Tue, 10 Nov 2026 03:43:57 +0530 Subject: [PATCH 02/10] Bound segmented sort merge transfers Signed-off-by: the-ivii --- .../parallel/segmented_algorithms/sort.hpp | 274 +++++++++++++++--- .../tests/performance/CMakeLists.txt | 2 +- .../partitioned_vector_sort_performance.cpp | 105 +++++++ .../tests/unit/partitioned_vector_sort.cpp | 26 ++ 4 files changed, 370 insertions(+), 37 deletions(-) create mode 100644 libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp 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 9d9d244ab4bd..00b21bc7cb4e 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 @@ -74,6 +74,45 @@ namespace hpx::parallel::detail { } }; + /// Merge two adjacent sorted ranges stored in one physical partition. + template + struct segmented_local_merge : algorithm, Iter> + { + constexpr segmented_local_merge() noexcept + : algorithm("segmented_local_merge") + { + } + + /// Merge two local ranges using the supplied policy and projection. + template + static InIter sequential(ExPolicy&& policy, InIter first, InIter middle, + InIter last, Comp&& comp, Proj&& proj) + { + using local_traits = + hpx::traits::segmented_local_iterator_traits; + using predicate_type = + util::compare_projected, std::decay_t>; + predicate_type pred( + HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); + hpx::inplace_merge(hpx::execution::experimental::to_non_task( + HPX_FORWARD(ExPolicy, policy)), + local_traits::local(first), local_traits::local(middle), + local_traits::local(last), pred); + return last; + } + + /// Parallel entry point for merging two local ranges. + template + static InIter parallel(ExPolicy&& policy, InIter first, InIter middle, + InIter last, Comp&& comp, Proj&& proj) + { + return sequential(HPX_FORWARD(ExPolicy, policy), first, middle, + last, HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); + } + }; + // Bound outstanding transport and namespace requests independently of // the number of partitions. inline constexpr std::size_t segmented_sort_transfer_limit = 8; @@ -627,37 +666,202 @@ namespace hpx::parallel::detail { { } + /// Return a subrange of a physical sorted run. + static segmented_sort_run subrun( + segmented_sort_run const& run, std::size_t offset, + std::size_t count) + { + auto const first = run.first + static_cast(offset); + return {run.id, run.locality, first, + first + static_cast(count)}; + } + + /// Compare projected values at two positions without gathering either + /// complete run on the coordinating locality. template - static bool execute(ExPolicy const& policy, - segmented_sort_run const& left, - segmented_sort_run const& right, Comp comp, Proj proj) + static bool less_at(ExPolicy const& policy, + segmented_sort_run const& lhs, std::size_t lhs_offset, + segmented_sort_run const& rhs, std::size_t rhs_offset, + Comp& comp, Proj& proj) + { + segmented_sort_block const values_to_fetch{ + subrun(lhs, lhs_offset, 1), subrun(rhs, rhs_offset, 1)}; + auto values = segmented_sort_fetch_block(policy, values_to_fetch); + HPX_ASSERT(values.size() == 2); + util::compare_projected pred(comp, proj); + return pred(values[0], values[1]); + } + + /// Find the stable merge partition that leaves left.size() values in + /// the left run. The two returned offsets delimit equally sized + /// crossing ranges: left[i, end) and right[begin, j). + template + static std::pair merge_partition( + ExPolicy const& policy, segmented_sort_run const& left, + segmented_sort_run const& right, Comp& comp, Proj& proj) { - segmented_sort_block const pair{left, right}; - auto values = segmented_sort_fetch_block(policy, pair); auto const left_size = static_cast(left.size()); - HPX_ASSERT(values.size() == - left_size + static_cast(right.size())); + auto const right_size = static_cast(right.size()); + std::size_t low = + left_size > right_size ? left_size - right_size : 0; + std::size_t high = left_size; - auto middle = values.begin() + - static_cast( - left_size); - util::compare_projected pred(comp, proj); + while (low <= high) + { + auto const left_cut = low + (high - low) / 2; + auto const right_cut = left_size - left_cut; + + if (left_cut != 0 && right_cut != right_size && + less_at(policy, right, right_cut, left, left_cut - 1, comp, + proj)) + { + high = left_cut - 1; + } + else if (right_cut != 0 && left_cut != left_size && + less_at(policy, left, left_cut, right, right_cut - 1, comp, + proj)) + { + low = left_cut + 1; + } + else + { + return {left_cut, right_cut}; + } + } + + HPX_ASSERT(false); + return {left_size, 0}; + } + + /// Exchange the crossing suffix and prefix in bounded chunks. At most + /// two transfer chunks are materialized on the coordinator at once. + template + static void exchange_crossing_ranges(ExPolicy const& policy, + segmented_sort_run const& left, + segmented_sort_run const& right, std::size_t left_cut, + std::size_t crossing_size) + { + for (std::size_t offset = 0; offset != crossing_size;) + { + auto const count = + (std::min) (segmented_sort_transfer_chunk_size, + crossing_size - offset); + auto const left_chunk = subrun(left, left_cut + offset, count); + auto const right_chunk = subrun(right, offset, count); + segmented_sort_block const chunks{ + left_chunk, right_chunk}; + auto values = segmented_sort_fetch_block(policy, chunks); + HPX_ASSERT(values.size() == 2 * count); + + segmented_sort_block const left_destination{ + left_chunk}; + segmented_sort_block const right_destination{ + right_chunk}; + auto const middle = values.begin() + + static_cast( + count); + [[maybe_unused]] auto const left_last = + segmented_sort_store_block( + policy, left_destination, middle); + [[maybe_unused]] auto const right_last = + segmented_sort_store_block( + policy, right_destination, values.begin()); + HPX_ASSERT(left_last == values.end()); + HPX_ASSERT(right_last == middle); + offset += count; + } + } - // Avoid rewriting an already ordered pair. The full pair has - // already been fetched, but no destination is modified. - if (middle == values.end() || !pred(*middle, *(std::prev(middle)))) + /// Merge the two exchanged runs independently on their owning + /// localities. Parallel policies overlap the two local merges. + template + static void merge_exchanged_runs(ExPolicy const& policy, + segmented_sort_run const& left, + segmented_sort_run const& right, std::size_t left_cut, + std::size_t right_cut, Comp const& comp, Proj const& proj, + IsSeq is_seq) + { + using operation = segmented_local_merge; + auto const here = hpx::find_here(); + std::vector> pending; + std::exception_ptr error; + auto merge_run = [&](segmented_sort_run const& run, + std::size_t middle_offset) { + if (middle_offset == 0 || + middle_offset == static_cast(run.size())) + { + return; + } + + auto const middle = + run.first + static_cast(middle_offset); + if constexpr (IsSeq::value) + { + if (run.locality == here) + { + operation::sequential( + policy, run.first, middle, run.last, comp, proj); + } + else + { + dispatch(run.locality, operation(), policy, is_seq, + run.first, middle, run.last, comp, proj); + } + } + else if (run.locality == here) + { + pending.push_back( + hpx::async([policy, first = run.first, middle, + last = run.last, comp, proj]() mutable { + return operation::parallel(policy, first, middle, + last, HPX_MOVE(comp), HPX_MOVE(proj)); + })); + } + else + { + pending.push_back( + dispatch_async(run.locality, operation(), policy, + is_seq, run.first, middle, run.last, comp, proj)); + } + }; + + try + { + merge_run(left, left_cut); + merge_run(right, right_cut); + } + catch (...) + { + error = std::current_exception(); + } + segmented_sort_wait(pending, error); + } + + /// Perform a bounded merge-split of two adjacent sorted runs. + template + static bool execute(ExPolicy const& policy, + segmented_sort_run const& left, + segmented_sort_run const& right, Comp comp, Proj proj) + { + auto const [left_cut, right_cut] = + merge_partition(policy, left, right, comp, proj); + auto const crossing_size = right_cut; + HPX_ASSERT(crossing_size == + static_cast(left.size()) - left_cut); + if (crossing_size == 0) { return false; } - hpx::inplace_merge( - policy, values.begin(), middle, values.end(), pred); - [[maybe_unused]] auto const last = - segmented_sort_store_block(policy, pair, values.begin()); - HPX_ASSERT(last == values.end()); + exchange_crossing_ranges( + policy, left, right, left_cut, crossing_size); + merge_exchanged_runs(policy, left, right, left_cut, right_cut, comp, + proj, hpx::is_sequenced_execution_policy{}); return true; } + /// Sequenced dispatch entry point for a compare-split. template static bool sequential(ExPolicy const& policy, segmented_sort_run const& left, @@ -666,6 +870,7 @@ namespace hpx::parallel::detail { return execute(policy, left, right, HPX_MOVE(comp), HPX_MOVE(proj)); } + /// Parallel dispatch entry point for a compare-split. template static bool parallel(ExPolicy const& policy, segmented_sort_run const& left, @@ -677,12 +882,12 @@ namespace hpx::parallel::detail { } }; - // Odd-even compare-split phases keep the data distributed. Each operation - // temporarily holds only two adjacent runs, keeps the lower part in the - // left run and the upper part in the right run, and uses bounded transfers. - // After P phases all P runs are globally ordered. Parallel policies overlap - // the disjoint pairs in each phase. Temporary storage is bounded by the - // largest adjacent pair, although values can move in multiple phases. + /// Run odd-even compare-split phases while keeping data distributed. Each + /// operation exchanges only the crossing suffix and prefix using bounded + /// buffers, then merges both runs on their owning localities. After P + /// phases all P runs are globally ordered. Parallel policies overlap the + /// disjoint pairs in each phase, although values can move in multiple + /// phases. template void segmented_sort_merge_runs(ExPolicy const& policy, @@ -814,10 +1019,9 @@ namespace hpx::segmented { /// by HPX. /// /// The final merge uses P odd-even compare-split phases for P participating - /// runs. Each operation temporarily gathers only two adjacent runs, keeps - /// their original sizes, and writes the lower and upper results back to - /// their respective owners. No locality gathers the full input; peak - /// temporary storage is proportional to the largest adjacent pair, and a + /// runs. Each operation finds the merge partition, exchanges only the + /// crossing suffix and prefix in bounded chunks, and merges both runs on + /// their owning localities. No locality gathers the full input, although a /// value can be transferred in multiple phases. An exception after a /// compare-split stores data can leave a partially reordered range. HPX_CXX_EXPORT template requires(hpx::is_execution_policy_v && diff --git a/libs/full/segmented_algorithms/tests/performance/CMakeLists.txt b/libs/full/segmented_algorithms/tests/performance/CMakeLists.txt index e8db7f041b00..114a51a96099 100644 --- a/libs/full/segmented_algorithms/tests/performance/CMakeLists.txt +++ b/libs/full/segmented_algorithms/tests/performance/CMakeLists.txt @@ -4,7 +4,7 @@ # Distributed under the Boost Software License, Version 1.0. (See accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) -set(benchmarks minmax_element_performance) +set(benchmarks minmax_element_performance partitioned_vector_sort_performance) foreach(benchmark ${benchmarks}) set(sources ${benchmark}.cpp) diff --git a/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp b/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp new file mode 100644 index 000000000000..a6c16b1c7eeb --- /dev/null +++ b/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp @@ -0,0 +1,105 @@ +// Copyright (c) 2026 Pratyksh Gupta +// +// 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 +#include +#include +#include + +namespace { + using vector_type = hpx::partitioned_vector; + + /// Restore the distributed input before a timed benchmark iteration. + void set_input(vector_type& values, + std::vector const& positions, + std::vector const& input) + { + values.set_values(hpx::launch::sync, positions, input); + } +} // namespace + +/// Compare distributed sorting with a centralized gather-sort-scatter. +int hpx_main(hpx::program_options::variables_map& vm) +{ + if (hpx::get_locality_id() != 0) + { + return 0; + } + + auto const size = vm["vector_size"].as(); + auto const test_count = vm["test_count"].as(); + auto partitions = vm["partitions"].as(); + auto const seed = vm["seed"].as(); + auto const localities = hpx::find_all_localities(); + if (partitions == 0) + { + partitions = localities.size(); + } + + vector_type values(size, 0, hpx::container_layout(partitions, localities)); + std::vector positions(size); + std::iota(positions.begin(), positions.end(), std::size_t(0)); + std::vector input(size); + std::mt19937 generator(seed); + std::uniform_int_distribution distribution; + std::generate( + input.begin(), input.end(), [&]() { return distribution(generator); }); + + hpx::util::perftests_init(vm, "partitioned_vector_sort_performance"); + hpx::util::perftests_report( + "partitioned_vector_sort", "distributed", test_count, 1, + [&]() { hpx::sort(hpx::execution::par, values.begin(), values.end()); }, + [&]() { set_input(values, positions, input); }); + + hpx::util::perftests_report( + "partitioned_vector_sort", "centralized_gather_sort", test_count, 1, + [&]() { + auto gathered = values.get_values(hpx::launch::sync, positions); + std::sort(gathered.begin(), gathered.end()); + values.set_values(hpx::launch::sync, positions, gathered); + }, + [&]() { set_input(values, positions, input); }); + + hpx::util::perftests_print_times(); + return hpx::finalize(); +} + +/// Configure and launch the distributed performance benchmark. +int main(int argc, char* argv[]) +{ + hpx::program_options::options_description cmdline( + "usage: " HPX_APPLICATION_STRING " [options]"); + cmdline.add_options()("vector_size", + hpx::program_options::value()->default_value(1000000), + "number of values")("partitions", + hpx::program_options::value()->default_value(0), + "number of partitions (zero uses one per locality)")("test_count", + hpx::program_options::value()->default_value(5), + "number of timed iterations")("seed", + hpx::program_options::value()->default_value(0), + "random-number seed"); + hpx::util::perftests_cfg(cmdline); + + hpx::init_params init_args; + init_args.desc_cmdline = cmdline; + init_args.cfg = {"hpx.os_threads=all", "hpx.run_hpx_main!=1"}; + return hpx::init(argc, argv, init_args); +} +#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 c6fdcfe328a1..de3cb8947e37 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -341,6 +341,7 @@ void test_sort_subranges( } } +/// Verify compare-split phases with uneven runs and duplicate values. template void test_uneven_merge_split( ExPolicy const& policy, std::vector const& localities) @@ -364,6 +365,30 @@ void test_uneven_merge_split( verify_sorted(values, expected); } +/// Verify that a complete two-run exchange remains chunked and distributed. +void test_two_run_merge_split(std::vector const& localities) +{ + // Put two reversed runs on different localities. Every value crosses the + // merge partition, exercising the bounded exchange without gathering the + // complete input on either locality. + std::vector hosts{ + localities[0], localities[localities.size() > 1 ? 1 : 0]}; + hpx::partitioned_vector values( + 2 * (65536 + 7), 0, hpx::container_layout(2, hosts)); + initialize_values(values, [&](std::size_t i) { + auto const run_size = values.size() / 2; + if (i < run_size) + { + return static_cast(run_size + i); + } + return static_cast(i - run_size); + }); + auto const expected = copy_values(values); + + hpx::sort(hpx::execution::par, values.begin(), values.end()); + verify_sorted(values, expected); +} + void test_large_transfers(std::vector const& localities) { // Large enough to exercise multiple bounded transfers through the public @@ -560,6 +585,7 @@ int main() test_uneven_merge_split(hpx::execution::par, localities); test_uneven_merge_split( hpx::execution::par(hpx::execution::task), localities); + test_two_run_merge_split(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)); From 70e9aa2d92c64938390dc2227772fa13bf2f14eb Mon Sep 17 00:00:00 2001 From: the-ivii Date: Tue, 10 Nov 2026 04:20:00 +0530 Subject: [PATCH 03/10] Handle unequal segmented sort runs Signed-off-by: the-ivii --- .../parallel/segmented_algorithms/sort.hpp | 71 ++++++++++++------- .../tests/performance/CMakeLists.txt | 4 ++ .../partitioned_vector_sort_performance.cpp | 58 ++++++++++----- .../tests/unit/partitioned_vector_sort.cpp | 17 +++++ 4 files changed, 105 insertions(+), 45 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 00b21bc7cb4e..9860c6a0bd5d 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 @@ -844,16 +844,18 @@ namespace hpx::parallel::detail { segmented_sort_run const& left, segmented_sort_run const& right, Comp comp, Proj proj) { - auto const [left_cut, right_cut] = - merge_partition(policy, left, right, comp, proj); - auto const crossing_size = right_cut; - HPX_ASSERT(crossing_size == - static_cast(left.size()) - left_cut); - if (crossing_size == 0) + auto const left_size = static_cast(left.size()); + if (!less_at(policy, right, 0, left, left_size - 1, comp, proj)) { return false; } + auto const [left_cut, right_cut] = + merge_partition(policy, left, right, comp, proj); + auto const crossing_size = right_cut; + HPX_ASSERT(crossing_size == left_size - left_cut); + HPX_ASSERT(crossing_size != 0); + exchange_crossing_ranges( policy, left, right, left_cut, crossing_size); merge_exchanged_runs(policy, left, right, left_cut, right_cut, comp, @@ -884,10 +886,10 @@ namespace hpx::parallel::detail { /// Run odd-even compare-split phases while keeping data distributed. Each /// operation exchanges only the crossing suffix and prefix using bounded - /// buffers, then merges both runs on their owning localities. After P - /// phases all P runs are globally ordered. Parallel policies overlap the - /// disjoint pairs in each phase, although values can move in multiple - /// phases. + /// buffers, then merges both runs on their owning localities. Alternating + /// phases continue until both parities report no changes. Parallel policies + /// overlap the disjoint pairs in each phase, although values can move in + /// multiple phases. template void segmented_sort_merge_runs(ExPolicy const& policy, @@ -901,8 +903,11 @@ namespace hpx::parallel::detail { using operation = segmented_sort_compare_split_on_host; auto const here = hpx::find_here(); - for (std::size_t phase = 0; phase != runs.size(); ++phase) + std::size_t phase = 0; + std::size_t unchanged_phases = 0; + while (unchanged_phases != 2) { + bool phase_changed = false; std::vector> pending; pending.reserve(runs.size() / 2); std::exception_ptr error; @@ -917,13 +922,17 @@ namespace hpx::parallel::detail { { if (host == here) { - operation().call2(policy, is_seq, runs[i], - runs[i + 1], comp, proj); + phase_changed = + operation().call2(policy, is_seq, runs[i], + runs[i + 1], comp, proj) || + phase_changed; } else { - dispatch(host, operation(), policy, is_seq, runs[i], - runs[i + 1], comp, proj); + phase_changed = + dispatch(host, operation(), policy, is_seq, + runs[i], runs[i + 1], comp, proj) || + phase_changed; } } else if (host == here) @@ -949,6 +958,12 @@ namespace hpx::parallel::detail { error = std::current_exception(); } segmented_sort_wait(pending, error); + for (auto& result : pending) + { + phase_changed = result.get() || phase_changed; + } + unchanged_phases = phase_changed ? 0 : unchanged_phases + 1; + ++phase; } } @@ -1018,12 +1033,13 @@ namespace hpx::segmented { /// spanning localities, the comparator must be copyable and serializable /// by HPX. /// - /// The final merge uses P odd-even compare-split phases for P participating - /// runs. Each operation finds the merge partition, exchanges only the - /// crossing suffix and prefix in bounded chunks, and merges both runs on - /// their owning localities. No locality gathers the full input, although a - /// value can be transferred in multiple phases. An exception after a - /// compare-split stores data can leave a partially reordered range. + /// The final merge uses alternating odd-even compare-split phases until + /// both parities are unchanged. Each operation finds the merge partition, + /// exchanges only the crossing suffix and prefix in bounded chunks, and + /// merges both runs on their owning localities. No locality gathers the + /// full input, although a value can be transferred in multiple phases. An + /// exception after a compare-split stores data can leave a partially + /// reordered range. HPX_CXX_EXPORT template requires(hpx::traits::is_iterator_v && @@ -1049,12 +1065,13 @@ namespace hpx::segmented { /// serializable by HPX. /// /// The policy controls local partition sorting and whether independent - /// compare-splits overlap. The final merge uses P odd-even phases for P - /// participating runs. Each operation finds the merge partition, exchanges - /// only the crossing suffix and prefix in bounded chunks, and merges both - /// runs on their owning localities. No locality gathers the full input, - /// although a value can be transferred in multiple phases. An exception - /// after a compare-split stores data can leave a partially reordered range. + /// compare-splits overlap. The final merge uses alternating odd-even phases + /// until both parities are unchanged. Each operation finds the merge + /// partition, exchanges only the crossing suffix and prefix in bounded + /// chunks, and merges both runs on their owning localities. No locality + /// gathers the full input, although a value can be transferred in multiple + /// phases. An exception after a compare-split stores data can leave a + /// partially reordered range. HPX_CXX_EXPORT template requires(hpx::is_execution_policy_v && diff --git a/libs/full/segmented_algorithms/tests/performance/CMakeLists.txt b/libs/full/segmented_algorithms/tests/performance/CMakeLists.txt index 114a51a96099..84cac16c7946 100644 --- a/libs/full/segmented_algorithms/tests/performance/CMakeLists.txt +++ b/libs/full/segmented_algorithms/tests/performance/CMakeLists.txt @@ -6,6 +6,10 @@ set(benchmarks minmax_element_performance partitioned_vector_sort_performance) +set(partitioned_vector_sort_performance_PARAMETERS LOCALITIES 2 + THREADS_PER_LOCALITY 2 +) + foreach(benchmark ${benchmarks}) set(sources ${benchmark}.cpp) diff --git a/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp b/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp index a6c16b1c7eeb..3e7238c1bdfe 100644 --- a/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp +++ b/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp @@ -13,11 +13,12 @@ #include #include #include -#include #include +#include #include #include +#include #include #include #include @@ -33,6 +34,26 @@ namespace { { values.set_values(hpx::launch::sync, positions, input); } + + /// Measure an operation while restoring its input outside the timed region. + template + double measure(std::size_t test_count, Reset&& reset, Operation&& operation) + { + using clock = std::chrono::steady_clock; + + reset(); + operation(); + + std::chrono::duration elapsed{}; + for (std::size_t i = 0; i != test_count; ++i) + { + reset(); + auto const start = clock::now(); + operation(); + elapsed += clock::now() - start; + } + return elapsed.count() / static_cast(test_count); + } } // namespace /// Compare distributed sorting with a centralized gather-sort-scatter. @@ -62,22 +83,24 @@ int hpx_main(hpx::program_options::variables_map& vm) std::generate( input.begin(), input.end(), [&]() { return distribution(generator); }); - hpx::util::perftests_init(vm, "partitioned_vector_sort_performance"); - hpx::util::perftests_report( - "partitioned_vector_sort", "distributed", test_count, 1, - [&]() { hpx::sort(hpx::execution::par, values.begin(), values.end()); }, - [&]() { set_input(values, positions, input); }); - - hpx::util::perftests_report( - "partitioned_vector_sort", "centralized_gather_sort", test_count, 1, - [&]() { - auto gathered = values.get_values(hpx::launch::sync, positions); - std::sort(gathered.begin(), gathered.end()); - values.set_values(hpx::launch::sync, positions, gathered); - }, - [&]() { set_input(values, positions, input); }); - - hpx::util::perftests_print_times(); + if (test_count == 0) + { + return hpx::finalize(); + } + + auto const reset = [&]() { set_input(values, positions, input); }; + auto const distributed = measure(test_count, reset, [&]() { + hpx::sort(hpx::execution::par, values.begin(), values.end()); + }); + auto const centralized = measure(test_count, reset, [&]() { + auto gathered = values.get_values(hpx::launch::sync, positions); + std::sort(gathered.begin(), gathered.end()); + values.set_values(hpx::launch::sync, positions, gathered); + }); + + std::cout << "partitioned_vector_sort distributed " << distributed + << " s\npartitioned_vector_sort centralized_gather_sort " + << centralized << " s\n"; return hpx::finalize(); } @@ -95,7 +118,6 @@ int main(int argc, char* argv[]) "number of timed iterations")("seed", hpx::program_options::value()->default_value(0), "random-number seed"); - hpx::util::perftests_cfg(cmdline); hpx::init_params init_args; init_args.desc_cmdline = cmdline; 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 de3cb8947e37..0fb29aded405 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -389,6 +389,22 @@ void test_two_run_merge_split(std::vector const& localities) verify_sorted(values, expected); } +/// Verify convergence when adjacent runs have strongly unequal capacities. +void test_unequal_explicit_layout(std::vector const& localities) +{ + std::vector const sizes{100, 1, 100}; + std::vector const owners{localities[0], + localities[localities.size() > 1 ? 1 : 0], + localities[localities.size() > 2 ? 2 : 0]}; + hpx::partitioned_vector values( + 201, 0, hpx::explicit_container_layout(sizes, owners)); + initialize_values(values, [](std::size_t i) { return i < 100 ? 1 : 0; }); + auto const expected = copy_values(values); + + hpx::sort(hpx::execution::par, values.begin(), values.end()); + verify_sorted(values, expected); +} + void test_large_transfers(std::vector const& localities) { // Large enough to exercise multiple bounded transfers through the public @@ -586,6 +602,7 @@ int main() test_uneven_merge_split( hpx::execution::par(hpx::execution::task), localities); test_two_run_merge_split(localities); + test_unequal_explicit_layout(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)); From 47282e1d3dfbd87b4166e8629547f419f5bac04a Mon Sep 17 00:00:00 2001 From: the-ivii Date: Tue, 10 Nov 2026 04:53:19 +0530 Subject: [PATCH 04/10] Document segmented sort benchmark helpers Signed-off-by: the-ivii --- .../partitioned_vector_sort_performance.cpp | 99 +++++++++++++++---- 1 file changed, 82 insertions(+), 17 deletions(-) diff --git a/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp b/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp index 3e7238c1bdfe..4cf1ac5c1c4c 100644 --- a/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp +++ b/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp @@ -28,6 +28,10 @@ namespace { using vector_type = hpx::partitioned_vector; /// Restore the distributed input before a timed benchmark iteration. + /// + /// \param values The distributed vector to restore. + /// \param positions The global positions corresponding to \a input. + /// \param input The values to store at \a positions. void set_input(vector_type& values, std::vector const& positions, std::vector const& input) @@ -35,28 +39,70 @@ namespace { values.set_values(hpx::launch::sync, positions, input); } - /// Measure an operation while restoring its input outside the timed region. - template - double measure(std::size_t test_count, Reset&& reset, Operation&& operation) + struct benchmark_sample + { + double distributed = 0.0; + double centralized = 0.0; + bool distributed_first = true; + }; + + /// Measure both operations in alternating order with untimed input resets. + /// + /// \tparam Reset A nullary callable that restores the benchmark input. + /// \tparam Distributed A nullary callable running the distributed sort. + /// \tparam Centralized A nullary callable running the centralized sort. + /// \param test_count The number of timed samples for each operation. + /// \param distributed_first Whether the first sample runs the distributed + /// operation first. Subsequent samples alternate the order. + /// \param reset The input restoration callable. + /// \param distributed The distributed operation to measure. + /// \param centralized The centralized operation to measure. + /// \return The raw timings and execution order for every sample. + template + std::vector measure(std::size_t test_count, + bool distributed_first, Reset&& reset, Distributed&& distributed, + Centralized&& centralized) { using clock = std::chrono::steady_clock; reset(); - operation(); + distributed(); + reset(); + centralized(); - std::chrono::duration elapsed{}; - for (std::size_t i = 0; i != test_count; ++i) - { + std::vector samples; + samples.reserve(test_count); + auto measure_one = [&](auto&& operation) { reset(); auto const start = clock::now(); operation(); - elapsed += clock::now() - start; + return std::chrono::duration(clock::now() - start).count(); + }; + for (std::size_t i = 0; i != test_count; ++i) + { + benchmark_sample sample; + sample.distributed_first = distributed_first == (i % 2 == 0); + if (sample.distributed_first) + { + sample.distributed = measure_one(distributed); + sample.centralized = measure_one(centralized); + } + else + { + sample.centralized = measure_one(centralized); + sample.distributed = measure_one(distributed); + } + samples.push_back(sample); } - return elapsed.count() / static_cast(test_count); + return samples; } } // namespace /// Compare distributed sorting with a centralized gather-sort-scatter. +/// +/// \param vm The parsed benchmark command-line options. +/// \return Zero after initiating HPX shutdown, or immediately on localities +/// that do not run the benchmark driver. int hpx_main(hpx::program_options::variables_map& vm) { if (hpx::get_locality_id() != 0) @@ -89,14 +135,29 @@ int hpx_main(hpx::program_options::variables_map& vm) } auto const reset = [&]() { set_input(values, positions, input); }; - auto const distributed = measure(test_count, reset, [&]() { - hpx::sort(hpx::execution::par, values.begin(), values.end()); - }); - auto const centralized = measure(test_count, reset, [&]() { - auto gathered = values.get_values(hpx::launch::sync, positions); - std::sort(gathered.begin(), gathered.end()); - values.set_values(hpx::launch::sync, positions, gathered); - }); + auto const samples = measure( + test_count, (seed % 2) == 0, reset, + [&]() { hpx::sort(hpx::execution::par, values.begin(), values.end()); }, + [&]() { + auto gathered = values.get_values(hpx::launch::sync, positions); + std::sort(gathered.begin(), gathered.end()); + values.set_values(hpx::launch::sync, positions, gathered); + }); + + double distributed = 0.0; + double centralized = 0.0; + for (std::size_t i = 0; i != samples.size(); ++i) + { + auto const& sample = samples[i]; + distributed += sample.distributed; + centralized += sample.centralized; + std::cout << "partitioned_vector_sort sample " << i << " first " + << (sample.distributed_first ? "distributed" : "centralized") + << " distributed " << sample.distributed << " s centralized " + << sample.centralized << " s\n"; + } + distributed /= static_cast(samples.size()); + centralized /= static_cast(samples.size()); std::cout << "partitioned_vector_sort distributed " << distributed << " s\npartitioned_vector_sort centralized_gather_sort " @@ -105,6 +166,10 @@ int hpx_main(hpx::program_options::variables_map& vm) } /// Configure and launch the distributed performance benchmark. +/// +/// \param argc The number of command-line arguments. +/// \param argv The command-line argument array. +/// \return The HPX runtime exit code. int main(int argc, char* argv[]) { hpx::program_options::options_description cmdline( From 003b7cc783de58ac5405a8cdc3615f9ea6c17fd9 Mon Sep 17 00:00:00 2001 From: the-ivii Date: Tue, 10 Nov 2026 06:16:36 +0530 Subject: [PATCH 05/10] Document segmented sort merge helpers Signed-off-by: the-ivii --- .../parallel/segmented_algorithms/sort.hpp | 53 +++++++++++++++++++ .../tests/unit/partitioned_vector_sort.cpp | 8 +++ 2 files changed, 61 insertions(+) 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 9860c6a0bd5d..120d6cc91800 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 @@ -695,6 +695,16 @@ namespace hpx::parallel::detail { /// Find the stable merge partition that leaves left.size() values in /// the left run. The two returned offsets delimit equally sized /// crossing ranges: left[i, end) and right[begin, j). + /// + /// \tparam ExPolicy The execution policy type. + /// \tparam Comp The comparison function type. + /// \tparam Proj The projection function type. + /// \param policy The execution policy instance. + /// \param left The sorted left run. + /// \param right The sorted right run. + /// \param comp The comparison function. + /// \param proj The projection function. + /// \return The left and right offsets delimiting the crossing ranges. template static std::pair merge_partition( ExPolicy const& policy, segmented_sort_run const& left, @@ -735,6 +745,14 @@ namespace hpx::parallel::detail { /// Exchange the crossing suffix and prefix in bounded chunks. At most /// two transfer chunks are materialized on the coordinator at once. + /// + /// \tparam ExPolicy The execution policy type. + /// \param policy The execution policy instance. + /// \param left The run containing the suffix to exchange. + /// \param right The run containing the prefix to exchange. + /// \param left_cut The offset of the crossing suffix in \a left. + /// \param crossing_size The number of values exchanged in each + /// direction. template static void exchange_crossing_ranges(ExPolicy const& policy, segmented_sort_run const& left, @@ -774,6 +792,19 @@ namespace hpx::parallel::detail { /// Merge the two exchanged runs independently on their owning /// localities. Parallel policies overlap the two local merges. + /// + /// \tparam ExPolicy The execution policy type. + /// \tparam Comp The comparison function type. + /// \tparam Proj The projection function type. + /// \tparam IsSeq A compile-time flag selecting sequenced dispatch. + /// \param policy The execution policy instance. + /// \param left The left run after exchanging its crossing suffix. + /// \param right The right run after exchanging its crossing prefix. + /// \param left_cut The merge boundary in \a left. + /// \param right_cut The merge boundary in \a right. + /// \param comp The comparison function. + /// \param proj The projection function. + /// \param is_seq The sequenced-dispatch flag. template static void merge_exchanged_runs(ExPolicy const& policy, @@ -839,6 +870,17 @@ namespace hpx::parallel::detail { } /// Perform a bounded merge-split of two adjacent sorted runs. + /// + /// \tparam ExPolicy The execution policy used for transfers and local + /// merges. + /// \tparam Comp The comparison function type. + /// \tparam Proj The projection function type. + /// \param policy The execution policy instance. + /// \param left The sorted run that retains the lower values. + /// \param right The sorted run that retains the higher values. + /// \param comp The comparison function. + /// \param proj The projection function. + /// \return True if values crossed the run boundary; otherwise false. template static bool execute(ExPolicy const& policy, segmented_sort_run const& left, @@ -890,6 +932,17 @@ namespace hpx::parallel::detail { /// phases continue until both parities report no changes. Parallel policies /// overlap the disjoint pairs in each phase, although values can move in /// multiple phases. + /// + /// \tparam ExPolicy The execution policy type. + /// \tparam LocalIter The local iterator type of each run. + /// \tparam Comp The comparison function type. + /// \tparam Proj The projection function type. + /// \tparam IsSeq A compile-time flag selecting sequenced dispatch. + /// \param policy The execution policy instance. + /// \param runs The sorted distributed runs to merge globally. + /// \param comp The comparison function. + /// \param proj The projection function. + /// \param is_seq The sequenced-dispatch flag. template void segmented_sort_merge_runs(ExPolicy const& policy, 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 0fb29aded405..0768c163b29d 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -342,6 +342,10 @@ void test_sort_subranges( } /// Verify compare-split phases with uneven runs and duplicate values. +/// +/// \tparam ExPolicy The execution policy type. +/// \param policy The policy used to invoke segmented sort. +/// \param localities The localities that own the test partitions. template void test_uneven_merge_split( ExPolicy const& policy, std::vector const& localities) @@ -366,6 +370,8 @@ void test_uneven_merge_split( } /// Verify that a complete two-run exchange remains chunked and distributed. +/// +/// \param localities The localities that own the two test partitions. void test_two_run_merge_split(std::vector const& localities) { // Put two reversed runs on different localities. Every value crosses the @@ -390,6 +396,8 @@ void test_two_run_merge_split(std::vector const& localities) } /// Verify convergence when adjacent runs have strongly unequal capacities. +/// +/// \param localities The localities used by the explicit partition layout. void test_unequal_explicit_layout(std::vector const& localities) { std::vector const sizes{100, 1, 100}; From e9946cdd8f22233f2b4017bec38de18d3e1a82ee Mon Sep 17 00:00:00 2001 From: the-ivii Date: Sat, 14 Nov 2026 15:14:46 +0530 Subject: [PATCH 06/10] Refine distributed segmented sort merging Signed-off-by: the-ivii --- .../parallel/segmented_algorithms/sort.hpp | 441 +++++++++++++----- .../tests/performance/CMakeLists.txt | 35 +- .../partitioned_vector_sort_performance.cpp | 279 +++++++---- .../tests/unit/partitioned_vector_sort.cpp | 20 + 4 files changed, 560 insertions(+), 215 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 120d6cc91800..cb3020ed5b74 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 @@ -74,45 +74,6 @@ namespace hpx::parallel::detail { } }; - /// Merge two adjacent sorted ranges stored in one physical partition. - template - struct segmented_local_merge : algorithm, Iter> - { - constexpr segmented_local_merge() noexcept - : algorithm("segmented_local_merge") - { - } - - /// Merge two local ranges using the supplied policy and projection. - template - static InIter sequential(ExPolicy&& policy, InIter first, InIter middle, - InIter last, Comp&& comp, Proj&& proj) - { - using local_traits = - hpx::traits::segmented_local_iterator_traits; - using predicate_type = - util::compare_projected, std::decay_t>; - predicate_type pred( - HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); - hpx::inplace_merge(hpx::execution::experimental::to_non_task( - HPX_FORWARD(ExPolicy, policy)), - local_traits::local(first), local_traits::local(middle), - local_traits::local(last), pred); - return last; - } - - /// Parallel entry point for merging two local ranges. - template - static InIter parallel(ExPolicy&& policy, InIter first, InIter middle, - InIter last, Comp&& comp, Proj&& proj) - { - return sequential(HPX_FORWARD(ExPolicy, policy), first, middle, - last, HPX_FORWARD(Comp, comp), HPX_FORWARD(Proj, proj)); - } - }; - // Bound outstanding transport and namespace requests independently of // the number of partitions. inline constexpr std::size_t segmented_sort_transfer_limit = 8; @@ -253,6 +214,60 @@ namespace hpx::parallel::detail { template using segmented_sort_block = std::vector>; + template + using segmented_sort_blocks = std::vector>; + + /// Group consecutive physical runs owned by the same locality. + /// + /// Only adjacent runs are combined. Nonadjacent runs on the same locality + /// remain separate logical blocks so that their global ordering is + /// preserved. + /// + /// \tparam LocalIter The local iterator type of each physical run. + /// \param runs The physical runs in global iteration order. + /// \return The logical blocks in the same global order as \a runs. + template + segmented_sort_blocks segmented_sort_locality_blocks( + segmented_sort_block const& runs) + { + segmented_sort_blocks blocks; + for (auto const& run : runs) + { + if (blocks.empty() || blocks.back().back().locality != run.locality) + { + blocks.push_back({run}); + } + else + { + blocks.back().push_back(run); + } + } + return blocks; + } + + /// Return cumulative physical-run endpoints for a logical block. + /// + /// The returned offsets are relative to the start of \a block and the last + /// offset equals the total number of elements in the block. + /// + /// \tparam LocalIter The local iterator type of each physical run. + /// \param block The logical block whose run endpoints are requested. + /// \return The cumulative endpoint of every physical run in \a block. + template + std::vector segmented_sort_run_ends( + segmented_sort_block const& block) + { + std::vector run_ends; + run_ends.reserve(block.size()); + std::size_t end = 0; + for (auto const& run : block) + { + end += static_cast(run.size()); + run_ends.push_back(end); + } + return run_ends; + } + template std::size_t segmented_sort_block_size( segmented_sort_block const& block) @@ -560,6 +575,83 @@ namespace hpx::parallel::detail { return first; } + /// Merge presorted physical runs that form one locality-owned block. + /// + /// The block is materialized only on its owning locality, merged at the + /// supplied cumulative boundaries, and stored back to the same physical + /// runs. + /// + /// \tparam LocalIter The local iterator type of each physical run. + template + struct segmented_sort_merge_local_block_on_host + : algorithm, bool> + { + constexpr segmented_sort_merge_local_block_on_host() noexcept + : algorithm( + "segmented_sort_merge_local_block_on_host") + { + } + + /// Merge consecutive presorted physical runs on their owning locality. + /// + /// \tparam ExPolicy The execution policy type. + /// \tparam Comp The comparison function type. + /// \tparam Proj The projection function type. + /// \param policy The execution policy instance. + /// \param block The physical runs owned by this locality. + /// \param run_ends The cumulative endpoint of each presorted run. + /// \param comp The comparison function. + /// \param proj The projection function. + /// \return True if two or more runs were merged; otherwise false. + template + static bool sequential(ExPolicy const& policy, + segmented_sort_block const& block, + std::vector const& run_ends, Comp comp, Proj proj) + { + if (run_ends.size() <= 1) + { + return false; + } + + auto values = + segmented_fetch_values::sequential(policy, block); + util::compare_projected pred(comp, proj); + std::size_t merged_size = run_ends.front(); + for (std::size_t i = 1; i != run_ends.size(); ++i) + { + auto const next_size = run_ends[i]; + hpx::inplace_merge(policy, values.begin(), + values.begin() + static_cast(merged_size), + values.begin() + static_cast(next_size), + pred); + merged_size = next_size; + } + segmented_store_values::sequential( + policy, block, HPX_MOVE(values)); + return true; + } + + /// Parallel entry point for merging one locality block. + /// + /// \tparam ExPolicy The execution policy type. + /// \tparam Comp The comparison function type. + /// \tparam Proj The projection function type. + /// \param policy The execution policy instance. + /// \param block The physical runs owned by this locality. + /// \param run_ends The cumulative endpoint of each presorted run. + /// \param comp The comparison function. + /// \param proj The projection function. + /// \return True if two or more runs were merged; otherwise false. + template + static bool parallel(ExPolicy const& policy, + segmented_sort_block const& block, + std::vector const& run_ends, Comp comp, Proj proj) + { + return sequential( + policy, block, run_ends, HPX_MOVE(comp), HPX_MOVE(proj)); + } + }; + template struct segmented_sort_local_runs_on_host : algorithm, bool> @@ -656,6 +748,85 @@ namespace hpx::parallel::detail { } } + /// Merge consecutive physical runs before starting remote compare-splits. + /// + /// Each block is dispatched to its owning locality. A parallel policy + /// overlaps independent blocks, while a sequenced policy processes them in + /// global order. + /// + /// \tparam ExPolicy The execution policy type. + /// \tparam LocalIter The local iterator type of each physical run. + /// \tparam Comp The comparison function type. + /// \tparam Proj The projection function type. + /// \tparam IsSeq A compile-time flag selecting sequenced dispatch. + /// \param policy The execution policy instance. + /// \param runs The presorted physical runs in global order. + /// \param comp The comparison function. + /// \param proj The projection function. + /// \param is_seq The sequenced-dispatch flag. + /// \return The merged logical blocks in global order. + template + segmented_sort_blocks segmented_sort_merge_locality_runs( + ExPolicy const& policy, segmented_sort_block const& runs, + Comp const& comp, Proj const& proj, IsSeq is_seq) + { + using operation = segmented_sort_merge_local_block_on_host; + auto blocks = segmented_sort_locality_blocks(runs); + auto const here = hpx::find_here(); + if constexpr (IsSeq::value) + { + for (auto const& block : blocks) + { + auto const host = block.front().locality; + auto const run_ends = segmented_sort_run_ends(block); + if (host == here) + { + operation::sequential(policy, block, run_ends, comp, proj); + } + else + { + dispatch(host, operation(), policy, is_seq, block, run_ends, + comp, proj); + } + } + } + else + { + std::vector> pending; + pending.reserve(blocks.size()); + std::exception_ptr error; + try + { + for (auto const& block : blocks) + { + auto const host = block.front().locality; + auto run_ends = segmented_sort_run_ends(block); + if (host == here) + { + pending.push_back(hpx::async( + [policy, block, run_ends = HPX_MOVE(run_ends), comp, + proj]() mutable { + return operation::parallel(policy, block, + run_ends, HPX_MOVE(comp), HPX_MOVE(proj)); + })); + } + else + { + pending.push_back(dispatch_async(host, operation(), + policy, is_seq, block, run_ends, comp, proj)); + } + } + } + catch (...) + { + error = std::current_exception(); + } + segmented_sort_wait(pending, error); + } + return blocks; + } + template struct segmented_sort_compare_split_on_host : algorithm, bool> @@ -666,34 +837,62 @@ namespace hpx::parallel::detail { { } - /// Return a subrange of a physical sorted run. - static segmented_sort_run subrun( - segmented_sort_run const& run, std::size_t offset, + /// Return a logical subrange spanning zero or more physical runs. + /// + /// \param block The logical block to slice. + /// \param offset The number of values skipped from the block start. + /// \param count The number of values in the requested slice. + /// \return Physical run fragments covering exactly \a count values. + static segmented_sort_block subrun( + segmented_sort_block const& block, std::size_t offset, std::size_t count) { - auto const first = run.first + static_cast(offset); - return {run.id, run.locality, first, - first + static_cast(count)}; + segmented_sort_block result; + for (auto const& run : block) + { + auto const run_size = static_cast(run.size()); + if (offset >= run_size) + { + offset -= run_size; + continue; + } + + auto const run_count = (std::min) (count, run_size - offset); + auto const first = + run.first + static_cast(offset); + result.push_back({run.id, run.locality, first, + first + static_cast(run_count)}); + count -= run_count; + offset = 0; + if (count == 0) + { + break; + } + } + HPX_ASSERT(count == 0); + return result; } /// Compare projected values at two positions without gathering either /// complete run on the coordinating locality. template static bool less_at(ExPolicy const& policy, - segmented_sort_run const& lhs, std::size_t lhs_offset, - segmented_sort_run const& rhs, std::size_t rhs_offset, + segmented_sort_block const& lhs, std::size_t lhs_offset, + segmented_sort_block const& rhs, std::size_t rhs_offset, Comp& comp, Proj& proj) { - segmented_sort_block const values_to_fetch{ - subrun(lhs, lhs_offset, 1), subrun(rhs, rhs_offset, 1)}; + auto values_to_fetch = subrun(lhs, lhs_offset, 1); + auto rhs_value = subrun(rhs, rhs_offset, 1); + values_to_fetch.insert( + values_to_fetch.end(), rhs_value.begin(), rhs_value.end()); auto values = segmented_sort_fetch_block(policy, values_to_fetch); HPX_ASSERT(values.size() == 2); util::compare_projected pred(comp, proj); return pred(values[0], values[1]); } - /// Find the stable merge partition that leaves left.size() values in - /// the left run. The two returned offsets delimit equally sized + /// Find a merge partition that leaves left.size() values in the left + /// block. The two returned offsets delimit equally sized /// crossing ranges: left[i, end) and right[begin, j). /// /// \tparam ExPolicy The execution policy type. @@ -707,11 +906,12 @@ namespace hpx::parallel::detail { /// \return The left and right offsets delimiting the crossing ranges. template static std::pair merge_partition( - ExPolicy const& policy, segmented_sort_run const& left, - segmented_sort_run const& right, Comp& comp, Proj& proj) + ExPolicy const& policy, segmented_sort_block const& left, + segmented_sort_block const& right, Comp& comp, + Proj& proj) { - auto const left_size = static_cast(left.size()); - auto const right_size = static_cast(right.size()); + auto const left_size = segmented_sort_block_size(left); + auto const right_size = segmented_sort_block_size(right); std::size_t low = left_size > right_size ? left_size - right_size : 0; std::size_t high = left_size; @@ -755,8 +955,8 @@ namespace hpx::parallel::detail { /// direction. template static void exchange_crossing_ranges(ExPolicy const& policy, - segmented_sort_run const& left, - segmented_sort_run const& right, std::size_t left_cut, + segmented_sort_block const& left, + segmented_sort_block const& right, std::size_t left_cut, std::size_t crossing_size) { for (std::size_t offset = 0; offset != crossing_size;) @@ -766,26 +966,21 @@ namespace hpx::parallel::detail { crossing_size - offset); auto const left_chunk = subrun(left, left_cut + offset, count); auto const right_chunk = subrun(right, offset, count); - segmented_sort_block const chunks{ - left_chunk, right_chunk}; - auto values = segmented_sort_fetch_block(policy, chunks); - HPX_ASSERT(values.size() == 2 * count); - - segmented_sort_block const left_destination{ - left_chunk}; - segmented_sort_block const right_destination{ - right_chunk}; - auto const middle = values.begin() + - static_cast( - count); + auto left_values = + segmented_sort_fetch_block(policy, left_chunk); + auto right_values = + segmented_sort_fetch_block(policy, right_chunk); + HPX_ASSERT(left_values.size() == count); + HPX_ASSERT(right_values.size() == count); + [[maybe_unused]] auto const left_last = segmented_sort_store_block( - policy, left_destination, middle); + policy, left_chunk, right_values.begin()); [[maybe_unused]] auto const right_last = segmented_sort_store_block( - policy, right_destination, values.begin()); - HPX_ASSERT(left_last == values.end()); - HPX_ASSERT(right_last == middle); + policy, right_chunk, left_values.begin()); + HPX_ASSERT(left_last == right_values.end()); + HPX_ASSERT(right_last == left_values.end()); offset += count; } } @@ -808,52 +1003,53 @@ namespace hpx::parallel::detail { template static void merge_exchanged_runs(ExPolicy const& policy, - segmented_sort_run const& left, - segmented_sort_run const& right, std::size_t left_cut, + segmented_sort_block const& left, + segmented_sort_block const& right, std::size_t left_cut, std::size_t right_cut, Comp const& comp, Proj const& proj, IsSeq is_seq) { - using operation = segmented_local_merge; + using operation = + segmented_sort_merge_local_block_on_host; auto const here = hpx::find_here(); - std::vector> pending; + std::vector> pending; std::exception_ptr error; - auto merge_run = [&](segmented_sort_run const& run, + auto merge_run = [&](segmented_sort_block const& run, std::size_t middle_offset) { if (middle_offset == 0 || - middle_offset == static_cast(run.size())) + middle_offset == segmented_sort_block_size(run)) { return; } - auto const middle = - run.first + static_cast(middle_offset); + auto const host = run.front().locality; + std::vector run_ends{ + middle_offset, segmented_sort_block_size(run)}; if constexpr (IsSeq::value) { - if (run.locality == here) + if (host == here) { operation::sequential( - policy, run.first, middle, run.last, comp, proj); + policy, run, run_ends, comp, proj); } else { - dispatch(run.locality, operation(), policy, is_seq, - run.first, middle, run.last, comp, proj); + dispatch(host, operation(), policy, is_seq, run, + run_ends, comp, proj); } } - else if (run.locality == here) + else if (host == here) { pending.push_back( - hpx::async([policy, first = run.first, middle, - last = run.last, comp, proj]() mutable { - return operation::parallel(policy, first, middle, - last, HPX_MOVE(comp), HPX_MOVE(proj)); + hpx::async([policy, run, run_ends = HPX_MOVE(run_ends), + comp, proj]() mutable { + return operation::parallel(policy, run, run_ends, + HPX_MOVE(comp), HPX_MOVE(proj)); })); } else { - pending.push_back( - dispatch_async(run.locality, operation(), policy, - is_seq, run.first, middle, run.last, comp, proj)); + pending.push_back(dispatch_async(host, operation(), policy, + is_seq, run, run_ends, comp, proj)); } }; @@ -883,10 +1079,10 @@ namespace hpx::parallel::detail { /// \return True if values crossed the run boundary; otherwise false. template static bool execute(ExPolicy const& policy, - segmented_sort_run const& left, - segmented_sort_run const& right, Comp comp, Proj proj) + segmented_sort_block const& left, + segmented_sort_block const& right, Comp comp, Proj proj) { - auto const left_size = static_cast(left.size()); + auto const left_size = segmented_sort_block_size(left); if (!less_at(policy, right, 0, left, left_size - 1, comp, proj)) { return false; @@ -908,8 +1104,8 @@ namespace hpx::parallel::detail { /// Sequenced dispatch entry point for a compare-split. template static bool sequential(ExPolicy const& policy, - segmented_sort_run const& left, - segmented_sort_run const& right, Comp comp, Proj proj) + 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)); } @@ -917,8 +1113,8 @@ namespace hpx::parallel::detail { /// Parallel dispatch entry point for a compare-split. template static bool parallel(ExPolicy const& policy, - segmented_sort_run const& left, - segmented_sort_run const& right, Comp comp, Proj proj) + segmented_sort_block const& left, + segmented_sort_block const& right, Comp comp, Proj proj) { // Disjoint pairs are overlapped by segmented_sort_merge_runs; the // policy is also used by the local merge and stores. @@ -929,9 +1125,10 @@ namespace hpx::parallel::detail { /// Run odd-even compare-split phases while keeping data distributed. Each /// operation exchanges only the crossing suffix and prefix using bounded /// buffers, then merges both runs on their owning localities. Alternating - /// phases continue until both parities report no changes. Parallel policies - /// overlap the disjoint pairs in each phase, although values can move in - /// multiple phases. + /// phases continue until both parities report no changes. With unequal run + /// capacities, the required number of phases is not bounded by the number + /// of runs. Parallel policies overlap the disjoint pairs in each phase, + /// although values can move in multiple phases. /// /// \tparam ExPolicy The execution policy type. /// \tparam LocalIter The local iterator type of each run. @@ -946,7 +1143,7 @@ namespace hpx::parallel::detail { template void segmented_sort_merge_runs(ExPolicy const& policy, - segmented_sort_block const& runs, Comp const& comp, + segmented_sort_blocks const& runs, Comp const& comp, Proj const& proj, IsSeq is_seq) { if (runs.size() <= 1) @@ -968,9 +1165,7 @@ namespace hpx::parallel::detail { { for (std::size_t i = phase % 2; i + 1 < runs.size(); i += 2) { - segmented_sort_block const left{runs[i]}; - segmented_sort_block const right{runs[i + 1]}; - auto const host = segmented_sort_host(left, right); + auto const host = segmented_sort_host(runs[i], runs[i + 1]); if constexpr (IsSeq::value) { if (host == here) @@ -1027,7 +1222,9 @@ namespace hpx::parallel::detail { 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); + auto locality_runs = segmented_sort_merge_locality_runs( + policy, runs, comp, proj, is_seq); + segmented_sort_merge_runs(policy, locality_runs, comp, proj, is_seq); } template requires(hpx::traits::is_iterator_v && @@ -1118,13 +1318,16 @@ namespace hpx::segmented { /// serializable by HPX. /// /// The policy controls local partition sorting and whether independent - /// compare-splits overlap. The final merge uses alternating odd-even phases + /// compare-splits overlap. Consecutive partitions on one locality are + /// merged locally first. The final merge uses alternating odd-even phases /// until both parities are unchanged. Each operation finds the merge /// partition, exchanges only the crossing suffix and prefix in bounded - /// chunks, and merges both runs on their owning localities. No locality - /// gathers the full input, although a value can be transferred in multiple - /// phases. An exception after a compare-split stores data can leave a - /// partially reordered range. + /// chunks, and merges both runs on their owning localities. No coordinator + /// gathers the full distributed input, although a value can be transferred + /// in multiple phases. With unequal run capacities, the number of phases is + /// not bounded by the number of runs. If an exception occurs after a + /// compare-split starts storing data, the contents of the range are + /// unspecified and may contain lost or duplicated values. HPX_CXX_EXPORT template requires(hpx::is_execution_policy_v && diff --git a/libs/full/segmented_algorithms/tests/performance/CMakeLists.txt b/libs/full/segmented_algorithms/tests/performance/CMakeLists.txt index 84cac16c7946..f0e78a2631f6 100644 --- a/libs/full/segmented_algorithms/tests/performance/CMakeLists.txt +++ b/libs/full/segmented_algorithms/tests/performance/CMakeLists.txt @@ -6,10 +6,6 @@ set(benchmarks minmax_element_performance partitioned_vector_sort_performance) -set(partitioned_vector_sort_performance_PARAMETERS LOCALITIES 2 - THREADS_PER_LOCALITY 2 -) - foreach(benchmark ${benchmarks}) set(sources ${benchmark}.cpp) @@ -25,7 +21,32 @@ foreach(benchmark ${benchmarks}) FOLDER "Benchmarks/Modules/Full/SegmentedAlgorithms" ) - add_hpx_performance_test( - "modules.segmented_algorithms" ${benchmark} ${${benchmark}_PARAMETERS} - ) + if(benchmark STREQUAL "partitioned_vector_sort_performance") + add_hpx_performance_test( + "modules.segmented_algorithms" + partitioned_vector_sort_performance_2_localities + EXECUTABLE + partitioned_vector_sort_performance + PSEUDO_DEPS_NAME + partitioned_vector_sort_performance + LOCALITIES + 2 + THREADS_PER_LOCALITY + 2 + ) + add_hpx_performance_test( + "modules.segmented_algorithms" + partitioned_vector_sort_performance_4_localities + EXECUTABLE + partitioned_vector_sort_performance + PSEUDO_DEPS_NAME + partitioned_vector_sort_performance + LOCALITIES + 4 + THREADS_PER_LOCALITY + 2 + ) + else() + add_hpx_performance_test("modules.segmented_algorithms" ${benchmark}) + endif() endforeach() diff --git a/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp b/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp index 4cf1ac5c1c4c..5acd71a4bf99 100644 --- a/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp +++ b/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp @@ -13,20 +13,29 @@ #include #include #include +#include #include -#include #include #include -#include +#include #include +#include #include #include +#include +#include #include namespace { using vector_type = hpx::partitioned_vector; + enum class input_kind + { + random, + reversed + }; + /// Restore the distributed input before a timed benchmark iteration. /// /// \param values The distributed vector to restore. @@ -39,66 +48,176 @@ namespace { values.set_values(hpx::launch::sync, positions, input); } - struct benchmark_sample + /// Construct deterministic random or reversed benchmark input. + /// + /// \param size The number of values to generate. + /// \param kind The requested input distribution. + /// \param seed The random seed used for random input. + /// \return The generated input values. + std::vector make_input( + std::size_t size, input_kind kind, std::uint32_t seed) { - double distributed = 0.0; - double centralized = 0.0; - bool distributed_first = true; - }; + std::vector input(size); + if (kind == input_kind::reversed) + { + std::iota(input.rbegin(), input.rend(), 0); + } + else + { + std::mt19937 generator(seed); + std::uniform_int_distribution distribution; + std::generate(input.begin(), input.end(), + [&]() { return distribution(generator); }); + } + return input; + } - /// Measure both operations in alternating order with untimed input resets. + /// Perform the centralized k-way merge used by the first segmented sort + /// implementation after its physical partitions have been sorted. /// - /// \tparam Reset A nullary callable that restores the benchmark input. - /// \tparam Distributed A nullary callable running the distributed sort. - /// \tparam Centralized A nullary callable running the centralized sort. - /// \param test_count The number of timed samples for each operation. - /// \param distributed_first Whether the first sample runs the distributed - /// operation first. Subsequent samples alternate the order. - /// \param reset The input restoration callable. - /// \param distributed The distributed operation to measure. - /// \param centralized The centralized operation to measure. - /// \return The raw timings and execution order for every sample. - template - std::vector measure(std::size_t test_count, - bool distributed_first, Reset&& reset, Distributed&& distributed, - Centralized&& centralized) + /// \tparam LocalIter The local iterator type of each physical run. + /// \param runs The sorted physical runs to gather, merge, and redistribute. + template + void centralized_kway_merge( + hpx::parallel::detail::segmented_sort_block const& runs) { - using clock = std::chrono::steady_clock; - - reset(); - distributed(); - reset(); - centralized(); - - std::vector samples; - samples.reserve(test_count); - auto measure_one = [&](auto&& operation) { - reset(); - auto const start = clock::now(); - operation(); - return std::chrono::duration(clock::now() - start).count(); + using value_type = typename std::iterator_traits::value_type; + auto values = hpx::parallel::detail::segmented_sort_fetch_block( + hpx::execution::par, runs); + std::vector offsets; + std::vector counts; + offsets.reserve(runs.size()); + counts.reserve(runs.size()); + std::size_t offset = 0; + for (auto const& run : runs) + { + offsets.push_back(offset); + auto const count = static_cast(run.size()); + counts.push_back(count); + offset += count; + } + + struct cursor + { + std::size_t position; + std::size_t end; }; - for (std::size_t i = 0; i != test_count; ++i) + + auto const compare = [&](cursor const& lhs, cursor const& rhs) { + return values[rhs.position] < values[lhs.position]; + }; + std::priority_queue, decltype(compare)> + heap(compare); + for (std::size_t i = 0; i != counts.size(); ++i) { - benchmark_sample sample; - sample.distributed_first = distributed_first == (i % 2 == 0); - if (sample.distributed_first) + if (counts[i] != 0) { - sample.distributed = measure_one(distributed); - sample.centralized = measure_one(centralized); + heap.push({offsets[i], offsets[i] + counts[i]}); } - else + } + + std::size_t destination = 0; + std::vector output; + output.reserve(counts.front()); + while (!heap.empty()) + { + auto current = heap.top(); + heap.pop(); + output.push_back(HPX_MOVE(values[current.position])); + if (++current.position != current.end) { - sample.centralized = measure_one(centralized); - sample.distributed = measure_one(distributed); + heap.push(current); } - samples.push_back(sample); + if (output.size() == counts[destination]) + { + hpx::parallel::detail::segmented_sort_block block{ + runs[destination]}; + [[maybe_unused]] auto const last = + hpx::parallel::detail::segmented_sort_store_block( + hpx::execution::par, block, output.begin()); + HPX_ASSERT(last == output.end()); + output.clear(); + if (++destination != runs.size()) + { + output.reserve(counts[destination]); + } + } + } + HPX_ASSERT(destination == runs.size()); + } + + /// Run the centralized k-way segmented sort retained as a benchmark. + /// + /// \param values The distributed vector to sort. + void centralized_kway_sort(vector_type& values) + { + auto runs = hpx::parallel::detail::segmented_sort_runs( + values.begin(), values.end()); + if (runs.empty()) + { + return; } - return samples; + hpx::parallel::detail::segmented_sort_local_runs(hpx::execution::par, + runs, std::less{}, hpx::identity_v, std::false_type{}); + centralized_kway_merge(runs); + } + + /// Gather, sort, and scatter the full input on the benchmark driver. + /// + /// \param values The distributed vector to sort. + /// \param positions The global positions to gather and update. + void gather_sort_scatter( + vector_type& values, std::vector const& positions) + { + auto gathered = values.get_values(hpx::launch::sync, positions); + std::sort(gathered.begin(), gathered.end()); + values.set_values(hpx::launch::sync, positions, gathered); + } + + /// Report all three sorting approaches for one benchmark configuration. + /// + /// \param size The total number of values. + /// \param test_count The number of timed iterations. + /// \param partitions_per_locality The partition density. + /// \param kind The input distribution. + /// \param seed The deterministic random seed. + /// \param localities The participating localities. + void run_configuration(std::size_t size, std::size_t test_count, + std::size_t partitions_per_locality, input_kind kind, + std::uint32_t seed, std::vector const& localities) + { + auto const partitions = partitions_per_locality * localities.size(); + vector_type values( + size, 0, hpx::container_layout(partitions, localities)); + std::vector positions(size); + std::iota(positions.begin(), positions.end(), std::size_t(0)); + auto const input = make_input(size, kind, seed); + auto const reset = [&]() { set_input(values, positions, input); }; + auto const distribution = + kind == input_kind::random ? "random" : "reversed"; + auto const context = std::string(distribution) + + "/localities=" + std::to_string(localities.size()) + + "/partitions_per_locality=" + + std::to_string(partitions_per_locality) + + "/partitions=" + std::to_string(partitions); + + hpx::util::perftests_report( + "partitioned_vector_sort", "distributed/" + context, test_count, 0, + [&]() { + hpx::sort(hpx::execution::par, values.begin(), values.end()); + }, + reset); + hpx::util::perftests_report( + "partitioned_vector_sort", "centralized_kway/" + context, + test_count, 0, [&]() { centralized_kway_sort(values); }, reset); + hpx::util::perftests_report( + "partitioned_vector_sort", "gather_sort_scatter/" + context, + test_count, 0, [&]() { gather_sort_scatter(values, positions); }, + reset); } } // namespace -/// Compare distributed sorting with a centralized gather-sort-scatter. +/// Compare distributed sorting with both centralized implementations. /// /// \param vm The parsed benchmark command-line options. /// \return Zero after initiating HPX shutdown, or immediately on localities @@ -112,56 +231,35 @@ int hpx_main(hpx::program_options::variables_map& vm) auto const size = vm["vector_size"].as(); auto const test_count = vm["test_count"].as(); - auto partitions = vm["partitions"].as(); + auto const requested_partitions_per_locality = + vm["partitions_per_locality"].as(); auto const seed = vm["seed"].as(); auto const localities = hpx::find_all_localities(); - if (partitions == 0) - { - partitions = localities.size(); - } - - vector_type values(size, 0, hpx::container_layout(partitions, localities)); - std::vector positions(size); - std::iota(positions.begin(), positions.end(), std::size_t(0)); - std::vector input(size); - std::mt19937 generator(seed); - std::uniform_int_distribution distribution; - std::generate( - input.begin(), input.end(), [&]() { return distribution(generator); }); if (test_count == 0) { return hpx::finalize(); } - auto const reset = [&]() { set_input(values, positions, input); }; - auto const samples = measure( - test_count, (seed % 2) == 0, reset, - [&]() { hpx::sort(hpx::execution::par, values.begin(), values.end()); }, - [&]() { - auto gathered = values.get_values(hpx::launch::sync, positions); - std::sort(gathered.begin(), gathered.end()); - values.set_values(hpx::launch::sync, positions, gathered); - }); - - double distributed = 0.0; - double centralized = 0.0; - for (std::size_t i = 0; i != samples.size(); ++i) + hpx::util::perftests_init(vm, "partitioned_vector_sort_performance"); + std::vector partitions_per_locality; + if (requested_partitions_per_locality != 0) { - auto const& sample = samples[i]; - distributed += sample.distributed; - centralized += sample.centralized; - std::cout << "partitioned_vector_sort sample " << i << " first " - << (sample.distributed_first ? "distributed" : "centralized") - << " distributed " << sample.distributed << " s centralized " - << sample.centralized << " s\n"; + partitions_per_locality.push_back(requested_partitions_per_locality); + } + else + { + partitions_per_locality = {8, 16, 32, 64}; } - distributed /= static_cast(samples.size()); - centralized /= static_cast(samples.size()); - std::cout << "partitioned_vector_sort distributed " << distributed - << " s\npartitioned_vector_sort centralized_gather_sort " - << centralized << " s\n"; + for (auto const partitions : partitions_per_locality) + { + run_configuration( + size, test_count, partitions, input_kind::random, seed, localities); + run_configuration(size, test_count, partitions, input_kind::reversed, + seed, localities); + } + hpx::util::perftests_print_times(); return hpx::finalize(); } @@ -176,14 +274,17 @@ int main(int argc, char* argv[]) "usage: " HPX_APPLICATION_STRING " [options]"); cmdline.add_options()("vector_size", hpx::program_options::value()->default_value(1000000), - "number of values")("partitions", + "number of values")("partitions_per_locality", hpx::program_options::value()->default_value(0), - "number of partitions (zero uses one per locality)")("test_count", + "partitions per locality (zero benchmarks 8, 16, 32, and 64)")( + "test_count", hpx::program_options::value()->default_value(5), "number of timed iterations")("seed", hpx::program_options::value()->default_value(0), "random-number seed"); + hpx::util::perftests_cfg(cmdline); + hpx::init_params init_args; init_args.desc_cmdline = cmdline; init_args.cfg = {"hpx.os_threads=all", "hpx.run_hpx_main!=1"}; 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 0768c163b29d..fe552e0c1e8d 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -413,6 +413,25 @@ void test_unequal_explicit_layout(std::vector const& localities) verify_sorted(values, expected); } +/// Verify that consecutive partitions on one locality are merged locally. +/// +/// \param localities The localities used by the explicit partition layout. +void test_adjacent_local_partitions(std::vector const& localities) +{ + std::vector const sizes{17, 19, 13, 23}; + auto const second = localities[localities.size() > 1 ? 1 : 0]; + std::vector const owners{ + localities[0], localities[0], second, second}; + hpx::partitioned_vector values( + 72, 0, hpx::explicit_container_layout(sizes, owners)); + initialize_values( + values, [](std::size_t i) { return static_cast(71 - i); }); + auto const expected = copy_values(values); + + hpx::sort(hpx::execution::par, values.begin(), values.end()); + verify_sorted(values, expected); +} + void test_large_transfers(std::vector const& localities) { // Large enough to exercise multiple bounded transfers through the public @@ -611,6 +630,7 @@ int main() hpx::execution::par(hpx::execution::task), localities); test_two_run_merge_split(localities); test_unequal_explicit_layout(localities); + test_adjacent_local_partitions(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)); From 8f18d71009771014c47f5edd55386813800eac06 Mon Sep 17 00:00:00 2001 From: Divyanshi Talreja Date: Sun, 15 Nov 2026 20:48:34 +0530 Subject: [PATCH 07/10] Fix segmented sort test compilation in module CI Signed-off-by: Divyanshi Talreja --- .../tests/performance/partitioned_vector_sort_performance.cpp | 3 ++- .../tests/unit/partitioned_vector_sort.cpp | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp b/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp index 5acd71a4bf99..0b1319ea6c99 100644 --- a/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp +++ b/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp @@ -1,4 +1,4 @@ -// Copyright (c) 2026 Pratyksh Gupta +// Copyright (c) 2026 Divyanshi Talreja // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying @@ -13,6 +13,7 @@ #include #include #include +#include #include #include 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 fe552e0c1e8d..d0beea0f5f68 100644 --- a/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp +++ b/libs/full/segmented_algorithms/tests/unit/partitioned_vector_sort.cpp @@ -380,7 +380,7 @@ void test_two_run_merge_split(std::vector const& localities) std::vector hosts{ localities[0], localities[localities.size() > 1 ? 1 : 0]}; hpx::partitioned_vector values( - 2 * (65536 + 7), 0, hpx::container_layout(2, hosts)); + std::size_t{2} * (65536 + 7), 0, hpx::container_layout(2, hosts)); initialize_values(values, [&](std::size_t i) { auto const run_size = values.size() / 2; if (i < run_size) From 6c336385a831c7a60d9a230eb120c52d8176c21c Mon Sep 17 00:00:00 2001 From: Divyanshi Talreja Date: Sun, 15 Nov 2026 20:48:34 +0530 Subject: [PATCH 08/10] Bound distributed sort benchmark work in CI Signed-off-by: Divyanshi Talreja --- .../segmented_algorithms/tests/performance/CMakeLists.txt | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/libs/full/segmented_algorithms/tests/performance/CMakeLists.txt b/libs/full/segmented_algorithms/tests/performance/CMakeLists.txt index f0e78a2631f6..e5d270629b6a 100644 --- a/libs/full/segmented_algorithms/tests/performance/CMakeLists.txt +++ b/libs/full/segmented_algorithms/tests/performance/CMakeLists.txt @@ -33,6 +33,10 @@ foreach(benchmark ${benchmarks}) 2 THREADS_PER_LOCALITY 2 + ARGS + --vector_size=65536 + --test_count=1 + --partitions_per_locality=8 ) add_hpx_performance_test( "modules.segmented_algorithms" @@ -45,6 +49,10 @@ foreach(benchmark ${benchmarks}) 4 THREADS_PER_LOCALITY 2 + ARGS + --vector_size=65536 + --test_count=1 + --partitions_per_locality=8 ) else() add_hpx_performance_test("modules.segmented_algorithms" ${benchmark}) From 3a8f81188bea9cfed778ab7f22f6735546a98291 Mon Sep 17 00:00:00 2001 From: Divyanshi Talreja Date: Mon, 16 Nov 2026 13:49:59 +0530 Subject: [PATCH 09/10] Use public partition APIs in segmented sort benchmark Signed-off-by: Divyanshi Talreja --- .../partitioned_vector_sort_performance.cpp | 95 +++++++++---------- 1 file changed, 47 insertions(+), 48 deletions(-) diff --git a/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp b/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp index 0b1319ea6c99..64c85889d7a2 100644 --- a/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp +++ b/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp @@ -19,12 +19,10 @@ #include #include #include -#include #include #include #include #include -#include #include #include @@ -73,30 +71,26 @@ namespace { return input; } - /// Perform the centralized k-way merge used by the first segmented sort - /// implementation after its physical partitions have been sorted. + /// Merge sorted physical partitions on the driver using public vector + /// operations. /// - /// \tparam LocalIter The local iterator type of each physical run. - /// \param runs The sorted physical runs to gather, merge, and redistribute. - template - void centralized_kway_merge( - hpx::parallel::detail::segmented_sort_block const& runs) + /// \param values The distributed vector containing sorted partitions. + /// \param positions Global positions of all values in the vector. + /// \param counts The sizes of the physical partitions. + void centralized_kway_merge(vector_type& values, + std::vector const& positions, + std::vector const& counts) { - using value_type = typename std::iterator_traits::value_type; - auto values = hpx::parallel::detail::segmented_sort_fetch_block( - hpx::execution::par, runs); + auto gathered = values.get_values(hpx::launch::sync, positions); std::vector offsets; - std::vector counts; - offsets.reserve(runs.size()); - counts.reserve(runs.size()); + offsets.reserve(counts.size()); std::size_t offset = 0; - for (auto const& run : runs) + for (auto const count : counts) { offsets.push_back(offset); - auto const count = static_cast(run.size()); - counts.push_back(count); offset += count; } + HPX_ASSERT(offset == gathered.size()); struct cursor { @@ -105,7 +99,7 @@ namespace { }; auto const compare = [&](cursor const& lhs, cursor const& rhs) { - return values[rhs.position] < values[lhs.position]; + return gathered[rhs.position] < gathered[lhs.position]; }; std::priority_queue, decltype(compare)> heap(compare); @@ -117,50 +111,48 @@ namespace { } } - std::size_t destination = 0; - std::vector output; - output.reserve(counts.front()); + std::vector output; + output.reserve(gathered.size()); while (!heap.empty()) { auto current = heap.top(); heap.pop(); - output.push_back(HPX_MOVE(values[current.position])); + output.push_back(HPX_MOVE(gathered[current.position])); if (++current.position != current.end) { heap.push(current); } - if (output.size() == counts[destination]) - { - hpx::parallel::detail::segmented_sort_block block{ - runs[destination]}; - [[maybe_unused]] auto const last = - hpx::parallel::detail::segmented_sort_store_block( - hpx::execution::par, block, output.begin()); - HPX_ASSERT(last == output.end()); - output.clear(); - if (++destination != runs.size()) - { - output.reserve(counts[destination]); - } - } } - HPX_ASSERT(destination == runs.size()); + HPX_ASSERT(output.size() == positions.size()); + values.set_values(hpx::launch::sync, positions, output); } /// Run the centralized k-way segmented sort retained as a benchmark. /// /// \param values The distributed vector to sort. - void centralized_kway_sort(vector_type& values) + /// \param positions Global positions of all values in the vector. + void centralized_kway_sort( + vector_type& values, std::vector const& positions) { - auto runs = hpx::parallel::detail::segmented_sort_runs( - values.begin(), values.end()); - if (runs.empty()) + auto const counts = values.get_partition_sizes(); + std::vector> sorts; + sorts.reserve(counts.size()); + auto first = values.begin(); + for (auto const count : counts) { - return; + auto const last = first + count; + if (count > 1) + { + sorts.push_back(hpx::sort( + hpx::execution::par(hpx::execution::task), first, last)); + } + first = last; + } + for (auto& sort : sorts) + { + sort.get(); } - hpx::parallel::detail::segmented_sort_local_runs(hpx::execution::par, - runs, std::less{}, hpx::identity_v, std::false_type{}); - centralized_kway_merge(runs); + centralized_kway_merge(values, positions, counts); } /// Gather, sort, and scatter the full input on the benchmark driver. @@ -196,7 +188,13 @@ namespace { auto const reset = [&]() { set_input(values, positions, input); }; auto const distribution = kind == input_kind::random ? "random" : "reversed"; - auto const context = std::string(distribution) + +#if defined(HPX_HAVE_NANOBENCH) + // nanobench times the input reset together with the sort. + auto const timing_mode = "/includes_reset"; +#else + auto const timing_mode = "/sort_only"; +#endif + auto const context = std::string(distribution) + timing_mode + "/localities=" + std::to_string(localities.size()) + "/partitions_per_locality=" + std::to_string(partitions_per_locality) + @@ -210,7 +208,8 @@ namespace { reset); hpx::util::perftests_report( "partitioned_vector_sort", "centralized_kway/" + context, - test_count, 0, [&]() { centralized_kway_sort(values); }, reset); + test_count, 0, [&]() { centralized_kway_sort(values, positions); }, + reset); hpx::util::perftests_report( "partitioned_vector_sort", "gather_sort_scatter/" + context, test_count, 0, [&]() { gather_sort_scatter(values, positions); }, From d51cc69b8a77a7e88aed4958e282f1a4bfabed8c Mon Sep 17 00:00:00 2001 From: Divyanshi Talreja Date: Mon, 16 Nov 2026 19:04:07 +0530 Subject: [PATCH 10/10] Cast partition size for benchmark iterator arithmetic Signed-off-by: Divyanshi Talreja --- .../tests/performance/partitioned_vector_sort_performance.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp b/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp index 64c85889d7a2..fe19024e07ad 100644 --- a/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp +++ b/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp @@ -140,7 +140,7 @@ namespace { auto first = values.begin(); for (auto const count : counts) { - auto const last = first + count; + auto const last = first + static_cast(count); if (count > 1) { sorts.push_back(hpx::sort(