Repository navigation
feat: add redux.sync integer min/max/and/or/xor warp reductions (sm_80+) - #258
Merged
Merged
Conversation
Collaborator
|
Thanks for the PR. LGTM 👍🏾 Reviewer note: GPU-verified on RTX 5090 (sm_120). All seven ops produce correct results: signed min/max |
Signed-off-by: sunteng <[email protected]>
nihalpasham
force-pushed
the
feat/redux-sync-integer-family
branch
from
June 20, 2026 12:16
2e3b163 to
8afcfa0
Compare
This was referenced Jun 22, 2026
5 of 26 tasks
nihalpasham
pushed a commit
that referenced
this pull request
Aug 12, 2026
…ent (#813) Option 3 from #811. `warp_reduce` is generic over `T`, so a full warp always costs five shuffles plus five combines; `redux.sync` does an integer reduction in one instruction and cuda-oxide has exposed it since #223/#258. Nothing told a reader that, so the book taught the butterfly and stopped there. Measured on an A10G (sm_86), 1M threads x 64 full-warp u32 sum reductions, 30 timed launches after 5 warmup: 159.4 us per launch for the butterfly against 33.6 us for `redux.sync` -- 4.74x, bit-identical. Wrapping u32 addition is associative modulo 2^32 and min/max/and/or/xor are exact, so reduction order cannot change the answer. Both places a reader might look now say so: * the book's "Warp reduction" section gains a subsection naming all eight functions, the measurement, and the constraints; * `warp_reduce`'s own rustdoc carries a short performance note, since that is what someone about to call it reads. The scope of the number is stated in both: the probe kernel does almost nothing but reduce, so 4.74x sizes the primitive, not an application. A kernel reducing once after a memory-bound pass sees very little. Three constraints are spelled out rather than implied: integers only (there is no f32 redux before sm_100); a full converged 32-lane warp, which is the contract the shuffle reductions already require, with sub-warp tiles and short tails staying on shuffles; and that it will not assemble below sm_80, so the call needs gating the way the `redux_sum` example gates it. Also corrected "five instructions" to "five shuffle steps" in the sentence above, since the butterfly is five shuffles plus five combines and the new subsection counts instructions a few lines later. No API or codegen change: #811 stays open for making `warp_reduce` select this automatically, which needs device code to know its target architecture. This documents what is available today. Verified: `RUSTDOCFLAGS="-D warnings" cargo doc -p cuda-device` clean, so the intra-doc link resolves; `sphinx-build -W --keep-going` succeeds; all eight function names, `reduce_sum_f32_partial`, and the `redux_sum` capability gate checked against the source. Signed-off-by: Vyncint Ng <[email protected]>
meefs
pushed a commit
to meefs/cuda-oxide
that referenced
this pull request
Sep 30, 2026
…VIDIA#258) Soundness and correctness fixes from the 2026-09 code and documentation audit, plus the documentation corrections. The cuda-oxide `simt` surface and the VMM modules are in a separate PR. cuda-core / cuda-bindings - Device::load_module_from_bytes (and the cuda-async wrapper) are unsafe fn: cuModuleLoadData takes no length, so a truncated cubin reads past the slice. - Stream::launch_host_function{,_with_sync_mode} require F: 'static and reclaim the boxed closure when the enqueue fails. - Streams of borrowed devices never enter the process-wide stream pool; a later owned device could reuse a handle from a destroyed external context. - The async memory wrappers return Result instead of panicking; callers propagate, Drop impls ignore. get_device_attribute returns Err and api_version surfaces its CUresult. - Host copies build their Vec with Vec::with_capacity instead of a raw allocation that was never null-checked and could be zero-sized. - curand generators bind to the executing stream (RNG::set_stream, RNG::new_on_stream); random tensors no longer race the legacy default stream against stream-ordered allocation. - DType is an unsafe trait carrying the bit-validity contract; the foreign-borrow constructors state it. - The driver-unavailable hint is attached to CUDA_ERROR_NOT_INITIALIZED, the code the shims actually return; cu_launch_host_func falls back to cuLaunchHostFunc when the driver lacks the _v2 entry point; device ordinals that do not fit c_int are rejected. cuda-async - DeviceFuture has a Drop: an in-flight result is released only after the stream proves completion (idle: one query; busy: synchronize; capturing or faulted: leak loudly). Supersedes the approach in NVIDIA#179. - Execute-once ops (shared, unzip) use a mutex and condvar and give a consumer on another stream an event dependency on the producer; the manual Send/Sync impls over UnsafeCells are gone. - AsyncKernelLaunch frees its arguments with the type they were boxed as. - A device fault after registration resolves the future with the error instead of hanging it and spinning the reactor. - ExecutionContext::alloc_async returns Result; Tensor::uninitialized and the copy constructors surface a failed allocation as the operation's error so callers can retry instead of aborting. - The execution lock is an RAII guard, and then_unchecked really releases it for its closure. - GraphLaunch shares the instantiated graph through an Arc; CudaGraph::update is restricted to unit-output GraphNodes under the lock; capture ends the capture on panic and error; the thread-local device map survives failed init and lookups; the completion flag uses Release/Acquire. cutile / cutile-macro - Prelude reshape on an owned tensor validates the element count (it built shapes larger than their storage); .generics() overrides are checked against the tensors' element types; mutable partitions of &mut Tensor require unique storage; try_partition returns Err as documented. - api::memcpy borrows its tensors for the lifetime of the op. - atomic_rmw_tko and atomic_cas_tko are unsafe fn like load_ptr_tko and store_ptr_tko. - Generated launchers are GraphNodes only over GraphNode inputs, which needs a nameable argument op (KernelArgs, PrepareInput, PrepareOutput, implemented for up to 64 arguments); compile()/specialize() run under the execution lock and drain the stream; reshape and view use checked arithmetic; the trial log is keyed on source hash and tileiras fingerprint; #[cutile::entry] keys and literal kinds are validated at expansion and a bare boolean key means true; an unwritable dump dir fails the launch instead of panicking. cutile-compiler / cutile-ir - A return below the function body and a break inside for are spanned errors instead of silently falling through or producing IR the assembler rejects. The prefill GQA kernel's early-exit guards become one conditional. - Integer / rounds toward zero (Rust semantics); u8 and u16 are unsigned in every signedness-carrying op; && and || short-circuit. - Module-level consts resolve in the scope of the module that names them. - Bounds-check hoisting stays sound under continue, step_by and extents near i32::MAX; in-place checks test the actual index. - Bytecode floor 13.2 with loud version negotiation; print_tko encodes its token correctly; frontend panics on valid input are spanned errors; CUDA_HOME and targets/ layouts are honored at run time. Docs: tutorials and references match the code (signatures, imports, tile size types, deprecated APIs, dump stages, env vars, cache keys), the changelog leads with the 0.3.1 breaking changes and the 0.3.0 fallback, covers everything since 0.3.0, and stale claims in crate and module docs are corrected. The root README is unchanged. Verified on an RTX 5090 with CUDA 13.3: cargo fmt, cargo clippy --all-features with no new warnings, the CPU test script and the GPU test script; new regression tests cover every behavioral fix. Signed-off-by: Melih Elibol <[email protected]>
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.
Single-instruction warp integer reductions via
@llvm.nvvm.redux.sync.{umin,min,umax,max,and,or,xor}: device API, NVVM ops, MIR import dispatch, lowering with[mask,value] → [value,mask]flip, and convergent marking on export.Summary
Extends the
redux.syncfamily (built out by #223'sredux_sync_add) with the remaining integer reductions —min/max(signed and unsigned) and bitwiseand/or/xor— each a single-instruction warp-wide reduction (PTXredux.sync.*, sm_80+). Previously a 32-lane warp min/max/bitwise reduction needed 5×shfl+ 5×op; these lower to one hardware instruction.min/maxcome in signed (_i32) and unsigned (_u32) flavors because the comparison differs: e.g.min(0xFFFFFFFF, 0)is-1signed but0unsigned.and/or/xorare bitwise, so a singleu32form coversi32too.redux_sync_min_u32/redux_sync_min_i32redux.sync.umin/redux.sync.minredux.sync.min.{u32,s32}redux_sync_max_u32/redux_sync_max_i32redux.sync.umax/redux.sync.maxredux.sync.max.{u32,s32}redux_sync_and/redux_sync_or/redux_sync_xorredux.sync.{and,or,xor}redux.sync.{and,or,xor}.b32Changes
redux_sync_min_{u32,i32},redux_sync_max_{u32,i32},redux_sync_and/or/xor), mirroringredux_sync_add.ReduxSync{Umin,Min,Umax,Max,And,Or,Xor}Op; 2 operands[mask, value], 1 result) + register.emit_warp_redux+ 7 dispatch branches. Added asigned: boolparam so the signedmin.s32/max.s32variants produce aSignedi32 result that matches ani32destination slot (store_localrequires the types agree);add, unsigned min/max, and the bitwise ops stayUnsigned.convert_redux(same[mask,value] → [value,mask]flip — LLVM wants(src, membermask)); 7MirToLlvmConversionimpls forwarding the per-variant intrinsic name. Signedness is carried by the intrinsic name (uminvsmin), so the call stays signless i32.llvm.nvvm.redux.*convergent prefix already covers the whole family (warp collective — must not be hoisted into divergent branches).redux_minmaxe2e example (sm_80-gated) built so signed vs unsigned answers differ.Testing
Verified end-to-end on RTX 4080 SUPER (sm_89) — PTX emits
redux.sync.{min,max,and,or,xor}and every reduction is correct, with the signed/unsigned results provably distinct:cargo oxide run redux_minmaxpasses (sm_89)cargo oxide run redux_sumstill passes (sm_89) — no regression to feat: add redux.sync.add warp reduction (sm_80+) #223'sredux.sync.addcargo test -p dialect-nvvm -p llvm-exportpasses (op verify + convergent over all 7 names)cargo fmt --checkandcargo clippy --all-targetscleanredux_minmax)Checklist
git commit -s)cuda-bindings/modified