Skip to content

Make the warp an index space, so a warp reduction writes safely - #655

Merged
nihalpasham merged 3 commits into
NVIDIA:mainfrom
alejandro-soto-franco:feat/warp-index-space
Aug 5, 2026
Merged

nihalpasham merged 3 commits into
NVIDIA:mainfrom
alejandro-soto-franco:feat/warp-index-space

Conversation

@alejandro-soto-franco

Copy link
Copy Markdown
Contributor

This issue asks first whether the warp case can be an ordinary ThreadIndex over a coarser index space rather than a new mechanism. It can, so no uniqueness witness of a new kind is introduced.

Closes #584.

The index space

WarpIndex has one element per warp. The witness is minted only for the lane that holds the completed reduction:

pub fn warp_index<'kernel>() -> Option<ThreadIndex<'kernel, WarpIndex>>

Some for lane 0 of each warp in a 1D launch, None for every other lane. A slice declared over the space accepts it through the ordinary get_mut, so the store is bounds-checked and needs no unsafe:

let total = warp::reduce_sum_f32(contribution);
if let Some(warp_slot) = thread::warp_index()
    && let Some(slot) = sums.get_mut(warp_slot)
{
    *slot = total;
}

Distinct warps get distinct indices and only one lane per warp holds a witness, so it is unique across the launch on the same terms as index_1d.

This also satisfies the rule #515 established. The witness is bound to the domain over which the invariant holds, which here is the slice type, not a per-call parameter that safe code could vary between calls.

Why not divide the global thread index

The index is built from the block and the lane. index_1d() / 32 differs whenever blockDim.x is not a multiple of the warp size, because the last warp of each block is then partial. At blockDim.x = 48, global indices 32 and 48 are both a lane 0 and both divide to 1, so two different warps would share a slot. The example below launches exactly that shape.

Design decisions

Chosen: a coarser index space reusing ThreadIndex and get_mut. Alternative rejected: a distinct uniqueness witness accepted wherever a thread index is accepted, which the issue sketches. It would need its own type, its own minting rules and a second accessor on the slice, to express what an index space already expresses.

Chosen: the scatter case stays unsafe, and get_unchecked_mut now says so. Alternative rejected: the bounds-checked unsafe write of #572. That a permutation is a bijection is a fact about buffer contents, so no device-side type can carry it, and a returned bool reads as a safety signal it is not.

Validation

RTX 5060 (sm_120), CUDA 13.3, via the new warp_sums example. 14 warps over 7 blocks of 48 threads, so every block has a partial second warp.

check result
warp sums against a host reference 0 absolute error
slots written every one, checked by value
safe against a raw twin equal bitwise across every warp

The raw twin derives the warp index by hand and stores through get_unchecked_mut, which is what such kernels write today.

The caveat

The cost, over 16384 warps and 50 timed runs:

kernel time
safe warp index 0.0095 ms
raw get_unchecked_mut 0.0094 ms

A ratio of 1.006. The proof and the bounds check together are within a percent of the unchecked store.

Five trybuild expectations are re-derived here. Adding a launch-contract impl changes the candidate list rustc prints in those errors, with no change to what they reject.

Gates

3286 workspace tests pass, cargo clippy --workspace --all-targets -- -D warnings clean, two device kernels verified against a host reference and against each other.

Closes NVIDIA#584.

The issue asks first whether the warp case can be an ordinary `ThreadIndex`
over a coarser index space rather than a new mechanism. It can, and that is
what this does, so no uniqueness witness of a new kind is introduced.

`WarpIndex` is an index space with one element per warp. `thread::warp_index`
mints the witness only for lane 0 of each warp in a 1D launch, and distinct
warps get distinct indices, so the witness is unique across the launch on the
same terms as `index_1d`. A slice declared over the space accepts it through
the ordinary `get_mut`, so the reduction's store is bounds-checked and needs no
`unsafe`, where it previously computed a warp index by hand and went through
`get_unchecked_mut`, losing the bounds check along with the proof.

This also satisfies the rule NVIDIA#515 established. The witness is bound to the
domain over which the invariant holds, which here is the slice type, not a
per-call parameter that safe code could vary between calls.

The index is built from the block and the lane rather than from
`index_1d() / 32`. Those differ whenever `blockDim.x` is not a multiple of the
warp size, because the last warp of each block is then partial and dividing the
global thread index gives two different warps the same value: at
`blockDim.x = 48`, global indices 32 and 48 are both a lane 0 and both divide
to 1. The example below launches exactly that shape.

The scatter case stays `unsafe`, and `get_unchecked_mut` now says so. That a
permutation is a bijection is a fact about buffer contents, so no device-side
type can carry it and both obligations remain the caller's. Those docs also
now point at this index space rather than presenting the escape hatch as the
only option, which is the issue's third question.

Validation, RTX 5060 (sm_120), CUDA 13.3, via the new `warp_sums` example:
- 14 warps over 7 blocks of 48 threads, so every block has a partial second
  warp, exactly the shape that defeats the divide-by-32 derivation.
- Warp sums match a host reference exactly, 0 absolute error, and every slot
  was written, checked by value rather than by inspection.
- The safe kernel and a raw twin that derives the warp index by hand and stores
  through `get_unchecked_mut` agree bitwise across every warp.
- 3286 workspace tests, clippy --all-targets -D warnings clean.
- Five trybuild expectations re-derived: adding a launch-contract impl changes
  the candidate list rustc prints, with no change to what they reject.

Cost against that raw twin, over 16384 warps and 50 timed runs: 0.0095 ms to
0.0094 ms, a ratio of 1.006. The proof and the bounds check together are within
a percent of the unchecked store.
@nihalpasham nihalpasham added intrinsics Device intrinsics and libdevice math mappings codegen Device code-generation pipeline (Rust MIR to IR to PTX) enhancement New feature or request labels Aug 5, 2026
Both warp_sums twins called warp::reduce_sum_f32, whose contract
requires all 32 lanes launched and converged, from 48-thread blocks
whose second warp has only 16 live lanes. The PTX ISA makes shfl.sync
undefined when a thread sources a lane that is inactive or outside the
member mask, and the full-mask butterfly reads lanes 16-31 that never
launched.

Both kernels now share a live-lane butterfly: the member mask names
exactly the launched lanes of the calling warp and the offsets start at
half the live-lane count, so every sourced lane is active and named.
The 16-lane tail is a power of two, which keeps lane ^ offset closed
over the mask at every step. The 48-thread partial-warp geometry stays,
since it is what proves the div_ceil warp-index math, and the host
reference still matches exactly (max error 0).
The warp_index rustdoc example called a two-argument
warp::reduce_sum_f32(u32::MAX, contribution) that does not exist; the
real API takes one argument. The snippet now shows the real call and
notes that reduce_sum_f32 itself requires full 32-lane warps, pointing
partial tail warps at shuffle_xor_f32_sync with a live-lane mask. The
snippet stays rust,ignore like every other kernel-context example in
this crate because it references kernel-local bindings, and its
witness-and-store block follows the same shape as the warp_sums
example.

Also add warp_index to the reserved-name caveat on ThreadIndex: the
macros now rewrite that free-function name inside #[kernel] and
#[device] bodies, so a user-local fn warp_index would be hijacked the
same way as index_1d.
@nihalpasham

Copy link
Copy Markdown
Collaborator

The WarpIndex mechanism checks out end to end:

  • re-derived the uniqueness argument independently: div_ceil warps-per-block (blockDim=48: gids 32 and 48 land in different slots, where /32 would alias them), lane-0 gating, checked arithmetic degrading to None, and no laundering path (WarpIndex implements no IndexFormula, so get_mut_indexed cannot take it).
  • cargo test --workspace green on the pinned toolchain, including the five re-derived trybuild snapshots.
  • warp_sums on RTX 5090: exact match against the host reference.

