Skip to content

feat(disjoint): derive multi-element and grid-stride index proofs - #571

Closed
honeyspoon wants to merge 4 commits into
NVIDIA:mainfrom
honeyspoon:up2/affine-thread-index
Closed

honeyspoon wants to merge 4 commits into
NVIDIA:mainfrom
honeyspoon:up2/affine-thread-index

Conversation

@honeyspoon

@honeyspoon honeyspoon commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

DisjointSlice::get_mut takes a ThreadIndex and yields one element. A thread that owns N contiguous elements has no way to say so, so multi-element and grid-stride kernels fall back to get_unchecked_mut.

This adds two derivations, each producing a proof the next step consumes:

let block  = thread::index_1d().scale::<4>();     // owns 4 contiguous elements
let tiling = block.repeat::<8>();                 // ... 8 times, at a derived period
let chunk: &mut [f32; 4] = slice.get_block_mut(block)?;
slice.for_each_tile::<4, 8>(tiling, |pass, chunk| { /* ... */ });
  • ThreadIndex::scale::<N>() -> DisjointBlock<'kernel, N, IndexSpace> — multiplying a disjoint index by a constant keeps it disjoint.
  • DisjointBlock::repeat::<K>() -> DisjointTiling<'kernel, N, K> — grid-stride, period derived.
  • DisjointSlice::get_block_mut::<N>(block) -> Option<&mut [T; N]>, plus for_each_tile::<N, K> returning the number of passes actually visited.

API decisions, and the alternatives rejected

1. New proof types, not a length on ThreadIndex

Chosen: DisjointBlock<'kernel, N, IndexSpace> and DisjointTiling<'kernel, N, K> as distinct types.

Alternative: add a length parameter to ThreadIndex and keep one type.

ThreadIndex means "this thread owns element i". Overloading it to mean "owns a run" changes what every existing consumer can assume, and get_mut would have to reject the run case at runtime. Separate types keep each proof exactly as strong as its name, and make get_block_mut unable to accept a bare index by construction.

2. const N rather than a runtime length

Chosen: const generic, so get_block_mut returns &mut [T; N].

Alternative: scale(n: usize) returning a slice-shaped proof.

The array type is the point — it is what lets the caller index without further bounds checks and what an over-aligned element type would need. A runtime length can only give &mut [T], which re-introduces a length the optimiser must track. Cost: the tile width must be a compile-time constant, which is true of every tiled kernel I have seen but is a real restriction; a runtime variant can be added later without changing this one.

3. repeat derives the period instead of accepting a stride

Chosen: period = gridDim.x * blockDim.x * N, computed inside repeat.

Alternative: repeat(stride: usize, passes: usize).

This is the decision I would most like reviewed. A passed-in stride is the classic grid-stride bug: it silently disagrees with the launch geometry and threads overlap. Deriving it means the proof cannot be constructed wrongly. The cost is that repeat reads gridDim/blockDim, so it is only meaningful inside a kernel — and it forecloses deliberately non-standard strides. If you want those reachable, the shape would be a separate repeat_with_stride marked unsafe, not a parameter here.

4. Infallible construction, is_valid() queried later

Chosen: scale/repeat always return a value; is_valid() reports whether the derived range is usable, and get_block_mut returns None when it is not.

Alternative: return Option<DisjointBlock<N>> from scale, making an invalid proof unrepresentable.

The Option version is more principled and I nearly went that way. I chose infallible because the interesting failure — the tile running past the slice — depends on the slice, which scale has never seen, so an Option there would only catch overflow in the index arithmetic and give false confidence about the rest. Validity is checked once, at the point that knows the length. Happy to flip this if you would rather have the stricter constructor.

5. for_each_tile takes a closure and returns a count

Chosen: f: impl FnMut(usize, &mut [T; N]), returning passes visited.

Alternative: an iterator of &mut [T; N].

An iterator is the more idiomatic Rust, but each item borrows the slice mutably, so a lending iterator is required — which means either GATs plumbing or handing out raw pointers. The closure keeps the borrow trivially sound today. The returned count matters because a grid-stride loop legitimately visits fewer than K passes at the tail, and silently doing fewer is exactly the bug worth surfacing.

6. Overflow is a stop, never a wrap

Every offset uses checked_*: a pass whose offset or end would wrap breaks the loop rather than folding into a passing bounds test, and get_block_mut uses start.checked_add(N)? so a tile straddling the end of the address space cannot alias low memory. Unusual to state, but this is index arithmetic guarding an unsafe block, so wrap-on-overflow would be a soundness hole rather than a wrong answer.


What this is not

It makes no performance claim. An earlier fork PR of mine proposed 32-bit index arithmetic on the theory that it would cut bounds-check cost; the measurement did not reproduce and I closed it. This is a different change. On the codebase that motivated it, get_block_mut on a DisjointSlice<f32> yields align-4 arrays that stay scalar, so it is instruction-neutral. The value is that a multi-element write stops needing unsafe.

Gates

fmt, clippy --workspace --all-targets -D warnings, rustdoc -D warnings, tests and doctests clean on nightly-2026-04-03. +617/−1 against main; the single deletion is a use crate::thread::{...} line being rewritten.

The period counterexample in the tests routes through an at(k, t, period, n) helper rather than literal 0 * / 1 * terms, because clippy's erasing_op/identity_op reject those under -D warnings.

`ThreadIndex` proves only that this thread's index differs from every other
thread's, which is a proof about a single element. Processing several elements
per thread is the usual way to stop wasting bandwidth, and there was no way to
say "index raw*N through raw*N+N-1, still disjoint" - so those writes went
through `get_unchecked_mut` with the bounds argument discharged by hand. That
is 24 sites in the audit, and it is why every kernel deliberately breaks the
1:1 mapping `get_mut` assumes.

Adds `ThreadIndex::scale::<N>()`, yielding a `DisjointBlock<N>`, and
`DisjointSlice::get_block_mut`, which turns that proof into a bounds-checked
`&mut [T; N]`:

    let block = thread::index_1d().scale::<4>();
    if let Some(row) = output.get_block_mut(block) {
        *row = [o0, o1, o2, o3];
    }

The proof carries because scaling tiles the space: if every `raw` is distinct,
the ranges [raw*N, raw*N+N) are pairwise disjoint and gapless. Consuming the
witness is what keeps it sound - `ThreadIndex` is deliberately not `Copy`, so
a thread cannot hold both a block proof and the original single-element proof,
or two differently scaled blocks, and end up with two live references to the
same slot. `DisjointBlock` is likewise `!Copy`.

Only scaling is offered, not a general affine `raw*S + K`. With a
caller-chosen stride the ranges do not tile unless S == N, so two such
families over one buffer could overlap while each looked disjoint on its own.
Scaling is the case where the proof is unconditional; `offset` and `stride`
are deliberately absent rather than forgotten.

Returning `&mut [T; N]` rather than `&mut [T]` is also deliberate: the length
is static, so it is the shape the codegen can fuse into one wide access when
`[T; N]` carries the matching alignment. That makes this a safe path toward
the wide accesses gap #2 is about, rather than only a safety improvement.

`N == 0` and any overflowing multiplication yield an invalid witness rather
than a wrong one, and the bounds test uses checked addition so a tile
straddling the end of the address space cannot wrap into a passing check.

Tests assert the properties the soundness argument rests on: tiles for
distinct indices never overlap across several N, tiles are gapless, overflow
and N == 0 are rejected, and the bounds test rejects wrapping. 21 tests pass,
fmt clean, no warnings.

Signed-off-by: abder <[email protected]>
The first cut only handled the contiguous case, `[tN, tN+N)`, and left the
strided families out on the grounds that a caller-chosen stride "could
overlap". That was a hunch stated as a limitation. Working the algebra out
turns it into a theorem, and the theorem covers the strided case too.

Write the element index as a mixed-radix numeral:

    index  =  k·(G·N)  +  t·N  +  c

    digit   range      place value
    c       [0, N)     1
    t       [0, G)     N
    k       [0, K)     G·N

Every place value is the product of the ranges of all lower digits: 1, then
1·N, then N·G. That is exactly the condition for a positional system to be
uniquely decodable, so (k, t, c) -> index is injective with inverse

    c = index mod N
    t = (index div N) mod G
    k = index div (G·N)

Injectivity *is* the disjointness proof: an index determines the thread that
produced it, so no index belongs to two threads.

The same algebra says why the period cannot be a parameter. Choosing S < G·N
makes the t and k digit ranges overlap and injectivity fails - with N=1, G=4,
S=2, both (k=0,t=2) and (k=1,t=0) land on element 2. So `repeat` derives
P = G·N from the launch geometry and there is deliberately no
`repeat_with_stride`. A period above G·N stays injective but leaves gaps, so
the derived value is the tight choice rather than merely a safe one; both
directions are pinned by tests.

This also explains a number the gaps document lists as hardcoded: the four
stripes at `tid*4 + k*1024` under 256 threads have G·N = 256·4 = 1024, so
1024 is the derived period, not a magic constant.

