Skip to content

Bind the runtime row width into the disjoint slice's index space - #653

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

nihalpasham merged 17 commits into
NVIDIA:mainfrom
alejandro-soto-franco:feat/index-space-pitch

Conversation

@alejandro-soto-franco

@alejandro-soto-franco alejandro-soto-franco commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Tile disjointness needs one row width per slice for the slice's whole lifetime. A width supplied per call cannot give that, which is why #515 was closed, so this moves the row width to where device code cannot choose it.

Closes #516. Reworks the design closed in #515.

Why no per-call witness can carry this

Uniformity is closed under arithmetic whose operands are all uniform. It is not closed under selection. Safe code can pick between two Uniform<u32> values on a thread-varying condition, or pass different ones at two call sites on one slice, and the selected row width then differs between threads:

let chosen = if thread_varying { wide } else { narrow };
c.tile_2d32_rt(coord, chosen)   // both values launch-uniform, the choice is not

Two threads that disagree about the row width describe two grids over one buffer. With 1x1 tiles, thread (1, 0) at width 5 and thread (0, 5) at width 100 both resolve flat index 5. Binding at the host boundary removes the choice: the host writes one word into the launch packet and device code has no step at which it could substitute another.

Changes

A sealed trait gives each index space the runtime layout it needs:

pub trait SpaceLayout: sealed::Sealed {
    /// Runtime layout data marshalled with the slice, or `()` when the index
    /// space is fully described by its type.
    type Data: Copy;
}

() for the five spaces fixed in their types, u32 for RuntimeRowMajorTiles and Runtime2DIndex. The host supplies it through RowWidth, or RowWidthOwned for the owned async launches. tile_2d32_rt therefore takes only a thread coordinate, and index_2d_runtime takes the slice it will address and is now safe, which is what closes #516.

mir.disjoint_slice was a dialect type of exactly two fields, so the third word could not reach the device. It now carries the index space's layout fields after { ptr, len }: the verifier accepts them, the importer reads them from rustc's layout rather than from the index space's name, signature conversion flattens them into kernel parameters, and the entry prologue repacks them.

() is zero-sized, so every existing slice keeps its two-word layout and kernel ABI. Const assertions check that.

Design decisions

Chosen: the payload lives in the slice, marshalled from the host. Alternative rejected: a consuming with_row_width on the device, binding once per slice. It reads as sound because DisjointSlice is neither Copy nor Clone, so it can be called at most once. The argument to that one call can still be selected on a thread-varying condition, which is the same defect one call up.

Chosen: read the payload from rustc's own layout of the struct. Alternative rejected: matching on the index space's name in the importer, which would silently miss any space added later.

Validation

RTX 5060 (sm_120), CUDA 13.3.

example result
gemm 538 GFLOPS, max error 1.5e-5
tiled_gemm 1447 GFLOPS, max error 1.5e-5
gemm_views naive, safe against raw 1117 against 1090 GFLOPS, bitwise equal
gemm_views tiled, safe against raw 1350 against 1360 GFLOPS, bitwise equal
async_mlp RowWidthOwned across four concurrent batches

A new compile-fail case rejects a per-call width, so reverting this change fails a test rather than passing quietly. The eight existing cases keep their expectations, re-derived against the new signatures.

The caveat

Leaving the entry prologue unfixed compiled and ran, and gave every thread a zero row width. Hardware caught that; the host-side suite did not. Anything else extending mir.disjoint_slice needs the same end-to-end check.

Gates

3289 workspace tests pass, cargo clippy --workspace --all-targets -- -D warnings clean, four device examples verified against host references.

Maintainer edits during review

Changes layered on top of the contribution during review, validated end to end on an RTX 5090 (sm_120):

  • (row, col) witness with per-slice resolution. A Runtime2DIndex witness no longer stores a flat index. It carries the thread's raw (row, col) coordinates, and whichever slice it is handed to resolves them against that slice's own host-bound row width (row * width + col, requiring col < width). Witnesses minted from two slices with different widths can therefore never put two threads on one element, even when safe code selects between them under a thread-varying condition.
  • Sealed launch-packet backstop. The #[cuda_module] macro picks the two-word or three-word packet from the index space's spelling, which a type alias can hide or fake. A hidden sealed trait, __LaunchContractDisjointSliceAbi, now bounds every generated launch method by the packet shape the macro chose, so a spelling/semantics mismatch is a compile error instead of the driver reading past the argument array. Compile-fail tests cover both directions.
  • Call-site flattening for by-value slices. Passing a runtime-width DisjointSlice by value to a non-inlined device function used to drop the width word at the internal call boundary. Call lowering now flattens the index-space fields through the call ABI, symmetric with the callee signature.
  • Fallback arm and tests. The no-history aggregate fallback in mir-lower accepts the lowered { ptr, i64, u32 } slice shape and still fails closed for anything else, with a direct unit test. A new GPU example, row_width_slice, holds the regressions: nonzero width readback, two-width witness mixing, and the by-value call ABI.
  • Book updates. The safety model, bounds checks, API quick reference, glossary, and async-MLP project pages now teach the safe slice-bound form everywhere the old unsafe per-call form survived.
  • Vocabulary: row width, not pitch. The API says what the value is: RowWidth / RowWidthOwned on the host, DisjointSlice::row_width() on the device, and matching prose throughout. Raw CUDA driver names are unaffected.

Closes NVIDIA#516. Reworks the design closed in NVIDIA#515.

A per-call pitch cannot carry the disjointness proof. Safe code can select
between two `Uniform<u32>` values under a thread-varying condition, or pass
different ones at two call sites on one slice, and two threads then hold
`&mut` to one element: with 1x1 tiles, `(1, 0)` at stride 5 and `(0, 5)` at
stride 100 both resolve flat index 5. Uniformity is closed under arithmetic
whose operands are all uniform, and it is not closed under selection, so no
witness passed at the call site fixes this.

Tile disjointness needs one pitch per slice for the slice's whole lifetime,
so the pitch moves to where device code cannot choose it. A sealed
`SpaceLayout` trait gives each index space the runtime layout it needs: `()`
for the five spaces fixed in their types, `u32` for `RuntimeRowMajorTiles`
and `Runtime2DIndex`. The host writes it into the launch packet through
`Pitched`, or `PitchedOwned` for the owned async launches.

`tile_2d32_rt` therefore takes only a thread coordinate, and
`index_2d_runtime` takes the slice it will address and is now safe, which is
what closes NVIDIA#516.

`mir.disjoint_slice` was a first-class dialect type of exactly two fields, so
the third word could not reach the device. It now carries the index space's
layout fields after `{ ptr, len }`: the verifier accepts them, the importer
reads them from rustc's layout rather than from the index space's name, the
signature conversion flattens them into kernel parameters, and the entry
prologue repacks them. Leaving that last step out compiled and ran, and gave
every thread a zero pitch.

`()` is zero-sized, so every existing slice keeps its two-word layout and
kernel ABI. Const assertions pin that.

`Uniform<T>` stays, with its host mapping to a bare scalar, its sealed
anti-spoof bound and trybuild tests, and the requires-relation unwrapping.
Its documentation now states what it cannot carry.

Validation, RTX 5060 (sm_120), CUDA 13.3:
- 3289 workspace tests, clippy --all-targets -D warnings clean.
- gemm 538 GFLOPS, max error 1.5e-5; tiled_gemm 1447 GFLOPS, 1.5e-5.
- gemm_views: safe == raw bitwise for both kernel pairs, 1117 vs 1090 GFLOPS
  naive and 1350 vs 1360 tiled, so the extra parameter costs nothing.
- async_mlp exercises PitchedOwned across four concurrent batches.
- New compile_fail case rejects a per-call pitch; the eight existing cases
  keep their expectations re-derived against the new signatures.
@nihalpasham nihalpasham added codegen Device code-generation pipeline (Rust MIR to IR to PTX) IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) host-apis Host-side runtime APIs (cuda-host, cuda-core, cuda-async) safety Memory safety, soundness, or undefined behavior enhancement New feature or request labels Aug 5, 2026
…sed slice's pitch

A ThreadIndex<Runtime2DIndex> stored the flat index computed with the
MINTING slice's pitch, while DisjointSlice::get_mut accepted any witness
of the matching index-space type with only a length check. Safe code
holding two differently pitched slices could mint a witness from each
and select one under a thread-varying condition; with pitches 5 and 100,
threads (1, 0) and (0, 5) both flattened to element 5 and took two &mut
to one location.

The witness now stores the thread's raw (row, col) coordinates, packed
into its single usize word exactly as ThreadCoord2D32 packs its pair, so
the device scalar ABI and the importer's newtype-to-usize translation
are unchanged. The addressed slice resolves the coordinates against its
OWN host-bound pitch at the access site (row * pitch + col, requiring
col < pitch). Distinct threads hold distinct coordinates and read one
host-written pitch per slice, so the mapping is injective per slice no
matter which slice minted the witness.

The flat accessors (get, in_bounds) move behind a sealed FlatIndexSpace
marker implemented for Index1D and Index2D only, so the packed word can
never be read as a flat index; row()/col() accessors replace them for
Runtime2DIndex. Host unit tests replay the historical two-pitch
collision and check per-slice injectivity, zero-pitch rejection, and
length clipping.
…ointSlice type

cuda_module_disjoint_slice_is_pitched picked the two-word or three-word
host ABI purely from the index space's SPELLING. A type alias defeats
it: type Rt = RuntimeRowMajorTiles<1, 1> spells an unpitched slice over
a pitched space, so the generated launch pushed two kernelParams for a
three-parameter kernel and the driver read past the argument array
(host UB). The inverse alias, a local Runtime2DIndex naming an
unpitched space, pushed one word too many.

Following the __LaunchContractUniform pattern this PR introduced, the
sealed __LaunchContractDisjointSliceAbi<Element, PITCHED> trait in
cuda-device is now the semantic authority: PITCHED = false is
implemented only where SpaceLayout::Data = () and PITCHED = true only
where Data = u32, so pitched-ness follows the resolved type, never the
spelling. The macro keeps the spelling check as the fast path that
selects the candidate ABI, and bounds every generated launch method
(raw, prepared, async, owned-async) by the pitched-ness it chose. A
spelling/semantics mismatch makes every launch method uncallable, so no
mis-shaped packet can be built from safe or generated code. An index
space with a future Data shape implements neither instantiation and
fails closed until the host marshalling learns it.

Two trybuild cases cover both alias directions, and an expansion unit
test checks the emitted bounds; the fake_disjoint_slice and
reordered_disjoint_alias expectations gain the second rejection the new
bound adds.
…slice call arguments

convert_function_type gives a callee taking a pitched DisjointSlice by
value a three-parameter signature (ptr, len, pitch), but
flatten_arguments still flattened the call-site argument to (ptr, len)
only, so the emitted call no longer matched the callee's own signature.

Pliron's module verification rejects that mismatch loudly (Function
call has incorrect type), so the user-visible defect was a valid
program failing to compile: any non-inlined device helper taking a
pitched slice by value stopped the device build at verification. No
short argument list and no wrong pitch could reach hardware through
this path.

The Slice arm now carries the MIR type's index-space field list and
extracts each non-zero-sized field from aggregate slot 2 + i,
symmetrically with the signature conversion and the entry prologue.
Covered end to end by the pitched_slice example's inline(never)
by-value helper, whose call now carries (ptr, len, i32 pitch) in the
emitted IR and reads the bound pitch back on hardware.
…egate fallback

Defensive symmetry for a path nothing currently reaches: every pitched
disjoint slice the pipeline produces today records conversion history,
so no existing test or example hits the no-history fallback in
resolve_aggregate_slots with a pitched shape (verified by reverting
this change under the full suite).

The asymmetry it closes is real, though. The fallback identity-mapped
only the two-field { ptr, i64 } fat pointer, so if a pitched disjoint
slice ever loses its conversion history the same way an unpitched one
can (the entry-prologue-born case the fallback exists for), it would
hit the refuse-to-guess error where the unpitched slice succeeds.

The fallback now also accepts the shape make_disjoint_slice_struct
builds for the one runtime layout current SpaceLayout impls carry (a
single u32 row pitch), constructed through the real type builder so the
check cannot drift from the lowered shape. Like the fat pointer, that
struct is index-preserving by construction, so identity indexing is
sound for it; any other lost-history shape still fails closed into the
refuse-to-guess error. Because no end-to-end path can reach the arm, a
direct unit test added later on this branch drives it explicitly.
…pitch

Three executable properties for DisjointSlice<T, Runtime2DIndex>:

1. Nonzero pitch readback: every thread writes the pitch it read from
   the slice; a prologue that drops or zeroes the third kernel
   parameter leaves the sentinel behind and fails loudly instead of
   passing with pitch 0.
2. Two-pitch witness mixing: witnesses minted from slices with pitches
   5 and 100 and selected under a thread-varying condition must resolve
   against the addressed slice's own pitch, landing every thread on its
   own (row, col) cell. Flat-index witnesses fail this deterministically
   because the minting slice's grid leaks through the selection.
3. By-value pitched slice through an inline(never) device helper: the
   internal call ABI must marshal all three fields to match the
   three-parameter callee.

The generated PTX carries exactly three .param entries per pitched
slice (six for the two-slice kernel), matching the launch packet the
host builds.
… per-slice pitch move

The indexing intrinsics module still described index_2d_runtime as a
caller-asserted helper flattened to row * s + col. It is a normal
function call whose witness packs the raw (row, col) coordinates, and
the addressed slice resolves them against its own host-bound pitch, so
a flat expansion would reintroduce the witness-mixing hole. Comment-only
change.
cargo fmt --all --check failed on the branch: the resolved_flat_index
test helper in cuda-device and several multi-line shapes in cuda-macros,
cuda-host, and mir-lower were left unformatted. Formatting-only; no
behavior change.
…nsafe form survived

The pitched-slice rework made index_2d_runtime safe (it takes the slice
whose host-bound pitch it reads) and dropped tile_2d32_rt's per-call
width, but several book pages, two example READMEs, and one thread.rs
doc bullet still taught the removed unsafe forms:

- appendix/api-quick-reference.md: sample, table row, and prose showed
  unsafe index_2d_runtime(stride) with a caller-asserted uniform stride
- appendix/supported-features.md: called the stride caller-proved
- appendix/glossary.md: described the unsafe escape-hatch contract
- projects/async-mlp-pipeline.md: sgemm sample no longer compiled, and
  the raw Stage 1 packet was missing the pitch word the pitched slice
  now marshals
- advanced/shared-memory-and-synchronization.md: unsafe sample
- gpu-safety/bounds-checks.md: unsafe tile_2d32_rt(coord, n) sample and
  the obligation paragraph it explained
- gpu-safety/the-safety-model.md: one leftover sentence introduced the
  now-safe sample as explicit and unsafe
- examples/gemm/README.md and examples/gemm_views/README.md: unsafe
  samples and the single-unsafe-obligation claim
- cuda-device/src/thread.rs: construction bullet still called
  index_2d_runtime an unsafe runtime-stride escape hatch

All samples now match the signatures on this branch: the witness stores
(row, col), the addressed slice resolves them against its own pitch,
and the host binds the pitch once via Pitched / PitchedOwned.
… fallback directly

No current lowering path produces a pitched disjoint-slice value with an
empty conversion history (the entry prologue records history when it
repacks kernel parameters), so the widened fallback arm in
resolve_aggregate_slots is defensive symmetry that no end-to-end test
can reach. Cover it at the unit level instead: a block argument born as
the lowered { ptr, i64, i32 } pitched shape with no recorded history
must resolve to identity indexing, and a three-field control shape with
i64 in the pitch slot must keep failing closed into the refuse-to-guess
error. The Identity assertion on the three-field shape can only be
satisfied by the pitched arm, so a revert of that arm fails this test.
…at compile time

The pitched-slice rework moved ThreadIndex::get and
ThreadIndex::in_bounds behind the sealed FlatIndexSpace marker
(Index1D and Index2D<S> only), because a Runtime2DIndex witness stores
packed (row, col) coordinates whose flat position only exists relative
to the addressed slice's pitch. That gating had no compile-fail
coverage. Add a trybuild case asserting both accessors are hard type
errors on ThreadIndex<Runtime2DIndex>, with the stderr snapshot
generated on the pinned toolchain via TRYBUILD=overwrite like the
sibling fixtures.
…th slice API

The maintainer prefers plain vocabulary for the user-facing API: "row
width" says exactly what the value is, while "pitch" assumes graphics-API
background. This renames every identifier this branch introduced that
contained pitch/pitched, and rewords the touched doc comments, assertion
messages, book pages, and example prose to match. No behavior change; the
trybuild snapshots were regenerated and re-run green.

Rename map:
- cuda-host `Pitched` -> `RowWidth` (accessor `pitch()` -> `width()`)
- cuda-host `PitchedOwned` -> `RowWidthOwned`
- `DisjointSlice::row_pitch()` -> `row_width()`
- `pitched_device_buffer_arg` -> `row_width_device_buffer_arg`
- `push_kernel_pitched_device_slice` -> `push_kernel_row_width_device_slice`
- `push_async_pitched_device_slice` -> `push_async_row_width_device_slice`
- `push_async_owned_pitched_device_slice` ->
  `push_async_owned_row_width_device_slice`
- cuda-macros `CudaModuleParamMarshal::PitchedDeviceBuffer` ->
  `RowWidthDeviceBuffer`
- `cuda_module_disjoint_slice_is_pitched` ->
  `cuda_module_disjoint_slice_has_row_width`
- `__LaunchContractDisjointSliceAbi<_, PITCHED>` -> `<_, HAS_ROW_WIDTH>`
- example `pitched_slice` -> `row_width_slice`; its kernels
  `write_pitch_readback` -> `write_width_readback`, `two_pitch_selection`
  -> `two_width_selection`, `byvalue_helper_pitch` -> `byvalue_helper_width`
- compile-fail fixtures `launch_contract_alias_{hides,fakes}_pitch` ->
  `..._row_width`, `runtime_tile_no_per_call_pitch` ->
  `runtime_tile_no_per_call_row_width`
- cuda-device tests `witnesses_from_two_pitches_cannot_alias_one_element`
  -> `witnesses_from_two_row_widths_cannot_alias_one_element`,
  `zero_pitch_resolves_nothing` -> `zero_row_width_resolves_nothing`

Raw CUDA driver names (cuMemAllocPitch and friends) are NVIDIA's API, not
ours; nothing under crates/cuda-bindings changes.
@nihalpasham nihalpasham changed the title Bind the runtime row pitch into the disjoint slice's index space Bind the runtime row width into the disjoint slice's index space Aug 5, 2026
@nihalpasham

Copy link
Copy Markdown
Collaborator

Lands the architecture the #515 close asked for, hardened during review; everything below ran on an RTX 5090 (sm_120):

  • gemm 2949 GFLOPS / tiled_gemm 9059, max error 1.5e-5 against host references; gemm_views safe vs raw bitwise-equal on both kernel pairs; async_mlp green.
  • ABI stability confirmed: a fixed-width example's PTX is byte-identical to main, and runtime-width kernels carry exactly three parameters.

Pushed on top (full list in the PR description's maintainer-edits section):

  • witness redesign: a Runtime2DIndex witness now carries the thread's (row, col) and every slice resolves it against its own host-bound row width. The submitted design stored a flat index baked with the minting slice's width; with two slices of widths 5 and 100, threads (1,0) and (0,5) both resolved flat index 5, and we reproduced that as real memory corruption on hardware before fixing it. Unit tests and the new row_width_slice GPU example replay the scenario.
  • sealed launch-packet backstop, so a type alias can no longer produce a two-word packet for a three-parameter kernel; call-site flattening for by-value slices through non-inlined helpers; and the no-history fallback arm with a direct unit test.
  • fmt gate fixed, the book now teaches the safe slice-bound form everywhere the old unsafe form survived, and the vocabulary moved from "pitch" to row width across the API (RowWidth / RowWidthOwned, row_width()).

Closes #516. Thanks for taking the #515 redesign all the way through the pipeline.

StructType::get_unnamed takes a shared context reference; the new
no-history fallback test passed &mut and clippy -D warnings rejects
the unnecessary mutable borrow. The row_width_slice example crate is
its own workspace, so the root cargo fmt pass never saw it; the fmt
CI job checks every example crate individually.
clippy's manual-is-multiple-of lint fires under the per-example -D
warnings pass. Verified the method still lowers through the device
pipeline: the example runs on GPU with all three regression
properties passing.
The lint fix pushed the single-line if past rustfmt's inline limit;
the per-example fmt CI pass wants the block form. GPU re-run still
passes all three regression properties.
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.
The merge imported WarpIndex into disjoint.rs scope for the
SpaceLayout and FlatIndexSpace impls, so the intra-doc link resolves
directly and rustdoc -D warnings rejects the explicit path target.
@nihalpasham
nihalpasham merged commit cd5ef39 into NVIDIA:main Aug 5, 2026
34 checks passed
@alejandro-soto-franco
alejandro-soto-franco deleted the feat/index-space-pitch 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 host-apis Host-side runtime APIs (cuda-host, cuda-core, cuda-async) IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) safety Memory safety, soundness, or undefined behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

index_2d_runtime still carries an unsafe launch-uniformity obligation

2 participants