I pushed two commits on top:

  • the 48-thread blocks leave a 16-lane tail warp, but both kernels called reduce_sum_f32, whose contract needs all 32 lanes launched; shfl.sync sourcing never-launched lanes is undefined per the PTX ISA. Both twins now reduce over exactly the live lanes (member mask from the live-lane count, butterfly from live/2), keeping the partial-warp geometry that proves the index math. Host reference still matches exactly.
  • doc fixes: the warp_index rustdoc called a two-argument reduce_sum_f32 that does not exist (now the real one-arg call with the full-warp caveat inline), and warp_index joined the reserved-names list since the macro now claims that name inside kernel bodies.

Closes #584.

@nihalpasham
nihalpasham merged commit 20c1db0 into NVIDIA:main Aug 5, 2026
33 checks passed
nihalpasham added a commit to alejandro-soto-franco/cuda-rust that referenced this pull request Aug 5, 2026
Resolves the overlap with the seven PRs merged ahead of this one,
chiefly WarpIndex (NVIDIA#655) meeting the reworked witness model: a
WarpIndex witness stores its flat warp slot computed from launch
geometry alone, so WarpIndex implements the sealed FlatIndexSpace,
and its SpaceLayout Data is (), keeping warp-index slices on the
two-word launch ABI through the existing blanket impls.

Validated on the merged tree: workspace tests, fmt on all three CI
scopes, clippy on the workspace and every example crate, and a 12/12
GPU smoketest across the examples this batch touches.
nihalpasham pushed a commit that referenced this pull request Aug 6, 2026
* Reduce over the live lanes of a partial warp

The warp reductions shuffle with the full 32-lane member mask, so every
lane must be launched and converged. A block whose width is not a
multiple of 32 leaves its last warp short: 48 threads give a second warp
of 16 live lanes, and the PTX ISA makes `shfl.sync` undefined when a
thread sources a lane that is inactive or outside the member mask. The
library offered nothing for that case, so #655 carried a live-lane
butterfly private to the `warp_sums` example, correct only for a
power-of-two tail by its own admission.

Add `reduce_{sum,max,min}_{f32,f64}_partial`, taking the live-lane count,
and `live_lanes_1d` to derive it for a one-dimensional block.

A power-of-two count takes the same butterfly as the full-warp form with
the mask and the first offset cut to the live lanes, which keeps
`lane ^ offset` inside the mask at every step. Any other count folds the
upper part of the span into the lower half and halves the span, reaching
an arbitrary count in `ceil(log2(live))` steps. Every shuffle there names
a source below the live count, clamped to the last live lane where the
arithmetic would run past it, so no thread sources a lane that was never
launched; the clamped result is discarded wherever the source lies
outside the current span. One broadcast then leaves the total in every
lane, as the full-warp form does.

`warp_sums` now calls the library form and drops its private helper.

Tests: a host model of the fold, which totals correctly for every live
count from 1 to 32 and never names a source at or above the live count;
mask tests; and `partial_warp_reduce` on GPU over a 16-lane tail from
48-thread blocks and a 13-lane tail from 45-thread blocks, sum and
maximum, exact against the host reference.

One measurement belongs in the record. Substituting the full-warp form
into those kernels also matches the reference exactly on sm_120, so this
hardware returns something harmless for a shuffle sourcing a
never-launched lane. The ISA promises nothing about that value on any
architecture, which is the reason to name the live lanes rather than
rely on it. The example's README says so, so nobody reads the passing
run as evidence the full-warp form is safe there.

* test(warp): index the partial-fold assertion by iterator, not a range loop

clippy's needless_range_loop, denied by -D warnings, was blocking #672.
@alejandro-soto-franco
alejandro-soto-franco deleted the feat/warp-index-space branch September 9, 2026 17:08
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.

No safe path for writes whose uniqueness is guaranteed by the algorithm, not a ThreadIndex

2 participants