From 12fbd436373903f708dfb98cfa2b89c7f01118d2 Mon Sep 17 00:00:00 2001 From: Henry Schreiner Date: Sun, 1 Nov 2026 13:30:33 -0500 Subject: [PATCH 1/6] perf: replace per-cell indexing in reduce with strided copy reduce visited every input cell through indexed() and computed the output index with result.at(idx) per cell. It now builds one lookup table per axis which maps each stored input position to an output offset, or marks it as skipped, and runs a nested strided loop over the raw storage. Skipped outer slabs are skipped as a block, so crop and pick in crop mode scale with the output size. For arithmetic dense storages, runs of input cells which land in the same output cell are summed in a local accumulator, in the same order as before. Adds pick benchmarks which mirror the boost-histogram python benchmarks, and a test with large axes which exercises the heap-backed lookup table. Assisted-by: ClaudeCode:claude-fable-5-1 ClaudeCode:claude-fable-5-1 --- benchmark/histogram_reduce.cpp | 51 ++++++ include/boost/histogram/algorithm/reduce.hpp | 162 +++++++++++++++---- test/algorithm_reduce_test.cpp | 15 ++ 3 files changed, 195 insertions(+), 33 deletions(-) diff --git a/benchmark/histogram_reduce.cpp b/benchmark/histogram_reduce.cpp index 12e8c97b..49e8d458 100644 --- a/benchmark/histogram_reduce.cpp +++ b/benchmark/histogram_reduce.cpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -82,6 +83,51 @@ static void ShrinkAndRebin(benchmark::State& state, Tag, boost::mp11::mp_int +static void Pick(benchmark::State& state, Tag) { + const int n = static_cast(state.range(0)); + std::vector cats; + for (int i = 0; i < n; ++i) cats.push_back(std::to_string(i)); + using C = axis::category; + auto h = make_histogram_with(make_storage(Tag{}), C(cats), C(cats), C(cats), + axis::regular<>(n, 0.0, 10.0 * n)); + for (auto&& v : unsafe_access::storage(h)) v = 1.0; + std::vector opts; + for (int i = 0; i < 3; ++i) opts.push_back(algorithm::pick(i, {13 % n})); + run_reduce(state, h, opts); +} + +template +static void PickCrop(benchmark::State& state, Tag) { + const int n = static_cast(state.range(0)); + std::vector cats; + for (int i = 0; i < n; ++i) cats.push_back(std::to_string(i)); + using C = axis::category; + auto h = make_histogram_with(make_storage(Tag{}), C(cats), C(cats), C(cats), + axis::regular<>(n, 0.0, 10.0 * n)); + for (auto&& v : unsafe_access::storage(h)) v = 1.0; + std::vector opts; + for (int i = 0; i < 3; ++i) + opts.push_back(algorithm::pick(i, {13 % n}, algorithm::slice_mode::crop)); + run_reduce(state, h, opts); +} + +template +static void PickAndSlice(benchmark::State& state, Tag) { + const int n = static_cast(state.range(0)); + std::vector cats; + for (int i = 0; i < n; ++i) cats.push_back(std::to_string(i)); + using C = axis::category; + auto h = make_histogram_with(make_storage(Tag{}), C(cats), C(cats), C(cats), + axis::regular<>(n, 0.0, 10.0 * n)); + for (auto&& v : unsafe_access::storage(h)) v = 1.0; + std::vector opts; + opts.push_back(algorithm::slice(0, 3, 29 % n)); + for (int i = 1; i < 3; ++i) opts.push_back(algorithm::pick(i, {13 % n})); + run_reduce(state, h, opts); +} + #define BENCH(Type, Tag, Dim) \ BENCHMARK_CAPTURE(Type, (Tag, Dim), Tag{}, Dim_t{}) \ ->RangeMultiplier(4) \ @@ -110,3 +156,8 @@ BENCH(ShrinkAndRebin, unlimited, 2); BENCH(Rebin, unlimited, 3); BENCH(Shrink, unlimited, 3); BENCH(ShrinkAndRebin, unlimited, 3); + +BENCHMARK_CAPTURE(Pick, (dense), dense{})->Arg(32); +BENCHMARK_CAPTURE(PickCrop, (dense), dense{})->Arg(32); +BENCHMARK_CAPTURE(PickAndSlice, (dense), dense{})->Arg(32); +BENCHMARK_CAPTURE(Pick, (unlimited), unlimited{})->Arg(32); diff --git a/include/boost/histogram/algorithm/reduce.hpp b/include/boost/histogram/algorithm/reduce.hpp index 9fc931cc..b1d06105 100644 --- a/include/boost/histogram/algorithm/reduce.hpp +++ b/include/boost/histogram/algorithm/reduce.hpp @@ -11,10 +11,10 @@ #include #include #include +#include #include #include #include -#include #include #include #include @@ -22,11 +22,75 @@ #include #include #include +#include #include #include namespace boost { namespace histogram { +namespace detail { + +struct reduce_axis_map { + std::size_t begin; // first entry of this axis in the lookup table + std::size_t extent; // number of stored input bins, including flow bins + std::size_t stride; // input stride of this axis +}; + +// Innermost axis. Consecutive input cells which map to the same output cell are +// summed in a local accumulator; this breaks the store-to-load chain on the output cell. +template +void reduce_fill_inner(std::true_type, const In& in, std::size_t in_off, Out& out, + std::size_t out_off, const std::size_t* l, std::size_t extent) { + std::size_t p = 0; + while (p < extent) { + const auto o = l[p]; + std::size_t q = p + 1; + while (q < extent && l[q] == o) ++q; + if (o != invalid_index) { + auto& dst = out[out_off + o]; + if (q == p + 1) { + dst += in[in_off + p]; + } else { + auto acc = dst; + for (; p < q; ++p) acc += in[in_off + p]; + dst = acc; + } + } + p = q; + } +} + +template +void reduce_fill_inner(std::false_type, const In& in, std::size_t in_off, Out& out, + std::size_t out_off, const std::size_t* l, std::size_t extent) { + for (std::size_t p = 0; p < extent; ++p) + if (l[p] != invalid_index) out[out_off + l[p]] += in[in_off + p]; +} + +// Accumulate input cells into output cells. The lookup table maps each stored input +// position to an output offset; invalid_index skips the input cell and, for an outer +// axis, the whole block of cells below it. +template +void reduce_fill(const In& in, std::size_t in_off, Out& out, std::size_t out_off, + const std::size_t* lut, const reduce_axis_map* maps, unsigned iaxis) { + const auto& m = maps[iaxis]; + const std::size_t* const l = lut + m.begin; + if (iaxis == 0) { + // local accumulation needs a true reference to an arithmetic cell + using ref_t = decltype(out[std::size_t{}]); + using fast_t = + std::integral_constant::value && + std::is_arithmetic>::value>; + reduce_fill_inner(fast_t{}, in, in_off, out, out_off, l, m.extent); + } else { + for (std::size_t p = 0; p < m.extent; ++p) + if (l[p] != invalid_index) + reduce_fill(in, in_off + p * m.stride, out, out_off + l[p], lut, maps, iaxis - 1); + } +} + +} // namespace detail + namespace algorithm { /** Holder for a reduce command. @@ -418,10 +482,8 @@ Histogram reduce(const Histogram& hist, const Iterable& options) { // lut maps old index to new index; unpicked bins and the // overflow bin map to the overflow bin of the new axis o.reduced_end = static_cast(o.indices.size()); - o.lut.assign(static_cast(a_in.size()) + 1, - o.reduced_end); - for (index_type k = 0; k < o.reduced_end; ++k) - o.lut[o.indices[k]] = k; + o.lut.assign(static_cast(a_in.size()) + 1, o.reduced_end); + for (index_type k = 0; k < o.reduced_end; ++k) o.lut[o.indices[k]] = k; return std::decay_t( a_in, o.indices.data(), o.indices.data() + o.indices.size()); }, @@ -488,37 +550,71 @@ Histogram reduce(const Histogram& hist, const Iterable& options) { auto result = Histogram(std::move(axes), detail::make_default(unsafe_access::storage(hist))); - auto idx = detail::make_stack_buffer(unsafe_access::axes(result)); - for (auto&& x : indexed(hist, coverage::all)) { - auto i = idx.begin(); - auto o = opts.begin(); - bool skip = false; - - for (auto j : x.indices()) { - if (o->range == reduce_command::range_t::indices_list) { - *i = o->lut[j]; - } else { - *i = (j - o->begin.index); - if (o->is_ordered && *i <= -1) { - *i = -1; - if (!o->use_underflow_bin) skip = true; - } else if (*i >= 0) - *i /= static_cast(o->merge); - else - *i = o->reduced_end; - } - if (*i >= o->reduced_end) { - *i = o->reduced_end; - if (!o->use_overflow_bin) skip = true; + // one table per axis maps each stored input position to an output offset + const auto rank = detail::axes_rank(old_axes); + std::size_t lut_size = 0; + detail::for_each_axis(old_axes, [&lut_size](const auto& a) { + lut_size += static_cast(axis::traits::extent(a)); + }); + // small tables live on the stack to keep reduce of small histograms cheap + std::size_t lut_stack[256]; + std::vector lut_heap; + std::size_t* lut = lut_stack; + if (lut_size > 256) { + lut_heap.resize(lut_size); + lut = lut_heap.data(); + } + auto maps = detail::make_stack_buffer(old_axes); + { + std::size_t* l = lut; + std::size_t in_stride = 1; + std::size_t out_stride = 1; + unsigned iaxis = 0; + detail::for_each_axis(old_axes, [&](const auto& a_in) { + using A = std::decay_t; + using AO = axis::traits::get_options; + const index_type u = AO::test(axis::option::underflow); + const index_type ov = AO::test(axis::option::overflow); + const auto& o = opts[iaxis]; + const auto size = a_in.size(); + auto& m = maps[iaxis]; + m.begin = static_cast(l - lut); + m.extent = static_cast(size + u + ov); + m.stride = in_stride; + for (index_type j = -u; j < size + ov; ++j) { + index_type i; + bool skip = false; + if (o.range == reduce_command::range_t::indices_list) { + i = j < 0 ? o.reduced_end : o.lut[j]; + } else { + i = (j - o.begin.index); + if (o.is_ordered && i <= -1) { + i = -1; + if (!o.use_underflow_bin) skip = true; + } else if (i >= 0) + i /= static_cast(o.merge); + else + i = o.reduced_end; + } + if (i >= o.reduced_end) { + i = o.reduced_end; + if (!o.use_overflow_bin) skip = true; + } + *l++ = + skip ? detail::invalid_index : static_cast(i + u) * out_stride; } - - ++i; - ++o; - } - - if (!skip) result.at(idx) += *x; + in_stride *= m.extent; + out_stride *= static_cast(o.reduced_end + u + ov); + ++iaxis; + }); + assert(static_cast(l - lut) == lut_size); + assert(in_stride == hist.size()); + assert(out_stride == result.size()); } + detail::reduce_fill(unsafe_access::storage(hist), 0, unsafe_access::storage(result), 0, + lut, maps.data(), rank - 1); + return result; } diff --git a/test/algorithm_reduce_test.cpp b/test/algorithm_reduce_test.cpp index 7caa4ac7..99fb69fc 100644 --- a/test/algorithm_reduce_test.cpp +++ b/test/algorithm_reduce_test.cpp @@ -12,6 +12,7 @@ #include #include #include +#include #include #include #include @@ -518,6 +519,20 @@ void run_tests() { BOOST_TEST_EQ(hr.at(1, 1), 4); BOOST_TEST_EQ(hr.at(2, 1), 0); } + + // large axes; the lookup tables of reduce do not fit on the stack + { + auto h = make_s(Tag(), std::vector(), R(300, 0, 300), ID(0, 300)); + for (auto&& x : indexed(h, coverage::all)) *x = x.index(0) + 1; + auto hr = reduce(h, shrink_and_rebin(0, 10, 290, 10), slice(1, 100, 200)); + BOOST_TEST_EQ(hr.axis(0), R(28, 10, 290)); + BOOST_TEST_EQ(hr.axis(1), ID(100, 200)); + BOOST_TEST_EQ(sum(hr), sum(h)); + // bin k of axis 0 merges original bins 10k+10..10k+19 of weight (index + 1) + for (int k = 0; k < 28; ++k) BOOST_TEST_EQ(hr.at(k, 0), 10 * (10 * k + 11) + 45); + BOOST_TEST_EQ(hr.at(-1, 0), 10 * 1 + 45); // bins 0..9, original underflow is 0 + BOOST_TEST_EQ(hr.at(28, 0), 10 * 291 + 45 + 301); // bins 290..299 + original overflow + } } int main() { From df1f0b76fef6ffb509cb4a53bfab61f570055ffb Mon Sep 17 00:00:00 2001 From: Henry Schreiner Date: Sun, 1 Nov 2026 13:40:50 -0500 Subject: [PATCH 2/6] refactor: build pick lookup table directly in reduce Drop reduce_command::lut and fill the per-axis table for pick commands directly, which removes a heap allocation per picked axis and the underflow special case. Use axis::traits::extent for the axis extent and share the setup of the pick benchmarks. Assisted-by: ClaudeCode:claude-opus-5-5 --- benchmark/histogram_reduce.cpp | 26 +++++------- include/boost/histogram/algorithm/reduce.hpp | 41 ++++++++++--------- .../boost/histogram/detail/reduce_command.hpp | 3 +- 3 files changed, 33 insertions(+), 37 deletions(-) diff --git a/benchmark/histogram_reduce.cpp b/benchmark/histogram_reduce.cpp index 49e8d458..2e6ac652 100644 --- a/benchmark/histogram_reduce.cpp +++ b/benchmark/histogram_reduce.cpp @@ -83,16 +83,22 @@ static void ShrinkAndRebin(benchmark::State& state, Tag, boost::mp11::mp_int -static void Pick(benchmark::State& state, Tag) { - const int n = static_cast(state.range(0)); +auto make_category_histogram(Tag, int n) { std::vector cats; for (int i = 0; i < n; ++i) cats.push_back(std::to_string(i)); using C = axis::category; auto h = make_histogram_with(make_storage(Tag{}), C(cats), C(cats), C(cats), axis::regular<>(n, 0.0, 10.0 * n)); for (auto&& v : unsafe_access::storage(h)) v = 1.0; + return h; +} + +// mirrors the boost-histogram python benchmark: h[loc(a), loc(b), loc(c), :] +template +static void Pick(benchmark::State& state, Tag) { + const int n = static_cast(state.range(0)); + const auto h = make_category_histogram(Tag{}, n); std::vector opts; for (int i = 0; i < 3; ++i) opts.push_back(algorithm::pick(i, {13 % n})); run_reduce(state, h, opts); @@ -101,12 +107,7 @@ static void Pick(benchmark::State& state, Tag) { template static void PickCrop(benchmark::State& state, Tag) { const int n = static_cast(state.range(0)); - std::vector cats; - for (int i = 0; i < n; ++i) cats.push_back(std::to_string(i)); - using C = axis::category; - auto h = make_histogram_with(make_storage(Tag{}), C(cats), C(cats), C(cats), - axis::regular<>(n, 0.0, 10.0 * n)); - for (auto&& v : unsafe_access::storage(h)) v = 1.0; + const auto h = make_category_histogram(Tag{}, n); std::vector opts; for (int i = 0; i < 3; ++i) opts.push_back(algorithm::pick(i, {13 % n}, algorithm::slice_mode::crop)); @@ -116,12 +117,7 @@ static void PickCrop(benchmark::State& state, Tag) { template static void PickAndSlice(benchmark::State& state, Tag) { const int n = static_cast(state.range(0)); - std::vector cats; - for (int i = 0; i < n; ++i) cats.push_back(std::to_string(i)); - using C = axis::category; - auto h = make_histogram_with(make_storage(Tag{}), C(cats), C(cats), C(cats), - axis::regular<>(n, 0.0, 10.0 * n)); - for (auto&& v : unsafe_access::storage(h)) v = 1.0; + const auto h = make_category_histogram(Tag{}, n); std::vector opts; opts.push_back(algorithm::slice(0, 3, 29 % n)); for (int i = 1; i < 3; ++i) opts.push_back(algorithm::pick(i, {13 % n})); diff --git a/include/boost/histogram/algorithm/reduce.hpp b/include/boost/histogram/algorithm/reduce.hpp index b1d06105..0f18125a 100644 --- a/include/boost/histogram/algorithm/reduce.hpp +++ b/include/boost/histogram/algorithm/reduce.hpp @@ -48,7 +48,7 @@ void reduce_fill_inner(std::true_type, const In& in, std::size_t in_off, Out& ou while (q < extent && l[q] == o) ++q; if (o != invalid_index) { auto& dst = out[out_off + o]; - if (q == p + 1) { + if (q == p + 1) { // faster for the common run of length 1 dst += in[in_off + p]; } else { auto acc = dst; @@ -479,11 +479,7 @@ Histogram reduce(const Histogram& hist, const Iterable& options) { [&o](const auto& a_in) { static_assert(!axis::traits::is_ordered::value, "pick requires an unordered axis"); - // lut maps old index to new index; unpicked bins and the - // overflow bin map to the overflow bin of the new axis o.reduced_end = static_cast(o.indices.size()); - o.lut.assign(static_cast(a_in.size()) + 1, o.reduced_end); - for (index_type k = 0; k < o.reduced_end; ++k) o.lut[o.indices[k]] = k; return std::decay_t( a_in, o.indices.data(), o.indices.data() + o.indices.size()); }, @@ -576,18 +572,23 @@ Histogram reduce(const Histogram& hist, const Iterable& options) { const index_type u = AO::test(axis::option::underflow); const index_type ov = AO::test(axis::option::overflow); const auto& o = opts[iaxis]; - const auto size = a_in.size(); auto& m = maps[iaxis]; m.begin = static_cast(l - lut); - m.extent = static_cast(size + u + ov); + m.extent = static_cast(axis::traits::extent(a_in)); m.stride = in_stride; - for (index_type j = -u; j < size + ov; ++j) { - index_type i; - bool skip = false; - if (o.range == reduce_command::range_t::indices_list) { - i = j < 0 ? o.reduced_end : o.lut[j]; - } else { - i = (j - o.begin.index); + if (o.range == reduce_command::range_t::indices_list) { + // unpicked bins and flow bins go to the overflow bin of the new axis + std::fill(l, l + m.extent, + o.use_overflow_bin + ? static_cast(o.reduced_end + u) * out_stride + : detail::invalid_index); + for (index_type k = 0; k < o.reduced_end; ++k) + l[o.indices[k] + u] = static_cast(k + u) * out_stride; + l += m.extent; + } else { + for (index_type j = -u; j < a_in.size() + ov; ++j) { + index_type i = (j - o.begin.index); + bool skip = false; if (o.is_ordered && i <= -1) { i = -1; if (!o.use_underflow_bin) skip = true; @@ -595,13 +596,13 @@ Histogram reduce(const Histogram& hist, const Iterable& options) { i /= static_cast(o.merge); else i = o.reduced_end; + if (i >= o.reduced_end) { + i = o.reduced_end; + if (!o.use_overflow_bin) skip = true; + } + *l++ = + skip ? detail::invalid_index : static_cast(i + u) * out_stride; } - if (i >= o.reduced_end) { - i = o.reduced_end; - if (!o.use_overflow_bin) skip = true; - } - *l++ = - skip ? detail::invalid_index : static_cast(i + u) * out_stride; } in_stride *= m.extent; out_stride *= static_cast(o.reduced_end + u + ov); diff --git a/include/boost/histogram/detail/reduce_command.hpp b/include/boost/histogram/detail/reduce_command.hpp index cd60c46d..43c69bf3 100644 --- a/include/boost/histogram/detail/reduce_command.hpp +++ b/include/boost/histogram/detail/reduce_command.hpp @@ -36,8 +36,7 @@ struct reduce_command { unsigned merge = 0; // default value indicates unset option bool crop = false; // for internal use by the reduce algorithm - axis::index_type reduced_end = 0; // overflow index of the new axis - std::vector lut; // pick: maps old bin index to new bin index + axis::index_type reduced_end = 0; // overflow index of the new axis bool is_ordered = true; bool use_underflow_bin = true; bool use_overflow_bin = true; From bb6d0886827847443fb6ae8f37e26eda7e4039ad Mon Sep 17 00:00:00 2001 From: Henry Schreiner Date: Sun, 1 Nov 2026 13:47:22 -0500 Subject: [PATCH 3/6] fix: handle zero-dimensional histograms in reduce Assisted-by: ClaudeCode:claude-opus-5-5 --- include/boost/histogram/algorithm/reduce.hpp | 7 +++++-- test/algorithm_reduce_test.cpp | 10 ++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/include/boost/histogram/algorithm/reduce.hpp b/include/boost/histogram/algorithm/reduce.hpp index 0f18125a..e1c707f8 100644 --- a/include/boost/histogram/algorithm/reduce.hpp +++ b/include/boost/histogram/algorithm/reduce.hpp @@ -613,8 +613,11 @@ Histogram reduce(const Histogram& hist, const Iterable& options) { assert(out_stride == result.size()); } - detail::reduce_fill(unsafe_access::storage(hist), 0, unsafe_access::storage(result), 0, - lut, maps.data(), rank - 1); + if (rank == 0) // a scalar histogram has one cell and no axis to recurse over + unsafe_access::storage(result)[0] += unsafe_access::storage(hist)[0]; + else + detail::reduce_fill(unsafe_access::storage(hist), 0, unsafe_access::storage(result), + 0, lut, maps.data(), rank - 1); return result; } diff --git a/test/algorithm_reduce_test.cpp b/test/algorithm_reduce_test.cpp index 99fb69fc..caafd97d 100644 --- a/test/algorithm_reduce_test.cpp +++ b/test/algorithm_reduce_test.cpp @@ -539,5 +539,15 @@ int main() { run_tests(); run_tests(); + // zero-dimensional histogram + { + auto h = make_histogram(std::vector>()); + BOOST_TEST_EQ(h.rank(), 0); + unsafe_access::storage(h)[0] = 3; + auto hr = reduce(h, std::vector()); + BOOST_TEST_EQ(hr.rank(), 0); + BOOST_TEST_EQ(unsafe_access::storage(hr)[0], 3); + } + return boost::report_errors(); } From 4c1a4f21652545f492f29e0cc8bd8ad5939b6b67 Mon Sep 17 00:00:00 2001 From: Henry Schreiner Date: Mon, 2 Nov 2026 09:35:12 -0500 Subject: [PATCH 4/6] refactor: use a single vector for the reduce lookup table The stack buffer saved about 12 ns per call, visible only on 1D histograms with few bins. Assisted-by: ClaudeCode:claude-fable-5-1 --- include/boost/histogram/algorithm/reduce.hpp | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/include/boost/histogram/algorithm/reduce.hpp b/include/boost/histogram/algorithm/reduce.hpp index e1c707f8..3c347573 100644 --- a/include/boost/histogram/algorithm/reduce.hpp +++ b/include/boost/histogram/algorithm/reduce.hpp @@ -552,17 +552,10 @@ Histogram reduce(const Histogram& hist, const Iterable& options) { detail::for_each_axis(old_axes, [&lut_size](const auto& a) { lut_size += static_cast(axis::traits::extent(a)); }); - // small tables live on the stack to keep reduce of small histograms cheap - std::size_t lut_stack[256]; - std::vector lut_heap; - std::size_t* lut = lut_stack; - if (lut_size > 256) { - lut_heap.resize(lut_size); - lut = lut_heap.data(); - } + std::vector lut(lut_size); auto maps = detail::make_stack_buffer(old_axes); { - std::size_t* l = lut; + std::size_t* l = lut.data(); std::size_t in_stride = 1; std::size_t out_stride = 1; unsigned iaxis = 0; @@ -573,7 +566,7 @@ Histogram reduce(const Histogram& hist, const Iterable& options) { const index_type ov = AO::test(axis::option::overflow); const auto& o = opts[iaxis]; auto& m = maps[iaxis]; - m.begin = static_cast(l - lut); + m.begin = static_cast(l - lut.data()); m.extent = static_cast(axis::traits::extent(a_in)); m.stride = in_stride; if (o.range == reduce_command::range_t::indices_list) { @@ -608,7 +601,7 @@ Histogram reduce(const Histogram& hist, const Iterable& options) { out_stride *= static_cast(o.reduced_end + u + ov); ++iaxis; }); - assert(static_cast(l - lut) == lut_size); + assert(static_cast(l - lut.data()) == lut_size); assert(in_stride == hist.size()); assert(out_stride == result.size()); } @@ -617,7 +610,7 @@ Histogram reduce(const Histogram& hist, const Iterable& options) { unsafe_access::storage(result)[0] += unsafe_access::storage(hist)[0]; else detail::reduce_fill(unsafe_access::storage(hist), 0, unsafe_access::storage(result), - 0, lut, maps.data(), rank - 1); + 0, lut.data(), maps.data(), rank - 1); return result; } From 531b37c07b0725b39b3cd037546e46352a98abc0 Mon Sep 17 00:00:00 2001 From: Henry Schreiner Date: Mon, 2 Nov 2026 09:52:15 -0500 Subject: [PATCH 5/6] refactor: use static_if for the reduce inner loop Assisted-by: ClaudeCode:claude-opus-5-5 --- include/boost/histogram/algorithm/reduce.hpp | 63 +++++++++----------- 1 file changed, 28 insertions(+), 35 deletions(-) diff --git a/include/boost/histogram/algorithm/reduce.hpp b/include/boost/histogram/algorithm/reduce.hpp index 3c347573..3ead920c 100644 --- a/include/boost/histogram/algorithm/reduce.hpp +++ b/include/boost/histogram/algorithm/reduce.hpp @@ -36,37 +36,6 @@ struct reduce_axis_map { std::size_t stride; // input stride of this axis }; -// Innermost axis. Consecutive input cells which map to the same output cell are -// summed in a local accumulator; this breaks the store-to-load chain on the output cell. -template -void reduce_fill_inner(std::true_type, const In& in, std::size_t in_off, Out& out, - std::size_t out_off, const std::size_t* l, std::size_t extent) { - std::size_t p = 0; - while (p < extent) { - const auto o = l[p]; - std::size_t q = p + 1; - while (q < extent && l[q] == o) ++q; - if (o != invalid_index) { - auto& dst = out[out_off + o]; - if (q == p + 1) { // faster for the common run of length 1 - dst += in[in_off + p]; - } else { - auto acc = dst; - for (; p < q; ++p) acc += in[in_off + p]; - dst = acc; - } - } - p = q; - } -} - -template -void reduce_fill_inner(std::false_type, const In& in, std::size_t in_off, Out& out, - std::size_t out_off, const std::size_t* l, std::size_t extent) { - for (std::size_t p = 0; p < extent; ++p) - if (l[p] != invalid_index) out[out_off + l[p]] += in[in_off + p]; -} - // Accumulate input cells into output cells. The lookup table maps each stored input // position to an output offset; invalid_index skips the input cell and, for an outer // axis, the whole block of cells below it. @@ -78,10 +47,34 @@ void reduce_fill(const In& in, std::size_t in_off, Out& out, std::size_t out_off if (iaxis == 0) { // local accumulation needs a true reference to an arithmetic cell using ref_t = decltype(out[std::size_t{}]); - using fast_t = - std::integral_constant::value && - std::is_arithmetic>::value>; - reduce_fill_inner(fast_t{}, in, in_off, out, out_off, l, m.extent); + static_if_c::value && + std::is_arithmetic>::value>( + [&](auto& res) { + // sum runs of input cells with the same output cell in a local accumulator; + // this breaks the store-to-load chain on the output cell + std::size_t p = 0; + while (p < m.extent) { + const auto o = l[p]; + std::size_t q = p + 1; + while (q < m.extent && l[q] == o) ++q; + if (o != invalid_index) { + auto& dst = res[out_off + o]; + if (q == p + 1) { // faster for the common run of length 1 + dst += in[in_off + p]; + } else { + auto acc = dst; + for (; p < q; ++p) acc += in[in_off + p]; + dst = acc; + } + } + p = q; + } + }, + [&](auto& res) { + for (std::size_t p = 0; p < m.extent; ++p) + if (l[p] != invalid_index) res[out_off + l[p]] += in[in_off + p]; + }, + out); } else { for (std::size_t p = 0; p < m.extent; ++p) if (l[p] != invalid_index) From a4595d6da7bd650f084626d0b4c73a7c80f69bba Mon Sep 17 00:00:00 2001 From: Henry Schreiner Date: Mon, 2 Nov 2026 10:21:58 -0500 Subject: [PATCH 6/6] perf: share strided cell copy between reduce and storage_grower Add detail::cell_map, which maps each input cell to an output offset through one lookup table per axis and visits the cells line by line. reduce and storage_grower now both use it. storage_grower no longer steps through a multi-index cell by cell. Assisted-by: ClaudeCode:claude-opus-5-5 --- include/boost/histogram/algorithm/reduce.hpp | 125 +++++++------------ include/boost/histogram/detail/cell_map.hpp | 86 +++++++++++++ include/boost/histogram/detail/fill.hpp | 95 +++++--------- 3 files changed, 163 insertions(+), 143 deletions(-) create mode 100644 include/boost/histogram/detail/cell_map.hpp diff --git a/include/boost/histogram/algorithm/reduce.hpp b/include/boost/histogram/algorithm/reduce.hpp index 3ead920c..07a652e1 100644 --- a/include/boost/histogram/algorithm/reduce.hpp +++ b/include/boost/histogram/algorithm/reduce.hpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include #include @@ -28,62 +29,6 @@ namespace boost { namespace histogram { -namespace detail { - -struct reduce_axis_map { - std::size_t begin; // first entry of this axis in the lookup table - std::size_t extent; // number of stored input bins, including flow bins - std::size_t stride; // input stride of this axis -}; - -// Accumulate input cells into output cells. The lookup table maps each stored input -// position to an output offset; invalid_index skips the input cell and, for an outer -// axis, the whole block of cells below it. -template -void reduce_fill(const In& in, std::size_t in_off, Out& out, std::size_t out_off, - const std::size_t* lut, const reduce_axis_map* maps, unsigned iaxis) { - const auto& m = maps[iaxis]; - const std::size_t* const l = lut + m.begin; - if (iaxis == 0) { - // local accumulation needs a true reference to an arithmetic cell - using ref_t = decltype(out[std::size_t{}]); - static_if_c::value && - std::is_arithmetic>::value>( - [&](auto& res) { - // sum runs of input cells with the same output cell in a local accumulator; - // this breaks the store-to-load chain on the output cell - std::size_t p = 0; - while (p < m.extent) { - const auto o = l[p]; - std::size_t q = p + 1; - while (q < m.extent && l[q] == o) ++q; - if (o != invalid_index) { - auto& dst = res[out_off + o]; - if (q == p + 1) { // faster for the common run of length 1 - dst += in[in_off + p]; - } else { - auto acc = dst; - for (; p < q; ++p) acc += in[in_off + p]; - dst = acc; - } - } - p = q; - } - }, - [&](auto& res) { - for (std::size_t p = 0; p < m.extent; ++p) - if (l[p] != invalid_index) res[out_off + l[p]] += in[in_off + p]; - }, - out); - } else { - for (std::size_t p = 0; p < m.extent; ++p) - if (l[p] != invalid_index) - reduce_fill(in, in_off + p * m.stride, out, out_off + l[p], lut, maps, iaxis - 1); - } -} - -} // namespace detail - namespace algorithm { /** Holder for a reduce command. @@ -539,17 +484,9 @@ Histogram reduce(const Histogram& hist, const Iterable& options) { auto result = Histogram(std::move(axes), detail::make_default(unsafe_access::storage(hist))); - // one table per axis maps each stored input position to an output offset - const auto rank = detail::axes_rank(old_axes); - std::size_t lut_size = 0; - detail::for_each_axis(old_axes, [&lut_size](const auto& a) { - lut_size += static_cast(axis::traits::extent(a)); - }); - std::vector lut(lut_size); - auto maps = detail::make_stack_buffer(old_axes); + // maps each input cell to its output cell + detail::cell_map> map(old_axes); { - std::size_t* l = lut.data(); - std::size_t in_stride = 1; std::size_t out_stride = 1; unsigned iaxis = 0; detail::for_each_axis(old_axes, [&](const auto& a_in) { @@ -558,19 +495,16 @@ Histogram reduce(const Histogram& hist, const Iterable& options) { const index_type u = AO::test(axis::option::underflow); const index_type ov = AO::test(axis::option::overflow); const auto& o = opts[iaxis]; - auto& m = maps[iaxis]; - m.begin = static_cast(l - lut.data()); - m.extent = static_cast(axis::traits::extent(a_in)); - m.stride = in_stride; + const auto extent = static_cast(axis::traits::extent(a_in)); + std::size_t* l = map.add_axis(extent); if (o.range == reduce_command::range_t::indices_list) { // unpicked bins and flow bins go to the overflow bin of the new axis - std::fill(l, l + m.extent, + std::fill(l, l + extent, o.use_overflow_bin ? static_cast(o.reduced_end + u) * out_stride : detail::invalid_index); for (index_type k = 0; k < o.reduced_end; ++k) l[o.indices[k] + u] = static_cast(k + u) * out_stride; - l += m.extent; } else { for (index_type j = -u; j < a_in.size() + ov; ++j) { index_type i = (j - o.begin.index); @@ -590,20 +524,51 @@ Histogram reduce(const Histogram& hist, const Iterable& options) { skip ? detail::invalid_index : static_cast(i + u) * out_stride; } } - in_stride *= m.extent; out_stride *= static_cast(o.reduced_end + u + ov); ++iaxis; }); - assert(static_cast(l - lut.data()) == lut_size); - assert(in_stride == hist.size()); + assert(map.input_size() == hist.size()); assert(out_stride == result.size()); } - if (rank == 0) // a scalar histogram has one cell and no axis to recurse over - unsafe_access::storage(result)[0] += unsafe_access::storage(hist)[0]; - else - detail::reduce_fill(unsafe_access::storage(hist), 0, unsafe_access::storage(result), - 0, lut.data(), maps.data(), rank - 1); + const auto& in = unsafe_access::storage(hist); + auto& out = unsafe_access::storage(result); + // local accumulation needs a true reference to an arithmetic cell + using ref_t = decltype(out[std::size_t{}]); + detail::static_if_c::value && + std::is_arithmetic>::value>( + [&map, &in](auto& res) { + map.for_each_line([&](std::size_t in_off, std::size_t out_off, + const std::size_t* l, std::size_t n) { + // sum runs of input cells with the same output cell in a local accumulator; + // this breaks the store-to-load chain on the output cell + std::size_t p = 0; + while (p < n) { + const auto o = l[p]; + std::size_t q = p + 1; + while (q < n && l[q] == o) ++q; + if (o != detail::invalid_index) { + auto& dst = res[out_off + o]; + if (q == p + 1) { // faster for the common run of length 1 + dst += in[in_off + p]; + } else { + auto acc = dst; + for (; p < q; ++p) acc += in[in_off + p]; + dst = acc; + } + } + p = q; + } + }); + }, + [&map, &in](auto& res) { + map.for_each_line([&](std::size_t in_off, std::size_t out_off, + const std::size_t* l, std::size_t n) { + for (std::size_t p = 0; p < n; ++p) + if (l[p] != detail::invalid_index) res[out_off + l[p]] += in[in_off + p]; + }); + }, + out); return result; } diff --git a/include/boost/histogram/detail/cell_map.hpp b/include/boost/histogram/detail/cell_map.hpp new file mode 100644 index 00000000..3c01a29c --- /dev/null +++ b/include/boost/histogram/detail/cell_map.hpp @@ -0,0 +1,86 @@ +// Copyright 2026 Henry Schreiner +// +// 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) + +#ifndef BOOST_HISTOGRAM_DETAIL_CELL_MAP_HPP +#define BOOST_HISTOGRAM_DETAIL_CELL_MAP_HPP + +#include +#include +#include +#include +#include +#include + +namespace boost { +namespace histogram { +namespace detail { + +// Maps each cell of an input storage to an offset in an output storage. Each axis has one +// lookup table with one entry per stored input bin, flow bins included. An entry is the +// output offset contributed by that bin. invalid_index skips the input cell and, for an +// outer axis, the whole block of cells below it. +template +class cell_map { + struct axis_row { + std::size_t begin; // first entry of this axis in lut_ + std::size_t extent; // number of stored input bins + std::size_t stride; // input stride + }; + +public: + explicit cell_map(const Axes& axes) : rows_(make_stack_buffer(axes)) {} + + // Adds the table for the next axis and returns it, to be filled with `extent` entries. + // The pointer is valid until the next call. + std::size_t* add_axis(std::size_t extent) { + assert(naxes_ < rows_.size()); + rows_[naxes_++] = {lut_.size(), extent, in_size_}; + in_size_ *= extent; + lut_.resize(lut_.size() + extent); + return lut_.data() + lut_.size() - extent; + } + + std::size_t input_size() const noexcept { return in_size_; } + + // Calls f(in_offset, out_offset, lut, extent) for each line of cells along the first + // axis which is not skipped. Cell p of that line goes to out_offset + lut[p]. + template + void for_each_line(F&& f) const { + assert(naxes_ == rows_.size()); + if (naxes_ == 0) { + // a histogram without axes has one cell + const std::size_t zero = 0; + f(std::size_t{0}, std::size_t{0}, &zero, std::size_t{1}); + } else { + visit(f, 0, 0, naxes_ - 1); + } + } + +private: + template + void visit(F& f, std::size_t in_off, std::size_t out_off, unsigned iaxis) const { + const auto& r = rows_[iaxis]; + const std::size_t* const l = lut_.data() + r.begin; + if (iaxis == 0) { + f(in_off, out_off, l, r.extent); + return; + } + for (std::size_t p = 0; p < r.extent; ++p) + if (l[p] != invalid_index) + visit(f, in_off + p * r.stride, out_off + l[p], iaxis - 1); + } + + decltype(make_stack_buffer(std::declval())) rows_; + std::vector lut_; + std::size_t in_size_ = 1; + unsigned naxes_ = 0; +}; + +} // namespace detail +} // namespace histogram +} // namespace boost + +#endif diff --git a/include/boost/histogram/detail/fill.hpp b/include/boost/histogram/detail/fill.hpp index 9b8038f9..8e30a845 100644 --- a/include/boost/histogram/detail/fill.hpp +++ b/include/boost/histogram/detail/fill.hpp @@ -13,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -52,83 +53,51 @@ struct sample_args_passed_vs_expected, std::tuple struct storage_grower { const A& axes_; - struct { - axis::index_type idx, old_extent; - std::size_t new_stride; - } data_[buffer_size::value]; - std::size_t new_size_; + decltype(make_stack_buffer(std::declval())) old_extents_; - storage_grower(const A& axes) noexcept : axes_(axes) {} + storage_grower(const A& axes) noexcept + : axes_(axes), old_extents_(make_stack_buffer(axes)) {} void from_shifts(const axis::index_type* shifts) noexcept { - auto dit = data_; - std::size_t s = 1; + auto eit = old_extents_.begin(); for_each_axis(axes_, [&](const auto& a) { - const auto n = axis::traits::extent(a); - *dit++ = {0, n - std::abs(*shifts++), s}; - s *= n; + *eit++ = axis::traits::extent(a) - std::abs(*shifts++); }); - new_size_ = s; } // must be extents before any shifts were applied void from_extents(const axis::index_type* old_extents) noexcept { - auto dit = data_; - std::size_t s = 1; - for_each_axis(axes_, [&](const auto& a) { - const auto n = axis::traits::extent(a); - *dit++ = {0, *old_extents++, s}; - s *= n; - }); - new_size_ = s; + std::copy(old_extents, old_extents + old_extents_.size(), old_extents_.begin()); } template void apply(S& storage, const axis::index_type* shifts) { + cell_map map(axes_); + std::size_t out_stride = 1; + auto eit = old_extents_.begin(); + for_each_axis(axes_, [&](const auto& a) { + using opt = axis::traits::get_options>; + const auto n = axis::traits::extent(a); + const auto old_extent = *eit++; + // normal bins move by the positive shift, if any + const auto shift = (std::max)(*shifts++, 0); + std::size_t* l = map.add_axis(static_cast(old_extent)); + for (axis::index_type i = 0; i < old_extent; ++i) + l[i] = static_cast(i + shift) * out_stride; + if (opt::test(axis::option::overflow)) + l[old_extent - 1] = static_cast(n - 1) * out_stride; + if (opt::test(axis::option::underflow)) l[0] = 0; + out_stride *= static_cast(n); + }); + assert(map.input_size() == storage.size()); + auto new_storage = make_default(storage); - new_storage.reset(new_size_); - const auto dlast = data_ + axes_rank(axes_) - 1; - for (auto&& x : storage) { - auto ns = new_storage.begin(); - auto sit = shifts; - auto dit = data_; - for_each_axis(axes_, [&](const auto& a) { - using opt = axis::traits::get_options>; - if (opt::test(axis::option::underflow)) { - if (dit->idx == 0) { - // axis has underflow and we are in the underflow bin: - // keep storage pointer unchanged - ++dit; - ++sit; - return; - } - } - if (opt::test(axis::option::overflow)) { - if (dit->idx == dit->old_extent - 1) { - // axis has overflow and we are in the overflow bin: - // move storage pointer to corresponding overflow bin position - ns += (axis::traits::extent(a) - 1) * dit->new_stride; - ++dit; - ++sit; - return; - } - } - // we are in a normal bin: - // move storage pointer to index position; apply positive shifts if any - ns += (dit->idx + (*sit >= 0 ? *sit : 0)) * dit->new_stride; - ++dit; - ++sit; - }); - // assign old value to new location - *ns = x; - // advance multi-dimensional index - dit = data_; - ++dit->idx; - while (dit != dlast && dit->idx == dit->old_extent) { - dit->idx = 0; - ++(++dit)->idx; - } - } + new_storage.reset(out_stride); + map.for_each_line([&](std::size_t in_off, std::size_t out_off, const std::size_t* l, + std::size_t n) { + for (std::size_t p = 0; p < n; ++p) + new_storage[out_off + l[p]] = storage[in_off + p]; + }); storage = std::move(new_storage); } };