Skip to content

Build the mapreduce kernel by recursion instead of a generated function - #105

Open
Jutho wants to merge 1 commit into
strided-planningfrom
jh/recursive-kernel
Open

Jutho wants to merge 1 commit into
strided-planningfrom
jh/recursive-kernel

Conversation

@Jutho

@Jutho Jutho commented Nov 29, 2026

Copy link
Copy Markdown
Member

Builds on #104, and targets its branch strided-planning; once #104 is merged, this PR can be retargeted to main.

This replaces _mapreduce_kernel_expr and the @generated _mapreduce_kernel! by @inline functions that recurse over the dimensions, following the idea of _stridedloop in QuantumKitHub/TensorKit.jl#626. Each level of the recursion loops over the last dimension and calls itself for the remaining ones; the base case runs the innermost loop.

The kernel keeps its name, signature and the variants of the generated kernel:

  • any number of arrays;
  • a unit-stride variant of the innermost loop, selected once at the top (for map) or per innermost loop (for reductions);
  • for reductions, accumulation in a register when the output has stride zero along the innermost loop, with a unit-stride variant of that loop;
  • initop on the first visit of each output block, along dimensions with a nonzero output stride;
  • the blocked kernel, with the block loops built by the same recursion, and the unblocked kernel for small inputs.

The loop bodies are passed to the recursion as @inline closures. Without the @inline, every iteration of the outer loops calls the closure, with a GC frame for the captured arrays, which made small reductions 50% slower; with it, the kernel compiles to a single function without calls, as before.

src/mapreduce.jl: 139 lines added, 269 removed. Run times are on par with the generated kernel, compilation is 15–30% faster; see the comment below for benchmarks.

🤖 Generated with Claude Code

Replaces `_mapreduce_kernel_expr` and the `@generated _mapreduce_kernel!` by
`@inline` functions that recurse over the dimensions, similar to
`_stridedloop` in TensorKit.jl. The loops and their variants are the same:
unit strides in the innermost loop, accumulation in a register for
reductions, `initop` on the first visit of each output block, and blocking.
The loop bodies are passed as `@inline` closures, so that the kernel still
compiles to a single function.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Jutho

Jutho commented Nov 29, 2026

Copy link
Copy Markdown
Member Author

Benchmarks of the generated kernel (#104 at eee0c43) against the recursive kernel (this PR at a41e609).

Apple M4 Max, Julia 1.13.1, StridedViews 0.5.8. Minimum times. Each version ran twice, interleaved, in separate processes; the cases marked † are bimodal across processes for both versions (for example copy! 1000×1000 takes either 84 or 118 µs), and were rerun three more times per version, so their numbers are the minimum over all five runs.

Run time, single-threaded

case generated recursive ratio
permutedims! n=2, p=(3,4,1,2) 16.2 ns 15.8 ns 0.97
permutedims! n=4, p=(3,4,1,2) † 84.6 ns 80.8 ns 0.96
permutedims! n=8, p=(3,4,1,2) 977.9 ns 977.5 ns 1.00
copy! 2×2 5.8 ns 6.2 ns 1.07
C .= A .+ 2 .* B 4×4 † 8.3 ns 9.6 ns 1.16
sum over dims=2, 8×8 32.5 ns 30.8 ns 0.95
C .= A .* B .+ D 32×32 127.9 ns 127.9 ns 1.00
copy!(C, conj(A)) ComplexF64 16×16 † 62.5 ns 63.3 ns 1.01
permutedims! n=16, p=(3,4,1,2) 18.2 µs 18.5 µs 1.02
permutedims! n=16, p=(4,3,2,1) † 28.2 µs 30.1 µs 1.07
permutedims! n=32, p=(3,4,1,2) 503.5 µs 502.2 µs 1.00
permutedims! n=32, p=(4,3,2,1) 709.2 µs 725.2 µs 1.02
copy!(C, A) 1000×1000 † 83.9 µs 83.6 µs 1.00
copy!(C, transpose(A)) 1000×1000 288.1 µs 259.5 µs 0.90
C .= A .+ 2 .* transpose(B) 1000×1000 408.0 µs 364.7 µs 0.89
sum(A) 1000×1000 69.6 µs 69.5 µs 1.00
sum over dims=1, 1000×1000 67.9 µs 68.0 µs 1.00
sum over dims=2, 1000×1000 112.1 µs 111.2 µs 0.99
sum over dims=(1,3), 64^4 3.42 ms 3.60 ms 1.05
mul!(C, A, B, 2, 3) Int 200×200 (native kernel, with initop) 2.81 ms 2.75 ms 0.98
mul!(C, A, conj(B)) ComplexF64 300×300 (native kernel) 14.31 ms 11.98 ms 0.84

The small broadcast is the only case that is consistently slower, by 0.5–1 ns. For permutedims! n=16, p=(4,3,2,1), the runs of both versions spread from 28 to 40 µs, so the 7% is within the noise.

Run time, 4 threads (no reruns)

case generated recursive ratio
permutedims! n=16, p=(3,4,1,2) 10.8 µs 11.5 µs 1.07
permutedims! n=16, p=(4,3,2,1) 17.2 µs 20.3 µs 1.18
permutedims! n=32, p=(3,4,1,2) 147.6 µs 148.8 µs 1.01
permutedims! n=32, p=(4,3,2,1) 212.9 µs 211.3 µs 0.99
copy!(C, transpose(A)) 1000×1000 77.1 µs 78.0 µs 1.01
C .= A .+ 2 .* transpose(B) 1000×1000 112.0 µs 104.8 µs 0.94
sum(A) 1000×1000 21.3 µs 21.2 µs 1.00
sum over dims=(1,3), 64^4 887.8 µs 960.0 µs 1.08
mul!(C, A, conj(B)) ComplexF64 300×300 (native kernel) 7.29 ms 6.22 ms 0.85

Small inputs do not use threads and give the same results as single-threaded.

Compilation: time of the first call in a fresh process, median of three

case generated recursive ratio
map! with 2 arrays, 4D, small 304 ms 240 ms 0.79
map! with 4 arrays, 5D, small 467 ms 322 ms 0.69
permutedims! 6D, large 369 ms 277 ms 0.75
mapreducedim! 4D, large 197 ms 165 ms 0.84

The local test suite also finishes faster: the CPU tests with 1 and 5 threads take 4m49s with the recursive kernel and 5m35s with the generated one, mostly because of compilation.

🤖 Generated with Claude Code

@codecov

codecov Bot commented Nov 30, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.82353% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/mapreduce.jl 98.82% 1 Missing ⚠️
Files with missing lines Coverage Δ
src/mapreduce.jl 95.11% <98.82%> (+0.56%) ⬆️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@lkdvos lkdvos left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From the benchmarks I am concluding that performance is more or less unchanged (and probably depends on architecture/compiler version), so given that I think this is way easier to follow and fewer lines of code, I am overall very happy with this change!

I'm somewhat surprised that the compiler also seems to prefer this version, and compilation is a bit faster as well 🎉

One thing that I had wanted to play around with additionally is to see if we could further reduce the compilation time for large values of N by e.g. only inlining the loops up to N = 4, and accepting the function call overhead beyond that. This obviously requires some more measurements to see if that is a viable strategy, but there must be some cutoff where the compiler can't really do anything more with the nested loops and where the function call overhead far outweighs the compilation cost?

Otherwise the same comments as with the previous PR, it would be nice to tell Claude to reduce some of the comment prose, either writing some proper docstrings or just getting rid of them seems better than explaining things that are really just clear from reading the code.

Comment thread src/mapreduce.jl
# applies `initop` to the entries of `A1` in a block of size `dims`, visiting every entry
# once: dimensions along which `A1` has stride zero are not looped over
@inline function _initloops!(initop::IOP, A1, dims, s1, i1::Int) where {IOP}
dims′ = map((d, s) -> ifelse(iszero(s), 1, d), dims, s1)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
dims′ = map((d, s) -> ifelse(iszero(s), 1, d), dims, s1)
isnothing(initop) && return nothing
dims′ = map((d, s) -> ifelse(iszero(s), 1, d), dims, s1)

I think we can capture the initop === nothing case here, which avoids the if branches in the callers, making them slightly easier to read

Comment thread src/mapreduce.jl
_loops!(@inline((n, s, I) -> _innerinit!(initop, A1, n, s[1], I[1])), dims′, map(tuple, s1), (i1,))
return nothing
end
@inline function _innerinit!(initop::IOP, A1, n::Int, s::Int, i::Int) where {IOP}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this function is only used above, and since everything is inlined anyways, can we not just manually inline this one? Claude does sometimes have a tendency to create helper functions for everything, and if there are no performance benefits here I'd say it is easier to just read the code without the helper

Comment thread src/mapreduce.jl
A1, As = arrays[1], tail(arrays)
@simd for _ in Base.OneTo(n)
@inbounds A1[ParentIndex(I[1])] = f(_args(As, tail(I))...)
I = _step(I, s)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we also want/need an explicit stride-1 version here, or does this auto-vectorize?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

never mind, just saw that this is handled through dispatch. Can we do the same for the _innerreduce!? I think I got confused because there the stride-1 version is explicit, while here it is implicit.

Comment thread src/mapreduce.jl
end
@inline _step(I, s) = map(+, I, s)
@inline _step(I, ::Val{1}) = map(i -> i + 1, I)
@inline _args(arrays, I) = map((a, i) -> @inbounds(a[ParentIndex(i)]), arrays, I)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is always used in combination with the function call, it might make sense to just have

@inline apply_f(f, arrays, I) = f(_args(arrays, I)...)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants