Skip to content

feat: add redux.sync integer min/max/and/or/xor warp reductions (sm_80+) - #258

Merged
nihalpasham merged 1 commit into
NVIDIA:mainfrom
goog00:feat/redux-sync-integer-family
Jun 20, 2026
Merged

nihalpasham merged 1 commit into
NVIDIA:mainfrom
goog00:feat/redux-sync-integer-family

Conversation

@goog00

@goog00 goog00 commented Jun 20, 2026

Copy link
Copy Markdown
Contributor

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.sync family (built out by #223's redux_sync_add) with the remaining integer reductions — min/max (signed and unsigned) and bitwise and/or/xor — each a single-instruction warp-wide reduction (PTX redux.sync.*, sm_80+). Previously a 32-lane warp min/max/bitwise reduction needed 5×shfl + 5×op; these lower to one hardware instruction.

min/max come in signed (_i32) and unsigned (_u32) flavors because the comparison differs: e.g. min(0xFFFFFFFF, 0) is -1 signed but 0 unsigned. and/or/xor are bitwise, so a single u32 form covers i32 too.

device API LLVM intrinsic PTX
redux_sync_min_u32 / redux_sync_min_i32 redux.sync.umin / redux.sync.min redux.sync.min.{u32,s32}
redux_sync_max_u32 / redux_sync_max_i32 redux.sync.umax / redux.sync.max redux.sync.max.{u32,s32}
redux_sync_and / redux_sync_or / redux_sync_xor redux.sync.{and,or,xor} redux.sync.{and,or,xor}.b32

Changes

  • cuda-device: 7 new device APIs (redux_sync_min_{u32,i32}, redux_sync_max_{u32,i32}, redux_sync_and/or/xor), mirroring redux_sync_add.
  • dialect-nvvm: 7 new ops (ReduxSync{Umin,Min,Umax,Max,And,Or,Xor}Op; 2 operands [mask, value], 1 result) + register.
  • mir-importer: reuse emit_warp_redux + 7 dispatch branches. Added a signed: bool param so the signed min.s32/max.s32 variants produce a Signed i32 result that matches an i32 destination slot (store_local requires the types agree); add, unsigned min/max, and the bitwise ops stay Unsigned.
  • mir-lower: reuse convert_redux (same [mask,value] → [value,mask] flip — LLVM wants (src, membermask)); 7 MirToLlvmConversion impls forwarding the per-variant intrinsic name. Signedness is carried by the intrinsic name (umin vs min), so the call stays signless i32.
  • llvm-export: no logic change — the existing llvm.nvvm.redux.* convergent prefix already covers the whole family (warp collective — must not be hoisted into divergent branches).
  • tests + example: op construct/verify for all 7 variants, convergent assertions for every redux name, and a new redux_minmax e2e 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:

GPU Compute Capability: sm_89
--- Test 1: redux.sync.min/max (signed vs unsigned) ---
signed   [min, max] = [-16, 15]        (expected [-16, 15])
unsigned [min, max] = [0, 4294967295] (expected [0, 4294967295])
✓ signed and unsigned min/max both correct (and distinct)
--- Test 2: redux.sync.and/or/xor ---
[and, or, xor] = [0x0, 0xffffffff, 0xffffffff]
expected       = [0x0, 0xffffffff, 0xffffffff]
✓ and/or/xor correct
SUCCESS: redux.sync integer family produced correct results
  • cargo oxide run redux_minmax passes (sm_89)
  • cargo oxide run redux_sum still passes (sm_89) — no regression to feat: add redux.sync.add warp reduction (sm_80+) #223's redux.sync.add
  • cargo test -p dialect-nvvm -p llvm-export passes (op verify + convergent over all 7 names)
  • cargo fmt --check and cargo clippy --all-targets clean
  • New example added (redux_minmax)

Checklist

  • All commits signed off (git commit -s)
  • No files under cuda-bindings/ modified
  • SPDX headers on new source files

@nihalpasham nihalpasham added enhancement New feature or request intrinsics Device intrinsics and libdevice math mappings codegen Device code-generation pipeline (Rust MIR to IR to PTX) labels Jun 20, 2026
@nihalpasham

Copy link
Copy Markdown
Collaborator

Thanks for the PR. LGTM 👍🏾

Reviewer note: GPU-verified on RTX 5090 (sm_120). All seven ops produce correct results: signed min/max [-16, 15], unsigned min/max [0, 4294967295], and bitwise and/or/xor [0x0, 0xffffffff, 0xffffffff]. The existing redux_sum example still passes; no regression from the signed: bool addition to emit_warp_redux.

@nihalpasham
nihalpasham force-pushed the feat/redux-sync-integer-family branch from 2e3b163 to 8afcfa0 Compare June 20, 2026 12:16
@nihalpasham
nihalpasham merged commit 1263bbc into NVIDIA:main Jun 20, 2026
47 of 67 checks passed
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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

codegen Device code-generation pipeline (Rust MIR to IR to PTX) enhancement New feature or request intrinsics Device intrinsics and libdevice math mappings

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants