Skip to content

fix(cuda): write reductions through the output dtype - #3185

Merged
inureyes merged 2 commits into
lablup:mainfrom
Jaeyeong-CHOI:fix/cuda-reduce-output-dtype
Nov 22, 2026
Merged

inureyes merged 2 commits into
lablup:mainfrom
Jaeyeong-CHOI:fix/cuda-reduce-output-dtype

Conversation

@Jaeyeong-CHOI

@Jaeyeong-CHOI Jaeyeong-CHOI commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

On CUDA, reductions whose output dtype is not their input dtype (sum / prod over bool and the narrow integers, any / all over 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 a ReduceOutput<Op, T> trait: the accumulation type, as upstream MLX, except for the bf16 Sum / Prod the overlay exists for, which still write bf16. Four mla::turbo_latent tests that fail on main on a GB10 pass again.

Related issues

Closes #3184.

Type of change

  • fix — bug fix

Cause

The overlay under src/lib/mlxcelverse/overlays/cuda/mlx/backend/cuda/reduce/ added an output type parameter V to the reduce kernels so a bf16 sum can accumulate in fp32 and still write bf16, and its dispatch code passes T (the input type) for V, with gpu_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: int32 for a sum over bool, uint32 for a sum over uint8, bool for any(float32). The kernel then writes sizeof(T) bytes per element into an output of another element size: too few for a sum over a narrow input, and for any / all over a multi-byte input more than the one-byte bool output holds, so it also writes past the end of the output buffer. Upstream MLX writes the accumulation type U = 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 is ReduceResult<Op, T>::type (upstream's behaviour) with two specializations, Sum and Prod over __nv_bfloat16, which keep bf16 (the overlay's behaviour).
  • row_reduce.cu, col_reduce.cu, all_reduce.cu: every final write uses V = ReduceOutput<OP, T>::type for the kernel's output type and gpu_ptr<V>(out). The two-pass intermediates were already written as U and are unchanged.
  • init_reduce.cu (empty-input reductions): the kernel's output parameter is V and the init value is cast to it.
  • For a reduction whose output dtype is its input dtype, V is the input type as before, or for a 32-bit integer sum the same-width int32_t upstream uses, so the bytes written do not change. bf16 keeps its fp32 accumulation and bf16 output.
  • ROCm is not touched: its reduce overlay does not have this substitution.
  • Second commit (tests and comments only for the kernels). A test-only bridge entry point reduce_axes_probe_for_test reduces 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-core lib tests, --profile test-fast --features cuda. "Before" is this branch with only the overlay directory checked out from 363a0ba6b (main), so the new tests run against the old kernels.

old overlay this PR
reduce_output_dtype_tests (new, 7 tests) 5 fail, 2 pass (the same-dtype control and the bf16 sum) 7 pass
mla::turbo_latent (7 tests) 4 fail 7 pass

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 (tree 2ca117fb6fa6) and the added coverage (tree f70e1c1e4329). Every line below was run on the second tree unless it says otherwise.

  • cargo fmt --all -- --check
  • cargo clippy --workspace --all-targets --features cuda -- -D warnings
  • cargo build --release --features cuda
  • New src/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 without keepdims, 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, int64 for any / all; same-dtype float32 / bfloat16 sums and a max as controls; and a bf16 sum that must stay bf16. The half-precision cases are skipped on Metal (cfg!(feature = "metal")), which I could not run
  • The same seven tests on a CPU-only build (cargo test -p mlxcel-core --profile test-fast --lib, no cuda feature): pass
  • cargo test -p mlxcel-core --profile test-fast --features cuda --lib -- --test-threads=1: 2400 passed, 0 failed
  • make 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 is commands::serve::tests::serve_preflight_kv_mode_on_deepseek_v2_follows_the_absorption_decision (left: Int8, right: Fp16), which fails the same way on unmodified 363a0ba6b and does not involve a reduction as far as I can tell; I noted it in the issue and did not touch it. On main the same gate has five failures on this host (this one and the four turbo_latent tests)
  • Release builds of main and 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-NVFP4
  • Self-hosted ci.yml jobs 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 refs
  • xla-compile: not run (no IREE on this host); no XLA file is touched
  • cargo deny check: not applicable (no manifest or lockfile change)
  • Metal, ROCm and Windows CUDA: not built or run here. The overlay change is CUDA-only; the new tests are backend-independent and ran on CUDA and CPU
  • Other CUDA architectures than sm_121: not run

Notes for reviewers

  • Why a trait and not a dispatch on out.dtype(). A second dispatch_all_types would 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 in ReduceResult, so one static trait is enough and adds no kernel instantiations beyond the changed ones.
  • Integer widths. ReduceResult<Sum, uint8> is int32_t while MLX's output dtype is uint32; the kernel writes the same 32 bits either way, as upstream does. The tests compare narrow-integer sums against the CPU for that reason.
  • Reach in the tree. Most any / all callers reduce a bool (from isfinite or 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.
  • Compared with upstream. I diffed the overlay's reduce files against MLX at the pinned revision (fc344c98): upstream writes gpu_ptr<U>(out) at every one of these sites, which is what ReduceOutput gives outside the two bf16 specializations.
  • The overlay README describes the reduce files only as "reduce ops"; I left it. The header comments of the five files say what the dispatch code passes now.

Checklist

  • PR title uses a Conventional Commits prefix
  • One logical change per PR
  • Updated docs/: not needed (no option or documented behaviour changes)
  • Updated // Used by: ... comments: not applicable (no shared Rust function changed)

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.
…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.
@inureyes

Copy link
Copy Markdown
Member

Hardening review

Reviewed against #3184. No changes pushed.

Findings

  • Dispatch completeness: every final write in the overlay (row_reduce_simple, row_reduce_looped, col_reduce_small, col_reduce_looped, the col_reduce_two_pass second pass, both all_reduce passes, init_reduce) now takes its output pointer and kernel V from ReduceOutput<OP, T>. No gpu_ptr<T>(out) site is left. Two-pass intermediates stay U.
  • Intermediate dtype: in all_reduce and col_reduce_two_pass the intermediate is float32 only when U is float and T is not, which is the bf16 Sum/Prod case only; otherwise it is out.dtype(), whose element size equals sizeof(U) for every op and input (bool for And/Or, 32 bits for narrow-int Sum/Prod).
  • Accumulator precision: ReduceResult is unchanged, so bf16 Sum/Prod still accumulate in fp32 and write bf16, and fp16 stays fp16 as before.
  • Init values: init_reduce casts ReduceInit<Op, T> to V, giving 0/1 in int32 for Sum/Prod over bool and narrow ints, true/false for And/Or, limits of T for Min/Max, and fp32 0/1 cast to bf16 for the bf16 case. Correct for every op.
  • Overflow: narrow-int Sum/Prod accumulate in int32 as upstream does. uint32 output is written as int32 bits, the same as upstream.
  • Metal/CPU: the only change outside the CUDA overlay is the test-only bridge entry point reduce_axes_probe_for_test (Result-returning, throws on an unknown op), so non-CUDA runtime behaviour does not change.

Validation

  • cargo test -p mlxcel-core --profile test-fast --lib reduce_output_dtype_tests -- --test-threads=1 on Metal (Apple Silicon), with the branch merged locally onto current main: 7 passed.
  • CUDA runtime: not available on this host. I relied on the author's GB10 (sm_121) results in the PR body: the 7 new tests and the 4 mla::turbo_latent tests pass, and the full mlxcel-core CUDA lib run shows 2400 passed.
  • CI on the PR head: all checks that ran passed.

@inureyes
inureyes merged commit f92117b into lablup:main Nov 22, 2026
32 checks passed
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core mlxcel-core: MLX FFI, primitives, KV cache, layers platform:linux Linux (CUDA / packaging) specific priority:high High priority status:review Under review type:bug Bug fixes, error corrections, or issue resolutions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(cuda): reductions with a differing output dtype return garbage (sum over bool, any/all over non-bool)

2 participants