Skip to content

Bounds-check elision: safe views + size contracts, and an opt-in unchecked switch - #477

Merged
nihalpasham merged 2 commits into
mainfrom
bounds-checks-pay-once-or-opt-out
Jul 26, 2026
Merged

nihalpasham merged 2 commits into
mainfrom
bounds-checks-pay-once-or-opt-out

Conversation

@nihalpasham

@nihalpasham nihalpasham commented Jul 26, 2026 •

Copy link
Copy Markdown
Collaborator

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)

  • Read views. 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_exact pairs 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.
  • Runtime-width output tiles. tile_2d32_rt writes C when the row width is a runtime value like n. One documented unsafe obligation: every thread must pass the same width (a kernel argument satisfies this by construction).
  • requires on 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:

#[launch_contract(domain = 2, coordinates = u32, block = (16, 16, 1),
    requires = (k >= 1, a.len() >= m * k, b.len() >= k * n, c.len() >= m * n))]

Launching with an undersized buffer never reaches the GPU:

sgemm_naive_views: size requirement `a.len() >= m * k` violated:
left-hand side is 8192, right-hand side is 16384

And inside the kernel, three up-front checks replace two checks per loop iteration:

if let Some(a_row) = a_mat.row(row, k)          // A's whole row: checked once
    && let Some(b_col) = b_mat.col(col, k)      // B's whole column: checked once
    && let Some(pair) = a_row.zip_exact(b_col)  // equal lengths: checked once
{
    for (x, y) in pair { sum += x * y; }        // no checks in here
}

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 * k cannot wrap and falsely pass).

Track 2 -- turn the checks off (opt-in)

  • #[kernel(unchecked_indexing)] per kernel, or CUDA_OXIDE_UNCHECKED_INDEXING=1 / cargo oxide --unchecked-indexing per build.
  • Deletes only indexing checks. Overflow, div-by-zero, and panics still trap.
  • The contract is get_unchecked's: you promise every index is in bounds; out of bounds is UB.
  • The flag never leaks: a kernel calling an opted-in kernel's helper keeps its own checks (pinned by a PTX regression test).

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 materialized Option discriminant 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 gemm example)

kernel GFLOPS
gemm (plain a[i], today) 2,942 baseline
gemm_views naive, safe views 7,159 2.43x
gemm_views naive, unsafe raw twin 7,161 safety costs ~0.1%
gemm_views tiled, safe views 9,272 +3.4% over checked tiled_gemm

Safe and raw twins produce bit-identical results.

Testing

  • Two new examples: gemm_views (safe/raw twins vs a CPU reference, a --verify-ptx harness that pins branch counts and memory-op parity, and the benchmark above in its default run) and unchecked_indexing (PTX assertions in both directions plus the leak regression).
  • 12 new compile-fail tests (requires grammar, 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.
  • The diff went through two adversarial review passes; all 15 confirmed findings (including a marker-leak soundness bug and a duplicate-edge export bug in the new pass) were fixed and re-verified.

Not in this PR

  • Partial edge tiles (sizes not a multiple of the tile shape).
  • Making tile_2d32_rt fully safe needs a host-proven "uniform value" witness for kernel scalars -- the natural next step, which would also let requires proofs delete the per-thread view checks.
  • requires takes unsigned integer scalars only; signed scalars are rejected at compile time until widening semantics are decided.

…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.
@nihalpasham nihalpasham added documentation Improvements or additions to documentation enhancement New feature or request host-apis Host-side runtime APIs (cuda-host, cuda-core, cuda-async) cargo-oxide The `cargo oxide` subcommand and build automation safety Memory safety, soundness, or undefined behavior perf Performance of generated code or of the compiler itself codegen Device code-generation pipeline (Rust MIR to IR to PTX) IR-lowering Lowering between dialects (dialect-mir to LLVM dialect) labels Jul 26, 2026
@nihalpasham nihalpasham changed the title Proof-carrying read views, size-requirement contracts, and opt-in unchecked indexing Bounds-check elision: safe views + size contracts, and an opt-in unchecked switch Jul 26, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cargo-oxide The `cargo oxide` subcommand and build automation codegen Device code-generation pipeline (Rust MIR to IR to PTX) documentation Improvements or additions to documentation 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) perf Performance of generated code or of the compiler itself safety Memory safety, soundness, or undefined behavior

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant