Repository navigation
Bounds-check elision: safe views + size contracts, and an opt-in unchecked switch - #477
Merged
Merged
Conversation
…nchecked indexing Three coordinated features that let kernels stop paying per-access bounds-check costs, each with a different safety story: 1. Read-side proof-carrying views (cuda-device): MatrixView32 row and column views over runtime-sized matrices, ZipView32 fused equal-length dot iteration, and RuntimeTileMut32 / tile_2d32_rt runtime-row-width output tiles. One up-front strip check, then check-free access; safe kernels compile to the same PTX as hand-written raw-pointer twins. 2. requires = (...) launch-contract size requirements (cuda-macros, cuda-core): relations over the kernel's own parameters, e.g. a.len() >= m * k, validated against the signature at compile time (typos are spanned errors, generic kernels included) and enforced once per launch on the host in checked u64 arithmetic. A violated relation returns LaunchContractError::SizeRequirementViolated before any GPU work; the _unchecked launchers document skipping the checks. 3. #[kernel(unchecked_indexing)] plus CUDA_OXIDE_UNCHECKED_INDEXING=1 and cargo oxide --unchecked-indexing (cuda-macros, mir-importer, cargo-oxide): opt-in removal of slice-indexing bounds checks, gated strictly on AssertMessage::BoundsCheck in translate_assert. The get_unchecked contract made explicit; every other assert kind keeps its trap. The per-kernel marker lives only in generated kernel entries (hidden hygienic twin for generic kernels), so it cannot leak into kernels that did not opt in. Supporting compiler work: new mir-lower pass scalarize_block_args splits aggregate block arguments at merge points into scalar leaves so LLVM can fold iterator Option discriminants out of hot loops (pliron mem2reg promotes enum slots to whole-aggregate block args, which export as aggregate PHIs that SROA cannot split); duplicate same-destination cond_br edges share one extract chain to preserve the exporter's PHI dedup invariant. Examples: gemm_views (safe/raw GEMM twins, CPU reference check, --verify-ptx structural parity harness, 1024^3 benchmark in the default run) and unchecked_indexing (flag demo plus marker-leak regression guard). Book: new gpu-safety chapter "Bounds Checks: Pay Once or Opt Out" with cross-references from The Safety Model. Measured on an RTX 5090 at 1024x1024x1024 (16x16 blocks, same methodology as the gemm example): naive GEMM 2942 -> 7159 GFLOPS (2.4x) with the safe kernels within ~0.1% of their unsafe twins and bit-identical results.
The size-requirement rename pushed a match pattern past the line width (per-example cargo fmt) and clippy's collapsible_if fires on the strided_scale guard; collapse it into a let-chain. Both gates run per-example in CI but the examples are not workspace members, so the workspace-wide local checks missed them.
This was referenced Jul 27, 2026
Closed
Open
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.
Every
a[i]in a kernel compiles to a hidden bounds check: a compare and a branch to a trap, on every access, in every thread. In hot loops that is the dominant cost -- it's worth 2.4x on naive GEMM. This PR gives users two ways to get rid of it.Track 1 -- prove the checks away (safe)
MatrixView32::row(...)/::col(...)check once that a whole row or column lies inside the slice, then every read through the view is check-free.zip_exactpairs a row with a column after a single length check, so a dot-product loop's only compare is its own exit test -- the same instruction sequence as a raw-pointer loop.tile_2d32_rtwrites C when the row width is a runtime value liken. One documentedunsafeobligation: every thread must pass the same width (a kernel argument satisfies this by construction).requireson the launch contract. The kernel states the buffer sizes it needs; the generated launcher checks them once per launch, on the CPU, and refuses with a typed error instead of letting the GPU fault.The three compose. In
gemm_views:Launching with an undersized buffer never reaches the GPU:
And inside the kernel, three up-front checks replace two checks per loop iteration:
Relations are a tiny grammar, not arbitrary Rust: identifiers are validated against the kernel signature (typos are compile errors) and all arithmetic is checked u64 (a huge
m * kcannot wrap and falsely pass).Track 2 -- turn the checks off (opt-in)
#[kernel(unchecked_indexing)]per kernel, orCUDA_OXIDE_UNCHECKED_INDEXING=1/cargo oxide --unchecked-indexingper build.get_unchecked's: you promise every index is in bounds; out of bounds is UB.Supporting compiler work
New mir-lower pass
scalarize_block_args: pliron's mem2reg promotes enum locals to whole-aggregate block arguments, which export as aggregate PHIs that LLVM cannot split (SROA only handles allocas), leaving a materializedOptiondiscriminant and an extra branch per loop iteration. The pass splits such arguments into scalar leaves at real merge points, with duplicate same-destination cond_br edges sharing one extract chain to preserve the exporter's PHI dedup invariant.Measured (RTX 5090, 1024x1024x1024, same setup as the
gemmexample)gemm(plaina[i], today)gemm_viewsnaive, safe viewsgemm_viewsnaive, unsafe raw twingemm_viewstiled, safe viewstiled_gemmSafe and raw twins produce bit-identical results.
Testing
gemm_views(safe/raw twins vs a CPU reference, a--verify-ptxharness that pins branch counts and memory-op parity, and the benchmark above in its default run) andunchecked_indexing(PTX assertions in both directions plus the leak regression).requiresgrammar, runtime-tile forgery attempts) and unit tests across cuda-macros, mir-lower, cuda-device, and the async launchers.cargo test --workspace, clippy-D warnings, fmt, and the full 170-example smoketest are all green; the book builds clean with a new gpu-safety chapter covering both tracks.Not in this PR
tile_2d32_rtfully safe needs a host-proven "uniform value" witness for kernel scalars -- the natural next step, which would also letrequiresproofs delete the per-thread view checks.requirestakes unsigned integer scalars only; signed scalars are rejected at compile time until widening semantics are decided.