Skip to content

Split the scatter max/min gradient evenly between tied values - #937

Merged
CarloLucibello merged 4 commits into
FluxML:masterfrom
parth-patel010:fix/scatter-maxmin-ties
Dec 2, 2026
Merged

CarloLucibello merged 4 commits into
FluxML:masterfrom
parth-patel010:fix/scatter-maxmin-ties

Conversation

@parth-patel010

@parth-patel010 parth-patel010 commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #922.

The pullback of scatter(max, ...) / scatter(min, ...) was a plain equality mask, (src .== gather(dst, idx)) .* gather(Δ, idx). When several sources tie for the extremum of a destination, each of them got the full cotangent, so with n tied sources the gradient of that destination was counted n times and no longer matched the function. scatter! did the same between the old dst value and the sources.

This PR splits the cotangent of each destination evenly between the values tied for its extremum, which is what PyTorch's scatter_reduce does for amax / amin, and also what NNlib's Mooncake rule for scatter(max/min) already does (_scatter_extremum_grads! in ext/NNlibMooncakeExt/rules.jl). So the Zygote/ChainRules path now agrees with it. Without ties nothing changes.

Change

In src/scatter.jl:

  • extremum_ties(dst, src, idx, start_tied) returns the tie mask src .== gather(dst, idx) and the number of tied values per destination (Int32 counts, as in the mean gradient, for backends without 64-bit atomics), both from one pass over src. On the CPU that's a loop. On GPU arrays it's a KernelAbstractions kernel (_count_ties!) that writes the mask and has only the tied sources issue the atomic add, through _atomic_scatter!, so Metal keeps its special case. It is @non_differentiable, so the mutation stays out of nested AD (e.g. Zygote over Zygote).
  • The cotangent of each destination is divided once by its count (tie_share, where a count of 0 for a destination no index reaches, or a NaN one, divides by 1). Floats narrower than 32 bits divide in Float32 and round back, so more than floatmax(Float16) ties don't overflow. Then ∂src = tied .* gather(share, idx).
  • scatter(op, src, idx; init): init competes for the extremum, so when it ties with the sources it counts as one more (it has no gradient of its own here, as before). Other ops ignore init, as before.
  • scatter!: the old dst value is counted in the same group as its sources, and ∂dst = kept .* share with kept = dst_old .== dst. The new ∇scatter! computes the mask, counts and shares once for both cotangents.
  • The Enzyme rule computes kept, the tie mask and the counts once before the loop over lanes; each lane divides its seed once per destination.
  • The scatter docstring states the tie rule. The comment above the Mooncake rule said ChainRules gives every tied source the full cotangent; I updated it.

Example

using NNlib, Zygote
f(x) = sum(NNlib.scatter(max, x, [1, 1, 2]))
x0 = Float32[2, 2, 3]; h = 1f-2
Zygote.gradient(f, x0)[1]
(f(x0 .+ h) - f(x0)) / h, sum(Zygote.gradient(f, x0)[1])
call master (d1f3bff) this PR
gradient(f, Float32[2, 2, 3]) Float32[1.0, 1.0, 1.0] Float32[0.5, 0.5, 1.0]
gradient(x -> sum(scatter(min, x, [1, 1, 1])), Float32[0, 0, 0]) Float32[1.0, 1.0, 1.0] Float32[0.33333334, 0.33333334, 0.33333334]
(f(x0 .+ h) - f(x0)) / h, sum(gradient) (1.9999981f0, 3.0f0) (1.9999981f0, 2.0f0)
scatter!(max, ...), dst [2, 0], src [2, 1], idx [1, 1]: (∂dst, ∂src) (Float32[1.0, 1.0], Float32[1.0, 0.0]) (Float32[0.5, 1.0], Float32[0.5, 0.0])
scatter(max, x, [1, 1, 2]; init = 2f0) at [2, 2, 3] Float32[1.0, 1.0, 1.0] Float32[0.33333334, 0.33333334, 1.0]
2-row x = [1 1 5 1; 2 3 3 3], idx [1, 1, 2, 1] Float32[1.0 1.0 1.0 1.0; 0.0 1.0 1.0 1.0] Float32[0.33333334 0.33333334 1.0 0.33333334; 0.0 0.5 1.0 0.5]
random 3×6 input, no ties: same as the old mask true true

Tests