API: `DisjointBlock::repeat::<K>()` yields `DisjointTiling<N, K>`, consumed by
`DisjointSlice::for_each_tile`. The callback shape is load-bearing - a
`get_tile_mut(k)` taking k at runtime could be called twice with the same k
and hand out two &mut to one tile, since the proof covers distinct threads and
distinct passes, not repeated access to one pass. Driving the loop internally
makes single-visit structural.

Tests assert the algebra rather than the API surface: injectivity checked
against the decode inverse over several (G, N, K); an ownership map proving
tiles are pairwise disjoint and gapless; the S < G·N collision as an explicit
counterexample; and the oversized-period gap. 25 tests pass, fmt clean, no
warnings.

Signed-off-by: abder <[email protected]>
I wrote that returning `&mut [T; N]` makes this "a route to wide accesses".
Measured on sm_86, that is wrong, so it is now stated the other way round.

Four safe spellings, PTX and SASS both inspected:

    element types                LDG          STG
    F32x4 -> F32x4  (align 16)   LDG.E.128    STG.E.128
    Quad  -> Quad   (align 4)    LDG.E x4     STG.E x4
    &[f32] -> F32x4              LDG.E x4     STG.E.128
    &[f32] -> f32                LDG.E x4     STG.E

Width is decided by the *alignment of the element type*, independently on each
side - the third row is one kernel with a scalar load and a wide store, which
pins it. A static length does nothing on its own. Since `T` is the element type
of the `DisjointSlice`, a `DisjointSlice<f32>` hands back `&mut [f32; N]` at
4-byte alignment and stays scalar.

So this method is about the disjointness proof for multi-element access, and
nothing else. The doc now points at the path that does widen: an aligned
element type plus ordinary `get_mut`.

Signed-off-by: abder <[email protected]>
CI now lints test targets (NVIDIA#486), and the counterexample wrote the colliding
pair as `0 * bad_period + 2 * n` against `1 * bad_period + 0 * n`, which trips
clippy::erasing_op and clippy::identity_op.

The literals were carrying meaning - they are the (k, t) digit pair - so
suppressing the lint would have been the wrong fix. Routed through a small
`at(k, t, period, n)` instead, which keeps the pair visible at each call and
makes the two assertions read as the same expression under two periods.

Same assertions, same numbers.

Signed-off-by: abder <[email protected]>
@honeyspoon

honeyspoon commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor Author

All CI jobs pass on this branch. Workflows here need maintainer approval before they start, so I ran the repository's own workflow job set against this tree myself. All 16 succeed:

fmt                                       clippy
fork-guard                                generated intrinsics are current and ABI-compatible
cargo test -p cuda-device                 cargo test -p dialect-nvvm
cargo test -p mir-importer                cargo test -p mir-lower
cargo test -p dialect-mir                 cargo test -p llvm-export
cargo test -p mir-transforms              cargo test -p nvvm-transforms
cargo test -p cuda-intrinsics             cargo test -p cuda-intrinsics-gen
cargo test -p oxide-artifacts             cargo test -p reserved-oxide-symbols

That covers three gates my local pre-push script does not: fmt across the rustc-codegen-cuda workspace and every example crate, clippy on those too, and generated intrinsics are current and ABI-compatible.

Also re-ran my pre-push review checklist over the diff: no em-dashes, no unescaped intra-doc brackets, SPDX headers present on new files, cargo fmt --check clean in both workspaces.

@honeyspoon

Copy link
Copy Markdown
Contributor Author

Closing — the design is not ready, and the reason is specific rather than a general doubt.

This invented a parallel vocabulary for something #477 already established in view.rs:

existing what this added
LocalIndex32<N> (bounded index proof) DisjointBlock<N> (bounded run proof)
InBounds32 / InBoundsMut32 Option<&mut [T; N]>
StaticView32::at(..), at_const::<I>() get_block_mut::<N>(block)
StaticTileMut32<T, ROWS, COLS, ROW_STRIDE> DisjointTiling<N, K>

Two vocabularies for one idea is worse than the gap. The established pattern is a view type parameterised by extents, indexed by a bounded-index proof, returning an InBounds wrapper — and a solution should extend that (a thread obtaining a sub-view it owns) rather than bolt Disjoint* types onto the slice.

It also carried no measured benefit: get_block_mut on a DisjointSlice<f32> yields align-4 arrays that stay scalar in SASS, so the value would have been purely that a multi-element write stops needing unsafe — worth having, but not at the cost of a second vocabulary.

The gap is real and now filed with worked examples, including the grid-stride-mismatch trap and the partial-tail problem: #583. Happy to attempt it again against that framing if the composition question gets an answer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant