Repository navigation
Add Uniform<T>, a launch-uniform scalar witness, and make tile_2d32_rt safe - #515
Closed
alejandro-soto-franco wants to merge 2 commits into
Closed
alejandro-soto-franco wants to merge 2 commits into
alejandro-soto-franco wants to merge 2 commits into
Conversation
#[launch_contract(block = (x, y, z))] binds a launch to one block shape, and that shape reached only the host. Carry it into the compiled artifact so the CUDA driver enforces it per axis at every launch, including raw _unchecked launches that never pass through preparation. #[launch_contract] injects __launch_contract_block_config::<X, Y, Z>(), the MIR importer reads it, mir-lower propagates reqntid_x/y/z, and llvm-export emits the matching nvvm.annotations entries. An exact shape displaces the thread maximum, since ptxas rejects an entry carrying both .maxntid and .reqntid. .minnctapersm is independent and still emitted. Reject a #[launch_bounds(max)] below the exact block's thread count, which would otherwise be dropped in silence. #[cuda_module] already diagnoses this at the attribute site, so the check added here covers standalone contracted kernels, which reach the device compiler by another path. Model the two directives as an enum in the exporter, so an entry cannot carry both by construction.
tile_2d32_rt carried an obligation the type system could not see: the row pitch has to be identical in every thread, or two threads describe different grids over one buffer and their tiles overlap. Uniform<T> is a #[repr(transparent)] newtype with a private field and no public constructor, so its only safe source is a kernel parameter, which the host marshals once for the whole grid. #[cuda_module] maps a Uniform<T> parameter to a plain T on the host, and a sealed __LaunchContractUniform bound rejects a local type of the same name. Uniformity is closed under arithmetic whose operands are all uniform. Uniformity is the safety half of the old obligation: under a uniform stride the last_col < stride check keeps each tile inside one logical row, making the coordinate-to-offset mapping injective, so distinct threads own disjoint elements. The stride matching the buffer's real row width governs the computed result, and the documentation separates the two.
Collaborator
|
Thanks, A per-call witness cannot carry the safety proof:
Tile disjointness needs one stride per slice for the slice's whole lifetime, so the sound redesign is to bind the pitch into the The Uniform-to-bare-scalar host mapping, the sealed anti-spoof bound with its trybuild tests, and the requires-relation unwrapping are all worth keeping in that rework, which will also need a rebase now that #514 lands separately. |
This was referenced Jul 29, 2026
This was referenced Aug 4, 2026
nihalpasham
added a commit
that referenced
this pull request
Aug 5, 2026
* Make the warp an index space, so a warp reduction writes safely Closes #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 #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. * fix(examples): reduce warp_sums over live lanes, not the full warp mask 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). * docs(cuda-device): truthful warp_index example, reserve its name 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. --------- Co-authored-by: nihalpasham <[email protected]>
nihalpasham
added a commit
that referenced
this pull request
Aug 5, 2026
* Bind the runtime row pitch into the disjoint slice's index space Closes #516. Reworks the design closed in #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 #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. * fix(cuda-device): resolve Runtime2DIndex witnesses against the addressed 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. * fix(cuda-macros): bind the launch packet's shape to the resolved DisjointSlice 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. * fix(mir-lower): flatten index-space fields through by-value disjoint-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. * fix(mir-lower): accept the pitched slice shape in the no-history aggregate 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. * test(examples): add pitched_slice GPU regression for the runtime row 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. * docs(mir-importer): correct stale index_2d_runtime comments after the 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. * style: apply cargo fmt across the pitched-slice branch 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. * docs(book): teach the safe slice-bound pitch API everywhere the old unsafe 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. * test(mir-lower): exercise the pitched arm of the no-history aggregate 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. * test(cuda-device): reject flat accessors on a Runtime2DIndex witness 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. * refactor(host-apis): say row width, not pitch, across the runtime-width 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. * style(mir-lower, examples): fix clippy unnecessary-mut and per-crate fmt 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. * style(examples): use is_multiple_of for the two-width parity selection 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. * style(examples): rustfmt the is_multiple_of selection 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. * docs(cuda-device): drop the now-redundant WarpIndex link target 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. --------- Co-authored-by: nihalpasham <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Depends on #514 and is branched from it. GitHub shows both commits until
that one merges; the change under review here is the second commit,
Add Uniform<T> and make DisjointSlice::tile_2d32_rt safe. It touches nocompiler crates, so the two are independent in substance.
DisjointSlice::tile_2d32_rttook au32row pitch and wasunsafe, with thecaller carrying an obligation the type system could not see: the stride has to
be the same value in every thread of the launch. Two threads that disagree
describe two different grids over one buffer, and their "disjoint" tiles can
overlap. With 1x1 tiles, thread (1, 0) at stride 5 and thread (0, 5) at stride
100 both resolve flat index 5, giving one element two
&mut.Uniform<T>turns that premise into a type.The witness
Uniform<T>is a#[repr(transparent)]newtype with a private field and nopublic constructor. rustc materialises it from the launch packet as a kernel
parameter, which is what makes it unforgeable in safe device code: the host
marshals one value for the whole grid, so every thread reads the same bytes.
#[cuda_module]maps aUniform<T>parameter to a plainTon the host,since the host is the source of the uniformity. A sealed
__LaunchContractUniformbound rejects a local type also namedUniform,which would otherwise take the scalar host ABI while presenting a different
device layout.
Uniform::new_uncheckedremains for a value proven uniform some other way, andblock_dim_x()and its siblings return witnesses with no obligation, since alaunch has one block shape. Uniformity is closed under arithmetic whose
operands are all uniform, so
wrapping_muland its siblings preserve thewitness.
Why the witness is sufficient
The old obligation had two clauses, and one of them is a safety property.
Under a uniform stride the
last_col < stridecheck keeps each tile inside onelogical row, which makes the coordinate-to-offset mapping injective, so
distinct threads own disjoint elements. "The stride is the true row width"
governs only whether the kernel computes the intended result: a uniform stride
that misdescribes the layout gives wrong answers inside the slice, never
aliasing or an out-of-bounds access. The documentation separates the two.
API change
tile_2d32_rtchanges fromunsafe fn(..., u32)tofn(..., Uniform<u32>).Both
gemm_viewssafe kernels lose theirunsafeblocks.Cost
None. PTX differs in parameter shape and instruction scheduling, and the
generated SASS is byte-identical at identical register counts.
Note for review
A
Uniform<T>parameter takes the aggregate.param .align N .b8 [N]path inplace of
.param .u32. Alignment and size are correct at u8, u16, u32 and u64,and ptxas absorbs the difference, so this costs nothing at runtime. Teaching
kernel-boundary scalarization to unwrap
repr(transparent)newtypes wouldstill tidy the emitted IR.