Skip to content

Give a thread a contiguous run, whole or clipped, and walk runs by grid stride - #654

Merged
nihalpasham merged 3 commits into
NVIDIA:mainfrom
alejandro-soto-franco:feat/thread-runs
Aug 5, 2026
Merged

nihalpasham merged 3 commits into
NVIDIA:mainfrom
alejandro-soto-franco:feat/thread-runs

Conversation

@alejandro-soto-franco

Copy link
Copy Markdown
Contributor

Two of this issue's three requirements are already met on main, so this adds only the tail and the grid stride.

Closes #583.

What already works

LinearTiles<N> plus tile_thread32 gives thread t the elements t * N .. t * N + N behind a proof derived from a ThreadIndex32, so a thread can already own N contiguous elements without get_unchecked_mut. The issue's worked example predates that index space. Requirement 1 is covered.

The tail

tile_thread32 accepts only a whole tile, so the one thread whose run straddles the end of the buffer gets None and drops back to raw indexing. Launches round the grid up, so that thread almost always exists, and the fallback lands exactly where the arithmetic is most awkward to get right.

pub enum ThreadRunMut32<'a, T, const N: usize> {
    /// The thread owns all `N` elements.
    Full(StaticViewMut32<'a, T, N>),
    /// The parent ended part-way through the run.
    Clipped(RuntimeViewMut32<'a, T>),
}

pub fn thread_run32<'kernel>(
    &mut self,
    thread: ThreadIndex32<'kernel>,
) -> Option<ThreadRunMut32<'_, T, N>>

None now means only that a thread owns nothing at all.

The grid stride

grid_stride_runs32 walks every run a thread owns with the period read from gridDim.x * blockDim.x inside the call. A passed stride is the defect the issue describes: one that disagrees with the launch makes threads overlap silently and nothing in the signature catches it. With the period taken from the launch, every tile index a thread takes is congruent to its own index modulo the period, and t < period holds for a 1D launch, so distinct threads never take the same tile.

Design decisions

Chosen: an enum for the tail, answering the issue's second design question. Alternative rejected: a single sub-view whose extent is always a runtime value. That would put a bounds branch on every thread to serve the one whose run is clipped, where the enum keeps at_const and its absent branch for the whole-run case.

Chosen: extend the view.rs vocabulary. RuntimeViewMut32 is the 1D counterpart of the existing RuntimeTileMut32, and both follow the established shape of a view parameterised by extents, indexed by a bounded-index proof, returning an InBounds wrapper. Alternative rejected: new Disjoint* types on the slice, which the issue's own retrospective on #571 identifies as the wrong shape.

Validation

RTX 5060 (sm_120), CUDA 13.3, via the new thread_runs example over a 4093-element buffer with a run width of 4, so the tail runs in every kernel.

check result
one run per thread, tail included all 4093 elements doubled
grid-stride coverage 256 threads covered all 1024 runs exactly once each
clipped runs exactly one, of the expected 1 element

Coverage is checked by value rather than by inspection: a thread that took a run twice, or none, changes the result.

The caveat

The issue notes its earlier attempt carried no performance benefit. This one carries a cost. Against a raw twin that computes the base by hand and stores through get_unchecked_mut, over 2^22 elements and 20 timed runs:

kernel time
safe runs 0.0633 ms
raw get_unchecked_mut 0.0625 ms

A ratio of 1.012. The proof and the bounds check together cost about one percent on a kernel that is bandwidth-bound, and the tail stops needing raw indexing.

ThreadRunMut32::at copies the base pointer and length out of the variant rather than borrowing through it, because a &mut through an enum downcast has no in-memory address the backend can name. That is #651, filed separately.

Gates

3286 workspace tests pass, cargo clippy --workspace --all-targets -- -D warnings clean, three device kernels verified against host references.

…id stride

Closes NVIDIA#583.

Two of the issue's three requirements are already met on main, which is worth
stating before adding anything. `LinearTiles<N>` plus `tile_thread32` gives
thread `t` the elements `t * N .. t * N + N` behind a proof derived from a
`ThreadIndex32`, so a thread can already own `N` contiguous elements without
`get_unchecked_mut`. The issue's worked example predates that index space.

What is missing is the tail and the grid stride.

`tile_thread32` accepts only a whole tile, so the one thread whose run
straddles the end of the buffer gets `None` and drops back to raw indexing.
Launches round the grid up, so that thread almost always exists, and the
fallback lands exactly where the arithmetic is most awkward. `thread_run32`
returns `ThreadRunMut32` instead: `Full` carries the check-free
`StaticViewMut32` for every thread whose run fits, `Clipped` carries a new
`RuntimeViewMut32` for the one that straddles the end, and `None` now means
only that a thread owns nothing at all. That answers the issue's second design
question in favour of the enum, since the whole-run case keeps `at_const` and
its absent bounds branch.

`grid_stride_runs32` walks every run a thread owns with the period read from
`gridDim.x * blockDim.x` inside the call. A passed stride is the defect the
issue describes: one that disagrees with the launch makes threads overlap
silently and nothing in the signature catches it. With the period taken from
the launch, every tile index a thread takes is congruent to its own index
modulo the period, and `t < period` holds for a 1D launch, so distinct threads
never take the same tile.

