Repository navigation
fix(cuda): write reductions through the output dtype - #3185
Merged
inureyes merged 2 commits intoNov 22, 2026
Merged
Conversation
The CUDA reduce overlay (bf16 accumulation in fp32) took the output pointer and the kernels' output type from the input type. MLX gives sum and prod over bool and the narrow integers a 32-bit output, and any and all a bool output whatever the input is, so those reductions wrote elements of the wrong size: sum(x > 0) over the rows of a 3 x 4 mask with 3, 0 and 2 true entries returned [65537, 0, 0], and any(float32) wrote four bytes per bool. ReduceOutput<Op, T> names the type a reduction writes: the accumulation type, as upstream, except the bf16 Sum and Prod the overlay exists for, which still write bf16. The row, column, all and init reductions take the output pointer from it.
12 of 18 tasks
…oint Extends the output-dtype tests to shapes that reach the row, column and all-reduce kernels at each of their size thresholds, to reductions over several non-adjacent axes at once (through a test-only bridge entry point, since the Rust API reduces one axis at a time), to int64 any/all, to a product over an empty axis, and to a bf16 sum, which stays bf16 by design. The cases that need native half-precision reductions are skipped on Metal. Corrects the overlay comments: before the fix any/all over a multi-byte input wrote past the one-byte bool output, not only the wrong values.
This was referenced Nov 20, 2026
Member
Hardening reviewReviewed against #3184. No changes pushed. Findings
Validation
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
On CUDA, reductions whose output dtype is not their input dtype (
sum/prodoverbooland the narrow integers,any/allover a non-bool input) returned garbage, because the reduce overlay took the output pointer from the input type. The dispatch code now takes it from aReduceOutput<Op, T>trait: the accumulation type, as upstream MLX, except for the bf16Sum/Prodthe overlay exists for, which still write bf16. Fourmla::turbo_latenttests that fail onmainon a GB10 pass again.Related issues
Closes #3184.
Type of change
fix— bug fixCause
The overlay under
src/lib/mlxcelverse/overlays/cuda/mlx/backend/cuda/reduce/added an output type parameterVto the reduce kernels so a bf16 sum can accumulate in fp32 and still write bf16, and its dispatch code passesT(the input type) forV, withgpu_ptr<T>(out). Its comments say why: "Output type is T (matches input dtype = out.dtype())". That does not hold when MLX gives the output another dtype:int32for a sum overbool,uint32for a sum overuint8,boolforany(float32). The kernel then writessizeof(T)bytes per element into an output of another element size: too few for a sum over a narrow input, and forany/allover a multi-byte input more than the one-bytebooloutput holds, so it also writes past the end of the output buffer. Upstream MLX writes the accumulation typeU = ReduceResult<Op, T>, which is the output dtype in exactly those cases.Change
reduce_ops.cuh:ReduceOutput<Op, T>, the type a reduction writes. It isReduceResult<Op, T>::type(upstream's behaviour) with two specializations,SumandProdover__nv_bfloat16, which keep bf16 (the overlay's behaviour).row_reduce.cu,col_reduce.cu,all_reduce.cu: every final write usesV = ReduceOutput<OP, T>::typefor the kernel's output type andgpu_ptr<V>(out). The two-pass intermediates were already written asUand are unchanged.init_reduce.cu(empty-input reductions): the kernel's output parameter isVand the init value is cast to it.Vis the input type as before, or for a 32-bit integer sum the same-widthint32_tupstream uses, so the bytes written do not change. bf16 keeps its fp32 accumulation and bf16 output.reduce_axes_probe_for_testreduces over several axes in one call, because the Rust API reduces one axis at a time and so never reached the multi-axis row reduction. The overlay comments are corrected (they still described the old write). No kernel code changes in it.Before / after
GB10 (sm_121, CUDA 13.0),
mlxcel-corelib tests,--profile test-fast --features cuda. "Before" is this branch with only the overlay directory checked out from363a0ba6b(main), so the new tests run against the old kernels.reduce_output_dtype_tests(new, 7 tests)mla::turbo_latent(7 tests)First failures on the old overlay:
sum(bool) all [3, 4]: left [1.0], right [5.0];sum(uint8) all [3, 4]: left [1084227600.0], right [13.0];any(float32) all [3, 4]: left [0.0], right [1.0];all(f32) over an empty axis: left [0.0, 0.0, 128.0], right [1.0, 1.0, 1.0].Test plan
Run on a DGX Spark (GB10). The PR is two commits on
363a0ba6b: the fix (tree2ca117fb6fa6) and the added coverage (treef70e1c1e4329). Every line below was run on the second tree unless it says otherwise.cargo fmt --all -- --checkcargo clippy --workspace --all-targets --features cuda -- -D warningscargo build --release --features cudasrc/lib/mlxcel-core/src/reduce_output_dtype_tests.rs, seven tests. Each case runs on the default device and on the CPU stream and must agree exactly in dtype, shape and values; mask counts are also checked against a host count. Shapes[3, 4],[8, 32],[24, 16],[5, 300],[300, 5],[1025, 8],[64, 4096],[7, 33, 65]and[2, 3, 4, 5], chosen to reach the row, column and all-reduce kernels on both sides of their size thresholds, every axis, with and withoutkeepdims, plus the all-elements forms, reductions over several axes at once (adjacent and not, up to[40, 3, 40, 4]), and sums and products over an empty axis. Inputs:bool;uint8,uint16,int8,int16;float32,float16,bfloat16,int32,int64forany/all; same-dtypefloat32/bfloat16sums and amaxas controls; and a bf16 sum that must stay bf16. The half-precision cases are skipped on Metal (cfg!(feature = "metal")), which I could not runcargo test -p mlxcel-core --profile test-fast --lib, nocudafeature): passcargo test -p mlxcel-core --profile test-fast --features cuda --lib -- --test-threads=1: 2400 passed, 0 failedmake verify-test-cuda(cargo test --workspace --profile test-fast --features cuda --no-fail-fast -- --test-threads=1): 16098 passed, 1 failed, 500 ignored. The failure iscommands::serve::tests::serve_preflight_kv_mode_on_deepseek_v2_follows_the_absorption_decision(left: Int8, right: Fp16), which fails the same way on unmodified363a0ba6band does not involve a reduction as far as I can tell; I noted it in the issue and did not touch it. Onmainthe same gate has five failures on this host (this one and the fourturbo_latenttests)mainand the first commit answer byte for byte the same on 21 runs (not repeated for the second commit, which changes no kernel code): two text prompts each on gemma-3-270m-it-4bit, gemma-3-4b-it-4bit, Qwen/Qwen3-0.6B, mgoin/Qwen3-0.6B-NVFP4, iromu/Gemma3-1B-tools-NVFP4, axteam/Qwen3.5-0.8B-NVFP4, axteam/Qwen3.5-0.8B-FP8-dynamic, axteam/gemma-4-E2B-it-NVFP4 and mlx-community/Qwen3.5-35B-A3B-4bit, and an image prompt on Qwen2.5-VL-3B-Instruct-4bit, Qwen3-VL-4B-Instruct-4bit and nvidia/Qwen2.5-VL-7B-Instruct-NVFP4ci.ymljobs a fork PR does not get, by hand:clippy(cargo clippy -p mlxcel --lib --tests -- -D warnings, default features); license headers, env-var docs, kernel dtype keys, kernel port dispatch, cross-repo refsxla-compile: not run (no IREE on this host); no XLA file is touchedcargo deny check: not applicable (no manifest or lockfile change)Notes for reviewers
out.dtype(). A seconddispatch_all_typeswould instantiate every kernel for every input and output type pair. MLX fixes the output dtype from the op and the input dtype, and upstream's kernels already encode that pairing inReduceResult, so one static trait is enough and adds no kernel instantiations beyond the changed ones.ReduceResult<Sum, uint8>isint32_twhile MLX's output dtype isuint32; the kernel writes the same 32 bits either way, as upstream does. The tests compare narrow-integer sums against the CPU for that reason.any/allcallers reduce abool(fromisfiniteor a comparison), which was never affected. I did not audit every caller. The Turbo-4 latent codec is the one user I know to be hit.fc344c98): upstream writesgpu_ptr<U>(out)at every one of these sites, which is whatReduceOutputgives outside the two bf16 specializations.Checklist
docs/: not needed (no option or documented behaviour changes)// Used by: ...comments: not applicable (no shared Rust function changed)