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 17bf017740b..cb3020ed5b7 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 @@ -215,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) @@ -248,8 +301,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,46 +575,82 @@ 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) + /// 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> { - struct cursor + constexpr segmented_sort_merge_local_block_on_host() noexcept + : algorithm( + "segmented_sort_merge_local_block_on_host") { - 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) + /// 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 (counts[i] != 0) + if (run_ends.size() <= 1) { - heap.push(cursor{offsets[i], offsets[i] + counts[i]}); + return false; } - } - while (!heap.empty()) - { - auto current = heap.top(); - heap.pop(); - emit(HPX_MOVE(values[current.pos])); - if (++current.pos != current.end) + 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) { - heap.push(current); + 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 @@ -659,91 +748,402 @@ 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_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") + { + } + + /// 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) + { + 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_block const& lhs, std::size_t lhs_offset, + segmented_sort_block const& rhs, std::size_t rhs_offset, + Comp& comp, Proj& proj) { + 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 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. + /// \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 bool execute(ExPolicy const& policy, - segmented_sort_block const& runs, Comp comp, Proj proj) + static std::pair merge_partition( + ExPolicy const& policy, segmented_sort_block const& left, + segmented_sort_block const& right, Comp& comp, + Proj& proj) { - using value_type = std::iterator_traits::value_type; + 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; - std::vector counts; - std::vector offsets; - counts.reserve(runs.size()); - offsets.reserve(runs.size()); - std::size_t total = 0; - for (auto const& run : runs) + while (low <= high) { - offsets.push_back(total); - auto const count = static_cast(run.size()); - counts.push_back(count); - total += count; + 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}; + } } - auto values = segmented_sort_fetch_block(policy, runs); - HPX_ASSERT(values.size() == total); + HPX_ASSERT(false); + return {left_size, 0}; + } - 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]) + /// 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_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;) + { + 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); + 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_chunk, right_values.begin()); + [[maybe_unused]] auto const right_last = + segmented_sort_store_block( + policy, right_chunk, left_values.begin()); + HPX_ASSERT(left_last == right_values.end()); + HPX_ASSERT(right_last == left_values.end()); + offset += count; + } + } + + /// 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, + 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_sort_merge_local_block_on_host; + auto const here = hpx::find_here(); + std::vector> pending; + std::exception_ptr error; + auto merge_run = [&](segmented_sort_block const& run, + std::size_t middle_offset) { + if (middle_offset == 0 || + middle_offset == segmented_sort_block_size(run)) { 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()) + auto const host = run.front().locality; + std::vector run_ends{ + middle_offset, segmented_sort_block_size(run)}; + if constexpr (IsSeq::value) { - output.reserve(counts[destination]); + if (host == here) + { + operation::sequential( + policy, run, run_ends, comp, proj); + } + else + { + dispatch(host, operation(), policy, is_seq, run, + run_ends, comp, proj); + } + } + else if (host == here) + { + pending.push_back( + 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(host, operation(), policy, + is_seq, run, run_ends, comp, proj)); } }; - segmented_sort_kway_for_each(values, offsets, counts, pred, emit); - HPX_ASSERT(destination == runs.size()); + 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. + /// + /// \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_block const& left, + segmented_sort_block const& right, Comp comp, Proj proj) + { + auto const left_size = segmented_sort_block_size(left); + 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, + 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_block const& runs, Comp comp, Proj proj) + segmented_sort_block const& left, + segmented_sort_block 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)); } + /// Parallel dispatch entry point for a compare-split. template static bool parallel(ExPolicy const& policy, - segmented_sort_block const& runs, Comp comp, Proj proj) + segmented_sort_block const& left, + segmented_sort_block 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. + /// 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. 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. + /// \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, - 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) @@ -751,28 +1151,68 @@ 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(); + std::size_t phase = 0; + std::size_t unchanged_phases = 0; + while (unchanged_phases != 2) { - if (host == hpx::find_here()) + bool phase_changed = false; + 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) + { + auto const host = segmented_sort_host(runs[i], runs[i + 1]); + if constexpr (IsSeq::value) + { + if (host == here) + { + phase_changed = + operation().call2(policy, is_seq, runs[i], + runs[i + 1], comp, proj) || + phase_changed; + } + else + { + phase_changed = + dispatch(host, operation(), policy, is_seq, + runs[i], runs[i + 1], comp, proj) || + phase_changed; + } + } + 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); + for (auto& result : pending) + { + phase_changed = result.get() || phase_changed; + } + unchanged_phases = phase_changed ? 0 : unchanged_phases + 1; + ++phase; } - catch (...) - { - error = std::current_exception(); - } - segmented_sort_wait(pending, error); } template requires(hpx::traits::is_iterator_v && @@ -871,11 +1318,16 @@ 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. 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 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 e8db7f041b0..e5d270629b6 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) @@ -21,7 +21,40 @@ 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 + ARGS + --vector_size=65536 + --test_count=1 + --partitions_per_locality=8 + ) + 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 + ARGS + --vector_size=65536 + --test_count=1 + --partitions_per_locality=8 + ) + 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 new file mode 100644 index 00000000000..fe19024e07a --- /dev/null +++ b/libs/full/segmented_algorithms/tests/performance/partitioned_vector_sort_performance.cpp @@ -0,0 +1,293 @@ +// Copyright (c) 2026 Divyanshi Talreja +// +// 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 +#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. + /// \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) + { + values.set_values(hpx::launch::sync, positions, input); + } + + /// 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) + { + 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; + } + + /// Merge sorted physical partitions on the driver using public vector + /// operations. + /// + /// \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) + { + auto gathered = values.get_values(hpx::launch::sync, positions); + std::vector offsets; + offsets.reserve(counts.size()); + std::size_t offset = 0; + for (auto const count : counts) + { + offsets.push_back(offset); + offset += count; + } + HPX_ASSERT(offset == gathered.size()); + + struct cursor + { + std::size_t position; + std::size_t end; + }; + + auto const compare = [&](cursor const& lhs, cursor const& rhs) { + return gathered[rhs.position] < gathered[lhs.position]; + }; + std::priority_queue, decltype(compare)> + heap(compare); + for (std::size_t i = 0; i != counts.size(); ++i) + { + if (counts[i] != 0) + { + heap.push({offsets[i], offsets[i] + counts[i]}); + } + } + + std::vector output; + output.reserve(gathered.size()); + while (!heap.empty()) + { + auto current = heap.top(); + heap.pop(); + output.push_back(HPX_MOVE(gathered[current.position])); + if (++current.position != current.end) + { + heap.push(current); + } + } + 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. + /// \param positions Global positions of all values in the vector. + void centralized_kway_sort( + vector_type& values, std::vector const& positions) + { + auto const counts = values.get_partition_sizes(); + std::vector> sorts; + sorts.reserve(counts.size()); + auto first = values.begin(); + for (auto const count : counts) + { + auto const last = first + static_cast(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(); + } + centralized_kway_merge(values, positions, counts); + } + + /// 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"; +#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) + + "/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, positions); }, + 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 both centralized implementations. +/// +/// \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) + { + return 0; + } + + auto const size = vm["vector_size"].as(); + auto const test_count = vm["test_count"].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 (test_count == 0) + { + return hpx::finalize(); + } + + hpx::util::perftests_init(vm, "partitioned_vector_sort_performance"); + std::vector partitions_per_locality; + if (requested_partitions_per_locality != 0) + { + partitions_per_locality.push_back(requested_partitions_per_locality); + } + else + { + partitions_per_locality = {8, 16, 32, 64}; + } + + 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(); +} + +/// 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( + "usage: " HPX_APPLICATION_STRING " [options]"); + cmdline.add_options()("vector_size", + hpx::program_options::value()->default_value(1000000), + "number of values")("partitions_per_locality", + hpx::program_options::value()->default_value(0), + "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"}; + 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 3d1120c1bc2..d0beea0f5f6 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,95 @@ void test_sort_subranges( } } -struct move_only_sort_value +/// 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) { - explicit move_only_sort_value(int value) - : value(value) + // 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); + + if constexpr (hpx::is_async_execution_policy_v) { + hpx::sort(policy, values.begin(), values.end()).get(); } + else + { + hpx::sort(policy, values.begin(), values.end()); + } + verify_sorted(values, expected); +} - 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; +/// 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 + // 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( + 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) + { + return static_cast(run_size + i); + } + return static_cast(i - run_size); + }); + auto const expected = copy_values(values); - int value; -}; + hpx::sort(hpx::execution::par, values.begin(), values.end()); + verify_sorted(values, expected); +} -// Cover arbitrary run counts, short final runs, duplicates, and value types -// that cannot be copied or default constructed. -void test_kway_merge() +/// 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) { - namespace detail = hpx::parallel::detail; + 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); - 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); - } - } - } + hpx::sort(hpx::execution::par, values.begin(), values.end()); + verify_sorted(values, expected); +} - std::vector values; - for (int value : {0, 3, 6, 1, 4, 7, 2, 5, 8}) - { - values.emplace_back(value); - } - 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) - { - HPX_TEST_EQ(output[i].value, static_cast(i)); - } +/// 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) @@ -616,7 +624,13 @@ 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_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));