Both types extend the `view.rs` vocabulary rather than adding a second one:
a view parameterised by extents, indexed by a bounded-index proof, returning
an `InBounds` wrapper. `RuntimeViewMut32` is the 1D counterpart of the
existing `RuntimeTileMut32`.

`ThreadRunMut32::at` copies the base pointer and length out of the variant
rather than borrowing through it. A `&mut` through an enum downcast has no
in-memory address the device backend can name, and it rejects the construct
outright, so the borrowing form does not compile for a kernel.

Validation, RTX 5060 (sm_120), CUDA 13.3, via the new `thread_runs` example
over a 4093-element buffer with a run width of 4, so the tail is exercised in
every kernel:
- every element doubled through one run per thread, tail included.
- 256 threads covered all 1024 runs exactly once each under the grid stride,
  checked by value rather than by inspection.
- exactly one clipped run, of the expected 1 element.
- 3286 workspace tests, clippy --all-targets -D warnings clean.

The issue notes that its earlier attempt carried no performance benefit, so
here is the cost rather than a benefit. Against a raw twin that computes the
base by hand and stores through `get_unchecked_mut`, the safe runs measure
0.0633 ms to 0.0625 ms over 20 runs on 2^22 elements, a ratio of 1.012. The
proof and the bounds check together cost about one percent on a kernel that is
bandwidth-bound, and the tail stops needing raw indexing.
@nihalpasham nihalpasham added device-apis User-facing device-side and kernel-authoring APIs (cuda-device, cuda-macros) enhancement New feature or request safety Memory safety, soundness, or undefined behavior labels Aug 5, 2026
thread_run32 and GridStrideRuns32::next_run carried two verbatim copies
of the start/available arithmetic, and neither rejected a tile width
above u32::MAX the way checked_linear_tile_start and
valid_mutable_extent do, so a Full run with such an N under-reported
its length through the N-as-u32 truncation in raw_parts.

Factor the proof into checked_run_bounds next to
checked_linear_tile_start. The helper packs the run's element count
above its start offset in one u64, with zero reserved as the no-run
value (a run that exists has a nonzero count, so a valid word can
never collide with the sentinel), keeping the proof scalar-only like
its neighbours. It rejects N of zero or above u32::MAX, checks the
tile scale in u64, and decides full against clipped at the exact
boundary.

Host tests cover start == len, available == 1, tile-scale overflow,
the exact u32::MAX start boundary and the first offset past it, the
zero-period guard, and a two-thread grid-stride walk over a clipped
parent that touches every element exactly once.

Document the u32::MAX offset cutoff on grid_stride_runs32 and
next_run: for parents longer than 2^32 elements the walk stops at
that boundary rather than continuing into the region past it,
matching the rest of the 32-suffix family. thread_run32's doc now
states the same cutoff and the width rejection.
checked_run_bounds's u32::MAX cutoff bounds where a run may start, not
where it may end, but no test exercised the positive side of that
asymmetry. Add one: tile 1431655765 of width 3 starts exactly at
u32::MAX and keeps its full count of 3 even though its tail sits at
element offsets 2^32 and 2^32 + 1, while the very next tile, whose
start of 2^32 + 2 is past the cutoff, is refused with parent elements
remaining.

The tile-scale overflow test only used products that also land past
the u32::MAX start guard, so replacing checked_mul with wrapping_mul
survived the whole suite. Add 2^33 * 2^31, which wraps to a start of
zero that the start guard would wave through; only the checked
multiply rejects it.

Both mutants were applied temporarily to confirm the kills, then
reverted: wrapping_mul fails exactly the strengthened overflow test,
and dropping the start guard fails the new boundary test's refusal
arm alongside the existing cutoff test.
@nihalpasham

Copy link
Copy Markdown
Collaborator

Verified the soundness core and the hardware behavior:

  • ThreadIndex32 is only constructible from a launch context proving 1D and grid.x * block.x <= 2^32, so the flat id always sits below the grid-stride period; clipping only ever shortens the last run; next_run terminates (strictly increasing tile, period == 0 guarded).
  • thread_runs on RTX 5090: PASS, covering Full, Clipped, and None in one launch.
  • cargo test --workspace and clippy clean.

I pushed two commits on top:

  • the start/length arithmetic was duplicated in thread_run32 and next_run with no host tests; it now lives in one helper (checked_run_bounds) with unit tests on every boundary. A differential harness confirmed the helper is exactly equivalent to both original copies: zero mismatches over the boundary grid plus an exhaustive small-domain sweep.
  • parity and docs: N > u32::MAX is now rejected like the sibling APIs (it used to truncate len()), and grid_stride_runs32 documents the u32::MAX start-offset cutoff for buffers past 2^32 elements. The added tests kill both mutants we tried (a wrapping_mul swap and a dropped boundary guard).

Closes #583. The raw_parts copy-out at the enum boundary can be revisited once #652 lands.

@nihalpasham
nihalpasham merged commit f1b52c0 into NVIDIA:main Aug 5, 2026
33 checks passed
@alejandro-soto-franco
alejandro-soto-franco deleted the feat/thread-runs 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

device-apis User-facing device-side and kernel-authoring APIs (cuda-device, cuda-macros) enhancement New feature or request safety Memory safety, soundness, or undefined behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

DisjointSlice cannot express a thread owning N contiguous elements

2 participants