In test/common_testsuite/scatter.jl:

  • A new "∂ with ties" testset for max and min: two and three tied sources, a 2-row source where each destination's gradient has to add up to its cotangent, a weighted loss, init tying with the sources, and scatter! with the old dst tied with one or more sources (and not tied). On the CPU it also checks 70,000 tied Float16 sources (each gets 1/70000), and, for max, Zygote over Zygote with and without a tie.
  • In test/gpu/cuda/scatter.jl: the 70,000-tie check for Float16 and BFloat16 on CUDA (Metal has no atomic max for Float16, so it isn't in the common suite on GPUs).
  • In the existing finite-difference "∂src" loop, the max / min sources are now made distinct. A finite difference that moves one element at a time can't see a shared gradient at a tie (it sees 1/2 one-sided), so the ties are covered by the testset above instead.

On master the new tie tests fail with the values in the master column. With this PR, common_testsuite/scatter (CPU) (including the Enzyme comparisons) passes, 4272/4272, on Julia 1.13.3. I don't have a GPU, so I ran the GPU code path (the kernel, mask and counts) with JLArrays against the CPU loop for integer, tuple and CartesianIndex indices, but not CUDA or Metal.

@CarloLucibello

Copy link
Copy Markdown
Member

Equal sharing is a reasonable policy and matches Mooncake's allocating rule. The current implementation has two correctness regressions and makes the common case without ties substantially slower.

  • With 70,000 tied Float16 inputs in one destination, the gradient is all zeros on CPU and CUDA. Division converts the Int32 count to Float16, where it overflows. Divide in Float32 for half-precision cotangents and round back after division. Count and division
  • Nested Zygote now errors on the count mutation even without ties. For f(x) = sum(abs2, NNlib.scatter(max, x, [1, 1, 2])), differentiating x -> sum(only(Zygote.gradient(f, x))) at Float32[2, 1, 3] returned [2, 0, 2] on master. Marking tie counting non-differentiable restored that result. Count mutation
  • Compute the counts once for both scatter! cotangents and share them across Enzyme lanes. Divide once per destination and issue GPU atomics only for winners. In an RTX 5090 case with 32 rows, 65,536 sources and 128 destinations, the in-place pullback went from 21.6 to 90.4 µs. A CUDA prototype that shares counts, divides once per destination, and counts only winners took 24.5 µs and also returned the expected shares for the large Float16 tie. In-place pullback

🧔‍♂️🤖 Assisted by GPT-6

…em, divide once per destination in Float32 for half precision
@parth-patel010

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review, @CarloLucibello. I've addressed all three points, now with a test for each regression:

Float16 count overflow. The cotangent of each destination is divided by its tie count with tie_share(δ, c). Floats narrower than 32 bits divide in Float32 and round back, so a count above floatmax(Float16) no longer becomes Inf. New test: 70,000 tied Float16 sources all get Float16(1/70_000).

Nested Zygote. The tie counting (extremum_tie_counts, scatter!_tie_counts) is @non_differentiable, so its mutation never reaches the outer AD. New test: your example and its min analogue, plus a tied input.

One count, one division, atomics only for winners.

  • The counts don't depend on the seed. The scatter! rrule goes through a new ∇scatter! that computes them once and divides once per destination (share = Δ ./ counts, sized like dst). It then builds both cotangents from share: kept .* share for dst, and the tied mask times gather(share, idx) for src.
  • The Enzyme reverse rule computes the counts once before the lane loop and passes them to ∇scatter!_dst/∇scatter!_src. Both take them as an optional last argument.
  • Counting no longer scatters a full Int32.(tied) array. On the CPU it's a loop. On GPU arrays it's a small KernelAbstractions kernel (_count_ties!), where only a source equal to its destination's extremum issues the atomic add, through _atomic_scatter!, so Metal keeps its special case.

Your examples, run locally on CPU:

                                    master                PR before (a045959)          now
70_000 tied Float16, gradient       1.0 each (sum 70000)  0.0 each                     1.43e-5 each (sum ≈ 1.0014)
nested Zygote at Float32[2, 1, 3]   [2, 0, 2]             error: Mutating arrays ...   [2, 0, 2]
nested Zygote at Float32[2, 2, 3]   [4, 4, 2]             error                        [1, 1, 2]

In-place scatter!(max) pullback, 32 rows, 65,536 sources, 128 destinations, no ties (BenchmarkTools median on a shared box, so somewhat noisy):

                      scatter! pullback          scatter pullback
master                7.78 ms, 24.0 MiB          5.64 ms, 24.0 MiB
PR before (a045959)   18.76 ms, 56.6 MiB         12.09 ms, 40.3 MiB
now                   7.62 ms, 24.1 MiB          6.14 ms, 24.0 MiB

I don't have a GPU, so I couldn't reproduce your RTX 5090 timing or run the CUDA tests. The CUDA scatter suite is skipped in runtests.jl anyway. To exercise the new kernel, I added a test that runs _count_ties! on KernelAbstractions' CPU backend and checks it against the loop, for integer, column, and tuple indices. common_testsuite/scatter (CPU, including the Enzyme comparisons) passes with 4280/4280, and so does common_testsuite/mooncake (CPU) with 8982/8982.

@CarloLucibello

Copy link
Copy Markdown
Member

Both correctness points are fixed on CPU and CUDA: 70,000 tied Float16 (and BFloat16) sources each get 1/70000, and nested Zygote gives [2, 0, 2] and [1, 1, 2]. Zygote, Enzyme and Mooncake agree on ties, including init and scatter!, and test/gpu/cuda/scatter.jl passes. Remaining points:

  • Without ties, the GPU pullback is still about 1.6× master. RTX 5090, 32 rows, 65,536 sources, 128 destinations, Float32: in-place 21.0 µs on master and 34.2 µs here, out-of-place 19.8 and 31.3 µs (at 128 rows, 262,144 sources and 1,024 destinations: 594 and 790 µs). _count_ties! is an extra pass over src (9.4 µs of device time), and ∇extremum_src then compares src .== gather(dst, idx) again. If the counting kernel also writes the tie mask, ∂src is tied .* gather(share, idx) with no second comparison. A prototype gave the same outputs in 25.9 µs (537 µs at the larger size, faster than master):
    @kernel function _count_ties!(counts, tied, dst, src, idxs, dim_ids, max_dims_idx::Int)
        i = @index(Global)
        j, k = divrem(i - 1, max_dims_idx)
        @inbounds idx = (Tuple(dim_ids[k + 1])..., Tuple(_convert_i64(idxs[j + 1]))...)
        @inbounds t = tied[i] = src[i] == dst[idx...]
        t && _atomic_scatter!(counts, idx, +, one(eltype(counts)))
    end
    # share = tie_share.(Δ, counts), with max(c, 1) folded into tie_share
    # ∂dst, ∂src = kept .* share, tied .* gather(share, idx)
    With the counts and the mask computed together, the optional counts arguments and scatter!_tie_counts can go. Counting, pullbacks
  • The 70,000-tie Float16 test will fail on Metal. It runs in the common suite on every backend, and gsum moves the input to the device, so the forward scatter(max, ::MtlArray{Float16}) goes through Metal.@atomic, whose compare-and-swap fallback only exists for Int32, UInt32 and Float32. Elsewhere the common suite tests GPU scatter(max) only with Int32 and Float32. Please run it on the CPU only, and add it to test/gpu/cuda/scatter.jl, where it passes. Test
  • Enzyme rule: each lane still divides twice and recomputes dst_old .== dst. With the mask, compute kept, tied and the counts once before the lane loop; each lane is then share = tie_share.(ddst, counts); dsrc .+= tied .* gather(share, idx); ddst .= kept .* share. Enzyme rule
  • Test cost: the new testsets add about 24 s, 13 s of it the first Zygote-over-Zygote compile. Keep the nested check for max only (AGENTS.md: second derivatives for a representative only). Optional: once Buildkite runs, test/gpu/cuda/scatter.jl covers the kernel on a GPU, and the "tie counts kernel" testset (KernelAbstractions' CPU backend, PoCL on KA 0.10) can go.
  • The PR description still says counting scatter-adds the mask and that the change uses only broadcasts, gather and scatter!(+). The scatter docstring could state the tie rule in one line.

Please also merge master: the Buildkite PR relay check reports that the workflow files differ from master, so no GPU CI has run on this PR yet.

🧔‍♂️🤖 Assisted by Claude Sonnet 5.5

@parth-patel010

Copy link
Copy Markdown
Contributor Author

Thanks, @CarloLucibello, the combined kernel is a nice simplification. Pushed cc182a7 (plus a merge of master for the Buildkite relay):

  • _count_ties! now writes the tie mask while counting, as in your prototype. extremum_ties returns the mask and the counts from one pass over src (a loop on the CPU, the kernel on GPU arrays) and is @non_differentiable.
  • max(c, 1) is folded into tie_share, and the cotangents are ∂dst = kept .* share and ∂src = tied .* gather(share, idx), with no second comparison. The optional counts arguments, scatter!_tie_counts and ∇extremum_src are gone.
  • Enzyme rule: kept, tied and the counts are computed once before the lane loop; each lane does share = tie_share.(ddst, counts), dsrc .+= tied .* gather(share, idx), ddst .= kept .* share.
  • Tests: the 70,000-tie Float16 check runs on the CPU only in the common suite, and test/gpu/cuda/scatter.jl has it for Float16 and BFloat16, max and min. The nested Zygote check is max only, and the "tie counts kernel" testset is removed.
  • The scatter docstring states the tie rule, and I've updated the PR description.

Pullback without ties, CPU, BenchmarkTools medians (shared box, so noisy; master's first number was 7.8 ms in my last run):

                                   master               PR
32 × 65,536 → 128      scatter!    11.17 ms, 24.0 MiB   6.72 ms, 18.1 MiB
                       scatter      6.28 ms, 24.0 MiB   4.05 ms, 18.0 MiB
128 × 262,144 → 1,024  scatter!   272.6 ms, 384.5 MiB  172.6 ms, 289.5 MiB
                       scatter    254.2 ms, 384.0 MiB  178.6 ms, 289.0 MiB

common_testsuite/scatter (CPU, including the Enzyme comparisons) passes, 4272/4272. I don't have a GPU, so CUDA and Metal aren't run locally. To exercise the kernel anyway, I ran the gradients, scatter! gradients, mask and counts through JLArrays against the CPU loop for integer, tuple and CartesianIndex indices, and they match (40/40).

@CarloLucibello
CarloLucibello merged commit fc246ae into FluxML:master Dec 2, 2026
20 of 22 checks passed
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.

scatter(max/min) gradient counts tied sources more than once

2 participants