From a8c9be9378f537ba9cf1eebbe92e97e147d2e66c Mon Sep 17 00:00:00 2001 From: Max Podkorytov <4273004+tenpercent@users.noreply.github.com> Date: Fri, 16 Jan 2026 11:19:35 -0600 Subject: [PATCH] Rewrite sequence_map_inverse using O(1) depth pack expansion MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace O(N) recursive template sequence_map_inverse_impl with constexpr function and pack expansion for O(1) template depth. Results: - sequence_map_inverse: 45 instances, 187ms → 7 instances, 10ms (95% reduction) --- include/ck/utility/sequence.hpp | 48 ++++++++++++++++++--------------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/include/ck/utility/sequence.hpp b/include/ck/utility/sequence.hpp index 18bb36d112..1f392af070 100644 --- a/include/ck/utility/sequence.hpp +++ b/include/ck/utility/sequence.hpp @@ -576,31 +576,35 @@ struct is_valid_sequence_map : is_same +__host__ __device__ constexpr index_t find_source_index(Sequence) +{ + constexpr index_t values[] = {Is...}; + for(index_t i = 0; i < static_cast(sizeof...(Is)); ++i) + { + if(values[i] == Target) + return i; + } + return 0; // should not reach for valid permutation +} + +template +__host__ __device__ constexpr auto invert_permutation_impl(Sequence) +{ + return Sequence(SeqMap{})...>{}; +} +} // namespace detail + +// Invert a permutation sequence using O(1) template depth pack expansion +// For X2Y = {a, b, c, ...}, computes Y2X where Y2X[X2Y[i]] = i template struct sequence_map_inverse { - template - struct sequence_map_inverse_impl - { - static constexpr auto new_y2x = - WorkingY2X::Modify(X2Y::At(Number{}), Number{}); - - using type = - typename sequence_map_inverse_impl:: - type; - }; - - template - struct sequence_map_inverse_impl - { - using type = WorkingY2X; - }; - - using type = - typename sequence_map_inverse_impl::type, - 0, - SeqMap::Size()>::type; + using type = decltype(detail::invert_permutation_impl( + typename arithmetic_sequence_gen<0, SeqMap::Size(), 1>::type{})); }; template